@ai-sdk/provider-utils 5.0.47 → 5.0.50

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.d.ts CHANGED
@@ -1084,6 +1084,9 @@ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, tru
1084
1084
  * Request headers are also protected: {@link sanitizeRequestHeaders} strips
1085
1085
  * proxy/metadata/cookie/hop-by-hop headers before the first request, and all
1086
1086
  * caller headers except `User-Agent` are dropped on a cross-origin redirect.
1087
+ * Credentials and custom headers are preserved on the first hop for backwards
1088
+ * compatibility. The caller must ensure that the initial URL may receive them.
1089
+ * Use `fetchUntrustedUrl` for URLs that require first-hop credential isolation.
1087
1090
  * The fetch spec only strips `Authorization` on cross-origin redirects because
1088
1091
  * in a browser, CORS preflighting protects custom headers; there is no CORS on
1089
1092
  * the server, so provider API keys carried in custom headers (e.g. `x-key`)
@@ -1154,6 +1157,41 @@ declare function extractResponseHeaders(response: Response): {
1154
1157
  [k: string]: string;
1155
1158
  };
1156
1159
 
1160
+ /**
1161
+ * Fetches an untrusted URL with first-hop credential isolation and validated
1162
+ * redirects. Uses the URL validation, DNS-pinned Node.js transport, redirect
1163
+ * limits, and cross-origin header stripping of {@link fetchWithValidatedRedirects}.
1164
+ * An injected fetch must provide equivalent connect-time DNS validation.
1165
+ *
1166
+ * Without a matching `credentialedOrigin` (or `trustedOrigin` when it is
1167
+ * omitted), only allowlisted request metadata is sent on the first hop.
1168
+ * Arbitrary caller headers require an explicit matching origin because vendor
1169
+ * credential names cannot be inferred safely. Proxy, metadata, cookie, and
1170
+ * hop-by-hop headers are sanitized even for a matching origin.
1171
+ *
1172
+ * `trustedOrigin` also exempts same-origin hops from URL validation, allowing
1173
+ * developer-configured private endpoints. Both origin options must come from
1174
+ * developer configuration, never from untrusted response data.
1175
+ *
1176
+ * This is an opt-in alternative to `fetchWithValidatedRedirects`, whose
1177
+ * existing first-hop header behavior is preserved for compatibility.
1178
+ */
1179
+ declare function fetchUntrustedUrl({ headers, credentialedOrigin, untrustedFirstHopHeaders, ...options }: Parameters<typeof fetchWithValidatedRedirects>[0] & {
1180
+ /**
1181
+ * The developer-configured origin allowed to receive arbitrary caller
1182
+ * headers on the first hop. Defaults to `trustedOrigin` when omitted.
1183
+ * An explicit value takes precedence over `trustedOrigin` and does not
1184
+ * exempt the URL from validation.
1185
+ */
1186
+ credentialedOrigin?: string;
1187
+ /**
1188
+ * Additional sanitized header names safe to disclose to an untrusted first
1189
+ * hop. Use only for non-credential protocol metadata. Credentials require
1190
+ * a matching `credentialedOrigin` instead. Names are case-insensitive.
1191
+ */
1192
+ untrustedFirstHopHeaders?: readonly string[];
1193
+ }): Promise<Response>;
1194
+
1157
1195
  /**
1158
1196
  * Filters `null` and `undefined` values out of a list of values.
1159
1197
  *
@@ -1308,11 +1346,11 @@ declare function isRecord(value: unknown): value is Record<string, unknown>;
1308
1346
  /**
1309
1347
  * Checks if the given URL is supported natively by the model.
1310
1348
  *
1311
- * @param mediaType - The media type of the URL. Case-sensitive. May be a full
1349
+ * @param mediaType - The media type of the URL. Case-insensitive. May be a full
1312
1350
  * `type/subtype`, a wildcard `type/*`, or just the
1313
1351
  * top-level segment (e.g. `image`).
1314
1352
  * @param url - The URL to check.
1315
- * @param supportedUrls - A record where keys are case-sensitive media types (or '*')
1353
+ * @param supportedUrls - A record where keys are case-insensitive media types (or '*')
1316
1354
  * and values are arrays of RegExp patterns for URLs.
1317
1355
  *
1318
1356
  * @returns `true` if the URL matches a pattern under the specific media type
@@ -2432,6 +2470,7 @@ interface StreamingToolCallDelta {
2432
2470
  interface StreamingToolCallTrackerOptions<DELTA extends StreamingToolCallDelta = StreamingToolCallDelta> {
2433
2471
  /**
2434
2472
  * ID generator function for tool call IDs.
2473
+ * Blank or repeated outputs are converted to usable unique IDs.
2435
2474
  * Defaults to the standard generateId.
2436
2475
  */
2437
2476
  generateId?: () => string;
@@ -2463,13 +2502,15 @@ type StreamingToolCallTrackerController = Pick<TransformStreamDefaultController<
2463
2502
  * emits tool-input-start/delta/end and tool-call events, and finalizes
2464
2503
  * unfinished tool calls on flush.
2465
2504
  *
2466
- * Used by openai, openai-compatible, groq, deepseek, and alibaba providers.
2505
+ * Used by openai, openai-compatible, groq, deepseek, alibaba, mistral, and
2506
+ * moonshotai providers.
2467
2507
  */
2468
2508
  declare class StreamingToolCallTracker<DELTA extends StreamingToolCallDelta = StreamingToolCallDelta> {
2469
2509
  private toolCalls;
2470
2510
  private toolCallsById;
2471
2511
  private toolCallsByIndex;
2472
- private latestToolCall;
2512
+ private usedToolCallIds;
2513
+ private nextGeneratedIdSuffixes;
2473
2514
  private readonly controller;
2474
2515
  private readonly _generateId;
2475
2516
  private readonly typeValidation;
@@ -2487,7 +2528,27 @@ declare class StreamingToolCallTracker<DELTA extends StreamingToolCallDelta = St
2487
2528
  * flush handler to ensure all tool calls are properly completed.
2488
2529
  */
2489
2530
  flush(): void;
2531
+ /**
2532
+ * Correlation precedence for streamed deltas:
2533
+ *
2534
+ * | ID evidence | index/name evidence | start evidence | resolution |
2535
+ * | --- | --- | --- | --- |
2536
+ * | known | matching | any | matching call, new call, or ambiguity |
2537
+ * | known | conflicting | named | new call |
2538
+ * | unseen | matching | structured start | new call |
2539
+ * | unseen | matching | continuation | matching call or ambiguity |
2540
+ * | absent | matching | any | matching call, new call, or ambiguity |
2541
+ * | absent | absent | named | new call |
2542
+ * | absent | absent | unnamed | sole unfinished call, new call, or ambiguity |
2543
+ */
2544
+ private resolveToolCall;
2545
+ private filterToolCallsByName;
2546
+ private resolveMatchingToolCall;
2490
2547
  private processNewToolCall;
2548
+ private associateWireId;
2549
+ private associateIndex;
2550
+ private createToolCallId;
2551
+ private getNonBlankString;
2491
2552
  private processExistingToolCall;
2492
2553
  private finishToolCall;
2493
2554
  }
@@ -2843,4 +2904,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
2843
2904
  dynamic?: boolean;
2844
2905
  }
2845
2906
 
2846
- export { type Arrayable, type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type DynamicTool, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER as EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE as EXPERIMENTAL_TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE, TRANSCRIPTION_STREAM_START_FRAME_TYPE as EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE, type EmbeddingModelProviderOptionsTransformer, type ExecutableTool, type SandboxProcess as Experimental_SandboxProcess, type SandboxSession as Experimental_SandboxSession, type ToolCallerDefinition as Experimental_ToolCallerDefinition, type ToolCallerTool as Experimental_ToolCallerTool, type TranscriptionStreamClientFrame as Experimental_TranscriptionStreamClientFrame, type TranscriptionStreamStartFrame as Experimental_TranscriptionStreamStartFrame, type FetchFunction, type FileData, type FileDataData, type FileDataReference, type FileDataText, type FileDataUrl, type FilePart, type FlexibleSchema, type FunctionTool, type HasRequiredKey, type IdGenerator, type ImagePart, type InferSchema, type InferToolContext, type InferToolInput, type InferToolOutput, type InferToolSetContext, type LazySchema, type MaybePromiseLike, type ModelMessage, type MultipartStreamPart, type ParseResult, type ProviderDefinedTool, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderExecutedTool, type ProviderExecutedToolFactory, type ProviderOptions, type ProviderReference, type ProviderStreamError, type ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, SerializationError, type ShouldRetryFunction, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type ToolSet, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type WebSocketConnection, type WebSocketConstructor, type WebSocketLike, asArray, asSchema, cancelResponseBody, combineHeaders, connectToWebSocket, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertInlineFileDataToUint8Array, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createBinaryStreamResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonLinesResponseHandler, createJsonResponseHandler, createLanguageModelResponseMetadata, createNullLanguageModelUsage, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createProviderExecutedToolFactory, createProviderStreamError, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, deleteFromApi, detectMediaType, downloadBlob, dynamicTool, executeTool, getToolCaller as experimental_getToolCaller, parseTranscriptionStreamClientFrame as experimental_parseTranscriptionStreamClientFrame, parseTranscriptionStreamPart as experimental_parseTranscriptionStreamPart, serializeTranscriptionStreamPart as experimental_serializeTranscriptionStreamPart, toolCaller as experimental_toolCaller, extractLines, extractResponseHeaders, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, filterNullable, generateId, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, isProviderStreamError, isRecord, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeBatchRequestCounts, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postMultipartStreamToApi, postToApi, readResponseWithSizeLimit, readWebSocketMessageText, removeUndefinedEntries, resolve, resolveFullMediaType, resolveProviderReference, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, serializeModelOptions, stripFileExtension, toWebSocketUrl, tool, validateBaseURL, validateDownloadUrl, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
2907
+ export { type Arrayable, type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type DynamicTool, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER as EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE as EXPERIMENTAL_TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE, TRANSCRIPTION_STREAM_START_FRAME_TYPE as EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE, type EmbeddingModelProviderOptionsTransformer, type ExecutableTool, type SandboxProcess as Experimental_SandboxProcess, type SandboxSession as Experimental_SandboxSession, type ToolCallerDefinition as Experimental_ToolCallerDefinition, type ToolCallerTool as Experimental_ToolCallerTool, type TranscriptionStreamClientFrame as Experimental_TranscriptionStreamClientFrame, type TranscriptionStreamStartFrame as Experimental_TranscriptionStreamStartFrame, type FetchFunction, type FileData, type FileDataData, type FileDataReference, type FileDataText, type FileDataUrl, type FilePart, type FlexibleSchema, type FunctionTool, type HasRequiredKey, type IdGenerator, type ImagePart, type InferSchema, type InferToolContext, type InferToolInput, type InferToolOutput, type InferToolSetContext, type LazySchema, type MaybePromiseLike, type ModelMessage, type MultipartStreamPart, type ParseResult, type ProviderDefinedTool, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderExecutedTool, type ProviderExecutedToolFactory, type ProviderOptions, type ProviderReference, type ProviderStreamError, type ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, SerializationError, type ShouldRetryFunction, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type ToolSet, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type WebSocketConnection, type WebSocketConstructor, type WebSocketLike, asArray, asSchema, cancelResponseBody, combineHeaders, connectToWebSocket, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertInlineFileDataToUint8Array, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createBinaryStreamResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonLinesResponseHandler, createJsonResponseHandler, createLanguageModelResponseMetadata, createNullLanguageModelUsage, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createProviderExecutedToolFactory, createProviderStreamError, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, deleteFromApi, detectMediaType, downloadBlob, dynamicTool, executeTool, getToolCaller as experimental_getToolCaller, parseTranscriptionStreamClientFrame as experimental_parseTranscriptionStreamClientFrame, parseTranscriptionStreamPart as experimental_parseTranscriptionStreamPart, serializeTranscriptionStreamPart as experimental_serializeTranscriptionStreamPart, toolCaller as experimental_toolCaller, extractLines, extractResponseHeaders, fetchUntrustedUrl, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, filterNullable, generateId, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, isProviderStreamError, isRecord, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeBatchRequestCounts, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postMultipartStreamToApi, postToApi, readResponseWithSizeLimit, readWebSocketMessageText, removeUndefinedEntries, resolve, resolveFullMediaType, resolveProviderReference, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, serializeModelOptions, stripFileExtension, toWebSocketUrl, tool, validateBaseURL, validateDownloadUrl, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, withoutTrailingSlash, zodSchema };