@ai-sdk/provider-utils 3.0.38 → 3.0.40

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,17 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 3.0.40
4
+
5
+ ### Patch Changes
6
+
7
+ - 14810cb: fix(provider-utils): preserve streamed tool calls with unreliable IDs and indices
8
+
9
+ ## 3.0.39
10
+
11
+ ### Patch Changes
12
+
13
+ - bf29419: chore: enable dead code lint rules
14
+
3
15
  ## 3.0.38
4
16
 
5
17
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { AISDKError, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV2Prompt, JSONSchema7, SharedV2ProviderOptions, LanguageModelV2ToolResultOutput, LanguageModelV2ToolResultPart } from '@ai-sdk/provider';
1
+ import { AISDKError, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV2Prompt, JSONSchema7, SharedV2ProviderOptions, LanguageModelV2ToolResultOutput, LanguageModelV2ToolResultPart, LanguageModelV2StreamPart, SharedV2ProviderMetadata } from '@ai-sdk/provider';
2
2
  import * as z4 from 'zod/v4';
3
3
  import { ZodType } from 'zod/v4';
4
4
  import { StandardSchemaV1 } from '@standard-schema/spec';
@@ -950,6 +950,73 @@ declare function resolve<T>(value: Resolvable<T>): Promise<T>;
950
950
 
951
951
  declare function asSchema<OBJECT>(schema: FlexibleSchema<OBJECT> | undefined): Schema<OBJECT>;
952
952
 
953
+ /**
954
+ * Minimal interface for a streaming tool call delta from an OpenAI-compatible API.
955
+ */
956
+ interface StreamingToolCallDelta {
957
+ index?: number | null;
958
+ id?: string | null;
959
+ type?: string | null;
960
+ function?: {
961
+ name?: string | null;
962
+ arguments?: string | null;
963
+ } | null;
964
+ }
965
+ interface StreamingToolCallTrackerOptions<DELTA extends StreamingToolCallDelta = StreamingToolCallDelta> {
966
+ /**
967
+ * ID generator function for tool call IDs.
968
+ * Blank or repeated outputs are converted to usable unique IDs.
969
+ * Defaults to the standard generateId.
970
+ */
971
+ generateId?: () => string;
972
+ /**
973
+ * How to validate the `type` field on new tool call deltas.
974
+ * - `'none'`: no validation (default)
975
+ * - `'if-present'`: throw if type is present and not `'function'`
976
+ * - `'required'`: throw if type is not exactly `'function'`
977
+ */
978
+ typeValidation?: 'none' | 'if-present' | 'required';
979
+ /**
980
+ * Extract provider-specific metadata from a tool call delta.
981
+ * Called once when a new tool call is detected.
982
+ */
983
+ extractMetadata?: (delta: DELTA) => SharedV2ProviderMetadata | undefined;
984
+ /**
985
+ * Build the `providerMetadata` object for a `tool-call` event.
986
+ */
987
+ buildToolCallProviderMetadata?: (metadata: SharedV2ProviderMetadata | undefined) => SharedV2ProviderMetadata | undefined;
988
+ }
989
+ type StreamingToolCallTrackerController = Pick<TransformStreamDefaultController<LanguageModelV2StreamPart>, 'enqueue'>;
990
+ /**
991
+ * Tracks streaming tool call state across multiple deltas from an
992
+ * OpenAI-compatible chat completion stream.
993
+ */
994
+ declare class StreamingToolCallTracker<DELTA extends StreamingToolCallDelta = StreamingToolCallDelta> {
995
+ private toolCalls;
996
+ private toolCallsById;
997
+ private toolCallsByIndex;
998
+ private usedToolCallIds;
999
+ private nextGeneratedIdSuffixes;
1000
+ private readonly controller;
1001
+ private readonly _generateId;
1002
+ private readonly typeValidation;
1003
+ private readonly extractMetadata?;
1004
+ private readonly buildToolCallProviderMetadata?;
1005
+ constructor(controller: StreamingToolCallTrackerController, options?: StreamingToolCallTrackerOptions<DELTA>);
1006
+ processDelta(toolCallDelta: DELTA): void;
1007
+ flush(): void;
1008
+ private resolveToolCall;
1009
+ private filterToolCallsByName;
1010
+ private resolveMatchingToolCall;
1011
+ private processNewToolCall;
1012
+ private associateWireId;
1013
+ private associateIndex;
1014
+ private createToolCallId;
1015
+ private getNonBlankString;
1016
+ private processExistingToolCall;
1017
+ private finishToolCall;
1018
+ }
1019
+
953
1020
  declare function convertBase64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer>;
954
1021
  declare function convertUint8ArrayToBase64(array: Uint8Array): string;
955
1022
  declare function convertToBase64(value: string | Uint8Array): string;
@@ -1098,4 +1165,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1098
1165
  dynamic?: boolean;
1099
1166
  }
1100
1167
 
1101
- export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isParsableJson, isSameOrigin, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateDownloadUrl, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1168
+ export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isParsableJson, isSameOrigin, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateDownloadUrl, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AISDKError, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV2Prompt, JSONSchema7, SharedV2ProviderOptions, LanguageModelV2ToolResultOutput, LanguageModelV2ToolResultPart } from '@ai-sdk/provider';
1
+ import { AISDKError, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV2Prompt, JSONSchema7, SharedV2ProviderOptions, LanguageModelV2ToolResultOutput, LanguageModelV2ToolResultPart, LanguageModelV2StreamPart, SharedV2ProviderMetadata } from '@ai-sdk/provider';
2
2
  import * as z4 from 'zod/v4';
3
3
  import { ZodType } from 'zod/v4';
4
4
  import { StandardSchemaV1 } from '@standard-schema/spec';
@@ -950,6 +950,73 @@ declare function resolve<T>(value: Resolvable<T>): Promise<T>;
950
950
 
951
951
  declare function asSchema<OBJECT>(schema: FlexibleSchema<OBJECT> | undefined): Schema<OBJECT>;
952
952
 
953
+ /**
954
+ * Minimal interface for a streaming tool call delta from an OpenAI-compatible API.
955
+ */
956
+ interface StreamingToolCallDelta {
957
+ index?: number | null;
958
+ id?: string | null;
959
+ type?: string | null;
960
+ function?: {
961
+ name?: string | null;
962
+ arguments?: string | null;
963
+ } | null;
964
+ }
965
+ interface StreamingToolCallTrackerOptions<DELTA extends StreamingToolCallDelta = StreamingToolCallDelta> {
966
+ /**
967
+ * ID generator function for tool call IDs.
968
+ * Blank or repeated outputs are converted to usable unique IDs.
969
+ * Defaults to the standard generateId.
970
+ */
971
+ generateId?: () => string;
972
+ /**
973
+ * How to validate the `type` field on new tool call deltas.
974
+ * - `'none'`: no validation (default)
975
+ * - `'if-present'`: throw if type is present and not `'function'`
976
+ * - `'required'`: throw if type is not exactly `'function'`
977
+ */
978
+ typeValidation?: 'none' | 'if-present' | 'required';
979
+ /**
980
+ * Extract provider-specific metadata from a tool call delta.
981
+ * Called once when a new tool call is detected.
982
+ */
983
+ extractMetadata?: (delta: DELTA) => SharedV2ProviderMetadata | undefined;
984
+ /**
985
+ * Build the `providerMetadata` object for a `tool-call` event.
986
+ */
987
+ buildToolCallProviderMetadata?: (metadata: SharedV2ProviderMetadata | undefined) => SharedV2ProviderMetadata | undefined;
988
+ }
989
+ type StreamingToolCallTrackerController = Pick<TransformStreamDefaultController<LanguageModelV2StreamPart>, 'enqueue'>;
990
+ /**
991
+ * Tracks streaming tool call state across multiple deltas from an
992
+ * OpenAI-compatible chat completion stream.
993
+ */
994
+ declare class StreamingToolCallTracker<DELTA extends StreamingToolCallDelta = StreamingToolCallDelta> {
995
+ private toolCalls;
996
+ private toolCallsById;
997
+ private toolCallsByIndex;
998
+ private usedToolCallIds;
999
+ private nextGeneratedIdSuffixes;
1000
+ private readonly controller;
1001
+ private readonly _generateId;
1002
+ private readonly typeValidation;
1003
+ private readonly extractMetadata?;
1004
+ private readonly buildToolCallProviderMetadata?;
1005
+ constructor(controller: StreamingToolCallTrackerController, options?: StreamingToolCallTrackerOptions<DELTA>);
1006
+ processDelta(toolCallDelta: DELTA): void;
1007
+ flush(): void;
1008
+ private resolveToolCall;
1009
+ private filterToolCallsByName;
1010
+ private resolveMatchingToolCall;
1011
+ private processNewToolCall;
1012
+ private associateWireId;
1013
+ private associateIndex;
1014
+ private createToolCallId;
1015
+ private getNonBlankString;
1016
+ private processExistingToolCall;
1017
+ private finishToolCall;
1018
+ }
1019
+
953
1020
  declare function convertBase64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer>;
954
1021
  declare function convertUint8ArrayToBase64(array: Uint8Array): string;
955
1022
  declare function convertToBase64(value: string | Uint8Array): string;
@@ -1098,4 +1165,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1098
1165
  dynamic?: boolean;
1099
1166
  }
1100
1167
 
1101
- export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isParsableJson, isSameOrigin, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateDownloadUrl, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1168
+ export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, fetchWithValidatedRedirects, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isParsableJson, isSameOrigin, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateDownloadUrl, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.js CHANGED
@@ -36,6 +36,7 @@ __export(index_exports, {
36
36
  DownloadError: () => DownloadError,
37
37
  EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL: () => EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL,
38
38
  EventSourceParserStream: () => import_stream2.EventSourceParserStream,
39
+ StreamingToolCallTracker: () => StreamingToolCallTracker,
39
40
  VERSION: () => VERSION,
40
41
  asSchema: () => asSchema,
41
42
  asValidator: () => asValidator,
@@ -105,7 +106,7 @@ function combineHeaders(...headers) {
105
106
  return headers.reduce(
106
107
  (combinedHeaders, currentHeaders) => ({
107
108
  ...combinedHeaders,
108
- ...currentHeaders != null ? currentHeaders : {}
109
+ ...currentHeaders
109
110
  }),
110
111
  {}
111
112
  );
@@ -325,7 +326,6 @@ function validateDownloadUrl(url) {
325
326
  message: `URL with IP address ${hostname} is not allowed`
326
327
  });
327
328
  }
328
- return;
329
329
  }
330
330
  }
331
331
  function validateDownloadAddress({
@@ -811,7 +811,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
811
811
  }
812
812
 
813
813
  // src/version.ts
814
- var VERSION = true ? "3.0.38" : "0.0.0-test";
814
+ var VERSION = true ? "3.0.40" : "0.0.0-test";
815
815
 
816
816
  // src/get-from-api.ts
817
817
  var getOriginalFetch = () => globalThis.fetch;
@@ -1992,7 +1992,7 @@ var zodPatterns = {
1992
1992
  /**
1993
1993
  * `a-z` was added to replicate /i flag
1994
1994
  */
1995
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1995
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/,
1996
1996
  /**
1997
1997
  * Constructed a valid Unicode RegExp
1998
1998
  *
@@ -2995,6 +2995,365 @@ function asSchema(schema) {
2995
2995
  }) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
2996
2996
  }
2997
2997
 
2998
+ // src/streaming-tool-call-tracker.ts
2999
+ var import_provider13 = require("@ai-sdk/provider");
3000
+
3001
+ // src/streaming-tool-call-argument-state.ts
3002
+ function startsWithStructuredValue(value) {
3003
+ if (typeof value !== "string") {
3004
+ return false;
3005
+ }
3006
+ const firstCharacter = value.trimStart()[0];
3007
+ return firstCharacter === "{" || firstCharacter === "[";
3008
+ }
3009
+ var StreamingToolCallArgumentState = class {
3010
+ constructor(initialValue = "") {
3011
+ this.structure = { kind: "undetermined" };
3012
+ this.append(initialValue);
3013
+ }
3014
+ get hasCompleteStructuredValue() {
3015
+ return this.structure.kind === "structured" && this.structure.complete === true;
3016
+ }
3017
+ append(delta) {
3018
+ let nextStructure = this.structure;
3019
+ for (const character of delta) {
3020
+ if (nextStructure.kind === "undetermined") {
3021
+ if (/\s/.test(character)) {
3022
+ continue;
3023
+ }
3024
+ if (character !== "{" && character !== "[") {
3025
+ nextStructure = { kind: "other" };
3026
+ continue;
3027
+ }
3028
+ nextStructure = {
3029
+ kind: "structured",
3030
+ stack: [character],
3031
+ inString: false,
3032
+ escaped: false,
3033
+ complete: false
3034
+ };
3035
+ continue;
3036
+ }
3037
+ if (nextStructure.kind !== "structured" || nextStructure.complete) {
3038
+ continue;
3039
+ }
3040
+ if (nextStructure.inString) {
3041
+ if (nextStructure.escaped) {
3042
+ nextStructure.escaped = false;
3043
+ } else if (character === "\\") {
3044
+ nextStructure.escaped = true;
3045
+ } else if (character === '"') {
3046
+ nextStructure.inString = false;
3047
+ }
3048
+ continue;
3049
+ }
3050
+ if (character === '"') {
3051
+ nextStructure.inString = true;
3052
+ } else if (character === "{" || character === "[") {
3053
+ nextStructure.stack.push(character);
3054
+ } else if (character === "}" || character === "]") {
3055
+ const expectedOpening = character === "}" ? "{" : "[";
3056
+ if (nextStructure.stack[nextStructure.stack.length - 1] !== expectedOpening) {
3057
+ nextStructure = { kind: "other" };
3058
+ continue;
3059
+ }
3060
+ nextStructure.stack.pop();
3061
+ if (nextStructure.stack.length === 0) {
3062
+ nextStructure.complete = true;
3063
+ }
3064
+ }
3065
+ }
3066
+ this.structure = nextStructure;
3067
+ }
3068
+ };
3069
+
3070
+ // src/streaming-tool-call-tracker.ts
3071
+ var StreamingToolCallTracker = class {
3072
+ constructor(controller, options = {}) {
3073
+ this.toolCalls = [];
3074
+ this.toolCallsById = /* @__PURE__ */ new Map();
3075
+ this.toolCallsByIndex = /* @__PURE__ */ new Map();
3076
+ this.usedToolCallIds = /* @__PURE__ */ new Set();
3077
+ this.nextGeneratedIdSuffixes = /* @__PURE__ */ new Map();
3078
+ var _a2, _b2;
3079
+ this.controller = controller;
3080
+ this._generateId = (_a2 = options.generateId) != null ? _a2 : generateId;
3081
+ this.typeValidation = (_b2 = options.typeValidation) != null ? _b2 : "none";
3082
+ this.extractMetadata = options.extractMetadata;
3083
+ this.buildToolCallProviderMetadata = options.buildToolCallProviderMetadata;
3084
+ }
3085
+ processDelta(toolCallDelta) {
3086
+ var _a2, _b2;
3087
+ const wireName = (_a2 = toolCallDelta.function) == null ? void 0 : _a2.name;
3088
+ const hasBlankName = typeof wireName === "string" && wireName.trim().length === 0;
3089
+ const wireId = this.getNonBlankString(toolCallDelta.id);
3090
+ const name2 = this.getNonBlankString(wireName);
3091
+ const { index } = toolCallDelta;
3092
+ const resolution = this.resolveToolCall({
3093
+ wireId,
3094
+ index,
3095
+ name: name2,
3096
+ hasExplicitCallStart: name2 != null && startsWithStructuredValue((_b2 = toolCallDelta.function) == null ? void 0 : _b2.arguments)
3097
+ });
3098
+ if (resolution.kind === "ambiguous") {
3099
+ return;
3100
+ }
3101
+ let toolCall;
3102
+ if (resolution.kind === "new") {
3103
+ if (hasBlankName) {
3104
+ return;
3105
+ }
3106
+ toolCall = this.processNewToolCall(toolCallDelta, {
3107
+ wireId,
3108
+ index,
3109
+ name: name2
3110
+ });
3111
+ } else {
3112
+ toolCall = resolution.toolCall;
3113
+ if (wireId != null) {
3114
+ this.associateWireId(toolCall, wireId);
3115
+ }
3116
+ this.processExistingToolCall(toolCall, toolCallDelta);
3117
+ }
3118
+ if (index != null) {
3119
+ this.associateIndex(toolCall, index);
3120
+ }
3121
+ }
3122
+ flush() {
3123
+ const toolCalls = this.toolCalls.every((toolCall) => toolCall.index != null) ? [...this.toolCalls].sort(
3124
+ (a, b) => a.index - b.index || a.sequence - b.sequence
3125
+ ) : this.toolCalls;
3126
+ for (const toolCall of toolCalls) {
3127
+ if (!toolCall.hasFinished) {
3128
+ this.finishToolCall(toolCall);
3129
+ }
3130
+ }
3131
+ }
3132
+ resolveToolCall({
3133
+ wireId,
3134
+ index,
3135
+ name: name2,
3136
+ hasExplicitCallStart
3137
+ }) {
3138
+ const indexedToolCalls = index != null ? this.toolCallsByIndex.get(index) : void 0;
3139
+ const matchingIndexedToolCalls = this.filterToolCallsByName(
3140
+ indexedToolCalls,
3141
+ name2
3142
+ );
3143
+ if (wireId != null) {
3144
+ const toolCallsWithId = this.toolCallsById.get(wireId);
3145
+ if (toolCallsWithId != null) {
3146
+ if (index != null) {
3147
+ const matchingToolCalls = matchingIndexedToolCalls.filter(
3148
+ (toolCall) => toolCallsWithId.has(toolCall)
3149
+ );
3150
+ const matchingToolCall = this.resolveMatchingToolCall(
3151
+ matchingToolCalls,
3152
+ hasExplicitCallStart
3153
+ );
3154
+ if (matchingToolCall.kind !== "new") {
3155
+ return matchingToolCall;
3156
+ }
3157
+ if (name2 != null) {
3158
+ return { kind: "new" };
3159
+ }
3160
+ if (indexedToolCalls != null) {
3161
+ return { kind: "ambiguous" };
3162
+ }
3163
+ return this.resolveMatchingToolCall([...toolCallsWithId], false);
3164
+ }
3165
+ if (name2 != null) {
3166
+ const matchingToolCalls = [...toolCallsWithId].filter(
3167
+ (toolCall) => toolCall.function.name === name2
3168
+ );
3169
+ return this.resolveMatchingToolCall(
3170
+ matchingToolCalls,
3171
+ hasExplicitCallStart
3172
+ );
3173
+ }
3174
+ return this.resolveMatchingToolCall([...toolCallsWithId], false);
3175
+ }
3176
+ if (matchingIndexedToolCalls.length > 0) {
3177
+ return hasExplicitCallStart ? { kind: "new" } : this.resolveMatchingToolCall(matchingIndexedToolCalls, false);
3178
+ }
3179
+ return { kind: "new" };
3180
+ }
3181
+ if (indexedToolCalls != null) {
3182
+ return this.resolveMatchingToolCall(
3183
+ matchingIndexedToolCalls,
3184
+ hasExplicitCallStart
3185
+ );
3186
+ }
3187
+ if (name2 != null) {
3188
+ return { kind: "new" };
3189
+ }
3190
+ const unfinishedToolCalls = this.toolCalls.filter(
3191
+ (toolCall) => !toolCall.hasFinished
3192
+ );
3193
+ if (unfinishedToolCalls.length === 1) {
3194
+ return { kind: "existing", toolCall: unfinishedToolCalls[0] };
3195
+ }
3196
+ return unfinishedToolCalls.length > 1 ? { kind: "ambiguous" } : { kind: "new" };
3197
+ }
3198
+ filterToolCallsByName(toolCalls, name2) {
3199
+ if (toolCalls == null) {
3200
+ return [];
3201
+ }
3202
+ return [...toolCalls].filter(
3203
+ (toolCall) => name2 == null || toolCall.function.name === name2
3204
+ );
3205
+ }
3206
+ resolveMatchingToolCall(toolCalls, hasExplicitCallStart) {
3207
+ if (toolCalls.length === 0) {
3208
+ return { kind: "new" };
3209
+ }
3210
+ if (!hasExplicitCallStart) {
3211
+ return toolCalls.length === 1 ? { kind: "existing", toolCall: toolCalls[0] } : { kind: "ambiguous" };
3212
+ }
3213
+ const continuableToolCalls = toolCalls.filter(
3214
+ (toolCall) => !toolCall.argumentState.hasCompleteStructuredValue
3215
+ );
3216
+ if (continuableToolCalls.length === 1) {
3217
+ return { kind: "existing", toolCall: continuableToolCalls[0] };
3218
+ }
3219
+ return continuableToolCalls.length > 1 ? { kind: "ambiguous" } : { kind: "new" };
3220
+ }
3221
+ processNewToolCall(toolCallDelta, {
3222
+ wireId,
3223
+ index,
3224
+ name: name2
3225
+ }) {
3226
+ var _a2, _b2, _c, _d, _e;
3227
+ if (this.typeValidation === "required") {
3228
+ if (toolCallDelta.type !== "function") {
3229
+ throw new import_provider13.InvalidResponseDataError({
3230
+ data: toolCallDelta,
3231
+ message: `Expected 'function' type.`
3232
+ });
3233
+ }
3234
+ } else if (this.typeValidation === "if-present") {
3235
+ if (toolCallDelta.type != null && toolCallDelta.type !== "function") {
3236
+ throw new import_provider13.InvalidResponseDataError({
3237
+ data: toolCallDelta,
3238
+ message: `Expected 'function' type.`
3239
+ });
3240
+ }
3241
+ }
3242
+ if (name2 == null) {
3243
+ throw new import_provider13.InvalidResponseDataError({
3244
+ data: toolCallDelta,
3245
+ message: `Expected 'function.name' to be a string.`
3246
+ });
3247
+ }
3248
+ const id = this.createToolCallId(wireId);
3249
+ this.controller.enqueue({
3250
+ type: "tool-input-start",
3251
+ id,
3252
+ toolName: name2
3253
+ });
3254
+ const toolCall = {
3255
+ id,
3256
+ index: index != null ? index : void 0,
3257
+ sequence: this.toolCalls.length,
3258
+ type: "function",
3259
+ function: {
3260
+ name: name2,
3261
+ arguments: (_b2 = (_a2 = toolCallDelta.function) == null ? void 0 : _a2.arguments) != null ? _b2 : ""
3262
+ },
3263
+ argumentState: new StreamingToolCallArgumentState(
3264
+ (_d = (_c = toolCallDelta.function) == null ? void 0 : _c.arguments) != null ? _d : ""
3265
+ ),
3266
+ hasFinished: false,
3267
+ metadata: (_e = this.extractMetadata) == null ? void 0 : _e.call(this, toolCallDelta)
3268
+ };
3269
+ this.toolCalls.push(toolCall);
3270
+ if (wireId != null) {
3271
+ this.associateWireId(toolCall, wireId);
3272
+ }
3273
+ if (toolCall.function.arguments.length > 0) {
3274
+ this.controller.enqueue({
3275
+ type: "tool-input-delta",
3276
+ id: toolCall.id,
3277
+ delta: toolCall.function.arguments
3278
+ });
3279
+ }
3280
+ return toolCall;
3281
+ }
3282
+ associateWireId(toolCall, wireId) {
3283
+ let toolCallsWithId = this.toolCallsById.get(wireId);
3284
+ if (toolCallsWithId == null) {
3285
+ toolCallsWithId = /* @__PURE__ */ new Set();
3286
+ this.toolCallsById.set(wireId, toolCallsWithId);
3287
+ }
3288
+ toolCallsWithId.add(toolCall);
3289
+ }
3290
+ associateIndex(toolCall, index) {
3291
+ let toolCallsWithIndex = this.toolCallsByIndex.get(index);
3292
+ if (toolCallsWithIndex == null) {
3293
+ toolCallsWithIndex = /* @__PURE__ */ new Set();
3294
+ this.toolCallsByIndex.set(index, toolCallsWithIndex);
3295
+ }
3296
+ toolCallsWithIndex.add(toolCall);
3297
+ }
3298
+ createToolCallId(wireId) {
3299
+ var _a2, _b2;
3300
+ if (wireId != null && !this.usedToolCallIds.has(wireId)) {
3301
+ this.usedToolCallIds.add(wireId);
3302
+ return wireId;
3303
+ }
3304
+ const generatedId = (_a2 = this.getNonBlankString(this._generateId())) != null ? _a2 : "tool-call";
3305
+ if (!this.usedToolCallIds.has(generatedId)) {
3306
+ this.usedToolCallIds.add(generatedId);
3307
+ return generatedId;
3308
+ }
3309
+ const initialSuffix = (_b2 = this.nextGeneratedIdSuffixes.get(generatedId)) != null ? _b2 : 1;
3310
+ const maximumSuffix = initialSuffix + this.usedToolCallIds.size;
3311
+ for (let suffix = initialSuffix; suffix <= maximumSuffix; suffix++) {
3312
+ const suffixedId = `${generatedId}-${suffix}`;
3313
+ if (!this.usedToolCallIds.has(suffixedId)) {
3314
+ this.usedToolCallIds.add(suffixedId);
3315
+ this.nextGeneratedIdSuffixes.set(generatedId, suffix + 1);
3316
+ return suffixedId;
3317
+ }
3318
+ }
3319
+ throw new Error("Failed to create a unique tool call ID.");
3320
+ }
3321
+ getNonBlankString(value) {
3322
+ return value != null && value.trim().length > 0 ? value : void 0;
3323
+ }
3324
+ processExistingToolCall(toolCall, toolCallDelta) {
3325
+ var _a2;
3326
+ if (!toolCall.hasFinished && ((_a2 = toolCallDelta.function) == null ? void 0 : _a2.arguments) != null) {
3327
+ toolCall.argumentState.append(toolCallDelta.function.arguments);
3328
+ toolCall.function.arguments += toolCallDelta.function.arguments;
3329
+ this.controller.enqueue({
3330
+ type: "tool-input-delta",
3331
+ id: toolCall.id,
3332
+ delta: toolCallDelta.function.arguments
3333
+ });
3334
+ }
3335
+ }
3336
+ finishToolCall(toolCall) {
3337
+ var _a2;
3338
+ this.controller.enqueue({
3339
+ type: "tool-input-end",
3340
+ id: toolCall.id
3341
+ });
3342
+ const providerMetadata = (_a2 = this.buildToolCallProviderMetadata) == null ? void 0 : _a2.call(
3343
+ this,
3344
+ toolCall.metadata
3345
+ );
3346
+ this.controller.enqueue({
3347
+ type: "tool-call",
3348
+ toolCallId: toolCall.id,
3349
+ toolName: toolCall.function.name,
3350
+ input: toolCall.function.arguments,
3351
+ ...providerMetadata ? { providerMetadata } : {}
3352
+ });
3353
+ toolCall.hasFinished = true;
3354
+ }
3355
+ };
3356
+
2998
3357
  // src/uint8-utils.ts
2999
3358
  var { btoa, atob } = globalThis;
3000
3359
  function convertBase64ToUint8Array(base64String) {
@@ -3053,6 +3412,7 @@ var import_stream2 = require("eventsource-parser/stream");
3053
3412
  DownloadError,
3054
3413
  EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL,
3055
3414
  EventSourceParserStream,
3415
+ StreamingToolCallTracker,
3056
3416
  VERSION,
3057
3417
  asSchema,
3058
3418
  asValidator,