@ai-sdk/provider-utils 4.0.34 → 4.0.35

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 4.0.35
4
+
5
+ ### Patch Changes
6
+
7
+ - ea1e95b: feat(mcp): add maxRetries option for failed mcp tool calls
8
+
3
9
  ## 4.0.34
4
10
 
5
11
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -1360,6 +1360,31 @@ type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);
1360
1360
  */
1361
1361
  declare function resolve<T>(value: Resolvable<T>): Promise<T>;
1362
1362
 
1363
+ type RetryFunction = <OUTPUT>(fn: () => PromiseLike<OUTPUT>) => PromiseLike<OUTPUT>;
1364
+ type RetryErrorReason = 'maxRetriesExceeded' | 'errorNotRetryable';
1365
+ type RetryErrorFactory = ({ message, reason, errors, }: {
1366
+ message: string;
1367
+ reason: RetryErrorReason;
1368
+ errors: Array<unknown>;
1369
+ }) => unknown;
1370
+ type RetryDelayProvider = ({ error, exponentialBackoffDelay, }: {
1371
+ error: unknown;
1372
+ exponentialBackoffDelay: number;
1373
+ }) => number;
1374
+ type ShouldRetryFunction = (error: unknown) => boolean | Promise<boolean>;
1375
+ /**
1376
+ * Retries a failed operation with exponential backoff.
1377
+ */
1378
+ declare const retryWithExponentialBackoff: ({ maxRetries, initialDelayInMs, backoffFactor, abortSignal, shouldRetry, getDelayInMs, createRetryError, }: {
1379
+ maxRetries?: number;
1380
+ initialDelayInMs?: number;
1381
+ backoffFactor?: number;
1382
+ abortSignal?: AbortSignal;
1383
+ shouldRetry: ShouldRetryFunction;
1384
+ getDelayInMs?: RetryDelayProvider;
1385
+ createRetryError?: RetryErrorFactory;
1386
+ }) => RetryFunction;
1387
+
1363
1388
  /**
1364
1389
  * Strips file extension segments from a filename.
1365
1390
  *
@@ -1518,4 +1543,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1518
1543
  */
1519
1544
  type ToolCallOptions = ToolExecutionOptions;
1520
1545
 
1521
- export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1546
+ export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.d.ts CHANGED
@@ -1360,6 +1360,31 @@ type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);
1360
1360
  */
1361
1361
  declare function resolve<T>(value: Resolvable<T>): Promise<T>;
1362
1362
 
1363
+ type RetryFunction = <OUTPUT>(fn: () => PromiseLike<OUTPUT>) => PromiseLike<OUTPUT>;
1364
+ type RetryErrorReason = 'maxRetriesExceeded' | 'errorNotRetryable';
1365
+ type RetryErrorFactory = ({ message, reason, errors, }: {
1366
+ message: string;
1367
+ reason: RetryErrorReason;
1368
+ errors: Array<unknown>;
1369
+ }) => unknown;
1370
+ type RetryDelayProvider = ({ error, exponentialBackoffDelay, }: {
1371
+ error: unknown;
1372
+ exponentialBackoffDelay: number;
1373
+ }) => number;
1374
+ type ShouldRetryFunction = (error: unknown) => boolean | Promise<boolean>;
1375
+ /**
1376
+ * Retries a failed operation with exponential backoff.
1377
+ */
1378
+ declare const retryWithExponentialBackoff: ({ maxRetries, initialDelayInMs, backoffFactor, abortSignal, shouldRetry, getDelayInMs, createRetryError, }: {
1379
+ maxRetries?: number;
1380
+ initialDelayInMs?: number;
1381
+ backoffFactor?: number;
1382
+ abortSignal?: AbortSignal;
1383
+ shouldRetry: ShouldRetryFunction;
1384
+ getDelayInMs?: RetryDelayProvider;
1385
+ createRetryError?: RetryErrorFactory;
1386
+ }) => RetryFunction;
1387
+
1363
1388
  /**
1364
1389
  * Strips file extension segments from a filename.
1365
1390
  *
@@ -1518,4 +1543,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1518
1543
  */
1519
1544
  type ToolCallOptions = ToolExecutionOptions;
1520
1545
 
1521
- export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1546
+ export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isNonNullable, isParsableJson, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.js CHANGED
@@ -86,6 +86,7 @@ __export(index_exports, {
86
86
  readResponseWithSizeLimit: () => readResponseWithSizeLimit,
87
87
  removeUndefinedEntries: () => removeUndefinedEntries,
88
88
  resolve: () => resolve,
89
+ retryWithExponentialBackoff: () => retryWithExponentialBackoff,
89
90
  safeParseJSON: () => safeParseJSON,
90
91
  safeValidateTypes: () => safeValidateTypes,
91
92
  stripFileExtension: () => stripFileExtension,
@@ -777,7 +778,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
777
778
  }
778
779
 
779
780
  // src/version.ts
780
- var VERSION = true ? "4.0.34" : "0.0.0-test";
781
+ var VERSION = true ? "4.0.35" : "0.0.0-test";
781
782
 
782
783
  // src/get-from-api.ts
783
784
  var getOriginalFetch = () => globalThis.fetch;
@@ -2715,6 +2716,85 @@ async function resolve(value) {
2715
2716
  return Promise.resolve(value);
2716
2717
  }
2717
2718
 
2719
+ // src/retry-with-exponential-backoff.ts
2720
+ var retryWithExponentialBackoff = ({
2721
+ maxRetries = 2,
2722
+ initialDelayInMs = 2e3,
2723
+ backoffFactor = 2,
2724
+ abortSignal,
2725
+ shouldRetry,
2726
+ getDelayInMs = ({ exponentialBackoffDelay }) => exponentialBackoffDelay,
2727
+ createRetryError = ({ message }) => new Error(message)
2728
+ }) => async (f) => retryWithExponentialBackoffInternal(f, {
2729
+ maxRetries,
2730
+ delayInMs: initialDelayInMs,
2731
+ backoffFactor,
2732
+ abortSignal,
2733
+ shouldRetry,
2734
+ getDelayInMs,
2735
+ createRetryError
2736
+ });
2737
+ async function retryWithExponentialBackoffInternal(f, {
2738
+ maxRetries,
2739
+ delayInMs,
2740
+ backoffFactor,
2741
+ abortSignal,
2742
+ shouldRetry,
2743
+ getDelayInMs,
2744
+ createRetryError
2745
+ }, errors = []) {
2746
+ try {
2747
+ return await f();
2748
+ } catch (error) {
2749
+ if (isAbortError(error)) {
2750
+ throw error;
2751
+ }
2752
+ if (maxRetries === 0) {
2753
+ throw error;
2754
+ }
2755
+ const errorMessage = getErrorMessage(error);
2756
+ const newErrors = [...errors, error];
2757
+ const tryNumber = newErrors.length;
2758
+ if (tryNumber > maxRetries) {
2759
+ throw createRetryError({
2760
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
2761
+ reason: "maxRetriesExceeded",
2762
+ errors: newErrors
2763
+ });
2764
+ }
2765
+ if (await shouldRetry(error) && tryNumber <= maxRetries) {
2766
+ await delay(
2767
+ getDelayInMs({
2768
+ error,
2769
+ exponentialBackoffDelay: delayInMs
2770
+ }),
2771
+ { abortSignal }
2772
+ );
2773
+ return retryWithExponentialBackoffInternal(
2774
+ f,
2775
+ {
2776
+ maxRetries,
2777
+ delayInMs: backoffFactor * delayInMs,
2778
+ backoffFactor,
2779
+ abortSignal,
2780
+ shouldRetry,
2781
+ getDelayInMs,
2782
+ createRetryError
2783
+ },
2784
+ newErrors
2785
+ );
2786
+ }
2787
+ if (tryNumber === 1) {
2788
+ throw error;
2789
+ }
2790
+ throw createRetryError({
2791
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
2792
+ reason: "errorNotRetryable",
2793
+ errors: newErrors
2794
+ });
2795
+ }
2796
+ }
2797
+
2718
2798
  // src/response-handler.ts
2719
2799
  var import_provider12 = require("@ai-sdk/provider");
2720
2800
  var textDecoder = new TextDecoder();
@@ -2961,6 +3041,7 @@ var import_stream2 = require("eventsource-parser/stream");
2961
3041
  readResponseWithSizeLimit,
2962
3042
  removeUndefinedEntries,
2963
3043
  resolve,
3044
+ retryWithExponentialBackoff,
2964
3045
  safeParseJSON,
2965
3046
  safeValidateTypes,
2966
3047
  stripFileExtension,