@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.cjs.js CHANGED
@@ -401,6 +401,18 @@ class Context {
401
401
  }
402
402
  }
403
403
  }
404
+ currentAgent() {
405
+ const agentNode = this.chain.agents[this.chain.agents.length - 1];
406
+ if (!agentNode) {
407
+ return null;
408
+ }
409
+ const agent = this.agents.filter((agent) => agent.Name == agentNode.agent.name)[0];
410
+ if (!agent) {
411
+ return null;
412
+ }
413
+ const agentContext = agent["agentContext"];
414
+ return [agent, agentNode.agent, agentContext];
415
+ }
404
416
  }
405
417
  class AgentContext {
406
418
  constructor(context, agent, agentChain) {
@@ -413,10 +425,10 @@ class AgentContext {
413
425
  }
414
426
 
415
427
  // src/errors/ai-sdk-error.ts
416
- var marker$1 = "vercel.ai.error";
417
- var symbol$1 = Symbol.for(marker$1);
418
- var _a$1;
419
- var _AISDKError$1 = class _AISDKError extends Error {
428
+ var marker = "vercel.ai.error";
429
+ var symbol = Symbol.for(marker);
430
+ var _a;
431
+ var _AISDKError = class _AISDKError extends Error {
420
432
  /**
421
433
  * Creates an AI SDK Error.
422
434
  *
@@ -431,7 +443,7 @@ var _AISDKError$1 = class _AISDKError extends Error {
431
443
  cause
432
444
  }) {
433
445
  super(message);
434
- this[_a$1] = true;
446
+ this[_a] = true;
435
447
  this.name = name14;
436
448
  this.cause = cause;
437
449
  }
@@ -441,22 +453,22 @@ var _AISDKError$1 = class _AISDKError extends Error {
441
453
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
442
454
  */
443
455
  static isInstance(error) {
444
- return _AISDKError.hasMarker(error, marker$1);
456
+ return _AISDKError.hasMarker(error, marker);
445
457
  }
446
458
  static hasMarker(error, marker15) {
447
459
  const markerSymbol = Symbol.for(marker15);
448
460
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
449
461
  }
450
462
  };
451
- _a$1 = symbol$1;
452
- var AISDKError$1 = _AISDKError$1;
463
+ _a = symbol;
464
+ var AISDKError = _AISDKError;
453
465
 
454
466
  // src/errors/api-call-error.ts
455
- var name$1 = "AI_APICallError";
456
- var marker2$1 = `vercel.ai.error.${name$1}`;
457
- var symbol2$1 = Symbol.for(marker2$1);
458
- var _a2$1;
459
- var APICallError$1 = class APICallError extends AISDKError$1 {
467
+ var name = "AI_APICallError";
468
+ var marker2 = `vercel.ai.error.${name}`;
469
+ var symbol2 = Symbol.for(marker2);
470
+ var _a2;
471
+ var APICallError = class extends AISDKError {
460
472
  constructor({
461
473
  message,
462
474
  url,
@@ -472,8 +484,8 @@ var APICallError$1 = class APICallError extends AISDKError$1 {
472
484
  // server error
473
485
  data
474
486
  }) {
475
- super({ name: name$1, message, cause });
476
- this[_a2$1] = true;
487
+ super({ name, message, cause });
488
+ this[_a2] = true;
477
489
  this.url = url;
478
490
  this.requestBodyValues = requestBodyValues;
479
491
  this.statusCode = statusCode;
@@ -483,30 +495,30 @@ var APICallError$1 = class APICallError extends AISDKError$1 {
483
495
  this.data = data;
484
496
  }
485
497
  static isInstance(error) {
486
- return AISDKError$1.hasMarker(error, marker2$1);
498
+ return AISDKError.hasMarker(error, marker2);
487
499
  }
488
500
  };
489
- _a2$1 = symbol2$1;
501
+ _a2 = symbol2;
490
502
 
491
503
  // src/errors/empty-response-body-error.ts
492
- var name2$1 = "AI_EmptyResponseBodyError";
493
- var marker3$1 = `vercel.ai.error.${name2$1}`;
494
- var symbol3$1 = Symbol.for(marker3$1);
495
- var _a3$1;
496
- var EmptyResponseBodyError$1 = class EmptyResponseBodyError extends AISDKError$1 {
504
+ var name2 = "AI_EmptyResponseBodyError";
505
+ var marker3 = `vercel.ai.error.${name2}`;
506
+ var symbol3 = Symbol.for(marker3);
507
+ var _a3;
508
+ var EmptyResponseBodyError = class extends AISDKError {
497
509
  // used in isInstance
498
510
  constructor({ message = "Empty response body" } = {}) {
499
- super({ name: name2$1, message });
500
- this[_a3$1] = true;
511
+ super({ name: name2, message });
512
+ this[_a3] = true;
501
513
  }
502
514
  static isInstance(error) {
503
- return AISDKError$1.hasMarker(error, marker3$1);
515
+ return AISDKError.hasMarker(error, marker3);
504
516
  }
505
517
  };
506
- _a3$1 = symbol3$1;
518
+ _a3 = symbol3;
507
519
 
508
520
  // src/errors/get-error-message.ts
509
- function getErrorMessage$1(error) {
521
+ function getErrorMessage(error) {
510
522
  if (error == null) {
511
523
  return "unknown error";
512
524
  }
@@ -520,119 +532,119 @@ function getErrorMessage$1(error) {
520
532
  }
521
533
 
522
534
  // src/errors/invalid-argument-error.ts
523
- var name3$1 = "AI_InvalidArgumentError";
524
- var marker4$1 = `vercel.ai.error.${name3$1}`;
525
- var symbol4$1 = Symbol.for(marker4$1);
526
- var _a4$1;
527
- var InvalidArgumentError$1 = class InvalidArgumentError extends AISDKError$1 {
535
+ var name3 = "AI_InvalidArgumentError";
536
+ var marker4 = `vercel.ai.error.${name3}`;
537
+ var symbol4 = Symbol.for(marker4);
538
+ var _a4;
539
+ var InvalidArgumentError = class extends AISDKError {
528
540
  constructor({
529
541
  message,
530
542
  cause,
531
543
  argument
532
544
  }) {
533
- super({ name: name3$1, message, cause });
534
- this[_a4$1] = true;
545
+ super({ name: name3, message, cause });
546
+ this[_a4] = true;
535
547
  this.argument = argument;
536
548
  }
537
549
  static isInstance(error) {
538
- return AISDKError$1.hasMarker(error, marker4$1);
550
+ return AISDKError.hasMarker(error, marker4);
539
551
  }
540
552
  };
541
- _a4$1 = symbol4$1;
553
+ _a4 = symbol4;
542
554
 
543
555
  // src/errors/invalid-prompt-error.ts
544
- var name4$1 = "AI_InvalidPromptError";
545
- var marker5$1 = `vercel.ai.error.${name4$1}`;
546
- var symbol5$1 = Symbol.for(marker5$1);
547
- var _a5$1;
548
- var InvalidPromptError$1 = class InvalidPromptError extends AISDKError$1 {
556
+ var name4 = "AI_InvalidPromptError";
557
+ var marker5 = `vercel.ai.error.${name4}`;
558
+ var symbol5 = Symbol.for(marker5);
559
+ var _a5;
560
+ var InvalidPromptError = class extends AISDKError {
549
561
  constructor({
550
562
  prompt,
551
563
  message,
552
564
  cause
553
565
  }) {
554
- super({ name: name4$1, message: `Invalid prompt: ${message}`, cause });
555
- this[_a5$1] = true;
566
+ super({ name: name4, message: `Invalid prompt: ${message}`, cause });
567
+ this[_a5] = true;
556
568
  this.prompt = prompt;
557
569
  }
558
570
  static isInstance(error) {
559
- return AISDKError$1.hasMarker(error, marker5$1);
571
+ return AISDKError.hasMarker(error, marker5);
560
572
  }
561
573
  };
562
- _a5$1 = symbol5$1;
574
+ _a5 = symbol5;
563
575
 
564
576
  // src/errors/invalid-response-data-error.ts
565
- var name5$1 = "AI_InvalidResponseDataError";
566
- var marker6$1 = `vercel.ai.error.${name5$1}`;
567
- var symbol6$1 = Symbol.for(marker6$1);
568
- var _a6$1;
569
- var InvalidResponseDataError$1 = class InvalidResponseDataError extends AISDKError$1 {
577
+ var name5 = "AI_InvalidResponseDataError";
578
+ var marker6 = `vercel.ai.error.${name5}`;
579
+ var symbol6 = Symbol.for(marker6);
580
+ var _a6;
581
+ var InvalidResponseDataError = class extends AISDKError {
570
582
  constructor({
571
583
  data,
572
584
  message = `Invalid response data: ${JSON.stringify(data)}.`
573
585
  }) {
574
- super({ name: name5$1, message });
575
- this[_a6$1] = true;
586
+ super({ name: name5, message });
587
+ this[_a6] = true;
576
588
  this.data = data;
577
589
  }
578
590
  static isInstance(error) {
579
- return AISDKError$1.hasMarker(error, marker6$1);
591
+ return AISDKError.hasMarker(error, marker6);
580
592
  }
581
593
  };
582
- _a6$1 = symbol6$1;
594
+ _a6 = symbol6;
583
595
 
584
596
  // src/errors/json-parse-error.ts
585
- var name6$1 = "AI_JSONParseError";
586
- var marker7$1 = `vercel.ai.error.${name6$1}`;
587
- var symbol7$1 = Symbol.for(marker7$1);
588
- var _a7$1;
589
- var JSONParseError$1 = class JSONParseError extends AISDKError$1 {
597
+ var name6 = "AI_JSONParseError";
598
+ var marker7 = `vercel.ai.error.${name6}`;
599
+ var symbol7 = Symbol.for(marker7);
600
+ var _a7;
601
+ var JSONParseError = class extends AISDKError {
590
602
  constructor({ text, cause }) {
591
603
  super({
592
- name: name6$1,
604
+ name: name6,
593
605
  message: `JSON parsing failed: Text: ${text}.
594
- Error message: ${getErrorMessage$1(cause)}`,
606
+ Error message: ${getErrorMessage(cause)}`,
595
607
  cause
596
608
  });
597
- this[_a7$1] = true;
609
+ this[_a7] = true;
598
610
  this.text = text;
599
611
  }
600
612
  static isInstance(error) {
601
- return AISDKError$1.hasMarker(error, marker7$1);
613
+ return AISDKError.hasMarker(error, marker7);
602
614
  }
603
615
  };
604
- _a7$1 = symbol7$1;
616
+ _a7 = symbol7;
605
617
 
606
618
  // src/errors/load-api-key-error.ts
607
- var name7$1 = "AI_LoadAPIKeyError";
608
- var marker8$1 = `vercel.ai.error.${name7$1}`;
609
- var symbol8$1 = Symbol.for(marker8$1);
610
- var _a8$1;
611
- var LoadAPIKeyError$1 = class LoadAPIKeyError extends AISDKError$1 {
619
+ var name7 = "AI_LoadAPIKeyError";
620
+ var marker8 = `vercel.ai.error.${name7}`;
621
+ var symbol8 = Symbol.for(marker8);
622
+ var _a8;
623
+ var LoadAPIKeyError = class extends AISDKError {
612
624
  // used in isInstance
613
625
  constructor({ message }) {
614
- super({ name: name7$1, message });
615
- this[_a8$1] = true;
626
+ super({ name: name7, message });
627
+ this[_a8] = true;
616
628
  }
617
629
  static isInstance(error) {
618
- return AISDKError$1.hasMarker(error, marker8$1);
630
+ return AISDKError.hasMarker(error, marker8);
619
631
  }
620
632
  };
621
- _a8$1 = symbol8$1;
633
+ _a8 = symbol8;
622
634
 
623
635
  // src/errors/load-setting-error.ts
624
636
  var name8 = "AI_LoadSettingError";
625
637
  var marker9 = `vercel.ai.error.${name8}`;
626
638
  var symbol9 = Symbol.for(marker9);
627
639
  var _a9;
628
- var LoadSettingError = class extends AISDKError$1 {
640
+ var LoadSettingError = class extends AISDKError {
629
641
  // used in isInstance
630
642
  constructor({ message }) {
631
643
  super({ name: name8, message });
632
644
  this[_a9] = true;
633
645
  }
634
646
  static isInstance(error) {
635
- return AISDKError$1.hasMarker(error, marker9);
647
+ return AISDKError.hasMarker(error, marker9);
636
648
  }
637
649
  };
638
650
  _a9 = symbol9;
@@ -642,7 +654,7 @@ var name10 = "AI_NoSuchModelError";
642
654
  var marker11 = `vercel.ai.error.${name10}`;
643
655
  var symbol11 = Symbol.for(marker11);
644
656
  var _a11;
645
- var NoSuchModelError = class extends AISDKError$1 {
657
+ var NoSuchModelError = class extends AISDKError {
646
658
  constructor({
647
659
  errorName = name10,
648
660
  modelId,
@@ -655,7 +667,7 @@ var NoSuchModelError = class extends AISDKError$1 {
655
667
  this.modelType = modelType;
656
668
  }
657
669
  static isInstance(error) {
658
- return AISDKError$1.hasMarker(error, marker11);
670
+ return AISDKError.hasMarker(error, marker11);
659
671
  }
660
672
  };
661
673
  _a11 = symbol11;
@@ -665,7 +677,7 @@ var name11 = "AI_TooManyEmbeddingValuesForCallError";
665
677
  var marker12 = `vercel.ai.error.${name11}`;
666
678
  var symbol12 = Symbol.for(marker12);
667
679
  var _a12;
668
- var TooManyEmbeddingValuesForCallError = class extends AISDKError$1 {
680
+ var TooManyEmbeddingValuesForCallError = class extends AISDKError {
669
681
  constructor(options) {
670
682
  super({
671
683
  name: name11,
@@ -678,29 +690,29 @@ var TooManyEmbeddingValuesForCallError = class extends AISDKError$1 {
678
690
  this.values = options.values;
679
691
  }
680
692
  static isInstance(error) {
681
- return AISDKError$1.hasMarker(error, marker12);
693
+ return AISDKError.hasMarker(error, marker12);
682
694
  }
683
695
  };
684
696
  _a12 = symbol12;
685
697
 
686
698
  // src/errors/type-validation-error.ts
687
- var name12$1 = "AI_TypeValidationError";
688
- var marker13$1 = `vercel.ai.error.${name12$1}`;
689
- var symbol13$1 = Symbol.for(marker13$1);
690
- var _a13$1;
691
- var _TypeValidationError$1 = class _TypeValidationError extends AISDKError$1 {
699
+ var name12 = "AI_TypeValidationError";
700
+ var marker13 = `vercel.ai.error.${name12}`;
701
+ var symbol13 = Symbol.for(marker13);
702
+ var _a13;
703
+ var _TypeValidationError = class _TypeValidationError extends AISDKError {
692
704
  constructor({ value, cause }) {
693
705
  super({
694
- name: name12$1,
706
+ name: name12,
695
707
  message: `Type validation failed: Value: ${JSON.stringify(value)}.
696
- Error message: ${getErrorMessage$1(cause)}`,
708
+ Error message: ${getErrorMessage(cause)}`,
697
709
  cause
698
710
  });
699
- this[_a13$1] = true;
711
+ this[_a13] = true;
700
712
  this.value = value;
701
713
  }
702
714
  static isInstance(error) {
703
- return AISDKError$1.hasMarker(error, marker13$1);
715
+ return AISDKError.hasMarker(error, marker13);
704
716
  }
705
717
  /**
706
718
  * Wraps an error into a TypeValidationError.
@@ -719,28 +731,28 @@ Error message: ${getErrorMessage$1(cause)}`,
719
731
  return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
720
732
  }
721
733
  };
722
- _a13$1 = symbol13$1;
723
- var TypeValidationError$1 = _TypeValidationError$1;
734
+ _a13 = symbol13;
735
+ var TypeValidationError = _TypeValidationError;
724
736
 
725
737
  // src/errors/unsupported-functionality-error.ts
726
- var name13$1 = "AI_UnsupportedFunctionalityError";
727
- var marker14$1 = `vercel.ai.error.${name13$1}`;
728
- var symbol14$1 = Symbol.for(marker14$1);
729
- var _a14$1;
730
- var UnsupportedFunctionalityError$1 = class UnsupportedFunctionalityError extends AISDKError$1 {
738
+ var name13 = "AI_UnsupportedFunctionalityError";
739
+ var marker14 = `vercel.ai.error.${name13}`;
740
+ var symbol14 = Symbol.for(marker14);
741
+ var _a14;
742
+ var UnsupportedFunctionalityError = class extends AISDKError {
731
743
  constructor({
732
744
  functionality,
733
745
  message = `'${functionality}' functionality not supported.`
734
746
  }) {
735
- super({ name: name13$1, message });
736
- this[_a14$1] = true;
747
+ super({ name: name13, message });
748
+ this[_a14] = true;
737
749
  this.functionality = functionality;
738
750
  }
739
751
  static isInstance(error) {
740
- return AISDKError$1.hasMarker(error, marker14$1);
752
+ return AISDKError.hasMarker(error, marker14);
741
753
  }
742
754
  };
743
- _a14$1 = symbol14$1;
755
+ _a14 = symbol14;
744
756
 
745
757
  let customAlphabet = (alphabet, defaultSize = 21) => {
746
758
  return (size = defaultSize) => {
@@ -896,7 +908,7 @@ var secureJsonParseExports = requireSecureJsonParse();
896
908
  var SecureJSON = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports);
897
909
 
898
910
  // src/combine-headers.ts
899
- function combineHeaders$1(...headers) {
911
+ function combineHeaders(...headers) {
900
912
  return headers.reduce(
901
913
  (combinedHeaders, currentHeaders) => ({
902
914
  ...combinedHeaders,
@@ -965,7 +977,7 @@ function createEventSourceParserStream() {
965
977
  }
966
978
  return new TransformStream({
967
979
  transform(chunk, controller) {
968
- const { lines, incompleteLine } = splitLines$1(buffer, chunk);
980
+ const { lines, incompleteLine } = splitLines(buffer, chunk);
969
981
  buffer = incompleteLine;
970
982
  for (let i = 0; i < lines.length; i++) {
971
983
  parseLine(lines[i], controller);
@@ -977,7 +989,7 @@ function createEventSourceParserStream() {
977
989
  }
978
990
  });
979
991
  }
980
- function splitLines$1(buffer, chunk) {
992
+ function splitLines(buffer, chunk) {
981
993
  const lines = [];
982
994
  let currentLine = buffer;
983
995
  for (let i = 0; i < chunk.length; ) {
@@ -999,14 +1011,14 @@ function splitLines$1(buffer, chunk) {
999
1011
  }
1000
1012
 
1001
1013
  // src/extract-response-headers.ts
1002
- function extractResponseHeaders$1(response) {
1014
+ function extractResponseHeaders(response) {
1003
1015
  const headers = {};
1004
1016
  response.headers.forEach((value, key) => {
1005
1017
  headers[key] = value;
1006
1018
  });
1007
1019
  return headers;
1008
1020
  }
1009
- var createIdGenerator$1 = ({
1021
+ var createIdGenerator = ({
1010
1022
  prefix,
1011
1023
  size: defaultSize = 16,
1012
1024
  alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
@@ -1017,27 +1029,27 @@ var createIdGenerator$1 = ({
1017
1029
  return generator;
1018
1030
  }
1019
1031
  if (alphabet.includes(separator)) {
1020
- throw new InvalidArgumentError$1({
1032
+ throw new InvalidArgumentError({
1021
1033
  argument: "separator",
1022
1034
  message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
1023
1035
  });
1024
1036
  }
1025
1037
  return (size) => `${prefix}${separator}${generator(size)}`;
1026
1038
  };
1027
- var generateId$1 = createIdGenerator$1();
1039
+ var generateId = createIdGenerator();
1028
1040
 
1029
1041
  // src/remove-undefined-entries.ts
1030
- function removeUndefinedEntries$1(record) {
1042
+ function removeUndefinedEntries(record) {
1031
1043
  return Object.fromEntries(
1032
1044
  Object.entries(record).filter(([_key, value]) => value != null)
1033
1045
  );
1034
1046
  }
1035
1047
 
1036
1048
  // src/is-abort-error.ts
1037
- function isAbortError$1(error) {
1049
+ function isAbortError(error) {
1038
1050
  return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
1039
1051
  }
1040
- function loadApiKey$1({
1052
+ function loadApiKey({
1041
1053
  apiKey,
1042
1054
  environmentVariableName,
1043
1055
  apiKeyParameterName = "apiKey",
@@ -1047,23 +1059,23 @@ function loadApiKey$1({
1047
1059
  return apiKey;
1048
1060
  }
1049
1061
  if (apiKey != null) {
1050
- throw new LoadAPIKeyError$1({
1062
+ throw new LoadAPIKeyError({
1051
1063
  message: `${description} API key must be a string.`
1052
1064
  });
1053
1065
  }
1054
1066
  if (typeof process === "undefined") {
1055
- throw new LoadAPIKeyError$1({
1067
+ throw new LoadAPIKeyError({
1056
1068
  message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
1057
1069
  });
1058
1070
  }
1059
1071
  apiKey = process.env[environmentVariableName];
1060
1072
  if (apiKey == null) {
1061
- throw new LoadAPIKeyError$1({
1073
+ throw new LoadAPIKeyError({
1062
1074
  message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
1063
1075
  });
1064
1076
  }
1065
1077
  if (typeof apiKey !== "string") {
1066
- throw new LoadAPIKeyError$1({
1078
+ throw new LoadAPIKeyError({
1067
1079
  message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
1068
1080
  });
1069
1081
  }
@@ -1121,39 +1133,39 @@ function loadSetting({
1121
1133
  }
1122
1134
 
1123
1135
  // src/validator.ts
1124
- var validatorSymbol$1 = Symbol.for("vercel.ai.validator");
1125
- function validator$1(validate) {
1126
- return { [validatorSymbol$1]: true, validate };
1136
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
1137
+ function validator(validate) {
1138
+ return { [validatorSymbol]: true, validate };
1127
1139
  }
1128
- function isValidator$1(value) {
1129
- return typeof value === "object" && value !== null && validatorSymbol$1 in value && value[validatorSymbol$1] === true && "validate" in value;
1140
+ function isValidator(value) {
1141
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
1130
1142
  }
1131
- function asValidator$1(value) {
1132
- return isValidator$1(value) ? value : zodValidator$1(value);
1143
+ function asValidator(value) {
1144
+ return isValidator(value) ? value : zodValidator(value);
1133
1145
  }
1134
- function zodValidator$1(zodSchema) {
1135
- return validator$1((value) => {
1146
+ function zodValidator(zodSchema) {
1147
+ return validator((value) => {
1136
1148
  const result = zodSchema.safeParse(value);
1137
1149
  return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1138
1150
  });
1139
1151
  }
1140
1152
 
1141
1153
  // src/validate-types.ts
1142
- function validateTypes$1({
1154
+ function validateTypes({
1143
1155
  value,
1144
1156
  schema: inputSchema
1145
1157
  }) {
1146
- const result = safeValidateTypes$1({ value, schema: inputSchema });
1158
+ const result = safeValidateTypes({ value, schema: inputSchema });
1147
1159
  if (!result.success) {
1148
- throw TypeValidationError$1.wrap({ value, cause: result.error });
1160
+ throw TypeValidationError.wrap({ value, cause: result.error });
1149
1161
  }
1150
1162
  return result.value;
1151
1163
  }
1152
- function safeValidateTypes$1({
1164
+ function safeValidateTypes({
1153
1165
  value,
1154
1166
  schema
1155
1167
  }) {
1156
- const validator2 = asValidator$1(schema);
1168
+ const validator2 = asValidator(schema);
1157
1169
  try {
1158
1170
  if (validator2.validate == null) {
1159
1171
  return { success: true, value };
@@ -1164,18 +1176,18 @@ function safeValidateTypes$1({
1164
1176
  }
1165
1177
  return {
1166
1178
  success: false,
1167
- error: TypeValidationError$1.wrap({ value, cause: result.error })
1179
+ error: TypeValidationError.wrap({ value, cause: result.error })
1168
1180
  };
1169
1181
  } catch (error) {
1170
1182
  return {
1171
1183
  success: false,
1172
- error: TypeValidationError$1.wrap({ value, cause: error })
1184
+ error: TypeValidationError.wrap({ value, cause: error })
1173
1185
  };
1174
1186
  }
1175
1187
  }
1176
1188
 
1177
1189
  // src/parse-json.ts
1178
- function parseJSON$1({
1190
+ function parseJSON({
1179
1191
  text,
1180
1192
  schema
1181
1193
  }) {
@@ -1184,15 +1196,15 @@ function parseJSON$1({
1184
1196
  if (schema == null) {
1185
1197
  return value;
1186
1198
  }
1187
- return validateTypes$1({ value, schema });
1199
+ return validateTypes({ value, schema });
1188
1200
  } catch (error) {
1189
- if (JSONParseError$1.isInstance(error) || TypeValidationError$1.isInstance(error)) {
1201
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
1190
1202
  throw error;
1191
1203
  }
1192
- throw new JSONParseError$1({ text, cause: error });
1204
+ throw new JSONParseError({ text, cause: error });
1193
1205
  }
1194
1206
  }
1195
- function safeParseJSON$1({
1207
+ function safeParseJSON({
1196
1208
  text,
1197
1209
  schema
1198
1210
  }) {
@@ -1201,16 +1213,16 @@ function safeParseJSON$1({
1201
1213
  if (schema == null) {
1202
1214
  return { success: true, value, rawValue: value };
1203
1215
  }
1204
- const validationResult = safeValidateTypes$1({ value, schema });
1216
+ const validationResult = safeValidateTypes({ value, schema });
1205
1217
  return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
1206
1218
  } catch (error) {
1207
1219
  return {
1208
1220
  success: false,
1209
- error: JSONParseError$1.isInstance(error) ? error : new JSONParseError$1({ text, cause: error })
1221
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
1210
1222
  };
1211
1223
  }
1212
1224
  }
1213
- function isParsableJson$1(input) {
1225
+ function isParsableJson(input) {
1214
1226
  try {
1215
1227
  SecureJSON.parse(input);
1216
1228
  return true;
@@ -1226,12 +1238,12 @@ function parseProviderOptions({
1226
1238
  if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
1227
1239
  return void 0;
1228
1240
  }
1229
- const parsedProviderOptions = safeValidateTypes$1({
1241
+ const parsedProviderOptions = safeValidateTypes({
1230
1242
  value: providerOptions[provider],
1231
1243
  schema
1232
1244
  });
1233
1245
  if (!parsedProviderOptions.success) {
1234
- throw new InvalidArgumentError$1({
1246
+ throw new InvalidArgumentError({
1235
1247
  argument: "providerOptions",
1236
1248
  message: `invalid ${provider} provider options`,
1237
1249
  cause: parsedProviderOptions.error
@@ -1239,8 +1251,8 @@ function parseProviderOptions({
1239
1251
  }
1240
1252
  return parsedProviderOptions.value;
1241
1253
  }
1242
- var getOriginalFetch2$1 = () => globalThis.fetch;
1243
- var postJsonToApi$1 = async ({
1254
+ var getOriginalFetch2 = () => globalThis.fetch;
1255
+ var postJsonToApi = async ({
1244
1256
  url,
1245
1257
  headers,
1246
1258
  body,
@@ -1248,7 +1260,7 @@ var postJsonToApi$1 = async ({
1248
1260
  successfulResponseHandler,
1249
1261
  abortSignal,
1250
1262
  fetch
1251
- }) => postToApi$1({
1263
+ }) => postToApi({
1252
1264
  url,
1253
1265
  headers: {
1254
1266
  "Content-Type": "application/json",
@@ -1271,7 +1283,7 @@ var postFormDataToApi = async ({
1271
1283
  successfulResponseHandler,
1272
1284
  abortSignal,
1273
1285
  fetch
1274
- }) => postToApi$1({
1286
+ }) => postToApi({
1275
1287
  url,
1276
1288
  headers,
1277
1289
  body: {
@@ -1283,23 +1295,23 @@ var postFormDataToApi = async ({
1283
1295
  abortSignal,
1284
1296
  fetch
1285
1297
  });
1286
- var postToApi$1 = async ({
1298
+ var postToApi = async ({
1287
1299
  url,
1288
1300
  headers = {},
1289
1301
  body,
1290
1302
  successfulResponseHandler,
1291
1303
  failedResponseHandler,
1292
1304
  abortSignal,
1293
- fetch = getOriginalFetch2$1()
1305
+ fetch = getOriginalFetch2()
1294
1306
  }) => {
1295
1307
  try {
1296
1308
  const response = await fetch(url, {
1297
1309
  method: "POST",
1298
- headers: removeUndefinedEntries$1(headers),
1310
+ headers: removeUndefinedEntries(headers),
1299
1311
  body: body.content,
1300
1312
  signal: abortSignal
1301
1313
  });
1302
- const responseHeaders = extractResponseHeaders$1(response);
1314
+ const responseHeaders = extractResponseHeaders(response);
1303
1315
  if (!response.ok) {
1304
1316
  let errorInformation;
1305
1317
  try {
@@ -1309,10 +1321,10 @@ var postToApi$1 = async ({
1309
1321
  requestBodyValues: body.values
1310
1322
  });
1311
1323
  } catch (error) {
1312
- if (isAbortError$1(error) || APICallError$1.isInstance(error)) {
1324
+ if (isAbortError(error) || APICallError.isInstance(error)) {
1313
1325
  throw error;
1314
1326
  }
1315
- throw new APICallError$1({
1327
+ throw new APICallError({
1316
1328
  message: "Failed to process error response",
1317
1329
  cause: error,
1318
1330
  statusCode: response.status,
@@ -1331,11 +1343,11 @@ var postToApi$1 = async ({
1331
1343
  });
1332
1344
  } catch (error) {
1333
1345
  if (error instanceof Error) {
1334
- if (isAbortError$1(error) || APICallError$1.isInstance(error)) {
1346
+ if (isAbortError(error) || APICallError.isInstance(error)) {
1335
1347
  throw error;
1336
1348
  }
1337
1349
  }
1338
- throw new APICallError$1({
1350
+ throw new APICallError({
1339
1351
  message: "Failed to process successful response",
1340
1352
  cause: error,
1341
1353
  statusCode: response.status,
@@ -1345,13 +1357,13 @@ var postToApi$1 = async ({
1345
1357
  });
1346
1358
  }
1347
1359
  } catch (error) {
1348
- if (isAbortError$1(error)) {
1360
+ if (isAbortError(error)) {
1349
1361
  throw error;
1350
1362
  }
1351
1363
  if (error instanceof TypeError && error.message === "fetch failed") {
1352
1364
  const cause = error.cause;
1353
1365
  if (cause != null) {
1354
- throw new APICallError$1({
1366
+ throw new APICallError({
1355
1367
  message: `Cannot connect to API: ${cause.message}`,
1356
1368
  cause,
1357
1369
  url,
@@ -1372,17 +1384,17 @@ async function resolve(value) {
1372
1384
  }
1373
1385
  return Promise.resolve(value);
1374
1386
  }
1375
- var createJsonErrorResponseHandler$1 = ({
1387
+ var createJsonErrorResponseHandler = ({
1376
1388
  errorSchema,
1377
1389
  errorToMessage,
1378
1390
  isRetryable
1379
1391
  }) => async ({ response, url, requestBodyValues }) => {
1380
1392
  const responseBody = await response.text();
1381
- const responseHeaders = extractResponseHeaders$1(response);
1393
+ const responseHeaders = extractResponseHeaders(response);
1382
1394
  if (responseBody.trim() === "") {
1383
1395
  return {
1384
1396
  responseHeaders,
1385
- value: new APICallError$1({
1397
+ value: new APICallError({
1386
1398
  message: response.statusText,
1387
1399
  url,
1388
1400
  requestBodyValues,
@@ -1394,13 +1406,13 @@ var createJsonErrorResponseHandler$1 = ({
1394
1406
  };
1395
1407
  }
1396
1408
  try {
1397
- const parsedError = parseJSON$1({
1409
+ const parsedError = parseJSON({
1398
1410
  text: responseBody,
1399
1411
  schema: errorSchema
1400
1412
  });
1401
1413
  return {
1402
1414
  responseHeaders,
1403
- value: new APICallError$1({
1415
+ value: new APICallError({
1404
1416
  message: errorToMessage(parsedError),
1405
1417
  url,
1406
1418
  requestBodyValues,
@@ -1414,7 +1426,7 @@ var createJsonErrorResponseHandler$1 = ({
1414
1426
  } catch (parseError) {
1415
1427
  return {
1416
1428
  responseHeaders,
1417
- value: new APICallError$1({
1429
+ value: new APICallError({
1418
1430
  message: response.statusText,
1419
1431
  url,
1420
1432
  requestBodyValues,
@@ -1426,10 +1438,10 @@ var createJsonErrorResponseHandler$1 = ({
1426
1438
  };
1427
1439
  }
1428
1440
  };
1429
- var createEventSourceResponseHandler$1 = (chunkSchema) => async ({ response }) => {
1430
- const responseHeaders = extractResponseHeaders$1(response);
1441
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
1442
+ const responseHeaders = extractResponseHeaders(response);
1431
1443
  if (response.body == null) {
1432
- throw new EmptyResponseBodyError$1({});
1444
+ throw new EmptyResponseBodyError({});
1433
1445
  }
1434
1446
  return {
1435
1447
  responseHeaders,
@@ -1440,7 +1452,7 @@ var createEventSourceResponseHandler$1 = (chunkSchema) => async ({ response }) =
1440
1452
  return;
1441
1453
  }
1442
1454
  controller.enqueue(
1443
- safeParseJSON$1({
1455
+ safeParseJSON({
1444
1456
  text: data,
1445
1457
  schema: chunkSchema
1446
1458
  })
@@ -1450,15 +1462,15 @@ var createEventSourceResponseHandler$1 = (chunkSchema) => async ({ response }) =
1450
1462
  )
1451
1463
  };
1452
1464
  };
1453
- var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
1465
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
1454
1466
  const responseBody = await response.text();
1455
- const parsedResult = safeParseJSON$1({
1467
+ const parsedResult = safeParseJSON({
1456
1468
  text: responseBody,
1457
1469
  schema: responseSchema
1458
1470
  });
1459
- const responseHeaders = extractResponseHeaders$1(response);
1471
+ const responseHeaders = extractResponseHeaders(response);
1460
1472
  if (!parsedResult.success) {
1461
- throw new APICallError$1({
1473
+ throw new APICallError({
1462
1474
  message: "Invalid JSON response",
1463
1475
  cause: parsedResult.error,
1464
1476
  statusCode: response.status,
@@ -1475,9 +1487,9 @@ var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, re
1475
1487
  };
1476
1488
  };
1477
1489
  var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
1478
- const responseHeaders = extractResponseHeaders$1(response);
1490
+ const responseHeaders = extractResponseHeaders(response);
1479
1491
  if (!response.body) {
1480
- throw new APICallError$1({
1492
+ throw new APICallError({
1481
1493
  message: "Response body is empty",
1482
1494
  url,
1483
1495
  requestBodyValues,
@@ -1493,7 +1505,7 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
1493
1505
  value: new Uint8Array(buffer)
1494
1506
  };
1495
1507
  } catch (error) {
1496
- throw new APICallError$1({
1508
+ throw new APICallError({
1497
1509
  message: "Failed to read response as array buffer",
1498
1510
  url,
1499
1511
  requestBodyValues,
@@ -1506,22 +1518,22 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
1506
1518
  };
1507
1519
 
1508
1520
  // src/uint8-utils.ts
1509
- var { btoa: btoa$1, atob: atob$1 } = globalThis;
1521
+ var { btoa, atob: atob$1 } = globalThis;
1510
1522
  function convertBase64ToUint8Array(base64String) {
1511
1523
  const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
1512
1524
  const latin1string = atob$1(base64Url);
1513
1525
  return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
1514
1526
  }
1515
- function convertUint8ArrayToBase64$1(array) {
1527
+ function convertUint8ArrayToBase64(array) {
1516
1528
  let latin1string = "";
1517
1529
  for (let i = 0; i < array.length; i++) {
1518
1530
  latin1string += String.fromCodePoint(array[i]);
1519
1531
  }
1520
- return btoa$1(latin1string);
1532
+ return btoa(latin1string);
1521
1533
  }
1522
1534
 
1523
1535
  // src/without-trailing-slash.ts
1524
- function withoutTrailingSlash$1(url) {
1536
+ function withoutTrailingSlash(url) {
1525
1537
  return url == null ? void 0 : url.replace(/\/$/, "");
1526
1538
  }
1527
1539
 
@@ -5979,7 +5991,7 @@ function convertToOpenAIChatMessages({
5979
5991
  return {
5980
5992
  type: "image_url",
5981
5993
  image_url: {
5982
- url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64$1(part.image)}`,
5994
+ url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
5983
5995
  // OpenAI specific extension: image detail
5984
5996
  detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
5985
5997
  }
@@ -5987,7 +5999,7 @@ function convertToOpenAIChatMessages({
5987
5999
  }
5988
6000
  case "file": {
5989
6001
  if (part.data instanceof URL) {
5990
- throw new UnsupportedFunctionalityError$1({
6002
+ throw new UnsupportedFunctionalityError({
5991
6003
  functionality: "'File content parts with URL data' functionality not supported."
5992
6004
  });
5993
6005
  }
@@ -6015,7 +6027,7 @@ function convertToOpenAIChatMessages({
6015
6027
  };
6016
6028
  }
6017
6029
  default: {
6018
- throw new UnsupportedFunctionalityError$1({
6030
+ throw new UnsupportedFunctionalityError({
6019
6031
  functionality: `File content part type ${part.mimeType} in user messages`
6020
6032
  });
6021
6033
  }
@@ -6050,7 +6062,7 @@ function convertToOpenAIChatMessages({
6050
6062
  }
6051
6063
  if (useLegacyFunctionCalling) {
6052
6064
  if (toolCalls.length > 1) {
6053
- throw new UnsupportedFunctionalityError$1({
6065
+ throw new UnsupportedFunctionalityError({
6054
6066
  functionality: "useLegacyFunctionCalling with multiple tool calls in one message"
6055
6067
  });
6056
6068
  }
@@ -6135,7 +6147,7 @@ var openaiErrorDataSchema = z.object({
6135
6147
  code: z.union([z.string(), z.number()]).nullish()
6136
6148
  })
6137
6149
  });
6138
- var openaiFailedResponseHandler = createJsonErrorResponseHandler$1({
6150
+ var openaiFailedResponseHandler = createJsonErrorResponseHandler({
6139
6151
  errorSchema: openaiErrorDataSchema,
6140
6152
  errorToMessage: (data) => data.error.message
6141
6153
  });
@@ -6195,7 +6207,7 @@ function prepareTools$3({
6195
6207
  toolWarnings
6196
6208
  };
6197
6209
  case "required":
6198
- throw new UnsupportedFunctionalityError$1({
6210
+ throw new UnsupportedFunctionalityError({
6199
6211
  functionality: "useLegacyFunctionCalling and toolChoice: required"
6200
6212
  });
6201
6213
  default:
@@ -6244,7 +6256,7 @@ function prepareTools$3({
6244
6256
  };
6245
6257
  default: {
6246
6258
  const _exhaustiveCheck = type;
6247
- throw new UnsupportedFunctionalityError$1({
6259
+ throw new UnsupportedFunctionalityError({
6248
6260
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
6249
6261
  });
6250
6262
  }
@@ -6307,12 +6319,12 @@ var OpenAIChatLanguageModel = class {
6307
6319
  }
6308
6320
  const useLegacyFunctionCalling = this.settings.useLegacyFunctionCalling;
6309
6321
  if (useLegacyFunctionCalling && this.settings.parallelToolCalls === true) {
6310
- throw new UnsupportedFunctionalityError$1({
6322
+ throw new UnsupportedFunctionalityError({
6311
6323
  functionality: "useLegacyFunctionCalling with parallelToolCalls"
6312
6324
  });
6313
6325
  }
6314
6326
  if (useLegacyFunctionCalling && this.supportsStructuredOutputs) {
6315
- throw new UnsupportedFunctionalityError$1({
6327
+ throw new UnsupportedFunctionalityError({
6316
6328
  functionality: "structuredOutputs with useLegacyFunctionCalling"
6317
6329
  });
6318
6330
  }
@@ -6513,15 +6525,15 @@ var OpenAIChatLanguageModel = class {
6513
6525
  responseHeaders,
6514
6526
  value: response,
6515
6527
  rawValue: rawResponse
6516
- } = await postJsonToApi$1({
6528
+ } = await postJsonToApi({
6517
6529
  url: this.config.url({
6518
6530
  path: "/chat/completions",
6519
6531
  modelId: this.modelId
6520
6532
  }),
6521
- headers: combineHeaders$1(this.config.headers(), options.headers),
6533
+ headers: combineHeaders(this.config.headers(), options.headers),
6522
6534
  body,
6523
6535
  failedResponseHandler: openaiFailedResponseHandler,
6524
- successfulResponseHandler: createJsonResponseHandler$1(
6536
+ successfulResponseHandler: createJsonResponseHandler(
6525
6537
  openaiChatResponseSchema
6526
6538
  ),
6527
6539
  abortSignal: options.abortSignal,
@@ -6549,7 +6561,7 @@ var OpenAIChatLanguageModel = class {
6549
6561
  toolCalls: this.settings.useLegacyFunctionCalling && choice.message.function_call ? [
6550
6562
  {
6551
6563
  toolCallType: "function",
6552
- toolCallId: generateId$1(),
6564
+ toolCallId: generateId(),
6553
6565
  toolName: choice.message.function_call.name,
6554
6566
  args: choice.message.function_call.arguments
6555
6567
  }
@@ -6557,7 +6569,7 @@ var OpenAIChatLanguageModel = class {
6557
6569
  var _a2;
6558
6570
  return {
6559
6571
  toolCallType: "function",
6560
- toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId$1(),
6572
+ toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
6561
6573
  toolName: toolCall.function.name,
6562
6574
  args: toolCall.function.arguments
6563
6575
  };
@@ -6627,15 +6639,15 @@ var OpenAIChatLanguageModel = class {
6627
6639
  // only include stream_options when in strict compatibility mode:
6628
6640
  stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
6629
6641
  };
6630
- const { responseHeaders, value: response } = await postJsonToApi$1({
6642
+ const { responseHeaders, value: response } = await postJsonToApi({
6631
6643
  url: this.config.url({
6632
6644
  path: "/chat/completions",
6633
6645
  modelId: this.modelId
6634
6646
  }),
6635
- headers: combineHeaders$1(this.config.headers(), options.headers),
6647
+ headers: combineHeaders(this.config.headers(), options.headers),
6636
6648
  body,
6637
6649
  failedResponseHandler: openaiFailedResponseHandler,
6638
- successfulResponseHandler: createEventSourceResponseHandler$1(
6650
+ successfulResponseHandler: createEventSourceResponseHandler(
6639
6651
  openaiChatChunkSchema
6640
6652
  ),
6641
6653
  abortSignal: options.abortSignal,
@@ -6723,7 +6735,7 @@ var OpenAIChatLanguageModel = class {
6723
6735
  const mappedToolCalls = useLegacyFunctionCalling && delta.function_call != null ? [
6724
6736
  {
6725
6737
  type: "function",
6726
- id: generateId$1(),
6738
+ id: generateId(),
6727
6739
  function: delta.function_call,
6728
6740
  index: 0
6729
6741
  }
@@ -6733,19 +6745,19 @@ var OpenAIChatLanguageModel = class {
6733
6745
  const index = toolCallDelta.index;
6734
6746
  if (toolCalls[index] == null) {
6735
6747
  if (toolCallDelta.type !== "function") {
6736
- throw new InvalidResponseDataError$1({
6748
+ throw new InvalidResponseDataError({
6737
6749
  data: toolCallDelta,
6738
6750
  message: `Expected 'function' type.`
6739
6751
  });
6740
6752
  }
6741
6753
  if (toolCallDelta.id == null) {
6742
- throw new InvalidResponseDataError$1({
6754
+ throw new InvalidResponseDataError({
6743
6755
  data: toolCallDelta,
6744
6756
  message: `Expected 'id' to be a string.`
6745
6757
  });
6746
6758
  }
6747
6759
  if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
6748
- throw new InvalidResponseDataError$1({
6760
+ throw new InvalidResponseDataError({
6749
6761
  data: toolCallDelta,
6750
6762
  message: `Expected 'function.name' to be a string.`
6751
6763
  });
@@ -6770,11 +6782,11 @@ var OpenAIChatLanguageModel = class {
6770
6782
  argsTextDelta: toolCall2.function.arguments
6771
6783
  });
6772
6784
  }
6773
- if (isParsableJson$1(toolCall2.function.arguments)) {
6785
+ if (isParsableJson(toolCall2.function.arguments)) {
6774
6786
  controller.enqueue({
6775
6787
  type: "tool-call",
6776
6788
  toolCallType: "function",
6777
- toolCallId: (_e = toolCall2.id) != null ? _e : generateId$1(),
6789
+ toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
6778
6790
  toolName: toolCall2.function.name,
6779
6791
  args: toolCall2.function.arguments
6780
6792
  });
@@ -6797,11 +6809,11 @@ var OpenAIChatLanguageModel = class {
6797
6809
  toolName: toolCall.function.name,
6798
6810
  argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
6799
6811
  });
6800
- if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson$1(toolCall.function.arguments)) {
6812
+ if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
6801
6813
  controller.enqueue({
6802
6814
  type: "tool-call",
6803
6815
  toolCallType: "function",
6804
- toolCallId: (_l = toolCall.id) != null ? _l : generateId$1(),
6816
+ toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
6805
6817
  toolName: toolCall.function.name,
6806
6818
  args: toolCall.function.arguments
6807
6819
  });
@@ -7000,7 +7012,7 @@ function convertToOpenAICompletionPrompt({
7000
7012
  for (const { role, content } of prompt) {
7001
7013
  switch (role) {
7002
7014
  case "system": {
7003
- throw new InvalidPromptError$1({
7015
+ throw new InvalidPromptError({
7004
7016
  message: "Unexpected system message in prompt: ${content}",
7005
7017
  prompt
7006
7018
  });
@@ -7012,7 +7024,7 @@ function convertToOpenAICompletionPrompt({
7012
7024
  return part.text;
7013
7025
  }
7014
7026
  case "image": {
7015
- throw new UnsupportedFunctionalityError$1({
7027
+ throw new UnsupportedFunctionalityError({
7016
7028
  functionality: "images"
7017
7029
  });
7018
7030
  }
@@ -7031,7 +7043,7 @@ ${userMessage}
7031
7043
  return part.text;
7032
7044
  }
7033
7045
  case "tool-call": {
7034
- throw new UnsupportedFunctionalityError$1({
7046
+ throw new UnsupportedFunctionalityError({
7035
7047
  functionality: "tool-call messages"
7036
7048
  });
7037
7049
  }
@@ -7044,7 +7056,7 @@ ${assistantMessage}
7044
7056
  break;
7045
7057
  }
7046
7058
  case "tool": {
7047
- throw new UnsupportedFunctionalityError$1({
7059
+ throw new UnsupportedFunctionalityError({
7048
7060
  functionality: "tool messages"
7049
7061
  });
7050
7062
  }
@@ -7145,24 +7157,24 @@ var OpenAICompletionLanguageModel = class {
7145
7157
  switch (type) {
7146
7158
  case "regular": {
7147
7159
  if ((_a = mode.tools) == null ? void 0 : _a.length) {
7148
- throw new UnsupportedFunctionalityError$1({
7160
+ throw new UnsupportedFunctionalityError({
7149
7161
  functionality: "tools"
7150
7162
  });
7151
7163
  }
7152
7164
  if (mode.toolChoice) {
7153
- throw new UnsupportedFunctionalityError$1({
7165
+ throw new UnsupportedFunctionalityError({
7154
7166
  functionality: "toolChoice"
7155
7167
  });
7156
7168
  }
7157
7169
  return { args: baseArgs, warnings };
7158
7170
  }
7159
7171
  case "object-json": {
7160
- throw new UnsupportedFunctionalityError$1({
7172
+ throw new UnsupportedFunctionalityError({
7161
7173
  functionality: "object-json mode"
7162
7174
  });
7163
7175
  }
7164
7176
  case "object-tool": {
7165
- throw new UnsupportedFunctionalityError$1({
7177
+ throw new UnsupportedFunctionalityError({
7166
7178
  functionality: "object-tool mode"
7167
7179
  });
7168
7180
  }
@@ -7178,15 +7190,15 @@ var OpenAICompletionLanguageModel = class {
7178
7190
  responseHeaders,
7179
7191
  value: response,
7180
7192
  rawValue: rawResponse
7181
- } = await postJsonToApi$1({
7193
+ } = await postJsonToApi({
7182
7194
  url: this.config.url({
7183
7195
  path: "/completions",
7184
7196
  modelId: this.modelId
7185
7197
  }),
7186
- headers: combineHeaders$1(this.config.headers(), options.headers),
7198
+ headers: combineHeaders(this.config.headers(), options.headers),
7187
7199
  body: args,
7188
7200
  failedResponseHandler: openaiFailedResponseHandler,
7189
- successfulResponseHandler: createJsonResponseHandler$1(
7201
+ successfulResponseHandler: createJsonResponseHandler(
7190
7202
  openaiCompletionResponseSchema
7191
7203
  ),
7192
7204
  abortSignal: options.abortSignal,
@@ -7217,15 +7229,15 @@ var OpenAICompletionLanguageModel = class {
7217
7229
  // only include stream_options when in strict compatibility mode:
7218
7230
  stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
7219
7231
  };
7220
- const { responseHeaders, value: response } = await postJsonToApi$1({
7232
+ const { responseHeaders, value: response } = await postJsonToApi({
7221
7233
  url: this.config.url({
7222
7234
  path: "/completions",
7223
7235
  modelId: this.modelId
7224
7236
  }),
7225
- headers: combineHeaders$1(this.config.headers(), options.headers),
7237
+ headers: combineHeaders(this.config.headers(), options.headers),
7226
7238
  body,
7227
7239
  failedResponseHandler: openaiFailedResponseHandler,
7228
- successfulResponseHandler: createEventSourceResponseHandler$1(
7240
+ successfulResponseHandler: createEventSourceResponseHandler(
7229
7241
  openaiCompletionChunkSchema
7230
7242
  ),
7231
7243
  abortSignal: options.abortSignal,
@@ -7377,12 +7389,12 @@ var OpenAIEmbeddingModel = class {
7377
7389
  values
7378
7390
  });
7379
7391
  }
7380
- const { responseHeaders, value: response } = await postJsonToApi$1({
7392
+ const { responseHeaders, value: response } = await postJsonToApi({
7381
7393
  url: this.config.url({
7382
7394
  path: "/embeddings",
7383
7395
  modelId: this.modelId
7384
7396
  }),
7385
- headers: combineHeaders$1(this.config.headers(), headers),
7397
+ headers: combineHeaders(this.config.headers(), headers),
7386
7398
  body: {
7387
7399
  model: this.modelId,
7388
7400
  input: values,
@@ -7391,7 +7403,7 @@ var OpenAIEmbeddingModel = class {
7391
7403
  user: this.settings.user
7392
7404
  },
7393
7405
  failedResponseHandler: openaiFailedResponseHandler,
7394
- successfulResponseHandler: createJsonResponseHandler$1(
7406
+ successfulResponseHandler: createJsonResponseHandler(
7395
7407
  openaiTextEmbeddingResponseSchema
7396
7408
  ),
7397
7409
  abortSignal,
@@ -7455,12 +7467,12 @@ var OpenAIImageModel = class {
7455
7467
  warnings.push({ type: "unsupported-setting", setting: "seed" });
7456
7468
  }
7457
7469
  const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
7458
- const { value: response, responseHeaders } = await postJsonToApi$1({
7470
+ const { value: response, responseHeaders } = await postJsonToApi({
7459
7471
  url: this.config.url({
7460
7472
  path: "/images/generations",
7461
7473
  modelId: this.modelId
7462
7474
  }),
7463
- headers: combineHeaders$1(this.config.headers(), headers),
7475
+ headers: combineHeaders(this.config.headers(), headers),
7464
7476
  body: {
7465
7477
  model: this.modelId,
7466
7478
  prompt,
@@ -7470,7 +7482,7 @@ var OpenAIImageModel = class {
7470
7482
  ...!hasDefaultResponseFormat.has(this.modelId) ? { response_format: "b64_json" } : {}
7471
7483
  },
7472
7484
  failedResponseHandler: openaiFailedResponseHandler,
7473
- successfulResponseHandler: createJsonResponseHandler$1(
7485
+ successfulResponseHandler: createJsonResponseHandler(
7474
7486
  openaiImageResponseSchema
7475
7487
  ),
7476
7488
  abortSignal,
@@ -7614,10 +7626,10 @@ var OpenAITranscriptionModel = class {
7614
7626
  path: "/audio/transcriptions",
7615
7627
  modelId: this.modelId
7616
7628
  }),
7617
- headers: combineHeaders$1(this.config.headers(), options.headers),
7629
+ headers: combineHeaders(this.config.headers(), options.headers),
7618
7630
  formData,
7619
7631
  failedResponseHandler: openaiFailedResponseHandler,
7620
- successfulResponseHandler: createJsonResponseHandler$1(
7632
+ successfulResponseHandler: createJsonResponseHandler(
7621
7633
  openaiTranscriptionResponseSchema
7622
7634
  ),
7623
7635
  abortSignal: options.abortSignal,
@@ -7701,14 +7713,14 @@ function convertToOpenAIResponsesMessages({
7701
7713
  case "image": {
7702
7714
  return {
7703
7715
  type: "input_image",
7704
- image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64$1(part.image)}`,
7716
+ image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
7705
7717
  // OpenAI specific extension: image detail
7706
7718
  detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
7707
7719
  };
7708
7720
  }
7709
7721
  case "file": {
7710
7722
  if (part.data instanceof URL) {
7711
- throw new UnsupportedFunctionalityError$1({
7723
+ throw new UnsupportedFunctionalityError({
7712
7724
  functionality: "File URLs in user messages"
7713
7725
  });
7714
7726
  }
@@ -7721,7 +7733,7 @@ function convertToOpenAIResponsesMessages({
7721
7733
  };
7722
7734
  }
7723
7735
  default: {
7724
- throw new UnsupportedFunctionalityError$1({
7736
+ throw new UnsupportedFunctionalityError({
7725
7737
  functionality: "Only PDF files are supported in user messages"
7726
7738
  });
7727
7739
  }
@@ -7863,7 +7875,7 @@ function prepareResponsesTools({
7863
7875
  }
7864
7876
  default: {
7865
7877
  const _exhaustiveCheck = type;
7866
- throw new UnsupportedFunctionalityError$1({
7878
+ throw new UnsupportedFunctionalityError({
7867
7879
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
7868
7880
  });
7869
7881
  }
@@ -8062,15 +8074,15 @@ var OpenAIResponsesLanguageModel = class {
8062
8074
  responseHeaders,
8063
8075
  value: response,
8064
8076
  rawValue: rawResponse
8065
- } = await postJsonToApi$1({
8077
+ } = await postJsonToApi({
8066
8078
  url: this.config.url({
8067
8079
  path: "/responses",
8068
8080
  modelId: this.modelId
8069
8081
  }),
8070
- headers: combineHeaders$1(this.config.headers(), options.headers),
8082
+ headers: combineHeaders(this.config.headers(), options.headers),
8071
8083
  body,
8072
8084
  failedResponseHandler: openaiFailedResponseHandler,
8073
- successfulResponseHandler: createJsonResponseHandler$1(
8085
+ successfulResponseHandler: createJsonResponseHandler(
8074
8086
  z.object({
8075
8087
  id: z.string(),
8076
8088
  created_at: z.number(),
@@ -8141,7 +8153,7 @@ var OpenAIResponsesLanguageModel = class {
8141
8153
  var _a2, _b2, _c2;
8142
8154
  return {
8143
8155
  sourceType: "url",
8144
- id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId$1(),
8156
+ id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId(),
8145
8157
  url: annotation.url,
8146
8158
  title: annotation.title
8147
8159
  };
@@ -8188,18 +8200,18 @@ var OpenAIResponsesLanguageModel = class {
8188
8200
  }
8189
8201
  async doStream(options) {
8190
8202
  const { args: body, warnings } = this.getArgs(options);
8191
- const { responseHeaders, value: response } = await postJsonToApi$1({
8203
+ const { responseHeaders, value: response } = await postJsonToApi({
8192
8204
  url: this.config.url({
8193
8205
  path: "/responses",
8194
8206
  modelId: this.modelId
8195
8207
  }),
8196
- headers: combineHeaders$1(this.config.headers(), options.headers),
8208
+ headers: combineHeaders(this.config.headers(), options.headers),
8197
8209
  body: {
8198
8210
  ...body,
8199
8211
  stream: true
8200
8212
  },
8201
8213
  failedResponseHandler: openaiFailedResponseHandler,
8202
- successfulResponseHandler: createEventSourceResponseHandler$1(
8214
+ successfulResponseHandler: createEventSourceResponseHandler(
8203
8215
  openaiResponsesChunkSchema
8204
8216
  ),
8205
8217
  abortSignal: options.abortSignal,
@@ -8292,7 +8304,7 @@ var OpenAIResponsesLanguageModel = class {
8292
8304
  type: "source",
8293
8305
  source: {
8294
8306
  sourceType: "url",
8295
- id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId$1(),
8307
+ id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId(),
8296
8308
  url: value.annotation.url,
8297
8309
  title: value.annotation.title
8298
8310
  }
@@ -8560,12 +8572,12 @@ var OpenAISpeechModel = class {
8560
8572
  value: audio,
8561
8573
  responseHeaders,
8562
8574
  rawValue: rawResponse
8563
- } = await postJsonToApi$1({
8575
+ } = await postJsonToApi({
8564
8576
  url: this.config.url({
8565
8577
  path: "/audio/speech",
8566
8578
  modelId: this.modelId
8567
8579
  }),
8568
- headers: combineHeaders$1(this.config.headers(), options.headers),
8580
+ headers: combineHeaders(this.config.headers(), options.headers),
8569
8581
  body: requestBody,
8570
8582
  failedResponseHandler: openaiFailedResponseHandler,
8571
8583
  successfulResponseHandler: createBinaryResponseHandler(),
@@ -8591,11 +8603,11 @@ var OpenAISpeechModel = class {
8591
8603
  // src/openai-provider.ts
8592
8604
  function createOpenAI(options = {}) {
8593
8605
  var _a, _b, _c;
8594
- const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
8606
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
8595
8607
  const compatibility = (_b = options.compatibility) != null ? _b : "compatible";
8596
8608
  const providerName = (_c = options.name) != null ? _c : "openai";
8597
8609
  const getHeaders = () => ({
8598
- Authorization: `Bearer ${loadApiKey$1({
8610
+ Authorization: `Bearer ${loadApiKey({
8599
8611
  apiKey: options.apiKey,
8600
8612
  environmentVariableName: "OPENAI_API_KEY",
8601
8613
  description: "OpenAI"
@@ -8696,7 +8708,7 @@ var anthropicErrorDataSchema = z.object({
8696
8708
  message: z.string()
8697
8709
  })
8698
8710
  });
8699
- var anthropicFailedResponseHandler = createJsonErrorResponseHandler$1({
8711
+ var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
8700
8712
  errorSchema: anthropicErrorDataSchema,
8701
8713
  errorToMessage: (data) => data.error.message
8702
8714
  });
@@ -8814,7 +8826,7 @@ function prepareTools$2(mode) {
8814
8826
  };
8815
8827
  default: {
8816
8828
  const _exhaustiveCheck = type;
8817
- throw new UnsupportedFunctionalityError$1({
8829
+ throw new UnsupportedFunctionalityError({
8818
8830
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
8819
8831
  });
8820
8832
  }
@@ -8843,7 +8855,7 @@ function convertToAnthropicMessagesPrompt({
8843
8855
  switch (type) {
8844
8856
  case "system": {
8845
8857
  if (system != null) {
8846
- throw new UnsupportedFunctionalityError$1({
8858
+ throw new UnsupportedFunctionalityError({
8847
8859
  functionality: "Multiple system messages that are separated by user/assistant messages"
8848
8860
  });
8849
8861
  }
@@ -8882,7 +8894,7 @@ function convertToAnthropicMessagesPrompt({
8882
8894
  } : {
8883
8895
  type: "base64",
8884
8896
  media_type: (_b = part.mimeType) != null ? _b : "image/jpeg",
8885
- data: convertUint8ArrayToBase64$1(part.image)
8897
+ data: convertUint8ArrayToBase64(part.image)
8886
8898
  },
8887
8899
  cache_control: cacheControl
8888
8900
  });
@@ -8890,7 +8902,7 @@ function convertToAnthropicMessagesPrompt({
8890
8902
  }
8891
8903
  case "file": {
8892
8904
  if (part.mimeType !== "application/pdf") {
8893
- throw new UnsupportedFunctionalityError$1({
8905
+ throw new UnsupportedFunctionalityError({
8894
8906
  functionality: "Non-PDF files in user messages"
8895
8907
  });
8896
8908
  }
@@ -9187,7 +9199,7 @@ var AnthropicMessagesLanguageModel = class {
9187
9199
  };
9188
9200
  if (isThinking) {
9189
9201
  if (thinkingBudget == null) {
9190
- throw new UnsupportedFunctionalityError$1({
9202
+ throw new UnsupportedFunctionalityError({
9191
9203
  functionality: "thinking requires a budget"
9192
9204
  });
9193
9205
  }
@@ -9232,7 +9244,7 @@ var AnthropicMessagesLanguageModel = class {
9232
9244
  };
9233
9245
  }
9234
9246
  case "object-json": {
9235
- throw new UnsupportedFunctionalityError$1({
9247
+ throw new UnsupportedFunctionalityError({
9236
9248
  functionality: "json-mode object generation"
9237
9249
  });
9238
9250
  }
@@ -9258,7 +9270,7 @@ var AnthropicMessagesLanguageModel = class {
9258
9270
  betas,
9259
9271
  headers
9260
9272
  }) {
9261
- return combineHeaders$1(
9273
+ return combineHeaders(
9262
9274
  await resolve(this.config.headers),
9263
9275
  betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {},
9264
9276
  headers
@@ -9279,12 +9291,12 @@ var AnthropicMessagesLanguageModel = class {
9279
9291
  responseHeaders,
9280
9292
  value: response,
9281
9293
  rawValue: rawResponse
9282
- } = await postJsonToApi$1({
9294
+ } = await postJsonToApi({
9283
9295
  url: this.buildRequestUrl(false),
9284
9296
  headers: await this.getHeaders({ betas, headers: options.headers }),
9285
9297
  body: this.transformRequestBody(args),
9286
9298
  failedResponseHandler: anthropicFailedResponseHandler,
9287
- successfulResponseHandler: createJsonResponseHandler$1(
9299
+ successfulResponseHandler: createJsonResponseHandler(
9288
9300
  anthropicMessagesResponseSchema
9289
9301
  ),
9290
9302
  abortSignal: options.abortSignal,
@@ -9354,12 +9366,12 @@ var AnthropicMessagesLanguageModel = class {
9354
9366
  async doStream(options) {
9355
9367
  const { args, warnings, betas } = await this.getArgs(options);
9356
9368
  const body = { ...args, stream: true };
9357
- const { responseHeaders, value: response } = await postJsonToApi$1({
9369
+ const { responseHeaders, value: response } = await postJsonToApi({
9358
9370
  url: this.buildRequestUrl(true),
9359
9371
  headers: await this.getHeaders({ betas, headers: options.headers }),
9360
9372
  body: this.transformRequestBody(body),
9361
9373
  failedResponseHandler: anthropicFailedResponseHandler,
9362
- successfulResponseHandler: createEventSourceResponseHandler$1(
9374
+ successfulResponseHandler: createEventSourceResponseHandler(
9363
9375
  anthropicMessagesChunkSchema
9364
9376
  ),
9365
9377
  abortSignal: options.abortSignal,
@@ -9800,10 +9812,10 @@ var anthropicTools = {
9800
9812
  // src/anthropic-provider.ts
9801
9813
  function createAnthropic(options = {}) {
9802
9814
  var _a;
9803
- const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
9815
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
9804
9816
  const getHeaders = () => ({
9805
9817
  "anthropic-version": "2023-06-01",
9806
- "x-api-key": loadApiKey$1({
9818
+ "x-api-key": loadApiKey({
9807
9819
  apiKey: options.apiKey,
9808
9820
  environmentVariableName: "ANTHROPIC_API_KEY",
9809
9821
  description: "Anthropic"
@@ -9943,7 +9955,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
9943
9955
  switch (role) {
9944
9956
  case "system": {
9945
9957
  if (!systemMessagesAllowed) {
9946
- throw new UnsupportedFunctionalityError$1({
9958
+ throw new UnsupportedFunctionalityError({
9947
9959
  functionality: "system messages are only supported at the beginning of the conversation"
9948
9960
  });
9949
9961
  }
@@ -9969,7 +9981,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
9969
9981
  } : {
9970
9982
  inlineData: {
9971
9983
  mimeType: (_b = part.mimeType) != null ? _b : "image/jpeg",
9972
- data: convertUint8ArrayToBase64$1(part.image)
9984
+ data: convertUint8ArrayToBase64(part.image)
9973
9985
  }
9974
9986
  }
9975
9987
  );
@@ -10007,12 +10019,12 @@ function convertToGoogleGenerativeAIMessages(prompt) {
10007
10019
  }
10008
10020
  case "file": {
10009
10021
  if (part.mimeType !== "image/png") {
10010
- throw new UnsupportedFunctionalityError$1({
10022
+ throw new UnsupportedFunctionalityError({
10011
10023
  functionality: "Only PNG images are supported in assistant messages"
10012
10024
  });
10013
10025
  }
10014
10026
  if (part.data instanceof URL) {
10015
- throw new UnsupportedFunctionalityError$1({
10027
+ throw new UnsupportedFunctionalityError({
10016
10028
  functionality: "File data URLs in assistant messages are not supported"
10017
10029
  });
10018
10030
  }
@@ -10071,7 +10083,7 @@ var googleErrorDataSchema = z.object({
10071
10083
  status: z.string()
10072
10084
  })
10073
10085
  });
10074
- var googleFailedResponseHandler = createJsonErrorResponseHandler$1({
10086
+ var googleFailedResponseHandler = createJsonErrorResponseHandler({
10075
10087
  errorSchema: googleErrorDataSchema,
10076
10088
  errorToMessage: (data) => data.error.message
10077
10089
  });
@@ -10146,7 +10158,7 @@ function prepareTools$1(mode, useSearchGrounding, dynamicRetrievalConfig, modelI
10146
10158
  };
10147
10159
  default: {
10148
10160
  const _exhaustiveCheck = type;
10149
- throw new UnsupportedFunctionalityError$1({
10161
+ throw new UnsupportedFunctionalityError({
10150
10162
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
10151
10163
  });
10152
10164
  }
@@ -10323,7 +10335,7 @@ var GoogleGenerativeAILanguageModel = class {
10323
10335
  var _a, _b, _c, _d, _e;
10324
10336
  const { args, warnings } = await this.getArgs(options);
10325
10337
  const body = JSON.stringify(args);
10326
- const mergedHeaders = combineHeaders$1(
10338
+ const mergedHeaders = combineHeaders(
10327
10339
  await resolve(this.config.headers),
10328
10340
  options.headers
10329
10341
  );
@@ -10331,14 +10343,14 @@ var GoogleGenerativeAILanguageModel = class {
10331
10343
  responseHeaders,
10332
10344
  value: response,
10333
10345
  rawValue: rawResponse
10334
- } = await postJsonToApi$1({
10346
+ } = await postJsonToApi({
10335
10347
  url: `${this.config.baseURL}/${getModelPath(
10336
10348
  this.modelId
10337
10349
  )}:generateContent`,
10338
10350
  headers: mergedHeaders,
10339
10351
  body: args,
10340
10352
  failedResponseHandler: googleFailedResponseHandler,
10341
- successfulResponseHandler: createJsonResponseHandler$1(responseSchema),
10353
+ successfulResponseHandler: createJsonResponseHandler(responseSchema),
10342
10354
  abortSignal: options.abortSignal,
10343
10355
  fetch: this.config.fetch
10344
10356
  });
@@ -10386,18 +10398,18 @@ var GoogleGenerativeAILanguageModel = class {
10386
10398
  async doStream(options) {
10387
10399
  const { args, warnings } = await this.getArgs(options);
10388
10400
  const body = JSON.stringify(args);
10389
- const headers = combineHeaders$1(
10401
+ const headers = combineHeaders(
10390
10402
  await resolve(this.config.headers),
10391
10403
  options.headers
10392
10404
  );
10393
- const { responseHeaders, value: response } = await postJsonToApi$1({
10405
+ const { responseHeaders, value: response } = await postJsonToApi({
10394
10406
  url: `${this.config.baseURL}/${getModelPath(
10395
10407
  this.modelId
10396
10408
  )}:streamGenerateContent?alt=sse`,
10397
10409
  headers,
10398
10410
  body: args,
10399
10411
  failedResponseHandler: googleFailedResponseHandler,
10400
- successfulResponseHandler: createEventSourceResponseHandler$1(chunkSchema),
10412
+ successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
10401
10413
  abortSignal: options.abortSignal,
10402
10414
  fetch: this.config.fetch
10403
10415
  });
@@ -10544,7 +10556,7 @@ function getTextFromParts(parts) {
10544
10556
  }
10545
10557
  function getReasoningDetailsFromParts(parts) {
10546
10558
  const reasoningParts = parts == null ? void 0 : parts.filter(
10547
- (part) => "text" in part && part.thought === true
10559
+ (part) => "text" in part && part.thought === true && part.text != null
10548
10560
  );
10549
10561
  return reasoningParts == null || reasoningParts.length === 0 ? void 0 : reasoningParts.map((part) => ({ type: "text", text: part.text }));
10550
10562
  }
@@ -10568,13 +10580,9 @@ function extractSources({
10568
10580
  }));
10569
10581
  }
10570
10582
  var contentSchema = z.object({
10571
- role: z.string(),
10572
10583
  parts: z.array(
10573
10584
  z.union([
10574
- z.object({
10575
- text: z.string(),
10576
- thought: z.boolean().nullish()
10577
- }),
10585
+ // note: order matters since text can be fully empty
10578
10586
  z.object({
10579
10587
  functionCall: z.object({
10580
10588
  name: z.string(),
@@ -10586,6 +10594,10 @@ var contentSchema = z.object({
10586
10594
  mimeType: z.string(),
10587
10595
  data: z.string()
10588
10596
  })
10597
+ }),
10598
+ z.object({
10599
+ text: z.string().nullish(),
10600
+ thought: z.boolean().nullish()
10589
10601
  })
10590
10602
  ])
10591
10603
  ).nullish()
@@ -10694,11 +10706,11 @@ var GoogleGenerativeAIEmbeddingModel = class {
10694
10706
  values
10695
10707
  });
10696
10708
  }
10697
- const mergedHeaders = combineHeaders$1(
10709
+ const mergedHeaders = combineHeaders(
10698
10710
  await resolve(this.config.headers),
10699
10711
  headers
10700
10712
  );
10701
- const { responseHeaders, value: response } = await postJsonToApi$1({
10713
+ const { responseHeaders, value: response } = await postJsonToApi({
10702
10714
  url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
10703
10715
  headers: mergedHeaders,
10704
10716
  body: {
@@ -10710,7 +10722,7 @@ var GoogleGenerativeAIEmbeddingModel = class {
10710
10722
  }))
10711
10723
  },
10712
10724
  failedResponseHandler: googleFailedResponseHandler,
10713
- successfulResponseHandler: createJsonResponseHandler$1(
10725
+ successfulResponseHandler: createJsonResponseHandler(
10714
10726
  googleGenerativeAITextEmbeddingResponseSchema
10715
10727
  ),
10716
10728
  abortSignal,
@@ -10735,9 +10747,9 @@ function isSupportedFileUrl(url) {
10735
10747
  // src/google-provider.ts
10736
10748
  function createGoogleGenerativeAI(options = {}) {
10737
10749
  var _a;
10738
- const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
10750
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
10739
10751
  const getHeaders = () => ({
10740
- "x-goog-api-key": loadApiKey$1({
10752
+ "x-goog-api-key": loadApiKey({
10741
10753
  apiKey: options.apiKey,
10742
10754
  environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
10743
10755
  description: "Google Generative AI"
@@ -10750,7 +10762,7 @@ function createGoogleGenerativeAI(options = {}) {
10750
10762
  provider: "google.generative-ai",
10751
10763
  baseURL,
10752
10764
  headers: getHeaders,
10753
- generateId: (_a2 = options.generateId) != null ? _a2 : generateId$1,
10765
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
10754
10766
  isSupportedUrl: isSupportedFileUrl,
10755
10767
  fetch: options.fetch
10756
10768
  });
@@ -11588,9 +11600,9 @@ var BedrockErrorSchema = z.object({
11588
11600
  type: z.string().nullish()
11589
11601
  });
11590
11602
  var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response }) => {
11591
- const responseHeaders = extractResponseHeaders$1(response);
11603
+ const responseHeaders = extractResponseHeaders(response);
11592
11604
  if (response.body == null) {
11593
- throw new EmptyResponseBodyError$1({});
11605
+ throw new EmptyResponseBodyError({});
11594
11606
  }
11595
11607
  const codec = new EventStreamCodec(toUtf8, fromUtf8);
11596
11608
  let buffer = new Uint8Array(0);
@@ -11620,7 +11632,7 @@ var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response
11620
11632
  buffer = buffer.slice(totalLength);
11621
11633
  if (((_a = decoded.headers[":message-type"]) == null ? void 0 : _a.value) === "event") {
11622
11634
  const data = textDecoder.decode(decoded.body);
11623
- const parsedDataResult = safeParseJSON$1({ text: data });
11635
+ const parsedDataResult = safeParseJSON({ text: data });
11624
11636
  if (!parsedDataResult.success) {
11625
11637
  controller.enqueue(parsedDataResult);
11626
11638
  break;
@@ -11629,7 +11641,7 @@ var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response
11629
11641
  let wrappedData = {
11630
11642
  [(_b = decoded.headers[":event-type"]) == null ? void 0 : _b.value]: parsedDataResult.value
11631
11643
  };
11632
- const validatedWrappedData = safeValidateTypes$1({
11644
+ const validatedWrappedData = safeValidateTypes({
11633
11645
  value: wrappedData,
11634
11646
  schema: chunkSchema
11635
11647
  });
@@ -11712,13 +11724,13 @@ function prepareTools(mode) {
11712
11724
  };
11713
11725
  default: {
11714
11726
  const _exhaustiveCheck = type;
11715
- throw new UnsupportedFunctionalityError$1({
11727
+ throw new UnsupportedFunctionalityError({
11716
11728
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
11717
11729
  });
11718
11730
  }
11719
11731
  }
11720
11732
  }
11721
- var generateFileId = createIdGenerator$1({ prefix: "file", size: 16 });
11733
+ var generateFileId = createIdGenerator({ prefix: "file", size: 16 });
11722
11734
  function getCachePoint(providerMetadata) {
11723
11735
  var _a;
11724
11736
  return (_a = providerMetadata == null ? void 0 : providerMetadata.bedrock) == null ? void 0 : _a.cachePoint;
@@ -11735,7 +11747,7 @@ function convertToBedrockChatMessages(prompt) {
11735
11747
  switch (type) {
11736
11748
  case "system": {
11737
11749
  if (messages.length > 0) {
11738
- throw new UnsupportedFunctionalityError$1({
11750
+ throw new UnsupportedFunctionalityError({
11739
11751
  functionality: "Multiple system messages that are separated by user/assistant messages"
11740
11752
  });
11741
11753
  }
@@ -11764,7 +11776,7 @@ function convertToBedrockChatMessages(prompt) {
11764
11776
  }
11765
11777
  case "image": {
11766
11778
  if (part.image instanceof URL) {
11767
- throw new UnsupportedFunctionalityError$1({
11779
+ throw new UnsupportedFunctionalityError({
11768
11780
  functionality: "Image URLs in user messages"
11769
11781
  });
11770
11782
  }
@@ -11774,7 +11786,7 @@ function convertToBedrockChatMessages(prompt) {
11774
11786
  "/"
11775
11787
  )) == null ? void 0 : _b[1],
11776
11788
  source: {
11777
- bytes: convertUint8ArrayToBase64$1(
11789
+ bytes: convertUint8ArrayToBase64(
11778
11790
  (_c = part.image) != null ? _c : part.image
11779
11791
  )
11780
11792
  }
@@ -11784,7 +11796,7 @@ function convertToBedrockChatMessages(prompt) {
11784
11796
  }
11785
11797
  case "file": {
11786
11798
  if (part.data instanceof URL) {
11787
- throw new UnsupportedFunctionalityError$1({
11799
+ throw new UnsupportedFunctionalityError({
11788
11800
  functionality: "File URLs in user messages"
11789
11801
  });
11790
11802
  }
@@ -12074,7 +12086,7 @@ var BedrockChatLanguageModel = class {
12074
12086
  (_a = providerMetadata == null ? void 0 : providerMetadata.bedrock) == null ? void 0 : _a.reasoning_config
12075
12087
  );
12076
12088
  if (!reasoningConfigOptions.success) {
12077
- throw new InvalidArgumentError$1({
12089
+ throw new InvalidArgumentError({
12078
12090
  argument: "providerOptions.bedrock.reasoning_config",
12079
12091
  message: "invalid reasoning configuration options",
12080
12092
  cause: reasoningConfigOptions.error
@@ -12139,7 +12151,7 @@ var BedrockChatLanguageModel = class {
12139
12151
  };
12140
12152
  }
12141
12153
  case "object-json": {
12142
- throw new UnsupportedFunctionalityError$1({
12154
+ throw new UnsupportedFunctionalityError({
12143
12155
  functionality: "json-mode object generation"
12144
12156
  });
12145
12157
  }
@@ -12175,21 +12187,21 @@ var BedrockChatLanguageModel = class {
12175
12187
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
12176
12188
  const { command: args, warnings } = this.getArgs(options);
12177
12189
  const url = `${this.getUrl(this.modelId)}/converse`;
12178
- const { value: response, responseHeaders } = await postJsonToApi$1({
12190
+ const { value: response, responseHeaders } = await postJsonToApi({
12179
12191
  url,
12180
- headers: combineHeaders$1(
12192
+ headers: combineHeaders(
12181
12193
  await resolve(this.config.headers),
12182
12194
  options.headers
12183
12195
  ),
12184
12196
  body: args,
12185
- failedResponseHandler: createJsonErrorResponseHandler$1({
12197
+ failedResponseHandler: createJsonErrorResponseHandler({
12186
12198
  errorSchema: BedrockErrorSchema,
12187
12199
  errorToMessage: (error) => {
12188
12200
  var _a2;
12189
12201
  return `${(_a2 = error.message) != null ? _a2 : "Unknown error"}`;
12190
12202
  }
12191
12203
  }),
12192
- successfulResponseHandler: createJsonResponseHandler$1(
12204
+ successfulResponseHandler: createJsonResponseHandler(
12193
12205
  BedrockResponseSchema
12194
12206
  ),
12195
12207
  abortSignal: options.abortSignal,
@@ -12257,14 +12269,14 @@ var BedrockChatLanguageModel = class {
12257
12269
  async doStream(options) {
12258
12270
  const { command: args, warnings } = this.getArgs(options);
12259
12271
  const url = `${this.getUrl(this.modelId)}/converse-stream`;
12260
- const { value: response, responseHeaders } = await postJsonToApi$1({
12272
+ const { value: response, responseHeaders } = await postJsonToApi({
12261
12273
  url,
12262
- headers: combineHeaders$1(
12274
+ headers: combineHeaders(
12263
12275
  await resolve(this.config.headers),
12264
12276
  options.headers
12265
12277
  ),
12266
12278
  body: args,
12267
- failedResponseHandler: createJsonErrorResponseHandler$1({
12279
+ failedResponseHandler: createJsonErrorResponseHandler({
12268
12280
  errorSchema: BedrockErrorSchema,
12269
12281
  errorToMessage: (error) => `${error.type}: ${error.message}`
12270
12282
  }),
@@ -12547,17 +12559,17 @@ var BedrockEmbeddingModel = class {
12547
12559
  normalize: this.settings.normalize
12548
12560
  };
12549
12561
  const url = this.getUrl(this.modelId);
12550
- const { value: response } = await postJsonToApi$1({
12562
+ const { value: response } = await postJsonToApi({
12551
12563
  url,
12552
12564
  headers: await resolve(
12553
- combineHeaders$1(await resolve(this.config.headers), headers)
12565
+ combineHeaders(await resolve(this.config.headers), headers)
12554
12566
  ),
12555
12567
  body: args,
12556
- failedResponseHandler: createJsonErrorResponseHandler$1({
12568
+ failedResponseHandler: createJsonErrorResponseHandler({
12557
12569
  errorSchema: BedrockErrorSchema,
12558
12570
  errorToMessage: (error) => `${error.type}: ${error.message}`
12559
12571
  }),
12560
- successfulResponseHandler: createJsonResponseHandler$1(
12572
+ successfulResponseHandler: createJsonResponseHandler(
12561
12573
  BedrockEmbeddingResponseSchema
12562
12574
  ),
12563
12575
  fetch: this.config.fetch,
@@ -12642,17 +12654,17 @@ var BedrockImageModel = class {
12642
12654
  });
12643
12655
  }
12644
12656
  const currentDate = (_f = (_e = (_d = this.config._internal) == null ? void 0 : _d.currentDate) == null ? void 0 : _e.call(_d)) != null ? _f : /* @__PURE__ */ new Date();
12645
- const { value: response, responseHeaders } = await postJsonToApi$1({
12657
+ const { value: response, responseHeaders } = await postJsonToApi({
12646
12658
  url: this.getUrl(this.modelId),
12647
12659
  headers: await resolve(
12648
- combineHeaders$1(await resolve(this.config.headers), headers)
12660
+ combineHeaders(await resolve(this.config.headers), headers)
12649
12661
  ),
12650
12662
  body: args,
12651
- failedResponseHandler: createJsonErrorResponseHandler$1({
12663
+ failedResponseHandler: createJsonErrorResponseHandler({
12652
12664
  errorSchema: BedrockErrorSchema,
12653
12665
  errorToMessage: (error) => `${error.type}: ${error.message}`
12654
12666
  }),
12655
- successfulResponseHandler: createJsonResponseHandler$1(
12667
+ successfulResponseHandler: createJsonResponseHandler(
12656
12668
  bedrockImageResponseSchema
12657
12669
  ),
12658
12670
  abortSignal,
@@ -12711,7 +12723,7 @@ function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
12711
12723
  const signer = new AwsV4Signer({
12712
12724
  url,
12713
12725
  method: "POST",
12714
- headers: Object.entries(removeUndefinedEntries$1(originalHeaders)),
12726
+ headers: Object.entries(removeUndefinedEntries(originalHeaders)),
12715
12727
  body,
12716
12728
  region: credentials.region,
12717
12729
  accessKeyId: credentials.accessKeyId,
@@ -12724,8 +12736,8 @@ function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
12724
12736
  return fetch(input, {
12725
12737
  ...init,
12726
12738
  body,
12727
- headers: removeUndefinedEntries$1(
12728
- combineHeaders$1(originalHeaders, signedHeaders)
12739
+ headers: removeUndefinedEntries(
12740
+ combineHeaders(originalHeaders, signedHeaders)
12729
12741
  )
12730
12742
  });
12731
12743
  };
@@ -12779,7 +12791,7 @@ function createAmazonBedrock(options = {}) {
12779
12791
  }, options.fetch);
12780
12792
  const getBaseUrl = () => {
12781
12793
  var _a, _b;
12782
- return (_b = withoutTrailingSlash$1(
12794
+ return (_b = withoutTrailingSlash(
12783
12795
  (_a = options.baseURL) != null ? _a : `https://bedrock-runtime.${loadSetting({
12784
12796
  settingValue: options.region,
12785
12797
  settingName: "region",
@@ -12794,7 +12806,7 @@ function createAmazonBedrock(options = {}) {
12794
12806
  baseUrl: getBaseUrl,
12795
12807
  headers: (_a = options.headers) != null ? _a : {},
12796
12808
  fetch: sigv4Fetch,
12797
- generateId: generateId$1
12809
+ generateId
12798
12810
  });
12799
12811
  };
12800
12812
  const provider = function(modelId, settings) {
@@ -12831,802 +12843,6 @@ function createAmazonBedrock(options = {}) {
12831
12843
  }
12832
12844
  createAmazonBedrock();
12833
12845
 
12834
- // src/errors/ai-sdk-error.ts
12835
- var marker = "vercel.ai.error";
12836
- var symbol = Symbol.for(marker);
12837
- var _a;
12838
- var _AISDKError = class _AISDKError extends Error {
12839
- /**
12840
- * Creates an AI SDK Error.
12841
- *
12842
- * @param {Object} params - The parameters for creating the error.
12843
- * @param {string} params.name - The name of the error.
12844
- * @param {string} params.message - The error message.
12845
- * @param {unknown} [params.cause] - The underlying cause of the error.
12846
- */
12847
- constructor({
12848
- name: name14,
12849
- message,
12850
- cause
12851
- }) {
12852
- super(message);
12853
- this[_a] = true;
12854
- this.name = name14;
12855
- this.cause = cause;
12856
- }
12857
- /**
12858
- * Checks if the given error is an AI SDK Error.
12859
- * @param {unknown} error - The error to check.
12860
- * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
12861
- */
12862
- static isInstance(error) {
12863
- return _AISDKError.hasMarker(error, marker);
12864
- }
12865
- static hasMarker(error, marker15) {
12866
- const markerSymbol = Symbol.for(marker15);
12867
- return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
12868
- }
12869
- };
12870
- _a = symbol;
12871
- var AISDKError = _AISDKError;
12872
-
12873
- // src/errors/api-call-error.ts
12874
- var name = "AI_APICallError";
12875
- var marker2 = `vercel.ai.error.${name}`;
12876
- var symbol2 = Symbol.for(marker2);
12877
- var _a2;
12878
- var APICallError = class extends AISDKError {
12879
- constructor({
12880
- message,
12881
- url,
12882
- requestBodyValues,
12883
- statusCode,
12884
- responseHeaders,
12885
- responseBody,
12886
- cause,
12887
- isRetryable = statusCode != null && (statusCode === 408 || // request timeout
12888
- statusCode === 409 || // conflict
12889
- statusCode === 429 || // too many requests
12890
- statusCode >= 500),
12891
- // server error
12892
- data
12893
- }) {
12894
- super({ name, message, cause });
12895
- this[_a2] = true;
12896
- this.url = url;
12897
- this.requestBodyValues = requestBodyValues;
12898
- this.statusCode = statusCode;
12899
- this.responseHeaders = responseHeaders;
12900
- this.responseBody = responseBody;
12901
- this.isRetryable = isRetryable;
12902
- this.data = data;
12903
- }
12904
- static isInstance(error) {
12905
- return AISDKError.hasMarker(error, marker2);
12906
- }
12907
- };
12908
- _a2 = symbol2;
12909
-
12910
- // src/errors/empty-response-body-error.ts
12911
- var name2 = "AI_EmptyResponseBodyError";
12912
- var marker3 = `vercel.ai.error.${name2}`;
12913
- var symbol3 = Symbol.for(marker3);
12914
- var _a3;
12915
- var EmptyResponseBodyError = class extends AISDKError {
12916
- // used in isInstance
12917
- constructor({ message = "Empty response body" } = {}) {
12918
- super({ name: name2, message });
12919
- this[_a3] = true;
12920
- }
12921
- static isInstance(error) {
12922
- return AISDKError.hasMarker(error, marker3);
12923
- }
12924
- };
12925
- _a3 = symbol3;
12926
-
12927
- // src/errors/get-error-message.ts
12928
- function getErrorMessage(error) {
12929
- if (error == null) {
12930
- return "unknown error";
12931
- }
12932
- if (typeof error === "string") {
12933
- return error;
12934
- }
12935
- if (error instanceof Error) {
12936
- return error.message;
12937
- }
12938
- return JSON.stringify(error);
12939
- }
12940
-
12941
- // src/errors/invalid-argument-error.ts
12942
- var name3 = "AI_InvalidArgumentError";
12943
- var marker4 = `vercel.ai.error.${name3}`;
12944
- var symbol4 = Symbol.for(marker4);
12945
- var _a4;
12946
- var InvalidArgumentError = class extends AISDKError {
12947
- constructor({
12948
- message,
12949
- cause,
12950
- argument
12951
- }) {
12952
- super({ name: name3, message, cause });
12953
- this[_a4] = true;
12954
- this.argument = argument;
12955
- }
12956
- static isInstance(error) {
12957
- return AISDKError.hasMarker(error, marker4);
12958
- }
12959
- };
12960
- _a4 = symbol4;
12961
-
12962
- // src/errors/invalid-prompt-error.ts
12963
- var name4 = "AI_InvalidPromptError";
12964
- var marker5 = `vercel.ai.error.${name4}`;
12965
- var symbol5 = Symbol.for(marker5);
12966
- var _a5;
12967
- var InvalidPromptError = class extends AISDKError {
12968
- constructor({
12969
- prompt,
12970
- message,
12971
- cause
12972
- }) {
12973
- super({ name: name4, message: `Invalid prompt: ${message}`, cause });
12974
- this[_a5] = true;
12975
- this.prompt = prompt;
12976
- }
12977
- static isInstance(error) {
12978
- return AISDKError.hasMarker(error, marker5);
12979
- }
12980
- };
12981
- _a5 = symbol5;
12982
-
12983
- // src/errors/invalid-response-data-error.ts
12984
- var name5 = "AI_InvalidResponseDataError";
12985
- var marker6 = `vercel.ai.error.${name5}`;
12986
- var symbol6 = Symbol.for(marker6);
12987
- var _a6;
12988
- var InvalidResponseDataError = class extends AISDKError {
12989
- constructor({
12990
- data,
12991
- message = `Invalid response data: ${JSON.stringify(data)}.`
12992
- }) {
12993
- super({ name: name5, message });
12994
- this[_a6] = true;
12995
- this.data = data;
12996
- }
12997
- static isInstance(error) {
12998
- return AISDKError.hasMarker(error, marker6);
12999
- }
13000
- };
13001
- _a6 = symbol6;
13002
-
13003
- // src/errors/json-parse-error.ts
13004
- var name6 = "AI_JSONParseError";
13005
- var marker7 = `vercel.ai.error.${name6}`;
13006
- var symbol7 = Symbol.for(marker7);
13007
- var _a7;
13008
- var JSONParseError = class extends AISDKError {
13009
- constructor({ text, cause }) {
13010
- super({
13011
- name: name6,
13012
- message: `JSON parsing failed: Text: ${text}.
13013
- Error message: ${getErrorMessage(cause)}`,
13014
- cause
13015
- });
13016
- this[_a7] = true;
13017
- this.text = text;
13018
- }
13019
- static isInstance(error) {
13020
- return AISDKError.hasMarker(error, marker7);
13021
- }
13022
- };
13023
- _a7 = symbol7;
13024
-
13025
- // src/errors/load-api-key-error.ts
13026
- var name7 = "AI_LoadAPIKeyError";
13027
- var marker8 = `vercel.ai.error.${name7}`;
13028
- var symbol8 = Symbol.for(marker8);
13029
- var _a8;
13030
- var LoadAPIKeyError = class extends AISDKError {
13031
- // used in isInstance
13032
- constructor({ message }) {
13033
- super({ name: name7, message });
13034
- this[_a8] = true;
13035
- }
13036
- static isInstance(error) {
13037
- return AISDKError.hasMarker(error, marker8);
13038
- }
13039
- };
13040
- _a8 = symbol8;
13041
-
13042
- // src/errors/type-validation-error.ts
13043
- var name12 = "AI_TypeValidationError";
13044
- var marker13 = `vercel.ai.error.${name12}`;
13045
- var symbol13 = Symbol.for(marker13);
13046
- var _a13;
13047
- var _TypeValidationError = class _TypeValidationError extends AISDKError {
13048
- constructor({ value, cause }) {
13049
- super({
13050
- name: name12,
13051
- message: `Type validation failed: Value: ${JSON.stringify(value)}.
13052
- Error message: ${getErrorMessage(cause)}`,
13053
- cause
13054
- });
13055
- this[_a13] = true;
13056
- this.value = value;
13057
- }
13058
- static isInstance(error) {
13059
- return AISDKError.hasMarker(error, marker13);
13060
- }
13061
- /**
13062
- * Wraps an error into a TypeValidationError.
13063
- * If the cause is already a TypeValidationError with the same value, it returns the cause.
13064
- * Otherwise, it creates a new TypeValidationError.
13065
- *
13066
- * @param {Object} params - The parameters for wrapping the error.
13067
- * @param {unknown} params.value - The value that failed validation.
13068
- * @param {unknown} params.cause - The original error or cause of the validation failure.
13069
- * @returns {TypeValidationError} A TypeValidationError instance.
13070
- */
13071
- static wrap({
13072
- value,
13073
- cause
13074
- }) {
13075
- return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
13076
- }
13077
- };
13078
- _a13 = symbol13;
13079
- var TypeValidationError = _TypeValidationError;
13080
-
13081
- // src/errors/unsupported-functionality-error.ts
13082
- var name13 = "AI_UnsupportedFunctionalityError";
13083
- var marker14 = `vercel.ai.error.${name13}`;
13084
- var symbol14 = Symbol.for(marker14);
13085
- var _a14;
13086
- var UnsupportedFunctionalityError = class extends AISDKError {
13087
- constructor({
13088
- functionality,
13089
- message = `'${functionality}' functionality not supported.`
13090
- }) {
13091
- super({ name: name13, message });
13092
- this[_a14] = true;
13093
- this.functionality = functionality;
13094
- }
13095
- static isInstance(error) {
13096
- return AISDKError.hasMarker(error, marker14);
13097
- }
13098
- };
13099
- _a14 = symbol14;
13100
-
13101
- class ParseError extends Error {
13102
- constructor(message, options) {
13103
- super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
13104
- }
13105
- }
13106
- function noop(_arg) {
13107
- }
13108
- function createParser(callbacks) {
13109
- if (typeof callbacks == "function")
13110
- throw new TypeError(
13111
- "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
13112
- );
13113
- const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
13114
- let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
13115
- function feed(newChunk) {
13116
- const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
13117
- for (const line of complete)
13118
- parseLine(line);
13119
- incompleteLine = incomplete, isFirstChunk = false;
13120
- }
13121
- function parseLine(line) {
13122
- if (line === "") {
13123
- dispatchEvent();
13124
- return;
13125
- }
13126
- if (line.startsWith(":")) {
13127
- onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
13128
- return;
13129
- }
13130
- const fieldSeparatorIndex = line.indexOf(":");
13131
- if (fieldSeparatorIndex !== -1) {
13132
- const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
13133
- processField(field, value, line);
13134
- return;
13135
- }
13136
- processField(line, "", line);
13137
- }
13138
- function processField(field, value, line) {
13139
- switch (field) {
13140
- case "event":
13141
- eventType = value;
13142
- break;
13143
- case "data":
13144
- data = `${data}${value}
13145
- `;
13146
- break;
13147
- case "id":
13148
- id = value.includes("\0") ? void 0 : value;
13149
- break;
13150
- case "retry":
13151
- /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
13152
- new ParseError(`Invalid \`retry\` value: "${value}"`, {
13153
- type: "invalid-retry",
13154
- value,
13155
- line
13156
- })
13157
- );
13158
- break;
13159
- default:
13160
- onError(
13161
- new ParseError(
13162
- `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
13163
- { type: "unknown-field", field, value, line }
13164
- )
13165
- );
13166
- break;
13167
- }
13168
- }
13169
- function dispatchEvent() {
13170
- data.length > 0 && onEvent({
13171
- id,
13172
- event: eventType || void 0,
13173
- // If the data buffer's last character is a U+000A LINE FEED (LF) character,
13174
- // then remove the last character from the data buffer.
13175
- data: data.endsWith(`
13176
- `) ? data.slice(0, -1) : data
13177
- }), id = void 0, data = "", eventType = "";
13178
- }
13179
- function reset(options = {}) {
13180
- incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
13181
- }
13182
- return { feed, reset };
13183
- }
13184
- function splitLines(chunk) {
13185
- const lines = [];
13186
- let incompleteLine = "", searchIndex = 0;
13187
- for (; searchIndex < chunk.length; ) {
13188
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
13189
- `, searchIndex);
13190
- let lineEnd = -1;
13191
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
13192
- incompleteLine = chunk.slice(searchIndex);
13193
- break;
13194
- } else {
13195
- const line = chunk.slice(searchIndex, lineEnd);
13196
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
13197
- ` && searchIndex++;
13198
- }
13199
- }
13200
- return [lines, incompleteLine];
13201
- }
13202
-
13203
- class EventSourceParserStream extends TransformStream {
13204
- constructor({ onError, onRetry, onComment } = {}) {
13205
- let parser;
13206
- super({
13207
- start(controller) {
13208
- parser = createParser({
13209
- onEvent: (event) => {
13210
- controller.enqueue(event);
13211
- },
13212
- onError(error) {
13213
- onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
13214
- },
13215
- onRetry,
13216
- onComment
13217
- });
13218
- },
13219
- transform(chunk) {
13220
- parser.feed(chunk);
13221
- }
13222
- });
13223
- }
13224
- }
13225
-
13226
- // src/combine-headers.ts
13227
- function combineHeaders(...headers) {
13228
- return headers.reduce(
13229
- (combinedHeaders, currentHeaders) => ({
13230
- ...combinedHeaders,
13231
- ...currentHeaders != null ? currentHeaders : {}
13232
- }),
13233
- {}
13234
- );
13235
- }
13236
-
13237
- // src/extract-response-headers.ts
13238
- function extractResponseHeaders(response) {
13239
- const headers = {};
13240
- response.headers.forEach((value, key) => {
13241
- headers[key] = value;
13242
- });
13243
- return headers;
13244
- }
13245
- var createIdGenerator = ({
13246
- prefix,
13247
- size: defaultSize = 16,
13248
- alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
13249
- separator = "-"
13250
- } = {}) => {
13251
- const generator = customAlphabet(alphabet, defaultSize);
13252
- if (prefix == null) {
13253
- return generator;
13254
- }
13255
- if (alphabet.includes(separator)) {
13256
- throw new InvalidArgumentError({
13257
- argument: "separator",
13258
- message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
13259
- });
13260
- }
13261
- return (size) => `${prefix}${separator}${generator(size)}`;
13262
- };
13263
- var generateId = createIdGenerator();
13264
-
13265
- // src/remove-undefined-entries.ts
13266
- function removeUndefinedEntries(record) {
13267
- return Object.fromEntries(
13268
- Object.entries(record).filter(([_key, value]) => value != null)
13269
- );
13270
- }
13271
-
13272
- // src/is-abort-error.ts
13273
- function isAbortError(error) {
13274
- return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
13275
- }
13276
- function loadApiKey({
13277
- apiKey,
13278
- environmentVariableName,
13279
- apiKeyParameterName = "apiKey",
13280
- description
13281
- }) {
13282
- if (typeof apiKey === "string") {
13283
- return apiKey;
13284
- }
13285
- if (apiKey != null) {
13286
- throw new LoadAPIKeyError({
13287
- message: `${description} API key must be a string.`
13288
- });
13289
- }
13290
- if (typeof process === "undefined") {
13291
- throw new LoadAPIKeyError({
13292
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
13293
- });
13294
- }
13295
- apiKey = process.env[environmentVariableName];
13296
- if (apiKey == null) {
13297
- throw new LoadAPIKeyError({
13298
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
13299
- });
13300
- }
13301
- if (typeof apiKey !== "string") {
13302
- throw new LoadAPIKeyError({
13303
- message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
13304
- });
13305
- }
13306
- return apiKey;
13307
- }
13308
-
13309
- // src/validator.ts
13310
- var validatorSymbol = Symbol.for("vercel.ai.validator");
13311
- function validator(validate) {
13312
- return { [validatorSymbol]: true, validate };
13313
- }
13314
- function isValidator(value) {
13315
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
13316
- }
13317
- function asValidator(value) {
13318
- return isValidator(value) ? value : zodValidator(value);
13319
- }
13320
- function zodValidator(zodSchema) {
13321
- return validator((value) => {
13322
- const result = zodSchema.safeParse(value);
13323
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
13324
- });
13325
- }
13326
-
13327
- // src/validate-types.ts
13328
- function validateTypes({
13329
- value,
13330
- schema: inputSchema
13331
- }) {
13332
- const result = safeValidateTypes({ value, schema: inputSchema });
13333
- if (!result.success) {
13334
- throw TypeValidationError.wrap({ value, cause: result.error });
13335
- }
13336
- return result.value;
13337
- }
13338
- function safeValidateTypes({
13339
- value,
13340
- schema
13341
- }) {
13342
- const validator2 = asValidator(schema);
13343
- try {
13344
- if (validator2.validate == null) {
13345
- return { success: true, value };
13346
- }
13347
- const result = validator2.validate(value);
13348
- if (result.success) {
13349
- return result;
13350
- }
13351
- return {
13352
- success: false,
13353
- error: TypeValidationError.wrap({ value, cause: result.error })
13354
- };
13355
- } catch (error) {
13356
- return {
13357
- success: false,
13358
- error: TypeValidationError.wrap({ value, cause: error })
13359
- };
13360
- }
13361
- }
13362
-
13363
- // src/parse-json.ts
13364
- function parseJSON({
13365
- text,
13366
- schema
13367
- }) {
13368
- try {
13369
- const value = SecureJSON.parse(text);
13370
- if (schema == null) {
13371
- return value;
13372
- }
13373
- return validateTypes({ value, schema });
13374
- } catch (error) {
13375
- if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
13376
- throw error;
13377
- }
13378
- throw new JSONParseError({ text, cause: error });
13379
- }
13380
- }
13381
- function safeParseJSON({
13382
- text,
13383
- schema
13384
- }) {
13385
- try {
13386
- const value = SecureJSON.parse(text);
13387
- if (schema == null) {
13388
- return { success: true, value, rawValue: value };
13389
- }
13390
- const validationResult = safeValidateTypes({ value, schema });
13391
- return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
13392
- } catch (error) {
13393
- return {
13394
- success: false,
13395
- error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
13396
- };
13397
- }
13398
- }
13399
- function isParsableJson(input) {
13400
- try {
13401
- SecureJSON.parse(input);
13402
- return true;
13403
- } catch (e) {
13404
- return false;
13405
- }
13406
- }
13407
- var getOriginalFetch2 = () => globalThis.fetch;
13408
- var postJsonToApi = async ({
13409
- url,
13410
- headers,
13411
- body,
13412
- failedResponseHandler,
13413
- successfulResponseHandler,
13414
- abortSignal,
13415
- fetch
13416
- }) => postToApi({
13417
- url,
13418
- headers: {
13419
- "Content-Type": "application/json",
13420
- ...headers
13421
- },
13422
- body: {
13423
- content: JSON.stringify(body),
13424
- values: body
13425
- },
13426
- failedResponseHandler,
13427
- successfulResponseHandler,
13428
- abortSignal,
13429
- fetch
13430
- });
13431
- var postToApi = async ({
13432
- url,
13433
- headers = {},
13434
- body,
13435
- successfulResponseHandler,
13436
- failedResponseHandler,
13437
- abortSignal,
13438
- fetch = getOriginalFetch2()
13439
- }) => {
13440
- try {
13441
- const response = await fetch(url, {
13442
- method: "POST",
13443
- headers: removeUndefinedEntries(headers),
13444
- body: body.content,
13445
- signal: abortSignal
13446
- });
13447
- const responseHeaders = extractResponseHeaders(response);
13448
- if (!response.ok) {
13449
- let errorInformation;
13450
- try {
13451
- errorInformation = await failedResponseHandler({
13452
- response,
13453
- url,
13454
- requestBodyValues: body.values
13455
- });
13456
- } catch (error) {
13457
- if (isAbortError(error) || APICallError.isInstance(error)) {
13458
- throw error;
13459
- }
13460
- throw new APICallError({
13461
- message: "Failed to process error response",
13462
- cause: error,
13463
- statusCode: response.status,
13464
- url,
13465
- responseHeaders,
13466
- requestBodyValues: body.values
13467
- });
13468
- }
13469
- throw errorInformation.value;
13470
- }
13471
- try {
13472
- return await successfulResponseHandler({
13473
- response,
13474
- url,
13475
- requestBodyValues: body.values
13476
- });
13477
- } catch (error) {
13478
- if (error instanceof Error) {
13479
- if (isAbortError(error) || APICallError.isInstance(error)) {
13480
- throw error;
13481
- }
13482
- }
13483
- throw new APICallError({
13484
- message: "Failed to process successful response",
13485
- cause: error,
13486
- statusCode: response.status,
13487
- url,
13488
- responseHeaders,
13489
- requestBodyValues: body.values
13490
- });
13491
- }
13492
- } catch (error) {
13493
- if (isAbortError(error)) {
13494
- throw error;
13495
- }
13496
- if (error instanceof TypeError && error.message === "fetch failed") {
13497
- const cause = error.cause;
13498
- if (cause != null) {
13499
- throw new APICallError({
13500
- message: `Cannot connect to API: ${cause.message}`,
13501
- cause,
13502
- url,
13503
- requestBodyValues: body.values,
13504
- isRetryable: true
13505
- // retry when network error
13506
- });
13507
- }
13508
- }
13509
- throw error;
13510
- }
13511
- };
13512
- var createJsonErrorResponseHandler = ({
13513
- errorSchema,
13514
- errorToMessage,
13515
- isRetryable
13516
- }) => async ({ response, url, requestBodyValues }) => {
13517
- const responseBody = await response.text();
13518
- const responseHeaders = extractResponseHeaders(response);
13519
- if (responseBody.trim() === "") {
13520
- return {
13521
- responseHeaders,
13522
- value: new APICallError({
13523
- message: response.statusText,
13524
- url,
13525
- requestBodyValues,
13526
- statusCode: response.status,
13527
- responseHeaders,
13528
- responseBody,
13529
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
13530
- })
13531
- };
13532
- }
13533
- try {
13534
- const parsedError = parseJSON({
13535
- text: responseBody,
13536
- schema: errorSchema
13537
- });
13538
- return {
13539
- responseHeaders,
13540
- value: new APICallError({
13541
- message: errorToMessage(parsedError),
13542
- url,
13543
- requestBodyValues,
13544
- statusCode: response.status,
13545
- responseHeaders,
13546
- responseBody,
13547
- data: parsedError,
13548
- isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
13549
- })
13550
- };
13551
- } catch (parseError) {
13552
- return {
13553
- responseHeaders,
13554
- value: new APICallError({
13555
- message: response.statusText,
13556
- url,
13557
- requestBodyValues,
13558
- statusCode: response.status,
13559
- responseHeaders,
13560
- responseBody,
13561
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
13562
- })
13563
- };
13564
- }
13565
- };
13566
- var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
13567
- const responseHeaders = extractResponseHeaders(response);
13568
- if (response.body == null) {
13569
- throw new EmptyResponseBodyError({});
13570
- }
13571
- return {
13572
- responseHeaders,
13573
- value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
13574
- new TransformStream({
13575
- transform({ data }, controller) {
13576
- if (data === "[DONE]") {
13577
- return;
13578
- }
13579
- controller.enqueue(
13580
- safeParseJSON({
13581
- text: data,
13582
- schema: chunkSchema
13583
- })
13584
- );
13585
- }
13586
- })
13587
- )
13588
- };
13589
- };
13590
- var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
13591
- const responseBody = await response.text();
13592
- const parsedResult = safeParseJSON({
13593
- text: responseBody,
13594
- schema: responseSchema
13595
- });
13596
- const responseHeaders = extractResponseHeaders(response);
13597
- if (!parsedResult.success) {
13598
- throw new APICallError({
13599
- message: "Invalid JSON response",
13600
- cause: parsedResult.error,
13601
- statusCode: response.status,
13602
- responseHeaders,
13603
- responseBody,
13604
- url,
13605
- requestBodyValues
13606
- });
13607
- }
13608
- return {
13609
- responseHeaders,
13610
- value: parsedResult.value,
13611
- rawValue: parsedResult.rawValue
13612
- };
13613
- };
13614
-
13615
- // src/uint8-utils.ts
13616
- var { btoa} = globalThis;
13617
- function convertUint8ArrayToBase64(array) {
13618
- let latin1string = "";
13619
- for (let i = 0; i < array.length; i++) {
13620
- latin1string += String.fromCodePoint(array[i]);
13621
- }
13622
- return btoa(latin1string);
13623
- }
13624
-
13625
- // src/without-trailing-slash.ts
13626
- function withoutTrailingSlash(url) {
13627
- return url == null ? void 0 : url.replace(/\/$/, "");
13628
- }
13629
-
13630
12846
  var __defProp = Object.defineProperty;
13631
12847
  var __defProps = Object.defineProperties;
13632
12848
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
@@ -13658,6 +12874,29 @@ var __objRest = (source, exclude) => {
13658
12874
  }
13659
12875
  return target;
13660
12876
  };
12877
+ var ReasoningDetailSummarySchema = z.object({
12878
+ type: z.literal("reasoning.summary" /* Summary */),
12879
+ summary: z.string()
12880
+ });
12881
+ var ReasoningDetailEncryptedSchema = z.object({
12882
+ type: z.literal("reasoning.encrypted" /* Encrypted */),
12883
+ data: z.string()
12884
+ });
12885
+ var ReasoningDetailTextSchema = z.object({
12886
+ type: z.literal("reasoning.text" /* Text */),
12887
+ text: z.string().nullish(),
12888
+ signature: z.string().nullish()
12889
+ });
12890
+ var ReasoningDetailUnionSchema = z.union([
12891
+ ReasoningDetailSummarySchema,
12892
+ ReasoningDetailEncryptedSchema,
12893
+ ReasoningDetailTextSchema
12894
+ ]);
12895
+ var ReasoningDetailsWithUnknownSchema = z.union([
12896
+ ReasoningDetailUnionSchema,
12897
+ z.unknown().transform(() => null)
12898
+ ]);
12899
+ var ReasoningDetailArraySchema = z.array(ReasoningDetailsWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
13661
12900
  function getCacheControl(providerMetadata) {
13662
12901
  var _a, _b, _c;
13663
12902
  const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
@@ -13689,14 +12928,15 @@ function convertToOpenRouterChatMessages(prompt) {
13689
12928
  const messageCacheControl = getCacheControl(providerMetadata);
13690
12929
  const contentParts = content.map(
13691
12930
  (part) => {
13692
- var _a2, _b2, _c2, _d, _e, _f;
12931
+ var _a2, _b2, _c2, _d;
12932
+ const cacheControl = (_a2 = getCacheControl(part.providerMetadata)) != null ? _a2 : messageCacheControl;
13693
12933
  switch (part.type) {
13694
12934
  case "text":
13695
12935
  return {
13696
12936
  type: "text",
13697
12937
  text: part.text,
13698
12938
  // For text parts, only use part-specific cache control
13699
- cache_control: (_a2 = getCacheControl(part.providerMetadata)) != null ? _a2 : messageCacheControl
12939
+ cache_control: cacheControl
13700
12940
  };
13701
12941
  case "image":
13702
12942
  return {
@@ -13707,18 +12947,18 @@ function convertToOpenRouterChatMessages(prompt) {
13707
12947
  )}`
13708
12948
  },
13709
12949
  // For image parts, use part-specific or message-level cache control
13710
- cache_control: (_c2 = getCacheControl(part.providerMetadata)) != null ? _c2 : messageCacheControl
12950
+ cache_control: cacheControl
13711
12951
  };
13712
12952
  case "file":
13713
12953
  return {
13714
12954
  type: "file",
13715
12955
  file: {
13716
12956
  filename: String(
13717
- (_e = (_d = part.providerMetadata) == null ? void 0 : _d.openrouter) == null ? void 0 : _e.filename
12957
+ (_d = (_c2 = part.providerMetadata) == null ? void 0 : _c2.openrouter) == null ? void 0 : _d.filename
13718
12958
  ),
13719
12959
  file_data: part.data instanceof Uint8Array ? `data:${part.mimeType};base64,${convertUint8ArrayToBase64(part.data)}` : `data:${part.mimeType};base64,${part.data}`
13720
12960
  },
13721
- cache_control: (_f = getCacheControl(part.providerMetadata)) != null ? _f : messageCacheControl
12961
+ cache_control: cacheControl
13722
12962
  };
13723
12963
  default: {
13724
12964
  const _exhaustiveCheck = part;
@@ -13737,6 +12977,8 @@ function convertToOpenRouterChatMessages(prompt) {
13737
12977
  }
13738
12978
  case "assistant": {
13739
12979
  let text = "";
12980
+ let reasoning = "";
12981
+ const reasoningDetails = [];
13740
12982
  const toolCalls = [];
13741
12983
  for (const part of content) {
13742
12984
  switch (part.type) {
@@ -13755,9 +12997,23 @@ function convertToOpenRouterChatMessages(prompt) {
13755
12997
  });
13756
12998
  break;
13757
12999
  }
13758
- // TODO: Handle reasoning and redacted-reasoning
13759
- case "reasoning":
13760
- case "redacted-reasoning":
13000
+ case "reasoning": {
13001
+ reasoning += part.text;
13002
+ reasoningDetails.push({
13003
+ type: "reasoning.text" /* Text */,
13004
+ text: part.text,
13005
+ signature: part.signature
13006
+ });
13007
+ break;
13008
+ }
13009
+ case "redacted-reasoning": {
13010
+ reasoningDetails.push({
13011
+ type: "reasoning.encrypted" /* Encrypted */,
13012
+ data: part.data
13013
+ });
13014
+ break;
13015
+ }
13016
+ case "file":
13761
13017
  break;
13762
13018
  default: {
13763
13019
  const _exhaustiveCheck = part;
@@ -13769,6 +13025,8 @@ function convertToOpenRouterChatMessages(prompt) {
13769
13025
  role: "assistant",
13770
13026
  content: text,
13771
13027
  tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
13028
+ reasoning: reasoning || void 0,
13029
+ reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
13772
13030
  cache_control: getCacheControl(providerMetadata)
13773
13031
  });
13774
13032
  break;
@@ -13824,10 +13082,10 @@ function mapOpenRouterFinishReason(finishReason) {
13824
13082
  }
13825
13083
  var OpenRouterErrorResponseSchema = z.object({
13826
13084
  error: z.object({
13085
+ code: z.union([z.string(), z.number()]).nullable(),
13827
13086
  message: z.string(),
13828
- type: z.string(),
13829
- param: z.any().nullable(),
13830
- code: z.string().nullable()
13087
+ type: z.string().nullable(),
13088
+ param: z.any().nullable()
13831
13089
  })
13832
13090
  });
13833
13091
  var openrouterFailedResponseHandler = createJsonErrorResponseHandler({
@@ -13866,7 +13124,7 @@ var OpenRouterChatLanguageModel = class {
13866
13124
  }) {
13867
13125
  var _a;
13868
13126
  const type = mode.type;
13869
- const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata["openrouter"]) != null ? _a : {};
13127
+ const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata.openrouter) != null ? _a : {};
13870
13128
  const baseArgs = __spreadValues(__spreadValues(__spreadValues({
13871
13129
  // model id:
13872
13130
  model: this.modelId,
@@ -13891,7 +13149,8 @@ var OpenRouterChatLanguageModel = class {
13891
13149
  messages: convertToOpenRouterChatMessages(prompt),
13892
13150
  // OpenRouter specific settings:
13893
13151
  include_reasoning: this.settings.includeReasoning,
13894
- reasoning: this.settings.reasoning
13152
+ reasoning: this.settings.reasoning,
13153
+ usage: this.settings.usage
13895
13154
  }, this.config.extraBody), this.settings.extraBody), extraCallingBody);
13896
13155
  switch (type) {
13897
13156
  case "regular": {
@@ -13927,7 +13186,7 @@ var OpenRouterChatLanguageModel = class {
13927
13186
  }
13928
13187
  }
13929
13188
  async doGenerate(options) {
13930
- var _b, _c, _d, _e, _f, _g, _h;
13189
+ var _b, _c, _d, _e, _f, _g, _h, _i, _j;
13931
13190
  const args = this.getArgs(options);
13932
13191
  const { responseHeaders, value: response } = await postJsonToApi({
13933
13192
  url: this.config.url({
@@ -13948,14 +13207,79 @@ var OpenRouterChatLanguageModel = class {
13948
13207
  if (!choice) {
13949
13208
  throw new Error("No choice in response");
13950
13209
  }
13951
- return {
13210
+ const usageInfo = response.usage ? {
13211
+ promptTokens: (_b = response.usage.prompt_tokens) != null ? _b : 0,
13212
+ completionTokens: (_c = response.usage.completion_tokens) != null ? _c : 0
13213
+ } : {
13214
+ promptTokens: 0,
13215
+ completionTokens: 0
13216
+ };
13217
+ const providerMetadata = {};
13218
+ if (response.usage && ((_d = this.settings.usage) == null ? void 0 : _d.include)) {
13219
+ providerMetadata.openrouter = {
13220
+ usage: {
13221
+ promptTokens: response.usage.prompt_tokens,
13222
+ promptTokensDetails: response.usage.prompt_tokens_details ? {
13223
+ cachedTokens: (_e = response.usage.prompt_tokens_details.cached_tokens) != null ? _e : 0
13224
+ } : void 0,
13225
+ completionTokens: response.usage.completion_tokens,
13226
+ completionTokensDetails: response.usage.completion_tokens_details ? {
13227
+ reasoningTokens: (_f = response.usage.completion_tokens_details.reasoning_tokens) != null ? _f : 0
13228
+ } : void 0,
13229
+ cost: response.usage.cost,
13230
+ totalTokens: (_g = response.usage.total_tokens) != null ? _g : 0
13231
+ }
13232
+ };
13233
+ }
13234
+ const hasProviderMetadata = Object.keys(providerMetadata).length > 0;
13235
+ const reasoningDetails = (_h = choice.message.reasoning_details) != null ? _h : [];
13236
+ const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
13237
+ var _a2;
13238
+ switch (detail.type) {
13239
+ case "reasoning.text" /* Text */: {
13240
+ if (detail.text) {
13241
+ return {
13242
+ type: "text",
13243
+ text: detail.text,
13244
+ signature: (_a2 = detail.signature) != null ? _a2 : void 0
13245
+ };
13246
+ }
13247
+ break;
13248
+ }
13249
+ case "reasoning.summary" /* Summary */: {
13250
+ if (detail.summary) {
13251
+ return {
13252
+ type: "text",
13253
+ text: detail.summary
13254
+ };
13255
+ }
13256
+ break;
13257
+ }
13258
+ case "reasoning.encrypted" /* Encrypted */: {
13259
+ if (detail.data) {
13260
+ return {
13261
+ type: "redacted",
13262
+ data: detail.data
13263
+ };
13264
+ }
13265
+ break;
13266
+ }
13267
+ }
13268
+ return null;
13269
+ }).filter((p) => p !== null) : choice.message.reasoning ? [
13270
+ {
13271
+ type: "text",
13272
+ text: choice.message.reasoning
13273
+ }
13274
+ ] : [];
13275
+ return __spreadValues({
13952
13276
  response: {
13953
13277
  id: response.id,
13954
13278
  modelId: response.model
13955
13279
  },
13956
- text: (_b = choice.message.content) != null ? _b : void 0,
13957
- reasoning: (_c = choice.message.reasoning) != null ? _c : void 0,
13958
- toolCalls: (_d = choice.message.tool_calls) == null ? void 0 : _d.map((toolCall) => {
13280
+ text: (_i = choice.message.content) != null ? _i : void 0,
13281
+ reasoning,
13282
+ toolCalls: (_j = choice.message.tool_calls) == null ? void 0 : _j.map((toolCall) => {
13959
13283
  var _a2;
13960
13284
  return {
13961
13285
  toolCallType: "function",
@@ -13965,17 +13289,15 @@ var OpenRouterChatLanguageModel = class {
13965
13289
  };
13966
13290
  }),
13967
13291
  finishReason: mapOpenRouterFinishReason(choice.finish_reason),
13968
- usage: {
13969
- promptTokens: (_f = (_e = response.usage) == null ? void 0 : _e.prompt_tokens) != null ? _f : 0,
13970
- completionTokens: (_h = (_g = response.usage) == null ? void 0 : _g.completion_tokens) != null ? _h : 0
13971
- },
13292
+ usage: usageInfo,
13972
13293
  rawCall: { rawPrompt, rawSettings },
13973
13294
  rawResponse: { headers: responseHeaders },
13974
13295
  warnings: [],
13975
13296
  logprobs: mapOpenRouterChatLogProbsOutput(choice.logprobs)
13976
- };
13297
+ }, hasProviderMetadata ? { providerMetadata } : {});
13977
13298
  }
13978
13299
  async doStream(options) {
13300
+ var _a, _c;
13979
13301
  const args = this.getArgs(options);
13980
13302
  const { responseHeaders, value: response } = await postJsonToApi({
13981
13303
  url: this.config.url({
@@ -13986,7 +13308,9 @@ var OpenRouterChatLanguageModel = class {
13986
13308
  body: __spreadProps(__spreadValues({}, args), {
13987
13309
  stream: true,
13988
13310
  // only include stream_options when in strict compatibility mode:
13989
- stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
13311
+ stream_options: this.config.compatibility === "strict" ? __spreadValues({
13312
+ include_usage: true
13313
+ }, ((_a = this.settings.usage) == null ? void 0 : _a.include) ? { include_usage: true } : {}) : void 0
13990
13314
  }),
13991
13315
  failedResponseHandler: openrouterFailedResponseHandler,
13992
13316
  successfulResponseHandler: createEventSourceResponseHandler(
@@ -13995,7 +13319,7 @@ var OpenRouterChatLanguageModel = class {
13995
13319
  abortSignal: options.abortSignal,
13996
13320
  fetch: this.config.fetch
13997
13321
  });
13998
- const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
13322
+ const _b = args, { messages: rawPrompt } = _b, rawSettings = __objRest(_b, ["messages"]);
13999
13323
  const toolCalls = [];
14000
13324
  let finishReason = "other";
14001
13325
  let usage = {
@@ -14003,11 +13327,13 @@ var OpenRouterChatLanguageModel = class {
14003
13327
  completionTokens: Number.NaN
14004
13328
  };
14005
13329
  let logprobs;
13330
+ const openrouterUsage = {};
13331
+ const shouldIncludeUsageAccounting = !!((_c = this.settings.usage) == null ? void 0 : _c.include);
14006
13332
  return {
14007
13333
  stream: response.pipeThrough(
14008
13334
  new TransformStream({
14009
13335
  transform(chunk, controller) {
14010
- var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
13336
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
14011
13337
  if (!chunk.success) {
14012
13338
  finishReason = "error";
14013
13339
  controller.enqueue({ type: "error", error: chunk.error });
@@ -14036,6 +13362,20 @@ var OpenRouterChatLanguageModel = class {
14036
13362
  promptTokens: value.usage.prompt_tokens,
14037
13363
  completionTokens: value.usage.completion_tokens
14038
13364
  };
13365
+ openrouterUsage.promptTokens = value.usage.prompt_tokens;
13366
+ if (value.usage.prompt_tokens_details) {
13367
+ openrouterUsage.promptTokensDetails = {
13368
+ cachedTokens: (_a2 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a2 : 0
13369
+ };
13370
+ }
13371
+ openrouterUsage.completionTokens = value.usage.completion_tokens;
13372
+ if (value.usage.completion_tokens_details) {
13373
+ openrouterUsage.completionTokensDetails = {
13374
+ reasoningTokens: (_b2 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b2 : 0
13375
+ };
13376
+ }
13377
+ openrouterUsage.cost = value.usage.cost;
13378
+ openrouterUsage.totalTokens = value.usage.total_tokens;
14039
13379
  }
14040
13380
  const choice = value.choices[0];
14041
13381
  if ((choice == null ? void 0 : choice.finish_reason) != null) {
@@ -14057,11 +13397,52 @@ var OpenRouterChatLanguageModel = class {
14057
13397
  textDelta: delta.reasoning
14058
13398
  });
14059
13399
  }
13400
+ if (delta.reasoning_details && delta.reasoning_details.length > 0) {
13401
+ for (const detail of delta.reasoning_details) {
13402
+ switch (detail.type) {
13403
+ case "reasoning.text" /* Text */: {
13404
+ if (detail.text) {
13405
+ controller.enqueue({
13406
+ type: "reasoning",
13407
+ textDelta: detail.text
13408
+ });
13409
+ }
13410
+ if (detail.signature) {
13411
+ controller.enqueue({
13412
+ type: "reasoning-signature",
13413
+ signature: detail.signature
13414
+ });
13415
+ }
13416
+ break;
13417
+ }
13418
+ case "reasoning.encrypted" /* Encrypted */: {
13419
+ if (detail.data) {
13420
+ controller.enqueue({
13421
+ type: "redacted-reasoning",
13422
+ data: detail.data
13423
+ });
13424
+ }
13425
+ break;
13426
+ }
13427
+ case "reasoning.summary" /* Summary */: {
13428
+ if (detail.summary) {
13429
+ controller.enqueue({
13430
+ type: "reasoning",
13431
+ textDelta: detail.summary
13432
+ });
13433
+ }
13434
+ break;
13435
+ }
13436
+ }
13437
+ }
13438
+ }
14060
13439
  const mappedLogprobs = mapOpenRouterChatLogProbsOutput(
14061
13440
  choice == null ? void 0 : choice.logprobs
14062
13441
  );
14063
13442
  if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
14064
- if (logprobs === void 0) logprobs = [];
13443
+ if (logprobs === void 0) {
13444
+ logprobs = [];
13445
+ }
14065
13446
  logprobs.push(...mappedLogprobs);
14066
13447
  }
14067
13448
  if (delta.tool_calls != null) {
@@ -14080,7 +13461,7 @@ var OpenRouterChatLanguageModel = class {
14080
13461
  message: `Expected 'id' to be a string.`
14081
13462
  });
14082
13463
  }
14083
- if (((_a2 = toolCallDelta.function) == null ? void 0 : _a2.name) == null) {
13464
+ if (((_c2 = toolCallDelta.function) == null ? void 0 : _c2.name) == null) {
14084
13465
  throw new InvalidResponseDataError({
14085
13466
  data: toolCallDelta,
14086
13467
  message: `Expected 'function.name' to be a string.`
@@ -14091,7 +13472,7 @@ var OpenRouterChatLanguageModel = class {
14091
13472
  type: "function",
14092
13473
  function: {
14093
13474
  name: toolCallDelta.function.name,
14094
- arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
13475
+ arguments: (_d = toolCallDelta.function.arguments) != null ? _d : ""
14095
13476
  },
14096
13477
  sent: false
14097
13478
  };
@@ -14099,7 +13480,7 @@ var OpenRouterChatLanguageModel = class {
14099
13480
  if (toolCall2 == null) {
14100
13481
  throw new Error("Tool call is missing");
14101
13482
  }
14102
- if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
13483
+ if (((_e = toolCall2.function) == null ? void 0 : _e.name) != null && ((_f = toolCall2.function) == null ? void 0 : _f.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
14103
13484
  controller.enqueue({
14104
13485
  type: "tool-call-delta",
14105
13486
  toolCallType: "function",
@@ -14110,7 +13491,7 @@ var OpenRouterChatLanguageModel = class {
14110
13491
  controller.enqueue({
14111
13492
  type: "tool-call",
14112
13493
  toolCallType: "function",
14113
- toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
13494
+ toolCallId: (_g = toolCall2.id) != null ? _g : generateId(),
14114
13495
  toolName: toolCall2.function.name,
14115
13496
  args: toolCall2.function.arguments
14116
13497
  });
@@ -14122,21 +13503,21 @@ var OpenRouterChatLanguageModel = class {
14122
13503
  if (toolCall == null) {
14123
13504
  throw new Error("Tool call is missing");
14124
13505
  }
14125
- if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
14126
- toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : "";
13506
+ if (((_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null) {
13507
+ toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null ? _j : "";
14127
13508
  }
14128
13509
  controller.enqueue({
14129
13510
  type: "tool-call-delta",
14130
13511
  toolCallType: "function",
14131
13512
  toolCallId: toolCall.id,
14132
13513
  toolName: toolCall.function.name,
14133
- argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
13514
+ argsTextDelta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
14134
13515
  });
14135
- if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
13516
+ if (((_l = toolCall.function) == null ? void 0 : _l.name) != null && ((_m = toolCall.function) == null ? void 0 : _m.arguments) != null && isParsableJson(toolCall.function.arguments)) {
14136
13517
  controller.enqueue({
14137
13518
  type: "tool-call",
14138
13519
  toolCallType: "function",
14139
- toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
13520
+ toolCallId: (_n = toolCall.id) != null ? _n : generateId(),
14140
13521
  toolName: toolCall.function.name,
14141
13522
  args: toolCall.function.arguments
14142
13523
  });
@@ -14162,12 +13543,19 @@ var OpenRouterChatLanguageModel = class {
14162
13543
  }
14163
13544
  }
14164
13545
  }
14165
- controller.enqueue({
13546
+ const providerMetadata = {};
13547
+ if (shouldIncludeUsageAccounting && (openrouterUsage.totalTokens !== void 0 || openrouterUsage.cost !== void 0 || openrouterUsage.promptTokensDetails !== void 0 || openrouterUsage.completionTokensDetails !== void 0)) {
13548
+ providerMetadata.openrouter = {
13549
+ usage: openrouterUsage
13550
+ };
13551
+ }
13552
+ const hasProviderMetadata = Object.keys(providerMetadata).length > 0 && shouldIncludeUsageAccounting;
13553
+ controller.enqueue(__spreadValues({
14166
13554
  type: "finish",
14167
13555
  finishReason,
14168
13556
  logprobs,
14169
13557
  usage
14170
- });
13558
+ }, hasProviderMetadata ? { providerMetadata } : {}));
14171
13559
  }
14172
13560
  })
14173
13561
  ),
@@ -14182,8 +13570,15 @@ var OpenRouterChatCompletionBaseResponseSchema = z.object({
14182
13570
  model: z.string().optional(),
14183
13571
  usage: z.object({
14184
13572
  prompt_tokens: z.number(),
13573
+ prompt_tokens_details: z.object({
13574
+ cached_tokens: z.number()
13575
+ }).nullish(),
14185
13576
  completion_tokens: z.number(),
14186
- total_tokens: z.number()
13577
+ completion_tokens_details: z.object({
13578
+ reasoning_tokens: z.number()
13579
+ }).nullish(),
13580
+ total_tokens: z.number(),
13581
+ cost: z.number().optional()
14187
13582
  }).nullish()
14188
13583
  });
14189
13584
  var OpenRouterNonStreamChatCompletionResponseSchema = OpenRouterChatCompletionBaseResponseSchema.extend({
@@ -14193,6 +13588,7 @@ var OpenRouterNonStreamChatCompletionResponseSchema = OpenRouterChatCompletionBa
14193
13588
  role: z.literal("assistant"),
14194
13589
  content: z.string().nullable().optional(),
14195
13590
  reasoning: z.string().nullable().optional(),
13591
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
14196
13592
  tool_calls: z.array(
14197
13593
  z.object({
14198
13594
  id: z.string().optional().nullable(),
@@ -14231,6 +13627,7 @@ var OpenRouterStreamChatCompletionChunkSchema = z.union([
14231
13627
  role: z.enum(["assistant"]).optional(),
14232
13628
  content: z.string().nullish(),
14233
13629
  reasoning: z.string().nullish().optional(),
13630
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
14234
13631
  tool_calls: z.array(
14235
13632
  z.object({
14236
13633
  index: z.number(),
@@ -14280,14 +13677,13 @@ function prepareToolsAndToolChoice(mode) {
14280
13677
  parameters: tool.parameters
14281
13678
  }
14282
13679
  };
14283
- } else {
14284
- return {
14285
- type: "function",
14286
- function: {
14287
- name: tool.name
14288
- }
14289
- };
14290
13680
  }
13681
+ return {
13682
+ type: "function",
13683
+ function: {
13684
+ name: tool.name
13685
+ }
13686
+ };
14291
13687
  });
14292
13688
  const toolChoice = mode.toolChoice;
14293
13689
  if (toolChoice == null) {
@@ -14390,6 +13786,11 @@ ${userMessage}
14390
13786
  functionality: "redacted reasoning messages"
14391
13787
  });
14392
13788
  }
13789
+ case "file": {
13790
+ throw new UnsupportedFunctionalityError({
13791
+ functionality: "file attachments"
13792
+ });
13793
+ }
14393
13794
  default: {
14394
13795
  const _exhaustiveCheck = part;
14395
13796
  throw new Error(
@@ -14468,7 +13869,7 @@ var OpenRouterCompletionLanguageModel = class {
14468
13869
  }) {
14469
13870
  var _a, _b;
14470
13871
  const type = mode.type;
14471
- const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata["openrouter"]) != null ? _a : {};
13872
+ const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata.openrouter) != null ? _a : {};
14472
13873
  const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
14473
13874
  prompt,
14474
13875
  inputFormat
@@ -14636,7 +14037,9 @@ var OpenRouterCompletionLanguageModel = class {
14636
14037
  choice == null ? void 0 : choice.logprobs
14637
14038
  );
14638
14039
  if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
14639
- if (logprobs === void 0) logprobs = [];
14040
+ if (logprobs === void 0) {
14041
+ logprobs = [];
14042
+ }
14640
14043
  logprobs.push(...mappedLogprobs);
14641
14044
  }
14642
14045
  },
@@ -14664,6 +14067,7 @@ var OpenRouterCompletionChunkSchema = z.union([
14664
14067
  z.object({
14665
14068
  text: z.string(),
14666
14069
  reasoning: z.string().nullish().optional(),
14070
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
14667
14071
  finish_reason: z.string().nullish(),
14668
14072
  index: z.number(),
14669
14073
  logprobs: z.object({
@@ -14721,9 +14125,7 @@ function createOpenRouter(options = {}) {
14721
14125
  }
14722
14126
  return createChatModel(modelId, settings);
14723
14127
  };
14724
- const provider = function(modelId, settings) {
14725
- return createLanguageModel(modelId, settings);
14726
- };
14128
+ const provider = (modelId, settings) => createLanguageModel(modelId, settings);
14727
14129
  provider.languageModel = createLanguageModel;
14728
14130
  provider.chat = createChatModel;
14729
14131
  provider.completion = createCompletionModel;
@@ -14756,12 +14158,12 @@ class RetryLanguageModel {
14756
14158
  temperature: request.temperature,
14757
14159
  topP: request.topP,
14758
14160
  topK: request.topK,
14759
- providerMetadata: {},
14760
14161
  abortSignal: request.abortSignal,
14761
14162
  });
14762
14163
  }
14763
14164
  async doGenerate(options) {
14764
14165
  const maxTokens = options.maxTokens;
14166
+ const providerMetadata = options.providerMetadata;
14765
14167
  const names = [...this.names, ...this.names];
14766
14168
  for (let i = 0; i < names.length; i++) {
14767
14169
  const name = names[i];
@@ -14773,11 +14175,17 @@ class RetryLanguageModel {
14773
14175
  options.maxTokens =
14774
14176
  this.llms[name].config?.maxTokens || config.maxTokens;
14775
14177
  }
14178
+ if (!providerMetadata) {
14179
+ options.providerMetadata = {};
14180
+ options.providerMetadata[llm.provider] = this.llms[name].options || {};
14181
+ }
14776
14182
  try {
14777
- let result = await llm.doGenerate(options);
14183
+ let result = (await llm.doGenerate(options));
14778
14184
  if (Log.isEnableDebug()) {
14779
14185
  Log.debug(`LLM nonstream body, name: ${name} => `, result.request?.body);
14780
14186
  }
14187
+ result.llm = name;
14188
+ result.llmConfig = this.llms[name];
14781
14189
  return result;
14782
14190
  }
14783
14191
  catch (e) {
@@ -14808,12 +14216,12 @@ class RetryLanguageModel {
14808
14216
  temperature: request.temperature,
14809
14217
  topP: request.topP,
14810
14218
  topK: request.topK,
14811
- providerMetadata: {},
14812
14219
  abortSignal: request.abortSignal,
14813
14220
  });
14814
14221
  }
14815
14222
  async doStream(options) {
14816
14223
  const maxTokens = options.maxTokens;
14224
+ const providerMetadata = options.providerMetadata;
14817
14225
  const names = [...this.names, ...this.names];
14818
14226
  for (let i = 0; i < names.length; i++) {
14819
14227
  const name = names[i];
@@ -14825,14 +14233,18 @@ class RetryLanguageModel {
14825
14233
  options.maxTokens =
14826
14234
  this.llms[name].config?.maxTokens || config.maxTokens;
14827
14235
  }
14236
+ if (!providerMetadata) {
14237
+ options.providerMetadata = {};
14238
+ options.providerMetadata[llm.provider] = this.llms[name].options || {};
14239
+ }
14828
14240
  try {
14829
14241
  const controller = new AbortController();
14830
14242
  const signal = options.abortSignal
14831
14243
  ? AbortSignal.any([options.abortSignal, controller.signal])
14832
14244
  : controller.signal;
14833
- const result = await call_timeout(async () => await llm.doStream({ ...options, abortSignal: signal }), this.stream_first_timeout, (e) => {
14245
+ const result = (await call_timeout(async () => await llm.doStream({ ...options, abortSignal: signal }), this.stream_first_timeout, (e) => {
14834
14246
  controller.abort();
14835
- });
14247
+ }));
14836
14248
  const stream = result.stream;
14837
14249
  const reader = stream.getReader();
14838
14250
  const { done, value } = await call_timeout(async () => await reader.read(), this.stream_first_timeout, (e) => {
@@ -14854,6 +14266,8 @@ class RetryLanguageModel {
14854
14266
  reader.releaseLock();
14855
14267
  continue;
14856
14268
  }
14269
+ result.llm = name;
14270
+ result.llmConfig = this.llms[name];
14857
14271
  result.stream = this.streamWrapper([chunk], reader);
14858
14272
  return result;
14859
14273
  }
@@ -14897,18 +14311,27 @@ class RetryLanguageModel {
14897
14311
  return createOpenAI({
14898
14312
  apiKey: apiKey,
14899
14313
  baseURL: baseURL,
14314
+ fetch: llm.fetch,
14315
+ organization: llm.config?.organization,
14316
+ project: llm.config?.project,
14317
+ headers: llm.config?.headers,
14318
+ compatibility: llm.config?.compatibility,
14900
14319
  }).languageModel(llm.model);
14901
14320
  }
14902
14321
  else if (llm.provider == "anthropic") {
14903
14322
  return createAnthropic({
14904
14323
  apiKey: apiKey,
14905
14324
  baseURL: baseURL,
14325
+ fetch: llm.fetch,
14326
+ headers: llm.config?.headers,
14906
14327
  }).languageModel(llm.model);
14907
14328
  }
14908
14329
  else if (llm.provider == "google") {
14909
14330
  return createGoogleGenerativeAI({
14910
14331
  apiKey: apiKey,
14911
14332
  baseURL: baseURL,
14333
+ fetch: llm.fetch,
14334
+ headers: llm.config?.headers,
14912
14335
  }).languageModel(llm.model);
14913
14336
  }
14914
14337
  else if (llm.provider == "aws") {
@@ -14918,12 +14341,18 @@ class RetryLanguageModel {
14918
14341
  secretAccessKey: keys[1],
14919
14342
  baseURL: baseURL,
14920
14343
  region: llm.config?.region || "us-west-1",
14344
+ fetch: llm.fetch,
14345
+ headers: llm.config?.headers,
14346
+ sessionToken: llm.config?.sessionToken,
14921
14347
  }).languageModel(llm.model);
14922
14348
  }
14923
14349
  else if (llm.provider == "openrouter") {
14924
14350
  return createOpenRouter({
14925
14351
  apiKey: apiKey,
14926
14352
  baseURL: baseURL,
14353
+ fetch: llm.fetch,
14354
+ headers: llm.config?.headers,
14355
+ compatibility: llm.config?.compatibility,
14927
14356
  }).languageModel(llm.model);
14928
14357
  }
14929
14358
  else {
@@ -14953,6 +14382,12 @@ class RetryLanguageModel {
14953
14382
  },
14954
14383
  });
14955
14384
  }
14385
+ get Llms() {
14386
+ return this.llms;
14387
+ }
14388
+ get Names() {
14389
+ return this.names;
14390
+ }
14956
14391
  }
14957
14392
 
14958
14393
  var domParser = {};
@@ -17400,11 +16835,21 @@ function requireDomParser () {
17400
16835
 
17401
16836
  var domParserExports = requireDomParser();
17402
16837
 
17403
- function parseWorkflow(taskId, xml, done) {
16838
+ function parseWorkflow(taskId, xml, done, thinking) {
16839
+ let _workflow = null;
17404
16840
  try {
16841
+ if (thinking) {
16842
+ _workflow = {
16843
+ taskId: taskId,
16844
+ name: "",
16845
+ thought: thinking,
16846
+ agents: [],
16847
+ xml: xml,
16848
+ };
16849
+ }
17405
16850
  let sIdx = xml.indexOf("<root>");
17406
16851
  if (sIdx == -1) {
17407
- return null;
16852
+ return _workflow;
17408
16853
  }
17409
16854
  xml = xml.substring(sIdx);
17410
16855
  let eIdx = xml.indexOf("</root>");
@@ -17418,13 +16863,14 @@ function parseWorkflow(taskId, xml, done) {
17418
16863
  const doc = parser.parseFromString(xml, "text/xml");
17419
16864
  let root = doc.documentElement;
17420
16865
  if (root.tagName !== "root") {
17421
- return null;
16866
+ return _workflow;
17422
16867
  }
17423
- let agents = [];
16868
+ const agents = [];
16869
+ const thought = root.getElementsByTagName("thought")[0]?.textContent || "";
17424
16870
  const workflow = {
17425
16871
  taskId: taskId,
17426
16872
  name: root.getElementsByTagName("name")[0]?.textContent || "",
17427
- thought: root.getElementsByTagName("thought")[0]?.textContent || "",
16873
+ thought: thinking ? thinking + "\n" + thought : thought,
17428
16874
  agents: agents,
17429
16875
  xml: xml,
17430
16876
  };
@@ -17457,7 +16903,7 @@ function parseWorkflow(taskId, xml, done) {
17457
16903
  throw e;
17458
16904
  }
17459
16905
  else {
17460
- return null;
16906
+ return _workflow;
17461
16907
  }
17462
16908
  }
17463
16909
  }
@@ -17534,7 +16980,8 @@ function buildAgentRootXml(agentXml, mainTaskPrompt, nodeCallback) {
17534
16980
  agentInnerHTML = agentInnerHTML
17535
16981
  .replace("<task>", "<currentTask>")
17536
16982
  .replace("</task>", "</currentTask>");
17537
- return `<root>${prefix}<mainTask>${mainTaskPrompt}</mainTask>${agentInnerHTML}</root>`;
16983
+ const xmlPrompt = `<root>${prefix}<mainTask>${mainTaskPrompt}</mainTask>${agentInnerHTML}</root>`;
16984
+ return xmlPrompt.replace(/ /g, " ").replace(" </root>", "</root>");
17538
16985
  }
17539
16986
  function extractAgentXmlNode(agentXml, nodeId) {
17540
16987
  const parser = new domParserExports.DOMParser();
@@ -18433,9 +17880,8 @@ class McpTool {
18433
17880
 
18434
17881
  const AGENT_SYSTEM_TEMPLATE = `
18435
17882
  You are {name}, an autonomous AI agent for {agent} agent.
18436
- Current datetime: {datetime}
18437
17883
 
18438
- # Task Description
17884
+ # Agent Description
18439
17885
  {description}
18440
17886
  {prompt}
18441
17887
 
@@ -18519,25 +17965,23 @@ function getAgentSystemPrompt(agent, agentNode, context, tools, extSysPrompt) {
18519
17965
  if (extSysPrompt && extSysPrompt.trim()) {
18520
17966
  prompt += "\n" + extSysPrompt.trim() + "\n";
18521
17967
  }
17968
+ prompt += "\nCurrent datetime: {datetime}";
18522
17969
  if (context.chain.agents.length > 1) {
18523
17970
  prompt += "\n Main task: " + context.chain.taskPrompt;
18524
17971
  prompt += "\n\n# Pre-task execution results";
18525
17972
  for (let i = 0; i < context.chain.agents.length; i++) {
18526
17973
  let agentChain = context.chain.agents[i];
18527
17974
  if (agentChain.agentResult) {
18528
- prompt += `\n## ${agentChain.agent.task || agentChain.agent.name}\n${sub(agentChain.agentResult, 500)}`;
17975
+ prompt += `\n## ${agentChain.agent.task || agentChain.agent.name}\n${sub(agentChain.agentResult, 500, true)}`;
18529
17976
  }
18530
17977
  }
18531
17978
  }
18532
- if (prompt) {
18533
- prompt = "\n" + prompt.trim();
18534
- }
18535
17979
  return AGENT_SYSTEM_TEMPLATE.replace("{name}", config.name)
18536
17980
  .replace("{agent}", agent.Name)
18537
17981
  .replace("{description}", agent.Description)
18538
- .replace("{datetime}", new Date().toLocaleString())
18539
- .replace("{prompt}", prompt)
17982
+ .replace("{prompt}", "\n" + prompt.trim())
18540
17983
  .replace("{nodePrompt}", nodePrompt)
17984
+ .replace("{datetime}", new Date().toLocaleString())
18541
17985
  .trim();
18542
17986
  }
18543
17987
  function getAgentUserPrompt(agent, agentNode, context, tools) {
@@ -18564,6 +18008,7 @@ class Agent {
18564
18008
  let mcpClient = this.mcpClient || context.config.defaultMcpClient;
18565
18009
  let agentContext = new AgentContext(context, this, agentChain);
18566
18010
  try {
18011
+ this.agentContext = agentContext;
18567
18012
  mcpClient && !mcpClient.isConnected() && (await mcpClient.connect());
18568
18013
  return this.runWithContext(agentContext, mcpClient, config.maxReactNum);
18569
18014
  }
@@ -18893,6 +18338,11 @@ class Agent {
18893
18338
  addTool(tool) {
18894
18339
  this.tools.push(tool);
18895
18340
  }
18341
+ async onTaskStatus(status, reason) {
18342
+ if (status == "abort" && this.agentContext) {
18343
+ this.agentContext?.variables.clear();
18344
+ }
18345
+ }
18896
18346
  get Llms() {
18897
18347
  return this.llms;
18898
18348
  }
@@ -18939,6 +18389,7 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
18939
18389
  let toolParts = [];
18940
18390
  const reader = result.stream.getReader();
18941
18391
  try {
18392
+ let toolPart = null;
18942
18393
  while (true) {
18943
18394
  await context.checkAborted();
18944
18395
  const { done, value } = await reader.read();
@@ -18948,6 +18399,9 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
18948
18399
  let chunk = value;
18949
18400
  switch (chunk.type) {
18950
18401
  case "text-delta": {
18402
+ if (toolPart && !chunk.textDelta) {
18403
+ continue;
18404
+ }
18951
18405
  streamText += chunk.textDelta || "";
18952
18406
  await streamCallback.onMessage({
18953
18407
  taskId: context.taskId,
@@ -18958,6 +18412,18 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
18958
18412
  streamDone: false,
18959
18413
  text: streamText,
18960
18414
  }, agentContext);
18415
+ if (toolPart) {
18416
+ await streamCallback.onMessage({
18417
+ taskId: context.taskId,
18418
+ agentName: agentNode.name,
18419
+ nodeId: agentNode.id,
18420
+ type: "tool_use",
18421
+ toolId: toolPart.toolCallId,
18422
+ toolName: toolPart.toolName,
18423
+ params: toolPart.args || {},
18424
+ }, agentContext);
18425
+ toolPart = null;
18426
+ }
18961
18427
  break;
18962
18428
  }
18963
18429
  case "reasoning": {
@@ -18996,6 +18462,15 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
18996
18462
  toolName: chunk.toolName,
18997
18463
  paramsText: toolArgsText,
18998
18464
  }, agentContext);
18465
+ if (toolPart == null) {
18466
+ toolPart = {
18467
+ type: "tool-call",
18468
+ toolCallId: chunk.toolCallId,
18469
+ toolName: chunk.toolName,
18470
+ args: {},
18471
+ };
18472
+ toolParts.push(toolPart);
18473
+ }
18999
18474
  break;
19000
18475
  }
19001
18476
  case "tool-call": {
@@ -19011,12 +18486,18 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
19011
18486
  params: args,
19012
18487
  };
19013
18488
  await streamCallback.onMessage(message, agentContext);
19014
- toolParts.push({
19015
- type: "tool-call",
19016
- toolCallId: chunk.toolCallId,
19017
- toolName: chunk.toolName,
19018
- args: message.params || args,
19019
- });
18489
+ if (toolPart == null) {
18490
+ toolParts.push({
18491
+ type: "tool-call",
18492
+ toolCallId: chunk.toolCallId,
18493
+ toolName: chunk.toolName,
18494
+ args: message.params || args,
18495
+ });
18496
+ }
18497
+ else {
18498
+ toolPart.args = message.params || args;
18499
+ toolPart = null;
18500
+ }
19020
18501
  break;
19021
18502
  }
19022
18503
  case "file": {
@@ -19039,7 +18520,7 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
19039
18520
  type: "error",
19040
18521
  error: chunk.error,
19041
18522
  }, agentContext);
19042
- throw new Error("Plan Error");
18523
+ throw new Error("LLM Error: " + chunk.error);
19043
18524
  }
19044
18525
  case "finish": {
19045
18526
  if (!textStreamDone) {
@@ -19054,6 +18535,18 @@ async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoic
19054
18535
  text: streamText,
19055
18536
  }, agentContext);
19056
18537
  }
18538
+ if (toolPart) {
18539
+ await streamCallback.onMessage({
18540
+ taskId: context.taskId,
18541
+ agentName: agentNode.name,
18542
+ nodeId: agentNode.id,
18543
+ type: "tool_use",
18544
+ toolId: toolPart.toolCallId,
18545
+ toolName: toolPart.toolName,
18546
+ params: toolPart.args || {},
18547
+ }, agentContext);
18548
+ toolPart = null;
18549
+ }
19057
18550
  await streamCallback.onMessage({
19058
18551
  taskId: context.taskId,
19059
18552
  agentName: agentNode.name,
@@ -19102,7 +18595,6 @@ class BaseChatAgent extends Agent {
19102
18595
 
19103
18596
  const PLAN_SYSTEM_TEMPLATE = `
19104
18597
  You are {name}, an autonomous AI Agent Planner.
19105
- Current datetime: {datetime}
19106
18598
 
19107
18599
  ## Task Description
19108
18600
  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:
@@ -19119,7 +18611,9 @@ Your task is to understand the user's requirements, dynamically plan the user's
19119
18611
 
19120
18612
  ## Output Rules and Format
19121
18613
  <root>
18614
+ <!-- Task Name (Short) -->
19122
18615
  <name>Task Name</name>
18616
+ <!-- Need to break down the task into multi-agent collaboration. Please think step by step and output a detailed thought process. -->
19123
18617
  <thought>Your thought process on user demand planning</thought>
19124
18618
  <!-- Multiple Agents work together to complete the task -->
19125
18619
  <agents>
@@ -19182,15 +18676,12 @@ Output result:
19182
18676
  </agent>
19183
18677
  </agents>
19184
18678
  </root>`,
19185
- `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.
18679
+ `User: Help me collect the latest AI news, summarize it, and send it to the "AI news information" group chat on WeChat.
19186
18680
  Output result:
19187
18681
  <root>
19188
- <name>AI Daily Morning Report</name>
19189
- <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>
18682
+ <name>Latest AI News</name>
18683
+ <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>
19190
18684
  <agents>
19191
- <agent name="Timer">
19192
- <task>Timing: every morning</task>
19193
- </agent>
19194
18685
  <agent name="Browser">
19195
18686
  <task>Search for the latest updates on AI</task>
19196
18687
  <nodes>
@@ -19203,10 +18694,10 @@ Output result:
19203
18694
  </nodes>
19204
18695
  </agent>
19205
18696
  <agent name="Computer">
19206
- <task>Send a message to the WeChat group chat "AI Daily Morning Report"</task>
18697
+ <task>Send a message to the WeChat group chat "AI news information"</task>
19207
18698
  <nodes>
19208
18699
  <node>Open WeChat</node>
19209
- <node>Search for the "AI Daily Morning Report" chat group</node>
18700
+ <node>Search for the "AI news information" chat group</node>
19210
18701
  <node input="summaryInfo">Send summary message</node>
19211
18702
  </nodes>
19212
18703
  </agent>
@@ -19259,11 +18750,13 @@ Output result:
19259
18750
  ];
19260
18751
  const PLAN_USER_TEMPLATE = `
19261
18752
  User Platform: {platform}
18753
+ Current datetime: {datetime}
19262
18754
  Task Description: {task_prompt}
19263
18755
  `;
19264
18756
  const PLAN_USER_TASK_WEBSITE_TEMPLATE = `
19265
18757
  User Platform: {platform}
19266
18758
  Task Website: {task_website}
18759
+ Current datetime: {datetime}
19267
18760
  Task Description: {task_prompt}
19268
18761
  `;
19269
18762
  async function getPlanSystemPrompt(context) {
@@ -19282,32 +18775,33 @@ async function getPlanSystemPrompt(context) {
19282
18775
  .join("\n") +
19283
18776
  "\n</agent>\n\n";
19284
18777
  }
19285
- let example_prompt = "";
18778
+ let plan_example_list = context.variables.get("plan_example_list") || PLAN_EXAMPLE_LIST;
19286
18779
  let hasChatAgent = context.agents.filter((a) => a.Name == AGENT_NAME$5).length > 0;
18780
+ let example_prompt = "";
19287
18781
  const example_list = hasChatAgent
19288
- ? [PLAN_CHAT_EXAMPLE, ...PLAN_EXAMPLE_LIST]
19289
- : [...PLAN_EXAMPLE_LIST];
18782
+ ? [PLAN_CHAT_EXAMPLE, ...plan_example_list]
18783
+ : [...plan_example_list];
19290
18784
  for (let i = 0; i < example_list.length; i++) {
19291
18785
  example_prompt += `## Example ${i + 1}\n${example_list[i]}\n\n`;
19292
18786
  }
19293
18787
  return PLAN_SYSTEM_TEMPLATE.replace("{name}", config.name)
19294
18788
  .replace("{agents}", agents_prompt.trim())
19295
- .replace("{datetime}", new Date().toLocaleString())
19296
18789
  .replace("{example_prompt}", example_prompt)
19297
18790
  .trim();
19298
18791
  }
19299
18792
  function getPlanUserPrompt(task_prompt, task_website, ext_prompt) {
19300
18793
  let prompt = "";
19301
18794
  if (task_website) {
19302
- prompt = PLAN_USER_TASK_WEBSITE_TEMPLATE.replace("{task_prompt}", task_prompt)
19303
- .replace("{platform}", config.platform)
19304
- .replace("{task_website}", task_website);
18795
+ prompt = PLAN_USER_TASK_WEBSITE_TEMPLATE.replace("{task_website}", task_website);
19305
18796
  }
19306
18797
  else {
19307
- prompt = PLAN_USER_TEMPLATE.replace("{task_prompt}", task_prompt)
19308
- .replace("{platform}", config.platform);
18798
+ prompt = PLAN_USER_TEMPLATE;
19309
18799
  }
19310
- prompt = prompt.trim();
18800
+ prompt = prompt
18801
+ .replace("{task_prompt}", task_prompt)
18802
+ .replace("{platform}", config.platform)
18803
+ .replace("{datetime}", new Date().toLocaleString())
18804
+ .trim();
19311
18805
  if (ext_prompt) {
19312
18806
  prompt += `\n${ext_prompt.trim()}`;
19313
18807
  }
@@ -19347,7 +18841,8 @@ class Planner {
19347
18841
  messages = [
19348
18842
  {
19349
18843
  role: "system",
19350
- content: await getPlanSystemPrompt(this.context),
18844
+ content: this.context.variables.get("plan_sys_prompt") ||
18845
+ (await getPlanSystemPrompt(this.context)),
19351
18846
  },
19352
18847
  {
19353
18848
  role: "user",
@@ -19369,6 +18864,7 @@ class Planner {
19369
18864
  let result = await rlm.callStream(request);
19370
18865
  const reader = result.stream.getReader();
19371
18866
  let streamText = "";
18867
+ let thinkingText = "";
19372
18868
  try {
19373
18869
  while (true) {
19374
18870
  await this.context.checkAborted();
@@ -19378,14 +18874,17 @@ class Planner {
19378
18874
  }
19379
18875
  let chunk = value;
19380
18876
  if (chunk.type == "error") {
19381
- Log.error("Plan Error: ", chunk);
19382
- throw new Error("Plan Error");
18877
+ Log.error("Plan, LLM Error: ", chunk);
18878
+ throw new Error("LLM Error: " + chunk.error);
18879
+ }
18880
+ if (chunk.type == "reasoning") {
18881
+ thinkingText += chunk.textDelta || "";
19383
18882
  }
19384
18883
  if (chunk.type == "text-delta") {
19385
18884
  streamText += chunk.textDelta || "";
19386
18885
  }
19387
18886
  if (config.callback) {
19388
- let workflow = parseWorkflow(this.taskId, streamText, false);
18887
+ let workflow = parseWorkflow(this.taskId, streamText, false, thinkingText);
19389
18888
  if (workflow) {
19390
18889
  await config.callback.onMessage({
19391
18890
  taskId: this.taskId,
@@ -19404,7 +18903,7 @@ class Planner {
19404
18903
  }
19405
18904
  chain.planRequest = request;
19406
18905
  chain.planResult = streamText;
19407
- let workflow = parseWorkflow(this.taskId, streamText, true);
18906
+ let workflow = parseWorkflow(this.taskId, streamText, true, thinkingText);
19408
18907
  if (config.callback) {
19409
18908
  await config.callback.onMessage({
19410
18909
  taskId: this.taskId,
@@ -19544,22 +19043,28 @@ class Eko {
19544
19043
  }
19545
19044
  deleteTask(taskId) {
19546
19045
  this.abortTask(taskId);
19046
+ const context = this.taskMap.get(taskId);
19047
+ if (context) {
19048
+ context.variables.clear();
19049
+ }
19547
19050
  return this.taskMap.delete(taskId);
19548
19051
  }
19549
- abortTask(taskId) {
19052
+ abortTask(taskId, reason) {
19550
19053
  let context = this.taskMap.get(taskId);
19551
19054
  if (context) {
19552
19055
  context.paused = false;
19553
- context.controller.abort();
19056
+ this.onTaskStatus(context, "abort", reason);
19057
+ context.controller.abort(reason);
19554
19058
  return true;
19555
19059
  }
19556
19060
  else {
19557
19061
  return false;
19558
19062
  }
19559
19063
  }
19560
- pauseTask(taskId, paused) {
19064
+ pauseTask(taskId, paused, reason) {
19561
19065
  let context = this.taskMap.get(taskId);
19562
19066
  if (context) {
19067
+ this.onTaskStatus(context, paused ? "pause" : "resume-pause", reason);
19563
19068
  context.paused = paused;
19564
19069
  return true;
19565
19070
  }
@@ -19578,6 +19083,15 @@ class Eko {
19578
19083
  this.config.agents = this.config.agents || [];
19579
19084
  this.config.agents.push(agent);
19580
19085
  }
19086
+ async onTaskStatus(context, status, reason) {
19087
+ const [agent] = context.currentAgent() || [];
19088
+ if (agent) {
19089
+ const onTaskStatus = agent["onTaskStatus"];
19090
+ if (onTaskStatus) {
19091
+ await onTaskStatus.call(agent, status, reason);
19092
+ }
19093
+ }
19094
+ }
19581
19095
  }
19582
19096
 
19583
19097
  class SimpleSseMcpClient {
@@ -20372,6 +19886,120 @@ This is a computer GUI interface, observe the execution through screenshots, and
20372
19886
  }
20373
19887
  }
20374
19888
 
19889
+ function extract_page_content(max_url_length = 200) {
19890
+ let result = "";
19891
+ max_url_length = max_url_length || 200;
19892
+ try {
19893
+ function traverse(node) {
19894
+ if (node.nodeType === Node.ELEMENT_NODE) {
19895
+ const tagName = node.tagName.toLowerCase();
19896
+ if (["script", "style", "noscript"].includes(tagName)) {
19897
+ return;
19898
+ }
19899
+ const style = window.getComputedStyle(node);
19900
+ if (style.display == "none" ||
19901
+ style.visibility == "hidden" ||
19902
+ style.opacity == "0") {
19903
+ return;
19904
+ }
19905
+ }
19906
+ if (node.nodeType === Node.TEXT_NODE) {
19907
+ // text
19908
+ const text = node.textContent.trim();
19909
+ if (text) {
19910
+ result += text + " ";
19911
+ }
19912
+ }
19913
+ else if (node.nodeType === Node.ELEMENT_NODE) {
19914
+ const tagName = node.tagName.toLowerCase();
19915
+ if (["input", "select", "textarea"].includes(tagName)) {
19916
+ // input / select / textarea
19917
+ if (tagName == "input" && node.type == "checkbox") {
19918
+ result += node.checked + " ";
19919
+ }
19920
+ else if (tagName == "input" && node.type == "radio") {
19921
+ if (node.checked && node.value) {
19922
+ result += node.value + " ";
19923
+ }
19924
+ }
19925
+ else if (node.value) {
19926
+ result += node.value + " ";
19927
+ }
19928
+ }
19929
+ else if (tagName === "img") {
19930
+ // image
19931
+ const src = node.src ||
19932
+ node.getAttribute("src") ||
19933
+ node.getAttribute("data-src");
19934
+ const alt = node.alt || node.title || "";
19935
+ if (src &&
19936
+ src.length <= max_url_length &&
19937
+ node.width * node.height >= 10000 &&
19938
+ src.startsWith("http")) {
19939
+ result += `![${alt ? alt : "image"}](${src.trim()}) `;
19940
+ }
19941
+ }
19942
+ else if (tagName === "a" && node.children.length == 0) {
19943
+ // link
19944
+ const href = node.href || node.getAttribute("href");
19945
+ const text = node.innerText.trim() || node.title;
19946
+ if (text &&
19947
+ href &&
19948
+ href.length <= max_url_length &&
19949
+ href.startsWith("http")) {
19950
+ result += `[${text}](${href.trim()}) `;
19951
+ }
19952
+ else {
19953
+ result += text + " ";
19954
+ }
19955
+ }
19956
+ else if (tagName === "video" || tagName == "audio") {
19957
+ // video / audio
19958
+ let src = node.src || node.getAttribute("src");
19959
+ const sources = node.querySelectorAll("source");
19960
+ if (sources.length > 0 && sources[0].src) {
19961
+ src = sources[0].src;
19962
+ if (src && src.startsWith("http") && sources[0].type) {
19963
+ result += sources[0].type + " ";
19964
+ }
19965
+ }
19966
+ if (src && src.startsWith("http")) {
19967
+ result += src.trim() + " ";
19968
+ }
19969
+ }
19970
+ else if (tagName === "br") {
19971
+ // br
19972
+ result += "\n";
19973
+ }
19974
+ else if (["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"].includes(tagName)) {
19975
+ // block
19976
+ result += "\n";
19977
+ for (let child of node.childNodes) {
19978
+ traverse(child);
19979
+ }
19980
+ result += "\n";
19981
+ return;
19982
+ }
19983
+ else if (tagName === "hr") {
19984
+ // hr
19985
+ result += "\n--------\n";
19986
+ }
19987
+ else {
19988
+ // recursive
19989
+ for (let child of node.childNodes) {
19990
+ traverse(child);
19991
+ }
19992
+ }
19993
+ }
19994
+ }
19995
+ traverse(document.body);
19996
+ }
19997
+ catch (e) {
19998
+ result = document.body.innerText;
19999
+ }
20000
+ return result.replace(/\s*\n/g, "\n").replace(/\n+/g, "\n").trim();
20001
+ }
20002
+
20375
20003
  const AGENT_NAME = "Browser";
20376
20004
  class BaseBrowserAgent extends Agent {
20377
20005
  async go_back(agentContext) {
@@ -20384,22 +20012,17 @@ class BaseBrowserAgent extends Agent {
20384
20012
  catch (e) { }
20385
20013
  }
20386
20014
  async extract_page_content(agentContext, variable_name) {
20387
- let content = await this.execute_script(agentContext, () => {
20388
- let str = window.document.body.innerText
20389
- .replaceAll(/\n+/g, "\n")
20390
- .replaceAll(/ +/g, " ")
20391
- .trim();
20392
- if (str.length > 20000) {
20393
- str = str.substring(0, 20000) + "...";
20394
- }
20395
- return str;
20396
- }, []);
20015
+ let content = await this.execute_script(agentContext, extract_page_content, []);
20397
20016
  let pageInfo = await this.get_current_page(agentContext);
20398
20017
  let result = `title: ${pageInfo.title}\npage_url: ${pageInfo.url}\npage_content: \n${content}`;
20399
20018
  if (variable_name) {
20400
20019
  agentContext.context.variables.set(variable_name, result);
20401
20020
  }
20402
- return result;
20021
+ return {
20022
+ title: pageInfo.title || "",
20023
+ page_url: pageInfo.url,
20024
+ page_content: content,
20025
+ };
20403
20026
  }
20404
20027
  async controlMcpTools(agentContext, messages, loopNum) {
20405
20028
  if (loopNum > 0) {
@@ -21150,7 +20773,9 @@ class BaseBrowserLabelsAgent extends BaseBrowserAgent {
21150
20773
  - If stuck, try alternative approaches, don't refuse tasks
21151
20774
  - Handle popups/cookies by accepting or closing them
21152
20775
  * BROWSER OPERATION:
21153
- - 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`;
20776
+ - 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
20777
+ * During execution, please output user-friendly step information. Do not output element and index information to users, as this would cause user confusion.
20778
+ `;
21154
20779
  const _tools_ = [];
21155
20780
  super({
21156
20781
  name: AGENT_NAME,
@@ -21201,9 +20826,18 @@ class BaseBrowserLabelsAgent extends BaseBrowserAgent {
21201
20826
  }
21202
20827
  }
21203
20828
  if (extract_page_content) {
21204
- let page_content = await this.extract_page_content(agentContext);
21205
- return ("The current page content has been extracted, latest page content:\n" +
21206
- page_content);
20829
+ let page_result = await this.extract_page_content(agentContext);
20830
+ return {
20831
+ result: "The current page content has been extracted, latest page content:\n" +
20832
+ "title: " +
20833
+ page_result.title +
20834
+ "\n" +
20835
+ "page_url: " +
20836
+ page_result.page_url +
20837
+ "\n" +
20838
+ "page_content: " +
20839
+ page_result.page_content,
20840
+ };
21207
20841
  }
21208
20842
  }
21209
20843
  async hover_to_element(agentContext, index) {
@@ -21422,7 +21056,7 @@ class BaseBrowserLabelsAgent extends BaseBrowserAgent {
21422
21056
  },
21423
21057
  {
21424
21058
  name: "extract_page_content",
21425
- description: "Extract the text content of the current webpage, please use this tool to obtain webpage data.",
21059
+ description: "Extract the text content and image links of the current webpage, please use this tool to obtain webpage data.",
21426
21060
  parameters: {
21427
21061
  type: "object",
21428
21062
  properties: {},
@@ -21605,9 +21239,7 @@ class BaseBrowserLabelsAgent extends BaseBrowserAgent {
21605
21239
  if (eIdx == -1) {
21606
21240
  continue;
21607
21241
  }
21608
- line =
21609
- line.substring(0, sIdx) +
21610
- line.substring(eIdx + 1).trim();
21242
+ line = line.substring(0, sIdx) + line.substring(eIdx + 1).trim();
21611
21243
  }
21612
21244
  return line.replace('" >', '">').replace(" >", ">");
21613
21245
  })
@@ -21814,6 +21446,19 @@ function scroll_by(params) {
21814
21446
  const visibleHeight = visibleBottom - visibleTop;
21815
21447
  return visibleWidth * visibleHeight;
21816
21448
  }
21449
+ function getComputedZIndex(element) {
21450
+ while (element &&
21451
+ element !== document.body &&
21452
+ element !== document.body.parentElement) {
21453
+ const style = window.getComputedStyle(element);
21454
+ let zIndex = style.zIndex === "auto" ? 0 : parseInt(style.zIndex) || 0;
21455
+ if (zIndex > 0) {
21456
+ return zIndex;
21457
+ }
21458
+ element = element.parentElement;
21459
+ }
21460
+ return 0;
21461
+ }
21817
21462
  const scrollableElements = findScrollableElements();
21818
21463
  if (scrollableElements.length === 0) {
21819
21464
  const y = Math.max(20, Math.min((window.innerHeight || documentElement.clientHeight) / 10, 200));
@@ -21821,7 +21466,21 @@ function scroll_by(params) {
21821
21466
  return false;
21822
21467
  }
21823
21468
  const sortedElements = scrollableElements.sort((a, b) => {
21824
- return getVisibleArea(b) - getVisibleArea(a);
21469
+ let z = getComputedZIndex(b) - getComputedZIndex(a);
21470
+ if (z > 0) {
21471
+ return 1;
21472
+ }
21473
+ else if (z < 0) {
21474
+ return -1;
21475
+ }
21476
+ let v = getVisibleArea(b) - getVisibleArea(a);
21477
+ if (v > 0) {
21478
+ return 1;
21479
+ }
21480
+ else if (v < 0) {
21481
+ return -1;
21482
+ }
21483
+ return 0;
21825
21484
  });
21826
21485
  const largestElement = sortedElements[0];
21827
21486
  const viewportHeight = largestElement.clientHeight;
@@ -22004,7 +21663,7 @@ class BaseBrowserScreenAgent extends BaseBrowserAgent {
22004
21663
  },
22005
21664
  {
22006
21665
  name: "extract_page_content",
22007
- description: "Extract the text content of the current webpage, please use this tool to obtain webpage data.",
21666
+ description: "Extract the text content and image links of the current webpage, please use this tool to obtain webpage data.",
22008
21667
  parameters: {
22009
21668
  type: "object",
22010
21669
  properties: {},
@@ -22165,6 +21824,7 @@ exports.call_timeout = call_timeout;
22165
21824
  exports.config = config;
22166
21825
  exports.convertToolSchema = convertToolSchema;
22167
21826
  exports.default = Eko;
21827
+ exports.extract_page_content = extract_page_content;
22168
21828
  exports.mergeTools = mergeTools;
22169
21829
  exports.toImage = toImage;
22170
21830
  exports.uuidv4 = uuidv4;