ai 4.1.61 → 4.1.63

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.mjs CHANGED
@@ -1,11 +1,4 @@
1
1
  var __defProp = Object.defineProperty;
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
- }) : x)(function(x) {
5
- if (typeof require !== "undefined")
6
- return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
2
  var __export = (target, all) => {
10
3
  for (var name17 in all)
11
4
  __defProp(target, name17, { get: all[name17], enumerable: true });
@@ -809,12 +802,6 @@ var DefaultEmbedManyResult = class {
809
802
  }
810
803
  };
811
804
 
812
- // core/generate-image/generate-image.ts
813
- import {
814
- convertBase64ToUint8Array,
815
- convertUint8ArrayToBase64
816
- } from "@ai-sdk/provider-utils";
817
-
818
805
  // errors/no-image-generated-error.ts
819
806
  import { AISDKError as AISDKError3 } from "@ai-sdk/provider";
820
807
  var name3 = "AI_NoImageGeneratedError";
@@ -837,6 +824,126 @@ var NoImageGeneratedError = class extends AISDKError3 {
837
824
  };
838
825
  _a3 = symbol3;
839
826
 
827
+ // core/generate-text/generated-file.ts
828
+ import {
829
+ convertBase64ToUint8Array,
830
+ convertUint8ArrayToBase64
831
+ } from "@ai-sdk/provider-utils";
832
+ var DefaultGeneratedFile = class {
833
+ constructor({
834
+ data,
835
+ mimeType
836
+ }) {
837
+ const isUint8Array = data instanceof Uint8Array;
838
+ this.base64Data = isUint8Array ? void 0 : data;
839
+ this.uint8ArrayData = isUint8Array ? data : void 0;
840
+ this.mimeType = mimeType;
841
+ }
842
+ // lazy conversion with caching to avoid unnecessary conversion overhead:
843
+ get base64() {
844
+ if (this.base64Data == null) {
845
+ this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);
846
+ }
847
+ return this.base64Data;
848
+ }
849
+ // lazy conversion with caching to avoid unnecessary conversion overhead:
850
+ get uint8Array() {
851
+ if (this.uint8ArrayData == null) {
852
+ this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);
853
+ }
854
+ return this.uint8ArrayData;
855
+ }
856
+ };
857
+ var DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {
858
+ constructor(options) {
859
+ super(options);
860
+ this.type = "file";
861
+ }
862
+ };
863
+
864
+ // core/util/detect-image-mimetype.ts
865
+ var mimeTypeSignatures = [
866
+ {
867
+ mimeType: "image/gif",
868
+ bytesPrefix: [71, 73, 70],
869
+ base64Prefix: "R0lG"
870
+ },
871
+ {
872
+ mimeType: "image/png",
873
+ bytesPrefix: [137, 80, 78, 71],
874
+ base64Prefix: "iVBORw"
875
+ },
876
+ {
877
+ mimeType: "image/jpeg",
878
+ bytesPrefix: [255, 216],
879
+ base64Prefix: "/9j/"
880
+ },
881
+ {
882
+ mimeType: "image/webp",
883
+ bytesPrefix: [82, 73, 70, 70],
884
+ base64Prefix: "UklGRg"
885
+ },
886
+ {
887
+ mimeType: "image/bmp",
888
+ bytesPrefix: [66, 77],
889
+ base64Prefix: "Qk"
890
+ },
891
+ {
892
+ mimeType: "image/tiff",
893
+ bytesPrefix: [73, 73, 42, 0],
894
+ base64Prefix: "SUkqAA"
895
+ },
896
+ {
897
+ mimeType: "image/tiff",
898
+ bytesPrefix: [77, 77, 0, 42],
899
+ base64Prefix: "TU0AKg"
900
+ },
901
+ {
902
+ mimeType: "image/avif",
903
+ bytesPrefix: [
904
+ 0,
905
+ 0,
906
+ 0,
907
+ 32,
908
+ 102,
909
+ 116,
910
+ 121,
911
+ 112,
912
+ 97,
913
+ 118,
914
+ 105,
915
+ 102
916
+ ],
917
+ base64Prefix: "AAAAIGZ0eXBhdmlm"
918
+ },
919
+ {
920
+ mimeType: "image/heic",
921
+ bytesPrefix: [
922
+ 0,
923
+ 0,
924
+ 0,
925
+ 32,
926
+ 102,
927
+ 116,
928
+ 121,
929
+ 112,
930
+ 104,
931
+ 101,
932
+ 105,
933
+ 99
934
+ ],
935
+ base64Prefix: "AAAAIGZ0eXBoZWlj"
936
+ }
937
+ ];
938
+ function detectImageMimeType(image) {
939
+ for (const signature of mimeTypeSignatures) {
940
+ if (typeof image === "string" ? image.startsWith(signature.base64Prefix) : image.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => image[index] === byte)) {
941
+ return signature.mimeType;
942
+ }
943
+ }
944
+ return void 0;
945
+ }
946
+
840
947
  // core/generate-image/generate-image.ts
841
948
  async function generateImage({
842
949
  model,
@@ -848,10 +955,7 @@ async function generateImage({
848
955
  providerOptions,
849
956
  maxRetries: maxRetriesArg,
850
957
  abortSignal,
851
- headers,
852
- _internal = {
853
- currentDate: () => /* @__PURE__ */ new Date()
854
- }
958
+ headers
855
959
  }) {
856
960
  var _a17;
857
961
  const { retry } = prepareRetries({ maxRetries: maxRetriesArg });
@@ -885,7 +989,15 @@ async function generateImage({
885
989
  const responses = [];
886
990
  for (const result of results) {
887
991
  images.push(
888
- ...result.images.map((image) => new DefaultGeneratedImage({ image }))
992
+ ...result.images.map(
993
+ (image) => {
994
+ var _a18;
995
+ return new DefaultGeneratedFile({
996
+ data: image,
997
+ mimeType: (_a18 = detectImageMimeType(image)) != null ? _a18 : "image/png"
998
+ });
999
+ }
1000
+ )
889
1001
  );
890
1002
  warnings.push(...result.warnings);
891
1003
  responses.push(result.response);
@@ -905,27 +1017,6 @@ var DefaultGenerateImageResult = class {
905
1017
  return this.images[0];
906
1018
  }
907
1019
  };
908
- var DefaultGeneratedImage = class {
909
- constructor({ image }) {
910
- const isUint8Array = image instanceof Uint8Array;
911
- this.base64Data = isUint8Array ? void 0 : image;
912
- this.uint8ArrayData = isUint8Array ? image : void 0;
913
- }
914
- // lazy conversion with caching to avoid unnecessary conversion overhead:
915
- get base64() {
916
- if (this.base64Data == null) {
917
- this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);
918
- }
919
- return this.base64Data;
920
- }
921
- // lazy conversion with caching to avoid unnecessary conversion overhead:
922
- get uint8Array() {
923
- if (this.uint8ArrayData == null) {
924
- this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);
925
- }
926
- return this.uint8ArrayData;
927
- }
928
- };
929
1020
 
930
1021
  // core/generate-object/generate-object.ts
931
1022
  import {
@@ -1014,22 +1105,6 @@ async function download({
1014
1105
  }
1015
1106
  }
1016
1107
 
1017
- // core/util/detect-image-mimetype.ts
1018
- var mimeTypeSignatures = [
1019
- { mimeType: "image/gif", bytes: [71, 73, 70] },
1020
- { mimeType: "image/png", bytes: [137, 80, 78, 71] },
1021
- { mimeType: "image/jpeg", bytes: [255, 216] },
1022
- { mimeType: "image/webp", bytes: [82, 73, 70, 70] }
1023
- ];
1024
- function detectImageMimeType(image) {
1025
- for (const { bytes, mimeType } of mimeTypeSignatures) {
1026
- if (image.length >= bytes.length && bytes.every((byte, index) => image[index] === byte)) {
1027
- return mimeType;
1028
- }
1029
- }
1030
- return void 0;
1031
- }
1032
-
1033
1108
  // core/prompt/data-content.ts
1034
1109
  import {
1035
1110
  convertBase64ToUint8Array as convertBase64ToUint8Array2,
@@ -1206,11 +1281,50 @@ function convertToLanguageModelMessage(message, downloadedAssets) {
1206
1281
  // remove empty text parts:
1207
1282
  (part) => part.type !== "text" || part.text !== ""
1208
1283
  ).map((part) => {
1209
- const { experimental_providerMetadata, providerOptions, ...rest } = part;
1210
- return {
1211
- ...rest,
1212
- providerMetadata: providerOptions != null ? providerOptions : experimental_providerMetadata
1213
- };
1284
+ var _a18;
1285
+ const providerOptions = (_a18 = part.providerOptions) != null ? _a18 : part.experimental_providerMetadata;
1286
+ switch (part.type) {
1287
+ case "file": {
1288
+ return {
1289
+ type: "file",
1290
+ data: part.data instanceof URL ? part.data : convertDataContentToBase64String(part.data),
1291
+ filename: part.filename,
1292
+ mimeType: part.mimeType,
1293
+ providerMetadata: providerOptions
1294
+ };
1295
+ }
1296
+ case "reasoning": {
1297
+ return {
1298
+ type: "reasoning",
1299
+ text: part.text,
1300
+ signature: part.signature,
1301
+ providerMetadata: providerOptions
1302
+ };
1303
+ }
1304
+ case "redacted-reasoning": {
1305
+ return {
1306
+ type: "redacted-reasoning",
1307
+ data: part.data,
1308
+ providerMetadata: providerOptions
1309
+ };
1310
+ }
1311
+ case "text": {
1312
+ return {
1313
+ type: "text",
1314
+ text: part.text,
1315
+ providerMetadata: providerOptions
1316
+ };
1317
+ }
1318
+ case "tool-call": {
1319
+ return {
1320
+ type: "tool-call",
1321
+ toolCallId: part.toolCallId,
1322
+ toolName: part.toolName,
1323
+ args: part.args,
1324
+ providerMetadata: providerOptions
1325
+ };
1326
+ }
1327
+ }
1214
1328
  }),
1215
1329
  providerMetadata: (_e = message.providerOptions) != null ? _e : message.experimental_providerMetadata
1216
1330
  };
@@ -1570,12 +1684,11 @@ function convertToCoreMessages(messages, options) {
1570
1684
  const content2 = [];
1571
1685
  for (const part of block) {
1572
1686
  switch (part.type) {
1573
- case "text":
1574
- content2.push({
1575
- type: "text",
1576
- text: part.text
1577
- });
1687
+ case "file":
1688
+ case "text": {
1689
+ content2.push(part);
1578
1690
  break;
1691
+ }
1579
1692
  case "reasoning": {
1580
1693
  for (const detail of part.details) {
1581
1694
  switch (detail.type) {
@@ -1656,9 +1769,6 @@ function convertToCoreMessages(messages, options) {
1656
1769
  let block = [];
1657
1770
  for (const part of message.parts) {
1658
1771
  switch (part.type) {
1659
- case "reasoning":
1660
- block.push(part);
1661
- break;
1662
1772
  case "text": {
1663
1773
  if (blockHasToolInvocations) {
1664
1774
  processBlock2();
@@ -1666,6 +1776,11 @@ function convertToCoreMessages(messages, options) {
1666
1776
  block.push(part);
1667
1777
  break;
1668
1778
  }
1779
+ case "file":
1780
+ case "reasoning": {
1781
+ block.push(part);
1782
+ break;
1783
+ }
1669
1784
  case "tool-invocation": {
1670
1785
  if (((_b = part.toolInvocation.step) != null ? _b : 0) !== currentStep) {
1671
1786
  processBlock2();
@@ -1781,6 +1896,7 @@ function detectSingleMessageCharacteristics(message) {
1781
1896
  if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
1782
1897
  message.role === "data" || // UI-only role
1783
1898
  "toolInvocations" in message || // UI-specific field
1899
+ "parts" in message || // UI-specific field
1784
1900
  "experimental_attachments" in message)) {
1785
1901
  return "has-ui-specific-parts";
1786
1902
  } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
@@ -1910,6 +2026,7 @@ var coreAssistantMessageSchema = z6.object({
1910
2026
  z6.array(
1911
2027
  z6.union([
1912
2028
  textPartSchema,
2029
+ filePartSchema,
1913
2030
  reasoningPartSchema,
1914
2031
  redactedReasoningPartSchema,
1915
2032
  toolCallPartSchema
@@ -3819,6 +3936,7 @@ function asReasoningText(reasoning) {
3819
3936
  // core/generate-text/to-response-messages.ts
3820
3937
  function toResponseMessages({
3821
3938
  text: text2 = "",
3939
+ files,
3822
3940
  reasoning,
3823
3941
  tools,
3824
3942
  toolCalls,
@@ -3833,6 +3951,12 @@ function toResponseMessages({
3833
3951
  ...reasoning.map(
3834
3952
  (part) => part.type === "text" ? { ...part, type: "reasoning" } : { ...part, type: "redacted-reasoning" }
3835
3953
  ),
3954
+ // TODO language model v2: switch to order response content (instead of type-based ordering)
3955
+ ...files.map((file) => ({
3956
+ type: "file",
3957
+ data: file.base64,
3958
+ mimeType: file.mimeType
3959
+ })),
3836
3960
  { type: "text", text: text2 },
3837
3961
  ...toolCalls
3838
3962
  ],
@@ -4122,6 +4246,7 @@ async function generateText({
4122
4246
  responseMessages.push(
4123
4247
  ...toResponseMessages({
4124
4248
  text: text2,
4249
+ files: asFiles(currentModelResponse.files),
4125
4250
  reasoning: asReasoningDetails(currentModelResponse.reasoning),
4126
4251
  tools: tools != null ? tools : {},
4127
4252
  toolCalls: currentToolCalls,
@@ -4137,6 +4262,7 @@ async function generateText({
4137
4262
  // TODO v5: rename reasoning to reasoningText (and use reasoning for composite array)
4138
4263
  reasoning: asReasoningText(currentReasoningDetails),
4139
4264
  reasoningDetails: currentReasoningDetails,
4265
+ files: asFiles(currentModelResponse.files),
4140
4266
  sources: (_e = currentModelResponse.sources) != null ? _e : [],
4141
4267
  toolCalls: currentToolCalls,
4142
4268
  toolResults: currentToolResults,
@@ -4178,6 +4304,7 @@ async function generateText({
4178
4304
  );
4179
4305
  return new DefaultGenerateTextResult({
4180
4306
  text: text2,
4307
+ files: asFiles(currentModelResponse.files),
4181
4308
  reasoning: asReasoningText(currentReasoningDetails),
4182
4309
  reasoningDetails: currentReasoningDetails,
4183
4310
  sources,
@@ -4287,6 +4414,7 @@ async function executeTools({
4287
4414
  var DefaultGenerateTextResult = class {
4288
4415
  constructor(options) {
4289
4416
  this.text = options.text;
4417
+ this.files = options.files;
4290
4418
  this.reasoning = options.reasoning;
4291
4419
  this.reasoningDetails = options.reasoningDetails;
4292
4420
  this.toolCalls = options.toolCalls;
@@ -4316,6 +4444,10 @@ function asReasoningDetails(reasoning) {
4316
4444
  }
4317
4445
  return reasoning;
4318
4446
  }
4447
+ function asFiles(files) {
4448
+ var _a17;
4449
+ return (_a17 = files == null ? void 0 : files.map((file) => new DefaultGeneratedFile(file))) != null ? _a17 : [];
4450
+ }
4319
4451
 
4320
4452
  // core/generate-text/output.ts
4321
4453
  var output_exports = {};
@@ -4654,6 +4786,15 @@ function runToolsTransformation({
4654
4786
  controller.enqueue(chunk);
4655
4787
  break;
4656
4788
  }
4789
+ case "file": {
4790
+ controller.enqueue(
4791
+ new DefaultGeneratedFileWithType({
4792
+ data: chunk.data,
4793
+ mimeType: chunk.mimeType
4794
+ })
4795
+ );
4796
+ break;
4797
+ }
4657
4798
  case "tool-call-delta": {
4658
4799
  if (toolCallStreaming) {
4659
4800
  if (!activeToolCalls[chunk.toolCallId]) {
@@ -4961,6 +5102,7 @@ var DefaultStreamTextResult = class {
4961
5102
  this.reasoningPromise = new DelayedPromise();
4962
5103
  this.reasoningDetailsPromise = new DelayedPromise();
4963
5104
  this.sourcesPromise = new DelayedPromise();
5105
+ this.filesPromise = new DelayedPromise();
4964
5106
  this.toolCallsPromise = new DelayedPromise();
4965
5107
  this.toolResultsPromise = new DelayedPromise();
4966
5108
  this.requestPromise = new DelayedPromise();
@@ -4979,6 +5121,7 @@ var DefaultStreamTextResult = class {
4979
5121
  let recordedContinuationText = "";
4980
5122
  let recordedFullText = "";
4981
5123
  let stepReasoning = [];
5124
+ let stepFiles = [];
4982
5125
  let activeReasoningText = void 0;
4983
5126
  let recordedStepSources = [];
4984
5127
  const recordedSources = [];
@@ -5031,6 +5174,9 @@ var DefaultStreamTextResult = class {
5031
5174
  if (part.type === "redacted-reasoning") {
5032
5175
  stepReasoning.push({ type: "redacted", data: part.data });
5033
5176
  }
5177
+ if (part.type === "file") {
5178
+ stepFiles.push(part);
5179
+ }
5034
5180
  if (part.type === "source") {
5035
5181
  recordedSources.push(part.source);
5036
5182
  recordedStepSources.push(part.source);
@@ -5044,6 +5190,7 @@ var DefaultStreamTextResult = class {
5044
5190
  if (part.type === "step-finish") {
5045
5191
  const stepMessages = toResponseMessages({
5046
5192
  text: recordedContinuationText,
5193
+ files: stepFiles,
5047
5194
  reasoning: stepReasoning,
5048
5195
  tools: tools != null ? tools : {},
5049
5196
  toolCalls: recordedToolCalls,
@@ -5070,6 +5217,7 @@ var DefaultStreamTextResult = class {
5070
5217
  text: recordedStepText,
5071
5218
  reasoning: asReasoningText(stepReasoning),
5072
5219
  reasoningDetails: stepReasoning,
5220
+ files: stepFiles,
5073
5221
  sources: recordedStepSources,
5074
5222
  toolCalls: recordedToolCalls,
5075
5223
  toolResults: recordedToolResults,
@@ -5093,6 +5241,7 @@ var DefaultStreamTextResult = class {
5093
5241
  recordedStepText = "";
5094
5242
  recordedStepSources = [];
5095
5243
  stepReasoning = [];
5244
+ stepFiles = [];
5096
5245
  activeReasoningText = void 0;
5097
5246
  if (nextStepType !== "done") {
5098
5247
  stepType = nextStepType;
@@ -5138,6 +5287,7 @@ var DefaultStreamTextResult = class {
5138
5287
  self.usagePromise.resolve(usage);
5139
5288
  self.textPromise.resolve(recordedFullText);
5140
5289
  self.sourcesPromise.resolve(recordedSources);
5290
+ self.filesPromise.resolve(lastStep.files);
5141
5291
  self.stepsPromise.resolve(recordedSteps);
5142
5292
  await (onFinish == null ? void 0 : onFinish({
5143
5293
  finishReason,
@@ -5146,6 +5296,7 @@ var DefaultStreamTextResult = class {
5146
5296
  text: recordedFullText,
5147
5297
  reasoning: lastStep.reasoning,
5148
5298
  reasoningDetails: lastStep.reasoningDetails,
5299
+ files: lastStep.files,
5149
5300
  sources: lastStep.sources,
5150
5301
  toolCalls: lastStep.toolCalls,
5151
5302
  toolResults: lastStep.toolResults,
@@ -5338,6 +5489,7 @@ var DefaultStreamTextResult = class {
5338
5489
  const stepToolCalls = [];
5339
5490
  const stepToolResults = [];
5340
5491
  const stepReasoning2 = [];
5492
+ const stepFiles2 = [];
5341
5493
  let activeReasoningText2 = void 0;
5342
5494
  let stepFinishReason = "unknown";
5343
5495
  let stepUsage = {
@@ -5483,6 +5635,11 @@ var DefaultStreamTextResult = class {
5483
5635
  });
5484
5636
  break;
5485
5637
  }
5638
+ case "file": {
5639
+ stepFiles2.push(chunk);
5640
+ controller.enqueue(chunk);
5641
+ break;
5642
+ }
5486
5643
  case "source":
5487
5644
  case "tool-call-streaming-start":
5488
5645
  case "tool-call-delta": {
@@ -5601,6 +5758,7 @@ var DefaultStreamTextResult = class {
5601
5758
  responseMessages.push(
5602
5759
  ...toResponseMessages({
5603
5760
  text: stepText,
5761
+ files: stepFiles2,
5604
5762
  reasoning: stepReasoning2,
5605
5763
  tools: tools != null ? tools : {},
5606
5764
  toolCalls: stepToolCalls,
@@ -5681,6 +5839,9 @@ var DefaultStreamTextResult = class {
5681
5839
  get sources() {
5682
5840
  return this.sourcesPromise.value;
5683
5841
  }
5842
+ get files() {
5843
+ return this.filesPromise.value;
5844
+ }
5684
5845
  get toolCalls() {
5685
5846
  return this.toolCallsPromise.value;
5686
5847
  }
@@ -5799,6 +5960,15 @@ var DefaultStreamTextResult = class {
5799
5960
  }
5800
5961
  break;
5801
5962
  }
5963
+ case "file": {
5964
+ controller.enqueue(
5965
+ formatDataStreamPart2("file", {
5966
+ mimeType: chunk.mimeType,
5967
+ data: chunk.base64
5968
+ })
5969
+ );
5970
+ break;
5971
+ }
5802
5972
  case "source": {
5803
5973
  if (sendSources) {
5804
5974
  controller.enqueue(
@@ -6314,6 +6484,7 @@ function appendClientMessage({
6314
6484
  import {
6315
6485
  extractMaxToolInvocationStep
6316
6486
  } from "@ai-sdk/ui-utils";
6487
+ import { AISDKError as AISDKError18 } from "@ai-sdk/provider";
6317
6488
  function appendResponseMessages({
6318
6489
  messages,
6319
6490
  responseMessages,
@@ -6394,6 +6565,19 @@ function appendResponseMessages({
6394
6565
  }
6395
6566
  case "tool-call":
6396
6567
  break;
6568
+ case "file":
6569
+ if (part.data instanceof URL) {
6570
+ throw new AISDKError18({
6571
+ name: "InvalidAssistantFileData",
6572
+ message: "File data cannot be a URL"
6573
+ });
6574
+ }
6575
+ parts.push({
6576
+ type: "file",
6577
+ mimeType: part.mimeType,
6578
+ data: convertDataContentToBase64String(part.data)
6579
+ });
6580
+ break;
6397
6581
  }
6398
6582
  }
6399
6583
  }
@@ -6517,7 +6701,7 @@ function customProvider({
6517
6701
  var experimental_customProvider = customProvider;
6518
6702
 
6519
6703
  // core/registry/no-such-provider-error.ts
6520
- import { AISDKError as AISDKError18, NoSuchModelError as NoSuchModelError3 } from "@ai-sdk/provider";
6704
+ import { AISDKError as AISDKError19, NoSuchModelError as NoSuchModelError3 } from "@ai-sdk/provider";
6521
6705
  var name16 = "AI_NoSuchProviderError";
6522
6706
  var marker16 = `vercel.ai.error.${name16}`;
6523
6707
  var symbol16 = Symbol.for(marker16);
@@ -6536,7 +6720,7 @@ var NoSuchProviderError = class extends NoSuchModelError3 {
6536
6720
  this.availableProviders = availableProviders;
6537
6721
  }
6538
6722
  static isInstance(error) {
6539
- return AISDKError18.hasMarker(error, marker16);
6723
+ return AISDKError19.hasMarker(error, marker16);
6540
6724
  }
6541
6725
  };
6542
6726
  _a16 = symbol16;
@@ -6631,79 +6815,11 @@ function tool(tool2) {
6631
6815
  return tool2;
6632
6816
  }
6633
6817
 
6634
- // core/tool/mcp/create-child-process.ts
6635
- async function createChildProcess(config, signal) {
6636
- var _a17, _b, _c;
6637
- const runtime = detectRuntime();
6638
- if (runtime !== "node") {
6639
- throw new MCPClientError({
6640
- message: "Attempted to use child_process module outside of Node.js environment"
6641
- });
6642
- }
6643
- let childProcess;
6644
- const nodePrefix = "node:";
6645
- try {
6646
- childProcess = await import(`${nodePrefix}child_process`);
6647
- } catch (error) {
6648
- try {
6649
- childProcess = __require(`${nodePrefix}child_process`);
6650
- } catch (innerError) {
6651
- throw new MCPClientError({
6652
- message: "Failed to load child_process module dynamically",
6653
- cause: innerError
6654
- });
6655
- }
6656
- }
6657
- const { spawn } = childProcess;
6658
- return spawn(config.command, (_a17 = config.args) != null ? _a17 : [], {
6659
- env: (_b = config.env) != null ? _b : getDefaultEnvironment(),
6660
- stdio: ["pipe", "pipe", (_c = config.stderr) != null ? _c : "inherit"],
6661
- shell: false,
6662
- signal,
6663
- windowsHide: globalThis.process.platform === "win32" && isElectron(),
6664
- cwd: config.cwd
6665
- });
6666
- }
6667
- function detectRuntime() {
6668
- var _a17, _b;
6669
- if (typeof window !== "undefined") {
6670
- return "browser";
6671
- }
6672
- if (((_b = (_a17 = globalThis.process) == null ? void 0 : _a17.release) == null ? void 0 : _b.name) === "node") {
6673
- return "node";
6674
- }
6675
- return null;
6676
- }
6677
- function getDefaultEnvironment() {
6678
- const DEFAULT_INHERITED_ENV_VARS = globalThis.process.platform === "win32" ? [
6679
- "APPDATA",
6680
- "HOMEDRIVE",
6681
- "HOMEPATH",
6682
- "LOCALAPPDATA",
6683
- "PATH",
6684
- "PROCESSOR_ARCHITECTURE",
6685
- "SYSTEMDRIVE",
6686
- "SYSTEMROOT",
6687
- "TEMP",
6688
- "USERNAME",
6689
- "USERPROFILE"
6690
- ] : ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"];
6691
- const env = {};
6692
- for (const key of DEFAULT_INHERITED_ENV_VARS) {
6693
- const value = globalThis.process.env[key];
6694
- if (value === void 0) {
6695
- continue;
6696
- }
6697
- if (value.startsWith("()")) {
6698
- continue;
6699
- }
6700
- env[key] = value;
6701
- }
6702
- return env;
6703
- }
6704
- function isElectron() {
6705
- return "type" in globalThis.process;
6706
- }
6818
+ // core/tool/mcp/mcp-sse-transport.ts
6819
+ import { EventSourceParserStream } from "eventsource-parser/stream";
6820
+
6821
+ // core/tool/mcp/json-rpc-message.ts
6822
+ import { z as z9 } from "zod";
6707
6823
 
6708
6824
  // core/tool/mcp/types.ts
6709
6825
  import { z as z8 } from "zod";
@@ -6712,7 +6828,6 @@ var SUPPORTED_PROTOCOL_VERSIONS = [
6712
6828
  LATEST_PROTOCOL_VERSION,
6713
6829
  "2024-10-07"
6714
6830
  ];
6715
- var JSONRPC_VERSION = "2.0";
6716
6831
  var ClientOrServerImplementationSchema = z8.object({
6717
6832
  name: z8.string(),
6718
6833
  version: z8.string()
@@ -6720,43 +6835,11 @@ var ClientOrServerImplementationSchema = z8.object({
6720
6835
  var BaseParamsSchema = z8.object({
6721
6836
  _meta: z8.optional(z8.object({}).passthrough())
6722
6837
  }).passthrough();
6723
- var RequestSchema = z8.object({
6724
- method: z8.string(),
6725
- params: z8.optional(BaseParamsSchema)
6726
- });
6727
6838
  var ResultSchema = BaseParamsSchema;
6728
- var NotificationSchema = z8.object({
6839
+ var RequestSchema = z8.object({
6729
6840
  method: z8.string(),
6730
6841
  params: z8.optional(BaseParamsSchema)
6731
6842
  });
6732
- var RequestIdSchema = z8.union([z8.string(), z8.number().int()]);
6733
- var JSONRPCRequestSchema = z8.object({
6734
- jsonrpc: z8.literal(JSONRPC_VERSION),
6735
- id: RequestIdSchema
6736
- }).merge(RequestSchema).strict();
6737
- var JSONRPCResponseSchema = z8.object({
6738
- jsonrpc: z8.literal(JSONRPC_VERSION),
6739
- id: RequestIdSchema,
6740
- result: ResultSchema
6741
- }).strict();
6742
- var JSONRPCErrorSchema = z8.object({
6743
- jsonrpc: z8.literal(JSONRPC_VERSION),
6744
- id: RequestIdSchema,
6745
- error: z8.object({
6746
- code: z8.number().int(),
6747
- message: z8.string(),
6748
- data: z8.optional(z8.unknown())
6749
- })
6750
- }).strict();
6751
- var JSONRPCNotificationSchema = z8.object({
6752
- jsonrpc: z8.literal(JSONRPC_VERSION)
6753
- }).merge(NotificationSchema).strict();
6754
- var JSONRPCMessageSchema = z8.union([
6755
- JSONRPCRequestSchema,
6756
- JSONRPCNotificationSchema,
6757
- JSONRPCResponseSchema,
6758
- JSONRPCErrorSchema
6759
- ]);
6760
6843
  var ServerCapabilitiesSchema = z8.object({
6761
6844
  experimental: z8.optional(z8.object({}).passthrough()),
6762
6845
  logging: z8.optional(z8.object({}).passthrough()),
@@ -6837,127 +6920,43 @@ var CallToolResultSchema = ResultSchema.extend({
6837
6920
  })
6838
6921
  );
6839
6922
 
6840
- // core/tool/mcp/mcp-stdio-transport.ts
6841
- var StdioClientTransport = class {
6842
- constructor(server) {
6843
- this.abortController = new AbortController();
6844
- this.readBuffer = new ReadBuffer();
6845
- this.serverParams = server;
6846
- }
6847
- async start() {
6848
- if (this.process) {
6849
- throw new MCPClientError({
6850
- message: "StdioClientTransport already started."
6851
- });
6852
- }
6853
- return new Promise(async (resolve, reject) => {
6854
- var _a17, _b, _c, _d;
6855
- try {
6856
- const process2 = await createChildProcess(
6857
- this.serverParams,
6858
- this.abortController.signal
6859
- );
6860
- this.process = process2;
6861
- this.process.on("error", (error) => {
6862
- var _a18, _b2;
6863
- if (error.name === "AbortError") {
6864
- (_a18 = this.onClose) == null ? void 0 : _a18.call(this);
6865
- return;
6866
- }
6867
- reject(error);
6868
- (_b2 = this.onError) == null ? void 0 : _b2.call(this, error);
6869
- });
6870
- this.process.on("spawn", () => {
6871
- resolve();
6872
- });
6873
- this.process.on("close", (_code) => {
6874
- var _a18;
6875
- this.process = void 0;
6876
- (_a18 = this.onClose) == null ? void 0 : _a18.call(this);
6877
- });
6878
- (_a17 = this.process.stdin) == null ? void 0 : _a17.on("error", (error) => {
6879
- var _a18;
6880
- (_a18 = this.onError) == null ? void 0 : _a18.call(this, error);
6881
- });
6882
- (_b = this.process.stdout) == null ? void 0 : _b.on("data", (chunk) => {
6883
- this.readBuffer.append(chunk);
6884
- this.processReadBuffer();
6885
- });
6886
- (_c = this.process.stdout) == null ? void 0 : _c.on("error", (error) => {
6887
- var _a18;
6888
- (_a18 = this.onError) == null ? void 0 : _a18.call(this, error);
6889
- });
6890
- } catch (error) {
6891
- reject(error);
6892
- (_d = this.onError) == null ? void 0 : _d.call(this, error);
6893
- }
6894
- });
6895
- }
6896
- processReadBuffer() {
6897
- var _a17, _b;
6898
- while (true) {
6899
- try {
6900
- const message = this.readBuffer.readMessage();
6901
- if (message === null) {
6902
- break;
6903
- }
6904
- (_a17 = this.onMessage) == null ? void 0 : _a17.call(this, message);
6905
- } catch (error) {
6906
- (_b = this.onError) == null ? void 0 : _b.call(this, error);
6907
- }
6908
- }
6909
- }
6910
- async close() {
6911
- this.abortController.abort();
6912
- this.process = void 0;
6913
- this.readBuffer.clear();
6914
- }
6915
- send(message) {
6916
- return new Promise((resolve) => {
6917
- var _a17;
6918
- if (!((_a17 = this.process) == null ? void 0 : _a17.stdin)) {
6919
- throw new MCPClientError({
6920
- message: "StdioClientTransport not connected"
6921
- });
6922
- }
6923
- const json = serializeMessage(message);
6924
- if (this.process.stdin.write(json)) {
6925
- resolve();
6926
- } else {
6927
- this.process.stdin.once("drain", resolve);
6928
- }
6929
- });
6930
- }
6931
- };
6932
- var ReadBuffer = class {
6933
- append(chunk) {
6934
- this.buffer = this.buffer ? Buffer.concat([this.buffer, chunk]) : chunk;
6935
- }
6936
- readMessage() {
6937
- if (!this.buffer)
6938
- return null;
6939
- const index = this.buffer.indexOf("\n");
6940
- if (index === -1) {
6941
- return null;
6942
- }
6943
- const line = this.buffer.toString("utf8", 0, index);
6944
- this.buffer = this.buffer.subarray(index + 1);
6945
- return deserializeMessage(line);
6946
- }
6947
- clear() {
6948
- this.buffer = void 0;
6949
- }
6950
- };
6951
- function serializeMessage(message) {
6952
- return JSON.stringify(message) + "\n";
6953
- }
6954
- function deserializeMessage(line) {
6955
- return JSONRPCMessageSchema.parse(JSON.parse(line));
6956
- }
6923
+ // core/tool/mcp/json-rpc-message.ts
6924
+ var JSONRPC_VERSION = "2.0";
6925
+ var JSONRPCRequestSchema = z9.object({
6926
+ jsonrpc: z9.literal(JSONRPC_VERSION),
6927
+ id: z9.union([z9.string(), z9.number().int()])
6928
+ }).merge(RequestSchema).strict();
6929
+ var JSONRPCResponseSchema = z9.object({
6930
+ jsonrpc: z9.literal(JSONRPC_VERSION),
6931
+ id: z9.union([z9.string(), z9.number().int()]),
6932
+ result: ResultSchema
6933
+ }).strict();
6934
+ var JSONRPCErrorSchema = z9.object({
6935
+ jsonrpc: z9.literal(JSONRPC_VERSION),
6936
+ id: z9.union([z9.string(), z9.number().int()]),
6937
+ error: z9.object({
6938
+ code: z9.number().int(),
6939
+ message: z9.string(),
6940
+ data: z9.optional(z9.unknown())
6941
+ })
6942
+ }).strict();
6943
+ var JSONRPCNotificationSchema = z9.object({
6944
+ jsonrpc: z9.literal(JSONRPC_VERSION)
6945
+ }).merge(
6946
+ z9.object({
6947
+ method: z9.string(),
6948
+ params: z9.optional(BaseParamsSchema)
6949
+ })
6950
+ ).strict();
6951
+ var JSONRPCMessageSchema = z9.union([
6952
+ JSONRPCRequestSchema,
6953
+ JSONRPCNotificationSchema,
6954
+ JSONRPCResponseSchema,
6955
+ JSONRPCErrorSchema
6956
+ ]);
6957
6957
 
6958
6958
  // core/tool/mcp/mcp-sse-transport.ts
6959
- import { EventSourceParserStream } from "eventsource-parser/stream";
6960
- var SSEClientTransport = class {
6959
+ var SseMCPTransport = class {
6961
6960
  constructor({ url }) {
6962
6961
  this.connected = false;
6963
6962
  this.url = new URL(url);
@@ -6981,7 +6980,7 @@ var SSEClientTransport = class {
6981
6980
  const error = new MCPClientError({
6982
6981
  message: `MCP SSE Transport Error: ${response.status} ${response.statusText}`
6983
6982
  });
6984
- (_b = this.onError) == null ? void 0 : _b.call(this, error);
6983
+ (_b = this.onerror) == null ? void 0 : _b.call(this, error);
6985
6984
  return reject(error);
6986
6985
  }
6987
6986
  const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream());
@@ -7015,13 +7014,13 @@ var SSEClientTransport = class {
7015
7014
  const message = JSONRPCMessageSchema.parse(
7016
7015
  JSON.parse(data)
7017
7016
  );
7018
- (_a18 = this.onMessage) == null ? void 0 : _a18.call(this, message);
7017
+ (_a18 = this.onmessage) == null ? void 0 : _a18.call(this, message);
7019
7018
  } catch (error) {
7020
7019
  const e = new MCPClientError({
7021
7020
  message: "MCP SSE Transport Error: Failed to parse message",
7022
7021
  cause: error
7023
7022
  });
7024
- (_b2 = this.onError) == null ? void 0 : _b2.call(this, e);
7023
+ (_b2 = this.onerror) == null ? void 0 : _b2.call(this, e);
7025
7024
  }
7026
7025
  }
7027
7026
  }
@@ -7029,7 +7028,7 @@ var SSEClientTransport = class {
7029
7028
  if (error instanceof Error && error.name === "AbortError") {
7030
7029
  return;
7031
7030
  }
7032
- (_c2 = this.onError) == null ? void 0 : _c2.call(this, error);
7031
+ (_c2 = this.onerror) == null ? void 0 : _c2.call(this, error);
7033
7032
  reject(error);
7034
7033
  }
7035
7034
  };
@@ -7041,7 +7040,7 @@ var SSEClientTransport = class {
7041
7040
  if (error instanceof Error && error.name === "AbortError") {
7042
7041
  return;
7043
7042
  }
7044
- (_c = this.onError) == null ? void 0 : _c.call(this, error);
7043
+ (_c = this.onerror) == null ? void 0 : _c.call(this, error);
7045
7044
  reject(error);
7046
7045
  }
7047
7046
  };
@@ -7053,7 +7052,7 @@ var SSEClientTransport = class {
7053
7052
  this.connected = false;
7054
7053
  (_a17 = this.sseConnection) == null ? void 0 : _a17.close();
7055
7054
  (_b = this.abortController) == null ? void 0 : _b.abort();
7056
- (_c = this.onClose) == null ? void 0 : _c.call(this);
7055
+ (_c = this.onclose) == null ? void 0 : _c.call(this);
7057
7056
  }
7058
7057
  async send(message) {
7059
7058
  var _a17, _b, _c;
@@ -7077,11 +7076,11 @@ var SSEClientTransport = class {
7077
7076
  const error = new MCPClientError({
7078
7077
  message: `MCP SSE Transport Error: POSTing to endpoint (HTTP ${response.status}): ${text2}`
7079
7078
  });
7080
- (_b = this.onError) == null ? void 0 : _b.call(this, error);
7079
+ (_b = this.onerror) == null ? void 0 : _b.call(this, error);
7081
7080
  return;
7082
7081
  }
7083
7082
  } catch (error) {
7084
- (_c = this.onError) == null ? void 0 : _c.call(this, error);
7083
+ (_c = this.onerror) == null ? void 0 : _c.call(this, error);
7085
7084
  return;
7086
7085
  }
7087
7086
  }
@@ -7089,7 +7088,15 @@ var SSEClientTransport = class {
7089
7088
 
7090
7089
  // core/tool/mcp/mcp-transport.ts
7091
7090
  function createMcpTransport(config) {
7092
- return config.type === "stdio" ? new StdioClientTransport(config) : new SSEClientTransport(config);
7091
+ if (config.type !== "sse") {
7092
+ throw new MCPClientError({
7093
+ message: "Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."
7094
+ });
7095
+ }
7096
+ return new SseMCPTransport(config);
7097
+ }
7098
+ function isCustomMcpTransport(transport) {
7099
+ return "start" in transport && typeof transport.start === "function" && "send" in transport && typeof transport.send === "function" && "close" in transport && typeof transport.close === "function";
7093
7100
  }
7094
7101
 
7095
7102
  // core/tool/mcp/mcp-client.ts
@@ -7110,10 +7117,14 @@ var MCPClient = class {
7110
7117
  this.serverCapabilities = {};
7111
7118
  this.isClosed = true;
7112
7119
  this.onUncaughtError = onUncaughtError;
7113
- this.transport = createMcpTransport(transportConfig);
7114
- this.transport.onClose = () => this.onClose();
7115
- this.transport.onError = (error) => this.onError(error);
7116
- this.transport.onMessage = (message) => {
7120
+ if (isCustomMcpTransport(transportConfig)) {
7121
+ this.transport = transportConfig;
7122
+ } else {
7123
+ this.transport = createMcpTransport(transportConfig);
7124
+ }
7125
+ this.transport.onclose = () => this.onClose();
7126
+ this.transport.onerror = (error) => this.onError(error);
7127
+ this.transport.onmessage = (message) => {
7117
7128
  if ("method" in message) {
7118
7129
  this.onError(
7119
7130
  new MCPClientError({