@8wave/ai-elements 0.117.0-beta.12 → 0.117.0-beta.22
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/_chunks/{Agent-BxyaZeuL.js → Agent-CFkAjuTy.js} +204 -168
- package/dist/_chunks/Agent-CFkAjuTy.js.map +1 -0
- package/dist/_chunks/{PkStreamingMarkdown-B8mvCNou.js → PkStreamingMarkdown-BoVR7gtl.js} +670 -644
- package/dist/_chunks/PkStreamingMarkdown-BoVR7gtl.js.map +1 -0
- package/dist/_chunks/{PkToolEditSpreadsheet-Bp-ES8B0.js → PkToolEditSpreadsheet-BlfsM7Qp.js} +2 -2
- package/dist/_chunks/{PkToolEditSpreadsheet-Bp-ES8B0.js.map → PkToolEditSpreadsheet-BlfsM7Qp.js.map} +1 -1
- package/dist/_chunks/{PkToolRequestGeolocation-DcPMMyJH.js → PkToolRequestGeolocation-DdQ91rpB.js} +2 -2
- package/dist/_chunks/{PkToolRequestGeolocation-DcPMMyJH.js.map → PkToolRequestGeolocation-DdQ91rpB.js.map} +1 -1
- package/dist/_chunks/{PkToolRequestOAuthConnection-Cc2qViGX.js → PkToolRequestOAuthConnection-yuTNMEFj.js} +2 -2
- package/dist/_chunks/{PkToolRequestOAuthConnection-Cc2qViGX.js.map → PkToolRequestOAuthConnection-yuTNMEFj.js.map} +1 -1
- package/dist/_chunks/{PkToolShowArtifact-CcwAlOFM.js → PkToolShowArtifact-DaTlDsDo.js} +2 -2
- package/dist/_chunks/{PkToolShowArtifact-CcwAlOFM.js.map → PkToolShowArtifact-DaTlDsDo.js.map} +1 -1
- package/dist/_chunks/{PkToolShowContactForm-DByjGK_F.js → PkToolShowContactForm-Dxh6bEZt.js} +2 -2
- package/dist/_chunks/{PkToolShowContactForm-DByjGK_F.js.map → PkToolShowContactForm-Dxh6bEZt.js.map} +1 -1
- package/dist/_chunks/{PkToolShowForm-CGrjJ-9k.js → PkToolShowForm-D1VzwMmq.js} +3 -3
- package/dist/_chunks/{PkToolShowForm-CGrjJ-9k.js.map → PkToolShowForm-D1VzwMmq.js.map} +1 -1
- package/dist/_chunks/{PkToolShowImageGallery-C3ZaW1jQ.js → PkToolShowImageGallery-Cs8FxK9V.js} +2 -2
- package/dist/_chunks/{PkToolShowImageGallery-C3ZaW1jQ.js.map → PkToolShowImageGallery-Cs8FxK9V.js.map} +1 -1
- package/dist/_chunks/{PkToolShowProductList-BAHoB6mi.js → PkToolShowProductList-B4fxqFaf.js} +2 -2
- package/dist/_chunks/{PkToolShowProductList-BAHoB6mi.js.map → PkToolShowProductList-B4fxqFaf.js.map} +1 -1
- package/dist/_chunks/{PkToolShowSources-BgnumOzQ.js → PkToolShowSources-DNiiBz9b.js} +3 -3
- package/dist/_chunks/{PkToolShowSources-BgnumOzQ.js.map → PkToolShowSources-DNiiBz9b.js.map} +1 -1
- package/dist/_chunks/{PkToolShowSuggestedReply-CpixDpsJ.js → PkToolShowSuggestedReply-Bn1w6HdI.js} +2 -2
- package/dist/_chunks/{PkToolShowSuggestedReply-CpixDpsJ.js.map → PkToolShowSuggestedReply-Bn1w6HdI.js.map} +1 -1
- package/dist/_chunks/{PkToolShowVideo-94-l_bBW.js → PkToolShowVideo-Be5bKhUf.js} +2 -2
- package/dist/_chunks/{PkToolShowVideo-94-l_bBW.js.map → PkToolShowVideo-Be5bKhUf.js.map} +1 -1
- package/dist/_chunks/{PkToolShowWebPages-q1gLOgDl.js → PkToolShowWebPages-Bs251x0h.js} +2 -2
- package/dist/_chunks/{PkToolShowWebPages-q1gLOgDl.js.map → PkToolShowWebPages-Bs251x0h.js.map} +1 -1
- package/dist/_chunks/{chatImagePolicy-D4kQJejM.js → chatImagePolicy-BACuW8x3.js} +2 -2
- package/dist/_chunks/{chatImagePolicy-D4kQJejM.js.map → chatImagePolicy-BACuW8x3.js.map} +1 -1
- package/dist/_chunks/{markdown-DCYDJNwF.js → markdown-Bk1clNA6.js} +13 -13
- package/dist/_chunks/{markdown-DCYDJNwF.js.map → markdown-Bk1clNA6.js.map} +1 -1
- package/dist/ai-elements.es.js +1992 -1880
- package/dist/ai-elements.es.js.map +1 -1
- package/dist-vue/PkChatbot.js +1 -1
- package/dist-vue/PkChatbotAudioTranscript.d.ts +2 -0
- package/dist-vue/PkChatbotAudioTranscript.js +1 -0
- package/dist-vue/PkChatbotAuth.js +1 -1
- package/dist-vue/PkChatbotEmptyState.js +1 -1
- package/dist-vue/PkChatbotInput.js +1 -1
- package/dist-vue/PkChatbotMessages.js +1 -1
- package/dist-vue/PkChatbotStepPayload.js +1 -1
- package/dist-vue/PkChatbotStepToolDetail.js +1 -1
- package/dist-vue/PkChatbotSteps.js +1 -1
- package/dist-vue/PkChatbotViewChat.js +1 -1
- package/dist-vue/PkChatbotViewConversations.js +1 -1
- package/dist-vue/PkChatbotViewFiles.js +1 -1
- package/dist-vue/PkChatbotViewProfile.js +1 -1
- package/dist-vue/_chunks/{Agent-CSXbmC44.js → Agent-CNJ3b9Je.js} +2 -2
- package/dist-vue/_chunks/{Agent-CSXbmC44.js.map → Agent-CNJ3b9Je.js.map} +1 -1
- package/dist-vue/_chunks/{Document-Ol8nGgij.js → Document-Bp3YJuQQ.js} +11 -11
- package/dist-vue/_chunks/{Document-Ol8nGgij.js.map → Document-Bp3YJuQQ.js.map} +1 -1
- package/dist-vue/_chunks/{Media-Cv7ou2tP.js → Media-C6Xsb1Lm.js} +77 -27
- package/dist-vue/_chunks/Media-C6Xsb1Lm.js.map +1 -0
- package/dist-vue/_chunks/{PkChatbot-BmpFnkde.js → PkChatbot-BEnC7_hV.js} +8 -8
- package/dist-vue/_chunks/{PkChatbot-BmpFnkde.js.map → PkChatbot-BEnC7_hV.js.map} +1 -1
- package/dist-vue/_chunks/PkChatbotAudioTranscript-BUxBHanA.js +80 -0
- package/dist-vue/_chunks/PkChatbotAudioTranscript-BUxBHanA.js.map +1 -0
- package/dist-vue/_chunks/{PkChatbotAuth-Dolfz0pa.js → PkChatbotAuth-C0qfDOGh.js} +8 -8
- package/dist-vue/_chunks/{PkChatbotAuth-Dolfz0pa.js.map → PkChatbotAuth-C0qfDOGh.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotEmptyState-BaiGfaAD.js → PkChatbotEmptyState-DjmF3dcI.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotEmptyState-BaiGfaAD.js.map → PkChatbotEmptyState-DjmF3dcI.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotInput-BjfW_bML.js → PkChatbotInput-B8hKYdD9.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotInput-BjfW_bML.js.map → PkChatbotInput-B8hKYdD9.js.map} +1 -1
- package/dist-vue/_chunks/PkChatbotMessages-DnoohZxu.js +861 -0
- package/dist-vue/_chunks/PkChatbotMessages-DnoohZxu.js.map +1 -0
- package/dist-vue/_chunks/{PkChatbotStepPayload-CGAdiGR5.js → PkChatbotStepPayload-BGYwwXaT.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotStepPayload-CGAdiGR5.js.map → PkChatbotStepPayload-BGYwwXaT.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotStepToolDetail-DQsmXnKT.js → PkChatbotStepToolDetail-BH07XycE.js} +3 -3
- package/dist-vue/_chunks/{PkChatbotStepToolDetail-DQsmXnKT.js.map → PkChatbotStepToolDetail-BH07XycE.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotSteps-DzajeHKc.js → PkChatbotSteps-qyUOh42z.js} +6 -6
- package/dist-vue/_chunks/{PkChatbotSteps-DzajeHKc.js.map → PkChatbotSteps-qyUOh42z.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewChat-DZbQQNQn.js → PkChatbotViewChat-BM51ovrp.js} +7 -7
- package/dist-vue/_chunks/{PkChatbotViewChat-DZbQQNQn.js.map → PkChatbotViewChat-BM51ovrp.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewConversations-BXtTZ3kb.js → PkChatbotViewConversations-ClJLe1bm.js} +3 -3
- package/dist-vue/_chunks/{PkChatbotViewConversations-BXtTZ3kb.js.map → PkChatbotViewConversations-ClJLe1bm.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewFiles--wM5SVAl.js → PkChatbotViewFiles-Do6tpo9O.js} +3 -3
- package/dist-vue/_chunks/{PkChatbotViewFiles--wM5SVAl.js.map → PkChatbotViewFiles-Do6tpo9O.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewProfile-B8T0AQC8.js → PkChatbotViewProfile-590b78yi.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotViewProfile-B8T0AQC8.js.map → PkChatbotViewProfile-590b78yi.js.map} +1 -1
- package/dist-vue/_chunks/{PkStreamingMarkdown-D6y6g6vP.js → PkStreamingMarkdown-NWO3WTw9.js} +3 -3
- package/dist-vue/_chunks/{PkStreamingMarkdown-D6y6g6vP.js.map → PkStreamingMarkdown-NWO3WTw9.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolEditSpreadsheet-BkjEQag2.js → PkToolEditSpreadsheet-BnMSzlCi.js} +2 -2
- package/dist-vue/_chunks/{PkToolEditSpreadsheet-BkjEQag2.js.map → PkToolEditSpreadsheet-BnMSzlCi.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolRequestGeolocation-BWWUGKHJ.js → PkToolRequestGeolocation-B2UNj6dx.js} +2 -2
- package/dist-vue/_chunks/{PkToolRequestGeolocation-BWWUGKHJ.js.map → PkToolRequestGeolocation-B2UNj6dx.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolRequestOAuthConnection-DvvLZ8yi.js → PkToolRequestOAuthConnection-B262JqNh.js} +2 -2
- package/dist-vue/_chunks/{PkToolRequestOAuthConnection-DvvLZ8yi.js.map → PkToolRequestOAuthConnection-B262JqNh.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowArtifact-CP-dG3-Y.js → PkToolShowArtifact-Dr0NHXDG.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowArtifact-CP-dG3-Y.js.map → PkToolShowArtifact-Dr0NHXDG.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowContactForm-BK7B-Qzr.js → PkToolShowContactForm-BDm1w3UK.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowContactForm-BK7B-Qzr.js.map → PkToolShowContactForm-BDm1w3UK.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowDiagram-9THUQfbg.js → PkToolShowDiagram-DzE-X06t.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowDiagram-9THUQfbg.js.map → PkToolShowDiagram-DzE-X06t.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowForm-CjN-_-1j.js → PkToolShowForm-cKgWwvPD.js} +4 -4
- package/dist-vue/_chunks/{PkToolShowForm-CjN-_-1j.js.map → PkToolShowForm-cKgWwvPD.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowImageGallery-8cmWigYT.js → PkToolShowImageGallery-DsAQhyOq.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowImageGallery-8cmWigYT.js.map → PkToolShowImageGallery-DsAQhyOq.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowProductList-BxsK6LXl.js → PkToolShowProductList-OwGaM5qj.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowProductList-BxsK6LXl.js.map → PkToolShowProductList-OwGaM5qj.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowSources-BfWNsyLw.js → PkToolShowSources-BVOqH-ZV.js} +3 -3
- package/dist-vue/_chunks/{PkToolShowSources-BfWNsyLw.js.map → PkToolShowSources-BVOqH-ZV.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowSuggestedReply-_bH3Jikn.js → PkToolShowSuggestedReply-CF31zmck.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowSuggestedReply-_bH3Jikn.js.map → PkToolShowSuggestedReply-CF31zmck.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowVideo-2_EdyT_U.js → PkToolShowVideo-BAqSAfdq.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowVideo-2_EdyT_U.js.map → PkToolShowVideo-BAqSAfdq.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowWebPages-B0glenu5.js → PkToolShowWebPages-BeMJqIkW.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowWebPages-B0glenu5.js.map → PkToolShowWebPages-BeMJqIkW.js.map} +1 -1
- package/dist-vue/_chunks/{createChatbotApiClient-DgtSqixO.js → createChatbotApiClient-DmqgH9Ul.js} +3 -3
- package/dist-vue/_chunks/{createChatbotApiClient-DgtSqixO.js.map → createChatbotApiClient-DmqgH9Ul.js.map} +1 -1
- package/dist-vue/_chunks/message-BOiF6Bt5.js +59 -0
- package/dist-vue/_chunks/message-BOiF6Bt5.js.map +1 -0
- package/dist-vue/_chunks/{useChatbotStore-A33jT5Cp.js → useChatbotStore-CiF_gfIk.js} +656 -653
- package/dist-vue/_chunks/useChatbotStore-CiF_gfIk.js.map +1 -0
- package/dist-vue/_chunks/{utils-ByN6GORv.js → utils-DxuGvgWg.js} +37 -37
- package/dist-vue/_chunks/{utils-ByN6GORv.js.map → utils-DxuGvgWg.js.map} +1 -1
- package/dist-vue/api.js +1 -1
- package/dist-vue/composables.js +15 -5
- package/dist-vue/composables.js.map +1 -1
- package/dist-vue/index.js +4754 -4749
- package/dist-vue/index.js.map +1 -1
- package/dist-vue/locales.js +52 -40
- package/dist-vue/packages/components/src/chat/PkChatbotAudioTranscript.d.ts +13 -0
- package/dist-vue/packages/components/src/chat/PkChatbotMessages.d.ts +2 -2
- package/dist-vue/packages/composable/src/chatbot/useChatbotStore.d.ts +1 -1
- package/dist-vue/packages/models/src/schema/Agent.d.ts +4 -4
- package/dist-vue/packages/models/src/schema/Media.d.ts +21 -0
- package/dist-vue/packages/models/src/schema/Tabular.d.ts +1 -1
- package/dist-vue/style.css +1 -1
- package/package.json +1 -1
- package/dist/_chunks/Agent-BxyaZeuL.js.map +0 -1
- package/dist/_chunks/PkStreamingMarkdown-B8mvCNou.js.map +0 -1
- package/dist-vue/_chunks/Media-Cv7ou2tP.js.map +0 -1
- package/dist-vue/_chunks/PkChatbotMessages-CztL_AMB.js +0 -837
- package/dist-vue/_chunks/PkChatbotMessages-CztL_AMB.js.map +0 -1
- package/dist-vue/_chunks/message-RohfrdWS.js +0 -33
- package/dist-vue/_chunks/message-RohfrdWS.js.map +0 -1
- package/dist-vue/_chunks/useChatbotStore-A33jT5Cp.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useChatbotStore-CiF_gfIk.js","names":["marker$16","name$15","marker$15","name$14","marker$14","name$13","marker$13","name$12","marker$12","name$11","marker$11","InvalidArgumentError","name$10","marker$10","name$9","marker$9","name$8","marker$8","name$7","marker$7","name$6","marker$6","name$5","marker$5","name$4","marker$4","name$3","marker$3","name$2","marker$2","name$1","marker$1","symbol$1","name","marker","name$1","marker$1","InvalidArgumentError","EventSourceParserStream$1","name","marker","AISDKError$1","DownloadError$1","enum$1","instanceof$1","null$1","createIdGenerator$1","zodSchema$1","APICallError$1","UnsupportedFunctionalityError$1","EmptyResponseBodyError$1","parseJsonEventStream$1","generateId$1","generateId","webPreset","useSWRV","useSWRV","swrv","unknown","toJSONSchema","safeParseAsync","union","number","record","never","looseObject","_instanceof","custom","literal","array","_enum","boolean","discriminatedUnion","object","string","isUserAnsweredTool","TOOL_TERMINAL_STATES","createChatbotApiClient","logger","getTextPart","withAudioTranscripts","useSafeLocalStorage","collectDeviceContext","connection","uaData","collectGeolocation","resolve","reject","latitude","longitude","accuracy","reverseGeocode","marker$16$2","symbol$16","AISDKError","message","name","cause","error","markerSymbol","marker","name$14$2","marker$14$2","symbol$14","APICallError","statusCode","url","requestBodyValues","responseHeaders","responseBody","isRetryable","data","name$13$2","marker$13$2","symbol$13","EmptyResponseBodyError","getErrorMessage","name$11$2","marker$11$2","symbol$11","InvalidArgumentError$1","argument","name$8$2","marker$8$2","symbol$8","JSONParseError","text","name$1$25","marker$1$25","symbol$1$1","TypeValidationError","contextPrefix","context","parts","value","name$26","marker$26","symbol","UnsupportedFunctionalityError","functionality","ParseError","options","LF","CR","SPACE","noop","createParser","config","pendingFragments","pendingFragmentsLength","isFirstChunk","id","dataLines","eventType","terminated","feed","chunk","trailing2","processLines","checkBufferSize","input","trailing","maxBufferSize","onError","searchIndex","lfIndex","onEvent","firstCharCode","isDataPrefix","valueStart","parseLine","crIndex","lineEnd","start","end","value2","isEventPrefix","onComment","line2","line","fieldSeparatorIndex","field","offset","processField","onRetry","dispatchEvent","reset","incompleteLine","i","EventSourceParserStream","parser","event","controller","btoa$1","atob$2","normalizeHeaders","headers","normalized","key","createIdGenerator","generator","alphabetLength","alphabet","chars","size","prefix","separator","generateId","isBuffer","suspectProtoRx","suspectConstructorRx","_parse","obj","filter","next","nodes","node","secureJsonParse","stackTraceLimit","addAdditionalPropertiesToJsonSchema","jsonSchema","additionalProperties","visit","properties","definitions","def","ignoreOverride","defaultOptions","getDefaultOptions","parseAnyDef","parseArrayDef","res","parseDef","refs","parseBigintDef","check","parseBooleanDef","parseBrandedDef","_def","parseCatchDef","parseDateDef","strategy","overrideDateStrategy","item","integerDateParser","parseDefaultDef","parseEffectsDef","parseEnumDef","isJsonSchema7AllOfType","type","parseIntersectionDef","allOf","x","mergedAllOf","schema","nestedSchema","_additionalProperties","rest","parseLiteralDef","parsedType","emojiRegex","zodPatterns","parseStringDef","escapeLiteralCheckValue","addFormat","addPattern","escapeNonAlphaNumeric","ALPHA_NUMERIC","result","source","stringifyRegExpWithFlags","regex","flags","pattern","isEscaped","inCharGroup","inCharRange","parseRecordDef","_type","keyType","parseMapDef","parseNativeEnumDef","actualValues","parsedTypes","values","parseNeverDef","parseNullDef","primitiveMappings","parseUnionDef","types","acc","uniqueTypes","a","asAnyOf","anyOf","parseNullableDef","base","parseNumberDef","parseObjectDef","required","shape","propName","propDef","propOptional","safeIsOptional","parsedDef","decideAdditionalProperties","parseOptionalDef","innerSchema","parsePipelineDef","inputSchema","parsePromiseDef","parseSetDef","parseTupleDef","parseUndefinedDef","parseUnknownDef","parseReadonlyDef","selectParser","typeName","getRelativePath","pathA","pathB","seenItem","overrideResult","forceResolution","seenSchema","get$ref","newItem","jsonSchemaOrGetter","addMeta","postProcessResult","index","getRefs","_options","currentPath","zod3ToJsonSchema","main","title","combined","schemaSymbol","lazySchema","createSchema","isSchema","asSchema","zodSchema","standardSchema","hasStandardJsonSchema","zod3Schema","useReferences","zod4Schema","isZod4Schema","validateTypes","safeValidateTypes","actualSchema","safeParseJSON","parseJsonEventStream","stream","name$23","marker$23","symbol$23","InvalidArgumentError","parameter","name$5","marker$5","symbol$5","UIMessageStreamError","chunkType","chunkId","mergeObjects","overrides","overridesValue","baseValue","isSourceObject","isTargetObject","z","_null","jsonValueSchema","providerMetadataSchema","fileInlineDataSchema","providerReferenceSchema$1","textPartSchema","imagePartSchema","taggedFileDataSchema","taggedReasoningFileDataSchema","filePartSchema","reasoningPartSchema","customPartSchema","reasoningFilePartSchema","toolCallPartSchema","outputSchema","toolResultPartSchema","toolApprovalRequestSchema","toolApprovalResponseSchema","systemModelMessageSchema","userModelMessageSchema","assistantModelMessageSchema","toolModelMessageSchema","fixJson","stack","lastValidIndex","literalStart","unicodeEscapeDigits","isHexDigit","char","processValueStart","swapState","processAfterObjectValue","processAfterArrayValue","partialLiteral","parsePartialJson","jsonText","toolMetadataSchema$1","uiMessageChunkSchema","isDataUIMessageChunk","createIdMap","isStaticToolUIPart","part","isDynamicToolUIPart","isToolUIPart","getStaticToolName","createStreamingUIMessageState","lastMessage","messageId","partialToolCalls","lastStepStartIndex","staticToolIndex","processUIMessageStream","runUpdateMessageJob","getCurrentStepParts","state","currentStepStartIndex","getCurrentStepToolInvocations","getToolInvocation","toolInvocation","invocation","toolCallId","getToolInvocationByApprovalId","approvalId","updateToolPart","existingPart","anyOptions","anyPart","providerMetadata","resultPart","updateDynamicToolPart","updateMessageMetadata","metadata","mergedMetadata","messageMetadataSchema","textPart","write","customPart","reasoningPart","toolInvocations","partialToolCall","partialArgs","onToolCall","p","approval","currentStepParts","resetStateOnFirstMessageStart","resetStateOnMessageIdChange","dataPartSchemas","partIdx","actualPartIdx","dataChunk","existingUIPart","chunkArg","onData","consumeStream","reader","cancelOnAbort","abortSignal","done","createResolvablePromise","rej","atob$1","SerialJobExecutor","job","createUIApiCallError","response","fallbackMessage","convertFileListToFileUIParts","files","file","readerEvent","appendPathToUrl","queryOrFragmentStart","urlPath","suffix","path","HttpChatTransport","api","credentials","body","fetch","prepareSendMessagesRequest","prepareReconnectToStreamRequest","resolvedBody","resolvedHeaders","resolvedCredentials","baseHeaders","preparedRequest","DefaultChatTransport","AbstractChat","generateId$3","candidate","pendingApprovalMessageIndex","uiMessage","abortController","fileParts","messageIndex","m","messages","updatePart","shouldSend","existingApproval","toolPart","activeResumeRequest","activeResponse","transport","onFinish","sendAutomaticallyWhen","status","stopGeneration","startedWhileStopping","request","consumesPendingApproval","completion","trigger","isCurrentRequest","clearActiveResumeRequest","resumeStream","reconnect","err","responseMessageIndex","responseMessage","resumableResponseMessage","usesEarlierAssistantMessage","isAbort","isDisconnect","isError","updateStatus","lastAssistantMessageIsCompleteWithApprovalResponses","lastIndex","lastStepToolInvocations","table","counter","hash","args","_hash","serializeKeyDefault","SWRVCache","ttl","_key","k","timeToLive","now","v","_this","serializedKey","isOnline","isDocumentVisible","web_preset_default","__assign","s","n","t","__awaiter","adopt","P","fulfilled","rejected","\"throw\"","step","thisArg","_arguments","__generator","_","f","y","g","verb","\"return\"","op","__read","o","r","ar","e","__spreadArray","pack","l","from","to","DATA_CACHE","REF_CACHE","PROMISES_CACHE","defaultConfig","setRefCache","refCacheItem","theRef","onErrorRetry","errorRetryCount","count","timeout","resolveRetryFlag","_b","_a","shouldRetry","mutate","cache","isValidating","err_1","newData","stateRef","refs_1","isPromise","idx","useSWRV$2","_i","fn","unmounted","isHydrated","getCurrentScope","IS_SERVER","keyRef","ref","reactive","revalidate","isFirstFetch","keyVal","cacheItem","fetcher","shouldRevalidate","opts","promiseFromCache","fetcherArgs","newPromise","configAllows","optsAllows","shouldRetryOnError","revalidateCall","timer","tick_1","isReadonly","val","toRefs","esm_default","VueChatState$1","Chat","init","VOICE_LINE_ID_PREFIX","normalizeSpoken","spokenText","SHORTEST_MATCHABLE_LINE","unpersistedVoiceLines","server","persisted","shown","match","other","partToolName","lastAssistantMessageIsCompleteWithAnsweredClientTools","last","userAnsweredParts","useChatbotStore","defineStore","agentId","useI18n","baseUrl","basePath","agentIdRef","agentType","userId","agentInterface","agentModel","agentTools","revisedAnswers","model","actionsInput","agentFileUpload","agentVoice","fallbackModels","gatewayOptions","externalContext","systemTheme","hideWelcomeMessage","prefersDark","usePreferredDark","isDark","computed","theme","isReasoningAgent","actions","action","storageId","localChatId","chatError","isConversationBlocked","isConversationBlockedError","isEntityNotFoundError","parsed","handleChatError","pendingMessages","chat","lastUserMessage","lastUserText","apiClient","storedGeolocation","buildDeviceContext","msgs","conversations","c","loadConversations","initialMessageResolved","locale","te","welcomeMessageId","welcomeMessage","resolveInFlight","msg","fp","storedFileName","inputMessagePlaceholder","isLoadingConversations","chatFiles","isLoadingChatFiles","activeView","messageFeedbacks","feedbackDialogMessage","isFeedbackSubmitting","isFeedbackSubmitted","feedbackSubmitError","isLeadSubmitted","isLoadingSubmitLead","submitLeadError","pendingAttachments","lastSubmittedInput","messageCountBeforeSubmit","loadChatFiles","chatId","getChatFileUrl","documentId","inline","getChatFilePreviewUrl","deleteChatFile","removed","rootId","loadChat","isTurnInFlight","refreshSequence","refreshApplied","refreshMessages","mine","pending","appendMessage","loadMessageFeedbacks","upsertLocalFeedback","feedback","extractFeedbackContext","msgList","assistantMessage","prevUser","initialize","lat","lon","geo","handleSubmit","att","startNewChat","sendMessage","clearPendingAttachments","trimmed","send","shouldRollback","revokeAll","navigate","regenerate","addToolOutput","params","output","addToolApprovalResponse","sentFileCount","maxFilesPerMessage","maxFilesPerChat","remainingAttachmentSlots","isAttachmentLimitReached","fileLimitError","clearFileLimitError","reached","handleFileSelect","attachment","mediaSource","submitVote","onUpvote","onDownvote","onFeedback","onFeedbackSubmit","onLeadSubmit","renameChatTitle","updated","deleteChat","view","boundUserId","isChatReadable","probe","watch","newUserId","previousUserId","verifiedChatId","isChatOwnedByNewUser"],"sources":["../../../../packages/utils/src/device-context.ts","../../../../node_modules/.pnpm/@ai-sdk+provider@4.0.26/node_modules/@ai-sdk/provider/dist/index.js","../../../../node_modules/.pnpm/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/index.js","../../../../node_modules/.pnpm/eventsource-parser@3.1.0/node_modules/eventsource-parser/dist/stream.js","../../../../node_modules/.pnpm/@ai-sdk+provider-utils@5.0.58_zod@4.6.5/node_modules/@ai-sdk/provider-utils/dist/index.js","../../../../node_modules/.pnpm/ai@7.0.137_zod@4.6.5/node_modules/ai/dist/index.js","../../../../node_modules/.pnpm/swrv@1.2.0_vue@3.5.43_typescript@6.0.3_/node_modules/swrv/esm/lib/hash.js","../../../../node_modules/.pnpm/swrv@1.2.0_vue@3.5.43_typescript@6.0.3_/node_modules/swrv/esm/cache/index.js","../../../../node_modules/.pnpm/swrv@1.2.0_vue@3.5.43_typescript@6.0.3_/node_modules/swrv/esm/lib/web-preset.js","../../../../node_modules/.pnpm/swrv@1.2.0_vue@3.5.43_typescript@6.0.3_/node_modules/swrv/esm/use-swrv.js","../../../../node_modules/.pnpm/swrv@1.2.0_vue@3.5.43_typescript@6.0.3_/node_modules/swrv/esm/index.js","../../../../node_modules/.pnpm/@ai-sdk+vue@4.0.137_vue@3.5.43_typescript@6.0.3__zod@4.6.5/node_modules/@ai-sdk/vue/dist/index.js","../../../../packages/composable/src/chatbot/useChatbotStore.ts"],"sourcesContent":["interface NetworkInformation {\n type?: string\n effectiveType?: string\n downlink?: number\n rtt?: number\n saveData?: boolean\n}\n\ninterface NavigatorUAData {\n platform?: string\n}\n\n/**\n * Collects client-side device context information useful for chatbot interactions.\n * No additional permissions are required — all values are available by default in the browser.\n */\nexport function collectDeviceContext() {\n const connection = (\n navigator as Navigator & { connection?: NetworkInformation }\n ).connection\n\n const uaData = (\n navigator as Navigator & { userAgentData?: NavigatorUAData }\n ).userAgentData\n\n return {\n dateTime: new Date().toISOString(),\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n language: navigator.language,\n languages: [...navigator.languages],\n url: window.location.href,\n pathname: window.location.pathname,\n pageTitle: document.title,\n referrer: document.referrer || undefined,\n screenWidth: screen.width,\n screenHeight: screen.height,\n viewportWidth: window.innerWidth,\n viewportHeight: window.innerHeight,\n devicePixelRatio: window.devicePixelRatio,\n maxTouchPoints: navigator.maxTouchPoints,\n hardwareConcurrency: navigator.hardwareConcurrency,\n deviceMemory: (navigator as Navigator & { deviceMemory?: number })\n .deviceMemory,\n platform: uaData?.platform,\n connectionType: connection?.type,\n connectionEffectiveType: connection?.effectiveType,\n connectionDownlink: connection?.downlink,\n connectionRtt: connection?.rtt,\n saveData: connection?.saveData,\n darkMode: window.matchMedia('(prefers-color-scheme: dark)').matches,\n reducedMotion: window.matchMedia('(prefers-reduced-motion: reduce)')\n .matches,\n historyLength: window.history.length,\n }\n}\n\nexport type GeolocationData = {\n geolocationLatitude: number\n geolocationLongitude: number\n geolocationAccuracy?: number\n geolocationCity?: string\n}\n\nexport type ReverseGeocodeFn = (\n lat: number,\n lon: number,\n) => Promise<string | undefined>\n\n/**\n * Collects geolocation data if the user has already granted permission.\n * Uses the Permissions API to avoid triggering a browser prompt.\n * Returns null if permission is not granted or geolocation is unavailable.\n * @param reverseGeocode - optional callback to resolve city name from coordinates (e.g. via backend proxy)\n */\nexport async function collectGeolocation(\n reverseGeocode?: ReverseGeocodeFn,\n): Promise<GeolocationData | null> {\n if (!navigator.geolocation || !navigator.permissions) {\n return null\n }\n\n try {\n const permission = await navigator.permissions.query({\n name: 'geolocation',\n })\n if (permission.state !== 'granted') {\n return null\n }\n\n const position = await new Promise<GeolocationPosition>(\n (resolve, reject) => {\n navigator.geolocation.getCurrentPosition(resolve, reject, {\n timeout: 10_000,\n })\n },\n )\n\n const { latitude, longitude, accuracy } = position.coords\n const city = reverseGeocode\n ? await reverseGeocode(latitude, longitude).catch(() => undefined)\n : undefined\n\n return {\n geolocationLatitude: latitude,\n geolocationLongitude: longitude,\n geolocationAccuracy: accuracy,\n geolocationCity: city,\n }\n } catch {\n return null\n }\n}\n","//#region src/errors/ai-sdk-error.ts\n/**\n* Symbol used for identifying AI SDK Error instances.\n* Enables checking if an error is an instance of AISDKError across package versions.\n*/\nconst marker$16 = \"vercel.ai.error\";\nconst symbol$16 = Symbol.for(marker$16);\n/**\n* Custom error class for AI SDK related errors.\n* @extends Error\n*/\nvar AISDKError = class AISDKError extends Error {\n\t/**\n\t* Creates an AI SDK Error.\n\t*\n\t* @param {Object} params - The parameters for creating the error.\n\t* @param {string} params.name - The name of the error.\n\t* @param {string} params.message - The error message.\n\t* @param {unknown} [params.cause] - The underlying cause of the error.\n\t*/\n\tconstructor({ name, message, cause }) {\n\t\tsuper(message);\n\t\tthis[symbol$16] = true;\n\t\tthis.name = name;\n\t\tthis.cause = cause;\n\t}\n\t/**\n\t* Checks if the given error is an AI SDK Error.\n\t* @param {unknown} error - The error to check.\n\t* @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n\t*/\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$16);\n\t}\n\tstatic hasMarker(error, marker) {\n\t\tconst markerSymbol = Symbol.for(marker);\n\t\treturn error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n\t}\n};\n//#endregion\n//#region src/errors/decision-unsupported-question-type-error.ts\nconst name$15 = \"AI_DecisionUnsupportedQuestionTypeError\";\nconst marker$15 = `vercel.ai.error.${name$15}`;\nconst symbol$15 = Symbol.for(marker$15);\n/**\n* A decision model does not support the type of a requested question.\n*/\nvar DecisionUnsupportedQuestionTypeError = class extends AISDKError {\n\tconstructor({ questionId, questionType, provider, modelId, message = `Question \"${questionId}\" has type \"${questionType}\", which is not supported by provider \"${provider}\" and model \"${modelId}\".` }) {\n\t\tsuper({\n\t\t\tname: name$15,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$15] = true;\n\t\tthis.questionId = questionId;\n\t\tthis.questionType = questionType;\n\t\tthis.provider = provider;\n\t\tthis.modelId = modelId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$15);\n\t}\n};\n//#endregion\n//#region src/errors/api-call-error.ts\nconst name$14 = \"AI_APICallError\";\nconst marker$14 = `vercel.ai.error.${name$14}`;\nconst symbol$14 = Symbol.for(marker$14);\nvar APICallError = class extends AISDKError {\n\tconstructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {\n\t\tsuper({\n\t\t\tname: name$14,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$14] = true;\n\t\tthis.url = url;\n\t\tthis.requestBodyValues = requestBodyValues;\n\t\tthis.statusCode = statusCode;\n\t\tthis.responseHeaders = responseHeaders;\n\t\tthis.responseBody = responseBody;\n\t\tthis.isRetryable = isRetryable;\n\t\tthis.data = data;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$14);\n\t}\n};\n//#endregion\n//#region src/errors/empty-response-body-error.ts\nconst name$13 = \"AI_EmptyResponseBodyError\";\nconst marker$13 = `vercel.ai.error.${name$13}`;\nconst symbol$13 = Symbol.for(marker$13);\nvar EmptyResponseBodyError = class extends AISDKError {\n\tconstructor({ message = \"Empty response body\" } = {}) {\n\t\tsuper({\n\t\t\tname: name$13,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$13] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$13);\n\t}\n};\n//#endregion\n//#region src/errors/decision-refusal-error.ts\nconst name$12 = \"AI_DecisionRefusalError\";\nconst marker$12 = `vercel.ai.error.${name$12}`;\nconst symbol$12 = Symbol.for(marker$12);\n/**\n* A decision model declined to answer one or more questions.\n*/\nvar DecisionRefusalError = class extends AISDKError {\n\tconstructor({ questionIds, provider, modelId, message = `Decision model \"${modelId}\" from provider \"${provider}\" refused ${questionIds.length === 1 ? \"question\" : \"questions\"} ${questionIds.map((id) => JSON.stringify(id)).join(\", \")}.` }) {\n\t\tsuper({\n\t\t\tname: name$12,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$12] = true;\n\t\tthis.questionIds = questionIds;\n\t\tthis.provider = provider;\n\t\tthis.modelId = modelId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$12);\n\t}\n};\n//#endregion\n//#region src/errors/get-error-message.ts\nfunction getErrorMessage(error) {\n\tif (error == null) return \"unknown error\";\n\tif (typeof error === \"string\") return error;\n\tif (error instanceof Error) return error.toString();\n\treturn JSON.stringify(error);\n}\n//#endregion\n//#region src/errors/invalid-argument-error.ts\nconst name$11 = \"AI_InvalidArgumentError\";\nconst marker$11 = `vercel.ai.error.${name$11}`;\nconst symbol$11 = Symbol.for(marker$11);\n/**\n* A function argument is invalid.\n*/\nvar InvalidArgumentError = class extends AISDKError {\n\tconstructor({ message, cause, argument }) {\n\t\tsuper({\n\t\t\tname: name$11,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$11] = true;\n\t\tthis.argument = argument;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$11);\n\t}\n};\n//#endregion\n//#region src/errors/invalid-prompt-error.ts\nconst name$10 = \"AI_InvalidPromptError\";\nconst marker$10 = `vercel.ai.error.${name$10}`;\nconst symbol$10 = Symbol.for(marker$10);\n/**\n* A prompt is invalid. This error should be thrown by providers when they cannot\n* process a prompt.\n*/\nvar InvalidPromptError = class extends AISDKError {\n\tconstructor({ prompt, message, cause }) {\n\t\tsuper({\n\t\t\tname: name$10,\n\t\t\tmessage: `Invalid prompt: ${message}`,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$10] = true;\n\t\tthis.prompt = prompt;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$10);\n\t}\n};\n//#endregion\n//#region src/errors/invalid-response-data-error.ts\nconst name$9 = \"AI_InvalidResponseDataError\";\nconst marker$9 = `vercel.ai.error.${name$9}`;\nconst symbol$9 = Symbol.for(marker$9);\n/**\n* Server returned a response with invalid data content.\n* This should be thrown by providers when they cannot parse the response from the API.\n*/\nvar InvalidResponseDataError = class extends AISDKError {\n\tconstructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {\n\t\tsuper({\n\t\t\tname: name$9,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$9] = true;\n\t\tthis.data = data;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$9);\n\t}\n};\n//#endregion\n//#region src/errors/json-parse-error.ts\nconst name$8 = \"AI_JSONParseError\";\nconst marker$8 = `vercel.ai.error.${name$8}`;\nconst symbol$8 = Symbol.for(marker$8);\nvar JSONParseError = class extends AISDKError {\n\tconstructor({ text, cause }) {\n\t\tsuper({\n\t\t\tname: name$8,\n\t\t\tmessage: `JSON parsing failed: Text: ${text}.\\nError message: ${getErrorMessage(cause)}`,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$8] = true;\n\t\tthis.text = text;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$8);\n\t}\n};\n//#endregion\n//#region src/errors/load-api-key-error.ts\nconst name$7 = \"AI_LoadAPIKeyError\";\nconst marker$7 = `vercel.ai.error.${name$7}`;\nconst symbol$7 = Symbol.for(marker$7);\nvar LoadAPIKeyError = class extends AISDKError {\n\tconstructor({ message }) {\n\t\tsuper({\n\t\t\tname: name$7,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$7] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$7);\n\t}\n};\n//#endregion\n//#region src/errors/load-setting-error.ts\nconst name$6 = \"AI_LoadSettingError\";\nconst marker$6 = `vercel.ai.error.${name$6}`;\nconst symbol$6 = Symbol.for(marker$6);\nvar LoadSettingError = class extends AISDKError {\n\tconstructor({ message }) {\n\t\tsuper({\n\t\t\tname: name$6,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$6] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$6);\n\t}\n};\n//#endregion\n//#region src/errors/no-content-generated-error.ts\nconst name$5 = \"AI_NoContentGeneratedError\";\nconst marker$5 = `vercel.ai.error.${name$5}`;\nconst symbol$5 = Symbol.for(marker$5);\n/**\n* Thrown when the AI provider fails to generate any content.\n*/\nvar NoContentGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No content generated.\" } = {}) {\n\t\tsuper({\n\t\t\tname: name$5,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$5] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$5);\n\t}\n};\n//#endregion\n//#region src/errors/no-such-model-error.ts\nconst name$4 = \"AI_NoSuchModelError\";\nconst marker$4 = `vercel.ai.error.${name$4}`;\nconst symbol$4 = Symbol.for(marker$4);\nvar NoSuchModelError = class extends AISDKError {\n\tconstructor({ errorName = name$4, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {\n\t\tsuper({\n\t\t\tname: errorName,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$4] = true;\n\t\tthis.modelId = modelId;\n\t\tthis.modelType = modelType;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$4);\n\t}\n};\n//#endregion\n//#region src/errors/no-such-provider-reference-error.ts\nconst name$3 = \"AI_NoSuchProviderReferenceError\";\nconst marker$3 = `vercel.ai.error.${name$3}`;\nconst symbol$3 = Symbol.for(marker$3);\n/**\n* Thrown when a provider reference cannot be resolved because the specified\n* provider is not found in the provider reference mapping.\n*/\nvar NoSuchProviderReferenceError = class extends AISDKError {\n\tconstructor({ provider, reference, message = `No provider reference found for provider '${provider}'. Available providers: ${Object.keys(reference).join(\", \")}` }) {\n\t\tsuper({\n\t\t\tname: name$3,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$3] = true;\n\t\tthis.provider = provider;\n\t\tthis.reference = reference;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$3);\n\t}\n};\n//#endregion\n//#region src/errors/too-many-embedding-values-for-call-error.ts\nconst name$2 = \"AI_TooManyEmbeddingValuesForCallError\";\nconst marker$2 = `vercel.ai.error.${name$2}`;\nconst symbol$2 = Symbol.for(marker$2);\nvar TooManyEmbeddingValuesForCallError = class extends AISDKError {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: name$2,\n\t\t\tmessage: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n\t\t});\n\t\tthis[symbol$2] = true;\n\t\tthis.provider = options.provider;\n\t\tthis.modelId = options.modelId;\n\t\tthis.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n\t\tthis.values = options.values;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$2);\n\t}\n};\n//#endregion\n//#region src/errors/type-validation-error.ts\nconst name$1 = \"AI_TypeValidationError\";\nconst marker$1 = `vercel.ai.error.${name$1}`;\nconst symbol$1 = Symbol.for(marker$1);\nvar TypeValidationError = class TypeValidationError extends AISDKError {\n\tconstructor({ value, cause, context }) {\n\t\tlet contextPrefix = \"Type validation failed\";\n\t\tif (context?.field) contextPrefix += ` for ${context.field}`;\n\t\tif (context?.entityName || context?.entityId) {\n\t\t\tcontextPrefix += \" (\";\n\t\t\tconst parts = [];\n\t\t\tif (context.entityName) parts.push(context.entityName);\n\t\t\tif (context.entityId) parts.push(`id: \"${context.entityId}\"`);\n\t\t\tcontextPrefix += parts.join(\", \");\n\t\t\tcontextPrefix += \")\";\n\t\t}\n\t\tsuper({\n\t\t\tname: name$1,\n\t\t\tmessage: `${contextPrefix}: Value: ${JSON.stringify(value)}.\\nError message: ${getErrorMessage(cause)}`,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$1] = true;\n\t\tthis.value = value;\n\t\tthis.context = context;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$1);\n\t}\n\t/**\n\t* Wraps an error into a TypeValidationError.\n\t* If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n\t* Otherwise, it creates a new TypeValidationError.\n\t*\n\t* @param {Object} params - The parameters for wrapping the error.\n\t* @param {unknown} params.value - The value that failed validation.\n\t* @param {unknown} params.cause - The original error or cause of the validation failure.\n\t* @param {TypeValidationContext} params.context - Optional context about what is being validated.\n\t* @returns {TypeValidationError} A TypeValidationError instance.\n\t*/\n\tstatic wrap({ value, cause, context }) {\n\t\tif (TypeValidationError.isInstance(cause) && cause.value === value && cause.context?.field === context?.field && cause.context?.entityName === context?.entityName && cause.context?.entityId === context?.entityId) return cause;\n\t\treturn new TypeValidationError({\n\t\t\tvalue,\n\t\t\tcause,\n\t\t\tcontext\n\t\t});\n\t}\n};\n//#endregion\n//#region src/errors/unsupported-functionality-error.ts\nconst name = \"AI_UnsupportedFunctionalityError\";\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\nvar UnsupportedFunctionalityError = class extends AISDKError {\n\tconstructor({ functionality, message = `'${functionality}' functionality not supported.` }) {\n\t\tsuper({\n\t\t\tname,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol] = true;\n\t\tthis.functionality = functionality;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker);\n\t}\n};\n//#endregion\n//#region src/errors/index.ts\n/** @deprecated Use `Experimental_DecisionUnsupportedQuestionTypeError` instead. */\nconst Experimental_EvaluationUnsupportedQuestionTypeError = DecisionUnsupportedQuestionTypeError;\n//#endregion\n//#region src/json-value/is-json.ts\nfunction isJSONValue(value) {\n\tif (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") return true;\n\tif (Array.isArray(value)) return value.every(isJSONValue);\n\tif (typeof value === \"object\") return Object.entries(value).every(([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val)));\n\treturn false;\n}\nfunction isJSONArray(value) {\n\treturn Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n\treturn value != null && typeof value === \"object\" && Object.entries(value).every(([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val)));\n}\n//#endregion\nexport { AISDKError, APICallError, EmptyResponseBodyError, DecisionRefusalError as Experimental_DecisionRefusalError, DecisionUnsupportedQuestionTypeError as Experimental_DecisionUnsupportedQuestionTypeError, Experimental_EvaluationUnsupportedQuestionTypeError, InvalidArgumentError, InvalidPromptError, InvalidResponseDataError, JSONParseError, LoadAPIKeyError, LoadSettingError, NoContentGeneratedError, NoSuchModelError, NoSuchProviderReferenceError, TooManyEmbeddingValuesForCallError, TypeValidationError, UnsupportedFunctionalityError, getErrorMessage, isJSONArray, isJSONObject, isJSONValue };\n\n//# sourceMappingURL=index.js.map","class ParseError extends Error {\n constructor(message, options) {\n super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n }\n}\nconst LF = 10, CR = 13, SPACE = 32;\nfunction noop(_arg) {\n}\nfunction createParser(config) {\n if (typeof config == \"function\")\n throw new TypeError(\n \"`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?\"\n );\n const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];\n let pendingFragmentsLength = 0, isFirstChunk = !0, id, data = \"\", dataLines = 0, eventType, terminated = !1;\n function feed(chunk) {\n if (terminated)\n throw new Error(\n \"Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.\"\n );\n if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {\n const trailing2 = processLines(chunk);\n trailing2 !== \"\" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();\n return;\n }\n if (chunk.indexOf(`\n`) === -1 && chunk.indexOf(\"\\r\") === -1) {\n pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();\n return;\n }\n pendingFragments.push(chunk);\n const input = pendingFragments.join(\"\");\n pendingFragments.length = 0, pendingFragmentsLength = 0;\n const trailing = processLines(input);\n trailing !== \"\" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();\n }\n function checkBufferSize() {\n maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = !0, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, onError(\n new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n type: \"max-buffer-size-exceeded\"\n })\n )));\n }\n function processLines(chunk) {\n let searchIndex = 0;\n if (chunk.indexOf(\"\\r\") === -1) {\n let lfIndex = chunk.indexOf(`\n`, searchIndex);\n for (; lfIndex !== -1; ) {\n if (searchIndex === lfIndex) {\n dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = \"\", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n continue;\n }\n const firstCharCode = chunk.charCodeAt(searchIndex);\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n onEvent({ id, event: eventType, data: value }), id = void 0, data = \"\", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`\n`, searchIndex);\n continue;\n }\n data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(\n chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n lfIndex\n ) || void 0 : parseLine(chunk, searchIndex, lfIndex);\n searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n }\n return chunk.slice(searchIndex);\n }\n for (; searchIndex < chunk.length; ) {\n const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)\n break;\n parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;\n }\n return chunk.slice(searchIndex);\n }\n function parseLine(chunk, start, end) {\n if (start === end) {\n dispatchEvent();\n return;\n }\n const firstCharCode = chunk.charCodeAt(start);\n if (isDataPrefix(chunk, start, firstCharCode)) {\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);\n data = dataLines === 0 ? value2 : `${data}\n${value2}`, dataLines++;\n return;\n }\n if (isEventPrefix(chunk, start, firstCharCode)) {\n eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;\n return;\n }\n if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {\n const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n id = value2.includes(\"\\0\") ? void 0 : value2;\n return;\n }\n if (firstCharCode === 58) {\n if (onComment) {\n const line2 = chunk.slice(start, end);\n onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n }\n return;\n }\n const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(\":\");\n if (fieldSeparatorIndex === -1) {\n processField(line, \"\", line);\n return;\n }\n const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n }\n function processField(field, value, line) {\n switch (field) {\n case \"event\":\n eventType = value || void 0;\n break;\n case \"data\":\n data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n break;\n case \"id\":\n id = value.includes(\"\\0\") ? void 0 : value;\n break;\n case \"retry\":\n /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: \"invalid-retry\",\n value,\n line\n })\n );\n break;\n default:\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n { type: \"unknown-field\", field, value, line }\n )\n );\n break;\n }\n }\n function dispatchEvent() {\n dataLines > 0 && onEvent({\n id,\n event: eventType,\n data\n }), id = void 0, data = \"\", dataLines = 0, eventType = void 0;\n }\n function reset(options = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join(\"\");\n parseLine(incompleteLine, 0, incompleteLine.length);\n }\n isFirstChunk = !0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = !1;\n }\n return { feed, reset };\n}\nfunction isDataPrefix(chunk, i, firstCharCode) {\n return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;\n}\nfunction isEventPrefix(chunk, i, firstCharCode) {\n return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;\n}\nexport {\n ParseError,\n createParser\n};\n//# sourceMappingURL=index.js.map\n","import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {\n let parser;\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event);\n },\n onError(error) {\n typeof onError == \"function\" && onError(error), (onError === \"terminate\" || error.type === \"max-buffer-size-exceeded\") && controller.error(error);\n },\n onRetry,\n onComment,\n maxBufferSize\n });\n },\n transform(chunk) {\n parser.feed(chunk);\n }\n });\n }\n}\nexport {\n EventSourceParserStream,\n ParseError\n};\n//# sourceMappingURL=stream.js.map\n","import { AISDKError, APICallError, EmptyResponseBodyError, InvalidArgumentError, InvalidResponseDataError, JSONParseError, LoadAPIKeyError, LoadSettingError, NoSuchProviderReferenceError, TypeValidationError, UnsupportedFunctionalityError, getErrorMessage } from \"@ai-sdk/provider\";\nimport { safeParseAsync } from \"zod/v4\";\nimport { toJSONSchema } from \"zod/v4/core\";\nimport { EventSourceParserStream, EventSourceParserStream as EventSourceParserStream$1 } from \"eventsource-parser/stream\";\nimport { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from \"@workflow/serde\";\n//#region src/as-array.ts\n/**\n* Normalizes a possibly undefined or non-array value into an array.\n*/\nfunction asArray(value) {\n\treturn value === void 0 ? [] : Array.isArray(value) ? value : [value];\n}\n//#endregion\n//#region src/combine-headers.ts\nfunction combineHeaders(...headers) {\n\treturn headers.reduce((combinedHeaders, currentHeaders) => ({\n\t\t...combinedHeaders,\n\t\t...currentHeaders\n\t}), {});\n}\n//#endregion\n//#region src/remove-undefined-entries.ts\n/**\n* Removes entries from a record where the value is null or undefined.\n* @param record - The input object whose entries may be null or undefined.\n* @returns A new object containing only entries with non-null and non-undefined values.\n*/\nfunction removeUndefinedEntries(record) {\n\treturn Object.fromEntries(Object.entries(record).filter(([_key, value]) => value != null));\n}\n//#endregion\n//#region src/delay.ts\n/**\n* Creates a Promise that resolves after a specified delay\n* @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.\n* @param signal - Optional AbortSignal to cancel the delay\n* @returns A Promise that resolves after the specified delay\n* @throws {DOMException} When the signal is aborted\n*/\nasync function delay(delayInMs, options) {\n\tif (delayInMs == null) return;\n\tconst signal = options?.abortSignal;\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(createAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t}, delayInMs);\n\t\tconst cleanup = () => {\n\t\t\tclearTimeout(timeoutId);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tcleanup();\n\t\t\treject(createAbortError());\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort);\n\t});\n}\nfunction createAbortError() {\n\treturn new DOMException(\"Delay was aborted\", \"AbortError\");\n}\n//#endregion\n//#region src/websocket.ts\nfunction getWebSocketConstructor(webSocket) {\n\tconst WebSocketConstructor = webSocket ?? globalThis.WebSocket;\n\tif (WebSocketConstructor == null) throw new Error(\"No WebSocket implementation available.\");\n\treturn WebSocketConstructor;\n}\n/**\n* Converts an http(s) URL to the corresponding ws(s) URL.\n*/\nfunction toWebSocketUrl(url) {\n\tconst wsUrl = new URL(url);\n\tif (wsUrl.protocol === \"http:\") wsUrl.protocol = \"ws:\";\n\telse if (wsUrl.protocol === \"https:\") wsUrl.protocol = \"wss:\";\n\treturn wsUrl;\n}\nconst textDecoder$1 = new TextDecoder();\n/**\n* Reads WebSocket message data as text, handling string, binary,\n* and Blob payloads.\n*/\nasync function readWebSocketMessageText(data) {\n\tif (typeof data === \"string\") return data;\n\tif (data instanceof ArrayBuffer) return textDecoder$1.decode(data);\n\tif (ArrayBuffer.isView(data)) return textDecoder$1.decode(data);\n\tif (typeof Blob !== \"undefined\" && data instanceof Blob) return data.text();\n\treturn String(data);\n}\nconst WEBSOCKET_OPEN_STATE = 1;\n/**\n* Waits until the socket's send buffer drains below `highWaterMark` bytes.\n* No-op for implementations that do not expose `bufferedAmount`. There is no\n* portable drain event, so this polls. Returns as soon as the socket is no\n* longer open or the signal aborts — `bufferedAmount` never drains on a\n* closed socket, so waiting on would poll forever.\n*/\nasync function waitForWebSocketBufferDrain(socket, { highWaterMark = 1048576, pollIntervalMs = 20, abortSignal } = {}) {\n\twhile (socket.readyState === WEBSOCKET_OPEN_STATE && (socket.bufferedAmount ?? 0) > highWaterMark) {\n\t\tif (abortSignal?.aborted === true) return;\n\t\tawait delay(pollIntervalMs);\n\t}\n}\n//#endregion\n//#region src/connect-to-websocket.ts\n/**\n* Opens a WebSocket for a provider model, owning the transport-generic layer\n* (analogous to `postToApi` for HTTP): constructor resolution, header hygiene,\n* abort wiring, and message decoding. Callers own the URL, the auth channel\n* (subprotocols vs headers), and the wire protocol.\n*/\nfunction connectToWebSocket({ url, protocols, headers, webSocket, abortSignal, onOpen, onMessageText, onProcessingError, onSocketError, onClose, onAbort }) {\n\tlet socket;\n\tlet abortListener;\n\tconst close = (code) => {\n\t\tif (abortListener != null) {\n\t\t\tabortSignal?.removeEventListener(\"abort\", abortListener);\n\t\t\tabortListener = void 0;\n\t\t}\n\t\ttry {\n\t\t\tsocket?.close(code);\n\t\t} catch {}\n\t};\n\tif (abortSignal?.aborted) {\n\t\tonAbort?.(abortSignal.reason ?? /* @__PURE__ */ new Error(\"Aborted\"));\n\t\treturn {\n\t\t\tsocket: void 0,\n\t\t\tclose\n\t\t};\n\t}\n\ttry {\n\t\tsocket = new (getWebSocketConstructor(webSocket))(url, protocols, { headers: removeUndefinedEntries(headers ?? {}) });\n\t} catch (error) {\n\t\tonProcessingError(error);\n\t\treturn {\n\t\t\tsocket: void 0,\n\t\t\tclose\n\t\t};\n\t}\n\tif (abortSignal != null && onAbort != null) {\n\t\tabortListener = () => onAbort(abortSignal.reason ?? /* @__PURE__ */ new Error(\"Aborted\"));\n\t\tabortSignal.addEventListener(\"abort\", abortListener, { once: true });\n\t}\n\tconst openedSocket = socket;\n\tsocket.onopen = () => {\n\t\ttry {\n\t\t\tonOpen?.(openedSocket);\n\t\t} catch (error) {\n\t\t\tonProcessingError(error);\n\t\t}\n\t};\n\tlet tail = Promise.resolve();\n\tsocket.onmessage = (event) => {\n\t\ttail = tail.then(() => readWebSocketMessageText(event.data)).then((text) => onMessageText(text)).catch(onProcessingError);\n\t};\n\tsocket.onerror = () => {\n\t\ttail = tail.then(() => onSocketError?.()).catch(onProcessingError);\n\t};\n\tsocket.onclose = (event) => {\n\t\tconst closeEvent = event;\n\t\tconst code = typeof closeEvent?.code === \"number\" ? closeEvent.code : void 0;\n\t\tconst reason = typeof closeEvent?.reason === \"string\" ? closeEvent.reason : void 0;\n\t\ttail = tail.then(() => onClose?.({\n\t\t\tcode,\n\t\t\treason\n\t\t})).catch(onProcessingError);\n\t};\n\treturn {\n\t\tsocket,\n\t\tclose\n\t};\n}\n//#endregion\n//#region src/convert-async-iterator-to-readable-stream.ts\n/**\n* Converts an AsyncIterator to a ReadableStream.\n*\n* @template T - The type of elements produced by the AsyncIterator.\n* @param { <T>} iterator - The AsyncIterator to convert.\n* @returns {ReadableStream<T>} - A ReadableStream that provides the same data as the AsyncIterator.\n*/\nfunction convertAsyncIteratorToReadableStream(iterator) {\n\tlet cancelled = false;\n\treturn new ReadableStream({\n\t\t/**\n\t\t* Called when the consumer wants to pull more data from the stream.\n\t\t*\n\t\t* @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n\t\t* @returns {Promise<void>}\n\t\t*/\n\t\tasync pull(controller) {\n\t\t\tif (cancelled) return;\n\t\t\ttry {\n\t\t\t\tconst { value, done } = await iterator.next();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t}\n\t\t},\n\t\t/**\n\t\t* Called when the consumer cancels the stream.\n\t\t*/\n\t\tasync cancel(reason) {\n\t\t\tcancelled = true;\n\t\t\tif (iterator.return) try {\n\t\t\t\tawait iterator.return(reason);\n\t\t\t} catch {}\n\t\t}\n\t});\n}\n//#endregion\n//#region src/uint8-utils.ts\nconst { btoa, atob } = globalThis;\nfunction convertBase64ToUint8Array(base64String) {\n\tconst base64Url = base64String.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst latin1string = atob(base64Url);\n\treturn Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));\n}\nfunction convertUint8ArrayToBase64(array) {\n\tconst chunks = [];\n\tconst chunkSize = 4096;\n\tfor (let i = 0; i < array.length; i += chunkSize) chunks.push(String.fromCodePoint(...array.subarray(i, i + chunkSize)));\n\treturn btoa(chunks.join(\"\"));\n}\nfunction convertToBase64(value) {\n\treturn value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n//#endregion\n//#region src/convert-inline-file-data-to-uint8-array.ts\n/**\n* Converts inline file data (a tagged `data` or `text` shape) into raw bytes.\n*\n* - `{ type: 'text', text }` → UTF-8 encoded bytes\n* - `{ type: 'data', data: Uint8Array | Buffer }` → returned as-is\n* - `{ type: 'data', data: ArrayBuffer }` → wrapped in a `Uint8Array`\n* - `{ type: 'data', data: string }` → decoded as base64\n*\n* `{ type: 'stream' }` data is rejected: providers without streaming upload\n* support funnel here and surface a clear `UnsupportedFunctionalityError`.\n*/\nfunction convertInlineFileDataToUint8Array(data) {\n\tif (data.type === \"stream\") {\n\t\tconst error = new UnsupportedFunctionalityError({ functionality: \"streaming file upload\" });\n\t\tdata.stream.cancel(error).catch(() => {});\n\t\tthrow error;\n\t}\n\tif (data.type === \"text\") return new TextEncoder().encode(data.text);\n\tif (data.data instanceof Uint8Array) return data.data;\n\tif (data.data instanceof ArrayBuffer) return new Uint8Array(data.data);\n\treturn convertBase64ToUint8Array(data.data);\n}\n//#endregion\n//#region src/convert-image-model-file-to-data-uri.ts\n/**\n* Convert an ImageModelV4File to a URL or data URI string.\n*\n* If the file is a URL, it returns the URL as-is.\n* If the file is base64 data, it returns a data URI with the base64 data.\n* If the file is a Uint8Array, it converts it to base64 and returns a data URI.\n*/\nfunction convertImageModelFileToDataUri(file) {\n\tif (file.type === \"url\") return file.url;\n\treturn `data:${file.mediaType};base64,${typeof file.data === \"string\" ? file.data : convertUint8ArrayToBase64(file.data)}`;\n}\n//#endregion\n//#region src/convert-json-response-tool-stream.ts\n/**\n* Providers that cannot use native structured output for a request can use a\n* JSON response tool instead. This utility converts that tool's streamed input\n* into text events so the SDK can parse it as structured output.\n*\n* Conversational text is suppressed. Application tool calls pass through so the\n* caller can execute them. A response containing only the JSON tool finishes\n* with `stop`; a response containing application calls keeps its finish reason.\n*/\nfunction convertJsonResponseToolStream(toolName) {\n\tconst responseToolIds = /* @__PURE__ */ new Set();\n\tconst responseToolsWithDeltas = /* @__PURE__ */ new Set();\n\tlet hasResponseTool = false;\n\tlet hasApplicationTool = false;\n\treturn new TransformStream({ transform(part, controller) {\n\t\tswitch (part.type) {\n\t\t\tcase \"text-start\":\n\t\t\tcase \"text-delta\":\n\t\t\tcase \"text-end\": return;\n\t\t\tcase \"tool-input-start\":\n\t\t\t\tif (part.toolName === toolName) {\n\t\t\t\t\tresponseToolIds.add(part.id);\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"text-start\",\n\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t...part.providerMetadata && { providerMetadata: part.providerMetadata }\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"tool-input-delta\":\n\t\t\t\tif (responseToolIds.has(part.id)) {\n\t\t\t\t\tif (part.delta.length > 0) responseToolsWithDeltas.add(part.id);\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\tdelta: part.delta,\n\t\t\t\t\t\t...part.providerMetadata && { providerMetadata: part.providerMetadata }\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"tool-input-end\":\n\t\t\t\tif (responseToolIds.has(part.id)) return;\n\t\t\t\tbreak;\n\t\t\tcase \"tool-call\":\n\t\t\t\tif (part.toolName === toolName) {\n\t\t\t\t\tif (!responseToolsWithDeltas.has(part.toolCallId)) controller.enqueue({\n\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\tid: part.toolCallId,\n\t\t\t\t\t\tdelta: part.input,\n\t\t\t\t\t\t...part.providerMetadata && { providerMetadata: part.providerMetadata }\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"text-end\",\n\t\t\t\t\t\tid: part.toolCallId,\n\t\t\t\t\t\t...part.providerMetadata && { providerMetadata: part.providerMetadata }\n\t\t\t\t\t});\n\t\t\t\t\thasResponseTool = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!part.providerExecuted) hasApplicationTool = true;\n\t\t\t\tbreak;\n\t\t\tcase \"finish\": if (hasResponseTool && !hasApplicationTool && part.finishReason.unified === \"tool-calls\") {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t...part,\n\t\t\t\t\tfinishReason: {\n\t\t\t\t\t\t...part.finishReason,\n\t\t\t\t\t\tunified: \"stop\"\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcontroller.enqueue(part);\n\t} });\n}\n//#endregion\n//#region src/convert-to-form-data.ts\n/**\n* Converts an input object to FormData for multipart/form-data requests.\n*\n* Handles the following cases:\n* - `null` or `undefined` values are skipped\n* - Arrays with a single element are appended as a single value\n* - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)\n* unless `useArrayBrackets` is set to `false`\n* - All other values are appended directly\n*\n* @param input - The input object to convert. Use a generic type for type validation.\n* @param options - Optional configuration object.\n* @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.\n* Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.\n* @returns A FormData object containing the input values.\n*\n* @example\n* ```ts\n* type MyInput = {\n* model: string;\n* prompt: string;\n* images: Blob[];\n* };\n*\n* const formData = convertToFormData<MyInput>({\n* model: 'gpt-image-1',\n* prompt: 'A cat',\n* images: [blob1, blob2],\n* });\n* ```\n*/\nfunction convertToFormData(input, options = {}) {\n\tconst { useArrayBrackets = true } = options;\n\tconst formData = new FormData();\n\tfor (const [key, value] of Object.entries(input)) {\n\t\tif (value == null) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length === 1) {\n\t\t\t\tformData.append(key, value[0]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst arrayKey = useArrayBrackets ? `${key}[]` : key;\n\t\t\tfor (const item of value) formData.append(arrayKey, item);\n\t\t\tcontinue;\n\t\t}\n\t\tformData.append(key, value);\n\t}\n\treturn formData;\n}\n//#endregion\n//#region src/create-language-model-response-metadata.ts\n/**\n* Converts common provider response fields into language model response\n* metadata.\n*/\nfunction createLanguageModelResponseMetadata({ id, model, created }) {\n\treturn {\n\t\tid: id ?? void 0,\n\t\tmodelId: model ?? void 0,\n\t\ttimestamp: created != null ? /* @__PURE__ */ new Date(created * 1e3) : void 0\n\t};\n}\n//#endregion\n//#region src/create-null-language-model-usage.ts\n/**\n* Creates an empty language model usage result for unavailable usage data.\n*/\nfunction createNullLanguageModelUsage() {\n\treturn {\n\t\tinputTokens: {\n\t\t\ttotal: void 0,\n\t\t\tnoCache: void 0,\n\t\t\tcacheRead: void 0,\n\t\t\tcacheWrite: void 0\n\t\t},\n\t\toutputTokens: {\n\t\t\ttotal: void 0,\n\t\t\ttext: void 0,\n\t\t\treasoning: void 0\n\t\t},\n\t\traw: void 0\n\t};\n}\n//#endregion\n//#region src/create-tool-name-mapping.ts\n/**\n* @param tools - Tools that were passed to the language model.\n* @param providerToolNames - Maps the provider tool ids to the provider tool names.\n*/\nfunction createToolNameMapping({ tools = [], providerToolNames }) {\n\tconst customToolNameToProviderToolName = {};\n\tconst providerToolNameToCustomToolName = {};\n\tfor (const tool of tools) if (tool.type === \"provider\" && tool.id in providerToolNames) {\n\t\tconst providerToolName = providerToolNames[tool.id];\n\t\tcustomToolNameToProviderToolName[tool.name] = providerToolName;\n\t\tproviderToolNameToCustomToolName[providerToolName] = tool.name;\n\t}\n\treturn {\n\t\ttoProviderToolName: (customToolName) => customToolNameToProviderToolName[customToolName] ?? customToolName,\n\t\ttoCustomToolName: (providerToolName) => providerToolNameToCustomToolName[providerToolName] ?? providerToolName\n\t};\n}\n//#endregion\n//#region src/create-provider-stream-error.ts\nconst marker$2 = Symbol.for(\"vercel.ai.providerStreamError\");\n/**\n* Adds provider-owned status and retry metadata to a stream error payload\n* without requiring provider packages to depend on AI SDK Core.\n*/\nfunction createProviderStreamError({ message, type, code, statusCode, isRetryable, data }) {\n\tconst error = {\n\t\tmessage,\n\t\ttype,\n\t\tcode,\n\t\tstatusCode,\n\t\tisRetryable,\n\t\tdata\n\t};\n\tObject.defineProperty(error, marker$2, { value: true });\n\treturn error;\n}\nfunction isProviderStreamError(error) {\n\treturn typeof error === \"object\" && error != null && error[marker$2] === true;\n}\n//#endregion\n//#region src/delayed-promise.ts\n/**\n* Delayed promise. It is only constructed once the value is accessed.\n* This is useful to avoid unhandled promise rejections when the promise is created\n* but not accessed.\n*/\nvar DelayedPromise = class {\n\tconstructor() {\n\t\tthis.status = { type: \"pending\" };\n\t\tthis._resolve = void 0;\n\t\tthis._reject = void 0;\n\t}\n\tget promise() {\n\t\tif (this._promise) return this._promise;\n\t\tthis._promise = new Promise((resolve, reject) => {\n\t\t\tif (this.status.type === \"resolved\") resolve(this.status.value);\n\t\t\telse if (this.status.type === \"rejected\") reject(this.status.error);\n\t\t\tthis._resolve = resolve;\n\t\t\tthis._reject = reject;\n\t\t});\n\t\treturn this._promise;\n\t}\n\tresolve(value) {\n\t\tthis.status = {\n\t\t\ttype: \"resolved\",\n\t\t\tvalue\n\t\t};\n\t\tif (this._promise) this._resolve?.(value);\n\t}\n\treject(error) {\n\t\tthis.status = {\n\t\t\ttype: \"rejected\",\n\t\t\terror\n\t\t};\n\t\tif (this._promise) this._reject?.(error);\n\t}\n\tisResolved() {\n\t\treturn this.status.type === \"resolved\";\n\t}\n\tisRejected() {\n\t\treturn this.status.type === \"rejected\";\n\t}\n\tisPending() {\n\t\treturn this.status.type === \"pending\";\n\t}\n};\n//#endregion\n//#region src/extract-response-headers.ts\n/**\n* Extracts the headers from a response object and returns them as a key-value object.\n*\n* @param response - The response object to extract headers from.\n* @returns The headers as a key-value object.\n*/\nfunction extractResponseHeaders(response) {\n\treturn Object.fromEntries([...response.headers]);\n}\n//#endregion\n//#region src/get-runtime-environment-user-agent.ts\nfunction getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {\n\tif (globalThisAny.navigator?.userAgent) return globalThisAny.navigator.userAgent.toLowerCase();\n\tif (globalThisAny.process?.versions?.node) return `node.js/${globalThisAny.process.version}`;\n\tif (globalThisAny.EdgeRuntime) return \"vercel-edge\";\n\treturn \"\";\n}\n//#endregion\n//#region src/is-abort-error.ts\nfunction isAbortError(error) {\n\treturn (error instanceof Error || typeof DOMException === \"function\" && error instanceof DOMException) && (error.name === \"AbortError\" || error.name === \"ResponseAborted\" || error.name === \"TimeoutError\");\n}\n//#endregion\n//#region src/handle-fetch-error.ts\nconst FETCH_FAILED_ERROR_MESSAGES = [\"fetch failed\", \"failed to fetch\"];\nconst RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([\n\t\"ConnectionRefused\",\n\t\"ConnectionClosed\",\n\t\"FailedToOpenSocket\",\n\t\"ECONNRESET\",\n\t\"ECONNREFUSED\",\n\t\"ETIMEDOUT\",\n\t\"EPIPE\",\n\t\"UND_ERR_SOCKET\",\n\t\"UND_ERR_HEADERS_TIMEOUT\",\n\t\"UND_ERR_BODY_TIMEOUT\",\n\t\"UND_ERR_CONNECT_TIMEOUT\"\n]);\nfunction findNetworkError(error) {\n\tconst visited = /* @__PURE__ */ new Set();\n\tlet current = error;\n\twhile (current instanceof Error && !visited.has(current)) {\n\t\tvisited.add(current);\n\t\tconst errorWithCode = current;\n\t\tif (typeof errorWithCode.code === \"string\" && RETRYABLE_NETWORK_ERROR_CODES.has(errorWithCode.code)) return errorWithCode;\n\t\tcurrent = current.cause;\n\t}\n}\nfunction handleFetchError({ error, url, requestBodyValues }) {\n\tif (isAbortError(error)) return error;\n\tif (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {\n\t\tconst cause = error.cause;\n\t\tif (cause != null) return new APICallError({\n\t\t\tmessage: `Cannot connect to API: ${cause.message}`,\n\t\t\tcause,\n\t\t\turl,\n\t\t\trequestBodyValues,\n\t\t\tisRetryable: true\n\t\t});\n\t}\n\tconst networkError = findNetworkError(error);\n\tif (networkError != null) {\n\t\tif (APICallError.isInstance(error)) return new APICallError({\n\t\t\tmessage: error.message,\n\t\t\tcause: error.cause,\n\t\t\turl: error.url,\n\t\t\trequestBodyValues: error.requestBodyValues,\n\t\t\tstatusCode: error.statusCode,\n\t\t\tresponseHeaders: error.responseHeaders,\n\t\t\tresponseBody: error.responseBody,\n\t\t\tdata: error.data,\n\t\t\tisRetryable: true\n\t\t});\n\t\treturn new APICallError({\n\t\t\tmessage: `Cannot connect to API: ${error instanceof Error ? error.message : networkError.message}`,\n\t\t\tcause: error,\n\t\t\turl,\n\t\t\trequestBodyValues,\n\t\t\tisRetryable: true\n\t\t});\n\t}\n\treturn error;\n}\n//#endregion\n//#region src/version.ts\nconst VERSION = \"5.0.58\";\n//#endregion\n//#region src/normalize-headers.ts\n/**\n* Normalizes different header inputs into a plain record with lower-case keys.\n* Entries with `undefined` or `null` values are removed.\n*\n* @param headers - Input headers (`Headers`, tuples array, plain record) to normalize.\n* @returns A record containing the normalized header entries.\n*/\nfunction normalizeHeaders(headers) {\n\tif (headers == null) return {};\n\tconst normalized = {};\n\tif (headers instanceof Headers) headers.forEach((value, key) => {\n\t\tnormalized[key.toLowerCase()] = value;\n\t});\n\telse {\n\t\tif (!Array.isArray(headers)) headers = Object.entries(headers);\n\t\tfor (const [key, value] of headers) if (value != null) normalized[key.toLowerCase()] = value;\n\t}\n\treturn normalized;\n}\n//#endregion\n//#region src/with-user-agent-suffix.ts\n/**\n* Appends suffix parts to the `user-agent` header.\n* If a `user-agent` header already exists, the suffix parts are appended to it.\n* If no `user-agent` header exists, a new one is created with the suffix parts.\n* Automatically removes undefined entries from the headers.\n*\n* @param headers - The original headers.\n* @param userAgentSuffixParts - The parts to append to the `user-agent` header.\n* @returns The new headers with the `user-agent` header set or updated.\n*/\nfunction withUserAgentSuffix(headers, ...userAgentSuffixParts) {\n\tconst normalizedHeaders = new Headers(normalizeHeaders(headers));\n\tconst currentUserAgentHeader = normalizedHeaders.get(\"user-agent\") || \"\";\n\tnormalizedHeaders.set(\"user-agent\", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(\" \"));\n\treturn Object.fromEntries(normalizedHeaders.entries());\n}\n//#endregion\n//#region src/delete-from-api.ts\nconst getOriginalFetch$3 = () => globalThis.fetch;\n/**\n* Sends a DELETE request. For URLs built from developer-configured endpoints\n* only — there is no untrusted-URL validation path (use `getFromApi` with\n* `validateUrl` for response-supplied URLs).\n*/\nconst deleteFromApi = async ({ url, headers = {}, failedResponseHandler, successfulResponseHandler, abortSignal, fetch = getOriginalFetch$3() }) => {\n\ttry {\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: withUserAgentSuffix(headers, `ai-sdk-provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tconst responseHeaders = extractResponseHeaders(response);\n\t\tif (!response.ok) {\n\t\t\tlet errorInformation;\n\t\t\ttry {\n\t\t\t\terrorInformation = await failedResponseHandler({\n\t\t\t\t\tresponse,\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues: {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t\tthrow new APICallError({\n\t\t\t\t\tmessage: \"Failed to process error response\",\n\t\t\t\t\tcause: error,\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\turl,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t\trequestBodyValues: {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow errorInformation.value;\n\t\t}\n\t\ttry {\n\t\t\treturn await successfulResponseHandler({\n\t\t\t\tresponse,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues: {}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t}\n\t\t\tthrow new APICallError({\n\t\t\t\tmessage: \"Failed to process successful response\",\n\t\t\t\tcause: error,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\turl,\n\t\t\t\tresponseHeaders,\n\t\t\t\trequestBodyValues: {}\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tthrow handleFetchError({\n\t\t\terror,\n\t\t\turl,\n\t\t\trequestBodyValues: {}\n\t\t});\n\t}\n};\n//#endregion\n//#region src/detect-media-type.ts\nconst imageMediaTypeSignatures = [\n\t{\n\t\tmediaType: \"image/gif\",\n\t\tbytesPrefix: [\n\t\t\t71,\n\t\t\t73,\n\t\t\t70,\n\t\t\t56,\n\t\t\t55,\n\t\t\t97\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/gif\",\n\t\tbytesPrefix: [\n\t\t\t71,\n\t\t\t73,\n\t\t\t70,\n\t\t\t56,\n\t\t\t57,\n\t\t\t97\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/png\",\n\t\tbytesPrefix: [\n\t\t\t137,\n\t\t\t80,\n\t\t\t78,\n\t\t\t71\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/jpeg\",\n\t\tbytesPrefix: [255, 216]\n\t},\n\t{\n\t\tmediaType: \"image/webp\",\n\t\tbytesPrefix: [\n\t\t\t82,\n\t\t\t73,\n\t\t\t70,\n\t\t\t70,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\t87,\n\t\t\t69,\n\t\t\t66,\n\t\t\t80\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/bmp\",\n\t\tbytesPrefix: [\n\t\t\t66,\n\t\t\t77,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t0\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/tiff\",\n\t\tbytesPrefix: [\n\t\t\t73,\n\t\t\t73,\n\t\t\t42,\n\t\t\t0\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/tiff\",\n\t\tbytesPrefix: [\n\t\t\t77,\n\t\t\t77,\n\t\t\t0,\n\t\t\t42\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/avif\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\tnull,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112,\n\t\t\t97,\n\t\t\t118,\n\t\t\t105,\n\t\t\t102\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/heic\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\tnull,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112,\n\t\t\t104,\n\t\t\t101,\n\t\t\t105,\n\t\t\t99\n\t\t]\n\t}\n];\nconst documentMediaTypeSignatures = [{\n\tmediaType: \"application/pdf\",\n\tbytesPrefix: [\n\t\t37,\n\t\t80,\n\t\t68,\n\t\t70\n\t]\n}];\nconst audioMediaTypeSignaturesWithoutMp4 = [\n\t{\n\t\tmediaType: \"audio/aac\",\n\t\tbytesPrefix: [255, 240]\n\t},\n\t{\n\t\tmediaType: \"audio/aac\",\n\t\tbytesPrefix: [255, 241]\n\t},\n\t{\n\t\tmediaType: \"audio/aac\",\n\t\tbytesPrefix: [255, 248]\n\t},\n\t{\n\t\tmediaType: \"audio/aac\",\n\t\tbytesPrefix: [255, 249]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 251]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 250]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 243]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 242]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 227]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 226]\n\t},\n\t{\n\t\tmediaType: \"audio/wav\",\n\t\tbytesPrefix: [\n\t\t\t82,\n\t\t\t73,\n\t\t\t70,\n\t\t\t70,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\t87,\n\t\t\t65,\n\t\t\t86,\n\t\t\t69\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/ogg\",\n\t\tbytesPrefix: [\n\t\t\t79,\n\t\t\t103,\n\t\t\t103,\n\t\t\t83\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/flac\",\n\t\tbytesPrefix: [\n\t\t\t102,\n\t\t\t76,\n\t\t\t97,\n\t\t\t67\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/aac\",\n\t\tbytesPrefix: [\n\t\t\t64,\n\t\t\t21,\n\t\t\t0,\n\t\t\t0\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/webm\",\n\t\tbytesPrefix: [\n\t\t\t26,\n\t\t\t69,\n\t\t\t223,\n\t\t\t163\n\t\t]\n\t}\n];\nconst audioMediaTypeSignatures = [...audioMediaTypeSignaturesWithoutMp4, {\n\tmediaType: \"audio/mp4\",\n\tbytesPrefix: [\n\t\t0,\n\t\t0,\n\t\t0,\n\t\tnull,\n\t\t102,\n\t\t116,\n\t\t121,\n\t\t112\n\t]\n}];\nconst videoMediaTypeSignatures = [\n\t{\n\t\tmediaType: \"video/mp4\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\tnull,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"video/webm\",\n\t\tbytesPrefix: [\n\t\t\t26,\n\t\t\t69,\n\t\t\t223,\n\t\t\t163\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"video/quicktime\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t20,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112,\n\t\t\t113,\n\t\t\t116\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"video/x-msvideo\",\n\t\tbytesPrefix: [\n\t\t\t82,\n\t\t\t73,\n\t\t\t70,\n\t\t\t70\n\t\t]\n\t}\n];\nconst DEFAULT_SNIFF_BYTES = 18;\nconst ID3_SCAN_BYTES = 131084;\nfunction decodePrefix(data, maxBytes) {\n\tif (typeof data !== \"string\") return data.length > maxBytes ? data.subarray(0, maxBytes) : data;\n\tconst maxChars = Math.ceil(maxBytes / 3) * 4;\n\tconst bytes = convertBase64ToUint8Array(data.substring(0, Math.min(data.length, maxChars)));\n\treturn bytes.length > maxBytes ? bytes.subarray(0, maxBytes) : bytes;\n}\nfunction hasID3(bytes) {\n\treturn bytes.length > 10 && bytes[0] === 73 && bytes[1] === 68 && bytes[2] === 51;\n}\nconst stripID3 = (bytes) => {\n\tconst id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;\n\treturn bytes.subarray(id3Size + 10);\n};\nfunction detectMediaTypeBySignatures({ data, signatures }) {\n\tlet bytes = decodePrefix(data, DEFAULT_SNIFF_BYTES);\n\tif (hasID3(bytes)) bytes = stripID3(decodePrefix(data, ID3_SCAN_BYTES));\n\tfor (const signature of signatures) if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => byte === null || bytes[index] === byte)) return signature.mediaType;\n}\nconst topLevelSignatureTables = {\n\timage: imageMediaTypeSignatures,\n\taudio: audioMediaTypeSignatures,\n\tvideo: videoMediaTypeSignatures,\n\tapplication: documentMediaTypeSignatures\n};\n/**\n* Detect the IANA media type of a file from its raw bytes or base64 string.\n*\n* - When `topLevelType` is omitted, every known signature is considered\n* (image, audio, video, and application). Returns `undefined` when the\n* bytes do not match any known signature.\n* - When `topLevelType` is provided, only signatures for that top-level\n* segment are considered. Returns `undefined` for unsupported segments\n* (e.g. `\"text\"`) or when no signature matches.\n*/\nfunction detectMediaType({ data, topLevelType }) {\n\tif (topLevelType === void 0) return detectMediaTypeBySignatures({\n\t\tdata,\n\t\tsignatures: [\n\t\t\t...imageMediaTypeSignatures,\n\t\t\t...documentMediaTypeSignatures,\n\t\t\t...audioMediaTypeSignaturesWithoutMp4,\n\t\t\t...videoMediaTypeSignatures\n\t\t]\n\t});\n\tconst signatures = topLevelSignatureTables[topLevelType];\n\tif (signatures === void 0) return;\n\treturn detectMediaTypeBySignatures({\n\t\tdata,\n\t\tsignatures\n\t});\n}\n/**\n* Returns the top-level segment of a media type (the portion before `/`).\n*\n* Examples:\n* - `\"image/png\"` -> `\"image\"`\n* - `\"image/*\"` -> `\"image\"`\n* - `\"image\"` -> `\"image\"`\n* - `\"image/\"` -> `\"image\"`\n* - `\"\"` -> `\"\"`\n* - `\"/\"` -> `\"\"`\n*/\nfunction getTopLevelMediaType(mediaType) {\n\tconst slashIndex = mediaType.indexOf(\"/\");\n\treturn slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex);\n}\n/**\n* Returns `true` only when the given media type has a non-empty, non-wildcard\n* subtype (i.e. matches the form `type/subtype`, and `subtype` is not `*`).\n*\n* Examples:\n* - `\"image/png\"` -> `true`\n* - `\"image/*\"` -> `false`\n* - `\"image\"` -> `false`\n* - `\"image/\"` -> `false`\n* - `\"\"` -> `false`\n* - `\"/\"` -> `false`\n*/\nfunction isFullMediaType(mediaType) {\n\tconst slashIndex = mediaType.indexOf(\"/\");\n\tif (slashIndex === -1) return false;\n\tconst subtype = mediaType.substring(slashIndex + 1);\n\treturn subtype.length > 0 && subtype !== \"*\";\n}\n//#endregion\n//#region src/cancel-response-body.ts\n/**\n* Cancels a response body to release the underlying connection.\n*\n* When a fetch Response is rejected without consuming its body (e.g. a failed\n* status code, an open-redirect rejection, or a Content-Length that exceeds the\n* size limit), the underlying TCP socket is not returned to the connection pool\n* and may stay open until the process runs out of file descriptors. Cancelling\n* the body avoids this leak.\n*\n* Errors thrown while cancelling are ignored: the body may already be locked,\n* disturbed, or absent, none of which should mask the original rejection.\n*/\nasync function cancelResponseBody(response) {\n\ttry {\n\t\tawait response.body?.cancel();\n\t} catch {}\n}\n//#endregion\n//#region src/download-error.ts\nconst name$1 = \"AI_DownloadError\";\nconst marker$1 = `vercel.ai.error.${name$1}`;\nconst symbol$1 = Symbol.for(marker$1);\nvar DownloadError = class extends AISDKError {\n\tconstructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {\n\t\tsuper({\n\t\t\tname: name$1,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$1] = true;\n\t\tthis.url = url;\n\t\tthis.statusCode = statusCode;\n\t\tthis.statusText = statusText;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$1);\n\t}\n};\n//#endregion\n//#region src/is-browser-runtime.ts\n/**\n* Returns `true` when running in a browser.\n*\n* Detection keys on the presence of a global `window`, matching the browser\n* check used elsewhere in this package (see `getRuntimeEnvironmentUserAgent`)\n* so the SDK has a single, consistent definition of \"browser\". Server runtimes\n* (Node.js, Deno, Bun, edge/workers) do not define `window`.\n*/\nfunction isBrowserRuntime(globalThisAny = globalThis) {\n\treturn globalThisAny.window != null;\n}\n//#endregion\n//#region src/is-same-origin.ts\n/**\n* Returns true when `url` has the same origin (scheme + host + port) as\n* `baseUrl`.\n*\n* Used to decide whether provider credentials may be attached to a request to a\n* URL taken from a provider response (e.g. a polling or media-download URL).\n* Credentials must only be sent to the provider's own origin; a response that\n* names a foreign host (a CDN, or an attacker-controlled host if the response\n* is tampered with) must not receive the API key.\n*\n* Returns false if either value is not a valid absolute URL (fail-closed).\n*/\nfunction isSameOrigin(url, baseUrl) {\n\ttry {\n\t\treturn new URL(url).origin === new URL(baseUrl).origin;\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\n//#region src/validate-download-url.ts\n/**\n* Validates that a URL is safe to download from, blocking private/internal addresses\n* to prevent SSRF attacks.\n*\n* Note: this function performs string/literal-IP checks only. The Node.js\n* download fetch additionally validates and pins DNS results at connect time.\n*\n* @param url - The URL string to validate.\n* @throws DownloadError if the URL is unsafe.\n*/\nfunction validateDownloadUrl(url) {\n\tlet parsed;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\tthrow new DownloadError({\n\t\t\turl,\n\t\t\tmessage: `Invalid URL: ${url}`\n\t\t});\n\t}\n\tif (parsed.protocol === \"data:\") return;\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") throw new DownloadError({\n\t\turl,\n\t\tmessage: `URL scheme must be http, https, or data, got ${parsed.protocol}`\n\t});\n\tconst hostname = parsed.hostname.toLowerCase().replace(/\\.+$/, \"\");\n\tif (!hostname) throw new DownloadError({\n\t\turl,\n\t\tmessage: `URL must have a hostname`\n\t});\n\tif (hostname === \"localhost\" || hostname.endsWith(\".local\") || hostname.endsWith(\".localhost\")) throw new DownloadError({\n\t\turl,\n\t\tmessage: `URL with hostname ${hostname} is not allowed`\n\t});\n\tif (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n\t\tif (isPrivateIPv6(hostname.slice(1, -1))) throw new DownloadError({\n\t\t\turl,\n\t\t\tmessage: `URL with IPv6 address ${hostname} is not allowed`\n\t\t});\n\t\treturn;\n\t}\n\tif (isIPv4(hostname)) {\n\t\tif (isPrivateIPv4(hostname)) throw new DownloadError({\n\t\t\turl,\n\t\t\tmessage: `URL with IP address ${hostname} is not allowed`\n\t\t});\n\t}\n}\n/**\n* Validates an address returned by DNS before it is used to open a socket.\n* This is intentionally not exported from the package entry point.\n*/\nfunction validateDownloadAddress({ address, family, hostname }) {\n\tif (family === 4 ? !isIPv4(address) || isPrivateIPv4(address) : family === 6 ? isPrivateIPv6(address) : true) throw new DownloadError({\n\t\turl: hostname,\n\t\tmessage: `Hostname ${hostname} resolved to disallowed IP address ${address}`\n\t});\n}\nfunction isIPv4(hostname) {\n\tconst parts = hostname.split(\".\");\n\tif (parts.length !== 4) return false;\n\treturn parts.every((part) => {\n\t\tconst num = Number(part);\n\t\treturn Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;\n\t});\n}\nfunction isPrivateIPv4(ip) {\n\tconst [a, b, c] = ip.split(\".\").map(Number);\n\tif (a === 0) return true;\n\tif (a === 10) return true;\n\tif (a === 100 && b >= 64 && b <= 127) return true;\n\tif (a === 127) return true;\n\tif (a === 169 && b === 254) return true;\n\tif (a === 172 && b >= 16 && b <= 31) return true;\n\tif (a === 192 && b === 0 && c === 0) return true;\n\tif (a === 192 && b === 0 && c === 2) return true;\n\tif (a === 192 && b === 168) return true;\n\tif (a === 198 && (b === 18 || b === 19)) return true;\n\tif (a === 198 && b === 51 && c === 100) return true;\n\tif (a === 203 && b === 0 && c === 113) return true;\n\tif (a >= 224) return true;\n\treturn false;\n}\n/**\n* Expands an IPv6 address string into its 8 16-bit groups, handling `::`\n* compression and an optional dotted-decimal IPv4 tail (e.g. `::ffff:127.0.0.1`).\n*\n* @returns the 8 groups, or null if the input is not a parseable IPv6 address.\n*/\nfunction parseIPv6(ip) {\n\tlet address = ip.toLowerCase();\n\tconst zoneIndex = address.indexOf(\"%\");\n\tif (zoneIndex !== -1) address = address.slice(0, zoneIndex);\n\tconst halves = address.split(\"::\");\n\tif (halves.length > 2) return null;\n\tconst toGroups = (segment) => {\n\t\tif (segment === \"\") return [];\n\t\tconst groups = [];\n\t\tconst parts = segment.split(\":\");\n\t\tfor (let i = 0; i < parts.length; i++) {\n\t\t\tconst part = parts[i];\n\t\t\tif (part.includes(\".\")) {\n\t\t\t\tif (i !== parts.length - 1 || !isIPv4(part)) return null;\n\t\t\t\tconst [a, b, c, d] = part.split(\".\").map(Number);\n\t\t\t\tgroups.push(a << 8 | b, c << 8 | d);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!/^[0-9a-f]{1,4}$/.test(part)) return null;\n\t\t\tgroups.push(parseInt(part, 16));\n\t\t}\n\t\treturn groups;\n\t};\n\tconst head = toGroups(halves[0]);\n\tif (head === null) return null;\n\tif (halves.length === 2) {\n\t\tconst tail = toGroups(halves[1]);\n\t\tif (tail === null) return null;\n\t\tconst fill = 8 - head.length - tail.length;\n\t\tif (fill < 0) return null;\n\t\treturn [\n\t\t\t...head,\n\t\t\t...new Array(fill).fill(0),\n\t\t\t...tail\n\t\t];\n\t}\n\treturn head.length === 8 ? head : null;\n}\nfunction isPrivateIPv6(ip) {\n\tconst groups = parseIPv6(ip);\n\tif (groups === null) return true;\n\tconst topZero = (count) => groups.slice(0, count).every((group) => group === 0);\n\tif (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true;\n\tif ((groups[0] & 65024) === 64512) return true;\n\tif ((groups[0] & 65472) === 65152) return true;\n\tif ((groups[0] & 65472) === 65216) return true;\n\tif ((groups[0] & 65280) === 65280) return true;\n\tif (groups[0] === 8193 && groups[1] === 3512) return true;\n\tif (groups[0] === 16383 && (groups[1] & 61440) === 0) return true;\n\tif (topZero(6) || topZero(5) && groups[5] === 65535 || topZero(4) && groups[4] === 65535 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 1) return isPrivateIPv4(`${groups[6] >> 8 & 255}.${groups[6] & 255}.${groups[7] >> 8 & 255}.${groups[7] & 255}`);\n\treturn false;\n}\n//#endregion\n//#region src/safe-node-fetch.ts\n/**\n* Creates a DNS lookup hook that validates every returned address before\n* returning the callback shape requested by the HTTP connector. Because\n* resolution and validation happen inside the connector, the socket is pinned\n* to the validated result and DNS rebinding cannot introduce a second lookup.\n*/\nfunction createSafeLookup(lookup) {\n\treturn ((hostname, options, callback) => {\n\t\tlookup(hostname, {\n\t\t\t...options,\n\t\t\tall: true\n\t\t}, (error, addresses) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst [firstAddress] = addresses;\n\t\t\t\tif (firstAddress == null) throw new Error(`Hostname ${hostname} did not resolve to an address`);\n\t\t\t\tfor (const { address, family } of addresses) validateDownloadAddress({\n\t\t\t\t\taddress,\n\t\t\t\t\tfamily,\n\t\t\t\t\thostname\n\t\t\t\t});\n\t\t\t\tif (options.all === true) callback(null, addresses);\n\t\t\t\telse callback(null, firstAddress.address, firstAddress.family);\n\t\t\t} catch (error) {\n\t\t\t\tcallback(error instanceof Error ? error : new Error(String(error)));\n\t\t\t}\n\t\t});\n\t});\n}\nlet safeNodeFetchPromise;\nfunction isNodeRuntime() {\n\tconst runtimeProcess = globalThis.process;\n\treturn runtimeProcess?.release?.name === \"node\" && runtimeProcess.versions?.bun == null && runtimeProcess.versions?.deno == null && runtimeProcess.title !== \"workerd\" && globalThis.EdgeRuntime == null;\n}\nasync function getDefaultDownloadFetch() {\n\tif (!isNodeRuntime()) return globalThis.fetch;\n\treturn safeNodeFetchPromise ??= Promise.resolve().then(createSafeNodeFetch);\n}\nfunction createSafeNodeFetch() {\n\tconst module = loadBuiltinModule(\"node:module\");\n\tconst { lookup } = loadBuiltinModule(\"node:dns\");\n\tconst { Agent, fetch } = module.createRequire(getCurrentModulePath())(\"undici\");\n\tconst dispatcher = new Agent({ connect: { lookup: createSafeLookup(lookup) } });\n\treturn ((input, init) => fetch(input, {\n\t\t...init,\n\t\tdispatcher\n\t}));\n}\nfunction loadBuiltinModule(id) {\n\tconst builtinModule = globalThis.process?.getBuiltinModule?.(id);\n\tif (builtinModule == null) throw new Error(`Node.js built-in module ${id} is unavailable`);\n\treturn builtinModule;\n}\nfunction getCurrentModulePath() {\n\tconst originalPrepareStackTrace = Error.prepareStackTrace;\n\ttry {\n\t\tError.prepareStackTrace = (_error, callSites) => callSites;\n\t\tconst error = /* @__PURE__ */ new Error(\"Capture current module path\");\n\t\tError.captureStackTrace(error, getCurrentModulePath);\n\t\tconst [caller] = error.stack;\n\t\tconst fileName = caller?.getFileName();\n\t\tif (fileName == null) throw new Error(\"Unable to determine the current module path\");\n\t\treturn fileName;\n\t} finally {\n\t\tError.prepareStackTrace = originalPrepareStackTrace;\n\t}\n}\n//#endregion\n//#region src/sanitize-request-headers.ts\n/**\n* Request headers stripped before fetching an untrusted URL: host/virtual-host\n* routing, proxy/origin spoofing, cloud-metadata, cookies, and hop-by-hop\n* transport headers (RFC 7230 §6.1).\n*\n* `Authorization` and other credential-bearing caller headers (e.g. `x-key`)\n* are intentionally not listed because trusted provider requests may need\n* them. `fetchUntrustedUrl` separately restricts an untrusted first hop to an\n* explicit allowlist of non-credential request metadata. Both it and\n* `fetchWithValidatedRedirects` drop all caller headers except the user-agent\n* on a cross-origin redirect.\n*/\nconst BLOCKED_REQUEST_HEADERS = [\n\t\"connection\",\n\t\"keep-alive\",\n\t\"te\",\n\t\"trailer\",\n\t\"transfer-encoding\",\n\t\"upgrade\",\n\t\"host\",\n\t\"forwarded\",\n\t\"proxy-authorization\",\n\t\"via\",\n\t\"x-forwarded-for\",\n\t\"x-forwarded-host\",\n\t\"x-forwarded-proto\",\n\t\"x-real-ip\",\n\t\"metadata\",\n\t\"metadata-flavor\",\n\t\"x-aws-ec2-metadata-token\",\n\t\"x-metadata-token\",\n\t\"cookie\",\n\t\"set-cookie\"\n];\n/**\n* Returns a fresh `Headers` built from `input` with {@link BLOCKED_REQUEST_HEADERS}\n* removed. The input is never mutated.\n*/\nfunction sanitizeRequestHeaders(input) {\n\tconst headers = new Headers(input);\n\tfor (const name of BLOCKED_REQUEST_HEADERS) headers.delete(name);\n\treturn headers;\n}\n//#endregion\n//#region src/fetch-with-validated-redirects.ts\nconst MAX_DOWNLOAD_REDIRECTS = 10;\nconst REDIRECT_STATUS_CODES = /* @__PURE__ */ new Set([\n\t301,\n\t302,\n\t303,\n\t307,\n\t308\n]);\nasync function getValidatedFetch(customFetch) {\n\treturn customFetch == null || customFetch === globalThis.fetch ? await getDefaultDownloadFetch() : customFetch;\n}\n/**\n* Fetches one validated URL without following redirects.\n*\n* On Node.js, the default fetch validates and pins DNS results at connect time.\n* An injected fetch is responsible for equivalent connect-time validation.\n* Redirects are rejected by default. Callers using `redirect: 'manual'` must\n* validate the Location target before issuing another request.\n*/\nasync function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, trustedOrigin, redirect = \"error\" }) {\n\tconst urlText = url.toString();\n\tconst isTrusted = trustedOrigin !== void 0 && isSameOrigin(urlText, trustedOrigin);\n\tif (!isTrusted) validateDownloadUrl(urlText);\n\treturn await (isTrusted && customFetch != null ? customFetch : isTrusted ? globalThis.fetch : await getValidatedFetch(customFetch))(url, {\n\t\t...init,\n\t\tredirect\n\t});\n}\n/**\n* Fetches a URL while enforcing the download guard on every hop.\n*\n* Redirects are followed manually (`redirect: 'manual'`) so each hop is\n* validated with {@link validateDownloadUrl} *before* it is requested. Relying\n* on the default `redirect: 'follow'` would issue the request to a redirect\n* target (e.g. an internal address) before we ever see its URL, defeating the\n* guard.\n*\n* Request headers are also protected: {@link sanitizeRequestHeaders} strips\n* proxy/metadata/cookie/hop-by-hop headers before the first request, and all\n* caller headers except `User-Agent` are dropped on a cross-origin redirect.\n* Credentials and custom headers are preserved on the first hop for backwards\n* compatibility. The caller must ensure that the initial URL may receive them.\n* Use `fetchUntrustedUrl` for URLs that require first-hop credential isolation.\n* The fetch spec only strips `Authorization` on cross-origin redirects because\n* in a browser, CORS preflighting protects custom headers; there is no CORS on\n* the server, so provider API keys carried in custom headers (e.g. `x-key`)\n* must be dropped here as well.\n*\n* A `redirect: 'manual'` request yields an unreadable opaque response in the\n* browser (and in other spec-compliant fetch implementations), so the redirect\n* target cannot be validated here. In a real browser this is safe to follow\n* natively because reaching an internal network is not possible (fetch is\n* constrained by CORS and cannot reach a server's internal network or\n* cloud-metadata). On any other runtime we cannot validate the hop, so we fail\n* closed rather than follow it blindly and bypass the guard.\n*\n* A hop that is same-origin with `trustedOrigin` (the developer-configured\n* provider endpoint) skips target validation: that origin is exactly what an\n* unvalidated, config-derived request would fetch anyway, and validating it\n* would break legitimate self-hosted / localhost deployments whose response\n* URLs point back at the configured host. Hops on any other origin are always\n* validated.\n*\n* The returned response is the final (non-redirect) response. The caller is\n* responsible for checking `response.ok` and reading the body.\n*\n* On Node.js, the default fetch resolves every hostname through a validating\n* lookup hook and passes those exact addresses to the connector, preventing\n* hostname-to-private-IP and DNS-rebinding bypasses. An injected fetch is\n* responsible for equivalent connect-time validation. Other runtimes should\n* constrain egress at the network layer when handling untrusted URLs.\n*\n* @throws DownloadError if a hop is unsafe, the redirect limit is exceeded, or\n* a redirect cannot be validated on a non-browser runtime.\n*/\nasync function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects = MAX_DOWNLOAD_REDIRECTS, fetch: customFetch, trustedOrigin }) {\n\tlet currentHeaders = headers === void 0 ? void 0 : sanitizeRequestHeaders(headers);\n\tconst perHopInit = (redirect) => {\n\t\tconst init = {\n\t\t\tsignal: abortSignal,\n\t\t\tredirect\n\t\t};\n\t\tif (currentHeaders !== void 0) init.headers = new Headers(currentHeaders);\n\t\treturn init;\n\t};\n\tlet currentUrl = url;\n\tfor (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {\n\t\tconst isTrustedHop = trustedOrigin !== void 0 && isSameOrigin(currentUrl, trustedOrigin);\n\t\tif (!isTrustedHop) validateDownloadUrl(currentUrl);\n\t\tconst fetch = isTrustedHop && customFetch != null ? customFetch : isTrustedHop ? globalThis.fetch : await getValidatedFetch(customFetch);\n\t\tconst response = await fetch(currentUrl, perHopInit(\"manual\"));\n\t\tif (response.type === \"opaqueredirect\") {\n\t\t\tif (!isBrowserRuntime()) throw new DownloadError({\n\t\t\t\turl,\n\t\t\t\tmessage: `Redirect from ${currentUrl} could not be validated and was blocked`\n\t\t\t});\n\t\t\treturn await fetch(currentUrl, perHopInit(\"follow\"));\n\t\t}\n\t\tconst location = response.headers?.get(\"location\");\n\t\tif (REDIRECT_STATUS_CODES.has(response.status) && location) {\n\t\t\tcancelResponseBody(response);\n\t\t\tconst nextUrl = new URL(location, currentUrl).toString();\n\t\t\tif (currentHeaders !== void 0 && !isSameOrigin(nextUrl, currentUrl)) {\n\t\t\t\tconst userAgent = currentHeaders.get(\"user-agent\");\n\t\t\t\tcurrentHeaders = new Headers(userAgent == null ? void 0 : { \"user-agent\": userAgent });\n\t\t\t}\n\t\t\tcurrentUrl = nextUrl;\n\t\t\tcontinue;\n\t\t}\n\t\treturn response;\n\t}\n\tthrow new DownloadError({\n\t\turl,\n\t\tmessage: `Too many redirects (max ${maxRedirects})`\n\t});\n}\n//#endregion\n//#region src/fetch-untrusted-url.ts\nconst SAFE_UNTRUSTED_FIRST_HOP_HEADERS = /* @__PURE__ */ new Set([\n\t\"accept\",\n\t\"accept-language\",\n\t\"baggage\",\n\t\"cache-control\",\n\t\"idempotency-key\",\n\t\"if-match\",\n\t\"if-modified-since\",\n\t\"if-none-match\",\n\t\"if-range\",\n\t\"if-unmodified-since\",\n\t\"pragma\",\n\t\"range\",\n\t\"traceparent\",\n\t\"tracestate\",\n\t\"user-agent\",\n\t\"x-correlation-id\",\n\t\"x-request-id\"\n]);\n/**\n* Fetches an untrusted URL with first-hop credential isolation and validated\n* redirects. Uses the URL validation, DNS-pinned Node.js transport, redirect\n* limits, and cross-origin header stripping of {@link fetchWithValidatedRedirects}.\n* An injected fetch must provide equivalent connect-time DNS validation.\n*\n* Without a matching `credentialedOrigin` (or `trustedOrigin` when it is\n* omitted), only allowlisted request metadata is sent on the first hop.\n* Arbitrary caller headers require an explicit matching origin because vendor\n* credential names cannot be inferred safely. Proxy, metadata, cookie, and\n* hop-by-hop headers are sanitized even for a matching origin.\n*\n* `trustedOrigin` also exempts same-origin hops from URL validation, allowing\n* developer-configured private endpoints. Both origin options must come from\n* developer configuration, never from untrusted response data.\n*\n* This is an opt-in alternative to `fetchWithValidatedRedirects`, whose\n* existing first-hop header behavior is preserved for compatibility.\n*/\nasync function fetchUntrustedUrl({ headers, credentialedOrigin, untrustedFirstHopHeaders, ...options }) {\n\tlet firstHopHeaders;\n\tif (headers !== void 0) {\n\t\tfirstHopHeaders = sanitizeRequestHeaders(headers);\n\t\tconst origin = credentialedOrigin ?? options.trustedOrigin;\n\t\tif (origin === void 0 || !isSameOrigin(options.url, origin)) {\n\t\t\tconst allowedHeaders = /* @__PURE__ */ new Set([...SAFE_UNTRUSTED_FIRST_HOP_HEADERS, ...(untrustedFirstHopHeaders ?? []).map((name) => name.toLowerCase())]);\n\t\t\tfirstHopHeaders = new Headers([...firstHopHeaders].filter(([name]) => allowedHeaders.has(name)));\n\t\t}\n\t}\n\treturn fetchWithValidatedRedirects({\n\t\t...options,\n\t\theaders: firstHopHeaders\n\t});\n}\n//#endregion\n//#region src/read-response-with-size-limit.ts\n/**\n* Default maximum download size: 2 GiB.\n*\n* `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the\n* body internally, then creates the JS ArrayBuffer), so very large downloads\n* risk exceeding the default V8 heap limit on 64-bit systems and terminating\n* the process with an out-of-memory error.\n*\n* Setting this limit converts an unrecoverable OOM crash into a catchable\n* `DownloadError`.\n*/\nconst DEFAULT_MAX_DOWNLOAD_SIZE = 2147483648;\n/**\n* Reads a fetch Response body with a size limit to prevent memory exhaustion.\n*\n* Checks the Content-Length header for early rejection, then reads the body\n* incrementally via ReadableStream and aborts with a DownloadError when the\n* limit is exceeded.\n*\n* @param response - The fetch Response to read.\n* @param url - The URL being downloaded (used in error messages).\n* @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.\n* @returns A Uint8Array containing the response body.\n* @throws DownloadError if the response exceeds maxBytes.\n*/\nasync function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) {\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength != null) {\n\t\tconst length = parseInt(contentLength, 10);\n\t\tif (!isNaN(length) && length > maxBytes) {\n\t\t\tawait cancelResponseBody(response);\n\t\t\tthrow new DownloadError({\n\t\t\t\turl,\n\t\t\t\tmessage: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`\n\t\t\t});\n\t\t}\n\t}\n\tconst body = response.body;\n\tif (body == null) return /* @__PURE__ */ new Uint8Array(0);\n\tconst reader = body.getReader();\n\tconst chunks = [];\n\tlet totalBytes = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\ttotalBytes += value.length;\n\t\t\tif (totalBytes > maxBytes) throw new DownloadError({\n\t\t\t\turl,\n\t\t\t\tmessage: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`\n\t\t\t});\n\t\t\tchunks.push(value);\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} catch {} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t}\n\tconst result = new Uint8Array(totalBytes);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tresult.set(chunk, offset);\n\t\toffset += chunk.length;\n\t}\n\treturn result;\n}\n//#endregion\n//#region src/download-blob.ts\n/**\n* Download a file from a URL and return it as a Blob.\n*\n* @param url - The URL to download from.\n* @param options - Optional settings for the download.\n* @param options.maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.\n* @param options.abortSignal - An optional abort signal to cancel the download.\n* @returns A Promise that resolves to the downloaded Blob.\n*\n* @throws DownloadError if the download fails or exceeds maxBytes.\n*/\nasync function downloadBlob(url, options) {\n\ttry {\n\t\tconst response = await fetchUntrustedUrl({\n\t\t\turl,\n\t\t\tabortSignal: options?.abortSignal\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tawait cancelResponseBody(response);\n\t\t\tthrow new DownloadError({\n\t\t\t\turl,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tstatusText: response.statusText\n\t\t\t});\n\t\t}\n\t\tconst data = await readResponseWithSizeLimit({\n\t\t\tresponse,\n\t\t\turl,\n\t\t\tmaxBytes: options?.maxBytes ?? 2147483648\n\t\t});\n\t\tconst contentType = response.headers.get(\"content-type\") ?? void 0;\n\t\treturn new Blob([data], contentType ? { type: contentType } : void 0);\n\t} catch (error) {\n\t\tif (DownloadError.isInstance(error)) throw error;\n\t\tthrow new DownloadError({\n\t\t\turl,\n\t\t\tcause: error\n\t\t});\n\t}\n}\n//#endregion\n//#region src/embedding-model-capabilities.ts\n/**\n* Symbol for exposing the UTF-8 input byte budget of an embedding model.\n*\n* This capability is experimental and intentionally lives outside the versioned\n* embedding model specification.\n*/\nconst EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL = Symbol.for(\"vercel.ai.embeddingModel.maxInputBytesPerCall\");\n/**\n* Symbol for transforming provider options for an automatically batched\n* embedding model call.\n*\n* This capability is experimental and intentionally lives outside the versioned\n* embedding model specification.\n*/\nconst EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER = Symbol.for(\"vercel.ai.embeddingModel.providerOptionsTransformer\");\n//#endregion\n//#region src/extract-lines.ts\n/**\n* Extracts a 1-based inclusive line range from `text`, auto-detecting the\n* file's line ending (`\\r\\n`, `\\n`, or `\\r`, in that priority).\n*\n* Mixed line endings are not supported: detection picks one and uses it for\n* both the split and the rejoin, so files that mix conventions will not slice\n* cleanly. When neither `startLine` nor `endLine` is provided, the input is\n* returned unchanged. `endLine` past EOF clamps to the last line.\n*/\nfunction extractLines({ text, startLine, endLine }) {\n\tif (startLine == null && endLine == null) return text;\n\tconst lineEnding = text.includes(\"\\r\\n\") ? \"\\r\\n\" : text.includes(\"\\n\") ? \"\\n\" : text.includes(\"\\r\") ? \"\\r\" : \"\\n\";\n\tconst lines = text.split(lineEnding);\n\tconst start = Math.max(1, startLine ?? 1) - 1;\n\tconst end = Math.min(lines.length, endLine ?? lines.length);\n\treturn lines.slice(start, end).join(lineEnding);\n}\n//#endregion\n//#region src/filter-nullable.ts\n/**\n* Filters `null` and `undefined` values out of a list of values.\n*\n* @param values - The values to filter.\n* @returns A new array containing only non-nullish values.\n*/\nfunction filterNullable(...values) {\n\treturn values.filter((value) => value != null);\n}\n//#endregion\n//#region src/generate-id.ts\n/**\n* Creates an ID generator.\n* The total length of the ID is the sum of the prefix, separator, and random part length.\n* Not cryptographically secure.\n*\n* @param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.\n* @param prefix - The prefix of the ID to generate. Optional.\n* @param separator - The separator between the prefix and the random part of the ID. Default: '-'.\n* @param size - The size of the random part of the ID to generate. Default: 16.\n*/\nconst createIdGenerator = ({ prefix, size = 16, alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\", separator = \"-\" } = {}) => {\n\tconst generator = () => {\n\t\tconst alphabetLength = alphabet.length;\n\t\tconst chars = new Array(size);\n\t\tfor (let i = 0; i < size; i++) chars[i] = alphabet[Math.random() * alphabetLength | 0];\n\t\treturn chars.join(\"\");\n\t};\n\tif (prefix == null) return generator;\n\tif (alphabet.includes(separator)) throw new InvalidArgumentError({\n\t\targument: \"separator\",\n\t\tmessage: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`\n\t});\n\treturn () => `${prefix}${separator}${generator()}`;\n};\n/**\n* Generates a 16-character random string to use for IDs.\n* Not cryptographically secure.\n*/\nconst generateId = createIdGenerator();\n//#endregion\n//#region src/get-from-api.ts\nconst getOriginalFetch$2 = () => globalThis.fetch;\nconst getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin }) => {\n\ttry {\n\t\tconst requestFetch = fetch ?? getOriginalFetch$2();\n\t\tconst requestHeaders = withUserAgentSuffix(credentialedOrigin !== void 0 && !isSameOrigin(url, credentialedOrigin) ? {} : headers, `ai-sdk-provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent());\n\t\tconst response = validateUrl ? await fetchWithValidatedRedirects({\n\t\t\turl,\n\t\t\theaders: requestHeaders,\n\t\t\tabortSignal,\n\t\t\tfetch,\n\t\t\ttrustedOrigin\n\t\t}) : await requestFetch(url, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: requestHeaders,\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tconst responseHeaders = extractResponseHeaders(response);\n\t\tif (!response.ok) {\n\t\t\tlet errorInformation;\n\t\t\ttry {\n\t\t\t\terrorInformation = await failedResponseHandler({\n\t\t\t\t\tresponse,\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues: {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t\tthrow new APICallError({\n\t\t\t\t\tmessage: \"Failed to process error response\",\n\t\t\t\t\tcause: error,\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\turl,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t\trequestBodyValues: {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow errorInformation.value;\n\t\t}\n\t\ttry {\n\t\t\treturn await successfulResponseHandler({\n\t\t\t\tresponse,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues: {}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t}\n\t\t\tthrow new APICallError({\n\t\t\t\tmessage: \"Failed to process successful response\",\n\t\t\t\tcause: error,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\turl,\n\t\t\t\tresponseHeaders,\n\t\t\t\trequestBodyValues: {}\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tthrow handleFetchError({\n\t\t\terror,\n\t\t\turl,\n\t\t\trequestBodyValues: {}\n\t\t});\n\t}\n};\n//#endregion\n//#region src/inject-json-instruction.ts\nconst DEFAULT_SCHEMA_PREFIX = \"JSON schema:\";\nconst DEFAULT_SCHEMA_SUFFIX = \"You MUST answer with a JSON object that matches the JSON schema above.\";\nconst DEFAULT_GENERIC_SUFFIX = \"You MUST answer with JSON.\";\nfunction injectJsonInstruction({ prompt, schema, schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0, schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX }) {\n\treturn [\n\t\tprompt != null && prompt.length > 0 ? prompt : void 0,\n\t\tprompt != null && prompt.length > 0 ? \"\" : void 0,\n\t\tschemaPrefix,\n\t\tschema != null ? JSON.stringify(schema) : void 0,\n\t\tschemaSuffix\n\t].filter((line) => line != null).join(\"\\n\");\n}\nfunction injectJsonInstructionIntoMessages({ messages, schema, schemaPrefix, schemaSuffix }) {\n\tconst systemMessage = messages[0]?.role === \"system\" ? { ...messages[0] } : {\n\t\trole: \"system\",\n\t\tcontent: \"\"\n\t};\n\tsystemMessage.content = injectJsonInstruction({\n\t\tprompt: systemMessage.content,\n\t\tschema,\n\t\tschemaPrefix,\n\t\tschemaSuffix\n\t});\n\treturn [systemMessage, ...messages[0]?.role === \"system\" ? messages.slice(1) : messages];\n}\n//#endregion\n//#region src/is-buffer.ts\n/**\n* Type-guard for Node.js `Buffer` instances.\n*\n* Uses optional chaining on `globalThis.Buffer` so it returns `false` in\n* runtimes where `Buffer` is not available (e.g. CloudFlare Workers).\n*/\nfunction isBuffer(value) {\n\treturn globalThis.Buffer?.isBuffer(value) ?? false;\n}\n//#endregion\n//#region src/is-non-nullable.ts\n/**\n* Type guard that checks whether a value is not `null` or `undefined`.\n*\n* @template T - The type of the value to check.\n* @param value - The value to check.\n* @returns `true` if the value is neither `null` nor `undefined`, otherwise `false`.\n*/\nfunction isNonNullable(value) {\n\treturn value != null;\n}\n//#endregion\n//#region src/is-provider-reference.ts\n/**\n* Checks whether a value is a provider reference (a mapping of provider names\n* to provider-specific identifiers) as opposed to raw bytes, a URL, or a\n* tagged `{ type: ... }` object.\n*/\nfunction isProviderReference(data) {\n\treturn typeof data === \"object\" && data !== null && !(data instanceof Uint8Array) && !(data instanceof URL) && !(data instanceof ArrayBuffer) && !isBuffer(data) && !(\"type\" in data);\n}\n//#endregion\n//#region src/is-record.ts\n/**\n* Checks whether a value is a non-null, non-array object.\n*/\nfunction isRecord(value) {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value);\n}\n//#endregion\n//#region src/is-url-supported.ts\n/**\n* Checks if the given URL is supported natively by the model.\n*\n* @param mediaType - The media type of the URL. Case-insensitive. May be a full\n* `type/subtype`, a wildcard `type/*`, or just the\n* top-level segment (e.g. `image`).\n* @param url - The URL to check.\n* @param supportedUrls - A record where keys are case-insensitive media types (or '*')\n* and values are arrays of RegExp patterns for URLs.\n*\n* @returns `true` if the URL matches a pattern under the specific media type\n* or the wildcard '*', `false` otherwise.\n*/\nfunction isUrlSupported({ mediaType, url, supportedUrls }) {\n\turl = url.toLowerCase();\n\tmediaType = mediaType.toLowerCase();\n\tconst isTopLevelOnly = !mediaType.includes(\"/\");\n\treturn Object.entries(supportedUrls).map(([key, value]) => {\n\t\tconst mediaType = key.toLowerCase();\n\t\treturn mediaType === \"*\" || mediaType === \"*/*\" ? {\n\t\t\tmediaTypePrefix: \"\",\n\t\t\tregexes: value\n\t\t} : {\n\t\t\tmediaTypePrefix: mediaType.replace(/\\*/, \"\"),\n\t\t\tregexes: value\n\t\t};\n\t}).filter(({ mediaTypePrefix }) => {\n\t\tif (mediaTypePrefix === \"\") return true;\n\t\tif (isTopLevelOnly) return `${mediaType}/` === mediaTypePrefix;\n\t\treturn mediaTypePrefix.endsWith(\"/\") ? mediaType.startsWith(mediaTypePrefix) : mediaType === mediaTypePrefix;\n\t}).flatMap(({ regexes }) => regexes).some((pattern) => testRegExpFromStart(pattern, url));\n}\nfunction testRegExpFromStart(pattern, value) {\n\tif (!pattern.global && !pattern.sticky) return pattern.test(value);\n\tconst lastIndex = pattern.lastIndex;\n\tpattern.lastIndex = 0;\n\ttry {\n\t\treturn pattern.test(value);\n\t} finally {\n\t\tpattern.lastIndex = lastIndex;\n\t}\n}\n//#endregion\n//#region src/is-valid-hostname-part.ts\n/**\n* Checks whether a value is a valid ASCII hostname part: 1–63 letters, digits,\n* or hyphens, without a leading or trailing hyphen.\n*\n* Use this before inserting a resource name, region, or location into a\n* generated hostname. Rejects values such as `evil.example.com/#` and\n* `user@localhost:8080/#` that could change the request destination.\n*/\nfunction isValidHostnamePart(value) {\n\treturn /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.exec(value)?.[0] === value;\n}\n//#endregion\n//#region src/load-api-key.ts\nfunction loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName = \"apiKey\", description }) {\n\tif (typeof apiKey === \"string\") return apiKey;\n\tif (apiKey != null) throw new LoadAPIKeyError({ message: `${description} API key must be a string.` });\n\tif (typeof process === \"undefined\") throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.` });\n\tapiKey = process.env[environmentVariableName];\n\tif (apiKey == null) throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` });\n\tif (typeof apiKey !== \"string\") throw new LoadAPIKeyError({ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.` });\n\treturn apiKey;\n}\n//#endregion\n//#region src/load-optional-setting.ts\n/**\n* Loads an optional `string` setting from the environment or a parameter.\n*\n* @param settingValue - The setting value.\n* @param environmentVariableName - The environment variable name.\n* @returns The setting value.\n*/\nfunction loadOptionalSetting({ settingValue, environmentVariableName }) {\n\tif (typeof settingValue === \"string\") return settingValue;\n\tif (settingValue != null || typeof process === \"undefined\") return;\n\tsettingValue = process.env[environmentVariableName];\n\tif (settingValue == null || typeof settingValue !== \"string\") return;\n\treturn settingValue;\n}\n//#endregion\n//#region src/load-setting.ts\n/**\n* Loads a `string` setting from the environment or a parameter.\n*\n* @param settingValue - The setting value.\n* @param environmentVariableName - The environment variable name.\n* @param settingName - The setting name.\n* @param description - The description of the setting.\n* @returns The setting value.\n*/\nfunction loadSetting({ settingValue, environmentVariableName, settingName, description }) {\n\tif (typeof settingValue === \"string\") return settingValue;\n\tif (settingValue != null) throw new LoadSettingError({ message: `${description} setting must be a string.` });\n\tif (typeof process === \"undefined\") throw new LoadSettingError({ message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables are not supported in this environment.` });\n\tsettingValue = process.env[environmentVariableName];\n\tif (settingValue == null) throw new LoadSettingError({ message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.` });\n\tif (typeof settingValue !== \"string\") throw new LoadSettingError({ message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.` });\n\treturn settingValue;\n}\n//#endregion\n//#region src/map-reasoning-to-provider.ts\nfunction isCustomReasoning(reasoning) {\n\treturn reasoning !== void 0 && reasoning !== \"provider-default\";\n}\n/**\n* Maps a top-level reasoning level to a provider-specific effort string using\n* the given effort map. Pushes a compatibility warning if the reasoning level\n* maps to a different string, or an unsupported warning if the level is not\n* present in the map.\n*\n* @returns The mapped effort string, or `undefined` if the level is not\n* supported.\n*/\nfunction mapReasoningToProviderEffort({ reasoning, effortMap, warnings }) {\n\tconst mapped = effortMap[reasoning];\n\tif (mapped == null) {\n\t\twarnings.push({\n\t\t\ttype: \"unsupported\",\n\t\t\tfeature: \"reasoning\",\n\t\t\tdetails: `reasoning \"${reasoning}\" is not supported by this model.`\n\t\t});\n\t\treturn;\n\t}\n\tif (mapped !== reasoning) warnings.push({\n\t\ttype: \"compatibility\",\n\t\tfeature: \"reasoning\",\n\t\tdetails: `reasoning \"${reasoning}\" is not directly supported by this model. mapped to effort \"${mapped}\".`\n\t});\n\treturn mapped;\n}\nconst DEFAULT_REASONING_BUDGET_PERCENTAGES = {\n\tminimal: .02,\n\tlow: .1,\n\tmedium: .3,\n\thigh: .6,\n\txhigh: .9,\n\tmax: .95\n};\n/**\n* Maps a top-level reasoning level to an absolute token budget by multiplying\n* the model's max output tokens by a percentage from the budget percentages\n* map. The result is clamped between `minReasoningBudget` (default 1024) and\n* `maxReasoningBudget`. Pushes an unsupported warning if the level is not\n* present in the budget percentages map.\n*\n* @returns The computed token budget, or `undefined` if the level is not\n* supported.\n*/\nfunction mapReasoningToProviderBudget({ reasoning, maxOutputTokens, maxReasoningBudget, minReasoningBudget = 1024, budgetPercentages = DEFAULT_REASONING_BUDGET_PERCENTAGES, warnings }) {\n\tconst pct = budgetPercentages[reasoning];\n\tif (pct == null) {\n\t\twarnings.push({\n\t\t\ttype: \"unsupported\",\n\t\t\tfeature: \"reasoning\",\n\t\t\tdetails: `reasoning \"${reasoning}\" is not supported by this model.`\n\t\t});\n\t\treturn;\n\t}\n\treturn Math.min(maxReasoningBudget, Math.max(minReasoningBudget, Math.round(maxOutputTokens * pct)));\n}\n//#endregion\n//#region src/media-type-to-extension.ts\n/**\n* Maps a media type to its corresponding file extension.\n* It was originally introduced to set a filename for audio file uploads\n* in https://github.com/vercel/ai/pull/8159.\n*\n* @param mediaType The media type to map.\n* @returns The corresponding file extension\n* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n*/\nfunction mediaTypeToExtension(mediaType) {\n\tconst [_type, subtype = \"\"] = mediaType.toLowerCase().split(\"/\");\n\treturn {\n\t\tmpeg: \"mp3\",\n\t\t\"x-wav\": \"wav\",\n\t\topus: \"ogg\",\n\t\tmp4: \"m4a\",\n\t\t\"x-m4a\": \"m4a\"\n\t}[subtype] ?? subtype;\n}\n//#endregion\n//#region src/normalize-batch-request-counts.ts\n/**\n* Normalizes complete batch request counts.\n*\n* Returns `undefined` when any count is missing, is not a non-negative safe\n* integer, or when the item counts do not add up to the total.\n*/\nfunction normalizeBatchRequestCounts({ total, pending, completed, failed }) {\n\tif (isNonNegativeSafeInteger(total) && isNonNegativeSafeInteger(pending) && isNonNegativeSafeInteger(completed) && isNonNegativeSafeInteger(failed) && pending + completed + failed === total) return {\n\t\ttotal,\n\t\tpending,\n\t\tcompleted,\n\t\tfailed\n\t};\n}\nfunction isNonNegativeSafeInteger(value) {\n\treturn value != null && Number.isSafeInteger(value) && value >= 0;\n}\n//#endregion\n//#region src/secure-json-parse.ts\nconst suspectProtoRx = /\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*:/;\nconst suspectConstructorRx = /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/;\nfunction _parse(text) {\n\tconst obj = JSON.parse(text);\n\tif (obj === null || typeof obj !== \"object\") return obj;\n\tif (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) return obj;\n\treturn filter(obj);\n}\nfunction filter(obj) {\n\tlet next = [obj];\n\twhile (next.length) {\n\t\tconst nodes = next;\n\t\tnext = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(node, \"__proto__\")) throw new SyntaxError(\"Object contains forbidden prototype property\");\n\t\t\tif (Object.prototype.hasOwnProperty.call(node, \"constructor\") && node.constructor !== null && typeof node.constructor === \"object\" && Object.prototype.hasOwnProperty.call(node.constructor, \"prototype\")) throw new SyntaxError(\"Object contains forbidden prototype property\");\n\t\t\tfor (const key in node) {\n\t\t\t\tconst value = node[key];\n\t\t\t\tif (value && typeof value === \"object\") next.push(value);\n\t\t\t}\n\t\t}\n\t}\n\treturn obj;\n}\nfunction secureJsonParse(text) {\n\tconst { stackTraceLimit } = Error;\n\ttry {\n\t\tError.stackTraceLimit = 0;\n\t} catch {\n\t\treturn _parse(text);\n\t}\n\ttry {\n\t\treturn _parse(text);\n\t} finally {\n\t\tError.stackTraceLimit = stackTraceLimit;\n\t}\n}\n//#endregion\n//#region src/add-additional-properties-to-json-schema.ts\n/**\n* Recursively adds additionalProperties: false to object schemas that do not\n* define a schema for their additional properties. This is necessary because\n* some providers (e.g. OpenAI) do not support additionalProperties: true.\n*/\nfunction addAdditionalPropertiesToJsonSchema(jsonSchema) {\n\tif (jsonSchema.type === \"object\" || Array.isArray(jsonSchema.type) && jsonSchema.type.includes(\"object\")) {\n\t\tconst { additionalProperties } = jsonSchema;\n\t\tjsonSchema.additionalProperties = additionalProperties != null && typeof additionalProperties !== \"boolean\" ? visit(additionalProperties) : false;\n\t\tconst { properties } = jsonSchema;\n\t\tif (properties != null) for (const key of Object.keys(properties)) properties[key] = visit(properties[key]);\n\t}\n\tif (jsonSchema.items != null) jsonSchema.items = Array.isArray(jsonSchema.items) ? jsonSchema.items.map(visit) : visit(jsonSchema.items);\n\tif (jsonSchema.anyOf != null) jsonSchema.anyOf = jsonSchema.anyOf.map(visit);\n\tif (jsonSchema.allOf != null) jsonSchema.allOf = jsonSchema.allOf.map(visit);\n\tif (jsonSchema.oneOf != null) jsonSchema.oneOf = jsonSchema.oneOf.map(visit);\n\tconst { definitions } = jsonSchema;\n\tif (definitions != null) for (const key of Object.keys(definitions)) definitions[key] = visit(definitions[key]);\n\treturn jsonSchema;\n}\nfunction visit(def) {\n\tif (typeof def === \"boolean\") return def;\n\treturn addAdditionalPropertiesToJsonSchema(def);\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/options.ts\nconst ignoreOverride = Symbol(\"Let zodToJsonSchema decide on which parser to use\");\nconst defaultOptions = {\n\tname: void 0,\n\t$refStrategy: \"root\",\n\tbasePath: [\"#\"],\n\teffectStrategy: \"input\",\n\tpipeStrategy: \"all\",\n\tdateStrategy: \"format:date-time\",\n\tmapStrategy: \"entries\",\n\tremoveAdditionalStrategy: \"passthrough\",\n\tallowedAdditionalProperties: true,\n\trejectedAdditionalProperties: false,\n\tdefinitionPath: \"definitions\",\n\tstrictUnions: false,\n\tdefinitions: {},\n\terrorMessages: false,\n\tpatternStrategy: \"escape\",\n\tapplyRegexFlags: false,\n\temailStrategy: \"format:email\",\n\tbase64Strategy: \"contentEncoding:base64\",\n\tnameStrategy: \"ref\"\n};\nconst getDefaultOptions = (options) => typeof options === \"string\" ? {\n\t...defaultOptions,\n\tname: options\n} : {\n\t...defaultOptions,\n\t...options\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/any.ts\nfunction parseAnyDef() {\n\treturn {};\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/array.ts\nfunction parseArrayDef(def, refs) {\n\tconst res = { type: \"array\" };\n\tif (def.type?._def && def.type?._def?.typeName !== \"ZodAny\") res.items = parseDef(def.type._def, {\n\t\t...refs,\n\t\tcurrentPath: [...refs.currentPath, \"items\"]\n\t});\n\tif (def.minLength) res.minItems = def.minLength.value;\n\tif (def.maxLength) res.maxItems = def.maxLength.value;\n\tif (def.exactLength) {\n\t\tres.minItems = def.exactLength.value;\n\t\tres.maxItems = def.exactLength.value;\n\t}\n\treturn res;\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts\nfunction parseBigintDef(def) {\n\tconst res = {\n\t\ttype: \"integer\",\n\t\tformat: \"int64\"\n\t};\n\tif (!def.checks) return res;\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tif (check.inclusive) res.minimum = check.value;\n\t\t\telse res.exclusiveMinimum = check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tif (check.inclusive) res.maximum = check.value;\n\t\t\telse res.exclusiveMaximum = check.value;\n\t\t\tbreak;\n\t\tcase \"multipleOf\": res.multipleOf = check.value;\n\t}\n\treturn res;\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts\nfunction parseBooleanDef() {\n\treturn { type: \"boolean\" };\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/branded.ts\nfunction parseBrandedDef(_def, refs) {\n\treturn parseDef(_def.type._def, refs);\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/catch.ts\nconst parseCatchDef = (def, refs) => {\n\treturn parseDef(def.innerType._def, refs);\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/date.ts\nfunction parseDateDef(def, refs, overrideDateStrategy) {\n\tconst strategy = overrideDateStrategy ?? refs.dateStrategy;\n\tif (Array.isArray(strategy)) return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) };\n\tswitch (strategy) {\n\t\tcase \"string\":\n\t\tcase \"format:date-time\": return {\n\t\t\ttype: \"string\",\n\t\t\tformat: \"date-time\"\n\t\t};\n\t\tcase \"format:date\": return {\n\t\t\ttype: \"string\",\n\t\t\tformat: \"date\"\n\t\t};\n\t\tcase \"integer\": return integerDateParser(def);\n\t}\n}\nconst integerDateParser = (def) => {\n\tconst res = {\n\t\ttype: \"integer\",\n\t\tformat: \"unix-time\"\n\t};\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tres.minimum = check.value;\n\t\t\tbreak;\n\t\tcase \"max\": res.maximum = check.value;\n\t}\n\treturn res;\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/default.ts\nfunction parseDefaultDef(_def, refs) {\n\treturn {\n\t\t...parseDef(_def.innerType._def, refs),\n\t\tdefault: _def.defaultValue()\n\t};\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/effects.ts\nfunction parseEffectsDef(_def, refs) {\n\treturn refs.effectStrategy === \"input\" ? parseDef(_def.schema._def, refs) : parseAnyDef();\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/enum.ts\nfunction parseEnumDef(def) {\n\treturn {\n\t\ttype: \"string\",\n\t\tenum: Array.from(def.values)\n\t};\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts\nconst isJsonSchema7AllOfType = (type) => {\n\tif (\"type\" in type && type.type === \"string\") return false;\n\treturn \"allOf\" in type;\n};\nfunction parseIntersectionDef(def, refs) {\n\tconst allOf = [parseDef(def.left._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"0\"\n\t\t]\n\t}), parseDef(def.right._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"1\"\n\t\t]\n\t})].filter((x) => !!x);\n\tconst mergedAllOf = [];\n\tallOf.forEach((schema) => {\n\t\tif (isJsonSchema7AllOfType(schema)) mergedAllOf.push(...schema.allOf);\n\t\telse {\n\t\t\tlet nestedSchema = schema;\n\t\t\tif (\"additionalProperties\" in schema && schema.additionalProperties === false) {\n\t\t\t\tconst { additionalProperties: _additionalProperties, ...rest } = schema;\n\t\t\t\tnestedSchema = rest;\n\t\t\t}\n\t\t\tmergedAllOf.push(nestedSchema);\n\t\t}\n\t});\n\treturn mergedAllOf.length ? { allOf: mergedAllOf } : void 0;\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/literal.ts\nfunction parseLiteralDef(def) {\n\tconst parsedType = typeof def.value;\n\tif (parsedType !== \"bigint\" && parsedType !== \"number\" && parsedType !== \"boolean\" && parsedType !== \"string\") return { type: Array.isArray(def.value) ? \"array\" : \"object\" };\n\treturn {\n\t\ttype: parsedType === \"bigint\" ? \"integer\" : parsedType,\n\t\tconst: def.value\n\t};\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/string.ts\nlet emojiRegex = void 0;\n/**\n* Generated from the regular expressions found here as of 2024-05-22:\n* https://github.com/colinhacks/zod/blob/master/src/types.ts.\n*\n* Expressions with /i flag have been changed accordingly.\n*/\nconst zodPatterns = {\n\t/**\n\t* `c` was changed to `[cC]` to replicate /i flag\n\t*/\n\tcuid: /^[cC][^\\s-]{8,}$/,\n\tcuid2: /^[0-9a-z]+$/,\n\tulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n\t/**\n\t* `a-z` was added to replicate /i flag\n\t*/\n\temail: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9-]*\\.)+[a-zA-Z]{2,}$/,\n\t/**\n\t* Constructed a valid Unicode RegExp\n\t*\n\t* Lazily instantiate since this type of regex isn't supported\n\t* in all envs (e.g. React Native).\n\t*\n\t* See:\n\t* https://github.com/colinhacks/zod/issues/2433\n\t* Fix in Zod:\n\t* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n\t*/\n\temoji: () => {\n\t\tif (emojiRegex === void 0) emojiRegex = RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\");\n\t\treturn emojiRegex;\n\t},\n\t/**\n\t* Unused\n\t*/\n\tuuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n\t/**\n\t* Unused\n\t*/\n\tipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n\tipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n\t/**\n\t* Unused\n\t*/\n\tipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n\tipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n\tbase64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n\tbase64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n\tnanoid: /^[a-zA-Z0-9_-]{21}$/,\n\tjwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/\n};\nfunction parseStringDef(def, refs) {\n\tconst res = { type: \"string\" };\n\tif (def.checks) for (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tres.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tres.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n\t\t\tbreak;\n\t\tcase \"email\":\n\t\t\tswitch (refs.emailStrategy) {\n\t\t\t\tcase \"format:email\":\n\t\t\t\t\taddFormat(res, \"email\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"format:idn-email\":\n\t\t\t\t\taddFormat(res, \"idn-email\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"pattern:zod\": addPattern(res, zodPatterns.email, check.message, refs);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"url\":\n\t\t\taddFormat(res, \"uri\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"uuid\":\n\t\t\taddFormat(res, \"uuid\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"regex\":\n\t\t\taddPattern(res, check.regex, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cuid\":\n\t\t\taddPattern(res, zodPatterns.cuid, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cuid2\":\n\t\t\taddPattern(res, zodPatterns.cuid2, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"startsWith\":\n\t\t\taddPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"endsWith\":\n\t\t\taddPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"datetime\":\n\t\t\taddFormat(res, \"date-time\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"date\":\n\t\t\taddFormat(res, \"date\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"time\":\n\t\t\taddFormat(res, \"time\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"duration\":\n\t\t\taddFormat(res, \"duration\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"length\":\n\t\t\tres.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n\t\t\tres.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n\t\t\tbreak;\n\t\tcase \"includes\":\n\t\t\taddPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"ip\":\n\t\t\tif (check.version !== \"v6\") addFormat(res, \"ipv4\", check.message, refs);\n\t\t\tif (check.version !== \"v4\") addFormat(res, \"ipv6\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"base64url\":\n\t\t\taddPattern(res, zodPatterns.base64url, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"jwt\":\n\t\t\taddPattern(res, zodPatterns.jwt, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cidr\":\n\t\t\tif (check.version !== \"v6\") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n\t\t\tif (check.version !== \"v4\") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"emoji\":\n\t\t\taddPattern(res, zodPatterns.emoji(), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"ulid\":\n\t\t\taddPattern(res, zodPatterns.ulid, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"base64\":\n\t\t\tswitch (refs.base64Strategy) {\n\t\t\t\tcase \"format:binary\":\n\t\t\t\t\taddFormat(res, \"binary\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"contentEncoding:base64\":\n\t\t\t\t\tres.contentEncoding = \"base64\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"pattern:zod\": addPattern(res, zodPatterns.base64, check.message, refs);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"nanoid\": addPattern(res, zodPatterns.nanoid, check.message, refs);\n\t}\n\treturn res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n\treturn refs.patternStrategy === \"escape\" ? escapeNonAlphaNumeric(literal) : literal;\n}\nconst ALPHA_NUMERIC = /* @__PURE__ */ new Set(\"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\");\nfunction escapeNonAlphaNumeric(source) {\n\tlet result = \"\";\n\tfor (let i = 0; i < source.length; i++) {\n\t\tif (!ALPHA_NUMERIC.has(source[i])) result += \"\\\\\";\n\t\tresult += source[i];\n\t}\n\treturn result;\n}\nfunction addFormat(schema, value, message, refs) {\n\tif (schema.format || schema.anyOf?.some((x) => x.format)) {\n\t\tif (!schema.anyOf) schema.anyOf = [];\n\t\tif (schema.format) {\n\t\t\tschema.anyOf.push({ format: schema.format });\n\t\t\tdelete schema.format;\n\t\t}\n\t\tschema.anyOf.push({\n\t\t\tformat: value,\n\t\t\t...message && refs.errorMessages && { errorMessage: { format: message } }\n\t\t});\n\t} else schema.format = value;\n}\nfunction addPattern(schema, regex, message, refs) {\n\tif (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n\t\tif (!schema.allOf) schema.allOf = [];\n\t\tif (schema.pattern) {\n\t\t\tschema.allOf.push({ pattern: schema.pattern });\n\t\t\tdelete schema.pattern;\n\t\t}\n\t\tschema.allOf.push({\n\t\t\tpattern: stringifyRegExpWithFlags(regex, refs),\n\t\t\t...message && refs.errorMessages && { errorMessage: { pattern: message } }\n\t\t});\n\t} else schema.pattern = stringifyRegExpWithFlags(regex, refs);\n}\nfunction stringifyRegExpWithFlags(regex, refs) {\n\tif (!refs.applyRegexFlags || !regex.flags) return regex.source;\n\tconst flags = {\n\t\ti: regex.flags.includes(\"i\"),\n\t\tm: regex.flags.includes(\"m\"),\n\t\ts: regex.flags.includes(\"s\")\n\t};\n\tconst source = flags.i ? regex.source.toLowerCase() : regex.source;\n\tlet pattern = \"\";\n\tlet isEscaped = false;\n\tlet inCharGroup = false;\n\tlet inCharRange = false;\n\tfor (let i = 0; i < source.length; i++) {\n\t\tif (isEscaped) {\n\t\t\tpattern += source[i];\n\t\t\tisEscaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (flags.i) {\n\t\t\tif (inCharGroup) {\n\t\t\t\tif (source[i].match(/[a-z]/)) {\n\t\t\t\t\tif (inCharRange) {\n\t\t\t\t\t\tpattern += source[i];\n\t\t\t\t\t\tpattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n\t\t\t\t\t\tinCharRange = false;\n\t\t\t\t\t} else if (source[i + 1] === \"-\" && source[i + 2]?.match(/[a-z]/)) {\n\t\t\t\t\t\tpattern += source[i];\n\t\t\t\t\t\tinCharRange = true;\n\t\t\t\t\t} else pattern += `${source[i]}${source[i].toUpperCase()}`;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (source[i].match(/[a-z]/)) {\n\t\t\t\tpattern += `[${source[i]}${source[i].toUpperCase()}]`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (flags.m) {\n\t\t\tif (source[i] === \"^\") {\n\t\t\t\tpattern += `(^|(?<=[\\r\\n]))`;\n\t\t\t\tcontinue;\n\t\t\t} else if (source[i] === \"$\") {\n\t\t\t\tpattern += `($|(?=[\\r\\n]))`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (flags.s && source[i] === \".\") {\n\t\t\tpattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n\t\t\tcontinue;\n\t\t}\n\t\tpattern += source[i];\n\t\tif (source[i] === \"\\\\\") isEscaped = true;\n\t\telse if (inCharGroup && source[i] === \"]\") inCharGroup = false;\n\t\telse if (!inCharGroup && source[i] === \"[\") inCharGroup = true;\n\t}\n\ttry {\n\t\tnew RegExp(pattern);\n\t} catch {\n\t\tconsole.warn(`Could not convert regex pattern at ${refs.currentPath.join(\"/\")} to a flag-independent form! Falling back to the flag-ignorant source`);\n\t\treturn regex.source;\n\t}\n\treturn pattern;\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/record.ts\nfunction parseRecordDef(def, refs) {\n\tconst schema = {\n\t\ttype: \"object\",\n\t\tadditionalProperties: parseDef(def.valueType._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"additionalProperties\"]\n\t\t}) ?? refs.allowedAdditionalProperties\n\t};\n\tif (def.keyType?._def.typeName === \"ZodString\" && def.keyType._def.checks?.length) {\n\t\tconst { type: _type, ...keyType } = parseStringDef(def.keyType._def, refs);\n\t\treturn {\n\t\t\t...schema,\n\t\t\tpropertyNames: keyType\n\t\t};\n\t} else if (def.keyType?._def.typeName === \"ZodEnum\") return {\n\t\t...schema,\n\t\tpropertyNames: { enum: def.keyType._def.values }\n\t};\n\telse if (def.keyType?._def.typeName === \"ZodBranded\" && def.keyType._def.type._def.typeName === \"ZodString\" && def.keyType._def.type._def.checks?.length) {\n\t\tconst { type: _type, ...keyType } = parseBrandedDef(def.keyType._def, refs);\n\t\treturn {\n\t\t\t...schema,\n\t\t\tpropertyNames: keyType\n\t\t};\n\t}\n\treturn schema;\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/map.ts\nfunction parseMapDef(def, refs) {\n\tif (refs.mapStrategy === \"record\") return parseRecordDef(def, refs);\n\treturn {\n\t\ttype: \"array\",\n\t\tmaxItems: 125,\n\t\titems: {\n\t\t\ttype: \"array\",\n\t\t\titems: [parseDef(def.keyType._def, {\n\t\t\t\t...refs,\n\t\t\t\tcurrentPath: [\n\t\t\t\t\t...refs.currentPath,\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"0\"\n\t\t\t\t]\n\t\t\t}) || parseAnyDef(), parseDef(def.valueType._def, {\n\t\t\t\t...refs,\n\t\t\t\tcurrentPath: [\n\t\t\t\t\t...refs.currentPath,\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"1\"\n\t\t\t\t]\n\t\t\t}) || parseAnyDef()],\n\t\t\tminItems: 2,\n\t\t\tmaxItems: 2\n\t\t}\n\t};\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts\nfunction parseNativeEnumDef(def) {\n\tconst object = def.values;\n\tconst actualValues = Object.keys(def.values).filter((key) => {\n\t\treturn typeof object[object[key]] !== \"number\";\n\t}).map((key) => object[key]);\n\tconst parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n\treturn {\n\t\ttype: parsedTypes.length === 1 ? parsedTypes[0] === \"string\" ? \"string\" : \"number\" : [\"string\", \"number\"],\n\t\tenum: actualValues\n\t};\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/never.ts\nfunction parseNeverDef() {\n\treturn { not: parseAnyDef() };\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/null.ts\nfunction parseNullDef() {\n\treturn { type: \"null\" };\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/union.ts\nconst primitiveMappings = {\n\tZodString: \"string\",\n\tZodNumber: \"number\",\n\tZodBigInt: \"integer\",\n\tZodBoolean: \"boolean\",\n\tZodNull: \"null\"\n};\nfunction parseUnionDef(def, refs) {\n\tconst options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n\tif (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {\n\t\tconst types = options.reduce((types, x) => {\n\t\t\tconst type = primitiveMappings[x._def.typeName];\n\t\t\treturn type && !types.includes(type) ? [...types, type] : types;\n\t\t}, []);\n\t\treturn { type: types.length > 1 ? types : types[0] };\n\t} else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n\t\tconst types = options.reduce((acc, x) => {\n\t\t\tconst type = typeof x._def.value;\n\t\t\tswitch (type) {\n\t\t\t\tcase \"string\":\n\t\t\t\tcase \"number\":\n\t\t\t\tcase \"boolean\": return [...acc, type];\n\t\t\t\tcase \"bigint\": return [...acc, \"integer\"];\n\t\t\t\tcase \"object\": if (x._def.value === null) return [...acc, \"null\"];\n\t\t\t\tdefault: return acc;\n\t\t\t}\n\t\t}, []);\n\t\tif (types.length === options.length) {\n\t\t\tconst uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n\t\t\treturn {\n\t\t\t\ttype: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n\t\t\t\tenum: options.reduce((acc, x) => {\n\t\t\t\t\treturn acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n\t\t\t\t}, [])\n\t\t\t};\n\t\t}\n\t} else if (options.every((x) => x._def.typeName === \"ZodEnum\")) return {\n\t\ttype: \"string\",\n\t\tenum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], [])\n\t};\n\treturn asAnyOf(def, refs);\n}\nconst asAnyOf = (def, refs) => {\n\tconst anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t`${i}`\n\t\t]\n\t})).filter((x) => !!x && (!refs.strictUnions || typeof x === \"object\" && Object.keys(x).length > 0));\n\treturn anyOf.length ? { anyOf } : void 0;\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts\nfunction parseNullableDef(def, refs) {\n\tif ([\n\t\t\"ZodString\",\n\t\t\"ZodNumber\",\n\t\t\"ZodBigInt\",\n\t\t\"ZodBoolean\",\n\t\t\"ZodNull\"\n\t].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) return { type: [primitiveMappings[def.innerType._def.typeName], \"null\"] };\n\tconst base = parseDef(def.innerType._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t\"0\"\n\t\t]\n\t});\n\treturn base && { anyOf: [base, { type: \"null\" }] };\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/number.ts\nfunction parseNumberDef(def) {\n\tconst res = { type: \"number\" };\n\tif (!def.checks) return res;\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"int\":\n\t\t\tres.type = \"integer\";\n\t\t\tbreak;\n\t\tcase \"min\":\n\t\t\tif (check.inclusive) res.minimum = check.value;\n\t\t\telse res.exclusiveMinimum = check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tif (check.inclusive) res.maximum = check.value;\n\t\t\telse res.exclusiveMaximum = check.value;\n\t\t\tbreak;\n\t\tcase \"multipleOf\": res.multipleOf = check.value;\n\t}\n\treturn res;\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/object.ts\nfunction parseObjectDef(def, refs) {\n\tconst result = {\n\t\ttype: \"object\",\n\t\tproperties: {}\n\t};\n\tconst required = [];\n\tconst shape = def.shape();\n\tfor (const propName in shape) {\n\t\tlet propDef = shape[propName];\n\t\tif (propDef === void 0 || propDef._def === void 0) continue;\n\t\tconst propOptional = safeIsOptional(propDef);\n\t\tconst parsedDef = parseDef(propDef._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"properties\",\n\t\t\t\tpropName\n\t\t\t],\n\t\t\tpropertyPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"properties\",\n\t\t\t\tpropName\n\t\t\t]\n\t\t});\n\t\tif (parsedDef === void 0) continue;\n\t\tresult.properties[propName] = parsedDef;\n\t\tif (!propOptional) required.push(propName);\n\t}\n\tif (required.length) result.required = required;\n\tconst additionalProperties = decideAdditionalProperties(def, refs);\n\tif (additionalProperties !== void 0) result.additionalProperties = additionalProperties;\n\treturn result;\n}\nfunction decideAdditionalProperties(def, refs) {\n\tif (def.catchall._def.typeName !== \"ZodNever\") return parseDef(def.catchall._def, {\n\t\t...refs,\n\t\tcurrentPath: [...refs.currentPath, \"additionalProperties\"]\n\t});\n\tswitch (def.unknownKeys) {\n\t\tcase \"passthrough\": return refs.allowedAdditionalProperties;\n\t\tcase \"strict\": return refs.rejectedAdditionalProperties;\n\t\tcase \"strip\": return refs.removeAdditionalStrategy === \"strict\" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;\n\t}\n}\nfunction safeIsOptional(schema) {\n\ttry {\n\t\treturn schema.isOptional();\n\t} catch {\n\t\treturn true;\n\t}\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/optional.ts\nconst parseOptionalDef = (def, refs) => {\n\tif (refs.currentPath.toString() === refs.propertyPath?.toString()) return parseDef(def.innerType._def, refs);\n\tconst innerSchema = parseDef(def.innerType._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t\"1\"\n\t\t]\n\t});\n\treturn innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts\nconst parsePipelineDef = (def, refs) => {\n\tif (refs.pipeStrategy === \"input\") return parseDef(def.in._def, refs);\n\telse if (refs.pipeStrategy === \"output\") return parseDef(def.out._def, refs);\n\tconst inputSchema = parseDef(def.in._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"0\"\n\t\t]\n\t});\n\treturn { allOf: [inputSchema, parseDef(def.out._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\tinputSchema ? \"1\" : \"0\"\n\t\t]\n\t})].filter((schema) => schema !== void 0) };\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/promise.ts\nfunction parsePromiseDef(def, refs) {\n\treturn parseDef(def.type._def, refs);\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/set.ts\nfunction parseSetDef(def, refs) {\n\tconst schema = {\n\t\ttype: \"array\",\n\t\tuniqueItems: true,\n\t\titems: parseDef(def.valueType._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"items\"]\n\t\t})\n\t};\n\tif (def.minSize) schema.minItems = def.minSize.value;\n\tif (def.maxSize) schema.maxItems = def.maxSize.value;\n\treturn schema;\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts\nfunction parseTupleDef(def, refs) {\n\tif (def.rest) return {\n\t\ttype: \"array\",\n\t\tminItems: def.items.length,\n\t\titems: def.items.map((x, i) => parseDef(x._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"items\",\n\t\t\t\t`${i}`\n\t\t\t]\n\t\t})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),\n\t\tadditionalItems: parseDef(def.rest._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"additionalItems\"]\n\t\t})\n\t};\n\telse return {\n\t\ttype: \"array\",\n\t\tminItems: def.items.length,\n\t\tmaxItems: def.items.length,\n\t\titems: def.items.map((x, i) => parseDef(x._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"items\",\n\t\t\t\t`${i}`\n\t\t\t]\n\t\t})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])\n\t};\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts\nfunction parseUndefinedDef() {\n\treturn { not: parseAnyDef() };\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts\nfunction parseUnknownDef() {\n\treturn parseAnyDef();\n}\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts\nconst parseReadonlyDef = (def, refs) => {\n\treturn parseDef(def.innerType._def, refs);\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/select-parser.ts\nconst selectParser = (def, typeName, refs) => {\n\tswitch (typeName) {\n\t\tcase \"ZodString\": return parseStringDef(def, refs);\n\t\tcase \"ZodNumber\": return parseNumberDef(def);\n\t\tcase \"ZodObject\": return parseObjectDef(def, refs);\n\t\tcase \"ZodBigInt\": return parseBigintDef(def);\n\t\tcase \"ZodBoolean\": return parseBooleanDef();\n\t\tcase \"ZodDate\": return parseDateDef(def, refs);\n\t\tcase \"ZodUndefined\": return parseUndefinedDef();\n\t\tcase \"ZodNull\": return parseNullDef();\n\t\tcase \"ZodArray\": return parseArrayDef(def, refs);\n\t\tcase \"ZodUnion\":\n\t\tcase \"ZodDiscriminatedUnion\": return parseUnionDef(def, refs);\n\t\tcase \"ZodIntersection\": return parseIntersectionDef(def, refs);\n\t\tcase \"ZodTuple\": return parseTupleDef(def, refs);\n\t\tcase \"ZodRecord\": return parseRecordDef(def, refs);\n\t\tcase \"ZodLiteral\": return parseLiteralDef(def);\n\t\tcase \"ZodEnum\": return parseEnumDef(def);\n\t\tcase \"ZodNativeEnum\": return parseNativeEnumDef(def);\n\t\tcase \"ZodNullable\": return parseNullableDef(def, refs);\n\t\tcase \"ZodOptional\": return parseOptionalDef(def, refs);\n\t\tcase \"ZodMap\": return parseMapDef(def, refs);\n\t\tcase \"ZodSet\": return parseSetDef(def, refs);\n\t\tcase \"ZodLazy\": return () => def.getter()._def;\n\t\tcase \"ZodPromise\": return parsePromiseDef(def, refs);\n\t\tcase \"ZodNaN\":\n\t\tcase \"ZodNever\": return parseNeverDef();\n\t\tcase \"ZodEffects\": return parseEffectsDef(def, refs);\n\t\tcase \"ZodAny\": return parseAnyDef();\n\t\tcase \"ZodUnknown\": return parseUnknownDef();\n\t\tcase \"ZodDefault\": return parseDefaultDef(def, refs);\n\t\tcase \"ZodBranded\": return parseBrandedDef(def, refs);\n\t\tcase \"ZodReadonly\": return parseReadonlyDef(def, refs);\n\t\tcase \"ZodCatch\": return parseCatchDef(def, refs);\n\t\tcase \"ZodPipeline\": return parsePipelineDef(def, refs);\n\t\tcase \"ZodFunction\":\n\t\tcase \"ZodVoid\":\n\t\tcase \"ZodSymbol\": return;\n\t\tdefault:\n /* c8 ignore next */\n\t\treturn ((_) => void 0)(typeName);\n\t}\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/get-relative-path.ts\nconst getRelativePath = (pathA, pathB) => {\n\tlet i = 0;\n\tfor (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;\n\treturn [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/parse-def.ts\nfunction parseDef(def, refs, forceResolution = false) {\n\tconst seenItem = refs.seen.get(def);\n\tif (refs.override) {\n\t\tconst overrideResult = refs.override?.(def, refs, seenItem, forceResolution);\n\t\tif (overrideResult !== ignoreOverride) return overrideResult;\n\t}\n\tif (seenItem && !forceResolution) {\n\t\tconst seenSchema = get$ref(seenItem, refs);\n\t\tif (seenSchema !== void 0) return seenSchema;\n\t}\n\tconst newItem = {\n\t\tdef,\n\t\tpath: refs.currentPath,\n\t\tjsonSchema: void 0\n\t};\n\trefs.seen.set(def, newItem);\n\tconst jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n\tconst jsonSchema = typeof jsonSchemaOrGetter === \"function\" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;\n\tif (jsonSchema) addMeta(def, refs, jsonSchema);\n\tif (refs.postProcess) {\n\t\tconst postProcessResult = refs.postProcess(jsonSchema, def, refs);\n\t\tnewItem.jsonSchema = jsonSchema;\n\t\treturn postProcessResult;\n\t}\n\tnewItem.jsonSchema = jsonSchema;\n\treturn jsonSchema;\n}\nconst get$ref = (item, refs) => {\n\tswitch (refs.$refStrategy) {\n\t\tcase \"root\": return { $ref: item.path.join(\"/\") };\n\t\tcase \"relative\": return { $ref: getRelativePath(refs.currentPath, item.path) };\n\t\tcase \"none\":\n\t\tcase \"seen\":\n\t\t\tif (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {\n\t\t\t\tconsole.warn(`Recursive reference detected at ${refs.currentPath.join(\"/\")}! Defaulting to any`);\n\t\t\t\treturn parseAnyDef();\n\t\t\t}\n\t\t\treturn refs.$refStrategy === \"seen\" ? parseAnyDef() : void 0;\n\t}\n};\nconst addMeta = (def, refs, jsonSchema) => {\n\tif (def.description) jsonSchema.description = def.description;\n\treturn jsonSchema;\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/refs.ts\nconst getRefs = (options) => {\n\tconst _options = getDefaultOptions(options);\n\tconst currentPath = _options.name !== void 0 ? [\n\t\t..._options.basePath,\n\t\t_options.definitionPath,\n\t\t_options.name\n\t] : _options.basePath;\n\treturn {\n\t\t..._options,\n\t\tcurrentPath,\n\t\tpropertyPath: void 0,\n\t\tseen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, {\n\t\t\tdef: def._def,\n\t\t\tpath: [\n\t\t\t\t..._options.basePath,\n\t\t\t\t_options.definitionPath,\n\t\t\t\tname\n\t\t\t],\n\t\t\tjsonSchema: void 0\n\t\t}]))\n\t};\n};\n//#endregion\n//#region src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts\nconst zod3ToJsonSchema = (schema, options) => {\n\tconst refs = getRefs(options);\n\tlet definitions = typeof options === \"object\" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({\n\t\t...acc,\n\t\t[name]: parseDef(schema._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.basePath,\n\t\t\t\trefs.definitionPath,\n\t\t\t\tname\n\t\t\t]\n\t\t}, true) ?? parseAnyDef()\n\t}), {}) : void 0;\n\tconst name = typeof options === \"string\" ? options : options?.nameStrategy === \"title\" ? void 0 : options?.name;\n\tconst main = parseDef(schema._def, name === void 0 ? refs : {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.basePath,\n\t\t\trefs.definitionPath,\n\t\t\tname\n\t\t]\n\t}, false) ?? parseAnyDef();\n\tconst title = typeof options === \"object\" && options.name !== void 0 && options.nameStrategy === \"title\" ? options.name : void 0;\n\tif (title !== void 0) main.title = title;\n\tconst combined = name === void 0 ? definitions ? {\n\t\t...main,\n\t\t[refs.definitionPath]: definitions\n\t} : main : {\n\t\t$ref: [\n\t\t\t...refs.$refStrategy === \"relative\" ? [] : refs.basePath,\n\t\t\trefs.definitionPath,\n\t\t\tname\n\t\t].join(\"/\"),\n\t\t[refs.definitionPath]: {\n\t\t\t...definitions,\n\t\t\t[name]: main\n\t\t}\n\t};\n\tcombined.$schema = \"http://json-schema.org/draft-07/schema#\";\n\treturn combined;\n};\n//#endregion\n//#region src/schema.ts\n/**\n* Used to mark schemas so we can support both Zod and custom schemas.\n*/\nconst schemaSymbol = Symbol.for(\"vercel.ai.schema\");\n/**\n* Creates a schema with deferred creation.\n* This is important to reduce the startup time of the library\n* and to avoid initializing unused validators.\n*\n* @param createValidator A function that creates a schema.\n* @returns A function that returns a schema.\n*/\nfunction lazySchema(createSchema) {\n\tlet schema;\n\treturn () => {\n\t\tif (schema == null) schema = createSchema();\n\t\treturn schema;\n\t};\n}\n/**\n* Create a schema using a JSON Schema.\n*\n* @param jsonSchema The JSON Schema for the schema.\n* @param options.validate Optional. A validation function for the schema.\n*/\nfunction jsonSchema(jsonSchema, { validate } = {}) {\n\treturn {\n\t\t[schemaSymbol]: true,\n\t\t_type: void 0,\n\t\tget jsonSchema() {\n\t\t\tif (typeof jsonSchema === \"function\") jsonSchema = jsonSchema();\n\t\t\treturn jsonSchema;\n\t\t},\n\t\tvalidate\n\t};\n}\nfunction isSchema(value) {\n\treturn typeof value === \"object\" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && \"jsonSchema\" in value && \"validate\" in value;\n}\nfunction asSchema(schema) {\n\treturn schema == null ? jsonSchema({\n\t\ttype: \"object\",\n\t\tproperties: {},\n\t\tadditionalProperties: false\n\t}) : isSchema(schema) ? schema : \"~standard\" in schema ? schema[\"~standard\"].vendor === \"zod\" ? zodSchema(schema) : standardSchema(schema) : schema();\n}\nfunction standardSchema(standardSchema) {\n\treturn jsonSchema(() => {\n\t\tif (!hasStandardJsonSchema(standardSchema)) throw new Error(`Standard schema vendor '${standardSchema[\"~standard\"].vendor}' does not support JSON Schema conversion.`);\n\t\treturn addAdditionalPropertiesToJsonSchema(standardSchema[\"~standard\"].jsonSchema.input({ target: \"draft-07\" }));\n\t}, { validate: async (value) => {\n\t\tconst result = await standardSchema[\"~standard\"].validate(value);\n\t\treturn \"value\" in result ? {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.value\n\t\t} : {\n\t\t\tsuccess: false,\n\t\t\terror: new TypeValidationError({\n\t\t\t\tvalue,\n\t\t\t\tcause: result.issues\n\t\t\t})\n\t\t};\n\t} });\n}\nfunction hasStandardJsonSchema(schema) {\n\treturn schema[\"~standard\"].jsonSchema != null;\n}\nfunction zod3Schema(zodSchema, options) {\n\tconst useReferences = options?.useReferences ?? false;\n\treturn jsonSchema(() => zod3ToJsonSchema(zodSchema, { $refStrategy: useReferences ? \"root\" : \"none\" }), { validate: async (value) => {\n\t\tconst result = await zodSchema.safeParseAsync(value);\n\t\treturn result.success ? {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.data\n\t\t} : {\n\t\t\tsuccess: false,\n\t\t\terror: result.error\n\t\t};\n\t} });\n}\nfunction zod4Schema(zodSchema, options) {\n\tconst useReferences = options?.useReferences ?? false;\n\treturn jsonSchema(() => addAdditionalPropertiesToJsonSchema(toJSONSchema(zodSchema, {\n\t\ttarget: \"draft-7\",\n\t\tio: \"input\",\n\t\treused: useReferences ? \"ref\" : \"inline\"\n\t})), { validate: async (value) => {\n\t\tconst result = await safeParseAsync(zodSchema, value);\n\t\treturn result.success ? {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.data\n\t\t} : {\n\t\t\tsuccess: false,\n\t\t\terror: result.error\n\t\t};\n\t} });\n}\nfunction isZod4Schema(zodSchema) {\n\treturn \"_zod\" in zodSchema;\n}\nfunction zodSchema(zodSchema, options) {\n\tif (isZod4Schema(zodSchema)) return zod4Schema(zodSchema, options);\n\telse return zod3Schema(zodSchema, options);\n}\n//#endregion\n//#region src/validate-types.ts\n/**\n* Validates the types of an unknown object using a schema and\n* return a strongly-typed object.\n*\n* @template T - The type of the object to validate.\n* @param {string} options.value - The object to validate.\n* @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n* @param {TypeValidationContext} options.context - Optional context about what is being validated.\n* @returns {Promise<T>} - The typed object.\n*/\nasync function validateTypes({ value, schema, context }) {\n\tconst result = await safeValidateTypes({\n\t\tvalue,\n\t\tschema,\n\t\tcontext\n\t});\n\tif (!result.success) throw TypeValidationError.wrap({\n\t\tvalue,\n\t\tcause: result.error,\n\t\tcontext\n\t});\n\treturn result.value;\n}\n/**\n* Safely validates the types of an unknown object using a schema and\n* return a strongly-typed object.\n*\n* @template T - The type of the object to validate.\n* @param {string} options.value - The JSON object to validate.\n* @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n* @param {TypeValidationContext} options.context - Optional context about what is being validated.\n* @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n*/\nasync function safeValidateTypes({ value, schema, context }) {\n\tconst actualSchema = asSchema(schema);\n\ttry {\n\t\tif (actualSchema.validate == null) return {\n\t\t\tsuccess: true,\n\t\t\tvalue,\n\t\t\trawValue: value\n\t\t};\n\t\tconst result = await actualSchema.validate(value);\n\t\tif (result.success) return {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.value,\n\t\t\trawValue: value\n\t\t};\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: TypeValidationError.wrap({\n\t\t\t\tvalue,\n\t\t\t\tcause: result.error,\n\t\t\t\tcontext\n\t\t\t}),\n\t\t\trawValue: value\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: TypeValidationError.wrap({\n\t\t\t\tvalue,\n\t\t\t\tcause: error,\n\t\t\t\tcontext\n\t\t\t}),\n\t\t\trawValue: value\n\t\t};\n\t}\n}\n//#endregion\n//#region src/parse-json.ts\nasync function parseJSON({ text, schema }) {\n\ttry {\n\t\tconst value = secureJsonParse(text);\n\t\tif (schema == null) return value;\n\t\treturn await validateTypes({\n\t\t\tvalue,\n\t\t\tschema\n\t\t});\n\t} catch (error) {\n\t\tif (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) throw error;\n\t\tthrow new JSONParseError({\n\t\t\ttext,\n\t\t\tcause: error\n\t\t});\n\t}\n}\nasync function safeParseJSON({ text, schema }) {\n\ttry {\n\t\tconst value = secureJsonParse(text);\n\t\tif (schema == null) return {\n\t\t\tsuccess: true,\n\t\t\tvalue,\n\t\t\trawValue: value\n\t\t};\n\t\treturn await safeValidateTypes({\n\t\t\tvalue,\n\t\t\tschema\n\t\t});\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: JSONParseError.isInstance(error) ? error : new JSONParseError({\n\t\t\t\ttext,\n\t\t\t\tcause: error\n\t\t\t}),\n\t\t\trawValue: void 0\n\t\t};\n\t}\n}\nfunction isParsableJson(input) {\n\ttry {\n\t\tsecureJsonParse(input);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\n//#region src/parse-json-event-stream.ts\n/**\n* Parses a JSON event stream into a stream of parsed JSON objects.\n*/\nfunction parseJsonEventStream({ stream, schema }) {\n\treturn stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream$1()).pipeThrough(new TransformStream({ async transform({ data }, controller) {\n\t\tif (data === \"[DONE]\") return;\n\t\tcontroller.enqueue(await safeParseJSON({\n\t\t\ttext: data,\n\t\t\tschema\n\t\t}));\n\t} }));\n}\n//#endregion\n//#region src/parse-provider-options.ts\nasync function parseProviderOptions({ provider, providerOptions, schema }) {\n\tif (providerOptions?.[provider] == null) return;\n\tconst parsedProviderOptions = await safeValidateTypes({\n\t\tvalue: providerOptions[provider],\n\t\tschema\n\t});\n\tif (!parsedProviderOptions.success) throw new InvalidArgumentError({\n\t\targument: \"providerOptions\",\n\t\tmessage: `invalid ${provider} provider options`,\n\t\tcause: parsedProviderOptions.error\n\t});\n\treturn parsedProviderOptions.value;\n}\n//#endregion\n//#region src/post-multipart-stream-to-api.ts\nconst getOriginalFetch$1 = () => globalThis.fetch;\nfunction escapeMultipartHeaderValue(value) {\n\treturn value.replace(/[\\r\\n]/g, \"\").replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, \"\\\\\\\"\");\n}\nfunction createMultipartBody(parts, boundary) {\n\tconst encoder = new TextEncoder();\n\tlet disposed = false;\n\tlet activeReader;\n\tconst enteredStreams = /* @__PURE__ */ new Set();\n\tasync function* emitParts() {\n\t\tfor (const part of parts) {\n\t\t\tif (disposed) return;\n\t\t\tconst disposition = `--${boundary}\\r\\nContent-Disposition: form-data; name=\"${escapeMultipartHeaderValue(part.name)}\"`;\n\t\t\tif (part.type === \"field\") {\n\t\t\t\tyield encoder.encode(`${disposition}\\r\\n\\r\\n${part.value}\\r\\n`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst filenameParameter = `; filename=\"${escapeMultipartHeaderValue(part.filename ?? \"blob\")}\"`;\n\t\t\tconst mediaType = (part.mediaType ?? \"application/octet-stream\").replace(/[\\r\\n]/g, \"\");\n\t\t\tyield encoder.encode(`${disposition}${filenameParameter}\\r\\nContent-Type: ${mediaType}\\r\\n\\r\\n`);\n\t\t\tif (part.content instanceof Uint8Array) yield part.content;\n\t\t\telse {\n\t\t\t\tconst reader = part.content.getReader();\n\t\t\t\tactiveReader = reader;\n\t\t\t\tenteredStreams.add(part.content);\n\t\t\t\tlet finished = false;\n\t\t\t\ttry {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\t\tif (done || disposed) {\n\t\t\t\t\t\t\tfinished = done;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield value;\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tactiveReader = void 0;\n\t\t\t\t\tif (!finished) await reader.cancel().catch(() => {});\n\t\t\t\t\treader.releaseLock();\n\t\t\t\t}\n\t\t\t\tif (disposed) return;\n\t\t\t}\n\t\t\tyield encoder.encode(\"\\r\\n\");\n\t\t}\n\t\tyield encoder.encode(`--${boundary}--\\r\\n`);\n\t}\n\treturn {\n\t\tstream: convertAsyncIteratorToReadableStream(emitParts()),\n\t\tasync dispose(reason) {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tconst reader = activeReader;\n\t\t\tif (reader != null) await reader.cancel(reason).catch(() => {});\n\t\t\tfor (const part of parts) if (part.type === \"file\" && !(part.content instanceof Uint8Array) && !enteredStreams.has(part.content)) await part.content.cancel(reason).catch(() => {});\n\t\t}\n\t};\n}\n/**\n* POSTs a multipart/form-data body as a request stream, so file parts backed\n* by a `ReadableStream` are sent without buffering the full file in memory.\n*\n* Requires a fetch implementation that supports streaming request bodies\n* (`duplex: 'half'`). Callers with fully buffered payloads can keep using\n* `postFormDataToApi`.\n*/\nconst postMultipartStreamToApi = async ({ url, headers = {}, parts, failedResponseHandler, successfulResponseHandler, abortSignal, fetch = getOriginalFetch$1() }) => {\n\tconst boundary = `ai-sdk-multipart-${generateId()}`;\n\tconst requestBodyValues = Object.fromEntries(parts.map((part) => [part.name, part.type === \"field\" ? part.value : `<file:${part.filename ?? part.name}>`]));\n\tconst body = createMultipartBody(parts, boundary);\n\ttry {\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: withUserAgentSuffix({\n\t\t\t\t...headers,\n\t\t\t\t\"Content-Type\": `multipart/form-data; boundary=${boundary}`\n\t\t\t}, `ai-sdk-provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tbody: body.stream,\n\t\t\tduplex: \"half\",\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tconst responseHeaders = extractResponseHeaders(response);\n\t\tif (!response.ok) {\n\t\t\tlet errorInformation;\n\t\t\ttry {\n\t\t\t\terrorInformation = await failedResponseHandler({\n\t\t\t\t\tresponse,\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t\tthrow new APICallError({\n\t\t\t\t\tmessage: \"Failed to process error response\",\n\t\t\t\t\tcause: error,\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\turl,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t\trequestBodyValues\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow errorInformation.value;\n\t\t}\n\t\ttry {\n\t\t\treturn await successfulResponseHandler({\n\t\t\t\tresponse,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t}\n\t\t\tthrow new APICallError({\n\t\t\t\tmessage: \"Failed to process successful response\",\n\t\t\t\tcause: error,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\turl,\n\t\t\t\tresponseHeaders,\n\t\t\t\trequestBodyValues\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tawait body.dispose(error);\n\t\tthrow handleFetchError({\n\t\t\terror,\n\t\t\turl,\n\t\t\trequestBodyValues\n\t\t});\n\t}\n};\n//#endregion\n//#region src/post-to-api.ts\nconst getOriginalFetch = () => globalThis.fetch;\nconst postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => await postToApi({\n\turl,\n\theaders: {\n\t\t\"Content-Type\": \"application/json\",\n\t\t...headers\n\t},\n\tbody: {\n\t\tcontent: JSON.stringify(body),\n\t\tvalues: body\n\t},\n\tfailedResponseHandler,\n\tsuccessfulResponseHandler,\n\tabortSignal,\n\tfetch\n});\nconst postFormDataToApi = async ({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => await postToApi({\n\turl,\n\theaders,\n\tbody: {\n\t\tcontent: formData,\n\t\tvalues: Object.fromEntries(formData.entries())\n\t},\n\tfailedResponseHandler,\n\tsuccessfulResponseHandler,\n\tabortSignal,\n\tfetch\n});\nconst postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch() }) => {\n\ttry {\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: withUserAgentSuffix(headers, `ai-sdk-provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tbody: body.content,\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tconst responseHeaders = extractResponseHeaders(response);\n\t\tif (!response.ok) {\n\t\t\tlet errorInformation;\n\t\t\ttry {\n\t\t\t\terrorInformation = await failedResponseHandler({\n\t\t\t\t\tresponse,\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues: body.values\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t\tthrow new APICallError({\n\t\t\t\t\tmessage: \"Failed to process error response\",\n\t\t\t\t\tcause: error,\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\turl,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t\trequestBodyValues: body.values\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow errorInformation.value;\n\t\t}\n\t\ttry {\n\t\t\treturn await successfulResponseHandler({\n\t\t\t\tresponse,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues: body.values\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t}\n\t\t\tthrow new APICallError({\n\t\t\t\tmessage: \"Failed to process successful response\",\n\t\t\t\tcause: error,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\turl,\n\t\t\t\tresponseHeaders,\n\t\t\t\trequestBodyValues: body.values\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tthrow handleFetchError({\n\t\t\terror,\n\t\t\turl,\n\t\t\trequestBodyValues: body.values\n\t\t});\n\t}\n};\n//#endregion\n//#region src/types/tool.ts\nfunction tool(tool) {\n\treturn tool;\n}\n/**\n* Define a dynamic tool.\n*/\nfunction dynamicTool(tool) {\n\treturn {\n\t\t...tool,\n\t\ttype: \"dynamic\"\n\t};\n}\n//#endregion\n//#region src/provider-defined-tool-factory.ts\nfunction createProviderDefinedToolFactory({ id, inputSchema }) {\n\treturn ({ execute, outputSchema, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({\n\t\ttype: \"provider\",\n\t\tisProviderExecuted: false,\n\t\tid,\n\t\targs,\n\t\tinputSchema,\n\t\toutputSchema,\n\t\texecute,\n\t\tneedsApproval,\n\t\ttoModelOutput,\n\t\tonInputStart,\n\t\tonInputDelta,\n\t\tonInputAvailable\n\t});\n}\nfunction createProviderDefinedToolFactoryWithOutputSchema({ id, inputSchema, outputSchema }) {\n\treturn ({ execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({\n\t\ttype: \"provider\",\n\t\tisProviderExecuted: false,\n\t\tid,\n\t\targs,\n\t\tinputSchema,\n\t\toutputSchema,\n\t\texecute,\n\t\tneedsApproval,\n\t\ttoModelOutput,\n\t\tonInputStart,\n\t\tonInputDelta,\n\t\tonInputAvailable\n\t});\n}\n//#endregion\n//#region src/provider-executed-tool-factory.ts\nfunction createProviderExecutedToolFactory({ id, inputSchema, outputSchema, supportsDeferredResults }) {\n\treturn ({ onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({\n\t\ttype: \"provider\",\n\t\tisProviderExecuted: true,\n\t\tid,\n\t\targs,\n\t\tinputSchema,\n\t\toutputSchema,\n\t\tonInputStart,\n\t\tonInputDelta,\n\t\tonInputAvailable,\n\t\tsupportsDeferredResults\n\t});\n}\n//#endregion\n//#region src/resolve.ts\n/**\n* Resolves a value that could be a raw value, a Promise, a function returning a value,\n* or a function returning a Promise.\n*/\nasync function resolve(value) {\n\tif (typeof value === \"function\") value = value();\n\treturn value;\n}\n//#endregion\n//#region src/resolve-full-media-type.ts\n/**\n* Resolves a file part's media type to a full `type/subtype` form required by\n* providers whose API demands the full IANA media type.\n*\n* - If `part.mediaType` is already a full media type (e.g. `image/png`), it is\n* returned as-is.\n* - Otherwise, when inline bytes are available (`part.data.type === 'data'`),\n* the subtype is sniffed from the bytes using the signature table that\n* corresponds to the top-level segment.\n* - When neither applies (e.g. top-level-only with a URL source, or bytes that\n* cannot be detected), an `UnsupportedFunctionalityError` is thrown.\n*/\nfunction resolveFullMediaType({ part }) {\n\tif (isFullMediaType(part.mediaType)) return part.mediaType;\n\tif (part.data.type === \"data\") {\n\t\tconst detected = detectMediaType({\n\t\t\tdata: part.data.data,\n\t\t\ttopLevelType: getTopLevelMediaType(part.mediaType)\n\t\t});\n\t\tif (detected) return detected;\n\t\tthrow new UnsupportedFunctionalityError({ functionality: `file of media type \"${part.mediaType}\" must specify subtype since it could not be auto-detected` });\n\t}\n\tthrow new UnsupportedFunctionalityError({ functionality: `file of media type \"${part.mediaType}\" must specify subtype since it is not passed as inline bytes` });\n}\n//#endregion\n//#region src/resolve-provider-reference.ts\n/**\n* Resolves a provider reference to the provider-specific identifier for the\n* given provider. Throws `NoSuchProviderReferenceError` if the provider is not\n* found in the reference mapping.\n*/\nfunction resolveProviderReference({ reference, provider }) {\n\tconst id = reference[provider];\n\tif (id != null) return id;\n\tthrow new NoSuchProviderReferenceError({\n\t\tprovider,\n\t\treference\n\t});\n}\n//#endregion\n//#region src/retry-with-exponential-backoff.ts\n/**\n* Retries a failed operation with exponential backoff.\n*/\nconst retryWithExponentialBackoff = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal, shouldRetry, getDelayInMs = ({ exponentialBackoffDelay }) => exponentialBackoffDelay, createRetryError = ({ message }) => new Error(message) }) => async (f) => retryWithExponentialBackoffInternal(f, {\n\tmaxRetries,\n\tdelayInMs: initialDelayInMs,\n\tbackoffFactor,\n\tabortSignal,\n\tshouldRetry,\n\tgetDelayInMs,\n\tcreateRetryError\n});\nasync function retryWithExponentialBackoffInternal(f, { maxRetries, delayInMs, backoffFactor, abortSignal, shouldRetry, getDelayInMs, createRetryError }, errors = []) {\n\ttry {\n\t\treturn await f();\n\t} catch (error) {\n\t\tif (isAbortError(error)) throw error;\n\t\tif (maxRetries === 0) throw error;\n\t\tconst errorMessage = getErrorMessage(error);\n\t\tconst newErrors = [...errors, error];\n\t\tconst tryNumber = newErrors.length;\n\t\tif (tryNumber > maxRetries) throw createRetryError({\n\t\t\tmessage: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,\n\t\t\treason: \"maxRetriesExceeded\",\n\t\t\terrors: newErrors\n\t\t});\n\t\tif (await shouldRetry(error) && tryNumber <= maxRetries) {\n\t\t\tawait delay(getDelayInMs({\n\t\t\t\terror,\n\t\t\t\texponentialBackoffDelay: delayInMs\n\t\t\t}), { abortSignal });\n\t\t\treturn retryWithExponentialBackoffInternal(f, {\n\t\t\t\tmaxRetries,\n\t\t\t\tdelayInMs: backoffFactor * delayInMs,\n\t\t\t\tbackoffFactor,\n\t\t\t\tabortSignal,\n\t\t\t\tshouldRetry,\n\t\t\t\tgetDelayInMs,\n\t\t\t\tcreateRetryError\n\t\t\t}, newErrors);\n\t\t}\n\t\tif (tryNumber === 1) throw error;\n\t\tthrow createRetryError({\n\t\t\tmessage: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,\n\t\t\treason: \"errorNotRetryable\",\n\t\t\terrors: newErrors\n\t\t});\n\t}\n}\n//#endregion\n//#region src/response-handler.ts\nconst textDecoder = new TextDecoder();\nconst DEFAULT_MAX_JSON_LINE_BYTES = 67108864;\nfunction wrapResponseBodyStream({ stream, url, requestBodyValues, statusCode, responseHeaders }) {\n\tconst reader = stream.getReader();\n\tlet readerReleased = false;\n\tconst releaseReader = () => {\n\t\tif (!readerReleased) {\n\t\t\treader.releaseLock();\n\t\t\treaderReleased = true;\n\t\t}\n\t};\n\treturn new ReadableStream({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) {\n\t\t\t\t\treleaseReader();\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} else controller.enqueue(value);\n\t\t\t} catch (error) {\n\t\t\t\treleaseReader();\n\t\t\t\tif (isAbortError(error)) {\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcontroller.error(handleFetchError({\n\t\t\t\t\terror: new APICallError({\n\t\t\t\t\t\tmessage: \"Failed to process successful response\",\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\tstatusCode,\n\t\t\t\t\t\turl,\n\t\t\t\t\t\tresponseHeaders,\n\t\t\t\t\t\trequestBodyValues\n\t\t\t\t\t}),\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues\n\t\t\t\t}));\n\t\t\t}\n\t\t},\n\t\tasync cancel(reason) {\n\t\t\ttry {\n\t\t\t\tawait reader.cancel(reason);\n\t\t\t} finally {\n\t\t\t\treleaseReader();\n\t\t\t}\n\t\t}\n\t});\n}\nasync function readResponseBodyAsText({ response, url }) {\n\treturn textDecoder.decode(await readResponseWithSizeLimit({\n\t\tresponse,\n\t\turl\n\t}));\n}\nconst createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {\n\tconst responseBody = await readResponseBodyAsText({\n\t\tresponse,\n\t\turl\n\t});\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (responseBody.trim() === \"\") return {\n\t\tresponseHeaders,\n\t\tvalue: new APICallError({\n\t\t\tmessage: response.statusText,\n\t\t\turl,\n\t\t\trequestBodyValues,\n\t\t\tstatusCode: response.status,\n\t\t\tresponseHeaders,\n\t\t\tresponseBody,\n\t\t\tisRetryable: isRetryable?.(response)\n\t\t})\n\t};\n\ttry {\n\t\tconst parsedError = await parseJSON({\n\t\t\ttext: responseBody,\n\t\t\tschema: errorSchema\n\t\t});\n\t\treturn {\n\t\t\tresponseHeaders,\n\t\t\tvalue: new APICallError({\n\t\t\t\tmessage: errorToMessage(parsedError),\n\t\t\t\turl,\n\t\t\t\trequestBodyValues,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tresponseHeaders,\n\t\t\t\tresponseBody,\n\t\t\t\tdata: parsedError,\n\t\t\t\tisRetryable: isRetryable?.(response, parsedError)\n\t\t\t})\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tresponseHeaders,\n\t\t\tvalue: new APICallError({\n\t\t\t\tmessage: response.statusText,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tresponseHeaders,\n\t\t\t\tresponseBody,\n\t\t\t\tisRetryable: isRetryable?.(response)\n\t\t\t})\n\t\t};\n\t}\n};\nconst createEventSourceResponseHandler = (chunkSchema) => async ({ response, url, requestBodyValues }) => {\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (response.body == null) throw new EmptyResponseBodyError({});\n\treturn {\n\t\tresponseHeaders,\n\t\tvalue: parseJsonEventStream({\n\t\t\tstream: wrapResponseBodyStream({\n\t\t\t\tstream: response.body,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tresponseHeaders\n\t\t\t}),\n\t\t\tschema: chunkSchema\n\t\t})\n\t};\n};\nconst createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {\n\tconst responseBody = await readResponseBodyAsText({\n\t\tresponse,\n\t\turl\n\t});\n\tconst parsedResult = await safeParseJSON({\n\t\ttext: responseBody,\n\t\tschema: responseSchema\n\t});\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (!parsedResult.success) throw new APICallError({\n\t\tmessage: \"Invalid JSON response\",\n\t\tcause: parsedResult.error,\n\t\tstatusCode: response.status,\n\t\tresponseHeaders,\n\t\tresponseBody,\n\t\turl,\n\t\trequestBodyValues\n\t});\n\treturn {\n\t\tresponseHeaders,\n\t\tvalue: parsedResult.value,\n\t\trawValue: parsedResult.rawValue\n\t};\n};\nconst createJsonLinesResponseHandler = (responseSchema, { maxLineBytes = DEFAULT_MAX_JSON_LINE_BYTES } = {}) => {\n\tif (!Number.isSafeInteger(maxLineBytes) || maxLineBytes <= 0) throw new InvalidArgumentError({\n\t\targument: \"maxLineBytes\",\n\t\tmessage: \"maxLineBytes must be a positive safe integer.\"\n\t});\n\treturn async ({ response, url }) => {\n\t\tconst responseHeaders = extractResponseHeaders(response);\n\t\tif (response.body == null) throw new EmptyResponseBodyError({});\n\t\treturn {\n\t\t\tresponseHeaders,\n\t\t\tvalue: parseJsonLines({\n\t\t\t\tstream: response.body,\n\t\t\t\tschema: responseSchema,\n\t\t\t\turl,\n\t\t\t\tmaxLineBytes\n\t\t\t})\n\t\t};\n\t};\n};\nasync function* parseJsonLines({ stream, schema, url, maxLineBytes }) {\n\tconst reader = stream.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tlet lineBytes = 0;\n\tlet finished = false;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tfinished = true;\n\t\t\t\tbuffer += decoder.decode();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlet offset = 0;\n\t\t\twhile (offset < value.length) {\n\t\t\t\tconst lineEnd = value.indexOf(10, offset);\n\t\t\t\tconst segmentEnd = lineEnd === -1 ? value.length : lineEnd;\n\t\t\t\tlineBytes += segmentEnd - offset;\n\t\t\t\tif (lineBytes > maxLineBytes) throw new DownloadError({\n\t\t\t\t\tmessage: `JSON Lines response exceeded maximum line size of ${maxLineBytes} bytes.`,\n\t\t\t\t\turl\n\t\t\t\t});\n\t\t\t\tconst decodeEnd = lineEnd === -1 ? segmentEnd : lineEnd + 1;\n\t\t\t\tbuffer += decoder.decode(value.subarray(offset, decodeEnd), { stream: true });\n\t\t\t\tif (lineEnd === -1) break;\n\t\t\t\tconst line = buffer.slice(0, -1).replace(/\\r$/, \"\");\n\t\t\t\tbuffer = \"\";\n\t\t\t\tlineBytes = 0;\n\t\t\t\toffset = decodeEnd;\n\t\t\t\tif (line.trim().length > 0) yield await parseJSON({\n\t\t\t\t\ttext: line,\n\t\t\t\t\tschema\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst finalLine = buffer.replace(/\\r$/, \"\");\n\t\tif (finalLine.trim().length > 0) yield await parseJSON({\n\t\t\ttext: finalLine,\n\t\t\tschema\n\t\t});\n\t} finally {\n\t\tif (!finished) await reader.cancel().catch(() => {});\n\t\treader.releaseLock();\n\t}\n}\nconst createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (!response.body) throw new APICallError({\n\t\tmessage: \"Response body is empty\",\n\t\turl,\n\t\trequestBodyValues,\n\t\tstatusCode: response.status,\n\t\tresponseHeaders,\n\t\tresponseBody: void 0\n\t});\n\ttry {\n\t\tconst buffer = await response.arrayBuffer();\n\t\treturn {\n\t\t\tresponseHeaders,\n\t\t\tvalue: new Uint8Array(buffer)\n\t\t};\n\t} catch (error) {\n\t\tthrow new APICallError({\n\t\t\tmessage: \"Failed to read response as array buffer\",\n\t\t\turl,\n\t\t\trequestBodyValues,\n\t\t\tstatusCode: response.status,\n\t\t\tresponseHeaders,\n\t\t\tresponseBody: void 0,\n\t\t\tcause: error\n\t\t});\n\t}\n};\n/**\n* Passes the response body through as a `ReadableStream<Uint8Array>` without\n* buffering it (unlike `createBinaryResponseHandler`). The consumer is\n* responsible for draining or cancelling the stream.\n*/\nconst createBinaryStreamResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (response.body == null) throw new EmptyResponseBodyError({});\n\treturn {\n\t\tresponseHeaders,\n\t\tvalue: wrapResponseBodyStream({\n\t\t\tstream: response.body,\n\t\t\turl,\n\t\t\trequestBodyValues,\n\t\t\tstatusCode: response.status,\n\t\t\tresponseHeaders\n\t\t})\n\t};\n};\nconst createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n\tconst responseHeaders = extractResponseHeaders(response);\n\tconst responseBody = await readResponseBodyAsText({\n\t\tresponse,\n\t\turl\n\t});\n\treturn {\n\t\tresponseHeaders,\n\t\tvalue: new APICallError({\n\t\t\tmessage: response.statusText,\n\t\t\turl,\n\t\t\trequestBodyValues,\n\t\t\tstatusCode: response.status,\n\t\t\tresponseHeaders,\n\t\t\tresponseBody\n\t\t})\n\t};\n};\n//#endregion\n//#region src/is-json-serializable.ts\n/**\n* Checks whether a value can cross a workflow serialization boundary.\n*\n* The check accepts JSON-like primitives, arrays, and plain objects whose\n* nested values are also serializable. It rejects functions, symbols,\n* bigints, and non-plain objects such as class instances, dates, and regexes.\n*/\nfunction isJSONSerializable(value) {\n\tif (value === null || value === void 0) return true;\n\tconst type = typeof value;\n\tif (type === \"string\" || type === \"number\" || type === \"boolean\") return true;\n\tif (type === \"function\" || type === \"symbol\" || type === \"bigint\") return false;\n\tif (Array.isArray(value)) return value.every(isJSONSerializable);\n\tif (Object.getPrototypeOf(value) === Object.prototype) return Object.values(value).every(isJSONSerializable);\n\treturn false;\n}\n//#endregion\n//#region src/serialization-error.ts\nconst name = \"AI_SerializationError\";\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\nvar SerializationError = class extends AISDKError {\n\tconstructor({ message = \"Failed to serialize value.\", cause } = {}) {\n\t\tsuper({\n\t\t\tname,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker);\n\t}\n};\n//#endregion\n//#region src/serialize-model-options.ts\n/**\n* Serializes a model instance for workflow step boundaries.\n* Returns the `modelId` plus the JSON-serializable config properties.\n*\n* Non-serializable values are omitted. As a special case, a\n* function-valued `headers` property is resolved during serialization\n* and included if the returned value is JSON-serializable.\n*\n* Used as the body of `static [WORKFLOW_SERIALIZE]` in provider models.\n*\n* @example\n* ```ts\n* static [WORKFLOW_SERIALIZE](model: MyLanguageModel) {\n* return serializeModelOptions({\n* modelId: model.modelId,\n* config: model.config,\n* });\n* }\n* ```\n*/\nfunction serializeModelOptions(options) {\n\tconst serializableConfig = {};\n\tfor (const [key, value] of Object.entries(options.config)) if (key === \"headers\") {\n\t\tconst resolvedHeaders = resolveSync(value);\n\t\tif (isJSONSerializable(resolvedHeaders)) serializableConfig[key] = resolvedHeaders;\n\t} else if (isJSONSerializable(value)) serializableConfig[key] = value;\n\treturn {\n\t\tmodelId: options.modelId,\n\t\tconfig: serializableConfig\n\t};\n}\nfunction resolveSync(value) {\n\tlet next = value;\n\tif (typeof value === \"function\") next = value();\n\tif (next instanceof Promise) throw new SerializationError({ message: \"Cannot serialize asynchronous model options.\" });\n\treturn next;\n}\n//#endregion\n//#region src/streaming-tool-call-argument-state.ts\nfunction startsWithStructuredValue(value) {\n\tif (typeof value !== \"string\") return false;\n\tconst firstCharacter = value.trimStart()[0];\n\treturn firstCharacter === \"{\" || firstCharacter === \"[\";\n}\n/**\n* Incrementally tracks whether streamed tool-call arguments contain a complete\n* structured JSON value. This is intentionally structural rather than a JSON\n* parse: a currently parsable scalar can still be the prefix of a later value.\n*/\nvar StreamingToolCallArgumentState = class {\n\tconstructor(initialValue = \"\") {\n\t\tthis.structure = { kind: \"undetermined\" };\n\t\tthis.append(initialValue);\n\t}\n\tget hasCompleteStructuredValue() {\n\t\treturn this.structure.kind === \"structured\" && this.structure.complete === true;\n\t}\n\tappend(delta) {\n\t\tlet nextStructure = this.structure;\n\t\tfor (const character of delta) {\n\t\t\tif (nextStructure.kind === \"undetermined\") {\n\t\t\t\tif (/\\s/.test(character)) continue;\n\t\t\t\tif (character !== \"{\" && character !== \"[\") {\n\t\t\t\t\tnextStructure = { kind: \"other\" };\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tnextStructure = {\n\t\t\t\t\tkind: \"structured\",\n\t\t\t\t\tstack: [character],\n\t\t\t\t\tinString: false,\n\t\t\t\t\tescaped: false,\n\t\t\t\t\tcomplete: false\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (nextStructure.kind !== \"structured\" || nextStructure.complete) continue;\n\t\t\tif (nextStructure.inString) {\n\t\t\t\tif (nextStructure.escaped) nextStructure.escaped = false;\n\t\t\t\telse if (character === \"\\\\\") nextStructure.escaped = true;\n\t\t\t\telse if (character === \"\\\"\") nextStructure.inString = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"\\\"\") nextStructure.inString = true;\n\t\t\telse if (character === \"{\" || character === \"[\") nextStructure.stack.push(character);\n\t\t\telse if (character === \"}\" || character === \"]\") {\n\t\t\t\tconst expectedOpening = character === \"}\" ? \"{\" : \"[\";\n\t\t\t\tif (nextStructure.stack.at(-1) !== expectedOpening) {\n\t\t\t\t\tnextStructure = { kind: \"other\" };\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tnextStructure.stack.pop();\n\t\t\t\tif (nextStructure.stack.length === 0) nextStructure.complete = true;\n\t\t\t}\n\t\t}\n\t\tthis.structure = nextStructure;\n\t}\n};\n//#endregion\n//#region src/streaming-tool-call-tracker.ts\n/**\n* Tracks streaming tool call state across multiple deltas from an\n* OpenAI-compatible chat completion stream. Handles argument accumulation,\n* emits tool-input-start/delta/end and tool-call events, and finalizes\n* unfinished tool calls on flush.\n*\n* Used by openai, openai-compatible, groq, deepseek, alibaba, mistral, and\n* moonshotai providers.\n*/\nvar StreamingToolCallTracker = class {\n\tconstructor(controller, options = {}) {\n\t\tthis.toolCalls = [];\n\t\tthis.toolCallsById = /* @__PURE__ */ new Map();\n\t\tthis.toolCallsByIndex = /* @__PURE__ */ new Map();\n\t\tthis.usedToolCallIds = /* @__PURE__ */ new Set();\n\t\tthis.nextGeneratedIdSuffixes = /* @__PURE__ */ new Map();\n\t\tthis.controller = controller;\n\t\tthis._generateId = options.generateId ?? generateId;\n\t\tthis.typeValidation = options.typeValidation ?? \"none\";\n\t\tthis.extractMetadata = options.extractMetadata;\n\t\tthis.buildToolCallProviderMetadata = options.buildToolCallProviderMetadata;\n\t}\n\t/**\n\t* Process a tool call delta from a streaming response chunk.\n\t* Emits tool-input-start, tool-input-delta, tool-input-end, and tool-call\n\t* events as appropriate.\n\t*/\n\tprocessDelta(toolCallDelta) {\n\t\tconst wireName = toolCallDelta.function?.name;\n\t\tconst hasBlankName = typeof wireName === \"string\" && wireName.trim().length === 0;\n\t\tconst wireId = this.getNonBlankString(toolCallDelta.id);\n\t\tconst name = this.getNonBlankString(wireName);\n\t\tconst argumentsDelta = toolCallDelta.function?.arguments;\n\t\tconst { index } = toolCallDelta;\n\t\tconst resolution = this.resolveToolCall({\n\t\t\twireId,\n\t\t\tindex,\n\t\t\tname,\n\t\t\thasExplicitCallStart: name != null && startsWithStructuredValue(argumentsDelta),\n\t\t\thasEmptyArguments: argumentsDelta == null || argumentsDelta.trim().length === 0\n\t\t});\n\t\tif (resolution.kind === \"ambiguous\") return;\n\t\tlet toolCall;\n\t\tif (resolution.kind === \"new\") {\n\t\t\tif (hasBlankName) return;\n\t\t\ttoolCall = this.processNewToolCall(toolCallDelta, {\n\t\t\t\twireId,\n\t\t\t\tindex,\n\t\t\t\tname\n\t\t\t});\n\t\t} else {\n\t\t\ttoolCall = resolution.toolCall;\n\t\t\tif (wireId != null) this.associateWireId(toolCall, wireId);\n\t\t\tthis.processExistingToolCall(toolCall, toolCallDelta);\n\t\t}\n\t\tif (index != null) this.associateIndex(toolCall, index);\n\t}\n\t/**\n\t* Finalize any unfinished tool calls. Should be called during the stream's\n\t* flush handler to ensure all tool calls are properly completed.\n\t*/\n\tflush() {\n\t\tconst toolCalls = this.toolCalls.every((toolCall) => toolCall.index != null) ? [...this.toolCalls].sort((a, b) => a.index - b.index || a.sequence - b.sequence) : this.toolCalls;\n\t\tfor (const toolCall of toolCalls) if (!toolCall.hasFinished) this.finishToolCall(toolCall);\n\t}\n\t/**\n\t* Correlation precedence for streamed deltas:\n\t*\n\t* | ID evidence | index/name evidence | start evidence | resolution |\n\t* | --- | --- | --- | --- |\n\t* | known | matching | any | matching call, new call, or ambiguity |\n\t* | known | conflicting | named | new call |\n\t* | unseen | matching | structured start | new call |\n\t* | unseen | matching | named empty arguments | incomplete call, new call, or ambiguity |\n\t* | unseen | matching | continuation | matching call or ambiguity |\n\t* | absent | matching | any | matching call, new call, or ambiguity |\n\t* | absent | absent | named | new call |\n\t* | absent | absent | unnamed | sole unfinished call, new call, or ambiguity |\n\t*/\n\tresolveToolCall({ wireId, index, name, hasExplicitCallStart, hasEmptyArguments }) {\n\t\tconst indexedToolCalls = index != null ? this.toolCallsByIndex.get(index) : void 0;\n\t\tconst matchingIndexedToolCalls = this.filterToolCallsByName(indexedToolCalls, name);\n\t\tif (wireId != null) {\n\t\t\tconst toolCallsWithId = this.toolCallsById.get(wireId);\n\t\t\tif (toolCallsWithId != null) {\n\t\t\t\tif (index != null) {\n\t\t\t\t\tconst matchingToolCalls = matchingIndexedToolCalls.filter((toolCall) => toolCallsWithId.has(toolCall));\n\t\t\t\t\tconst matchingToolCall = this.resolveMatchingToolCall(matchingToolCalls, hasExplicitCallStart);\n\t\t\t\t\tif (matchingToolCall.kind !== \"new\") return matchingToolCall;\n\t\t\t\t\tif (name != null) return { kind: \"new\" };\n\t\t\t\t\tif (indexedToolCalls != null) return { kind: \"ambiguous\" };\n\t\t\t\t\treturn this.resolveMatchingToolCall([...toolCallsWithId], false);\n\t\t\t\t}\n\t\t\t\tif (name != null) {\n\t\t\t\t\tconst matchingToolCalls = [...toolCallsWithId].filter((toolCall) => toolCall.function.name === name);\n\t\t\t\t\treturn this.resolveMatchingToolCall(matchingToolCalls, hasExplicitCallStart);\n\t\t\t\t}\n\t\t\t\treturn this.resolveMatchingToolCall([...toolCallsWithId], false);\n\t\t\t}\n\t\t\tif (matchingIndexedToolCalls.length > 0) return hasExplicitCallStart ? { kind: \"new\" } : this.resolveMatchingToolCall(matchingIndexedToolCalls, name != null && hasEmptyArguments);\n\t\t\treturn { kind: \"new\" };\n\t\t}\n\t\tif (indexedToolCalls != null) return this.resolveMatchingToolCall(matchingIndexedToolCalls, hasExplicitCallStart);\n\t\tif (name != null) return { kind: \"new\" };\n\t\tconst unfinishedToolCalls = this.toolCalls.filter((toolCall) => !toolCall.hasFinished);\n\t\treturn this.resolveMatchingToolCall(unfinishedToolCalls, false);\n\t}\n\tfilterToolCallsByName(toolCalls, name) {\n\t\tif (toolCalls == null) return [];\n\t\treturn [...toolCalls].filter((toolCall) => name == null || toolCall.function.name === name);\n\t}\n\tresolveMatchingToolCall(toolCalls, hasExplicitCallStart) {\n\t\tif (toolCalls.length === 0) return { kind: \"new\" };\n\t\tconst continuableToolCalls = toolCalls.filter((toolCall) => !toolCall.argumentState.hasCompleteStructuredValue);\n\t\tif (!hasExplicitCallStart && toolCalls.length === 1) return {\n\t\t\tkind: \"existing\",\n\t\t\ttoolCall: toolCalls[0]\n\t\t};\n\t\tif (continuableToolCalls.length === 1) return {\n\t\t\tkind: \"existing\",\n\t\t\ttoolCall: continuableToolCalls[0]\n\t\t};\n\t\tif (continuableToolCalls.length > 1 || !hasExplicitCallStart) return { kind: \"ambiguous\" };\n\t\treturn { kind: \"new\" };\n\t}\n\tprocessNewToolCall(toolCallDelta, { wireId, index, name }) {\n\t\tif (this.typeValidation === \"required\") {\n\t\t\tif (toolCallDelta.type !== \"function\") throw new InvalidResponseDataError({\n\t\t\t\tdata: toolCallDelta,\n\t\t\t\tmessage: `Expected 'function' type.`\n\t\t\t});\n\t\t} else if (this.typeValidation === \"if-present\") {\n\t\t\tif (toolCallDelta.type != null && toolCallDelta.type !== \"function\") throw new InvalidResponseDataError({\n\t\t\t\tdata: toolCallDelta,\n\t\t\t\tmessage: `Expected 'function' type.`\n\t\t\t});\n\t\t}\n\t\tif (name == null) throw new InvalidResponseDataError({\n\t\t\tdata: toolCallDelta,\n\t\t\tmessage: `Expected 'function.name' to be a string.`\n\t\t});\n\t\tconst id = this.createToolCallId(wireId);\n\t\tthis.controller.enqueue({\n\t\t\ttype: \"tool-input-start\",\n\t\t\tid,\n\t\t\ttoolName: name\n\t\t});\n\t\tconst metadata = this.extractMetadata?.(toolCallDelta);\n\t\tconst initialArguments = toolCallDelta.function?.arguments ?? \"\";\n\t\tconst toolCall = {\n\t\t\tid,\n\t\t\tindex: index ?? void 0,\n\t\t\tsequence: this.toolCalls.length,\n\t\t\ttype: \"function\",\n\t\t\tfunction: {\n\t\t\t\tname,\n\t\t\t\targuments: initialArguments\n\t\t\t},\n\t\t\targumentState: new StreamingToolCallArgumentState(initialArguments),\n\t\t\thasFinished: false,\n\t\t\tmetadata\n\t\t};\n\t\tthis.toolCalls.push(toolCall);\n\t\tif (wireId != null) this.associateWireId(toolCall, wireId);\n\t\tif (toolCall.function.arguments.length > 0) this.controller.enqueue({\n\t\t\ttype: \"tool-input-delta\",\n\t\t\tid: toolCall.id,\n\t\t\tdelta: toolCall.function.arguments\n\t\t});\n\t\treturn toolCall;\n\t}\n\tassociateWireId(toolCall, wireId) {\n\t\tlet toolCallsWithId = this.toolCallsById.get(wireId);\n\t\tif (toolCallsWithId == null) {\n\t\t\ttoolCallsWithId = /* @__PURE__ */ new Set();\n\t\t\tthis.toolCallsById.set(wireId, toolCallsWithId);\n\t\t}\n\t\ttoolCallsWithId.add(toolCall);\n\t}\n\tassociateIndex(toolCall, index) {\n\t\tlet toolCallsWithIndex = this.toolCallsByIndex.get(index);\n\t\tif (toolCallsWithIndex == null) {\n\t\t\ttoolCallsWithIndex = /* @__PURE__ */ new Set();\n\t\t\tthis.toolCallsByIndex.set(index, toolCallsWithIndex);\n\t\t}\n\t\ttoolCallsWithIndex.add(toolCall);\n\t}\n\tcreateToolCallId(wireId) {\n\t\tif (wireId != null && !this.usedToolCallIds.has(wireId)) {\n\t\t\tthis.usedToolCallIds.add(wireId);\n\t\t\treturn wireId;\n\t\t}\n\t\tconst generatedId = this.getNonBlankString(this._generateId()) ?? \"tool-call\";\n\t\tif (!this.usedToolCallIds.has(generatedId)) {\n\t\t\tthis.usedToolCallIds.add(generatedId);\n\t\t\treturn generatedId;\n\t\t}\n\t\tconst initialSuffix = this.nextGeneratedIdSuffixes.get(generatedId) ?? 1;\n\t\tconst maximumSuffix = initialSuffix + this.usedToolCallIds.size;\n\t\tfor (let suffix = initialSuffix; suffix <= maximumSuffix; suffix++) {\n\t\t\tconst suffixedId = `${generatedId}-${suffix}`;\n\t\t\tif (!this.usedToolCallIds.has(suffixedId)) {\n\t\t\t\tthis.usedToolCallIds.add(suffixedId);\n\t\t\t\tthis.nextGeneratedIdSuffixes.set(generatedId, suffix + 1);\n\t\t\t\treturn suffixedId;\n\t\t\t}\n\t\t}\n\t\tthrow new Error(\"Failed to create a unique tool call ID.\");\n\t}\n\tgetNonBlankString(value) {\n\t\treturn value != null && value.trim().length > 0 ? value : void 0;\n\t}\n\tprocessExistingToolCall(toolCall, toolCallDelta) {\n\t\tif (toolCall.hasFinished) return;\n\t\tif (toolCallDelta.function?.arguments != null) {\n\t\t\ttoolCall.argumentState.append(toolCallDelta.function.arguments);\n\t\t\ttoolCall.function.arguments += toolCallDelta.function.arguments;\n\t\t\tthis.controller.enqueue({\n\t\t\t\ttype: \"tool-input-delta\",\n\t\t\t\tid: toolCall.id,\n\t\t\t\tdelta: toolCallDelta.function.arguments\n\t\t\t});\n\t\t}\n\t}\n\tfinishToolCall(toolCall) {\n\t\tthis.controller.enqueue({\n\t\t\ttype: \"tool-input-end\",\n\t\t\tid: toolCall.id\n\t\t});\n\t\tconst providerMetadata = this.buildToolCallProviderMetadata?.(toolCall.metadata);\n\t\tthis.controller.enqueue({\n\t\t\ttype: \"tool-call\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.function.name,\n\t\t\tinput: toolCall.function.arguments,\n\t\t\t...providerMetadata ? { providerMetadata } : {}\n\t\t});\n\t\ttoolCall.hasFinished = true;\n\t}\n};\n//#endregion\n//#region src/strip-file-extension.ts\n/**\n* Strips file extension segments from a filename.\n*\n* Examples:\n* - \"report.pdf\" -> \"report\"\n* - \"archive.tar.gz\" -> \"archive\"\n* - \"filename\" -> \"filename\"\n*/\nfunction stripFileExtension(filename) {\n\tconst firstDotIndex = filename.indexOf(\".\");\n\treturn firstDotIndex === -1 ? filename : filename.slice(0, firstDotIndex);\n}\n//#endregion\n//#region src/transcription-stream-envelope.ts\n/**\n* Experimental transcription-stream WebSocket envelope (v1): the standard\n* serialization of `TranscriptionModelV4.doStream` over a WebSocket. Clients\n* (e.g. the `@ai-sdk/gateway` provider) encode with this module and servers\n* (e.g. AI Gateway) decode with it, so the two sides cannot drift.\n*\n* Envelope rules:\n*\n* 1. The client sends exactly one `transcription-stream.start` TEXT frame\n* first.\n* 2. Audio rides BINARY frames containing raw bytes in the declared\n* `inputAudioFormat` (base64 string chunks are decoded before sending).\n* 3. The client signals end of audio with the\n* `transcription-stream.audio-done` TEXT frame; a plain close without it\n* is an abort.\n* 4. Every server→client TEXT frame is one JSON-serialized\n* `TranscriptionModelV4StreamPart` (flattened, no wrapper). Payloads must\n* be JSON-serializable. `Date` values (`response-metadata.timestamp`)\n* serialize to ISO 8601 strings and are revived by\n* `parseTranscriptionStreamPart`. `Error` payloads in `error` parts\n* serialize as `{ name, message }`.\n* 5. The server closes with code 1000 after the `finish` part; on failure it\n* sends an `error` part and closes non-1000. A close without a prior\n* `finish` is an error.\n* 6. Unknown frame/part types are ignored in both directions (forward\n* compatibility).\n* 7. Servers may enforce a maximum frame size (the AI Gateway rejects frames\n* over 256 KiB); clients should split audio into frames of at most\n* 64 KiB.\n* 8. Connection establishment (URL, auth) is transport-specific and out of\n* scope.\n*\n* The envelope validates frame shape only; server policy (accepted audio\n* formats, required `rate`, size limits) layers on top. Both parsers use\n* `secureJsonParse`, so frames carrying `__proto__` / `constructor.prototype`\n* keys are rejected (prototype-pollution protection) rather than parsed.\n*/\n/** Type of the first client TEXT frame. */\nconst TRANSCRIPTION_STREAM_START_FRAME_TYPE = \"transcription-stream.start\";\n/** Type of the client TEXT frame that signals the end of the audio input. */\nconst TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE = \"transcription-stream.audio-done\";\n/**\n* Server-side: parse a client TEXT frame. Validates envelope shape only and\n* rejects prototype-pollution payloads (parsed with `secureJsonParse`). Never\n* throws.\n*/\nfunction parseTranscriptionStreamClientFrame(text) {\n\tlet value;\n\ttry {\n\t\tvalue = secureJsonParse(text);\n\t} catch {\n\t\treturn {\n\t\t\ttype: \"invalid\",\n\t\t\tmessage: \"malformed JSON\"\n\t\t};\n\t}\n\tif (value == null || typeof value !== \"object\" || Array.isArray(value)) return {\n\t\ttype: \"invalid\",\n\t\tmessage: \"frame must be a JSON object\"\n\t};\n\tconst frame = value;\n\tif (typeof frame.type !== \"string\") return {\n\t\ttype: \"invalid\",\n\t\tmessage: \"frame type must be a string\"\n\t};\n\tswitch (frame.type) {\n\t\tcase TRANSCRIPTION_STREAM_START_FRAME_TYPE: {\n\t\t\tconst inputAudioFormat = frame.inputAudioFormat;\n\t\t\tif (inputAudioFormat == null || typeof inputAudioFormat !== \"object\" || Array.isArray(inputAudioFormat) || typeof inputAudioFormat.type !== \"string\") return {\n\t\t\t\ttype: \"invalid\",\n\t\t\t\tmessage: \"start frame must have an inputAudioFormat object with a string type\"\n\t\t\t};\n\t\t\tif (inputAudioFormat.rate !== void 0 && typeof inputAudioFormat.rate !== \"number\") return {\n\t\t\t\ttype: \"invalid\",\n\t\t\t\tmessage: \"inputAudioFormat.rate must be a number when present\"\n\t\t\t};\n\t\t\tif (frame.providerOptions !== void 0 && (frame.providerOptions == null || typeof frame.providerOptions !== \"object\" || Array.isArray(frame.providerOptions))) return {\n\t\t\t\ttype: \"invalid\",\n\t\t\t\tmessage: \"providerOptions must be an object when present\"\n\t\t\t};\n\t\t\tif (frame.includeRawChunks !== void 0 && typeof frame.includeRawChunks !== \"boolean\") return {\n\t\t\t\ttype: \"invalid\",\n\t\t\t\tmessage: \"includeRawChunks must be a boolean when present\"\n\t\t\t};\n\t\t\treturn {\n\t\t\t\ttype: \"start\",\n\t\t\t\tframe\n\t\t\t};\n\t\t}\n\t\tcase TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE: return { type: \"audio-done\" };\n\t\tdefault: return { type: \"unknown\" };\n\t}\n}\n/**\n* Server-side: serialize a transcription stream part as one TEXT frame.\n* `Error` payloads in `error` parts serialize as `{ name, message }` —\n* `Error` properties are non-enumerable, so a plain `JSON.stringify` would\n* serialize them to `{}` and lose the message end-to-end. Returns\n* `undefined` for payloads that are not JSON-serializable (envelope rule 4,\n* e.g. bigint or cyclic values); callers drop the frame.\n*/\nfunction serializeTranscriptionStreamPart(part) {\n\ttry {\n\t\tif (part.type === \"error\" && isError(part.error)) return JSON.stringify({\n\t\t\t...part,\n\t\t\terror: {\n\t\t\t\tname: part.error.name,\n\t\t\t\tmessage: part.error.message\n\t\t\t}\n\t\t});\n\t\treturn JSON.stringify(part);\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction isError(value) {\n\treturn value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\";\n}\n/**\n* Client-side: parse a server TEXT frame into a transcription stream part.\n* Returns `undefined` for malformed or unsafe (prototype-polluting) JSON\n* (parsed with `secureJsonParse`), unknown part types, and known part types\n* whose required or optional fields are missing or mistyped (including\n* warning and segment elements) — downstream SDK code dereferences those\n* fields, so a drifted server must not crash or pollute the stream.\n* Revives `response-metadata.timestamp` to a `Date`.\n*/\nfunction parseTranscriptionStreamPart(text) {\n\tlet value;\n\ttry {\n\t\tvalue = secureJsonParse(text);\n\t} catch {\n\t\treturn;\n\t}\n\tif (value == null || typeof value !== \"object\" || Array.isArray(value)) return;\n\tconst part = value;\n\tswitch (part.type) {\n\t\tcase \"stream-start\": return Array.isArray(part.warnings) && part.warnings.every(isWarning) ? part : void 0;\n\t\tcase \"transcript-delta\": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isRecord) ? part : void 0;\n\t\tcase \"transcript-partial\": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isRecord) ? part : void 0;\n\t\tcase \"transcript-final\": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.endSecond, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isRecord) ? part : void 0;\n\t\tcase \"finish\": return isString(part.text) && Array.isArray(part.segments) && part.segments.every(isSegment) && isOptional(part.language, isString) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.usage, isRecord) && isOptional(part.providerMetadata, isRecord) ? part : void 0;\n\t\tcase \"response-metadata\": {\n\t\t\tif (!(isOptional(part.modelId, isString) && isOptional(part.headers, isRecord))) return;\n\t\t\tconst timestamp = part.timestamp;\n\t\t\tif (timestamp == null) return {\n\t\t\t\t...part,\n\t\t\t\ttimestamp: void 0\n\t\t\t};\n\t\t\tif (typeof timestamp !== \"string\") return;\n\t\t\tconst revived = new Date(timestamp);\n\t\t\treturn Number.isNaN(revived.getTime()) ? void 0 : {\n\t\t\t\t...part,\n\t\t\t\ttimestamp: revived\n\t\t\t};\n\t\t}\n\t\tcase \"raw\": return \"rawValue\" in part ? part : void 0;\n\t\tcase \"error\": return \"error\" in part ? part : void 0;\n\t\tdefault: return;\n\t}\n}\nfunction isString(value) {\n\treturn typeof value === \"string\";\n}\nfunction isNumber(value) {\n\treturn typeof value === \"number\";\n}\nfunction isOptional(value, check) {\n\treturn value === void 0 || check(value);\n}\nfunction isWarning(value) {\n\treturn isRecord(value) && isString(value.type);\n}\nfunction isSegment(value) {\n\treturn isRecord(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);\n}\n//#endregion\n//#region src/validate-base-url.ts\nfunction validateBaseURL(baseURL) {\n\tif (baseURL?.trim() === \"\") throw new InvalidArgumentError({\n\t\targument: \"baseURL\",\n\t\tmessage: \"baseURL must be a non-empty string.\"\n\t});\n\treturn baseURL;\n}\n//#endregion\n//#region src/without-trailing-slash.ts\nfunction withoutTrailingSlash(url) {\n\treturn url?.replace(/\\/$/, \"\");\n}\n//#endregion\n//#region src/types/executable-tool.ts\n/**\n* Checks whether a tool exposes an execute function.\n*/\nfunction isExecutableTool(tool) {\n\treturn tool != null && typeof tool.execute === \"function\";\n}\n//#endregion\n//#region src/is-async-iterable.ts\nfunction isAsyncIterable(obj) {\n\treturn obj != null && typeof obj[Symbol.asyncIterator] === \"function\";\n}\n//#endregion\n//#region src/types/execute-tool.ts\n/**\n* Executes a tool function and normalizes its results into a stream of outputs.\n*\n* - If the tool's `execute` function returns an `AsyncIterable`, each yielded value is emitted as\n* `{ type: \"preliminary\", output }`. After iteration completes, the last yielded value is emitted\n* again as `{ type: \"final\", output }`.\n* - If the tool returns a direct value or Promise, a single `{ type: \"final\", output }` is yielded.\n*\n* @param params.tool The tool whose `execute` function should be invoked.\n* @param params.input The input value to pass to the tool.\n* @param params.options Additional options for tool execution.\n* @yields A preliminary output for each streamed value, followed by a final output, or a single final\n* output for non-streaming tools.\n*/\nasync function* executeTool({ tool, input, options }) {\n\tconst result = tool.execute(input, options);\n\tif (isAsyncIterable(result)) {\n\t\tlet lastOutput;\n\t\tfor await (const output of result) {\n\t\t\tlastOutput = output;\n\t\t\tyield {\n\t\t\t\ttype: \"preliminary\",\n\t\t\t\toutput\n\t\t\t};\n\t\t}\n\t\tyield {\n\t\t\ttype: \"final\",\n\t\t\toutput: lastOutput\n\t\t};\n\t} else yield {\n\t\ttype: \"final\",\n\t\toutput: await result\n\t};\n}\n//#endregion\n//#region src/types/tool-caller.ts\nfunction toolCaller(tool, definition) {\n\treturn Object.defineProperty({ ...tool }, \"experimental_toolCaller\", { value: definition });\n}\nfunction getToolCaller(tool) {\n\treturn tool?.experimental_toolCaller;\n}\n//#endregion\nexport { DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise, DownloadError, 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, EventSourceParserStream, SerializationError, StreamingToolCallTracker, VERSION, WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, asArray, asSchema, cancelResponseBody, combineHeaders, connectToWebSocket, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertInlineFileDataToUint8Array, convertJsonResponseToolStream, 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, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, isProviderStreamError, isRecord, isSameOrigin, isUrlSupported, isValidHostnamePart, 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 };\n\n//# sourceMappingURL=index.js.map","import { t as __exportAll } from \"./rolldown-runtime-D7D4PA-g.js\";\nimport { GatewayAuthenticationError, GatewayError, createGateway, gateway, gateway as gateway$1 } from \"@ai-sdk/gateway\";\nimport { DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise, DownloadError, DownloadError as DownloadError$1, EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, asArray, asSchema, asSchema as asSchema$1, cancelResponseBody, convertBase64ToUint8Array, convertUint8ArrayToBase64, createIdGenerator, createIdGenerator as createIdGenerator$1, delay, detectMediaType, dynamicTool, executeTool, experimental_getToolCaller, experimental_toolCaller, fetchUntrustedUrl, filterNullable, generateId, generateId as generateId$1, getErrorMessage, getRuntimeEnvironmentUserAgent, getWebSocketConstructor, isAbortError, isBuffer, isExecutableTool, isFullMediaType, isNonNullable, isProviderReference, isProviderStreamError, isUrlSupported, jsonSchema, jsonSchema as jsonSchema$1, lazySchema, normalizeHeaders, parseJsonEventStream, parseJsonEventStream as parseJsonEventStream$1, readResponseWithSizeLimit, readWebSocketMessageText, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, toWebSocketUrl, tool, tool as tool$1, validateTypes, waitForWebSocketBufferDrain, withUserAgentSuffix, zodSchema, zodSchema as zodSchema$1 } from \"@ai-sdk/provider-utils\";\nimport { AISDKError, AISDKError as AISDKError$1, APICallError, APICallError as APICallError$1, EmptyResponseBodyError, EmptyResponseBodyError as EmptyResponseBodyError$1, Experimental_DecisionRefusalError, Experimental_DecisionRefusalError as Experimental_DecisionRefusalError$1, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_DecisionUnsupportedQuestionTypeError as Experimental_DecisionUnsupportedQuestionTypeError$1, InvalidArgumentError as InvalidArgumentError$1, InvalidPromptError, InvalidPromptError as InvalidPromptError$1, InvalidResponseDataError, InvalidResponseDataError as InvalidResponseDataError$1, JSONParseError, JSONParseError as JSONParseError$1, LoadAPIKeyError, LoadSettingError, NoContentGeneratedError, NoSuchModelError, NoSuchModelError as NoSuchModelError$1, NoSuchProviderReferenceError, TooManyEmbeddingValuesForCallError, TypeValidationError, TypeValidationError as TypeValidationError$1, UnsupportedFunctionalityError, UnsupportedFunctionalityError as UnsupportedFunctionalityError$1, getErrorMessage as getErrorMessage$1, isJSONArray, isJSONObject } from \"@ai-sdk/provider\";\nimport { array, boolean, custom, discriminatedUnion, enum as enum$1, instanceof as instanceof$1, lazy, literal, looseObject, never, null as null$1, number, object, record, string, union, unknown } from \"zod/v4\";\n//#region src/error/invalid-argument-error.ts\nconst name$23 = \"AI_InvalidArgumentError\";\nconst marker$23 = `vercel.ai.error.${name$23}`;\nconst symbol$23 = Symbol.for(marker$23);\nvar InvalidArgumentError = class extends AISDKError$1 {\n\tconstructor({ parameter, value, message }) {\n\t\tsuper({\n\t\t\tname: name$23,\n\t\t\tmessage: `Invalid argument for parameter ${parameter}: ${message}`\n\t\t});\n\t\tthis[symbol$23] = true;\n\t\tthis.parameter = parameter;\n\t\tthis.value = value;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$23);\n\t}\n};\n//#endregion\n//#region src/error/invalid-stream-part-error.ts\nconst name$22 = \"AI_InvalidStreamPartError\";\nconst marker$22 = `vercel.ai.error.${name$22}`;\nconst symbol$22 = Symbol.for(marker$22);\nvar InvalidStreamPartError = class extends AISDKError$1 {\n\tconstructor({ chunk, message }) {\n\t\tsuper({\n\t\t\tname: name$22,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$22] = true;\n\t\tthis.chunk = chunk;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$22);\n\t}\n};\n//#endregion\n//#region src/error/invalid-tool-approval-error.ts\nconst name$21 = \"AI_InvalidToolApprovalError\";\nconst marker$21 = `vercel.ai.error.${name$21}`;\nconst symbol$21 = Symbol.for(marker$21);\nvar InvalidToolApprovalError = class extends AISDKError$1 {\n\tconstructor({ approvalId }) {\n\t\tsuper({\n\t\t\tname: name$21,\n\t\t\tmessage: `Tool approval response references unknown approvalId: \"${approvalId}\". No matching tool-approval-request found in message history.`\n\t\t});\n\t\tthis[symbol$21] = true;\n\t\tthis.approvalId = approvalId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$21);\n\t}\n};\n//#endregion\n//#region src/error/invalid-tool-approval-signature-error.ts\nconst name$20 = \"AI_InvalidToolApprovalSignatureError\";\nconst marker$20 = `vercel.ai.error.${name$20}`;\nconst symbol$20 = Symbol.for(marker$20);\nvar InvalidToolApprovalSignatureError = class extends AISDKError$1 {\n\tconstructor({ approvalId, toolCallId, reason }) {\n\t\tsuper({\n\t\t\tname: name$20,\n\t\t\tmessage: `Tool approval signature verification failed for approval \"${approvalId}\" (tool call \"${toolCallId}\"): ${reason}`\n\t\t});\n\t\tthis[symbol$20] = true;\n\t\tthis.approvalId = approvalId;\n\t\tthis.toolCallId = toolCallId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$20);\n\t}\n};\n//#endregion\n//#region src/error/invalid-tool-input-error.ts\nconst name$19 = \"AI_InvalidToolInputError\";\nconst marker$19 = `vercel.ai.error.${name$19}`;\nconst symbol$19 = Symbol.for(marker$19);\nvar InvalidToolInputError = class extends AISDKError$1 {\n\tconstructor({ toolInput, toolName, cause, message = `Invalid input for tool ${toolName}: ${getErrorMessage$1(cause)}` }) {\n\t\tsuper({\n\t\t\tname: name$19,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$19] = true;\n\t\tthis.toolInput = toolInput;\n\t\tthis.toolName = toolName;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$19);\n\t}\n};\n//#endregion\n//#region src/error/tool-call-not-found-for-approval-error.ts\nconst name$18 = \"AI_ToolCallNotFoundForApprovalError\";\nconst marker$18 = `vercel.ai.error.${name$18}`;\nconst symbol$18 = Symbol.for(marker$18);\nvar ToolCallNotFoundForApprovalError = class extends AISDKError$1 {\n\tconstructor({ toolCallId, approvalId }) {\n\t\tsuper({\n\t\t\tname: name$18,\n\t\t\tmessage: `Tool call \"${toolCallId}\" not found for approval request \"${approvalId}\".`\n\t\t});\n\t\tthis[symbol$18] = true;\n\t\tthis.toolCallId = toolCallId;\n\t\tthis.approvalId = approvalId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$18);\n\t}\n};\n//#endregion\n//#region src/error/missing-tool-result-error.ts\nconst name$17 = \"AI_MissingToolResultsError\";\nconst marker$17 = `vercel.ai.error.${name$17}`;\nconst symbol$17 = Symbol.for(marker$17);\nvar MissingToolResultsError = class extends AISDKError$1 {\n\tconstructor({ toolCallIds }) {\n\t\tsuper({\n\t\t\tname: name$17,\n\t\t\tmessage: `Tool result${toolCallIds.length > 1 ? \"s are\" : \" is\"} missing for tool call${toolCallIds.length > 1 ? \"s\" : \"\"} ${toolCallIds.join(\", \")}.`\n\t\t});\n\t\tthis[symbol$17] = true;\n\t\tthis.toolCallIds = toolCallIds;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$17);\n\t}\n};\n//#endregion\n//#region src/error/no-image-generated-error.ts\nconst name$16 = \"AI_NoImageGeneratedError\";\nconst marker$16 = `vercel.ai.error.${name$16}`;\nconst symbol$16 = Symbol.for(marker$16);\n/**\n* Thrown when no image could be generated. This can have multiple causes:\n*\n* - The model failed to generate a response.\n* - The model generated a response that could not be parsed.\n*/\nvar NoImageGeneratedError = class extends AISDKError$1 {\n\tconstructor({ message = \"No image generated.\", cause, calls, responses }) {\n\t\tsuper({\n\t\t\tname: name$16,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$16] = true;\n\t\tthis.calls = calls;\n\t\tthis.responses = responses;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$16);\n\t}\n};\n//#endregion\n//#region src/error/no-object-generated-error.ts\nconst name$15 = \"AI_NoObjectGeneratedError\";\nconst marker$15 = `vercel.ai.error.${name$15}`;\nconst symbol$15 = Symbol.for(marker$15);\n/**\n* Thrown when no object could be generated. This can have several causes:\n*\n* - The model failed to generate a response.\n* - The model generated a response that could not be parsed.\n* - The model generated a response that could not be validated against the schema.\n*\n* The error contains the following properties:\n*\n* - `text`: The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.\n*/\nvar NoObjectGeneratedError = class extends AISDKError$1 {\n\tconstructor({ message = \"No object generated.\", cause, text, response, usage, finishReason }) {\n\t\tsuper({\n\t\t\tname: name$15,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$15] = true;\n\t\tthis.text = text;\n\t\tthis.response = response;\n\t\tthis.usage = usage;\n\t\tthis.finishReason = finishReason;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$15);\n\t}\n};\n//#endregion\n//#region src/error/no-output-generated-error.ts\nconst name$14 = \"AI_NoOutputGeneratedError\";\nconst marker$14 = `vercel.ai.error.${name$14}`;\nconst symbol$14 = Symbol.for(marker$14);\n/**\n* Thrown when no LLM output was generated, e.g. because of errors.\n*/\nvar NoOutputGeneratedError = class extends AISDKError$1 {\n\tconstructor({ message = \"No output generated.\", cause } = {}) {\n\t\tsuper({\n\t\t\tname: name$14,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$14] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$14);\n\t}\n};\n//#endregion\n//#region src/error/no-speech-generated-error.ts\nconst name$13 = \"AI_NoSpeechGeneratedError\";\nconst marker$13 = `vercel.ai.error.${name$13}`;\nconst symbol$13 = Symbol.for(marker$13);\n/**\n* Error that is thrown when no speech audio was generated.\n*/\nvar NoSpeechGeneratedError = class extends AISDKError$1 {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: name$13,\n\t\t\tmessage: \"No speech audio generated.\"\n\t\t});\n\t\tthis[symbol$13] = true;\n\t\tthis.responses = options.responses;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$13);\n\t}\n};\n//#endregion\n//#region src/error/no-transcript-generated-error.ts\nconst name$12 = \"AI_NoTranscriptGeneratedError\";\nconst marker$12 = `vercel.ai.error.${name$12}`;\nconst symbol$12 = Symbol.for(marker$12);\n/**\n* Error that is thrown when no transcript was generated.\n*/\nvar NoTranscriptGeneratedError = class extends AISDKError$1 {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: name$12,\n\t\t\tmessage: \"No transcript generated.\"\n\t\t});\n\t\tthis[symbol$12] = true;\n\t\tthis.responses = options.responses;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$12);\n\t}\n};\n//#endregion\n//#region src/error/no-translation-generated-error.ts\nconst name$11 = \"AI_NoTranslationGeneratedError\";\nconst marker$11 = `vercel.ai.error.${name$11}`;\nconst symbol$11 = Symbol.for(marker$11);\n/**\n* Error that is thrown when no translation was generated.\n*/\nvar NoTranslationGeneratedError = class extends AISDKError$1 {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: name$11,\n\t\t\tmessage: \"No translation generated.\"\n\t\t});\n\t\tthis[symbol$11] = true;\n\t\tthis.response = options.response;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$11);\n\t}\n};\n//#endregion\n//#region src/error/no-video-generated-error.ts\nconst name$10 = \"AI_NoVideoGeneratedError\";\nconst marker$10 = `vercel.ai.error.${name$10}`;\nconst symbol$10 = Symbol.for(marker$10);\nvar NoVideoGeneratedError = class extends AISDKError$1 {\n\tconstructor({ message = \"No video generated.\", cause, responses }) {\n\t\tsuper({\n\t\t\tname: name$10,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$10] = true;\n\t\tthis.responses = responses;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$10);\n\t}\n\t/**\n\t* @deprecated use `isInstance` instead\n\t*/\n\tstatic isNoVideoGeneratedError(error) {\n\t\treturn error instanceof Error && error.name === name$10 && typeof error.responses !== \"undefined\" ? true : false;\n\t}\n\t/**\n\t* @deprecated Do not use this method. It will be removed in the next major version.\n\t*/\n\ttoJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\tstack: this.stack,\n\t\t\tcause: this.cause,\n\t\t\tresponses: this.responses\n\t\t};\n\t}\n};\n//#endregion\n//#region src/error/no-such-tool-error.ts\nconst name$9 = \"AI_NoSuchToolError\";\nconst marker$9 = `vercel.ai.error.${name$9}`;\nconst symbol$9 = Symbol.for(marker$9);\nvar NoSuchToolError = class extends AISDKError$1 {\n\tconstructor({ toolName, availableTools = void 0, message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? \"No tools are available.\" : `Available tools: ${availableTools.join(\", \")}.`}` }) {\n\t\tsuper({\n\t\t\tname: name$9,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$9] = true;\n\t\tthis.toolName = toolName;\n\t\tthis.availableTools = availableTools;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$9);\n\t}\n};\n//#endregion\n//#region src/error/stream-provider-error.ts\nconst name$8 = \"AI_StreamProviderError\";\nconst marker$8 = `vercel.ai.error.${name$8}`;\nconst symbol$8 = Symbol.for(marker$8);\n/**\n* Error reported by a provider after a model response stream has started.\n*/\nvar StreamProviderError = class extends AISDKError$1 {\n\tconstructor({ message, type, code, statusCode, isRetryable = isRetryableStatusCode$1(statusCode), data, cause }) {\n\t\tsuper({\n\t\t\tname: name$8,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$8] = true;\n\t\tthis.type = type;\n\t\tthis.code = code;\n\t\tthis.statusCode = statusCode;\n\t\tthis.isRetryable = isRetryable;\n\t\tthis.data = data;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$8);\n\t}\n};\nfunction isRetryableStatusCode$1(statusCode) {\n\treturn statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500);\n}\n//#endregion\n//#region src/error/tool-call-repair-error.ts\nconst name$7 = \"AI_ToolCallRepairError\";\nconst marker$7 = `vercel.ai.error.${name$7}`;\nconst symbol$7 = Symbol.for(marker$7);\nvar ToolCallRepairError = class extends AISDKError$1 {\n\tconstructor({ cause, originalError, message = `Error repairing tool call: ${getErrorMessage$1(cause)}` }) {\n\t\tsuper({\n\t\t\tname: name$7,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$7] = true;\n\t\tthis.originalError = originalError;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$7);\n\t}\n};\n//#endregion\n//#region src/error/tool-choice-violation-error.ts\nconst name$6 = \"AI_ToolChoiceViolationError\";\nconst marker$6 = `vercel.ai.error.${name$6}`;\nconst symbol$6 = Symbol.for(marker$6);\n/**\n* Thrown when a model response does not satisfy an enforced tool choice.\n*/\nvar ToolChoiceViolationError = class extends AISDKError$1 {\n\tconstructor({ toolChoice, finishReason, provider, modelId, content, message = toolChoice.type === \"required\" ? \"Model response did not contain a tool call even though tool choice was required.\" : `Model response did not contain a call to the required tool '${toolChoice.toolName}'.` }) {\n\t\tsuper({\n\t\t\tname: name$6,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$6] = true;\n\t\tthis.toolChoice = toolChoice;\n\t\tthis.finishReason = finishReason;\n\t\tthis.provider = provider;\n\t\tthis.modelId = modelId;\n\t\tthis.content = content;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$6);\n\t}\n};\n//#endregion\n//#region src/error/unsupported-model-version-error.ts\n/**\n* Error that is thrown when a model with an unsupported version is used.\n*/\nvar UnsupportedModelVersionError = class extends AISDKError$1 {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: \"AI_UnsupportedModelVersionError\",\n\t\t\tmessage: `Unsupported model version ${options.version} for provider \"${options.provider}\" and model \"${options.modelId}\". AI SDK 5 only supports models that implement specification version \"v2\".`\n\t\t});\n\t\tthis.version = options.version;\n\t\tthis.provider = options.provider;\n\t\tthis.modelId = options.modelId;\n\t}\n};\n//#endregion\n//#region src/error/ui-message-stream-error.ts\nconst name$5 = \"AI_UIMessageStreamError\";\nconst marker$5 = `vercel.ai.error.${name$5}`;\nconst symbol$5 = Symbol.for(marker$5);\n/**\n* Error thrown when a UI message stream reports an error or contains invalid\n* or out-of-sequence chunks.\n*\n* This typically occurs when:\n* - An error chunk is received\n* - A delta chunk is received without a corresponding start chunk\n* - An end chunk is received without a corresponding start chunk\n* - A tool invocation is not found for the given toolCallId\n*\n* @see https://ai-sdk.dev/docs/reference/ai-sdk-errors/ai-ui-message-stream-error\n*/\nvar UIMessageStreamError = class extends AISDKError$1 {\n\tconstructor({ chunkType, chunkId, message }) {\n\t\tsuper({\n\t\t\tname: name$5,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$5] = true;\n\t\tthis.chunkType = chunkType;\n\t\tthis.chunkId = chunkId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$5);\n\t}\n};\n//#endregion\n//#region src/prompt/invalid-data-content-error.ts\nconst name$4 = \"AI_InvalidDataContentError\";\nconst marker$4 = `vercel.ai.error.${name$4}`;\nconst symbol$4 = Symbol.for(marker$4);\nvar InvalidDataContentError = class extends AISDKError$1 {\n\tconstructor({ content, cause, message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.` }) {\n\t\tsuper({\n\t\t\tname: name$4,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$4] = true;\n\t\tthis.content = content;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$4);\n\t}\n};\n//#endregion\n//#region src/prompt/invalid-message-role-error.ts\nconst name$3 = \"AI_InvalidMessageRoleError\";\nconst marker$3 = `vercel.ai.error.${name$3}`;\nconst symbol$3 = Symbol.for(marker$3);\nvar InvalidMessageRoleError = class extends AISDKError$1 {\n\tconstructor({ role, message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".` }) {\n\t\tsuper({\n\t\t\tname: name$3,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$3] = true;\n\t\tthis.role = role;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$3);\n\t}\n};\n//#endregion\n//#region src/prompt/message-conversion-error.ts\nconst name$2 = \"AI_MessageConversionError\";\nconst marker$2 = `vercel.ai.error.${name$2}`;\nconst symbol$2 = Symbol.for(marker$2);\nvar MessageConversionError = class extends AISDKError$1 {\n\tconstructor({ originalMessage, message }) {\n\t\tsuper({\n\t\t\tname: name$2,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$2] = true;\n\t\tthis.originalMessage = originalMessage;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$2);\n\t}\n};\n//#endregion\n//#region src/util/retry-error.ts\nconst name$1 = \"AI_RetryError\";\nconst marker$1 = `vercel.ai.error.${name$1}`;\nconst symbol$1 = Symbol.for(marker$1);\nvar RetryError = class extends AISDKError$1 {\n\tconstructor({ message, reason, errors }) {\n\t\tsuper({\n\t\t\tname: name$1,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$1] = true;\n\t\tthis.reason = reason;\n\t\tthis.errors = errors;\n\t\tthis.lastError = errors[errors.length - 1];\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker$1);\n\t}\n};\n//#endregion\n//#region src/error/index.ts\n/** @deprecated Use `Experimental_DecisionUnsupportedQuestionTypeError` instead. */\nconst Experimental_EvaluationUnsupportedQuestionTypeError = Experimental_DecisionUnsupportedQuestionTypeError$1;\n//#endregion\n//#region src/logger/deprecations.ts\nconst deprecationCodes = /* @__PURE__ */ new Map([\n\t[\"generateObject\", \"AISDK_DEP_GENERATE_OBJECT\"],\n\t[\"streamObject\", \"AISDK_DEP_STREAM_OBJECT\"],\n\t[\"experimental_generateSpeech\", \"AISDK_DEP_EXPERIMENTAL_GENERATE_SPEECH\"],\n\t[\"experimental_transcribe\", \"AISDK_DEP_EXPERIMENTAL_TRANSCRIBE\"],\n\t[\"\\\"image\\\" content part\", \"AISDK_DEP_IMAGE_CONTENT_PART\"],\n\t[\"\\\"tool-result\\\" content of type \\\"file-data\\\"\", \"AISDK_DEP_TOOL_RESULT_FILE_DATA\"],\n\t[\"\\\"tool-result\\\" content of type \\\"file-url\\\"\", \"AISDK_DEP_TOOL_RESULT_FILE_URL\"],\n\t[\"\\\"tool-result\\\" content of type \\\"file-id\\\"\", \"AISDK_DEP_TOOL_RESULT_FILE_ID\"],\n\t[\"\\\"tool-result\\\" content of type \\\"file-reference\\\"\", \"AISDK_DEP_TOOL_RESULT_FILE_REFERENCE\"],\n\t[\"\\\"tool-result\\\" content of type \\\"image-data\\\"\", \"AISDK_DEP_TOOL_RESULT_IMAGE_DATA\"],\n\t[\"\\\"tool-result\\\" content of type \\\"image-url\\\"\", \"AISDK_DEP_TOOL_RESULT_IMAGE_URL\"],\n\t[\"\\\"tool-result\\\" content of type \\\"image-file-id\\\"\", \"AISDK_DEP_TOOL_RESULT_IMAGE_FILE_ID\"],\n\t[\"\\\"tool-result\\\" content of type \\\"image-file-reference\\\"\", \"AISDK_DEP_TOOL_RESULT_IMAGE_FILE_REFERENCE\"],\n\t[\"rawInput in output-error UI message parts\", \"AISDK_DEP_UI_MESSAGE_RAW_INPUT\"]\n]);\n/**\n* Escape punctuation and UTF-16 code units without losing case or collapsing\n* distinct settings. Underscores are escaped too, so `__` separates code parts.\n*/\nfunction encodeCodePart(value) {\n\treturn value.replace(/[^a-zA-Z0-9]/g, (character) => `_${character.charCodeAt(0).toString(16).toUpperCase().padStart(4, \"0\")}`);\n}\nfunction getDeprecationCode({ setting, provider }) {\n\tif (provider == null) return deprecationCodes.get(setting) ?? `AISDK_DEP_SETTING_${encodeCodePart(setting)}`;\n\treturn `AISDK_DEP_PROVIDER_${encodeCodePart(provider)}__${encodeCodePart(setting)}`;\n}\n//#endregion\n//#region src/logger/log-warnings.ts\n/**\n* Formats a warning object into a human-readable string with clear AI SDK branding.\n*\n* @param options - The options for formatting the warning.\n* @param options.warning - The warning to format.\n* @param options.provider - The provider id used for the call, if scoped to a specific provider.\n* @param options.model - The model id used for the call, if scoped to a specific provider.\n* @returns A formatted warning message string.\n*/\nfunction formatWarning({ warning, provider, model }) {\n\tconst prefix = `AI SDK Warning${provider != null && model != null ? ` (${provider} / ${model})` : \"\"}:`;\n\tswitch (warning.type) {\n\t\tcase \"unsupported\": {\n\t\t\tlet message = `${prefix} The feature \"${warning.feature}\" is not supported.`;\n\t\t\tif (warning.details) message += ` ${warning.details}`;\n\t\t\treturn message;\n\t\t}\n\t\tcase \"compatibility\": {\n\t\t\tlet message = `${prefix} The feature \"${warning.feature}\" is used in a compatibility mode.`;\n\t\t\tif (warning.details) message += ` ${warning.details}`;\n\t\t\treturn message;\n\t\t}\n\t\tcase \"deprecated\": return `${prefix} Deprecated: \"${warning.setting}\". ${warning.message}`;\n\t\tcase \"other\": return `${prefix} ${warning.message}`;\n\t\tdefault: return `${prefix} ${JSON.stringify(warning, null, 2)}`;\n\t}\n}\nconst FIRST_WARNING_INFO_MESSAGE = \"AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.\";\nlet hasLoggedBefore = false;\nconst emittedDeprecationCodes = /* @__PURE__ */ new Set();\nfunction emitWarning({ message, type, code }) {\n\tif (typeof process !== \"undefined\" && typeof process.emitWarning === \"function\") process.emitWarning(message, code == null ? { type } : {\n\t\ttype,\n\t\tcode\n\t});\n\telse console.warn(code == null ? message : `[${code}] ${message}`);\n}\n/**\n* Logs warnings to the console or uses a custom logger if configured.\n*\n* The behavior can be customized via the `AI_SDK_LOG_WARNINGS` global variable:\n* - If set to `false`, warnings are suppressed.\n* - If set to a function, that function is called with the warnings.\n* - Otherwise, warnings use `process.emitWarning` when available, falling back\n* to `console.warn`. Deprecations have stable codes and are emitted once per\n* code by the default logger. Custom loggers receive every warning.\n*\n* @param options - The options containing warnings and context.\n* @param options.warnings - The warnings to log.\n* @param options.provider - The provider id used for the call, if scoped to a specific provider.\n* @param options.model - The model id used for the call, if scoped to a specific provider.\n*/\nconst logWarnings = (options) => {\n\tif (options.warnings.length === 0) return;\n\tconst logger = globalThis.AI_SDK_LOG_WARNINGS;\n\tif (logger === false) return;\n\tif (typeof logger === \"function\") {\n\t\tlogger(options);\n\t\treturn;\n\t}\n\tif (!hasLoggedBefore) {\n\t\thasLoggedBefore = true;\n\t\temitWarning({\n\t\t\tmessage: FIRST_WARNING_INFO_MESSAGE,\n\t\t\ttype: \"Warning\"\n\t\t});\n\t}\n\tfor (const warning of options.warnings) {\n\t\tconst code = warning.type === \"deprecated\" ? getDeprecationCode({\n\t\t\tsetting: warning.setting,\n\t\t\tprovider: options.provider\n\t\t}) : void 0;\n\t\tif (code != null) {\n\t\t\tif (emittedDeprecationCodes.has(code)) continue;\n\t\t\temittedDeprecationCodes.add(code);\n\t\t}\n\t\temitWarning({\n\t\t\tmessage: formatWarning({\n\t\t\t\twarning,\n\t\t\t\tprovider: options.provider,\n\t\t\t\tmodel: options.model\n\t\t\t}),\n\t\t\ttype: warning.type === \"deprecated\" ? \"DeprecationWarning\" : \"Warning\",\n\t\t\tcode\n\t\t});\n\t}\n};\n//#endregion\n//#region src/util/log-v2-compatibility-warning.ts\nfunction logV2CompatibilityWarning({ provider, modelId }) {\n\tlogWarnings({\n\t\twarnings: [{\n\t\t\ttype: \"compatibility\",\n\t\t\tfeature: \"specificationVersion\",\n\t\t\tdetails: `Using v2 specification compatibility mode. Some features may not be available.`\n\t\t}],\n\t\tprovider,\n\t\tmodel: modelId\n\t});\n}\n//#endregion\n//#region src/model/as-embedding-model-v3.ts\nfunction asEmbeddingModelV3(model) {\n\tif (model.specificationVersion === \"v3\") return model;\n\tlogV2CompatibilityWarning({\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn new Proxy(model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v3\";\n\t\treturn target[prop];\n\t} });\n}\n//#endregion\n//#region src/model/as-embedding-model-v4.ts\nfunction asEmbeddingModelV4(model) {\n\tif (model.specificationVersion === \"v4\") return model;\n\tconst v3Model = model.specificationVersion === \"v2\" ? asEmbeddingModelV3(model) : model;\n\treturn new Proxy(v3Model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v4\";\n\t\treturn target[prop];\n\t} });\n}\n//#endregion\n//#region src/model/as-image-model-v3.ts\nfunction asImageModelV3(model) {\n\tif (model.specificationVersion === \"v3\") return model;\n\tlogV2CompatibilityWarning({\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn new Proxy(model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v3\";\n\t\treturn target[prop];\n\t} });\n}\n//#endregion\n//#region src/model/as-image-model-v4.ts\nfunction asImageModelV4(model) {\n\tif (model.specificationVersion === \"v4\") return model;\n\tconst v3Model = model.specificationVersion === \"v2\" ? asImageModelV3(model) : model;\n\treturn new Proxy(v3Model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v4\";\n\t\treturn target[prop];\n\t} });\n}\n//#endregion\n//#region src/model/as-language-model-v3.ts\nfunction asLanguageModelV3(model) {\n\tif (model.specificationVersion === \"v3\") return model;\n\tlogV2CompatibilityWarning({\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn new Proxy(model, { get(target, prop) {\n\t\tswitch (prop) {\n\t\t\tcase \"specificationVersion\": return \"v3\";\n\t\t\tcase \"doGenerate\": return async (...args) => {\n\t\t\t\tconst result = await target.doGenerate(...args);\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tfinishReason: convertV2FinishReasonToV3(result.finishReason),\n\t\t\t\t\tusage: convertV2UsageToV3(result.usage)\n\t\t\t\t};\n\t\t\t};\n\t\t\tcase \"doStream\": return async (...args) => {\n\t\t\t\tconst result = await target.doStream(...args);\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tstream: convertV2StreamToV3(result.stream)\n\t\t\t\t};\n\t\t\t};\n\t\t\tdefault: return target[prop];\n\t\t}\n\t} });\n}\nfunction convertV2StreamToV3(stream) {\n\treturn stream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\tswitch (chunk.type) {\n\t\t\tcase \"finish\":\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t...chunk,\n\t\t\t\t\tfinishReason: convertV2FinishReasonToV3(chunk.finishReason),\n\t\t\t\t\tusage: convertV2UsageToV3(chunk.usage)\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault: controller.enqueue(chunk);\n\t\t}\n\t} }));\n}\nfunction convertV2FinishReasonToV3(finishReason) {\n\treturn {\n\t\tunified: finishReason === \"unknown\" ? \"other\" : finishReason,\n\t\traw: void 0\n\t};\n}\nfunction convertV2UsageToV3(usage) {\n\treturn {\n\t\tinputTokens: {\n\t\t\ttotal: usage.inputTokens,\n\t\t\tnoCache: void 0,\n\t\t\tcacheRead: usage.cachedInputTokens,\n\t\t\tcacheWrite: void 0\n\t\t},\n\t\toutputTokens: {\n\t\t\ttotal: usage.outputTokens,\n\t\t\ttext: void 0,\n\t\t\treasoning: usage.reasoningTokens\n\t\t},\n\t\traw: usage.totalTokens == null ? void 0 : { totalTokens: usage.totalTokens }\n\t};\n}\n//#endregion\n//#region src/model/as-language-model-v4.ts\nfunction asLanguageModelV4(model) {\n\tif (model.specificationVersion === \"v4\") return model;\n\tconst v3Model = model.specificationVersion === \"v2\" ? asLanguageModelV3(model) : model;\n\treturn new Proxy(v3Model, { get(target, prop) {\n\t\tswitch (prop) {\n\t\t\tcase \"specificationVersion\": return \"v4\";\n\t\t\tcase \"doGenerate\": return async (options) => {\n\t\t\t\tconst result = await target.doGenerate({\n\t\t\t\t\t...options,\n\t\t\t\t\tprompt: convertV4PromptToV3(options.prompt)\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tcontent: result.content.map(convertV3ContentToV4)\n\t\t\t\t};\n\t\t\t};\n\t\t\tcase \"doStream\": return async (options) => {\n\t\t\t\tconst result = await target.doStream({\n\t\t\t\t\t...options,\n\t\t\t\t\tprompt: convertV4PromptToV3(options.prompt)\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tstream: convertV3StreamToV4(result.stream)\n\t\t\t\t};\n\t\t\t};\n\t\t\tdefault: return target[prop];\n\t\t}\n\t} });\n}\nfunction convertV4PromptToV3(prompt) {\n\treturn prompt.map((message) => {\n\t\tif (message.role === \"system\") return message;\n\t\treturn {\n\t\t\t...message,\n\t\t\tcontent: message.content.map((part) => {\n\t\t\t\tswitch (part.type) {\n\t\t\t\t\tcase \"file\": return {\n\t\t\t\t\t\t...part,\n\t\t\t\t\t\tdata: convertV4FileDataToV3(part.data)\n\t\t\t\t\t};\n\t\t\t\t\tcase \"tool-result\": return {\n\t\t\t\t\t\t...part,\n\t\t\t\t\t\toutput: convertV4ToolResultOutputToV3(part.output)\n\t\t\t\t\t};\n\t\t\t\t\tdefault: return part;\n\t\t\t\t}\n\t\t\t})\n\t\t};\n\t});\n}\nfunction convertV4FileDataToV3(data) {\n\tswitch (data.type) {\n\t\tcase \"data\": return data.data;\n\t\tcase \"url\": return data.url;\n\t\tcase \"reference\":\n\t\tcase \"text\": return data;\n\t}\n}\nfunction convertV4ToolResultOutputToV3(output) {\n\tif (output.type !== \"content\") return output;\n\treturn {\n\t\t...output,\n\t\tvalue: output.value.map((part) => {\n\t\t\tif (part.type !== \"file\") return part;\n\t\t\tswitch (part.data.type) {\n\t\t\t\tcase \"data\": return {\n\t\t\t\t\ttype: \"file-data\",\n\t\t\t\t\tdata: typeof part.data.data === \"string\" ? part.data.data : convertUint8ArrayToBase64(part.data.data),\n\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t\t};\n\t\t\t\tcase \"url\": return {\n\t\t\t\t\ttype: \"file-url\",\n\t\t\t\t\turl: part.data.url.toString(),\n\t\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t\t};\n\t\t\t\tcase \"reference\": return {\n\t\t\t\t\ttype: \"file-id\",\n\t\t\t\t\tfileId: part.data.reference,\n\t\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t\t};\n\t\t\t\tcase \"text\": return part;\n\t\t\t}\n\t\t})\n\t};\n}\nfunction convertV3ContentToV4(content) {\n\treturn content.type === \"file\" ? {\n\t\t...content,\n\t\tdata: {\n\t\t\ttype: \"data\",\n\t\t\tdata: content.data\n\t\t}\n\t} : content;\n}\nfunction convertV3StreamToV4(stream) {\n\treturn stream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\tcontroller.enqueue(chunk.type === \"file\" ? {\n\t\t\t...chunk,\n\t\t\tdata: {\n\t\t\t\ttype: \"data\",\n\t\t\t\tdata: chunk.data\n\t\t\t}\n\t\t} : chunk);\n\t} }));\n}\n//#endregion\n//#region src/model/as-reranking-model-v4.ts\nfunction asRerankingModelV4(model) {\n\tif (model.specificationVersion === \"v4\") return model;\n\treturn new Proxy(model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v4\";\n\t\treturn target[prop];\n\t} });\n}\n//#endregion\n//#region src/model/as-speech-model-v3.ts\nfunction asSpeechModelV3(model) {\n\tif (model.specificationVersion === \"v3\") return model;\n\tlogV2CompatibilityWarning({\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn new Proxy(model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v3\";\n\t\treturn target[prop];\n\t} });\n}\n//#endregion\n//#region src/model/as-speech-model-v4.ts\nfunction asSpeechModelV4(model) {\n\tif (model.specificationVersion === \"v4\") return model;\n\tconst v3Model = model.specificationVersion === \"v2\" ? asSpeechModelV3(model) : model;\n\treturn new Proxy(v3Model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v4\";\n\t\treturn target[prop];\n\t} });\n}\n//#endregion\n//#region src/model/as-transcription-model-v3.ts\nfunction asTranscriptionModelV3(model) {\n\tif (model.specificationVersion === \"v3\") return model;\n\tlogV2CompatibilityWarning({\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn new Proxy(model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v3\";\n\t\treturn target[prop];\n\t} });\n}\n//#endregion\n//#region src/model/as-transcription-model-v4.ts\nfunction asTranscriptionModelV4(model) {\n\tif (model.specificationVersion === \"v4\") return model;\n\tconst v3Model = model.specificationVersion === \"v2\" ? asTranscriptionModelV3(model) : model;\n\treturn new Proxy(v3Model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v4\";\n\t\treturn target[prop];\n\t} });\n}\n//#endregion\n//#region src/model/as-video-model-v4.ts\nfunction asVideoModelV4(model) {\n\tif (model.specificationVersion === \"v4\") return model;\n\treturn new Proxy(model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v4\";\n\t\treturn target[prop];\n\t} });\n}\n//#endregion\n//#region src/model/as-provider-v3.ts\nfunction asProviderV3(provider) {\n\tif (\"specificationVersion\" in provider && provider.specificationVersion === \"v3\") return provider;\n\tconst v2Provider = provider;\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\tlanguageModel: (modelId) => asLanguageModelV3(v2Provider.languageModel(modelId)),\n\t\tembeddingModel: (modelId) => asEmbeddingModelV3(v2Provider.textEmbeddingModel(modelId)),\n\t\timageModel: (modelId) => asImageModelV3(v2Provider.imageModel(modelId)),\n\t\ttranscriptionModel: v2Provider.transcriptionModel ? (modelId) => asTranscriptionModelV3(v2Provider.transcriptionModel(modelId)) : void 0,\n\t\tspeechModel: v2Provider.speechModel ? (modelId) => asSpeechModelV3(v2Provider.speechModel(modelId)) : void 0,\n\t\trerankingModel: void 0\n\t};\n}\n//#endregion\n//#region src/model/as-provider-v4.ts\nfunction asProviderV4(provider) {\n\tif (\"specificationVersion\" in provider && provider.specificationVersion === \"v4\") return provider;\n\tconst v3Provider = !(\"specificationVersion\" in provider) || provider.specificationVersion !== \"v3\" ? asProviderV3(provider) : provider;\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\tlanguageModel: (modelId) => asLanguageModelV4(v3Provider.languageModel(modelId)),\n\t\tembeddingModel: (modelId) => asEmbeddingModelV4(v3Provider.embeddingModel(modelId)),\n\t\timageModel: (modelId) => asImageModelV4(v3Provider.imageModel(modelId)),\n\t\ttranscriptionModel: v3Provider.transcriptionModel ? (modelId) => asTranscriptionModelV4(v3Provider.transcriptionModel(modelId)) : void 0,\n\t\tspeechModel: v3Provider.speechModel ? (modelId) => asSpeechModelV4(v3Provider.speechModel(modelId)) : void 0,\n\t\trerankingModel: v3Provider.rerankingModel ? (modelId) => asRerankingModelV4(v3Provider.rerankingModel(modelId)) : void 0\n\t};\n}\n//#endregion\n//#region src/model/resolve-model.ts\nfunction resolveLanguageModel(model) {\n\tif (typeof model === \"string\") return getGlobalProvider().languageModel(model);\n\tif (![\n\t\t\"v4\",\n\t\t\"v3\",\n\t\t\"v2\"\n\t].includes(model.specificationVersion)) {\n\t\tconst unsupportedModel = model;\n\t\tthrow new UnsupportedModelVersionError({\n\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\tprovider: unsupportedModel.provider,\n\t\t\tmodelId: unsupportedModel.modelId\n\t\t});\n\t}\n\treturn asLanguageModelV4(model);\n}\nfunction resolveEmbeddingModel(model) {\n\tif (typeof model === \"string\") return getGlobalProvider().embeddingModel(model);\n\tif (![\n\t\t\"v4\",\n\t\t\"v3\",\n\t\t\"v2\"\n\t].includes(model.specificationVersion)) {\n\t\tconst unsupportedModel = model;\n\t\tthrow new UnsupportedModelVersionError({\n\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\tprovider: unsupportedModel.provider,\n\t\t\tmodelId: unsupportedModel.modelId\n\t\t});\n\t}\n\treturn asEmbeddingModelV4(model);\n}\nfunction resolveTranscriptionModel(model) {\n\tif (typeof model === \"string\") return getGlobalProvider().transcriptionModel?.(model);\n\tif (![\n\t\t\"v4\",\n\t\t\"v3\",\n\t\t\"v2\"\n\t].includes(model.specificationVersion)) {\n\t\tconst unsupportedModel = model;\n\t\tthrow new UnsupportedModelVersionError({\n\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\tprovider: unsupportedModel.provider,\n\t\t\tmodelId: unsupportedModel.modelId\n\t\t});\n\t}\n\treturn asTranscriptionModelV4(model);\n}\nfunction resolveSpeechTranslationModel(model) {\n\tif (typeof model === \"string\") {\n\t\tconst speechTranslationModel = (globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway$1).speechTranslationModel;\n\t\tif (!speechTranslationModel) throw new Error(\"The default provider does not support speech translation models. Please pass a provider model instance that implements the experimental speech translation model specification.\");\n\t\treturn speechTranslationModel(model);\n\t}\n\tif (model.specificationVersion !== \"v4\") {\n\t\tconst unsupportedModel = model;\n\t\tthrow new UnsupportedModelVersionError({\n\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\tprovider: unsupportedModel.provider,\n\t\t\tmodelId: unsupportedModel.modelId\n\t\t});\n\t}\n\treturn model;\n}\nfunction resolveSpeechModel(model) {\n\tif (typeof model === \"string\") return getGlobalProvider().speechModel?.(model);\n\tif (![\n\t\t\"v4\",\n\t\t\"v3\",\n\t\t\"v2\"\n\t].includes(model.specificationVersion)) {\n\t\tconst unsupportedModel = model;\n\t\tthrow new UnsupportedModelVersionError({\n\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\tprovider: unsupportedModel.provider,\n\t\t\tmodelId: unsupportedModel.modelId\n\t\t});\n\t}\n\treturn asSpeechModelV4(model);\n}\nfunction resolveImageModel(model) {\n\tif (typeof model === \"string\") return getGlobalProvider().imageModel(model);\n\tif (![\n\t\t\"v4\",\n\t\t\"v3\",\n\t\t\"v2\"\n\t].includes(model.specificationVersion)) {\n\t\tconst unsupportedModel = model;\n\t\tthrow new UnsupportedModelVersionError({\n\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\tprovider: unsupportedModel.provider,\n\t\t\tmodelId: unsupportedModel.modelId\n\t\t});\n\t}\n\treturn asImageModelV4(model);\n}\nfunction resolveVideoModel(model) {\n\tif (typeof model === \"string\") {\n\t\tconst videoModel = (globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway$1).videoModel;\n\t\tif (!videoModel) throw new Error(\"The default provider does not support video models. Please use a Experimental_VideoModelV4 object from a provider (e.g., vertex.video(\\\"model-id\\\")).\");\n\t\treturn videoModel(model);\n\t}\n\tif (![\"v4\", \"v3\"].includes(model.specificationVersion)) {\n\t\tconst unsupportedModel = model;\n\t\tthrow new UnsupportedModelVersionError({\n\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\tprovider: unsupportedModel.provider,\n\t\t\tmodelId: unsupportedModel.modelId\n\t\t});\n\t}\n\treturn asVideoModelV4(model);\n}\nfunction resolveRerankingModel(model) {\n\tif (typeof model === \"string\") {\n\t\tconst rerankingModel = getGlobalProvider().rerankingModel;\n\t\tif (!rerankingModel) throw new Error(\"The default provider does not support reranking models. Please use a RerankingModel object from a provider (e.g., gateway.rerankingModel(\\\"model-id\\\")).\");\n\t\treturn rerankingModel(model);\n\t}\n\tif (model.specificationVersion !== \"v4\" && model.specificationVersion !== \"v3\") {\n\t\tconst unsupportedModel = model;\n\t\tthrow new UnsupportedModelVersionError({\n\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\tprovider: unsupportedModel.provider,\n\t\t\tmodelId: unsupportedModel.modelId\n\t\t});\n\t}\n\treturn asRerankingModelV4(model);\n}\nfunction resolveDecisionModel(model) {\n\tif (typeof model === \"string\") {\n\t\tconst provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway$1;\n\t\tconst factory = provider.decisionModel ?? provider.evaluationModel;\n\t\tif (typeof factory !== \"function\") throw new NoSuchModelError$1({\n\t\t\tmodelId: model,\n\t\t\tmodelType: \"decisionModel\",\n\t\t\tmessage: \"The default provider does not support decision models. Pass a decision model instance or configure AI_SDK_DEFAULT_PROVIDER with a decisionModel method.\"\n\t\t});\n\t\tconst resolvedModel = factory.call(provider, model);\n\t\tif (resolvedModel == null) throw new NoSuchModelError$1({\n\t\t\tmodelId: model,\n\t\t\tmodelType: \"decisionModel\"\n\t\t});\n\t\tmodel = resolvedModel;\n\t}\n\tif (model.specificationVersion !== \"v4\") throw new UnsupportedModelVersionError({\n\t\tversion: model.specificationVersion,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\tif (\"doDecide\" in model) return model;\n\tconst legacyModel = model;\n\treturn {\n\t\tspecificationVersion: legacyModel.specificationVersion,\n\t\tprovider: legacyModel.provider,\n\t\tmodelId: legacyModel.modelId,\n\t\tsupportedQuestionTypes: legacyModel.supportedQuestionTypes,\n\t\tdoDecide: (options) => legacyModel.doEvaluate(options)\n\t};\n}\nfunction getGlobalProvider() {\n\treturn asProviderV4(globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway$1);\n}\n/** Internal adapter for deprecated provider factories. */\nfunction asEvaluationModel(model) {\n\tif (\"doEvaluate\" in model && typeof model.doEvaluate === \"function\") return model;\n\treturn {\n\t\tspecificationVersion: model.specificationVersion,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId,\n\t\tsupportedQuestionTypes: model.supportedQuestionTypes,\n\t\tdoDecide: (options) => model.doDecide(options),\n\t\tdoEvaluate: (options) => model.doDecide(options)\n\t};\n}\n//#endregion\n//#region src/prompt/clone-model-message.ts\n/**\n* Clone model messages while preserving URL instances. Node's structuredClone\n* currently rejects URL objects, which are valid file/image prompt payloads.\n*/\nfunction cloneModelMessages(messages) {\n\treturn messages.map((message) => cloneValue(message));\n}\nfunction cloneValue(value) {\n\tif (value instanceof URL) return new URL(value.href);\n\tif (Array.isArray(value)) return value.map((item) => cloneValue(item));\n\tif (value instanceof Uint8Array) return new Uint8Array(value);\n\tif (value instanceof ArrayBuffer) return value.slice(0);\n\tif (value instanceof Date) return new Date(value);\n\tif (value != null && typeof value === \"object\") return Object.fromEntries(Object.entries(value).map(([key, value]) => [key, cloneValue(value)]));\n\treturn value;\n}\n//#endregion\n//#region src/version.ts\nconst VERSION = \"7.0.137\";\n//#endregion\n//#region src/util/download/download.ts\n/**\n* Download a file from a URL.\n*\n* @param url - The URL to download from.\n* @param maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.\n* @param abortSignal - An optional abort signal to cancel the download.\n* @returns The downloaded data and media type.\n*\n* @throws DownloadError if the download fails or exceeds maxBytes.\n*/\nconst download = async ({ url, maxBytes, abortSignal }) => {\n\tconst urlText = url.toString();\n\ttry {\n\t\tconst headers = withUserAgentSuffix({}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent());\n\t\tconst response = await fetchUntrustedUrl({\n\t\t\turl: urlText,\n\t\t\theaders,\n\t\t\tabortSignal\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tawait cancelResponseBody(response);\n\t\t\tthrow new DownloadError$1({\n\t\t\t\turl: urlText,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tstatusText: response.statusText\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tdata: await readResponseWithSizeLimit({\n\t\t\t\tresponse,\n\t\t\t\turl: urlText,\n\t\t\t\tmaxBytes: maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE\n\t\t\t}),\n\t\t\tmediaType: response.headers.get(\"content-type\") ?? void 0\n\t\t};\n\t} catch (error) {\n\t\tif (DownloadError$1.isInstance(error)) throw error;\n\t\tthrow new DownloadError$1({\n\t\t\turl: urlText,\n\t\t\tcause: error\n\t\t});\n\t}\n};\n//#endregion\n//#region src/util/download/download-function.ts\n/**\n* Default download function.\n* Downloads the file if it is not supported by the model.\n*/\nconst createDefaultDownloadFunction = (download$1 = download, abortSignal) => (requestedDownloads) => Promise.all(requestedDownloads.map(async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : await download$1({\n\t...requestedDownload,\n\tabortSignal\n})));\n//#endregion\n//#region src/util/merge-objects.ts\n/**\n* Deeply merges two objects together.\n* - Properties from the `overrides` object override those in the `base` object with the same key.\n* - For nested objects, the merge is performed recursively (deep merge).\n* - Arrays are replaced, not merged.\n* - Primitive values are replaced.\n* - If both `base` and `overrides` are undefined, returns undefined.\n* - If one of `base` or `overrides` is undefined, returns the other.\n*\n* @param base The target object to merge into\n* @param overrides The source object to merge from\n* @returns A new object with the merged properties, or undefined if both inputs are undefined\n*/\nfunction mergeObjects(base, overrides) {\n\tif (base === void 0 && overrides === void 0) return;\n\tif (base === void 0) return overrides;\n\tif (overrides === void 0) return base;\n\tconst result = { ...base };\n\tfor (const key in overrides) {\n\t\tif (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n\t\tif (Object.prototype.hasOwnProperty.call(overrides, key)) {\n\t\t\tconst overridesValue = overrides[key];\n\t\t\tif (overridesValue === void 0) continue;\n\t\t\tconst baseValue = key in base ? base[key] : void 0;\n\t\t\tconst isSourceObject = overridesValue !== null && typeof overridesValue === \"object\" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);\n\t\t\tconst isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === \"object\" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);\n\t\t\tif (isSourceObject && isTargetObject) result[key] = mergeObjects(baseValue, overridesValue);\n\t\t\telse result[key] = overridesValue;\n\t\t}\n\t}\n\treturn result;\n}\n//#endregion\n//#region src/prompt/split-data-url.ts\nfunction splitDataUrl(dataUrl) {\n\ttry {\n\t\tconst [header, base64Content] = dataUrl.split(\",\");\n\t\treturn {\n\t\t\tmediaType: header.split(\";\")[0].split(\":\")[1],\n\t\t\tbase64Content\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tmediaType: void 0,\n\t\t\tbase64Content: void 0\n\t\t};\n\t}\n}\n//#endregion\n//#region src/prompt/file-part-data.ts\nfunction isTaggedFileData(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst type = value.type;\n\treturn type === \"data\" || type === \"url\" || type === \"reference\" || type === \"text\";\n}\nfunction convertUrlToFilePartData(url, originalUrl) {\n\tif (url.protocol === \"data:\") {\n\t\tconst { mediaType, base64Content } = splitDataUrl(url.toString());\n\t\tif (mediaType == null || base64Content == null) throw new InvalidDataContentError({\n\t\t\tcontent: url,\n\t\t\tmessage: `Invalid data URL format in content ${url.toString()}`\n\t\t});\n\t\treturn {\n\t\t\tdata: {\n\t\t\t\ttype: \"data\",\n\t\t\t\tdata: base64Content\n\t\t\t},\n\t\t\tmediaType\n\t\t};\n\t}\n\treturn {\n\t\tdata: {\n\t\t\ttype: \"url\",\n\t\t\turl,\n\t\t\t...originalUrl != null ? { originalUrl } : {}\n\t\t},\n\t\tmediaType: void 0\n\t};\n}\nfunction convertUrlStringToFilePartData(content) {\n\tconst result = convertUrlToFilePartData(new URL(content));\n\tif (result.data.type === \"url\" && result.data.url.toString() !== content) result.data.originalUrl = content;\n\treturn result;\n}\nfunction convertInlineDataToFilePartData(content) {\n\tif (content instanceof Uint8Array) return {\n\t\tdata: {\n\t\t\ttype: \"data\",\n\t\t\tdata: content\n\t\t},\n\t\tmediaType: void 0\n\t};\n\tif (content instanceof ArrayBuffer) return {\n\t\tdata: {\n\t\t\ttype: \"data\",\n\t\t\tdata: new Uint8Array(content)\n\t\t},\n\t\tmediaType: void 0\n\t};\n\tif (isBuffer(content)) return {\n\t\tdata: {\n\t\t\ttype: \"data\",\n\t\t\tdata: new Uint8Array(content)\n\t\t},\n\t\tmediaType: void 0\n\t};\n\treturn {\n\t\tdata: {\n\t\t\ttype: \"data\",\n\t\t\tdata: content\n\t\t},\n\t\tmediaType: void 0\n\t};\n}\n/**\n* Converts any legacy-or-tagged top-level `FilePart.data` /\n* `ReasoningFilePart.data` value into the tagged v4 provider prompt shape.\n*\n* Returns the tagged `data` together with the resolved mediaType (extracted\n* from a `data:` URL when applicable).\n*/\nfunction convertToLanguageModelV4FilePart(content) {\n\tif (isTaggedFileData(content)) switch (content.type) {\n\t\tcase \"data\":\n\t\t\tif (typeof content.data === \"string\" && content.data.startsWith(\"data:\")) throw new InvalidDataContentError({\n\t\t\t\tcontent: content.data,\n\t\t\t\tmessage: \"Data URLs are not valid inline data. Pass them as { type: \\\"url\\\", url } instead.\"\n\t\t\t});\n\t\t\treturn convertInlineDataToFilePartData(content.data);\n\t\tcase \"url\": return convertUrlToFilePartData(content.url, content.originalUrl);\n\t\tcase \"reference\": return {\n\t\t\tdata: {\n\t\t\t\ttype: \"reference\",\n\t\t\t\treference: content.reference\n\t\t\t},\n\t\t\tmediaType: void 0\n\t\t};\n\t\tcase \"text\": return {\n\t\t\tdata: {\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: content.text\n\t\t\t},\n\t\t\tmediaType: void 0\n\t\t};\n\t}\n\tif (content instanceof URL) return convertUrlToFilePartData(content);\n\tif (typeof content === \"string\") try {\n\t\treturn convertUrlStringToFilePartData(content);\n\t} catch {\n\t\treturn convertInlineDataToFilePartData(content);\n\t}\n\tif (isProviderReference(content)) return {\n\t\tdata: {\n\t\t\ttype: \"reference\",\n\t\t\treference: content\n\t\t},\n\t\tmediaType: void 0\n\t};\n\treturn convertInlineDataToFilePartData(content);\n}\n//#endregion\n//#region src/prompt/convert-to-language-model-prompt.ts\nasync function convertToLanguageModelPrompt({ prompt, supportedUrls, download, abortSignal, provider }) {\n\tconst downloadedAssets = await downloadAssets(prompt.messages, download ?? createDefaultDownloadFunction(void 0, abortSignal), supportedUrls);\n\tconst approvalIdToToolCallId = /* @__PURE__ */ new Map();\n\tfor (const message of prompt.messages) if (message.role === \"assistant\" && Array.isArray(message.content)) {\n\t\tfor (const part of message.content) if (part.type === \"tool-approval-request\" && \"approvalId\" in part && \"toolCallId\" in part) approvalIdToToolCallId.set(part.approvalId, part.toolCallId);\n\t}\n\tconst approvedToolCallIds = /* @__PURE__ */ new Set();\n\tfor (const message of prompt.messages) if (message.role === \"tool\") {\n\t\tfor (const part of message.content) if (part.type === \"tool-approval-response\") {\n\t\t\tconst toolCallId = approvalIdToToolCallId.get(part.approvalId);\n\t\t\tif (toolCallId) approvedToolCallIds.add(toolCallId);\n\t\t}\n\t}\n\tconst messages = [...prompt.instructions != null ? typeof prompt.instructions === \"string\" ? [{\n\t\trole: \"system\",\n\t\tcontent: prompt.instructions\n\t}] : asArray(prompt.instructions).map((message) => ({\n\t\trole: \"system\",\n\t\tcontent: message.content,\n\t\tproviderOptions: message.providerOptions\n\t})) : [], ...prompt.messages.map((message) => convertToLanguageModelMessage({\n\t\tmessage,\n\t\tdownloadedAssets,\n\t\tprovider\n\t}))];\n\tconst combinedMessages = [];\n\tfor (const message of messages) {\n\t\tif (message.role !== \"tool\") {\n\t\t\tcombinedMessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tconst lastCombinedMessage = combinedMessages.at(-1);\n\t\tif (lastCombinedMessage?.role === \"tool\") {\n\t\t\tconst lastContentPart = lastCombinedMessage.content.at(-1);\n\t\t\tif (lastContentPart != null && lastCombinedMessage.providerOptions != null) lastContentPart.providerOptions = mergeObjects(lastCombinedMessage.providerOptions, lastContentPart.providerOptions);\n\t\t\tlastCombinedMessage.content.push(...message.content);\n\t\t\tlastCombinedMessage.providerOptions = lastContentPart == null ? mergeObjects(lastCombinedMessage.providerOptions, message.providerOptions) : message.providerOptions;\n\t\t} else combinedMessages.push(message);\n\t}\n\tconst toolCallIds = /* @__PURE__ */ new Set();\n\tfor (const message of combinedMessages) switch (message.role) {\n\t\tcase \"assistant\":\n\t\t\tfor (const content of message.content) if (content.type === \"tool-call\" && !content.providerExecuted) toolCallIds.add(content.toolCallId);\n\t\t\tbreak;\n\t\tcase \"tool\":\n\t\t\tfor (const content of message.content) if (content.type === \"tool-result\") toolCallIds.delete(content.toolCallId);\n\t\t\tbreak;\n\t\tcase \"user\":\n\t\tcase \"system\":\n\t\t\tfor (const id of approvedToolCallIds) toolCallIds.delete(id);\n\t\t\tif (toolCallIds.size > 0) throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n\t}\n\tfor (const id of approvedToolCallIds) toolCallIds.delete(id);\n\tif (toolCallIds.size > 0) throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n\treturn combinedMessages.filter((message) => message.role !== \"tool\" || message.content.length > 0);\n}\n/**\n* Convert a ModelMessage to a LanguageModelV4Message.\n*\n* @param message - The ModelMessage to convert.\n* @param downloadedAssets - A map of URLs to their downloaded data. Only\n* available if the model does not support URLs, null otherwise.\n*/\nfunction convertToLanguageModelMessage({ message, downloadedAssets, provider }) {\n\tconst warnings = [];\n\tconst role = message.role;\n\tswitch (role) {\n\t\tcase \"system\": return {\n\t\t\trole: \"system\",\n\t\t\tcontent: message.content,\n\t\t\tproviderOptions: message.providerOptions\n\t\t};\n\t\tcase \"user\": {\n\t\t\tif (typeof message.content === \"string\") return {\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: message.content\n\t\t\t\t}],\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\tconst converted = {\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: message.content.map((part) => {\n\t\t\t\t\tif (part.type === \"image\") warnings.push({\n\t\t\t\t\t\ttype: \"deprecated\",\n\t\t\t\t\t\tsetting: \"\\\"image\\\" content part\",\n\t\t\t\t\t\tmessage: `The \"image\" content part type is deprecated. Use a \"file\" part with mediaType: 'image' (or a more specific image/* subtype) instead.`\n\t\t\t\t\t});\n\t\t\t\t\treturn convertImagePartToFilePart(part);\n\t\t\t\t}).map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== \"text\" || part.text !== \"\"),\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\tif (warnings.length > 0) logWarnings({ warnings });\n\t\t\treturn converted;\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tif (typeof message.content === \"string\") return {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: message.content\n\t\t\t\t}],\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\tconst converted = {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: message.content.filter((part) => part.type !== \"text\" || part.text !== \"\" || part.providerOptions != null).filter((part) => part.type !== \"tool-approval-request\").map((part) => {\n\t\t\t\t\tconst providerOptions = part.providerOptions;\n\t\t\t\t\tswitch (part.type) {\n\t\t\t\t\t\tcase \"custom\": return {\n\t\t\t\t\t\t\ttype: \"custom\",\n\t\t\t\t\t\t\tkind: part.kind,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"file\": {\n\t\t\t\t\t\t\tconst { data, mediaType } = convertToLanguageModelV4FilePart(part.data);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\t\t\tmediaType: mediaType ?? part.mediaType,\n\t\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"reasoning\": return {\n\t\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"reasoning-file\": {\n\t\t\t\t\t\t\tconst { data, mediaType } = convertToLanguageModelV4FilePart(part.data);\n\t\t\t\t\t\t\tif (data.type !== \"data\" && data.type !== \"url\") throw new Error(`Unsupported reasoning-file data type: ${data.type}`);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\ttype: \"reasoning-file\",\n\t\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\t\tmediaType: mediaType ?? part.mediaType,\n\t\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"text\": return {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"tool-call\": return {\n\t\t\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"tool-result\": return {\n\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\toutput: mapToolResultOutput({\n\t\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\t\tprovider,\n\t\t\t\t\t\t\t\twarnings,\n\t\t\t\t\t\t\t\tdownloadedAssets\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\tif (warnings.length > 0) logWarnings({ warnings });\n\t\t\treturn converted;\n\t\t}\n\t\tcase \"tool\": {\n\t\t\tconst converted = {\n\t\t\t\trole: \"tool\",\n\t\t\t\tcontent: message.content.filter((part) => part.type !== \"tool-approval-response\" || part.providerExecuted).map((part) => {\n\t\t\t\t\tswitch (part.type) {\n\t\t\t\t\t\tcase \"tool-result\": return {\n\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\toutput: mapToolResultOutput({\n\t\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\t\tprovider,\n\t\t\t\t\t\t\t\twarnings,\n\t\t\t\t\t\t\t\tdownloadedAssets\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"tool-approval-response\": return {\n\t\t\t\t\t\t\ttype: \"tool-approval-response\",\n\t\t\t\t\t\t\tapprovalId: part.approvalId,\n\t\t\t\t\t\t\tapproved: part.approved,\n\t\t\t\t\t\t\treason: part.reason\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\tif (warnings.length > 0) logWarnings({ warnings });\n\t\t\treturn converted;\n\t\t}\n\t\tdefault: throw new InvalidMessageRoleError({ role });\n\t}\n}\nfunction convertImagePartToFilePart(part) {\n\tif (part.type !== \"image\") return part;\n\treturn {\n\t\ttype: \"file\",\n\t\tdata: part.image,\n\t\tmediaType: part.mediaType ?? \"image\",\n\t\tproviderOptions: part.providerOptions\n\t};\n}\n/**\n* Downloads files from URLs in the user messages.\n*/\nasync function downloadAssets(messages, download, supportedUrls) {\n\tconst downloadableFiles = [];\n\tfor (const message of messages) {\n\t\tif (message.role === \"user\" && Array.isArray(message.content)) for (const part of message.content) {\n\t\t\tconst filePart = convertImagePartToFilePart(part);\n\t\t\tif (filePart.type === \"file\") downloadableFiles.push(filePart);\n\t\t}\n\t\tif (message.role === \"tool\") for (const part of message.content) {\n\t\t\tif (part.type !== \"tool-result\") continue;\n\t\t\tif (part.output.type !== \"content\") continue;\n\t\t\tfor (const contentPart of part.output.value) if (contentPart.type === \"file\") downloadableFiles.push(contentPart);\n\t\t}\n\t\tif (message.role === \"assistant\" && Array.isArray(message.content)) for (const part of message.content) {\n\t\t\tif (part.type !== \"tool-result\") continue;\n\t\t\tif (part.output.type !== \"content\") continue;\n\t\t\tfor (const contentPart of part.output.value) if (contentPart.type === \"file\") downloadableFiles.push(contentPart);\n\t\t}\n\t}\n\tconst plannedDownloads = downloadableFiles.map((part) => {\n\t\tconst mediaType = part.mediaType;\n\t\tconst { data } = convertToLanguageModelV4FilePart(part.data);\n\t\treturn {\n\t\t\tmediaType,\n\t\t\tdata\n\t\t};\n\t}).filter((part) => part.data.type === \"url\").map((part) => ({\n\t\turl: part.data.url,\n\t\tisUrlSupportedByModel: part.mediaType != null && isUrlSupported({\n\t\t\turl: part.data.url.toString(),\n\t\t\tmediaType: part.mediaType,\n\t\t\tsupportedUrls\n\t\t})\n\t}));\n\tconst downloadedFiles = await download(plannedDownloads);\n\treturn Object.fromEntries(downloadedFiles.map((file, index) => file == null ? null : [plannedDownloads[index].url.toString(), {\n\t\tdata: file.data,\n\t\tmediaType: file.mediaType\n\t}]).filter((file) => file != null));\n}\n/**\n* Convert part of a user message to a LanguageModelV4Part.\n*\n* @param part - The part to convert.\n* @param downloadedAssets - A map of URLs to their downloaded data. Only\n* available if the model does not support URLs, null otherwise.\n* @returns The converted part.\n*/\nfunction convertPartToLanguageModelPart(part, downloadedAssets) {\n\tif (part.type === \"text\") return {\n\t\ttype: \"text\",\n\t\ttext: part.text,\n\t\tproviderOptions: part.providerOptions\n\t};\n\tconst { data: normalizedData, mediaType: dataUrlMediaType } = convertToLanguageModelV4FilePart(part.data);\n\tlet mediaType = dataUrlMediaType ?? part.mediaType;\n\tlet data = normalizedData;\n\tif (data.type === \"url\") {\n\t\tconst downloadedFile = downloadedAssets[data.url.toString()];\n\t\tif (downloadedFile) {\n\t\t\tdata = {\n\t\t\t\ttype: \"data\",\n\t\t\t\tdata: downloadedFile.data\n\t\t\t};\n\t\t\tif (downloadedFile.mediaType != null && (mediaType == null || !isFullMediaType(mediaType))) mediaType = downloadedFile.mediaType;\n\t\t}\n\t}\n\tif (data.type === \"data\" && (data.data instanceof Uint8Array || typeof data.data === \"string\")) {\n\t\tconst imageMediaType = detectMediaType({\n\t\t\tdata: data.data,\n\t\t\ttopLevelType: \"image\"\n\t\t});\n\t\tif (imageMediaType != null) mediaType = imageMediaType;\n\t}\n\tif (mediaType == null) throw new Error(`Media type is missing for file part`);\n\treturn {\n\t\ttype: \"file\",\n\t\tmediaType,\n\t\tfilename: part.filename,\n\t\tdata,\n\t\tproviderOptions: part.providerOptions\n\t};\n}\nfunction mapToolResultOutput({ output, provider, warnings = [], downloadedAssets }) {\n\tif (output.type !== \"content\") return output;\n\treturn {\n\t\ttype: \"content\",\n\t\tvalue: output.value.map((item) => {\n\t\t\tswitch (item.type) {\n\t\t\t\tcase \"file\": {\n\t\t\t\t\tconst convertedPart = convertPartToLanguageModelPart(item, downloadedAssets);\n\t\t\t\t\tif (convertedPart.type !== \"file\") throw new Error(\"Expected tool result file content to convert to file.\");\n\t\t\t\t\treturn convertedPart;\n\t\t\t\t}\n\t\t\t\tcase \"file-data\":\n\t\t\t\t\twarnings.push({\n\t\t\t\t\t\ttype: \"deprecated\",\n\t\t\t\t\t\tsetting: \"\\\"tool-result\\\" content of type \\\"file-data\\\"\",\n\t\t\t\t\t\tmessage: `The \"file-data\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'data', data } instead.`\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\ttype: \"data\",\n\t\t\t\t\t\t\tdata: item.data\n\t\t\t\t\t\t},\n\t\t\t\t\t\tfilename: item.filename,\n\t\t\t\t\t\tmediaType: item.mediaType,\n\t\t\t\t\t\tproviderOptions: item.providerOptions\n\t\t\t\t\t};\n\t\t\t\tcase \"file-url\": {\n\t\t\t\t\tconst mediaType = item.mediaType ?? getMediaTypeFromUrl(item.url);\n\t\t\t\t\tconst url = new URL(item.url);\n\t\t\t\t\tlet message = `The \"file-url\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'url', url } instead.`;\n\t\t\t\t\tif (!item.mediaType) {\n\t\t\t\t\t\tconst inferenceSuffix = mediaType === \"application/octet-stream\" ? `Unable to infer media type from URL. Defaulting to 'application/octet-stream'.` : `Inferred media type '${mediaType}' from URL.`;\n\t\t\t\t\t\tmessage = `The \"file-url\" tool result content part with URL \"${item.url}\" is missing a \"mediaType\". ${inferenceSuffix} ${message}`;\n\t\t\t\t\t}\n\t\t\t\t\twarnings.push({\n\t\t\t\t\t\ttype: \"deprecated\",\n\t\t\t\t\t\tsetting: \"\\\"tool-result\\\" content of type \\\"file-url\\\"\",\n\t\t\t\t\t\tmessage\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\ttype: \"url\",\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\t...url.toString() !== item.url ? { originalUrl: item.url } : {}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmediaType,\n\t\t\t\t\t\tproviderOptions: item.providerOptions\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcase \"file-id\":\n\t\t\t\t\twarnings.push({\n\t\t\t\t\t\ttype: \"deprecated\",\n\t\t\t\t\t\tsetting: \"\\\"tool-result\\\" content of type \\\"file-id\\\"\",\n\t\t\t\t\t\tmessage: `The \"file-id\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\ttype: \"reference\",\n\t\t\t\t\t\t\treference: convertFileIdToProviderReference({\n\t\t\t\t\t\t\t\tfileId: item.fileId,\n\t\t\t\t\t\t\t\tprovider\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmediaType: \"application\",\n\t\t\t\t\t\tproviderOptions: item.providerOptions\n\t\t\t\t\t};\n\t\t\t\tcase \"file-reference\":\n\t\t\t\t\twarnings.push({\n\t\t\t\t\t\ttype: \"deprecated\",\n\t\t\t\t\t\tsetting: \"\\\"tool-result\\\" content of type \\\"file-reference\\\"\",\n\t\t\t\t\t\tmessage: `The \"file-reference\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\ttype: \"reference\",\n\t\t\t\t\t\t\treference: item.providerReference\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmediaType: \"application\",\n\t\t\t\t\t\tproviderOptions: item.providerOptions\n\t\t\t\t\t};\n\t\t\t\tcase \"image-data\":\n\t\t\t\t\twarnings.push({\n\t\t\t\t\t\ttype: \"deprecated\",\n\t\t\t\t\t\tsetting: \"\\\"tool-result\\\" content of type \\\"image-data\\\"\",\n\t\t\t\t\t\tmessage: `The \"image-data\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'data', data } instead.`\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\ttype: \"data\",\n\t\t\t\t\t\t\tdata: item.data\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmediaType: item.mediaType,\n\t\t\t\t\t\tproviderOptions: item.providerOptions\n\t\t\t\t\t};\n\t\t\t\tcase \"image-url\": {\n\t\t\t\t\tconst url = new URL(item.url);\n\t\t\t\t\twarnings.push({\n\t\t\t\t\t\ttype: \"deprecated\",\n\t\t\t\t\t\tsetting: \"\\\"tool-result\\\" content of type \\\"image-url\\\"\",\n\t\t\t\t\t\tmessage: `The \"image-url\" type for tool result content is deprecated. Use the \"file\" type with mediaType 'image' (or a specific image/* subtype) and { type: 'url', url } instead.`\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\ttype: \"url\",\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\t...url.toString() !== item.url ? { originalUrl: item.url } : {}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmediaType: \"image\",\n\t\t\t\t\t\tproviderOptions: item.providerOptions\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcase \"image-file-id\":\n\t\t\t\t\twarnings.push({\n\t\t\t\t\t\ttype: \"deprecated\",\n\t\t\t\t\t\tsetting: \"\\\"tool-result\\\" content of type \\\"image-file-id\\\"\",\n\t\t\t\t\t\tmessage: `The \"image-file-id\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\ttype: \"reference\",\n\t\t\t\t\t\t\treference: convertFileIdToProviderReference({\n\t\t\t\t\t\t\t\tfileId: item.fileId,\n\t\t\t\t\t\t\t\tprovider\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmediaType: \"image\",\n\t\t\t\t\t\tproviderOptions: item.providerOptions\n\t\t\t\t\t};\n\t\t\t\tcase \"image-file-reference\":\n\t\t\t\t\twarnings.push({\n\t\t\t\t\t\ttype: \"deprecated\",\n\t\t\t\t\t\tsetting: \"\\\"tool-result\\\" content of type \\\"image-file-reference\\\"\",\n\t\t\t\t\t\tmessage: `The \"image-file-reference\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\ttype: \"reference\",\n\t\t\t\t\t\t\treference: item.providerReference\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmediaType: \"image\",\n\t\t\t\t\t\tproviderOptions: item.providerOptions\n\t\t\t\t\t};\n\t\t\t\tdefault: return item;\n\t\t\t}\n\t\t})\n\t};\n}\nfunction convertFileIdToProviderReference({ fileId, provider }) {\n\tif (typeof fileId === \"object\") return fileId;\n\tif (provider == null) throw new Error(\"Cannot convert string fileId to provider reference without a provider ID. Use a Record<string, string> fileId or switch to the file-reference type.\");\n\treturn { [provider]: fileId };\n}\nconst URL_EXTENSION_TO_MEDIA_TYPE = {\n\tjpg: \"image/jpeg\",\n\tjpeg: \"image/jpeg\",\n\tpng: \"image/png\",\n\tgif: \"image/gif\",\n\twebp: \"image/webp\",\n\tsvg: \"image/svg+xml\",\n\tavif: \"image/avif\",\n\theic: \"image/heic\",\n\tbmp: \"image/bmp\",\n\ttiff: \"image/tiff\",\n\ttif: \"image/tiff\",\n\tpdf: \"application/pdf\",\n\tmp4: \"video/mp4\",\n\twebm: \"video/webm\",\n\tmp3: \"audio/mpeg\",\n\twav: \"audio/wav\",\n\togg: \"audio/ogg\"\n};\nfunction getMediaTypeFromUrl(url, fallbackMediaType = \"application/octet-stream\") {\n\ttry {\n\t\tconst fileExtension = new URL(url).pathname.split(\".\").pop()?.toLowerCase();\n\t\tif (fileExtension && Object.hasOwn(URL_EXTENSION_TO_MEDIA_TYPE, fileExtension)) return URL_EXTENSION_TO_MEDIA_TYPE[fileExtension];\n\t} catch {}\n\treturn fallbackMediaType;\n}\n//#endregion\n//#region src/prompt/create-tool-model-output.ts\nasync function createToolModelOutput({ toolCallId, input, output, tool, errorMode }) {\n\tif (errorMode === \"text\") return {\n\t\ttype: \"error-text\",\n\t\tvalue: getErrorMessage$1(output)\n\t};\n\telse if (errorMode === \"json\") return {\n\t\ttype: \"error-json\",\n\t\tvalue: toJSONValue(output)\n\t};\n\tif (tool?.toModelOutput) return await tool.toModelOutput({\n\t\ttoolCallId,\n\t\tinput,\n\t\toutput\n\t});\n\treturn typeof output === \"string\" ? {\n\t\ttype: \"text\",\n\t\tvalue: output\n\t} : {\n\t\ttype: \"json\",\n\t\tvalue: toJSONValue(output)\n\t};\n}\n/**\n* Normalizes an in-process tool output to a plain JSON value\n* (applies `toJSON`, converts `Date`, drops `undefined`, etc.)\n* by round-tripping it through `JSON.stringify`.\n*\n* The parsed text is produced by `JSON.stringify` from a value that is\n* already materialized in this process, so it is not untrusted input.\n* `JSON.parse` is used deliberately instead of the secure parser from\n* `@ai-sdk/provider-utils`: the secure parser rejects own `__proto__` and\n* `constructor.prototype` keys, which are valid data in tool outputs\n* (e.g. rows from an external API). `JSON.parse` defines `__proto__` as an\n* own data property and never modifies the prototype chain, so preserving\n* these keys here is safe. Do not reuse this pattern for text that comes\n* from outside the process; use `parseJSON` / `safeParseJSON` instead.\n*/\nfunction toJSONValue(value) {\n\tif (value === void 0) return null;\n\tconst serialized = JSON.stringify(value);\n\treturn serialized === void 0 ? null : JSON.parse(serialized);\n}\n//#endregion\n//#region src/prompt/prepare-language-model-call-options.ts\n/**\n* Validates model call options and returns a new object with normalized values.\n*/\nfunction prepareLanguageModelCallOptions({ maxOutputTokens, temperature, topP, topK, presencePenalty, frequencyPenalty, seed, stopSequences, reasoning }) {\n\tif (maxOutputTokens != null) {\n\t\tif (!Number.isInteger(maxOutputTokens)) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxOutputTokens\",\n\t\t\tvalue: maxOutputTokens,\n\t\t\tmessage: \"maxOutputTokens must be an integer\"\n\t\t});\n\t\tif (maxOutputTokens < 1) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxOutputTokens\",\n\t\t\tvalue: maxOutputTokens,\n\t\t\tmessage: \"maxOutputTokens must be >= 1\"\n\t\t});\n\t}\n\tif (temperature != null) {\n\t\tif (typeof temperature !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"temperature\",\n\t\t\tvalue: temperature,\n\t\t\tmessage: \"temperature must be a number\"\n\t\t});\n\t}\n\tif (topP != null) {\n\t\tif (typeof topP !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"topP\",\n\t\t\tvalue: topP,\n\t\t\tmessage: \"topP must be a number\"\n\t\t});\n\t}\n\tif (topK != null) {\n\t\tif (typeof topK !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"topK\",\n\t\t\tvalue: topK,\n\t\t\tmessage: \"topK must be a number\"\n\t\t});\n\t}\n\tif (presencePenalty != null) {\n\t\tif (typeof presencePenalty !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"presencePenalty\",\n\t\t\tvalue: presencePenalty,\n\t\t\tmessage: \"presencePenalty must be a number\"\n\t\t});\n\t}\n\tif (frequencyPenalty != null) {\n\t\tif (typeof frequencyPenalty !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"frequencyPenalty\",\n\t\t\tvalue: frequencyPenalty,\n\t\t\tmessage: \"frequencyPenalty must be a number\"\n\t\t});\n\t}\n\tif (seed != null) {\n\t\tif (!Number.isInteger(seed)) throw new InvalidArgumentError({\n\t\t\tparameter: \"seed\",\n\t\t\tvalue: seed,\n\t\t\tmessage: \"seed must be an integer\"\n\t\t});\n\t}\n\treturn {\n\t\tmaxOutputTokens,\n\t\ttemperature,\n\t\ttopP,\n\t\ttopK,\n\t\tpresencePenalty,\n\t\tfrequencyPenalty,\n\t\tstopSequences,\n\t\tseed,\n\t\treasoning\n\t};\n}\n//#endregion\n//#region src/prompt/prepare-tool-choice.ts\nfunction prepareToolChoice({ toolChoice }) {\n\treturn toolChoice == null ? { type: \"auto\" } : typeof toolChoice === \"string\" ? { type: toolChoice } : {\n\t\ttype: \"tool\",\n\t\ttoolName: toolChoice.toolName\n\t};\n}\n//#endregion\n//#region src/util/is-non-empty-object.ts\nfunction isNonEmptyObject(object) {\n\treturn object != null && Object.keys(object).length > 0;\n}\n//#endregion\n//#region src/prompt/prepare-tools.ts\nasync function prepareTools({ tools, toolOrder, toolsContext = {}, experimental_sandbox: sandbox }) {\n\tif (!isNonEmptyObject(tools)) return;\n\tconst languageModelTools = [];\n\tfor (const [name, tool] of orderToolEntries({\n\t\ttools,\n\t\ttoolOrder\n\t})) {\n\t\tconst toolType = tool.type;\n\t\tswitch (toolType) {\n\t\t\tcase void 0:\n\t\t\tcase \"dynamic\":\n\t\t\tcase \"function\": {\n\t\t\t\tconst description = resolveToolDescription({\n\t\t\t\t\ttool,\n\t\t\t\t\ttoolName: name,\n\t\t\t\t\ttoolsContext,\n\t\t\t\t\texperimental_sandbox: sandbox\n\t\t\t\t});\n\t\t\t\tconst providerOptions = tool.providerOptions;\n\t\t\t\tconst inputExamples = tool.inputExamples;\n\t\t\t\tconst strict = tool.strict;\n\t\t\t\tlanguageModelTools.push({\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tname,\n\t\t\t\t\tinputSchema: await asSchema$1(tool.inputSchema).jsonSchema,\n\t\t\t\t\t...description != null ? { description } : {},\n\t\t\t\t\t...inputExamples != null ? { inputExamples } : {},\n\t\t\t\t\t...providerOptions != null ? { providerOptions } : {},\n\t\t\t\t\t...strict != null ? { strict } : {}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"provider\":\n\t\t\t\tlanguageModelTools.push({\n\t\t\t\t\ttype: \"provider\",\n\t\t\t\t\tname,\n\t\t\t\t\tid: tool.id,\n\t\t\t\t\targs: tool.args\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault: throw new Error(`Unsupported tool type: ${toolType}`);\n\t\t}\n\t}\n\treturn languageModelTools;\n}\nfunction orderToolEntries({ tools, toolOrder }) {\n\tif (toolOrder == null) return Object.entries(tools);\n\tconst toolEntries = Object.entries(tools);\n\tconst orderedTools = toolEntries.filter(([name]) => toolOrder.includes(name)).sort(([nameA], [nameB]) => toolOrder.indexOf(nameA) - toolOrder.indexOf(nameB));\n\tconst unorderedTools = toolEntries.filter(([name]) => !toolOrder.includes(name)).sort(([nameA], [nameB]) => nameA < nameB ? -1 : nameA > nameB ? 1 : 0);\n\treturn [...orderedTools, ...unorderedTools];\n}\nfunction resolveToolDescription({ tool, toolName, toolsContext, experimental_sandbox: sandbox }) {\n\treturn tool.description === void 0 ? void 0 : typeof tool.description === \"string\" ? tool.description : tool.description({\n\t\tcontext: toolsContext[toolName],\n\t\texperimental_sandbox: sandbox\n\t});\n}\n//#endregion\n//#region src/prompt/request-options.ts\n/**\n* Extracts the total timeout value in milliseconds from a TimeoutConfiguration.\n*\n* @param timeout - The timeout configuration.\n* @returns The total timeout in milliseconds, or undefined if no timeout is configured.\n*/\nfunction getTotalTimeoutMs(timeout) {\n\tif (timeout == null) return;\n\tif (typeof timeout === \"number\") return timeout;\n\treturn timeout.totalMs;\n}\n/**\n* Extracts the step timeout value in milliseconds from a TimeoutConfiguration.\n*\n* @param timeout - The timeout configuration.\n* @returns The step timeout in milliseconds, or undefined if no step timeout is configured.\n*/\nfunction getStepTimeoutMs(timeout) {\n\tif (timeout == null || typeof timeout === \"number\") return;\n\treturn timeout.stepMs;\n}\n/**\n* Extracts the first chunk timeout value in milliseconds from a TimeoutConfiguration.\n* This timeout is for streaming only - it aborts if no content chunk is received within the specified duration.\n*\n* @param timeout - The timeout configuration.\n* @returns The first chunk timeout in milliseconds, or undefined if no first chunk timeout is configured.\n*/\nfunction getFirstChunkTimeoutMs(timeout) {\n\tif (timeout == null || typeof timeout === \"number\") return;\n\treturn timeout.firstChunkMs;\n}\n/**\n* Extracts the chunk timeout value in milliseconds from a TimeoutConfiguration.\n* This timeout is for streaming only - it aborts if no new content chunk is received within the specified duration.\n*\n* @param timeout - The timeout configuration.\n* @returns The chunk timeout in milliseconds, or undefined if no chunk timeout is configured.\n*/\nfunction getChunkTimeoutMs(timeout) {\n\tif (timeout == null || typeof timeout === \"number\") return;\n\treturn timeout.chunkMs;\n}\nfunction getToolTimeoutMs(timeout, toolName) {\n\tif (timeout == null || typeof timeout === \"number\") return;\n\treturn timeout.tools?.[`${toolName}Ms`] ?? timeout.toolMs;\n}\n//#endregion\n//#region src/util/zod.ts\nconst z = {\n\tarray,\n\tboolean,\n\tcustom,\n\tdiscriminatedUnion,\n\tenum: enum$1,\n\tinstanceof: instanceof$1,\n\tlazy,\n\tliteral,\n\tlooseObject,\n\tnever,\n\tnull: null$1,\n\tnumber,\n\tobject,\n\trecord,\n\tstring,\n\tunion,\n\tunknown\n};\n//#endregion\n//#region src/types/json-value.ts\nconst jsonValueSchema = z.lazy(() => z.union([\n\tz.null(),\n\tz.string(),\n\tz.number(),\n\tz.boolean(),\n\tz.record(z.string(), jsonValueSchema.optional()),\n\tz.array(jsonValueSchema)\n]));\n//#endregion\n//#region src/types/provider-metadata.ts\nconst providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema.optional()));\n//#endregion\n//#region src/prompt/content-part.ts\nconst fileInlineDataSchema = z.union([\n\tz.string(),\n\tz.instanceof(Uint8Array),\n\tz.instanceof(ArrayBuffer),\n\tz.custom(isBuffer, { message: \"Must be a Buffer\" })\n]);\nconst providerReferenceSchema$1 = z.record(z.string(), z.string());\n/**\n* @internal\n*/\nconst textPartSchema = z.object({\n\ttype: z.literal(\"text\"),\n\ttext: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\n/**\n* @internal\n* @deprecated Use `filePartSchema` with `mediaType: 'image'` instead:\n* `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.\n*/\nconst imagePartSchema = z.object({\n\ttype: z.literal(\"image\"),\n\timage: z.union([\n\t\tfileInlineDataSchema,\n\t\tz.instanceof(URL),\n\t\tproviderReferenceSchema$1\n\t]),\n\tmediaType: z.string().optional(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nconst taggedFileDataSchema = z.discriminatedUnion(\"type\", [\n\tz.object({\n\t\ttype: z.literal(\"data\"),\n\t\tdata: fileInlineDataSchema\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"url\"),\n\t\turl: z.instanceof(URL)\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"reference\"),\n\t\treference: providerReferenceSchema$1\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"text\"),\n\t\ttext: z.string()\n\t})\n]);\nconst taggedReasoningFileDataSchema = z.discriminatedUnion(\"type\", [z.object({\n\ttype: z.literal(\"data\"),\n\tdata: fileInlineDataSchema\n}), z.object({\n\ttype: z.literal(\"url\"),\n\turl: z.instanceof(URL)\n})]);\n/**\n* @internal\n*/\nconst filePartSchema = z.object({\n\ttype: z.literal(\"file\"),\n\tdata: z.union([\n\t\ttaggedFileDataSchema,\n\t\tfileInlineDataSchema,\n\t\tz.instanceof(URL),\n\t\tproviderReferenceSchema$1\n\t]),\n\tfilename: z.string().optional(),\n\tmediaType: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\n/**\n* @internal\n*/\nconst reasoningPartSchema = z.object({\n\ttype: z.literal(\"reasoning\"),\n\ttext: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\n/**\n* @internal\n*/\nconst customPartSchema = z.object({\n\ttype: z.literal(\"custom\"),\n\tkind: z.string().transform((value) => value),\n\tproviderOptions: providerMetadataSchema.optional()\n});\n/**\n* @internal\n*/\nconst reasoningFilePartSchema = z.object({\n\ttype: z.literal(\"reasoning-file\"),\n\tdata: z.union([\n\t\ttaggedReasoningFileDataSchema,\n\t\tfileInlineDataSchema,\n\t\tz.instanceof(URL)\n\t]),\n\tmediaType: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\n/**\n* @internal\n*/\nconst toolCallPartSchema = z.object({\n\ttype: z.literal(\"tool-call\"),\n\ttoolCallId: z.string(),\n\ttoolName: z.string(),\n\tinput: z.unknown(),\n\tproviderOptions: providerMetadataSchema.optional(),\n\tproviderExecuted: z.boolean().optional()\n});\n/**\n* @internal\n*/\nconst outputSchema = z.discriminatedUnion(\"type\", [\n\tz.object({\n\t\ttype: z.literal(\"text\"),\n\t\tvalue: z.string(),\n\t\tproviderOptions: providerMetadataSchema.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"json\"),\n\t\tvalue: jsonValueSchema,\n\t\tproviderOptions: providerMetadataSchema.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"execution-denied\"),\n\t\treason: z.string().optional(),\n\t\tproviderOptions: providerMetadataSchema.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"error-text\"),\n\t\tvalue: z.string(),\n\t\tproviderOptions: providerMetadataSchema.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"error-json\"),\n\t\tvalue: jsonValueSchema,\n\t\tproviderOptions: providerMetadataSchema.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"content\"),\n\t\tvalue: z.array(z.union([\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"text\"),\n\t\t\t\ttext: z.string(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"file\"),\n\t\t\t\tdata: taggedFileDataSchema,\n\t\t\t\tmediaType: z.string(),\n\t\t\t\tfilename: z.string().optional(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"file-data\"),\n\t\t\t\tdata: z.string(),\n\t\t\t\tmediaType: z.string(),\n\t\t\t\tfilename: z.string().optional(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"file-url\"),\n\t\t\t\turl: z.string(),\n\t\t\t\tmediaType: z.string().optional(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"file-id\"),\n\t\t\t\tfileId: z.union([z.string(), z.record(z.string(), z.string())]),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"file-reference\"),\n\t\t\t\tproviderReference: z.record(z.string(), z.string()),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"image-data\"),\n\t\t\t\tdata: z.string(),\n\t\t\t\tmediaType: z.string(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"image-url\"),\n\t\t\t\turl: z.string(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"image-file-id\"),\n\t\t\t\tfileId: z.union([z.string(), z.record(z.string(), z.string())]),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"image-file-reference\"),\n\t\t\t\tproviderReference: z.record(z.string(), z.string()),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"custom\"),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t})\n\t\t]))\n\t})\n]);\n/**\n* @internal\n*/\nconst toolResultPartSchema = z.object({\n\ttype: z.literal(\"tool-result\"),\n\ttoolCallId: z.string(),\n\ttoolName: z.string(),\n\toutput: outputSchema,\n\tproviderOptions: providerMetadataSchema.optional()\n});\n/**\n* @internal\n*/\nconst toolApprovalRequestSchema = z.object({\n\ttype: z.literal(\"tool-approval-request\"),\n\tapprovalId: z.string(),\n\ttoolCallId: z.string(),\n\treason: z.string().optional(),\n\tisAutomatic: z.boolean().optional(),\n\tsignature: z.string().optional(),\n\tinputSchemaInput: z.unknown().optional()\n});\n/**\n* @internal\n*/\nconst toolApprovalResponseSchema = z.object({\n\ttype: z.literal(\"tool-approval-response\"),\n\tapprovalId: z.string(),\n\tapproved: z.boolean(),\n\treason: z.string().optional()\n});\n//#endregion\n//#region src/prompt/message.ts\nconst systemModelMessageSchema = z.object({\n\trole: z.literal(\"system\"),\n\tcontent: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nconst userModelMessageSchema = z.object({\n\trole: z.literal(\"user\"),\n\tcontent: z.union([z.string(), z.array(z.union([\n\t\ttextPartSchema,\n\t\timagePartSchema,\n\t\tfilePartSchema\n\t]))]),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nconst assistantModelMessageSchema = z.object({\n\trole: z.literal(\"assistant\"),\n\tcontent: z.union([z.string(), z.array(z.union([\n\t\ttextPartSchema,\n\t\tcustomPartSchema,\n\t\tfilePartSchema,\n\t\treasoningPartSchema,\n\t\treasoningFilePartSchema,\n\t\ttoolCallPartSchema,\n\t\ttoolResultPartSchema,\n\t\ttoolApprovalRequestSchema\n\t]))]),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nconst toolModelMessageSchema = z.object({\n\trole: z.literal(\"tool\"),\n\tcontent: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nconst modelMessageSchema = z.union([\n\tsystemModelMessageSchema,\n\tuserModelMessageSchema,\n\tassistantModelMessageSchema,\n\ttoolModelMessageSchema\n]);\n//#endregion\n//#region src/prompt/standardize-prompt.ts\n/**\n* Converts a prompt input into a standardized prompt with validated model\n* messages.\n*\n* @param prompt - The prompt definition to standardize.\n* Set `allowSystemInMessages` to true to allow system messages in the\n* `prompt` or `messages` fields. System messages in the `instructions`\n* option are always allowed.\n* @returns The standardized prompt.\n* @throws {InvalidPromptError} When the prompt is invalid.\n*/\nasync function standardizePrompt({ allowSystemInMessages = false, system, instructions = system, prompt, messages }) {\n\tif (prompt == null && messages == null) throw new InvalidPromptError$1({\n\t\tprompt,\n\t\tmessage: \"prompt or messages must be defined\"\n\t});\n\tif (prompt != null && messages != null) throw new InvalidPromptError$1({\n\t\tprompt,\n\t\tmessage: \"prompt and messages cannot be defined at the same time\"\n\t});\n\tif (typeof instructions !== \"string\" && !asArray(instructions).every((message) => message.role === \"system\")) throw new InvalidPromptError$1({\n\t\tprompt,\n\t\tmessage: \"instructions must be a string, SystemModelMessage, or array of SystemModelMessage\"\n\t});\n\tif (prompt != null && typeof prompt === \"string\") messages = [{\n\t\trole: \"user\",\n\t\tcontent: prompt\n\t}];\n\telse if (prompt != null && Array.isArray(prompt)) messages = prompt;\n\telse if (messages == null) throw new InvalidPromptError$1({\n\t\tprompt,\n\t\tmessage: \"prompt or messages must be defined\"\n\t});\n\tif (messages.length === 0) throw new InvalidPromptError$1({\n\t\tprompt,\n\t\tmessage: \"messages must not be empty\"\n\t});\n\tif (!allowSystemInMessages && messages.some((message) => message.role === \"system\")) throw new InvalidPromptError$1({\n\t\tprompt,\n\t\tmessage: \"System messages are not allowed in the prompt or messages fields. Use the instructions option instead.\"\n\t});\n\tconst validationResult = await safeValidateTypes({\n\t\tvalue: messages,\n\t\tschema: z.array(modelMessageSchema)\n\t});\n\tif (!validationResult.success) throw new InvalidPromptError$1({\n\t\tprompt,\n\t\tmessage: \"The messages do not match the ModelMessage[] schema.\",\n\t\tcause: validationResult.error\n\t});\n\treturn {\n\t\tmessages,\n\t\tinstructions\n\t};\n}\n//#endregion\n//#region src/prompt/wrap-gateway-error.ts\nfunction wrapGatewayError(error) {\n\tif (!GatewayAuthenticationError.isInstance(error)) return error;\n\tconst isProductionEnv = process?.env.NODE_ENV === \"production\";\n\tconst moreInfoURL = \"https://ai-sdk.dev/unauthenticated-ai-gateway\";\n\tif (isProductionEnv) return new AISDKError$1({\n\t\tname: \"GatewayError\",\n\t\tmessage: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`\n\t});\n\treturn Object.assign(/* @__PURE__ */ new Error(`\\u001b[1m\\u001b[31mUnauthenticated request to AI Gateway.\\u001b[0m\n\nTo authenticate, set the \\u001b[33mAI_GATEWAY_API_KEY\\u001b[0m environment variable with your API key.\n\nAlternatively, you can use a provider module instead of the AI Gateway.\n\nLearn more: \\u001b[34m${moreInfoURL}\\u001b[0m\n\n`), { name: \"GatewayAuthenticationError\" });\n}\n//#endregion\n//#region src/types/usage.ts\nfunction asLanguageModelUsage(usage) {\n\treturn {\n\t\tinputTokens: usage.inputTokens.total,\n\t\tinputTokenDetails: {\n\t\t\tnoCacheTokens: usage.inputTokens.noCache,\n\t\t\tcacheReadTokens: usage.inputTokens.cacheRead,\n\t\t\tcacheWriteTokens: usage.inputTokens.cacheWrite\n\t\t},\n\t\toutputTokens: usage.outputTokens.total,\n\t\toutputTokenDetails: {\n\t\t\ttextTokens: usage.outputTokens.text,\n\t\t\treasoningTokens: usage.outputTokens.reasoning\n\t\t},\n\t\ttotalTokens: addTokenCounts(usage.inputTokens.total, usage.outputTokens.total),\n\t\traw: usage.raw\n\t};\n}\nfunction createNullLanguageModelUsage() {\n\treturn {\n\t\tinputTokens: void 0,\n\t\tinputTokenDetails: {\n\t\t\tnoCacheTokens: void 0,\n\t\t\tcacheReadTokens: void 0,\n\t\t\tcacheWriteTokens: void 0\n\t\t},\n\t\toutputTokens: void 0,\n\t\toutputTokenDetails: {\n\t\t\ttextTokens: void 0,\n\t\t\treasoningTokens: void 0\n\t\t},\n\t\ttotalTokens: void 0,\n\t\traw: void 0\n\t};\n}\nfunction addLanguageModelUsage(usage1, usage2) {\n\tconst raw = isNullLanguageModelUsage(usage1) ? usage2.raw : isNullLanguageModelUsage(usage2) ? usage1.raw : void 0;\n\treturn {\n\t\tinputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n\t\tinputTokenDetails: {\n\t\t\tnoCacheTokens: addTokenCounts(usage1.inputTokenDetails?.noCacheTokens, usage2.inputTokenDetails?.noCacheTokens),\n\t\t\tcacheReadTokens: addTokenCounts(usage1.inputTokenDetails?.cacheReadTokens, usage2.inputTokenDetails?.cacheReadTokens),\n\t\t\tcacheWriteTokens: addTokenCounts(usage1.inputTokenDetails?.cacheWriteTokens, usage2.inputTokenDetails?.cacheWriteTokens)\n\t\t},\n\t\toutputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n\t\toutputTokenDetails: {\n\t\t\ttextTokens: addTokenCounts(usage1.outputTokenDetails?.textTokens, usage2.outputTokenDetails?.textTokens),\n\t\t\treasoningTokens: addTokenCounts(usage1.outputTokenDetails?.reasoningTokens, usage2.outputTokenDetails?.reasoningTokens)\n\t\t},\n\t\ttotalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n\t\t...raw == null ? {} : { raw }\n\t};\n}\nfunction isNullLanguageModelUsage(usage) {\n\treturn usage.inputTokens == null && usage.inputTokenDetails?.noCacheTokens == null && usage.inputTokenDetails?.cacheReadTokens == null && usage.inputTokenDetails?.cacheWriteTokens == null && usage.outputTokens == null && usage.outputTokenDetails?.textTokens == null && usage.outputTokenDetails?.reasoningTokens == null && usage.totalTokens == null && usage.raw == null;\n}\nfunction addTokenCounts(tokenCount1, tokenCount2) {\n\treturn tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);\n}\nfunction addImageModelUsage(usage1, usage2) {\n\treturn {\n\t\tinputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n\t\toutputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n\t\ttotalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens)\n\t};\n}\n//#endregion\n//#region src/util/get-own.ts\n/**\n* Reads a property by an untrusted key, ignoring inherited prototype members.\n*\n* Tool sets, tool contexts, and similar lookup objects are indexed by names\n* that can come from model output or client-supplied message history. Plain\n* bracket access (`obj[name]`) resolves names such as `constructor`,\n* `toString`, or `__proto__` to values on `Object.prototype`, which would slip\n* past the `== null` / `!value` guards that treat an unknown name as \"not\n* present\". This helper returns `undefined` unless `key` is an own property.\n*/\nfunction getOwn(obj, key) {\n\treturn obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0;\n}\n//#endregion\n//#region src/util/merge-abort-signals.ts\n/**\n* Merges multiple abort sources into a single `AbortSignal`.\n* The returned signal will abort when any input signal aborts or when any\n* numeric timeout elapses, using the reason from the first source to abort.\n*\n* @param signals - Abort signals or timeout durations in milliseconds.\n* `null` and `undefined` values are ignored.\n* @returns An `AbortSignal` that aborts when any valid source aborts,\n* or `undefined` if no valid sources are provided.\n*/\nfunction mergeAbortSignals(...signals) {\n\tconst validSignals = filterNullable(...signals).map((signal) => typeof signal === \"number\" ? AbortSignal.timeout(signal) : signal);\n\treturn validSignals.length === 0 ? void 0 : validSignals.length === 1 ? validSignals[0] : AbortSignal.any(validSignals);\n}\n//#endregion\n//#region src/util/now.ts\nfunction now() {\n\treturn globalThis?.performance?.now() ?? Date.now();\n}\n//#endregion\n//#region src/util/notify.ts\n/**\n* Notifies all provided callbacks with the given event in parallel.\n* Errors in callbacks do not break the generation flow.\n*/\nasync function notify(options) {\n\tawait Promise.all(asArray(options.callbacks).map(async (callback) => {\n\t\ttry {\n\t\t\tawait callback?.(options.event);\n\t\t} catch {}\n\t}));\n}\n//#endregion\n//#region src/util/retry-with-exponential-backoff.ts\nfunction getRetryDelayInMs({ error, exponentialBackoffDelay }) {\n\tconst headers = APICallError$1.isInstance(error) ? error.responseHeaders : APICallError$1.isInstance(error.cause) ? error.cause.responseHeaders : void 0;\n\tif (!headers) return exponentialBackoffDelay;\n\tlet ms;\n\tconst retryAfterMs = headers[\"retry-after-ms\"];\n\tif (retryAfterMs) {\n\t\tconst timeoutMs = parseFloat(retryAfterMs);\n\t\tif (!Number.isNaN(timeoutMs)) ms = timeoutMs;\n\t}\n\tconst retryAfter = headers[\"retry-after\"];\n\tif (retryAfter && ms === void 0) {\n\t\tconst timeoutSeconds = parseFloat(retryAfter);\n\t\tif (!Number.isNaN(timeoutSeconds)) ms = timeoutSeconds * 1e3;\n\t\telse ms = Date.parse(retryAfter) - Date.now();\n\t}\n\tif (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 6e4 || ms < exponentialBackoffDelay)) return ms;\n\treturn exponentialBackoffDelay;\n}\n/**\n* The `retryWithExponentialBackoffRespectingRetryHeaders` strategy retries a failed API call with an exponential backoff,\n* while respecting rate limit headers (retry-after-ms and retry-after) if they are provided and reasonable (0-60 seconds).\n* You can configure the maximum number of retries, the initial delay, and the backoff factor.\n*/\nconst retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal, additionalRetryableError } = {}) => retryWithExponentialBackoff({\n\tmaxRetries,\n\tinitialDelayInMs,\n\tbackoffFactor,\n\tabortSignal,\n\tshouldRetry: async (error) => error instanceof Error && (APICallError$1.isInstance(error) && error.isRetryable === true || GatewayError.isInstance(error) && error.isRetryable === true) || additionalRetryableError != null && await additionalRetryableError(error),\n\tgetDelayInMs: ({ error, exponentialBackoffDelay }) => getRetryDelayInMs({\n\t\terror,\n\t\texponentialBackoffDelay\n\t}),\n\tcreateRetryError: ({ message, reason, errors }) => new RetryError({\n\t\tmessage,\n\t\treason,\n\t\terrors\n\t})\n});\n//#endregion\n//#region src/util/prepare-retries.ts\n/**\n* Validate and prepare retries.\n*/\nfunction prepareRetries({ maxRetries, abortSignal, additionalRetryableError, parameter = \"maxRetries\", defaultMaxRetries = 2 }) {\n\tif (maxRetries != null) {\n\t\tif (!Number.isInteger(maxRetries)) throw new InvalidArgumentError({\n\t\t\tparameter,\n\t\t\tvalue: maxRetries,\n\t\t\tmessage: `${parameter} must be an integer`\n\t\t});\n\t\tif (maxRetries < 0) throw new InvalidArgumentError({\n\t\t\tparameter,\n\t\t\tvalue: maxRetries,\n\t\t\tmessage: `${parameter} must be >= 0`\n\t\t});\n\t}\n\tconst maxRetriesResult = maxRetries ?? defaultMaxRetries;\n\treturn {\n\t\tmaxRetries: maxRetriesResult,\n\t\tretry: retryWithExponentialBackoffRespectingRetryHeaders({\n\t\t\tmaxRetries: maxRetriesResult,\n\t\t\tabortSignal,\n\t\t\tadditionalRetryableError\n\t\t})\n\t};\n}\n//#endregion\n//#region src/util/set-abort-timeout.ts\n/**\n* Schedules a timeout that aborts the given controller with a `TimeoutError`\n* `DOMException`, matching the reason produced by `AbortSignal.timeout(ms)`.\n*\n* @param abortController - The controller to abort when the timeout elapses.\n* If undefined, no timeout is scheduled.\n* @param label - Human-readable label included in the error message\n* (e.g. \"Step\", \"Chunk\").\n* @param timeoutMs - Duration in milliseconds before the controller is aborted.\n* If undefined, no timeout is scheduled.\n* @returns The timeout id (suitable for passing to `clearTimeout`), or\n* `undefined` if no timeout was scheduled.\n*/\nfunction setAbortTimeout({ abortController, label, timeoutMs }) {\n\tif (abortController == null || timeoutMs == null) return;\n\treturn setTimeout(() => abortController.abort(new DOMException(`${label} timeout of ${timeoutMs}ms exceeded`, \"TimeoutError\")), timeoutMs);\n}\n//#endregion\n//#region src/generate-text/calculate-tokens-per-second.ts\n/**\n* Calculates a token rate in tokens per second.\n*\n* Returns 0 when the token count is unknown, the duration is unknown or 0, or\n* the computed rate cannot be represented as a finite JSON-safe number.\n*/\nfunction calculateTokensPerSecond({ tokens, durationMs }) {\n\tconst tokenRate = 1e3 * (tokens ?? 0) / (durationMs ?? 0);\n\treturn Number.isFinite(tokenRate) ? tokenRate : 0;\n}\n//#endregion\n//#region src/generate-text/collect-tool-approvals.ts\n/**\n* If the last message is a tool message, this function collects all tool approvals\n* from that message.\n*/\nfunction collectToolApprovals({ messages }) {\n\tconst lastMessage = messages.at(-1);\n\tif (lastMessage?.role != \"tool\") return {\n\t\tapprovedToolApprovals: [],\n\t\tdeniedToolApprovals: []\n\t};\n\tconst toolCallsByToolCallId = Object.create(null);\n\tfor (const message of messages) if (message.role === \"assistant\" && typeof message.content !== \"string\") {\n\t\tconst content = message.content;\n\t\tfor (const part of content) if (part.type === \"tool-call\") toolCallsByToolCallId[part.toolCallId] = part;\n\t}\n\tconst toolApprovalRequestsByApprovalId = Object.create(null);\n\tfor (const message of messages) if (message.role === \"assistant\" && typeof message.content !== \"string\") {\n\t\tconst content = message.content;\n\t\tfor (const part of content) if (part.type === \"tool-approval-request\") toolApprovalRequestsByApprovalId[part.approvalId] = part;\n\t}\n\tconst toolResults = Object.create(null);\n\tfor (const part of lastMessage.content) if (part.type === \"tool-result\") toolResults[part.toolCallId] = part;\n\tconst approvedToolApprovals = [];\n\tconst deniedToolApprovals = [];\n\tconst approvalResponses = lastMessage.content.filter((part) => part.type === \"tool-approval-response\");\n\tfor (const approvalResponse of approvalResponses) {\n\t\tconst approvalRequest = toolApprovalRequestsByApprovalId[approvalResponse.approvalId];\n\t\tif (approvalRequest == null) throw new InvalidToolApprovalError({ approvalId: approvalResponse.approvalId });\n\t\tconst existingToolResult = toolResults[approvalRequest.toolCallId];\n\t\tif (existingToolResult != null && (approvalResponse.approved || existingToolResult.output.type !== \"execution-denied\")) continue;\n\t\tconst toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];\n\t\tif (toolCall == null) throw new ToolCallNotFoundForApprovalError({\n\t\t\ttoolCallId: approvalRequest.toolCallId,\n\t\t\tapprovalId: approvalRequest.approvalId\n\t\t});\n\t\tconst approval = {\n\t\t\tapprovalRequest,\n\t\t\tapprovalResponse,\n\t\t\ttoolCall,\n\t\t\t...existingToolResult != null ? { existingToolResult } : {}\n\t\t};\n\t\tif (approvalResponse.approved) approvedToolApprovals.push(approval);\n\t\telse deniedToolApprovals.push(approval);\n\t}\n\treturn {\n\t\tapprovedToolApprovals,\n\t\tdeniedToolApprovals\n\t};\n}\n//#endregion\n//#region src/generate-text/generated-file.ts\nvar DefaultGeneratedFile = class {\n\tconstructor({ data, mediaType, providerMetadata }) {\n\t\tconst isUint8Array = data instanceof Uint8Array;\n\t\tthis.base64Data = isUint8Array ? void 0 : data;\n\t\tthis.uint8ArrayData = isUint8Array ? data : void 0;\n\t\tthis.mediaType = mediaType;\n\t\tthis.providerMetadata = providerMetadata;\n\t}\n\tget base64() {\n\t\tif (this.base64Data == null) this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);\n\t\treturn this.base64Data;\n\t}\n\tget uint8Array() {\n\t\tif (this.uint8ArrayData == null) this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);\n\t\treturn this.uint8ArrayData;\n\t}\n};\nvar DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {\n\tconstructor(..._args) {\n\t\tsuper(..._args);\n\t\tthis.type = \"file\";\n\t}\n};\n//#endregion\n//#region src/generate-text/resolve-generated-file-data.ts\nasync function resolveGeneratedFileData({ data, abortSignal, cache }) {\n\tif (data.type === \"data\") return data.data;\n\tconst cachedData = cache?.get(data);\n\tif (cachedData != null) return cachedData;\n\tconst downloadedData = (await download({\n\t\turl: data.url,\n\t\tabortSignal\n\t})).data;\n\tcache?.set(data, downloadedData);\n\treturn downloadedData;\n}\n//#endregion\n//#region src/generate-text/convert-language-model-content.ts\nasync function convertLanguageModelContent({ content, toolCalls, toolOutputs, toolApprovalRequests, toolApprovalResponses, tools, abortSignal, generatedFileDataCache }) {\n\tconst contentParts = [];\n\tconst toolOutputsWithApprovalResponses = [];\n\tconst toolOutputsWithoutApprovalResponses = [];\n\tconst toolCallIdsWithApprovalResponses = new Set(toolApprovalResponses.map((toolApprovalResponse) => toolApprovalResponse.toolCall.toolCallId));\n\tfor (const part of content) switch (part.type) {\n\t\tcase \"text\":\n\t\tcase \"reasoning\":\n\t\tcase \"custom\":\n\t\tcase \"source\":\n\t\t\tcontentParts.push(part);\n\t\t\tbreak;\n\t\tcase \"file\":\n\t\tcase \"reasoning-file\":\n\t\t\tcontentParts.push({\n\t\t\t\ttype: part.type,\n\t\t\t\tfile: new DefaultGeneratedFile({\n\t\t\t\t\tdata: await resolveGeneratedFileData({\n\t\t\t\t\t\tdata: part.data,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\tcache: generatedFileDataCache\n\t\t\t\t\t}),\n\t\t\t\t\tmediaType: part.mediaType\n\t\t\t\t}),\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"tool-call\": {\n\t\t\tconst toolCall = toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId);\n\t\t\tif (toolCall == null) throw new Error(`Tool call ${part.toolCallId} not found.`);\n\t\t\tcontentParts.push(toolCall);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-result\": {\n\t\t\tconst toolCall = toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId);\n\t\t\tif (toolCall == null) {\n\t\t\t\tconst tool = getOwn(tools, part.toolName);\n\t\t\t\tif (!(tool?.type === \"provider\" && tool.supportsDeferredResults)) throw new Error(`Tool call ${part.toolCallId} not found.`);\n\t\t\t\tif (part.isError) contentParts.push({\n\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\tinput: void 0,\n\t\t\t\t\terror: part.result,\n\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\tdynamic: part.dynamic,\n\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t...tool?.metadata != null ? { toolMetadata: tool.metadata } : {}\n\t\t\t\t});\n\t\t\t\telse contentParts.push({\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\tinput: void 0,\n\t\t\t\t\toutput: part.result,\n\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\tdynamic: part.dynamic,\n\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t...tool?.metadata != null ? { toolMetadata: tool.metadata } : {}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (part.isError) contentParts.push({\n\t\t\t\ttype: \"tool-error\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\tinput: toolCall.input,\n\t\t\t\terror: part.result,\n\t\t\t\tproviderExecuted: true,\n\t\t\t\tdynamic: toolCall.dynamic,\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t});\n\t\t\telse contentParts.push({\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\tinput: toolCall.input,\n\t\t\t\toutput: part.result,\n\t\t\t\tproviderExecuted: true,\n\t\t\t\tdynamic: toolCall.dynamic,\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-approval-request\": {\n\t\t\tconst toolCall = toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId);\n\t\t\tif (toolCall == null) throw new ToolCallNotFoundForApprovalError({\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\tapprovalId: part.approvalId\n\t\t\t});\n\t\t\tcontentParts.push({\n\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\tapprovalId: part.approvalId,\n\t\t\t\ttoolCall\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor (const toolOutput of toolOutputs) if (toolCallIdsWithApprovalResponses.has(toolOutput.toolCallId)) toolOutputsWithApprovalResponses.push(toolOutput);\n\telse toolOutputsWithoutApprovalResponses.push(toolOutput);\n\treturn [\n\t\t...contentParts,\n\t\t...toolOutputsWithoutApprovalResponses,\n\t\t...toolApprovalRequests,\n\t\t...toolApprovalResponses,\n\t\t...toolOutputsWithApprovalResponses\n\t];\n}\nfunction resolveToolCallerConfiguration({ tools, toolCallers }) {\n\tif (tools == null || toolCallers == null) return;\n\tconst resolved = {};\n\tfor (const [toolName, callers] of Object.entries(toolCallers)) {\n\t\tif (!Object.prototype.hasOwnProperty.call(tools, toolName)) throw new InvalidArgumentError({\n\t\t\tparameter: \"experimental_toolCallers\",\n\t\t\tvalue: toolCallers,\n\t\t\tmessage: `unknown tool \"${toolName}\".`\n\t\t});\n\t\tif (!Array.isArray(callers)) throw new InvalidArgumentError({\n\t\t\tparameter: \"experimental_toolCallers\",\n\t\t\tvalue: toolCallers,\n\t\t\tmessage: `callers for tool \"${toolName}\" must be an array.`\n\t\t});\n\t\tresolved[toolName] = callers.map((caller) => {\n\t\t\tif (caller === \"AI_SDK_DIRECT_TOOL_CALL\") return caller;\n\t\t\tif (typeof caller !== \"string\" || !Object.prototype.hasOwnProperty.call(tools, caller) || experimental_getToolCaller(tools[caller]) == null) throw new InvalidArgumentError({\n\t\t\t\tparameter: \"experimental_toolCallers\",\n\t\t\t\tvalue: toolCallers,\n\t\t\t\tmessage: `tool \"${toolName}\" contains an invalid caller.`\n\t\t\t});\n\t\t\treturn caller;\n\t\t});\n\t}\n\treturn resolved;\n}\nfunction prepareToolsForToolCallers({ tools, toolCallers }) {\n\tif (tools == null || toolCallers == null) return {\n\t\texecutionTools: tools,\n\t\tmodelTools: tools,\n\t\ttoolCallerMessages: []\n\t};\n\tconst executionTools = { ...tools };\n\tconst modelTools = { ...tools };\n\tconst localToolsByCaller = /* @__PURE__ */ new Map();\n\tconst toolCallerMessages = [];\n\tfor (const [toolName, callerNames] of Object.entries(toolCallers)) {\n\t\tconst tool = executionTools[toolName];\n\t\tif (tool == null) continue;\n\t\tlet availableDirectly = false;\n\t\tlet availableToProvider = false;\n\t\tlet preparedTool = tool;\n\t\tfor (const callerName of callerNames) {\n\t\t\tif (callerName === \"AI_SDK_DIRECT_TOOL_CALL\") {\n\t\t\t\tavailableDirectly = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst caller = experimental_getToolCaller(executionTools[callerName]);\n\t\t\tif (caller == null) continue;\n\t\t\tif (caller.type === \"provider\") {\n\t\t\t\tavailableToProvider = true;\n\t\t\t\tpreparedTool = {\n\t\t\t\t\t...preparedTool,\n\t\t\t\t\tproviderOptions: caller.prepareProviderOptions(preparedTool.providerOptions)\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\tconst localTools = localToolsByCaller.get(callerName) ?? {};\n\t\t\t\tlocalTools[toolName] = preparedTool;\n\t\t\t\tlocalToolsByCaller.set(callerName, localTools);\n\t\t\t}\n\t\t}\n\t\texecutionTools[toolName] = preparedTool;\n\t\tif (availableDirectly || availableToProvider) modelTools[toolName] = preparedTool;\n\t\telse delete modelTools[toolName];\n\t}\n\tfor (const [callerName, callerTool] of Object.entries(executionTools)) {\n\t\tconst caller = experimental_getToolCaller(callerTool);\n\t\tif (caller?.type !== \"local\") continue;\n\t\tconst callerTools = localToolsByCaller.get(callerName) ?? {};\n\t\tconst boundCaller = caller.bind(callerTools);\n\t\texecutionTools[callerName] = boundCaller;\n\t\tif (Object.prototype.hasOwnProperty.call(modelTools, callerName)) {\n\t\t\tif (caller.prepareModelMessage == null) modelTools[callerName] = boundCaller;\n\t\t\telse {\n\t\t\t\tconst content = caller.prepareModelMessage(callerTools);\n\t\t\t\tif (content != null) toolCallerMessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\texecutionTools,\n\t\tmodelTools,\n\t\ttoolCallerMessages\n\t};\n}\nfunction appendToolCallerMessages({ messages, toolCallerMessages }) {\n\tif (toolCallerMessages.length === 0) return messages;\n\tconst latestUserText = messages.findLast((message) => message.role === \"user\" && typeof message.content === \"string\")?.content;\n\tconst existingUserText = new Set(latestUserText == null ? [] : [latestUserText]);\n\tconst additions = toolCallerMessages.filter((message) => {\n\t\tif (typeof message.content !== \"string\" || existingUserText.has(message.content)) return false;\n\t\texistingUserText.add(message.content);\n\t\treturn true;\n\t});\n\treturn additions.length === 0 ? messages : [...messages, ...additions];\n}\n//#endregion\n//#region src/tool-search/tool-search.ts\nconst toolSearchSymbol = Symbol.for(\"vercel.ai.toolSearch\");\nconst toolSearchFunctionSymbol = Symbol.for(\"vercel.ai.toolSearch.search\");\nconst toolSearchMaxResultsSymbol = Symbol.for(\"vercel.ai.toolSearch.maxResults\");\n/**\n* Search deferred tools by name and description. The surrounding generation\n* binds the search registry and makes matches available on the next step.\n* Use directly or through code mode with `toolDiscovery: 'conversation'`.\n*/\nfunction toolSearch({ search, maxResults = 5 } = {}) {\n\tif (!Number.isSafeInteger(maxResults) || maxResults < 1) throw new InvalidArgumentError({\n\t\tparameter: \"maxResults\",\n\t\tvalue: maxResults,\n\t\tmessage: \"maxResults must be a positive safe integer.\"\n\t});\n\treturn Object.assign(tool$1({\n\t\tdescription: `${search == null ? \"Search for tools by keywords in their names and descriptions.\" : \"Search for tools matching a query.\"} Returns up to ${maxResults === 5 ? \"five\" : maxResults} matching tools. Matches become available on the next model step, after this execution finishes. Wait for their tool definitions before calling the discovered tools. If no tools match, try different keywords.`,\n\t\tinputSchema: jsonSchema$1({\n\t\t\ttype: \"object\",\n\t\t\tproperties: { query: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tminLength: 1\n\t\t\t} },\n\t\t\trequired: [\"query\"],\n\t\t\tadditionalProperties: false\n\t\t}),\n\t\toutputSchema: jsonSchema$1({\n\t\t\ttype: \"object\",\n\t\t\tproperties: { tools: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tname: { type: \"string\" },\n\t\t\t\t\t\tdescription: { type: \"string\" }\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"name\"],\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t}\n\t\t\t} },\n\t\t\trequired: [\"tools\"],\n\t\t\tadditionalProperties: false\n\t\t}),\n\t\texecute: () => {\n\t\t\tthrow new Error(\"toolSearch must be bound by an AI SDK generation.\");\n\t\t}\n\t}), {\n\t\ttype: \"function\",\n\t\t[toolSearchSymbol]: true,\n\t\t[toolSearchFunctionSymbol]: search,\n\t\t[toolSearchMaxResultsSymbol]: maxResults\n\t});\n}\nfunction getToolSearchMaxResults(tool) {\n\treturn tool[toolSearchMaxResultsSymbol] ?? 5;\n}\nfunction getToolSearchFunction(tool) {\n\treturn tool[toolSearchFunctionSymbol];\n}\nfunction isToolSearch(tool) {\n\treturn tool[toolSearchSymbol] === true;\n}\n//#endregion\n//#region src/tool-search/prepare-tool-search.ts\n/** Create discovery state for one generation, never for a shared tool instance. */\nfunction createToolSearchState({ tools, toolCallers }) {\n\tconst searchTools = Object.entries(tools ?? {}).filter(([, tool]) => tool.deferLoading || isToolSearch(tool));\n\tif (searchTools.length === 0) return (activeTools) => activeTools;\n\tconst discovered = /* @__PURE__ */ new Set();\n\tconst getCallers = (name) => getOwn(toolCallers, name) ?? [\"AI_SDK_DIRECT_TOOL_CALL\"];\n\tfor (const [name, tool] of searchTools) if (getCallers(name).some((name) => {\n\t\tif (name === \"AI_SDK_DIRECT_TOOL_CALL\") return false;\n\t\tconst caller = experimental_getToolCaller(tools?.[name]);\n\t\treturn caller?.type !== \"local\" || caller.prepareModelMessage == null;\n\t}) || isToolSearch(tool) && tool.deferLoading) throw new InvalidArgumentError({\n\t\tparameter: \"tools\",\n\t\tvalue: name,\n\t\tmessage: `tool \"${name}\" must be callable directly or through code mode with toolDiscovery: 'conversation'. The search tool itself must not defer loading.`\n\t});\n\treturn (activeTools, { toolsContext = {}, experimental_sandbox } = {}) => {\n\t\tif (activeTools == null) return;\n\t\tconst entries = Object.entries(activeTools);\n\t\treturn Object.fromEntries(entries.filter(([name, tool]) => !tool.deferLoading || discovered.has(name)).map(([searchName, tool]) => {\n\t\t\tif (!isToolSearch(tool)) return [searchName, tool];\n\t\t\tconst callers = getCallers(searchName).filter((name) => name === \"AI_SDK_DIRECT_TOOL_CALL\" || Object.hasOwn(activeTools, name));\n\t\t\tconst candidates = entries.filter(([name, candidate]) => candidate.deferLoading && !isToolSearch(candidate) && callers.some((caller) => getCallers(name).includes(caller)));\n\t\t\treturn [searchName, {\n\t\t\t\t...tool,\n\t\t\t\texecute: async ({ query }) => {\n\t\t\t\t\tconst availableTools = candidates.map(([name, candidate]) => {\n\t\t\t\t\t\tconst description = resolveToolDescription({\n\t\t\t\t\t\t\ttool: candidate,\n\t\t\t\t\t\t\ttoolName: name,\n\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\texperimental_sandbox\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t...description == null ? {} : { description }\n\t\t\t\t\t\t};\n\t\t\t\t\t});\n\t\t\t\t\tconst toolsByName = new Map(availableTools.map((tool) => [tool.name, tool]));\n\t\t\t\t\tconst customSearch = getToolSearchFunction(tool);\n\t\t\t\t\tconst terms = [...new Set(tokenize(query))];\n\t\t\t\t\tconst rankedNames = customSearch ? await customSearch({\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\ttools: availableTools.map((tool) => ({ ...tool }))\n\t\t\t\t\t}) : availableTools.map(({ name, description }) => {\n\t\t\t\t\t\tconst nameTerms = tokenize(name);\n\t\t\t\t\t\tconst descriptionTerms = tokenize(description ?? \"\");\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tscore: terms.reduce((score, term) => score + (nameTerms.includes(term) ? 2 : 0) + (descriptionTerms.includes(term) ? 1 : 0), 0)\n\t\t\t\t\t\t};\n\t\t\t\t\t}).filter((match) => match.score > 0).sort((a, b) => b.score - a.score).map((match) => match.name);\n\t\t\t\t\tconst matches = [...new Set(rankedNames)].flatMap((name) => {\n\t\t\t\t\t\tconst match = toolsByName.get(name);\n\t\t\t\t\t\treturn match == null ? [] : [match];\n\t\t\t\t\t}).slice(0, getToolSearchMaxResults(tool));\n\t\t\t\t\tfor (const { name } of matches) discovered.add(name);\n\t\t\t\t\treturn { tools: matches };\n\t\t\t\t}\n\t\t\t}];\n\t\t}));\n\t};\n}\nfunction tokenize(text) {\n\treturn text.replace(/([a-z\\d])([A-Z])/g, \"$1 $2\").toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? [];\n}\n//#endregion\n//#region src/generate-text/validate-tool-context.ts\n/**\n* Validates a tool context value against the tool's optional context schema.\n*\n* When no context schema is defined, the original context value is returned as-is.\n* Otherwise, the context is validated and normalized through the schema before\n* being passed into tool execution and approval hooks.\n*\n* @throws {TypeValidationError} When the provided tool context does not match\n* the tool's declared `contextSchema`.\n*/\nasync function validateToolContext({ toolName, context, contextSchema }) {\n\tif (contextSchema == null) return context;\n\treturn await validateTypes({\n\t\tvalue: context,\n\t\tschema: contextSchema,\n\t\tcontext: {\n\t\t\tfield: \"tool context\",\n\t\t\tentityName: toolName\n\t\t}\n\t});\n}\n//#endregion\n//#region src/generate-text/execute-tool-call.ts\n/**\n* Executes a single tool call and manages its lifecycle callbacks.\n*\n* This function handles the complete tool execution flow:\n* 1. Invokes `onToolExecutionStart` callback before execution\n* 2. Executes the tool's `execute` function with proper context\n* 3. Handles streaming outputs via `onPreliminaryToolResult`\n* 4. Invokes `onToolExecutionEnd` callback with success or error result\n*\n* @returns The tool output with performance metrics, or undefined if the tool has no execute function.\n*/\nasync function executeToolCall({ toolCall, tools, toolsContext, callId, messages, abortSignal, timeout, experimental_sandbox: sandbox, onPreliminaryToolResult, onToolExecutionStart, onToolExecutionEnd, executeToolInTelemetryContext = async ({ execute }) => await execute(), runInTracingChannelSpan = async ({ execute }) => await execute() }) {\n\tconst { toolName, toolCallId, input } = toolCall;\n\tconst tool = getOwn(tools, toolName);\n\tif (!isExecutableTool(tool)) return;\n\tconst context = await validateToolContext({\n\t\ttoolName,\n\t\tcontext: getOwn(toolsContext, toolName),\n\t\tcontextSchema: tool.contextSchema\n\t});\n\tconst toolExecutionContext = {\n\t\ttoolCall,\n\t\tmessages,\n\t\ttoolContext: context\n\t};\n\tconst baseCallbackEvent = {\n\t\tcallId,\n\t\t...toolExecutionContext\n\t};\n\treturn await runInTracingChannelSpan({\n\t\ttype: \"executeTool\",\n\t\tevent: baseCallbackEvent,\n\t\texecute: async () => {\n\t\t\tlet output;\n\t\t\tawait notify({\n\t\t\t\tevent: baseCallbackEvent,\n\t\t\t\tcallbacks: onToolExecutionStart\n\t\t\t});\n\t\t\tconst toolAbortSignal = mergeAbortSignals(abortSignal, getToolTimeoutMs(timeout, toolName));\n\t\t\tlet toolExecutionMs = 0;\n\t\t\ttry {\n\t\t\t\tawait executeToolInTelemetryContext({\n\t\t\t\t\tcallId,\n\t\t\t\t\ttoolCallId,\n\t\t\t\t\t...toolExecutionContext,\n\t\t\t\t\texecute: async () => {\n\t\t\t\t\t\tconst startTime = now();\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst stream = executeTool({\n\t\t\t\t\t\t\t\ttool,\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\t\t\tabortSignal: toolAbortSignal,\n\t\t\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\t\t\texperimental_sandbox: sandbox\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tfor await (const part of stream) if (part.type === \"preliminary\") onPreliminaryToolResult?.({\n\t\t\t\t\t\t\t\t...toolCall,\n\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\t\tpreliminary: true\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\telse output = part.output;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\ttoolExecutionMs = now() - startTime;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconst toolError = {\n\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\ttoolCallId,\n\t\t\t\t\ttoolName,\n\t\t\t\t\tinput,\n\t\t\t\t\terror,\n\t\t\t\t\tdynamic: tool.type === \"dynamic\",\n\t\t\t\t\t...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {},\n\t\t\t\t\t...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t\t};\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\t...baseCallbackEvent,\n\t\t\t\t\t\ttoolOutput: toolError,\n\t\t\t\t\t\ttoolExecutionMs\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: onToolExecutionEnd\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\toutput: toolError,\n\t\t\t\t\ttoolExecutionMs\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst toolResult = {\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId,\n\t\t\t\ttoolName,\n\t\t\t\tinput,\n\t\t\t\toutput,\n\t\t\t\tdynamic: tool.type === \"dynamic\",\n\t\t\t\t...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {},\n\t\t\t\t...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t};\n\t\t\tawait notify({\n\t\t\t\tevent: {\n\t\t\t\t\t...baseCallbackEvent,\n\t\t\t\t\ttoolOutput: toolResult,\n\t\t\t\t\ttoolExecutionMs\n\t\t\t\t},\n\t\t\t\tcallbacks: onToolExecutionEnd\n\t\t\t});\n\t\t\treturn {\n\t\t\t\toutput: toolResult,\n\t\t\t\ttoolExecutionMs\n\t\t\t};\n\t\t}\n\t});\n}\n//#endregion\n//#region src/generate-text/filter-active-tools.ts\n/**\n* Filters the tools to only include the active tools.\n* When activeTools is provided, we only include the tools that are in the list.\n*\n* @param tools - The tools to filter.\n* @param activeTools - The active tools to include.\n* @returns The filtered tools.\n*/\nfunction filterActiveTools({ tools, activeTools }) {\n\tif (tools == null || activeTools == null) return tools;\n\treturn Object.fromEntries(Object.entries(tools).filter(([name]) => activeTools.includes(name)));\n}\n//#endregion\n//#region src/generate-text/reasoning-output.ts\nfunction unwrapReasoningFileData(data) {\n\tif (typeof data === \"object\" && data !== null && \"type\" in data) return data.type === \"data\" ? data.data : data.url;\n\treturn data;\n}\nfunction convertFromReasoningOutputs(parts) {\n\treturn parts.map((part) => {\n\t\tif (part.type === \"reasoning\") return {\n\t\t\ttype: \"reasoning\",\n\t\t\ttext: part.text,\n\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t};\n\t\treturn {\n\t\t\ttype: \"reasoning-file\",\n\t\t\tdata: part.file.base64,\n\t\t\tmediaType: part.file.mediaType,\n\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t};\n\t});\n}\nfunction convertToReasoningOutputs(parts) {\n\treturn parts.map((part) => {\n\t\tif (part.type === \"reasoning\") return {\n\t\t\ttype: \"reasoning\",\n\t\t\ttext: part.text,\n\t\t\t...part.providerOptions != null ? { providerMetadata: part.providerOptions } : {}\n\t\t};\n\t\tconst rawData = unwrapReasoningFileData(part.data);\n\t\treturn {\n\t\t\ttype: \"reasoning-file\",\n\t\t\tfile: new DefaultGeneratedFile({\n\t\t\t\tdata: rawData instanceof ArrayBuffer ? new Uint8Array(rawData) : rawData instanceof URL ? rawData.toString() : rawData,\n\t\t\t\tmediaType: part.mediaType\n\t\t\t}),\n\t\t\t...part.providerOptions != null ? { providerMetadata: part.providerOptions } : {}\n\t\t};\n\t});\n}\n//#endregion\n//#region src/generate-text/default-generate-text-result.ts\nvar DefaultGenerateTextResult = class {\n\tconstructor(options) {\n\t\tthis.initialResponseMessages = options.initialResponseMessages;\n\t\tthis.steps = options.steps;\n\t\tthis._output = options.output;\n\t\tthis.totalUsage = options.totalUsage;\n\t}\n\tget finalStep() {\n\t\treturn this.steps.at(-1);\n\t}\n\tget content() {\n\t\treturn this.steps.flatMap((step) => step.content);\n\t}\n\tget text() {\n\t\treturn this.finalStep.text;\n\t}\n\tget files() {\n\t\treturn this.steps.flatMap((step) => step.files);\n\t}\n\tget reasoningText() {\n\t\treturn this.finalStep.reasoningText;\n\t}\n\tget reasoning() {\n\t\treturn convertToReasoningOutputs(this.finalStep.reasoning);\n\t}\n\tget toolCalls() {\n\t\treturn this.steps.flatMap((step) => step.toolCalls);\n\t}\n\tget staticToolCalls() {\n\t\treturn this.steps.flatMap((step) => step.staticToolCalls);\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.steps.flatMap((step) => step.dynamicToolCalls);\n\t}\n\tget toolResults() {\n\t\treturn this.steps.flatMap((step) => step.toolResults);\n\t}\n\tget staticToolResults() {\n\t\treturn this.steps.flatMap((step) => step.staticToolResults);\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.steps.flatMap((step) => step.dynamicToolResults);\n\t}\n\tget sources() {\n\t\treturn this.steps.flatMap((step) => step.sources);\n\t}\n\tget finishReason() {\n\t\treturn this.finalStep.finishReason;\n\t}\n\tget rawFinishReason() {\n\t\treturn this.finalStep.rawFinishReason;\n\t}\n\tget warnings() {\n\t\treturn this.steps.flatMap((step) => step.warnings ?? []);\n\t}\n\tget providerMetadata() {\n\t\treturn this.finalStep.providerMetadata;\n\t}\n\tget response() {\n\t\treturn this.finalStep.response;\n\t}\n\tget responseMessages() {\n\t\treturn [...this.initialResponseMessages, ...this.steps.flatMap((step) => step.response.messages)];\n\t}\n\tget request() {\n\t\treturn this.finalStep.request;\n\t}\n\tget usage() {\n\t\treturn this.totalUsage;\n\t}\n\tget output() {\n\t\tif (this._output == null) throw new NoOutputGeneratedError();\n\t\treturn this._output;\n\t}\n};\n//#endregion\n//#region src/generate-text/is-tool-execution-allowed-finish-reason.ts\nfunction isToolExecutionAllowedFinishReason(finishReason) {\n\treturn finishReason === \"stop\" || finishReason === \"tool-calls\";\n}\n//#endregion\n//#region src/util/fix-json.ts\nfunction fixJson(input) {\n\tconst stack = [\"ROOT\"];\n\tlet lastValidIndex = -1;\n\tlet literalStart = null;\n\tlet unicodeEscapeDigits = 0;\n\tfunction isHexDigit(char) {\n\t\treturn char >= \"0\" && char <= \"9\" || char >= \"A\" && char <= \"F\" || char >= \"a\" && char <= \"f\";\n\t}\n\tfunction processValueStart(char, i, swapState) {\n\t\tswitch (char) {\n\t\t\tcase \"\\\"\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_STRING\");\n\t\t\t\tbreak;\n\t\t\tcase \"f\":\n\t\t\tcase \"t\":\n\t\t\tcase \"n\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tliteralStart = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_LITERAL\");\n\t\t\t\tbreak;\n\t\t\tcase \"-\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_NUMBER\");\n\t\t\t\tbreak;\n\t\t\tcase \"0\":\n\t\t\tcase \"1\":\n\t\t\tcase \"2\":\n\t\t\tcase \"3\":\n\t\t\tcase \"4\":\n\t\t\tcase \"5\":\n\t\t\tcase \"6\":\n\t\t\tcase \"7\":\n\t\t\tcase \"8\":\n\t\t\tcase \"9\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_NUMBER\");\n\t\t\t\tbreak;\n\t\t\tcase \"{\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_OBJECT_START\");\n\t\t\t\tbreak;\n\t\t\tcase \"[\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_ARRAY_START\");\n\t\t}\n\t}\n\tfunction processAfterObjectValue(char, i) {\n\t\tswitch (char) {\n\t\t\tcase \",\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(\"INSIDE_OBJECT_AFTER_COMMA\");\n\t\t\t\tbreak;\n\t\t\tcase \"}\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t}\n\t}\n\tfunction processAfterArrayValue(char, i) {\n\t\tswitch (char) {\n\t\t\tcase \",\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n\t\t\t\tbreak;\n\t\t\tcase \"]\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t}\n\t}\n\tfor (let i = 0; i < input.length; i++) {\n\t\tconst char = input[i];\n\t\tswitch (stack[stack.length - 1]) {\n\t\t\tcase \"ROOT\":\n\t\t\t\tprocessValueStart(char, i, \"FINISH\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_START\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_KEY\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"}\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_COMMA\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_KEY\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_KEY\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_AFTER_KEY\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_KEY\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \":\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_BEFORE_VALUE\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_BEFORE_VALUE\":\n\t\t\t\tprocessValueStart(char, i, \"INSIDE_OBJECT_AFTER_VALUE\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_VALUE\":\n\t\t\t\tprocessAfterObjectValue(char, i);\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_STRING\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"\\\\\":\n\t\t\t\t\t\tstack.push(\"INSIDE_STRING_ESCAPE\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: lastValidIndex = i;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_START\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tprocessValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_AFTER_VALUE\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \",\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: lastValidIndex = i;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_AFTER_COMMA\":\n\t\t\t\tprocessValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_STRING_ESCAPE\":\n\t\t\t\tstack.pop();\n\t\t\t\tif (char === \"u\") {\n\t\t\t\t\tunicodeEscapeDigits = 0;\n\t\t\t\t\tstack.push(\"INSIDE_STRING_UNICODE_ESCAPE\");\n\t\t\t\t} else lastValidIndex = i;\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_STRING_UNICODE_ESCAPE\":\n\t\t\t\tif (isHexDigit(char)) {\n\t\t\t\t\tunicodeEscapeDigits++;\n\t\t\t\t\tif (unicodeEscapeDigits === 4) {\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_NUMBER\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"0\":\n\t\t\t\t\tcase \"1\":\n\t\t\t\t\tcase \"2\":\n\t\t\t\t\tcase \"3\":\n\t\t\t\t\tcase \"4\":\n\t\t\t\t\tcase \"5\":\n\t\t\t\t\tcase \"6\":\n\t\t\t\t\tcase \"7\":\n\t\t\t\t\tcase \"8\":\n\t\t\t\t\tcase \"9\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"e\":\n\t\t\t\t\tcase \"E\":\n\t\t\t\t\tcase \"-\":\n\t\t\t\t\tcase \".\": break;\n\t\t\t\t\tcase \",\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"}\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: stack.pop();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_LITERAL\": {\n\t\t\t\tconst partialLiteral = input.substring(literalStart, i + 1);\n\t\t\t\tif (!\"false\".startsWith(partialLiteral) && !\"true\".startsWith(partialLiteral) && !\"null\".startsWith(partialLiteral)) {\n\t\t\t\t\tstack.pop();\n\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\telse if (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t} else lastValidIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tlet result = input.slice(0, lastValidIndex + 1);\n\tfor (let i = stack.length - 1; i >= 0; i--) switch (stack[i]) {\n\t\tcase \"INSIDE_STRING\":\n\t\t\tresult += \"\\\"\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_OBJECT_KEY\":\n\t\tcase \"INSIDE_OBJECT_AFTER_KEY\":\n\t\tcase \"INSIDE_OBJECT_AFTER_COMMA\":\n\t\tcase \"INSIDE_OBJECT_START\":\n\t\tcase \"INSIDE_OBJECT_BEFORE_VALUE\":\n\t\tcase \"INSIDE_OBJECT_AFTER_VALUE\":\n\t\t\tresult += \"}\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_ARRAY_START\":\n\t\tcase \"INSIDE_ARRAY_AFTER_COMMA\":\n\t\tcase \"INSIDE_ARRAY_AFTER_VALUE\":\n\t\t\tresult += \"]\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_LITERAL\": {\n\t\t\tconst partialLiteral = input.substring(literalStart, input.length);\n\t\t\tif (\"true\".startsWith(partialLiteral)) result += \"true\".slice(partialLiteral.length);\n\t\t\telse if (\"false\".startsWith(partialLiteral)) result += \"false\".slice(partialLiteral.length);\n\t\t\telse if (\"null\".startsWith(partialLiteral)) result += \"null\".slice(partialLiteral.length);\n\t\t}\n\t}\n\treturn result;\n}\n//#endregion\n//#region src/util/parse-partial-json.ts\nasync function parsePartialJson(jsonText) {\n\tif (jsonText === void 0) return {\n\t\tvalue: void 0,\n\t\tstate: \"undefined-input\"\n\t};\n\tlet result = await safeParseJSON({ text: jsonText });\n\tif (result.success) return {\n\t\tvalue: result.value,\n\t\tstate: \"successful-parse\"\n\t};\n\tresult = await safeParseJSON({ text: fixJson(jsonText) });\n\tif (result.success) return {\n\t\tvalue: result.value,\n\t\tstate: \"repaired-parse\"\n\t};\n\treturn {\n\t\tvalue: void 0,\n\t\tstate: \"failed-parse\"\n\t};\n}\n//#endregion\n//#region src/generate-text/output.ts\nvar output_exports = /* @__PURE__ */ __exportAll({\n\tarray: () => array$1,\n\tchoice: () => choice,\n\tjson: () => json,\n\tobject: () => object$1,\n\ttext: () => text\n});\n/**\n* Output specification for text generation.\n* This is the default output mode that generates plain text.\n*\n* @returns An output specification for generating text.\n*/\nconst text = () => ({\n\tname: \"text\",\n\tresponseFormat: Promise.resolve({ type: \"text\" }),\n\tasync parseCompleteOutput({ text }) {\n\t\treturn text;\n\t},\n\tasync parsePartialOutput({ text }) {\n\t\treturn { partial: text };\n\t},\n\tcreateElementStreamTransform() {}\n});\n/**\n* Output specification for typed object generation using schemas.\n* When the model generates a text response, it will return an object that matches the schema.\n*\n* @param schema - The schema of the object to generate.\n* @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n* @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n*\n* @returns An output specification for generating objects with the specified schema.\n*/\nconst object$1 = ({ schema: inputSchema, name, description }) => {\n\tconst schema = asSchema$1(inputSchema);\n\treturn {\n\t\tname: \"object\",\n\t\tresponseFormat: resolve(schema.jsonSchema).then((jsonSchema) => ({\n\t\t\ttype: \"json\",\n\t\t\tschema: jsonSchema,\n\t\t\t...name != null && { name },\n\t\t\t...description != null && { description }\n\t\t})),\n\t\tasync parseCompleteOutput({ text }, context) {\n\t\t\tconst parseResult = await safeParseJSON({ text });\n\t\t\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: could not parse the response.\",\n\t\t\t\tcause: parseResult.error,\n\t\t\t\ttext,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\tconst validationResult = await safeValidateTypes({\n\t\t\t\tvalue: parseResult.value,\n\t\t\t\tschema\n\t\t\t});\n\t\t\tif (!validationResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\tcause: validationResult.error,\n\t\t\t\ttext,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\treturn validationResult.value;\n\t\t},\n\t\tasync parsePartialOutput({ text }) {\n\t\t\tconst result = await parsePartialJson(text);\n\t\t\tswitch (result.state) {\n\t\t\t\tcase \"failed-parse\":\n\t\t\t\tcase \"undefined-input\": return;\n\t\t\t\tcase \"repaired-parse\":\n\t\t\t\tcase \"successful-parse\": return { partial: result.value };\n\t\t\t}\n\t\t},\n\t\tcreateElementStreamTransform() {}\n\t};\n};\n/**\n* Output specification for array generation.\n* When the model generates a text response, it will return an array of elements.\n*\n* @param element - The schema of the array elements to generate.\n* @param minItems - Optional minimum number of elements to generate.\n* @param maxItems - Optional maximum number of elements to generate.\n* @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n* @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n*\n* @returns An output specification for generating an array of elements.\n*/\nconst array$1 = ({ element: inputElementSchema, minItems, maxItems, name, description }) => {\n\tvalidateArrayBound({\n\t\tname: \"minItems\",\n\t\tvalue: minItems\n\t});\n\tvalidateArrayBound({\n\t\tname: \"maxItems\",\n\t\tvalue: maxItems\n\t});\n\tif (minItems != null && maxItems != null && minItems > maxItems) throw new InvalidArgumentError({\n\t\tparameter: \"minItems\",\n\t\tvalue: minItems,\n\t\tmessage: \"minItems must be less than or equal to maxItems\"\n\t});\n\tconst elementSchema = asSchema$1(inputElementSchema);\n\treturn {\n\t\tname: \"array\",\n\t\tresponseFormat: resolve(elementSchema.jsonSchema).then((jsonSchema) => {\n\t\t\tconst { $schema: _$schema, definitions, $defs, ...itemSchema } = jsonSchema;\n\t\t\treturn {\n\t\t\t\ttype: \"json\",\n\t\t\t\tschema: {\n\t\t\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\t\t\t...definitions != null && { definitions },\n\t\t\t\t\t...$defs != null && { $defs },\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { elements: {\n\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\titems: itemSchema,\n\t\t\t\t\t\t...minItems != null && { minItems },\n\t\t\t\t\t\t...maxItems != null && { maxItems }\n\t\t\t\t\t} },\n\t\t\t\t\trequired: [\"elements\"],\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t},\n\t\t\t\t...name != null && { name },\n\t\t\t\t...description != null && { description }\n\t\t\t};\n\t\t}),\n\t\tasync parseCompleteOutput({ text }, context) {\n\t\t\tconst parseResult = await safeParseJSON({ text });\n\t\t\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: could not parse the response.\",\n\t\t\t\tcause: parseResult.error,\n\t\t\t\ttext,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\tconst outerValue = parseResult.value;\n\t\t\tif (outerValue == null || typeof outerValue !== \"object\" || !(\"elements\" in outerValue) || !Array.isArray(outerValue.elements)) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\tcause: new TypeValidationError$1({\n\t\t\t\t\tvalue: outerValue,\n\t\t\t\t\tcause: \"response must be an object with an elements array\"\n\t\t\t\t}),\n\t\t\t\ttext,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\tconst lengthValidationError = getArrayLengthValidationError({\n\t\t\t\tvalue: outerValue.elements,\n\t\t\t\tminItems,\n\t\t\t\tmaxItems\n\t\t\t});\n\t\t\tif (lengthValidationError != null) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\tcause: lengthValidationError,\n\t\t\t\ttext,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\tconst validatedElements = [];\n\t\t\tfor (const element of outerValue.elements) {\n\t\t\t\tconst validationResult = await safeValidateTypes({\n\t\t\t\t\tvalue: element,\n\t\t\t\t\tschema: elementSchema\n\t\t\t\t});\n\t\t\t\tif (!validationResult.success) throw new NoObjectGeneratedError({\n\t\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\t\tcause: validationResult.error,\n\t\t\t\t\ttext,\n\t\t\t\t\tresponse: context.response,\n\t\t\t\t\tusage: context.usage,\n\t\t\t\t\tfinishReason: context.finishReason\n\t\t\t\t});\n\t\t\t\tvalidatedElements.push(validationResult.value);\n\t\t\t}\n\t\t\treturn validatedElements;\n\t\t},\n\t\tasync parsePartialOutput({ text }) {\n\t\t\tconst result = await parsePartialJson(text);\n\t\t\tswitch (result.state) {\n\t\t\t\tcase \"failed-parse\":\n\t\t\t\tcase \"undefined-input\": return;\n\t\t\t\tcase \"repaired-parse\":\n\t\t\t\tcase \"successful-parse\": {\n\t\t\t\t\tconst outerValue = result.value;\n\t\t\t\t\tif (outerValue == null || typeof outerValue !== \"object\" || !(\"elements\" in outerValue) || !Array.isArray(outerValue.elements)) return;\n\t\t\t\t\tconst rawElements = result.state === \"repaired-parse\" && outerValue.elements.length > 0 ? outerValue.elements.slice(0, -1) : outerValue.elements;\n\t\t\t\t\tconst parsedElements = [];\n\t\t\t\t\tfor (const rawElement of rawElements) {\n\t\t\t\t\t\tconst validationResult = await safeValidateTypes({\n\t\t\t\t\t\t\tvalue: rawElement,\n\t\t\t\t\t\t\tschema: elementSchema\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (validationResult.success) parsedElements.push(validationResult.value);\n\t\t\t\t\t}\n\t\t\t\t\treturn { partial: parsedElements };\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tcreateElementStreamTransform() {\n\t\t\tlet publishedElements = 0;\n\t\t\treturn new TransformStream({ transform({ partialOutput }, controller) {\n\t\t\t\tif (partialOutput != null) for (; publishedElements < partialOutput.length; publishedElements++) {\n\t\t\t\t\tif (maxItems != null && publishedElements >= maxItems) {\n\t\t\t\t\t\tcontroller.error(getArrayLengthValidationError({\n\t\t\t\t\t\t\tvalue: partialOutput,\n\t\t\t\t\t\t\tmaxItems\n\t\t\t\t\t\t}));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue(partialOutput[publishedElements]);\n\t\t\t\t}\n\t\t\t} });\n\t\t}\n\t};\n};\nfunction validateArrayBound({ name, value }) {\n\tif (value == null) return;\n\tif (!Number.isInteger(value)) throw new InvalidArgumentError({\n\t\tparameter: name,\n\t\tvalue,\n\t\tmessage: `${name} must be an integer`\n\t});\n\tif (value < 0) throw new InvalidArgumentError({\n\t\tparameter: name,\n\t\tvalue,\n\t\tmessage: `${name} must be greater than or equal to 0`\n\t});\n}\nfunction getArrayLengthValidationError({ value, minItems, maxItems }) {\n\tif (minItems != null && value.length < minItems) return new TypeValidationError$1({\n\t\tvalue,\n\t\tcause: `elements array must contain at least ${minItems} items`\n\t});\n\tif (maxItems != null && value.length > maxItems) return new TypeValidationError$1({\n\t\tvalue,\n\t\tcause: `elements array must contain at most ${maxItems} items`\n\t});\n}\n/**\n* Output specification for choice generation.\n* When the model generates a text response, it will return a one of the choice options.\n*\n* @param options - The available choices.\n* @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n* @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n*\n* @returns An output specification for generating a choice.\n*/\nconst choice = ({ options: choiceOptions, name, description }) => {\n\treturn {\n\t\tname: \"choice\",\n\t\tresponseFormat: Promise.resolve({\n\t\t\ttype: \"json\",\n\t\t\tschema: {\n\t\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { result: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tenum: choiceOptions\n\t\t\t\t} },\n\t\t\t\trequired: [\"result\"],\n\t\t\t\tadditionalProperties: false\n\t\t\t},\n\t\t\t...name != null && { name },\n\t\t\t...description != null && { description }\n\t\t}),\n\t\tasync parseCompleteOutput({ text }, context) {\n\t\t\tconst parseResult = await safeParseJSON({ text });\n\t\t\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: could not parse the response.\",\n\t\t\t\tcause: parseResult.error,\n\t\t\t\ttext,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\tconst outerValue = parseResult.value;\n\t\t\tif (outerValue == null || typeof outerValue !== \"object\" || !(\"result\" in outerValue) || typeof outerValue.result !== \"string\" || !choiceOptions.includes(outerValue.result)) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\tcause: new TypeValidationError$1({\n\t\t\t\t\tvalue: outerValue,\n\t\t\t\t\tcause: \"response must be an object that contains a choice value.\"\n\t\t\t\t}),\n\t\t\t\ttext,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\treturn outerValue.result;\n\t\t},\n\t\tasync parsePartialOutput({ text }) {\n\t\t\tconst result = await parsePartialJson(text);\n\t\t\tswitch (result.state) {\n\t\t\t\tcase \"failed-parse\":\n\t\t\t\tcase \"undefined-input\": return;\n\t\t\t\tcase \"repaired-parse\":\n\t\t\t\tcase \"successful-parse\": {\n\t\t\t\t\tconst outerValue = result.value;\n\t\t\t\t\tif (outerValue == null || typeof outerValue !== \"object\" || !(\"result\" in outerValue) || typeof outerValue.result !== \"string\") return;\n\t\t\t\t\tconst potentialMatches = choiceOptions.filter((choiceOption) => choiceOption.startsWith(outerValue.result));\n\t\t\t\t\tif (result.state === \"successful-parse\") return potentialMatches.includes(outerValue.result) ? { partial: outerValue.result } : void 0;\n\t\t\t\t\telse return potentialMatches.length === 1 ? { partial: potentialMatches[0] } : void 0;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tcreateElementStreamTransform() {}\n\t};\n};\n/**\n* Output specification for unstructured JSON generation.\n* When the model generates a text response, it will return a JSON object.\n*\n* @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n* @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n*\n* @returns An output specification for generating JSON.\n*/\nconst json = ({ name, description } = {}) => {\n\treturn {\n\t\tname: \"json\",\n\t\tresponseFormat: Promise.resolve({\n\t\t\ttype: \"json\",\n\t\t\t...name != null && { name },\n\t\t\t...description != null && { description }\n\t\t}),\n\t\tasync parseCompleteOutput({ text }, context) {\n\t\t\tconst parseResult = await safeParseJSON({ text });\n\t\t\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: could not parse the response.\",\n\t\t\t\tcause: parseResult.error,\n\t\t\t\ttext,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\treturn parseResult.value;\n\t\t},\n\t\tasync parsePartialOutput({ text }) {\n\t\t\tconst result = await parsePartialJson(text);\n\t\t\tswitch (result.state) {\n\t\t\t\tcase \"failed-parse\":\n\t\t\t\tcase \"undefined-input\": return;\n\t\t\t\tcase \"repaired-parse\":\n\t\t\t\tcase \"successful-parse\": return result.value === void 0 ? void 0 : { partial: result.value };\n\t\t\t}\n\t\t},\n\t\tcreateElementStreamTransform() {}\n\t};\n};\n//#endregion\n//#region src/generate-text/tool-call.ts\nconst inputSchemaInputSymbol = Symbol(\"ai-sdk-tool-call-input-schema-input\");\nfunction setToolCallInputSchemaInput(toolCall, inputSchemaInput) {\n\tObject.defineProperty(toolCall, inputSchemaInputSymbol, { value: inputSchemaInput });\n\treturn toolCall;\n}\nfunction getToolCallInputSchemaInput(toolCall) {\n\treturn inputSchemaInputSymbol in toolCall ? { value: toolCall[inputSchemaInputSymbol] } : void 0;\n}\n//#endregion\n//#region src/generate-text/parse-tool-call.ts\nasync function parseToolCall({ toolCall, tools, repairToolCall, refineToolInput, messages, instructions, abortSignal }) {\n\ttry {\n\t\tif (tools == null) {\n\t\t\tif (toolCall.providerExecuted && toolCall.dynamic) return await refineParsedToolCallInput({\n\t\t\t\ttoolCall: await parseProviderExecutedDynamicToolCall(toolCall),\n\t\t\t\trefineToolInput\n\t\t\t});\n\t\t\tthrow new NoSuchToolError({ toolName: toolCall.toolName });\n\t\t}\n\t\ttry {\n\t\t\treturn await refineParsedToolCallInput({\n\t\t\t\ttoolCall: await doParseToolCall({\n\t\t\t\t\ttoolCall,\n\t\t\t\t\ttools\n\t\t\t\t}),\n\t\t\t\trefineToolInput\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (repairToolCall == null || !(NoSuchToolError.isInstance(error) || InvalidToolInputError.isInstance(error))) throw error;\n\t\t\tlet repairedToolCall = null;\n\t\t\ttry {\n\t\t\t\tabortSignal?.throwIfAborted();\n\t\t\t\trepairedToolCall = await waitForPromiseWithAbortSignal({\n\t\t\t\t\tpromise: repairToolCall({\n\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\tinputSchema: async ({ toolName }) => {\n\t\t\t\t\t\t\tconst inputSchema = getOwn(tools, toolName)?.inputSchema;\n\t\t\t\t\t\t\treturn await asSchema$1(inputSchema).jsonSchema;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tinstructions,\n\t\t\t\t\t\tsystem: instructions,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tabortSignal\n\t\t\t\t\t}),\n\t\t\t\t\tabortSignal\n\t\t\t\t});\n\t\t\t} catch (repairError) {\n\t\t\t\tabortSignal?.throwIfAborted();\n\t\t\t\tthrow new ToolCallRepairError({\n\t\t\t\t\tcause: repairError,\n\t\t\t\t\toriginalError: error\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (repairedToolCall == null) throw error;\n\t\t\tconst parsedRepairedToolCall = await refineParsedToolCallInput({\n\t\t\t\ttoolCall: await doParseToolCall({\n\t\t\t\t\ttoolCall: repairedToolCall,\n\t\t\t\t\ttools\n\t\t\t\t}),\n\t\t\t\trefineToolInput\n\t\t\t});\n\t\t\tabortSignal?.throwIfAborted();\n\t\t\treturn parsedRepairedToolCall;\n\t\t}\n\t} catch (error) {\n\t\tabortSignal?.throwIfAborted();\n\t\tconst parsedInput = await safeParseJSON({ text: toolCall.input });\n\t\tconst input = parsedInput.success ? parsedInput.value : toolCall.input;\n\t\tconst tool = getOwn(tools, toolCall.toolName);\n\t\treturn {\n\t\t\ttype: \"tool-call\",\n\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\ttoolName: toolCall.toolName,\n\t\t\tinput,\n\t\t\tdynamic: true,\n\t\t\tinvalid: true,\n\t\t\terror,\n\t\t\ttitle: tool?.title,\n\t\t\tproviderExecuted: toolCall.providerExecuted,\n\t\t\tproviderMetadata: toolCall.providerMetadata,\n\t\t\t...tool?.metadata != null ? { toolMetadata: tool.metadata } : {}\n\t\t};\n\t}\n}\nasync function waitForPromiseWithAbortSignal({ promise, abortSignal }) {\n\tif (abortSignal == null) return await promise;\n\treturn await new Promise((resolve, reject) => {\n\t\tconst cleanup = () => {\n\t\t\tabortSignal.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tcleanup();\n\t\t\treject(abortSignal.reason);\n\t\t};\n\t\tPromise.resolve(promise).then((value) => {\n\t\t\tcleanup();\n\t\t\tresolve(value);\n\t\t}).catch((error) => {\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t});\n\t\tabortSignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tif (abortSignal.aborted) onAbort();\n\t});\n}\nasync function refineParsedToolCallInput({ toolCall, refineToolInput }) {\n\tconst refine = getOwn(refineToolInput, toolCall.toolName);\n\tif (refine == null) return toolCall;\n\tconst refinedToolCall = {\n\t\t...toolCall,\n\t\tinput: await refine(toolCall.input)\n\t};\n\tconst inputSchemaInput = getToolCallInputSchemaInput(toolCall);\n\treturn inputSchemaInput == null ? refinedToolCall : setToolCallInputSchemaInput(refinedToolCall, inputSchemaInput.value);\n}\nasync function parseProviderExecutedDynamicToolCall(toolCall) {\n\tconst parseResult = toolCall.input.trim() === \"\" ? {\n\t\tsuccess: true,\n\t\tvalue: {}\n\t} : await safeParseJSON({ text: toolCall.input });\n\tif (parseResult.success === false) throw new InvalidToolInputError({\n\t\ttoolName: toolCall.toolName,\n\t\ttoolInput: toolCall.input,\n\t\tcause: parseResult.error\n\t});\n\treturn {\n\t\ttype: \"tool-call\",\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName: toolCall.toolName,\n\t\tinput: parseResult.value,\n\t\tproviderExecuted: true,\n\t\tdynamic: true,\n\t\tproviderMetadata: toolCall.providerMetadata\n\t};\n}\nasync function doParseToolCall({ toolCall, tools }) {\n\tconst toolName = toolCall.toolName;\n\tconst tool = getOwn(tools, toolName);\n\tif (tool == null) {\n\t\tif (toolCall.providerExecuted && toolCall.dynamic) return await parseProviderExecutedDynamicToolCall(toolCall);\n\t\tthrow new NoSuchToolError({\n\t\t\ttoolName: toolCall.toolName,\n\t\t\tavailableTools: Object.keys(tools)\n\t\t});\n\t}\n\tconst schema = asSchema$1(tool.inputSchema);\n\tconst parseResult = toolCall.input.trim() === \"\" ? await safeValidateTypes({\n\t\tvalue: {},\n\t\tschema\n\t}) : await safeParseJSON({\n\t\ttext: toolCall.input,\n\t\tschema\n\t});\n\tif (parseResult.success === false) throw new InvalidToolInputError({\n\t\ttoolName,\n\t\ttoolInput: toolCall.input,\n\t\tcause: parseResult.error\n\t});\n\treturn setToolCallInputSchemaInput(tool.type === \"dynamic\" ? {\n\t\ttype: \"tool-call\",\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName: toolCall.toolName,\n\t\tinput: parseResult.value,\n\t\tproviderExecuted: toolCall.providerExecuted,\n\t\tproviderMetadata: toolCall.providerMetadata,\n\t\t...tool.metadata != null ? { toolMetadata: tool.metadata } : {},\n\t\tdynamic: true,\n\t\ttitle: tool.title\n\t} : {\n\t\ttype: \"tool-call\",\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName,\n\t\tinput: parseResult.value,\n\t\tproviderExecuted: toolCall.providerExecuted,\n\t\tproviderMetadata: toolCall.providerMetadata,\n\t\t...tool.metadata != null ? { toolMetadata: tool.metadata } : {},\n\t\ttitle: tool.title\n\t}, parseResult.rawValue);\n}\n//#endregion\n//#region src/generate-text/prepare-step-call-settings.ts\n/**\n* Resolves model call settings for a single step.\n*\n* Undefined step settings intentionally fall back to the outer call settings,\n* while defined falsy values such as `temperature: 0` and `seed: 0` are kept.\n*/\nfunction prepareStepCallSettings({ callSettings, stepSettings }) {\n\treturn prepareLanguageModelCallOptions({\n\t\tmaxOutputTokens: stepSettings?.maxOutputTokens ?? callSettings.maxOutputTokens,\n\t\ttemperature: stepSettings?.temperature ?? callSettings.temperature,\n\t\ttopP: stepSettings?.topP ?? callSettings.topP,\n\t\ttopK: stepSettings?.topK ?? callSettings.topK,\n\t\tpresencePenalty: stepSettings?.presencePenalty ?? callSettings.presencePenalty,\n\t\tfrequencyPenalty: stepSettings?.frequencyPenalty ?? callSettings.frequencyPenalty,\n\t\tstopSequences: stepSettings?.stopSequences ?? callSettings.stopSequences,\n\t\tseed: stepSettings?.seed ?? callSettings.seed,\n\t\treasoning: stepSettings?.reasoning ?? callSettings.reasoning\n\t});\n}\n//#endregion\n//#region src/generate-text/resolve-tool-approval.ts\n/**\n* Resolves the approval state for a tool call by checking user-supplied and tool-defined\n* approval settings, and normalizes the result to the object status shape.\n* User-defined approval settings take precedence over tool-defined settings.\n* If no approval settings are provided, the tool call does not require approval.\n*/\nasync function resolveToolApproval({ tools, toolCall, toolApproval, messages, toolsContext, runtimeContext }) {\n\tif (toolApproval != null && typeof toolApproval === \"function\") return normalizeToolApprovalStatus(await toolApproval({\n\t\ttoolCall,\n\t\ttools,\n\t\ttoolsContext,\n\t\tmessages,\n\t\truntimeContext\n\t}));\n\tconst toolName = toolCall.toolName;\n\tconst tool = getOwn(tools, toolName);\n\tconst input = toolCall.input;\n\tconst userDefinedToolApprovalStatus = getOwn(toolApproval, toolName);\n\tif (userDefinedToolApprovalStatus != null) return normalizeToolApprovalStatus(typeof userDefinedToolApprovalStatus === \"function\" ? await userDefinedToolApprovalStatus(input, {\n\t\ttoolCallId: toolCall.toolCallId,\n\t\tmessages,\n\t\ttoolContext: await validateToolContext({\n\t\t\ttoolName,\n\t\t\tcontext: getOwn(toolsContext, toolName),\n\t\t\tcontextSchema: tool?.contextSchema\n\t\t}),\n\t\truntimeContext\n\t}) : userDefinedToolApprovalStatus);\n\tif (tool?.needsApproval == null) return { type: \"not-applicable\" };\n\treturn (typeof tool.needsApproval === \"function\" ? await tool.needsApproval(input, {\n\t\ttoolCallId: toolCall.toolCallId,\n\t\tmessages,\n\t\tcontext: await validateToolContext({\n\t\t\ttoolName,\n\t\t\tcontext: getOwn(toolsContext, toolName),\n\t\t\tcontextSchema: tool?.contextSchema\n\t\t})\n\t}) : tool.needsApproval) ? { type: \"user-approval\" } : { type: \"not-applicable\" };\n}\nfunction normalizeToolApprovalStatus(status) {\n\treturn status === void 0 ? { type: \"not-applicable\" } : typeof status === \"string\" ? { type: status } : status;\n}\n//#endregion\n//#region src/telemetry/filter-included-context.ts\n/**\n* Returns a shallow copy of the runtime context with only top-level\n* properties marked for telemetry inclusion.\n*/\nfunction filterIncludedContext({ context, includeContext }) {\n\tif (context == null) return {};\n\treturn Object.fromEntries(Object.entries(context).filter(([key]) => includeContext?.[key] === true));\n}\nfunction filterToolsContext({ toolsContext, includeToolsContext }) {\n\tif (includeToolsContext == null) return {};\n\treturn Object.fromEntries(Object.entries(toolsContext).map(([toolName, toolContext]) => [toolName, filterToolContext({\n\t\ttoolName,\n\t\ttoolContext,\n\t\tincludeToolsContext\n\t})]));\n}\nfunction filterToolContext({ toolName, toolContext, includeToolsContext }) {\n\tconst includeToolContext = includeToolsContext?.[toolName];\n\treturn filterIncludedContext({\n\t\tcontext: toolContext,\n\t\tincludeContext: includeToolContext\n\t});\n}\n//#endregion\n//#region src/util/merge-callbacks.ts\n/**\n* Creates an async callback that invokes the provided callbacks in parallel.\n* Undefined callbacks are skipped, and thrown or rejected callback errors are\n* ignored.\n*\n* @param callbacks The callbacks to invoke for each event.\n* @returns A callback that forwards each event to all callbacks and waits for\n* them to settle.\n*/\nfunction mergeCallbacks(...callbacks) {\n\treturn async (event) => {\n\t\tawait Promise.allSettled(callbacks.map(async (callback) => {\n\t\t\tawait callback?.(event);\n\t\t}));\n\t};\n}\n//#endregion\n//#region src/telemetry/tracing-channel.ts\nconst AI_SDK_TELEMETRY_TRACING_CHANNEL = \"ai:telemetry\";\n//#endregion\n//#region src/util/is-node-runtime.ts\nfunction isNodeRuntime() {\n\treturn typeof process !== \"undefined\" && process.release?.name === \"node\";\n}\n//#endregion\n//#region src/telemetry/tracing-channel-publisher.ts\nlet diagnosticsChannelPromise;\n/**\n* Loads Node's diagnostics channel module only when the current runtime supports\n* it. Unsupported runtimes and failed imports intentionally resolve to\n* undefined so telemetry tracing never crashes user code.\n*/\nasync function loadDiagnosticsChannel() {\n\tif (!isNodeRuntime()) return;\n\tif (diagnosticsChannelPromise == null) diagnosticsChannelPromise = Promise.resolve(loadBuiltinModule(\"node:diagnostics_channel\"));\n\treturn diagnosticsChannelPromise;\n}\nfunction loadBuiltinModule(id) {\n\tconst processWithBuiltins = globalThis.process;\n\ttry {\n\t\treturn processWithBuiltins?.getBuiltinModule?.(id);\n\t} catch {\n\t\treturn;\n\t}\n}\n/**\n* Runs an async operation inside the AI SDK telemetry tracing channel when\n* tracing subscribers may exist. Without Node diagnostics-channel support,\n* without tracingChannel support, or when the runtime reports no subscribers,\n* this is a direct pass-through.\n*\n* The execution bookkeeping preserves the original model/tool result or error\n* if tracing itself throws, and prevents falling back by calling `execute` a\n* second time.\n*/\nasync function runWithTracingChannelSpan(message, execute) {\n\tconst tracingChannel = (await loadDiagnosticsChannel())?.tracingChannel?.(AI_SDK_TELEMETRY_TRACING_CHANNEL);\n\tif (tracingChannel == null || tracingChannel.hasSubscribers === false) return await execute();\n\tlet executePromise;\n\tlet executionResult;\n\tlet executionError;\n\tlet hasExecutionResult = false;\n\tlet hasExecutionError = false;\n\tconst tracedExecute = () => {\n\t\ttry {\n\t\t\texecutePromise = Promise.resolve(execute());\n\t\t} catch (error) {\n\t\t\texecutePromise = Promise.reject(error);\n\t\t}\n\t\texecutePromise = executePromise.then((result) => {\n\t\t\texecutionResult = result;\n\t\t\thasExecutionResult = true;\n\t\t\treturn result;\n\t\t}, (error) => {\n\t\t\texecutionError = error;\n\t\t\thasExecutionError = true;\n\t\t\tthrow error;\n\t\t});\n\t\treturn executePromise;\n\t};\n\ttry {\n\t\treturn await tracingChannel.tracePromise(tracedExecute, message);\n\t} catch {\n\t\tif (hasExecutionError) throw executionError;\n\t\tif (hasExecutionResult) return executionResult;\n\t\tif (executePromise != null) return await executePromise;\n\t\treturn await execute();\n\t}\n}\n/**\n* Opens a long-lived tracing-channel span context and returns a runner that can\n* re-enter that context later without changing stream setup timing.\n*/\nfunction openTelemetryChannelSpanContext({ message, completion }) {\n\tif (!isNodeRuntime()) {\n\t\tPromise.resolve(completion).catch(() => {});\n\t\treturn;\n\t}\n\tconst diagnosticsChannel = loadBuiltinModule(\"node:diagnostics_channel\");\n\tconst asyncHooks = loadBuiltinModule(\"node:async_hooks\");\n\tconst tracingChannel = diagnosticsChannel?.tracingChannel?.(AI_SDK_TELEMETRY_TRACING_CHANNEL);\n\tif (tracingChannel == null || tracingChannel.hasSubscribers === false || asyncHooks == null) {\n\t\tPromise.resolve(completion).catch(() => {});\n\t\treturn;\n\t}\n\tconst context = message;\n\tlet asyncResource;\n\tlet asyncEndPublished = false;\n\tconst safePublish = (publish) => {\n\t\ttry {\n\t\t\tpublish();\n\t\t} catch {}\n\t};\n\tconst publishAsyncEnd = ({ result, error }) => {\n\t\tif (asyncEndPublished) return;\n\t\tasyncEndPublished = true;\n\t\tif (error !== void 0) {\n\t\t\tcontext.error = error;\n\t\t\tsafePublish(() => tracingChannel.error.publish(context));\n\t\t}\n\t\tif (result !== void 0) context.result = result;\n\t\tsafePublish(() => tracingChannel.asyncEnd.publish(context));\n\t};\n\tsafePublish(() => {\n\t\ttracingChannel.start.runStores(context, () => {\n\t\t\tasyncResource = new asyncHooks.AsyncResource(\"ai.telemetry\");\n\t\t});\n\t});\n\tsafePublish(() => tracingChannel.end.publish(context));\n\tPromise.resolve(completion).then((result) => publishAsyncEnd({ result }), (error) => publishAsyncEnd({ error }));\n\treturn { run: (execute) => asyncResource == null ? execute() : asyncResource.runInAsyncScope(execute) };\n}\n//#endregion\n//#region src/telemetry/telemetry-registry.ts\n/**\n* Registers one or more telemetry integrations globally.\n*/\nfunction registerTelemetry(...integrations) {\n\tif (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];\n\tglobalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(...integrations);\n}\nfunction getGlobalTelemetryIntegrations() {\n\treturn globalThis.AI_SDK_TELEMETRY_INTEGRATIONS ?? [];\n}\n//#endregion\n//#region src/telemetry/create-telemetry-dispatcher.ts\nfunction augmentEvent(event, telemetry, filterContext = false) {\n\tconst augmentedEvent = Object.assign(Object.create(Object.getPrototypeOf(event)), event, {\n\t\trecordInputs: telemetry.recordInputs,\n\t\trecordOutputs: telemetry.recordOutputs,\n\t\tfunctionId: telemetry.functionId\n\t});\n\tif (filterContext && event != null && typeof event === \"object\" && \"runtimeContext\" in event) augmentedEvent.runtimeContext = filterIncludedContext({\n\t\tcontext: event.runtimeContext,\n\t\tincludeContext: telemetry.includeRuntimeContext\n\t});\n\tif (filterContext && event != null && typeof event === \"object\") {\n\t\tif (\"toolsContext\" in event) augmentedEvent.toolsContext = filterToolsContext({\n\t\t\ttoolsContext: event.toolsContext,\n\t\t\tincludeToolsContext: telemetry.includeToolsContext\n\t\t});\n\t\telse if (\"toolContext\" in event && event.toolContext != null && \"toolCall\" in event && event.toolCall != null && typeof event.toolCall === \"object\" && \"toolName\" in event.toolCall) augmentedEvent.toolContext = filterToolContext({\n\t\t\ttoolName: event.toolCall.toolName,\n\t\t\ttoolContext: event.toolContext,\n\t\t\tincludeToolsContext: telemetry.includeToolsContext\n\t\t});\n\t}\n\treturn augmentedEvent;\n}\n/**\n* Creates a telemetry dispatcher that sends telemetry events\n* to the resolved set of integrations.\n*\n* When per-call integrations are provided, they take precedence over the globally\n* registered integrations for that call. When no per-call integrations are\n* provided, the globally registered integrations are used.\n*\n* @param args.telemetry - Optional per-call telemetry settings and integrations.\n*\n* @returns A telemetry dispatcher that fans out lifecycle events to the\n* resolved set of integrations.\n*/\nfunction createTelemetryDispatcher({ telemetry }) {\n\tif (telemetry?.isEnabled === false) return {};\n\tconst localIntegrations = telemetry?.integrations;\n\tconst integrations = localIntegrations != null ? asArray(localIntegrations) : getGlobalTelemetryIntegrations();\n\tconst telemetryMetadata = {\n\t\trecordInputs: telemetry?.recordInputs,\n\t\trecordOutputs: telemetry?.recordOutputs,\n\t\tfunctionId: telemetry?.functionId,\n\t\tincludeRuntimeContext: telemetry?.includeRuntimeContext,\n\t\tincludeToolsContext: telemetry?.includeToolsContext\n\t};\n\tconst mergeTelemetryCallback = (key, deprecatedKey) => {\n\t\tconst integrationCallbacks = integrations.map((integration) => {\n\t\t\tconst callback = integration[key] ?? (deprecatedKey == null ? void 0 : integration[deprecatedKey]);\n\t\t\treturn typeof callback === \"function\" ? callback.bind(integration) : void 0;\n\t\t}).filter(Boolean).map((callback) => ((event) => callback(augmentEvent(event, telemetryMetadata))));\n\t\tif (integrationCallbacks.length === 0) return;\n\t\tconst mergedIntegrationCallback = mergeCallbacks(...integrationCallbacks);\n\t\treturn async (event) => {\n\t\t\tawait mergedIntegrationCallback(event);\n\t\t};\n\t};\n\tconst onStepEnd = mergeTelemetryCallback(\"onStepEnd\");\n\tconst onStepFinish = mergeTelemetryCallback(\"onStepFinish\");\n\tconst executeLanguageModelCallWrappers = integrations.map((integration) => integration.executeLanguageModelCall?.bind(integration)).filter(Boolean);\n\tconst executeToolWrappers = integrations.map((integration) => integration.executeTool?.bind(integration)).filter(Boolean);\n\treturn {\n\t\trunInTracingChannelSpan: async ({ type, event, execute }) => await runWithTracingChannelSpan({\n\t\t\ttype,\n\t\t\tevent: augmentEvent(event, telemetryMetadata, true)\n\t\t}, execute),\n\t\tstartTracingChannelContext: ({ type, event, completion }) => openTelemetryChannelSpanContext({\n\t\t\tmessage: {\n\t\t\t\ttype,\n\t\t\t\tevent: augmentEvent(event, telemetryMetadata, true)\n\t\t\t},\n\t\t\tcompletion\n\t\t}),\n\t\tonStart: mergeTelemetryCallback(\"onStart\"),\n\t\tonStepStart: mergeTelemetryCallback(\"onStepStart\"),\n\t\tonLanguageModelCallStart: mergeTelemetryCallback(\"onLanguageModelCallStart\"),\n\t\tonLanguageModelCallEnd: mergeTelemetryCallback(\"onLanguageModelCallEnd\"),\n\t\tonToolExecutionStart: mergeTelemetryCallback(\"onToolExecutionStart\"),\n\t\tonToolExecutionEnd: mergeTelemetryCallback(\"onToolExecutionEnd\"),\n\t\tonStepEnd: onStepEnd == null && onStepFinish == null ? void 0 : mergeCallbacks(onStepEnd, onStepFinish),\n\t\tonObjectStepStart: mergeTelemetryCallback(\"onObjectStepStart\"),\n\t\tonObjectStepEnd: mergeTelemetryCallback(\"onObjectStepEnd\"),\n\t\tonEmbedStart: mergeTelemetryCallback(\"onEmbedStart\"),\n\t\tonEmbedEnd: mergeTelemetryCallback(\"onEmbedEnd\"),\n\t\tonRerankStart: mergeTelemetryCallback(\"onRerankStart\"),\n\t\tonRerankEnd: mergeTelemetryCallback(\"onRerankEnd\"),\n\t\texperimental_onDecideStart: mergeTelemetryCallback(\"experimental_onDecideStart\", \"experimental_onEvaluateStart\"),\n\t\texperimental_onDecisionModelCallStart: mergeTelemetryCallback(\"experimental_onDecisionModelCallStart\", \"experimental_onEvaluationModelCallStart\"),\n\t\texperimental_onDecisionModelCallEnd: mergeTelemetryCallback(\"experimental_onDecisionModelCallEnd\", \"experimental_onEvaluationModelCallEnd\"),\n\t\texperimental_onDecideEnd: mergeTelemetryCallback(\"experimental_onDecideEnd\", \"experimental_onEvaluateEnd\"),\n\t\texperimental_onStreamTranscriptionStart: mergeTelemetryCallback(\"experimental_onStreamTranscriptionStart\"),\n\t\texperimental_onStreamTranscriptionEnd: mergeTelemetryCallback(\"experimental_onStreamTranscriptionEnd\"),\n\t\tonEnd: mergeTelemetryCallback(\"onEnd\"),\n\t\tonAbort: mergeTelemetryCallback(\"onAbort\"),\n\t\tonError: mergeTelemetryCallback(\"onError\"),\n\t\t/**\n\t\t* Runs provider calls inside integration-specific context so\n\t\t* auto-instrumented provider requests can be associated with model work.\n\t\t*/\n\t\texecuteLanguageModelCall: async ({ execute, ...event }) => {\n\t\t\tconst augmentedEvent = augmentEvent(event, telemetryMetadata);\n\t\t\tlet wrappedExecute = execute;\n\t\t\tfor (const executeWrapper of executeLanguageModelCallWrappers) {\n\t\t\t\tconst innerExecute = wrappedExecute;\n\t\t\t\twrappedExecute = () => executeWrapper({\n\t\t\t\t\t...augmentedEvent,\n\t\t\t\t\texecute: innerExecute\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn await runWithTracingChannelSpan({\n\t\t\t\ttype: \"languageModelCall\",\n\t\t\t\tevent: augmentedEvent\n\t\t\t}, wrappedExecute);\n\t\t},\n\t\t/**\n\t\t* Composes all `executeTool` wrappers around the original tool execution.\n\t\t* Each wrapper receives an `execute` function that calls the next wrapper in\n\t\t* the chain, so integrations can establish nested telemetry context before\n\t\t* delegating to the underlying tool.\n\t\t*/\n\t\texecuteTool: async ({ execute, ...event }) => {\n\t\t\tconst augmentedEvent = augmentEvent(event, telemetryMetadata);\n\t\t\tlet wrappedExecute = execute;\n\t\t\tfor (const executeWrapper of executeToolWrappers) {\n\t\t\t\tconst innerExecute = wrappedExecute;\n\t\t\t\twrappedExecute = () => executeWrapper({\n\t\t\t\t\t...augmentedEvent,\n\t\t\t\t\texecute: innerExecute\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn await wrappedExecute();\n\t\t}\n\t};\n}\n//#endregion\n//#region src/generate-text/reasoning.ts\nfunction asReasoningText(reasoningParts) {\n\tconst reasoningText = reasoningParts.map((part) => \"text\" in part ? part.text : \"\").join(\"\");\n\treturn reasoningText.length > 0 ? reasoningText : void 0;\n}\n//#endregion\n//#region src/generate-text/step-result.ts\nvar DefaultStepResult = class {\n\tconstructor({ callId, stepNumber, provider, modelId, runtimeContext, toolsContext, content, finishReason, rawFinishReason, usage, performance, warnings, request, response, providerMetadata }) {\n\t\tthis.callId = callId;\n\t\tthis.stepNumber = stepNumber;\n\t\tthis.model = {\n\t\t\tprovider,\n\t\t\tmodelId\n\t\t};\n\t\tthis.runtimeContext = runtimeContext;\n\t\tthis.toolsContext = toolsContext;\n\t\tthis.content = content;\n\t\tthis.finishReason = finishReason;\n\t\tthis.rawFinishReason = rawFinishReason;\n\t\tthis.usage = usage;\n\t\tthis.performance = performance;\n\t\tthis.warnings = warnings;\n\t\tthis.request = request;\n\t\tthis.response = response;\n\t\tthis.providerMetadata = providerMetadata;\n\t}\n\tget text() {\n\t\treturn this.content.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\");\n\t}\n\tget reasoning() {\n\t\treturn convertFromReasoningOutputs(this.content.filter((part) => part.type === \"reasoning\" || part.type === \"reasoning-file\"));\n\t}\n\tget reasoningText() {\n\t\treturn asReasoningText(this.reasoning);\n\t}\n\tget files() {\n\t\treturn this.content.filter((part) => part.type === \"file\").map((part) => part.file);\n\t}\n\tget sources() {\n\t\treturn this.content.filter((part) => part.type === \"source\");\n\t}\n\tget toolCalls() {\n\t\treturn this.content.filter((part) => part.type === \"tool-call\");\n\t}\n\tget staticToolCalls() {\n\t\treturn this.toolCalls.filter((toolCall) => toolCall.dynamic !== true);\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.toolCalls.filter((toolCall) => toolCall.dynamic === true);\n\t}\n\tget toolResults() {\n\t\treturn this.content.filter((part) => part.type === \"tool-result\");\n\t}\n\tget staticToolResults() {\n\t\treturn this.toolResults.filter((toolResult) => toolResult.dynamic !== true);\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.toolResults.filter((toolResult) => toolResult.dynamic === true);\n\t}\n};\n//#endregion\n//#region src/generate-text/restricted-telemetry-dispatcher.ts\n/**\n* Creates a copy of a step result whose runtime context only contains\n* top-level properties marked for telemetry inclusion.\n*/\nfunction restrictStepResult({ step, includeRuntimeContext, includeToolsContext }) {\n\treturn new DefaultStepResult({\n\t\tcallId: step.callId,\n\t\tstepNumber: step.stepNumber,\n\t\tprovider: step.model.provider,\n\t\tmodelId: step.model.modelId,\n\t\truntimeContext: filterIncludedContext({\n\t\t\tcontext: step.runtimeContext,\n\t\t\tincludeContext: includeRuntimeContext\n\t\t}),\n\t\ttoolsContext: filterToolsContext({\n\t\t\ttoolsContext: step.toolsContext,\n\t\t\tincludeToolsContext\n\t\t}),\n\t\tcontent: step.content,\n\t\tfinishReason: step.finishReason,\n\t\trawFinishReason: step.rawFinishReason,\n\t\tusage: step.usage,\n\t\tperformance: step.performance,\n\t\twarnings: step.warnings,\n\t\trequest: step.request,\n\t\tresponse: step.response,\n\t\tproviderMetadata: step.providerMetadata\n\t});\n}\n/**\n* Creates a telemetry dispatcher that only includes configured runtime context\n* properties in text-generation lifecycle events before dispatching them.\n*/\nfunction createRestrictedTelemetryDispatcher$3({ telemetry, includeRuntimeContext, includeToolsContext }) {\n\tconst telemetryDispatcher = createTelemetryDispatcher({ telemetry });\n\treturn {\n\t\t...telemetryDispatcher,\n\t\tonStart: (event) => telemetryDispatcher.onStart?.({\n\t\t\t...event,\n\t\t\truntimeContext: filterIncludedContext({\n\t\t\t\tcontext: event.runtimeContext,\n\t\t\t\tincludeContext: includeRuntimeContext\n\t\t\t}),\n\t\t\ttoolsContext: filterToolsContext({\n\t\t\t\ttoolsContext: event.toolsContext,\n\t\t\t\tincludeToolsContext\n\t\t\t})\n\t\t}),\n\t\tonStepStart: (event) => telemetryDispatcher.onStepStart?.({\n\t\t\t...event,\n\t\t\truntimeContext: filterIncludedContext({\n\t\t\t\tcontext: event.runtimeContext,\n\t\t\t\tincludeContext: includeRuntimeContext\n\t\t\t}),\n\t\t\tsteps: event.steps.map((step) => restrictStepResult({\n\t\t\t\tstep,\n\t\t\t\tincludeRuntimeContext,\n\t\t\t\tincludeToolsContext\n\t\t\t})),\n\t\t\ttoolsContext: filterToolsContext({\n\t\t\t\ttoolsContext: event.toolsContext,\n\t\t\t\tincludeToolsContext\n\t\t\t})\n\t\t}),\n\t\tonStepEnd: (event) => telemetryDispatcher.onStepEnd?.(restrictStepResult({\n\t\t\tstep: event,\n\t\t\tincludeRuntimeContext,\n\t\t\tincludeToolsContext\n\t\t})),\n\t\tonStepFinish: (event) => telemetryDispatcher.onStepEnd?.(restrictStepResult({\n\t\t\tstep: event,\n\t\t\tincludeRuntimeContext,\n\t\t\tincludeToolsContext\n\t\t})),\n\t\tonEnd: (event) => telemetryDispatcher.onEnd?.(((restrictedSteps) => {\n\t\t\treturn {\n\t\t\t\t...event,\n\t\t\t\truntimeContext: filterIncludedContext({\n\t\t\t\t\tcontext: event.runtimeContext,\n\t\t\t\t\tincludeContext: includeRuntimeContext\n\t\t\t\t}),\n\t\t\t\tsteps: restrictedSteps,\n\t\t\t\tfinalStep: restrictedSteps.at(-1),\n\t\t\t\ttoolsContext: filterToolsContext({\n\t\t\t\t\ttoolsContext: event.toolsContext,\n\t\t\t\t\tincludeToolsContext\n\t\t\t\t})\n\t\t\t};\n\t\t})(event.steps.map((step) => restrictStepResult({\n\t\t\tstep,\n\t\t\tincludeRuntimeContext,\n\t\t\tincludeToolsContext\n\t\t})))),\n\t\tonAbort: (event) => telemetryDispatcher.onAbort?.({\n\t\t\t...event,\n\t\t\tsteps: event.steps.map((step) => restrictStepResult({\n\t\t\t\tstep,\n\t\t\t\tincludeRuntimeContext,\n\t\t\t\tincludeToolsContext\n\t\t\t}))\n\t\t}),\n\t\tonToolExecutionStart: (event) => telemetryDispatcher.onToolExecutionStart?.({\n\t\t\t...event,\n\t\t\ttoolContext: filterToolContext({\n\t\t\t\ttoolName: event.toolCall.toolName,\n\t\t\t\ttoolContext: event.toolContext,\n\t\t\t\tincludeToolsContext\n\t\t\t})\n\t\t}),\n\t\tonToolExecutionEnd: (event) => telemetryDispatcher.onToolExecutionEnd?.({\n\t\t\t...event,\n\t\t\ttoolContext: filterToolContext({\n\t\t\t\ttoolName: event.toolCall.toolName,\n\t\t\t\ttoolContext: event.toolContext,\n\t\t\t\tincludeToolsContext\n\t\t\t})\n\t\t})\n\t};\n}\n//#endregion\n//#region src/generate-text/stop-condition.ts\n/**\n* Creates a stop condition that returns `true` when the number of completed\n* steps equals `stepCount`.\n*\n* @param stepCount - The number of steps to allow before stopping.\n*/\nfunction isStepCount(stepCount) {\n\treturn ({ steps }) => steps.length === stepCount;\n}\n/**\n* Creates a stop condition that never returns `true`.\n*\n* This lets the tool-calling loop continue until it reaches one of its\n* natural termination conditions.\n*/\nfunction isLoopFinished() {\n\treturn () => false;\n}\n/**\n* Creates a stop condition that returns `true` when the most recent step\n* contains a tool call with any of the specified names.\n*\n* @param toolName - The names of the tools that should stop the loop.\n*/\nfunction hasToolCall(...toolName) {\n\treturn ({ steps }) => steps[steps.length - 1]?.toolCalls?.some((toolCall) => toolName.includes(toolCall.toolName)) ?? false;\n}\n/**\n* Evaluates the provided stop conditions for the current list of steps.\n*\n* Returns `true` as soon as any stop condition is met.\n*\n* @param stopConditions - The stop conditions to evaluate.\n* @param steps - The completed steps accumulated so far.\n*/\nasync function isStopConditionMet({ stopConditions, steps }) {\n\treturn (await Promise.all(stopConditions.map((condition) => condition({ steps })))).some((result) => result);\n}\n//#endregion\n//#region src/generate-text/sum-token-counts.ts\n/**\n* Adds token counts while preserving an unknown total when both counts are\n* unknown.\n*/\nfunction sumTokenCounts(tokenCount1, tokenCount2) {\n\treturn tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);\n}\n//#endregion\n//#region src/util/is-deep-equal-data.ts\n/**\n* Performs a deep-equal comparison of two parsed JSON objects.\n*\n* @param {any} obj1 - The first object to compare.\n* @param {any} obj2 - The second object to compare.\n* @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise.\n*/\nfunction isDeepEqualData(obj1, obj2) {\n\tif (obj1 === obj2) return true;\n\tif (obj1 == null || obj2 == null) return false;\n\tif (typeof obj1 !== \"object\" && typeof obj2 !== \"object\") return obj1 === obj2;\n\tif (obj1.constructor !== obj2.constructor) return false;\n\tif (obj1 instanceof Date && obj2 instanceof Date) return obj1.getTime() === obj2.getTime();\n\tif (Array.isArray(obj1)) {\n\t\tif (obj1.length !== obj2.length) return false;\n\t\tfor (let i = 0; i < obj1.length; i++) if (!isDeepEqualData(obj1[i], obj2[i])) return false;\n\t\treturn true;\n\t}\n\tconst keys1 = Object.keys(obj1);\n\tconst keys2 = Object.keys(obj2);\n\tif (keys1.length !== keys2.length) return false;\n\tfor (const key of keys1) {\n\t\tif (!keys2.includes(key)) return false;\n\t\tif (!isDeepEqualData(obj1[key], obj2[key])) return false;\n\t}\n\treturn true;\n}\n//#endregion\n//#region src/generate-text/to-response-messages.ts\n/**\n* Converts the result of a `generateText` or `streamText` call to a list of response messages.\n*/\nasync function toResponseMessages({ content: inputContent, tools }) {\n\tconst responseMessages = [];\n\tconst toolCallOrder = /* @__PURE__ */ new Map();\n\tconst content = [];\n\tfor (const part of inputContent) {\n\t\tif (part.type === \"source\") continue;\n\t\tif ((part.type === \"tool-result\" || part.type === \"tool-error\") && !part.providerExecuted) continue;\n\t\tif (part.type === \"text\" && part.text.length === 0) continue;\n\t\tswitch (part.type) {\n\t\t\tcase \"text\":\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: part.text,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"custom\":\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"custom\",\n\t\t\t\t\tkind: part.kind,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"reasoning\":\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\ttext: part.text,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"file\":\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tdata: part.file.base64,\n\t\t\t\t\tmediaType: part.file.mediaType,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"reasoning-file\":\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"reasoning-file\",\n\t\t\t\t\tdata: part.file.base64,\n\t\t\t\t\tmediaType: part.file.mediaType,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"tool-call\":\n\t\t\t\tif (!toolCallOrder.has(part.toolCallId)) toolCallOrder.set(part.toolCallId, toolCallOrder.size);\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\tinput: part.invalid && typeof part.input !== \"object\" ? {} : part.input,\n\t\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"tool-result\": {\n\t\t\t\tconst output = await createToolModelOutput({\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\tinput: part.input,\n\t\t\t\t\ttool: getOwn(tools, part.toolName),\n\t\t\t\t\toutput: part.output,\n\t\t\t\t\terrorMode: \"none\"\n\t\t\t\t});\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\toutput,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool-error\": {\n\t\t\t\tconst output = await createToolModelOutput({\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\tinput: part.input,\n\t\t\t\t\ttool: getOwn(tools, part.toolName),\n\t\t\t\t\toutput: part.error,\n\t\t\t\t\terrorMode: \"json\"\n\t\t\t\t});\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\toutput,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool-approval-request\":\n\t\t\t\tconst inputSchemaInput = getToolCallInputSchemaInput(part.toolCall);\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\tapprovalId: part.approvalId,\n\t\t\t\t\ttoolCallId: part.toolCall.toolCallId,\n\t\t\t\t\t...part.reason != null ? { reason: part.reason } : {},\n\t\t\t\t\tisAutomatic: part.isAutomatic,\n\t\t\t\t\t...part.signature != null ? { signature: part.signature } : {},\n\t\t\t\t\t...inputSchemaInput != null && !isDeepEqualData(inputSchemaInput.value, part.toolCall.input) ? { inputSchemaInput: inputSchemaInput.value } : {}\n\t\t\t\t});\n\t\t}\n\t}\n\tif (content.length > 0) responseMessages.push({\n\t\trole: \"assistant\",\n\t\tcontent\n\t});\n\tconst toolResultContent = [];\n\tfor (const part of inputContent) {\n\t\tif (part.type !== \"tool-approval-response\" && part.type !== \"tool-result\" && part.type !== \"tool-error\") continue;\n\t\tif (part.type === \"tool-approval-response\") {\n\t\t\ttoolResultContent.push({\n\t\t\t\ttype: \"tool-approval-response\",\n\t\t\t\tapprovalId: part.approvalId,\n\t\t\t\tapproved: part.approved,\n\t\t\t\treason: part.reason,\n\t\t\t\tproviderExecuted: part.providerExecuted\n\t\t\t});\n\t\t\tif (part.approved === false) toolResultContent.push({\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId: part.toolCall.toolCallId,\n\t\t\t\ttoolName: part.toolCall.toolName,\n\t\t\t\toutput: {\n\t\t\t\t\ttype: \"execution-denied\",\n\t\t\t\t\treason: part.reason\n\t\t\t\t}\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (part.providerExecuted) continue;\n\t\tconst output = await createToolModelOutput({\n\t\t\ttoolCallId: part.toolCallId,\n\t\t\tinput: part.input,\n\t\t\ttool: getOwn(tools, part.toolName),\n\t\t\toutput: part.type === \"tool-result\" ? part.output : part.error,\n\t\t\terrorMode: part.type === \"tool-error\" ? \"text\" : \"none\"\n\t\t});\n\t\ttoolResultContent.push({\n\t\t\ttype: \"tool-result\",\n\t\t\ttoolCallId: part.toolCallId,\n\t\t\ttoolName: part.toolName,\n\t\t\toutput,\n\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t});\n\t}\n\tif (toolResultContent.length > 0) responseMessages.push({\n\t\trole: \"tool\",\n\t\tcontent: sortToolResultContentByToolCallOrder({\n\t\t\ttoolResultContent,\n\t\t\ttoolCallOrder\n\t\t})\n\t});\n\treturn responseMessages;\n}\nfunction sortToolResultContentByToolCallOrder({ toolResultContent, toolCallOrder }) {\n\tconst sortedToolResults = toolResultContent.filter((part) => part.type === \"tool-result\").map((part, index) => ({\n\t\tpart,\n\t\tindex\n\t})).sort((a, b) => {\n\t\tconst aOrder = toolCallOrder.get(a.part.toolCallId);\n\t\tconst bOrder = toolCallOrder.get(b.part.toolCallId);\n\t\tif (aOrder == null && bOrder == null) return a.index - b.index;\n\t\tif (aOrder == null) return 1;\n\t\tif (bOrder == null) return -1;\n\t\treturn aOrder - bOrder || a.index - b.index;\n\t}).map(({ part }) => part);\n\tlet toolResultIndex = 0;\n\treturn toolResultContent.map((part) => part.type === \"tool-result\" ? sortedToolResults[toolResultIndex++] : part);\n}\n//#endregion\n//#region src/util/canonical-hash.ts\nconst encoder$1 = new TextEncoder();\n/**\n* Deterministic JSON serialization: object keys are sorted so that two\n* structurally-equal values always produce the same string regardless of key\n* insertion order. Used as the input to content hashing.\n*/\nfunction canonicalJSON(value) {\n\tif (value === null || value === void 0) return JSON.stringify(value);\n\tif (typeof value !== \"object\") return JSON.stringify(value);\n\tif (Array.isArray(value)) return `[${value.map((element) => element === void 0 ? \"null\" : canonicalJSON(element)).join(\",\")}]`;\n\treturn `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJSON(value[k])}`).join(\",\")}}`;\n}\nfunction toBase64url(bytes) {\n\treturn convertUint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/g, \"\");\n}\n/**\n* Canonical SHA-256 digest (base64url) of an arbitrary JSON-serializable value.\n*/\nasync function hashCanonical(value) {\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", encoder$1.encode(canonicalJSON(value)));\n\treturn toBase64url(new Uint8Array(digest));\n}\n//#endregion\n//#region src/generate-text/tool-approval-signature.ts\nconst encoder = new TextEncoder();\nfunction fromBase64url(str) {\n\treturn convertBase64ToUint8Array(str);\n}\nasync function importKey(secret) {\n\tconst keyData = typeof secret === \"string\" ? encoder.encode(secret) : secret;\n\treturn crypto.subtle.importKey(\"raw\", keyData, {\n\t\tname: \"HMAC\",\n\t\thash: \"SHA-256\"\n\t}, false, [\"sign\", \"verify\"]);\n}\nfunction buildPayload(approvalId, toolCallId, toolName, inputDigest) {\n\treturn encoder.encode(JSON.stringify([\n\t\t\"ai-sdk-tool-approval-v1\",\n\t\tapprovalId,\n\t\ttoolCallId,\n\t\ttoolName,\n\t\tinputDigest\n\t]));\n}\nfunction buildLegacyPayload(approvalId, toolCallId, toolName, inputDigest) {\n\treturn encoder.encode(`${approvalId}\\n${toolCallId}\\n${toolName}\\n${inputDigest}`);\n}\nasync function signToolApproval({ secret, approvalId, toolCallId, toolName, input }) {\n\tconst key = await importKey(secret);\n\tconst payload = buildPayload(approvalId, toolCallId, toolName, await hashCanonical(input));\n\tconst sig = await crypto.subtle.sign(\"HMAC\", key, payload);\n\treturn toBase64url(new Uint8Array(sig));\n}\nasync function verifyToolApprovalSignature({ secret, signature, approvalId, toolCallId, toolName, input }) {\n\tconst key = await importKey(secret);\n\tconst inputDigest = await hashCanonical(input);\n\tconst sigBytes = fromBase64url(signature);\n\tconst payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);\n\tif (await crypto.subtle.verify(\"HMAC\", key, sigBytes, payload)) return true;\n\tif (!approvalId.includes(\"\\n\") && !toolCallId.includes(\"\\n\") && !toolName.includes(\"\\n\")) {\n\t\tconst legacyPayload = buildLegacyPayload(approvalId, toolCallId, toolName, inputDigest);\n\t\treturn crypto.subtle.verify(\"HMAC\", key, sigBytes, legacyPayload);\n\t}\n\treturn false;\n}\nasync function maybeSignApproval({ secret, approvalId, toolCallId, toolName, input }) {\n\tif (secret == null) return void 0;\n\treturn signToolApproval({\n\t\tsecret,\n\t\tapprovalId,\n\t\ttoolCallId,\n\t\ttoolName,\n\t\tinput\n\t});\n}\n//#endregion\n//#region src/generate-text/validate-tool-approvals.ts\n/**\n* Re-validates approved tool approvals reconstructed from client-supplied\n* message history before they are executed. Checks HMAC signature (when\n* configured), input schema, and approval policy.\n*/\nasync function validateApprovedToolApprovals({ approvedToolApprovals, tools, toolApproval, messages, toolsContext, runtimeContext, toolApprovalSecret, refineToolInput }) {\n\tconst approved = [];\n\tconst denied = [];\n\tconst invalid = [];\n\tfor (const approval of approvedToolApprovals) {\n\t\tconst { approvalRequest, toolCall } = approval;\n\t\tconst tool = getOwn(tools, toolCall.toolName);\n\t\tif (toolApprovalSecret != null) {\n\t\t\tif (approvalRequest.signature == null) throw new InvalidToolApprovalSignatureError({\n\t\t\t\tapprovalId: approvalRequest.approvalId,\n\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\treason: \"missing signature\"\n\t\t\t});\n\t\t\tif (!await verifyToolApprovalSignature({\n\t\t\t\tsecret: toolApprovalSecret,\n\t\t\t\tsignature: approvalRequest.signature,\n\t\t\t\tapprovalId: approvalRequest.approvalId,\n\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\tinput: toolCall.input\n\t\t\t})) throw new InvalidToolApprovalSignatureError({\n\t\t\t\tapprovalId: approvalRequest.approvalId,\n\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\treason: \"invalid signature\"\n\t\t\t});\n\t\t}\n\t\tif (isExecutableTool(tool) && tool.inputSchema != null) {\n\t\t\tconst hasInputSchemaInput = Object.prototype.hasOwnProperty.call(approvalRequest, \"inputSchemaInput\");\n\t\t\tconst validation = await safeValidateTypes({\n\t\t\t\tvalue: hasInputSchemaInput ? approvalRequest.inputSchemaInput : toolCall.input,\n\t\t\t\tschema: asSchema$1(tool.inputSchema)\n\t\t\t});\n\t\t\tlet validationError;\n\t\t\tif (!validation.success) validationError = validation.error;\n\t\t\telse try {\n\t\t\t\tconst revalidatedToolCall = await refineParsedToolCallInput({\n\t\t\t\t\ttoolCall: {\n\t\t\t\t\t\t...toolCall,\n\t\t\t\t\t\tinput: validation.value\n\t\t\t\t\t},\n\t\t\t\t\trefineToolInput\n\t\t\t\t});\n\t\t\t\tif (!isDeepEqualData(structuredClone(revalidatedToolCall.input), structuredClone(toolCall.input))) validationError = /* @__PURE__ */ new Error(\"Approved tool input does not match the validated schema output.\");\n\t\t\t} catch (error) {\n\t\t\t\tvalidationError = error;\n\t\t\t}\n\t\t\tif (validationError != null) {\n\t\t\t\tinvalid.push({\n\t\t\t\t\t...approval,\n\t\t\t\t\terror: new InvalidToolInputError({\n\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\ttoolInput: JSON.stringify(toolCall.input),\n\t\t\t\t\t\tcause: validationError\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tconst approvalStatus = await resolveToolApproval({\n\t\t\ttools,\n\t\t\ttoolApproval,\n\t\t\ttoolCall,\n\t\t\tmessages,\n\t\t\ttoolsContext,\n\t\t\truntimeContext\n\t\t});\n\t\tif (approvalStatus.type === \"denied\") denied.push({\n\t\t\t...approval,\n\t\t\tapprovalResponse: {\n\t\t\t\t...approval.approvalResponse,\n\t\t\t\tapproved: false,\n\t\t\t\treason: approvalStatus.reason ?? approval.approvalResponse.reason\n\t\t\t}\n\t\t});\n\t\telse approved.push(approval);\n\t}\n\treturn {\n\t\tapprovedToolApprovals: approved,\n\t\tdeniedToolApprovals: denied,\n\t\tinvalidToolApprovals: invalid\n\t};\n}\n//#endregion\n//#region src/generate-text/generate-text.ts\nconst originalGenerateId$4 = createIdGenerator$1({\n\tprefix: \"aitxt\",\n\tsize: 24\n});\nconst originalGenerateCallId$9 = createIdGenerator$1({\n\tprefix: \"call\",\n\tsize: 24\n});\n/**\n* Generate a text and call tools for a given prompt using a language model.\n*\n* This function does not stream the output. If you want to stream the output, use `streamText` instead.\n*\n* @param model - The language model to use.\n*\n* @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n* @param toolChoice - The tool choice strategy. Default: 'auto'.\n* @param toolOrder - Controls the order in which tools are sent to the provider. Tools not listed are appended alphabetically.\n*\n* @param system - A system message that will be part of the prompt.\n* @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n* @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n* @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.\n*\n* @param maxOutputTokens - Maximum number of tokens to generate.\n* @param temperature - Temperature setting.\n* The value is passed through to the provider. The range depends on the provider and model.\n* It is recommended to set either `temperature` or `topP`, but not both.\n* @param topP - Nucleus sampling.\n* The value is passed through to the provider. The range depends on the provider and model.\n* It is recommended to set either `temperature` or `topP`, but not both.\n* @param topK - Only sample from the top K options for each subsequent token.\n* Used to remove \"long tail\" low probability responses.\n* Recommended for advanced use cases only. You usually only need to use temperature.\n* @param presencePenalty - Presence penalty setting.\n* It affects the likelihood of the model to repeat information that is already in the prompt.\n* The value is passed through to the provider. The range depends on the provider and model.\n* @param frequencyPenalty - Frequency penalty setting.\n* It affects the likelihood of the model to repeatedly use the same words or phrases.\n* The value is passed through to the provider. The range depends on the provider and model.\n* @param stopSequences - Stop sequences.\n* If set, the model will stop generating text when one of the stop sequences is generated.\n* @param seed - The seed (integer) to use for random sampling.\n* If set and supported by the model, calls will generate deterministic results.\n*\n* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n*\n* @param experimental_sandbox - The sandbox environment that is passed through to tool execution.\n* @param runtimeContext - User-defined runtime context that flows through the entire generation lifecycle.\n* @param experimental_refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before tools are executed and before outputs, callbacks, and telemetry are recorded.\n* @param onStart - Callback invoked when generation begins, before any LLM calls.\n* @param experimental_onStart - Deprecated alias for `onStart`.\n* @param onStepStart - Callback invoked when each step begins, before the provider is called.\n* @param experimental_onStepStart - Deprecated alias for `onStepStart`.\n* Receives step number, messages (in ModelMessage format), tools, and runtimeContext.\n* @param onLanguageModelCallStart - Callback invoked immediately before each provider model call begins.\n* @param experimental_onLanguageModelCallStart - Deprecated alias for `onLanguageModelCallStart`.\n* @param onLanguageModelCallEnd - Callback invoked after each provider model call response is normalized and parsed.\n* @param experimental_onLanguageModelCallEnd - Deprecated alias for `onLanguageModelCallEnd`.\n* @param onToolExecutionStart - Callback invoked before each tool execution begins.\n* Receives tool name, call ID, input, and context.\n* @param experimental_onToolCallStart - Deprecated alias for `onToolExecutionStart`.\n* @param onToolExecutionEnd - Callback invoked after each tool execution completes.\n* Uses a discriminated union: check `success` to determine if `output` or `error` is present.\n* @param experimental_onToolCallFinish - Deprecated alias for `onToolExecutionEnd`.\n* @param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.\n* @param onEnd - Callback that is called when all steps are finished and the response is complete.\n* @param onFinish - Deprecated alias for `onEnd`.\n*\n* @returns\n* A result object that contains the generated text, the results of the tool calls, and additional information.\n*/\nasync function generateText({ model: modelArg, tools, toolChoice, instructions, system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, timeout, headers, stopWhen = isStepCount(1), experimental_sandbox: sandbox, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, experimental_telemetry, telemetry = experimental_telemetry, providerOptions, activeTools, toolOrder, prepareStep, experimental_repairToolCall, repairToolCall = experimental_repairToolCall, experimental_refineToolInput: refineToolInput, experimental_download: download, runtimeContext = {}, toolsContext = {}, experimental_include, include = experimental_include, _internal: { generateId = originalGenerateId$4, generateCallId = originalGenerateCallId$9, now: now$4 = now } = {}, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onLanguageModelCallStart, experimental_onLanguageModelCallStart, onLanguageModelCallEnd, experimental_onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, experimental_onToolCallStart, experimental_onToolCallFinish, onStepEnd, onStepFinish, onFinish, onEnd = onFinish, ...settings }) {\n\tinclude = {\n\t\trequestBody: include?.requestBody ?? false,\n\t\trequestMessages: include?.requestMessages ?? false,\n\t\tresponseBody: include?.responseBody ?? false\n\t};\n\tconst model = resolveLanguageModel(modelArg);\n\tconst resolvedToolCallers = resolveToolCallerConfiguration({\n\t\ttools,\n\t\ttoolCallers: experimental_toolCallers\n\t});\n\tconst prepareToolSearch = createToolSearchState({\n\t\ttools,\n\t\ttoolCallers: resolvedToolCallers\n\t});\n\tconst stopConditions = asArray(stopWhen);\n\tconst resolvedOnStart = onStart ?? experimental_onStart;\n\tconst resolvedOnStepStart = onStepStart ?? experimental_onStepStart;\n\tconst resolvedOnLanguageModelCallStart = onLanguageModelCallStart ?? experimental_onLanguageModelCallStart;\n\tconst resolvedOnLanguageModelCallEnd = onLanguageModelCallEnd ?? experimental_onLanguageModelCallEnd;\n\tconst resolvedOnToolExecutionStart = onToolExecutionStart ?? experimental_onToolCallStart;\n\tconst resolvedOnToolExecutionEnd = onToolExecutionEnd ?? experimental_onToolCallFinish;\n\tconst resolvedOnStepEnd = onStepEnd ?? onStepFinish;\n\tconst unsupportedTimeoutWarnings = [];\n\tif (getFirstChunkTimeoutMs(timeout) != null) unsupportedTimeoutWarnings.push({\n\t\ttype: \"unsupported\",\n\t\tfeature: \"timeout.firstChunkMs\",\n\t\tdetails: \"The firstChunkMs timeout is only supported by streaming functions.\"\n\t});\n\tif (getChunkTimeoutMs(timeout) != null) unsupportedTimeoutWarnings.push({\n\t\ttype: \"unsupported\",\n\t\tfeature: \"timeout.chunkMs\",\n\t\tdetails: \"The chunkMs timeout is only supported by streaming functions.\"\n\t});\n\tif (unsupportedTimeoutWarnings.length > 0) logWarnings({\n\t\twarnings: unsupportedTimeoutWarnings,\n\t\tprovider: model.provider,\n\t\tmodel: model.modelId\n\t});\n\tconst totalTimeoutMs = getTotalTimeoutMs(timeout);\n\tconst stepTimeoutMs = getStepTimeoutMs(timeout);\n\tconst stepAbortController = stepTimeoutMs != null ? new AbortController() : void 0;\n\tconst mergedAbortSignal = mergeAbortSignals(abortSignal, totalTimeoutMs, stepAbortController?.signal);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal: mergedAbortSignal\n\t});\n\tconst callSettings = prepareLanguageModelCallOptions(settings);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst initialPrompt = await standardizePrompt({\n\t\tinstructions,\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages\n\t});\n\tconst callId = generateCallId();\n\tconst telemetryDispatcher = createRestrictedTelemetryDispatcher$3({\n\t\ttelemetry,\n\t\tincludeRuntimeContext: telemetry?.includeRuntimeContext,\n\t\tincludeToolsContext: telemetry?.includeToolsContext\n\t});\n\tconst runInTracingChannelSpan = telemetryDispatcher.runInTracingChannelSpan ?? (async ({ execute }) => await execute());\n\tconst generateTextStartEvent = {\n\t\tcallId,\n\t\toperationId: \"ai.generateText\",\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId,\n\t\tinstructions: initialPrompt.instructions,\n\t\tmessages: initialPrompt.messages,\n\t\ttools,\n\t\ttoolChoice,\n\t\tactiveTools,\n\t\ttoolOrder,\n\t\tmaxOutputTokens: callSettings.maxOutputTokens,\n\t\ttemperature: callSettings.temperature,\n\t\ttopP: callSettings.topP,\n\t\ttopK: callSettings.topK,\n\t\tpresencePenalty: callSettings.presencePenalty,\n\t\tfrequencyPenalty: callSettings.frequencyPenalty,\n\t\tstopSequences: callSettings.stopSequences,\n\t\tseed: callSettings.seed,\n\t\treasoning: callSettings.reasoning,\n\t\tmaxRetries,\n\t\ttimeout,\n\t\theaders: headersWithUserAgent,\n\t\tproviderOptions,\n\t\toutput,\n\t\truntimeContext,\n\t\ttoolsContext\n\t};\n\tconst executeGenerateText = async () => {\n\t\tawait notify({\n\t\t\tevent: generateTextStartEvent,\n\t\t\tcallbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n\t\t});\n\t\ttry {\n\t\t\tconst initialMessages = initialPrompt.messages;\n\t\t\tconst initialResponseMessages = [];\n\t\t\tconst { approvedToolApprovals, deniedToolApprovals: collectedDeniedToolApprovals } = collectToolApprovals({ messages: initialMessages });\n\t\t\tconst { approvedToolApprovals: localApprovedToolApprovals, deniedToolApprovals: revalidationDeniedToolApprovals, invalidToolApprovals } = await validateApprovedToolApprovals({\n\t\t\t\tapprovedToolApprovals: approvedToolApprovals.filter((toolApproval) => !toolApproval.toolCall.providerExecuted),\n\t\t\t\ttools,\n\t\t\t\ttoolApproval,\n\t\t\t\tmessages: initialMessages,\n\t\t\t\ttoolsContext,\n\t\t\t\truntimeContext,\n\t\t\t\ttoolApprovalSecret: experimental_toolApprovalSecret,\n\t\t\t\trefineToolInput\n\t\t\t});\n\t\t\tconst deniedToolApprovalsWithoutResults = [...collectedDeniedToolApprovals, ...revalidationDeniedToolApprovals].filter((toolApproval) => toolApproval.existingToolResult == null);\n\t\t\tif (deniedToolApprovalsWithoutResults.length > 0 || localApprovedToolApprovals.length > 0 || invalidToolApprovals.length > 0) {\n\t\t\t\tconst toolResults = await executeTools({\n\t\t\t\t\ttoolCalls: localApprovedToolApprovals.map((toolApproval) => toolApproval.toolCall),\n\t\t\t\t\ttools,\n\t\t\t\t\tcallId,\n\t\t\t\t\tmessages: initialMessages,\n\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\ttimeout,\n\t\t\t\t\texperimental_sandbox: sandbox,\n\t\t\t\t\ttoolsContext,\n\t\t\t\t\tonToolExecutionStart: (event) => notify({\n\t\t\t\t\t\tevent,\n\t\t\t\t\t\tcallbacks: [resolvedOnToolExecutionStart, telemetryDispatcher.onToolExecutionStart]\n\t\t\t\t\t}),\n\t\t\t\t\tonToolExecutionEnd: (event) => notify({\n\t\t\t\t\t\tevent,\n\t\t\t\t\t\tcallbacks: [resolvedOnToolExecutionEnd, telemetryDispatcher.onToolExecutionEnd]\n\t\t\t\t\t}),\n\t\t\t\t\texecuteToolInTelemetryContext: telemetryDispatcher.executeTool,\n\t\t\t\t\trunInTracingChannelSpan\n\t\t\t\t});\n\t\t\t\tconst toolContent = [];\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tconst output = result.output;\n\t\t\t\t\tconst modelOutput = await createToolModelOutput({\n\t\t\t\t\t\ttoolCallId: output.toolCallId,\n\t\t\t\t\t\tinput: output.input,\n\t\t\t\t\t\ttool: getOwn(tools, output.toolName),\n\t\t\t\t\t\toutput: output.type === \"tool-result\" ? output.output : output.error,\n\t\t\t\t\t\terrorMode: output.type === \"tool-error\" ? \"text\" : \"none\"\n\t\t\t\t\t});\n\t\t\t\t\ttoolContent.push({\n\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\ttoolCallId: output.toolCallId,\n\t\t\t\t\t\ttoolName: output.toolName,\n\t\t\t\t\t\toutput: modelOutput\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfor (const toolApproval of invalidToolApprovals) toolContent.push({\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\ttoolName: toolApproval.toolCall.toolName,\n\t\t\t\t\toutput: await createToolModelOutput({\n\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\tinput: toolApproval.toolCall.input,\n\t\t\t\t\t\ttool: getOwn(tools, toolApproval.toolCall.toolName),\n\t\t\t\t\t\toutput: toolApproval.error,\n\t\t\t\t\t\terrorMode: \"text\"\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t\tfor (const toolApproval of deniedToolApprovalsWithoutResults) toolContent.push({\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\ttoolName: toolApproval.toolCall.toolName,\n\t\t\t\t\toutput: {\n\t\t\t\t\t\ttype: \"execution-denied\",\n\t\t\t\t\t\treason: toolApproval.approvalResponse.reason,\n\t\t\t\t\t\t...toolApproval.toolCall.providerExecuted && { providerOptions: { openai: { approvalId: toolApproval.approvalResponse.approvalId } } }\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tinitialResponseMessages.push({\n\t\t\t\t\trole: \"tool\",\n\t\t\t\t\tcontent: toolContent\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst callSettings = prepareLanguageModelCallOptions(settings);\n\t\t\tlet currentModelResponse;\n\t\t\tlet clientToolCalls = [];\n\t\t\tlet clientToolOutputs = [];\n\t\t\tlet toolApprovalResponses = [];\n\t\t\tlet deniedToolApprovalResponses = [];\n\t\t\tconst steps = [];\n\t\t\tlet instructionsForNextStep = initialPrompt.instructions;\n\t\t\tlet messagesForNextStep = [...initialMessages, ...initialResponseMessages];\n\t\t\tconst pendingDeferredToolCalls = /* @__PURE__ */ new Map();\n\t\t\tdo {\n\t\t\t\tif (steps.length > 0) mergedAbortSignal?.throwIfAborted();\n\t\t\t\tconst stepTimeoutId = setAbortTimeout({\n\t\t\t\t\tabortController: stepAbortController,\n\t\t\t\t\tlabel: \"Step\",\n\t\t\t\t\ttimeoutMs: stepTimeoutMs\n\t\t\t\t});\n\t\t\t\tconst stepNumber = steps.length;\n\t\t\t\ttry {\n\t\t\t\t\tawait runInTracingChannelSpan({\n\t\t\t\t\t\ttype: \"step\",\n\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\tstepNumber\n\t\t\t\t\t\t},\n\t\t\t\t\t\texecute: async () => {\n\t\t\t\t\t\t\tconst accumulatedResponseMessages = [...initialResponseMessages, ...steps.flatMap((step) => step.response.messages)];\n\t\t\t\t\t\t\tconst stepInputMessages = messagesForNextStep;\n\t\t\t\t\t\t\tconst prepareStepResult = await prepareStep?.({\n\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\tsteps,\n\t\t\t\t\t\t\t\tstepNumber: steps.length,\n\t\t\t\t\t\t\t\tinstructions: instructionsForNextStep,\n\t\t\t\t\t\t\t\tinitialInstructions: initialPrompt.instructions,\n\t\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\t\tinitialMessages,\n\t\t\t\t\t\t\t\tresponseMessages: accumulatedResponseMessages,\n\t\t\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\t\texperimental_sandbox: sandbox\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst stepSandbox = prepareStepResult?.experimental_sandbox ?? sandbox;\n\t\t\t\t\t\t\tconst stepModel = resolveLanguageModel(prepareStepResult?.model ?? model);\n\t\t\t\t\t\t\tconst stepInstructions = prepareStepResult?.instructions ?? prepareStepResult?.system ?? instructionsForNextStep;\n\t\t\t\t\t\t\truntimeContext = prepareStepResult?.runtimeContext ?? runtimeContext;\n\t\t\t\t\t\t\ttoolsContext = prepareStepResult?.toolsContext ?? toolsContext;\n\t\t\t\t\t\t\tconst stepActiveTools = filterActiveTools({\n\t\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\t\tactiveTools: prepareStepResult?.activeTools ?? activeTools\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst { executionTools: stepExecutionTools, modelTools: stepModelTools, toolCallerMessages } = prepareToolsForToolCallers({\n\t\t\t\t\t\t\t\ttools: prepareToolSearch(stepActiveTools, {\n\t\t\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\t\t\texperimental_sandbox: stepSandbox\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\ttoolCallers: resolvedToolCallers\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst stepToolOrder = prepareStepResult?.toolOrder ?? toolOrder;\n\t\t\t\t\t\t\tconst stepTools = await prepareTools({\n\t\t\t\t\t\t\t\ttools: stepModelTools,\n\t\t\t\t\t\t\t\ttoolOrder: stepToolOrder,\n\t\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\t\texperimental_sandbox: stepSandbox\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst stepToolChoice = prepareToolChoice({ toolChoice: prepareStepResult?.toolChoice ?? toolChoice });\n\t\t\t\t\t\t\tconst stepMessages = appendToolCallerMessages({\n\t\t\t\t\t\t\t\tmessages: prepareStepResult?.messages ?? stepInputMessages,\n\t\t\t\t\t\t\t\ttoolCallerMessages\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\t\t\t\t\t\tprompt: {\n\t\t\t\t\t\t\t\t\tinstructions: stepInstructions,\n\t\t\t\t\t\t\t\t\tmessages: stepMessages\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tsupportedUrls: await stepModel.supportedUrls,\n\t\t\t\t\t\t\t\tdownload,\n\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\tprovider: stepModel.provider.split(\".\")[0]\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst stepProviderOptions = mergeObjects(providerOptions, prepareStepResult?.providerOptions);\n\t\t\t\t\t\t\tconst stepCallSettings = prepareStepCallSettings({\n\t\t\t\t\t\t\t\tcallSettings,\n\t\t\t\t\t\t\t\tstepSettings: prepareStepResult\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\t\tprovider: stepModel.provider,\n\t\t\t\t\t\t\t\t\tmodelId: stepModel.modelId,\n\t\t\t\t\t\t\t\t\tstepNumber,\n\t\t\t\t\t\t\t\t\tinstructions: stepInstructions,\n\t\t\t\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\t\t\ttoolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n\t\t\t\t\t\t\t\t\tactiveTools: prepareStepResult?.activeTools ?? activeTools,\n\t\t\t\t\t\t\t\t\ttoolOrder: stepToolOrder,\n\t\t\t\t\t\t\t\t\tsteps: [...steps],\n\t\t\t\t\t\t\t\t\tproviderOptions: stepProviderOptions,\n\t\t\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\t\t\t\tpromptMessages,\n\t\t\t\t\t\t\t\t\tstepTools,\n\t\t\t\t\t\t\t\t\tstepToolChoice,\n\t\t\t\t\t\t\t\t\ttoolsContext\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tcallbacks: [resolvedOnStepStart, telemetryDispatcher.onStepStart]\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst languageModelCallContext = {\n\t\t\t\t\t\t\t\tprovider: stepModel.provider,\n\t\t\t\t\t\t\t\tmodelId: stepModel.modelId,\n\t\t\t\t\t\t\t\tinstructions: stepInstructions,\n\t\t\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\t\t\ttools: stepTools,\n\t\t\t\t\t\t\t\t...stepCallSettings\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst languageModelCallStartEvent = {\n\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\t...languageModelCallContext\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst stepStartTimestampMs = now$4();\n\t\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\t\tevent: languageModelCallStartEvent,\n\t\t\t\t\t\t\t\tcallbacks: [resolvedOnLanguageModelCallStart, telemetryDispatcher.onLanguageModelCallStart]\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst executeLanguageModelCallInTelemetryContext = telemetryDispatcher.executeLanguageModelCall ?? (async ({ execute }) => await execute());\n\t\t\t\t\t\t\tcurrentModelResponse = await retry(async () => {\n\t\t\t\t\t\t\t\tconst result = await executeLanguageModelCallInTelemetryContext({\n\t\t\t\t\t\t\t\t\t...languageModelCallStartEvent,\n\t\t\t\t\t\t\t\t\texecute: async () => await stepModel.doGenerate({\n\t\t\t\t\t\t\t\t\t\t...stepCallSettings,\n\t\t\t\t\t\t\t\t\t\ttools: stepTools,\n\t\t\t\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\t\t\t\tresponseFormat: await output?.responseFormat,\n\t\t\t\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\t\t\t\tproviderOptions: stepProviderOptions,\n\t\t\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\t\t\theaders: headersWithUserAgent\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst responseData = {\n\t\t\t\t\t\t\t\t\tid: result.response?.id ?? generateId(),\n\t\t\t\t\t\t\t\t\ttimestamp: result.response?.timestamp ?? /* @__PURE__ */ new Date(),\n\t\t\t\t\t\t\t\t\tmodelId: result.response?.modelId ?? stepModel.modelId,\n\t\t\t\t\t\t\t\t\theaders: result.response?.headers,\n\t\t\t\t\t\t\t\t\tbody: result.response?.body\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\t\t\tresponse: responseData\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst responseTimeMs = now$4() - stepStartTimestampMs;\n\t\t\t\t\t\t\tconst stepUsage = asLanguageModelUsage(currentModelResponse.usage);\n\t\t\t\t\t\t\tconst stepToolCalls = await Promise.all(currentModelResponse.content.filter((part) => part.type === \"tool-call\").map((toolCall) => parseToolCall({\n\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\ttools: stepModelTools,\n\t\t\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\t\t\trefineToolInput,\n\t\t\t\t\t\t\t\tinstructions: stepInstructions,\n\t\t\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal\n\t\t\t\t\t\t\t})));\n\t\t\t\t\t\t\tconst toolApprovalRequests = {};\n\t\t\t\t\t\t\tconst stepToolApprovalResponses = {};\n\t\t\t\t\t\t\tconst blockedToolCallIds = /* @__PURE__ */ new Set();\n\t\t\t\t\t\t\tconst generatedFileDataCache = /* @__PURE__ */ new WeakMap();\n\t\t\t\t\t\t\tconst modelCallContent = await convertLanguageModelContent({\n\t\t\t\t\t\t\t\tcontent: currentModelResponse.content,\n\t\t\t\t\t\t\t\ttoolCalls: stepToolCalls,\n\t\t\t\t\t\t\t\ttoolOutputs: [],\n\t\t\t\t\t\t\t\ttoolApprovalRequests: [],\n\t\t\t\t\t\t\t\ttoolApprovalResponses: [],\n\t\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\tgeneratedFileDataCache\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\t\tprovider: stepModel.provider,\n\t\t\t\t\t\t\t\t\tmodelId: currentModelResponse.response.modelId,\n\t\t\t\t\t\t\t\t\tfinishReason: currentModelResponse.finishReason.unified,\n\t\t\t\t\t\t\t\t\tusage: stepUsage,\n\t\t\t\t\t\t\t\t\tcontent: modelCallContent,\n\t\t\t\t\t\t\t\t\tresponseId: currentModelResponse.response.id,\n\t\t\t\t\t\t\t\t\t...currentModelResponse.providerMetadata != null ? { providerMetadata: currentModelResponse.providerMetadata } : {},\n\t\t\t\t\t\t\t\t\tperformance: {\n\t\t\t\t\t\t\t\t\t\tresponseTimeMs,\n\t\t\t\t\t\t\t\t\t\teffectiveOutputTokensPerSecond: calculateTokensPerSecond({\n\t\t\t\t\t\t\t\t\t\t\ttokens: stepUsage.outputTokens,\n\t\t\t\t\t\t\t\t\t\t\tdurationMs: responseTimeMs\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\toutputTokensPerSecond: void 0,\n\t\t\t\t\t\t\t\t\t\tinputTokensPerSecond: void 0,\n\t\t\t\t\t\t\t\t\t\teffectiveTotalTokensPerSecond: calculateTokensPerSecond({\n\t\t\t\t\t\t\t\t\t\t\ttokens: sumTokenCounts(stepUsage.inputTokens, stepUsage.outputTokens),\n\t\t\t\t\t\t\t\t\t\t\tdurationMs: responseTimeMs\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\ttimeToFirstOutputMs: void 0\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tcallbacks: [resolvedOnLanguageModelCallEnd, telemetryDispatcher.onLanguageModelCallEnd]\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst enforcedToolChoice = stepToolChoice.type === \"required\" || stepToolChoice.type === \"tool\" ? stepToolChoice : void 0;\n\t\t\t\t\t\t\tif (enforcedToolChoice != null && !stepToolCalls.some((toolCall) => enforcedToolChoice.type === \"required\" || toolCall.toolName === enforcedToolChoice.toolName)) throw new ToolChoiceViolationError({\n\t\t\t\t\t\t\t\ttoolChoice: enforcedToolChoice,\n\t\t\t\t\t\t\t\tfinishReason: currentModelResponse.finishReason.unified,\n\t\t\t\t\t\t\t\tprovider: stepModel.provider,\n\t\t\t\t\t\t\t\tmodelId: stepModel.modelId,\n\t\t\t\t\t\t\t\tcontent: currentModelResponse.content\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tfor (const toolCall of stepToolCalls) {\n\t\t\t\t\t\t\t\tif (toolCall.invalid) continue;\n\t\t\t\t\t\t\t\tconst tool = getOwn(stepExecutionTools, toolCall.toolName);\n\t\t\t\t\t\t\t\tif (tool == null) continue;\n\t\t\t\t\t\t\t\tif (tool.onInputStart != null || tool.onInputAvailable != null) {\n\t\t\t\t\t\t\t\t\tconst context = await validateToolContext({\n\t\t\t\t\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\t\t\t\t\tcontext: getOwn(toolsContext, toolCall.toolName),\n\t\t\t\t\t\t\t\t\t\tcontextSchema: tool.contextSchema\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (tool.onInputStart != null) await tool.onInputStart({\n\t\t\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\t\t\tcontext\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (tool.onInputAvailable != null) await tool.onInputAvailable({\n\t\t\t\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\t\t\tcontext\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst toolApprovalStatus = await resolveToolApproval({\n\t\t\t\t\t\t\t\t\ttools: stepExecutionTools,\n\t\t\t\t\t\t\t\t\ttoolApproval,\n\t\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\t\t\truntimeContext\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (toolApprovalStatus.type === \"not-applicable\") continue;\n\t\t\t\t\t\t\t\tconst approvalId = generateId();\n\t\t\t\t\t\t\t\tconst signature = await maybeSignApproval({\n\t\t\t\t\t\t\t\t\tsecret: experimental_toolApprovalSecret,\n\t\t\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\t\t\t\tinput: toolCall.input\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tswitch (toolApprovalStatus.type) {\n\t\t\t\t\t\t\t\t\tcase \"user-approval\":\n\t\t\t\t\t\t\t\t\t\ttoolApprovalRequests[toolCall.toolCallId] = {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t\t\t\t...toolApprovalStatus.reason != null ? { reason: toolApprovalStatus.reason } : {},\n\t\t\t\t\t\t\t\t\t\t\t...signature != null ? { signature } : {}\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t\tblockedToolCallIds.add(toolCall.toolCallId);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"approved\":\n\t\t\t\t\t\t\t\t\t\ttoolApprovalRequests[toolCall.toolCallId] = {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t\t\t\tisAutomatic: true,\n\t\t\t\t\t\t\t\t\t\t\t...signature != null ? { signature } : {}\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t\tstepToolApprovalResponses[toolCall.toolCallId] = {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"tool-approval-response\",\n\t\t\t\t\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t\t\t\tapproved: true,\n\t\t\t\t\t\t\t\t\t\t\treason: toolApprovalStatus.reason,\n\t\t\t\t\t\t\t\t\t\t\tproviderExecuted: toolCall.providerExecuted\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"denied\":\n\t\t\t\t\t\t\t\t\t\ttoolApprovalRequests[toolCall.toolCallId] = {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t\t\t\tisAutomatic: true,\n\t\t\t\t\t\t\t\t\t\t\t...signature != null ? { signature } : {}\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t\tstepToolApprovalResponses[toolCall.toolCallId] = {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"tool-approval-response\",\n\t\t\t\t\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t\t\t\tapproved: false,\n\t\t\t\t\t\t\t\t\t\t\treason: toolApprovalStatus.reason,\n\t\t\t\t\t\t\t\t\t\t\tproviderExecuted: toolCall.providerExecuted\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t\tblockedToolCallIds.add(toolCall.toolCallId);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst invalidToolCalls = stepToolCalls.filter((toolCall) => toolCall.invalid && toolCall.dynamic && !toolCall.providerExecuted);\n\t\t\t\t\t\t\tclientToolOutputs = [];\n\t\t\t\t\t\t\tfor (const toolCall of invalidToolCalls) clientToolOutputs.push({\n\t\t\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\t\terror: getErrorMessage(toolCall.error),\n\t\t\t\t\t\t\t\tdynamic: true\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tclientToolCalls = stepToolCalls.filter((toolCall) => !toolCall.providerExecuted);\n\t\t\t\t\t\t\ttoolApprovalResponses = Object.values(stepToolApprovalResponses);\n\t\t\t\t\t\t\tdeniedToolApprovalResponses = toolApprovalResponses.filter((toolApprovalResponse) => toolApprovalResponse.approved === false);\n\t\t\t\t\t\t\tconst toolExecutionMs = {};\n\t\t\t\t\t\t\tif (stepExecutionTools != null && isToolExecutionAllowedFinishReason(currentModelResponse.finishReason.unified)) {\n\t\t\t\t\t\t\t\tconst toolExecutionResults = await executeTools({\n\t\t\t\t\t\t\t\t\ttoolCalls: clientToolCalls.filter((toolCall) => !toolCall.invalid && !blockedToolCallIds.has(toolCall.toolCallId)),\n\t\t\t\t\t\t\t\t\ttools: stepExecutionTools,\n\t\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t\t\texperimental_sandbox: stepSandbox,\n\t\t\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\t\t\tonToolExecutionStart: (event) => notify({\n\t\t\t\t\t\t\t\t\t\tevent,\n\t\t\t\t\t\t\t\t\t\tcallbacks: [resolvedOnToolExecutionStart, telemetryDispatcher.onToolExecutionStart]\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\tonToolExecutionEnd: (event) => notify({\n\t\t\t\t\t\t\t\t\t\tevent,\n\t\t\t\t\t\t\t\t\t\tcallbacks: [resolvedOnToolExecutionEnd, telemetryDispatcher.onToolExecutionEnd]\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\texecuteToolInTelemetryContext: telemetryDispatcher.executeTool,\n\t\t\t\t\t\t\t\t\trunInTracingChannelSpan\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tfor (const result of toolExecutionResults) {\n\t\t\t\t\t\t\t\t\ttoolExecutionMs[result.output.toolCallId] = result.toolExecutionMs;\n\t\t\t\t\t\t\t\t\tclientToolOutputs.push(result.output);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst stepTimeMs = now$4() - stepStartTimestampMs;\n\t\t\t\t\t\t\tconst stepPerformance = {\n\t\t\t\t\t\t\t\teffectiveOutputTokensPerSecond: calculateTokensPerSecond({\n\t\t\t\t\t\t\t\t\ttokens: stepUsage.outputTokens,\n\t\t\t\t\t\t\t\t\tdurationMs: responseTimeMs\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\toutputTokensPerSecond: void 0,\n\t\t\t\t\t\t\t\tinputTokensPerSecond: void 0,\n\t\t\t\t\t\t\t\teffectiveTotalTokensPerSecond: calculateTokensPerSecond({\n\t\t\t\t\t\t\t\t\ttokens: sumTokenCounts(stepUsage.inputTokens, stepUsage.outputTokens),\n\t\t\t\t\t\t\t\t\tdurationMs: responseTimeMs\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tstepTimeMs,\n\t\t\t\t\t\t\t\tresponseTimeMs,\n\t\t\t\t\t\t\t\ttoolExecutionMs,\n\t\t\t\t\t\t\t\ttimeToFirstOutputMs: void 0\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tfor (const toolCall of stepToolCalls) {\n\t\t\t\t\t\t\t\tif (!toolCall.providerExecuted) continue;\n\t\t\t\t\t\t\t\tconst tool = getOwn(stepExecutionTools, toolCall.toolName);\n\t\t\t\t\t\t\t\tif (tool?.type === \"provider\" && tool.supportsDeferredResults) {\n\t\t\t\t\t\t\t\t\tif (!currentModelResponse.content.some((part) => part.type === \"tool-result\" && part.toolCallId === toolCall.toolCallId)) pendingDeferredToolCalls.set(toolCall.toolCallId, { toolName: toolCall.toolName });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (const part of currentModelResponse.content) if (part.type === \"tool-result\") pendingDeferredToolCalls.delete(part.toolCallId);\n\t\t\t\t\t\t\tconst stepContent = await convertLanguageModelContent({\n\t\t\t\t\t\t\t\tcontent: currentModelResponse.content,\n\t\t\t\t\t\t\t\ttoolCalls: stepToolCalls,\n\t\t\t\t\t\t\t\ttoolOutputs: clientToolOutputs,\n\t\t\t\t\t\t\t\ttoolApprovalRequests: Object.values(toolApprovalRequests),\n\t\t\t\t\t\t\t\ttoolApprovalResponses,\n\t\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\tgeneratedFileDataCache\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst stepResponseMessages = await toResponseMessages({\n\t\t\t\t\t\t\t\tcontent: stepContent,\n\t\t\t\t\t\t\t\ttools\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst stepRequest = {\n\t\t\t\t\t\t\t\t...currentModelResponse.request,\n\t\t\t\t\t\t\t\tbody: include.requestBody ? currentModelResponse.request?.body : void 0,\n\t\t\t\t\t\t\t\tmessages: include.requestMessages ? cloneModelMessages(stepMessages) : void 0\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst stepResponse = {\n\t\t\t\t\t\t\t\t...currentModelResponse.response,\n\t\t\t\t\t\t\t\tmessages: cloneModelMessages(stepResponseMessages),\n\t\t\t\t\t\t\t\tbody: include.responseBody ? currentModelResponse.response?.body : void 0\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst currentStepResult = new DefaultStepResult({\n\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\tstepNumber,\n\t\t\t\t\t\t\t\tprovider: stepModel.provider,\n\t\t\t\t\t\t\t\tmodelId: stepModel.modelId,\n\t\t\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\t\t\tcontent: stepContent,\n\t\t\t\t\t\t\t\tfinishReason: currentModelResponse.finishReason.unified,\n\t\t\t\t\t\t\t\trawFinishReason: currentModelResponse.finishReason.raw,\n\t\t\t\t\t\t\t\tusage: stepUsage,\n\t\t\t\t\t\t\t\tperformance: stepPerformance,\n\t\t\t\t\t\t\t\twarnings: currentModelResponse.warnings,\n\t\t\t\t\t\t\t\tproviderMetadata: currentModelResponse.providerMetadata,\n\t\t\t\t\t\t\t\trequest: stepRequest,\n\t\t\t\t\t\t\t\tresponse: stepResponse,\n\t\t\t\t\t\t\t\ttoolsContext\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tlogWarnings({\n\t\t\t\t\t\t\t\twarnings: currentModelResponse.warnings ?? [],\n\t\t\t\t\t\t\t\tprovider: stepModel.provider,\n\t\t\t\t\t\t\t\tmodel: stepModel.modelId\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tsteps.push(currentStepResult);\n\t\t\t\t\t\t\tinstructionsForNextStep = stepInstructions;\n\t\t\t\t\t\t\tmessagesForNextStep = [...stepMessages, ...stepResponseMessages];\n\t\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\t\tevent: currentStepResult,\n\t\t\t\t\t\t\t\tcallbacks: [resolvedOnStepEnd, telemetryDispatcher.onStepEnd]\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn currentStepResult;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\tif (stepTimeoutId != null) clearTimeout(stepTimeoutId);\n\t\t\t\t}\n\t\t\t} while (clientToolOutputs.length + deniedToolApprovalResponses.length === clientToolCalls.length && (clientToolCalls.length > 0 || pendingDeferredToolCalls.size > 0) && !await isStopConditionMet({\n\t\t\t\tstopConditions,\n\t\t\t\tsteps\n\t\t\t}));\n\t\t\tconst lastStep = steps[steps.length - 1];\n\t\t\tconst totalUsage = steps.reduce((totalUsage, step) => {\n\t\t\t\treturn addLanguageModelUsage(totalUsage, step.usage);\n\t\t\t}, {\n\t\t\t\tinputTokens: void 0,\n\t\t\t\tinputTokenDetails: {\n\t\t\t\t\tnoCacheTokens: void 0,\n\t\t\t\t\tcacheReadTokens: void 0,\n\t\t\t\t\tcacheWriteTokens: void 0\n\t\t\t\t},\n\t\t\t\toutputTokens: void 0,\n\t\t\t\toutputTokenDetails: {\n\t\t\t\t\ttextTokens: void 0,\n\t\t\t\t\treasoningTokens: void 0\n\t\t\t\t},\n\t\t\t\ttotalTokens: void 0\n\t\t\t});\n\t\t\tconst files = steps.flatMap((step) => step.files);\n\t\t\tconst sources = steps.flatMap((step) => step.sources);\n\t\t\tconst toolCalls = steps.flatMap((step) => step.toolCalls);\n\t\t\tconst staticToolCalls = steps.flatMap((step) => step.staticToolCalls);\n\t\t\tconst dynamicToolCalls = steps.flatMap((step) => step.dynamicToolCalls);\n\t\t\tconst toolResults = steps.flatMap((step) => step.toolResults);\n\t\t\tconst staticToolResults = steps.flatMap((step) => step.staticToolResults);\n\t\t\tconst dynamicToolResults = steps.flatMap((step) => step.dynamicToolResults);\n\t\t\tconst warnings = steps.flatMap((step) => step.warnings ?? []);\n\t\t\tawait notify({\n\t\t\t\tevent: {\n\t\t\t\t\tcallId,\n\t\t\t\t\tstepNumber: lastStep.stepNumber,\n\t\t\t\t\tmodel: lastStep.model,\n\t\t\t\t\truntimeContext: lastStep.runtimeContext,\n\t\t\t\t\tfinishReason: lastStep.finishReason,\n\t\t\t\t\trawFinishReason: lastStep.rawFinishReason,\n\t\t\t\t\tusage: totalUsage,\n\t\t\t\t\ttotalUsage,\n\t\t\t\t\tcontent: steps.flatMap((step) => step.content),\n\t\t\t\t\ttext: lastStep.text,\n\t\t\t\t\treasoning: lastStep.reasoning,\n\t\t\t\t\treasoningText: lastStep.reasoningText,\n\t\t\t\t\tfiles,\n\t\t\t\t\tsources,\n\t\t\t\t\ttoolCalls,\n\t\t\t\t\tstaticToolCalls,\n\t\t\t\t\tdynamicToolCalls,\n\t\t\t\t\ttoolResults,\n\t\t\t\t\tstaticToolResults,\n\t\t\t\t\tdynamicToolResults,\n\t\t\t\t\tresponseMessages: [...initialResponseMessages, ...steps.flatMap((step) => step.response.messages)],\n\t\t\t\t\twarnings,\n\t\t\t\t\trequest: lastStep.request,\n\t\t\t\t\tresponse: lastStep.response,\n\t\t\t\t\tproviderMetadata: lastStep.providerMetadata,\n\t\t\t\t\tsteps,\n\t\t\t\t\tfinalStep: lastStep,\n\t\t\t\t\ttoolsContext\n\t\t\t\t},\n\t\t\t\tcallbacks: [onEnd, telemetryDispatcher.onEnd]\n\t\t\t});\n\t\t\tlet resolvedOutput;\n\t\t\tif (lastStep.finishReason === \"stop\" || lastStep.finishReason !== \"tool-calls\" && lastStep.text.length > 0) resolvedOutput = await (output ?? text()).parseCompleteOutput({ text: lastStep.text }, {\n\t\t\t\tresponse: lastStep.response,\n\t\t\t\tusage: lastStep.usage,\n\t\t\t\tfinishReason: lastStep.finishReason\n\t\t\t});\n\t\t\treturn new DefaultGenerateTextResult({\n\t\t\t\tinitialResponseMessages,\n\t\t\t\tsteps,\n\t\t\t\ttotalUsage,\n\t\t\t\toutput: resolvedOutput\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\tcallId,\n\t\t\t\terror\n\t\t\t});\n\t\t\tthrow wrapGatewayError(error);\n\t\t}\n\t};\n\treturn await runInTracingChannelSpan({\n\t\ttype: \"generateText\",\n\t\tevent: generateTextStartEvent,\n\t\texecute: executeGenerateText\n\t});\n}\nasync function executeTools({ toolCalls, tools, callId, messages, abortSignal, timeout, experimental_sandbox: sandbox, toolsContext, onToolExecutionStart, onToolExecutionEnd, executeToolInTelemetryContext, runInTracingChannelSpan }) {\n\treturn (await Promise.all(toolCalls.map(async (toolCall) => await executeToolCall({\n\t\ttoolCall,\n\t\ttools,\n\t\tcallId,\n\t\tmessages,\n\t\tabortSignal,\n\t\ttimeout,\n\t\texperimental_sandbox: sandbox,\n\t\ttoolsContext,\n\t\tonToolExecutionStart,\n\t\tonToolExecutionEnd,\n\t\texecuteToolInTelemetryContext,\n\t\trunInTracingChannelSpan\n\t})))).filter((result) => result != null);\n}\n//#endregion\n//#region src/util/prepare-headers.ts\nfunction prepareHeaders(headers, defaultHeaders) {\n\tconst responseHeaders = new Headers(headers ?? {});\n\tfor (const [key, value] of Object.entries(defaultHeaders)) if (!responseHeaders.has(key)) responseHeaders.set(key, value);\n\treturn responseHeaders;\n}\n//#endregion\n//#region src/text-stream/create-text-stream-response.ts\n/**\n* Creates a Response object from a text stream.\n* Each text chunk is encoded as UTF-8 and sent as a separate chunk.\n* Sets a `Content-Type` header to `text/plain; charset=utf-8`.\n*\n* @param options - The options for creating the response.\n* @param options.status - Optional HTTP status code (default: 200).\n* @param options.statusText - Optional HTTP status text.\n* @param options.headers - Optional response headers.\n* @param options.stream - The text stream to send.\n* @returns A Response object with the text stream body.\n*/\nfunction createTextStreamResponse({ status, statusText, headers, stream }) {\n\treturn new Response(stream.pipeThrough(new TextEncoderStream()), {\n\t\tstatus: status ?? 200,\n\t\tstatusText,\n\t\theaders: prepareHeaders(headers, { \"content-type\": \"text/plain; charset=utf-8\" })\n\t});\n}\n//#endregion\n//#region src/util/write-to-server-response.ts\n/**\n* Writes the content of a stream to a server response.\n*\n* When the client disconnects before the stream has been fully written\n* (premature `close`), the stream is cancelled so that upstream resources\n* can be released, and no further chunks are written.\n*/\nfunction writeToServerResponse({ response, status, statusText, headers, stream }) {\n\tconst statusCode = status ?? 200;\n\tif (headers != null) response.setHeaders(headers);\n\tif (statusText !== void 0) response.writeHead(statusCode, statusText);\n\telse response.writeHead(statusCode);\n\tconst reader = stream.getReader();\n\tlet clientDisconnected = false;\n\tlet onDisconnect;\n\tconst handleClose = () => {\n\t\tif (response.writableFinished) return;\n\t\tclientDisconnected = true;\n\t\tonDisconnect?.();\n\t\treader.cancel(/* @__PURE__ */ new Error(\"Client disconnected.\")).catch(() => {});\n\t};\n\tresponse.once(\"close\", handleClose);\n\tif (response.destroyed) handleClose();\n\tconst read = async () => {\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done || clientDisconnected || response.destroyed) break;\n\t\t\t\tconst canContinue = response.write(value);\n\t\t\t\tconst flush = response.flush;\n\t\t\t\tif (typeof flush === \"function\") flush.call(response);\n\t\t\t\tif (!canContinue) {\n\t\t\t\t\tawait new Promise((resolve) => {\n\t\t\t\t\t\tonDisconnect = resolve;\n\t\t\t\t\t\tresponse.once(\"drain\", resolve);\n\t\t\t\t\t});\n\t\t\t\t\tonDisconnect = void 0;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tresponse.off(\"close\", handleClose);\n\t\t\tif (clientDisconnected || response.destroyed) reader.cancel().catch(() => {});\n\t\t\telse response.end();\n\t\t}\n\t};\n\treturn read();\n}\n//#endregion\n//#region src/text-stream/pipe-text-stream-to-response.ts\n/**\n* Writes a text stream to a Node.js ServerResponse object.\n* Each text chunk is encoded as UTF-8 and written as a separate chunk.\n* Sets a `Content-Type` header to `text/plain; charset=utf-8`.\n*\n* @param options - The options for piping the stream.\n* @param options.response - The Node.js ServerResponse to write to.\n* @param options.status - Optional HTTP status code.\n* @param options.statusText - Optional HTTP status text.\n* @param options.headers - Optional response headers.\n* @param options.stream - The text stream to pipe.\n* @returns A promise that resolves when the stream has been written.\n*/\nfunction pipeTextStreamToResponse({ response, status, statusText, headers, stream }) {\n\treturn writeToServerResponse({\n\t\tresponse,\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: prepareHeaders(headers, { \"content-type\": \"text/plain; charset=utf-8\" }),\n\t\tstream: stream.pipeThrough(new TextEncoderStream())\n\t});\n}\n//#endregion\n//#region src/text-stream/to-text-stream.ts\n/**\n* Converts a stream of `TextStreamPart` chunks into a stream of text deltas.\n*/\nfunction toTextStream({ stream }) {\n\treturn stream.pipeThrough(new TransformStream({ transform(part, controller) {\n\t\tif (part.type === \"text-delta\") controller.enqueue(part.text);\n\t} }));\n}\n//#endregion\n//#region src/ui-message-stream/create-sse-stream-with-keep-alive.ts\nconst STREAM_OPEN_COMMENT = \": stream-open\\n\\n\";\nconst KEEP_ALIVE_COMMENT = \": keep-alive\\n\\n\";\nfunction createSseStreamWithKeepAlive({ stream, keepAliveMs }) {\n\tif (keepAliveMs == null) return stream;\n\tif (!Number.isFinite(keepAliveMs) || keepAliveMs <= 0 || keepAliveMs > 2147483647) throw new Error(\"keepAliveMs must be a positive finite timer duration no greater than 2147483647\");\n\tconst reader = stream.getReader();\n\tlet keepAliveTimeout;\n\tlet isCancelled = false;\n\tconst clearKeepAliveTimeout = () => {\n\t\tclearTimeout(keepAliveTimeout);\n\t\tkeepAliveTimeout = void 0;\n\t};\n\tconst scheduleKeepAlive = (controller) => {\n\t\tclearKeepAliveTimeout();\n\t\tkeepAliveTimeout = setTimeout(() => {\n\t\t\tif (isCancelled) return;\n\t\t\tif (controller.desiredSize != null && controller.desiredSize > 0) controller.enqueue(KEEP_ALIVE_COMMENT);\n\t\t\tscheduleKeepAlive(controller);\n\t\t}, keepAliveMs);\n\t};\n\treturn new ReadableStream({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue(STREAM_OPEN_COMMENT);\n\t\t\tscheduleKeepAlive(controller);\n\t\t},\n\t\tpull(controller) {\n\t\t\treturn reader.read().then((result) => {\n\t\t\t\tclearKeepAliveTimeout();\n\t\t\t\tif (isCancelled) return;\n\t\t\t\tif (result.done) controller.close();\n\t\t\t\telse {\n\t\t\t\t\tcontroller.enqueue(result.value);\n\t\t\t\t\tscheduleKeepAlive(controller);\n\t\t\t\t}\n\t\t\t}, (error) => {\n\t\t\t\tclearKeepAliveTimeout();\n\t\t\t\tif (!isCancelled) throw error;\n\t\t\t});\n\t\t},\n\t\tasync cancel(reason) {\n\t\t\tisCancelled = true;\n\t\t\tclearKeepAliveTimeout();\n\t\t\tawait reader.cancel(reason);\n\t\t}\n\t});\n}\n//#endregion\n//#region src/ui-message-stream/json-to-sse-transform-stream.ts\n/**\n* A TransformStream that converts JSON objects to Server-Sent Events (SSE) format.\n* Each object is serialized to JSON and wrapped in `data: ...\\n\\n` format.\n* When the stream ends, a `data: [DONE]\\n\\n` message is sent.\n*/\nvar JsonToSseTransformStream = class extends TransformStream {\n\tconstructor() {\n\t\tsuper({\n\t\t\ttransform(part, controller) {\n\t\t\t\tcontroller.enqueue(`data: ${JSON.stringify(part)}\\n\\n`);\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tcontroller.enqueue(\"data: [DONE]\\n\\n\");\n\t\t\t}\n\t\t});\n\t}\n};\n//#endregion\n//#region src/ui-message-stream/ui-message-stream-headers.ts\nconst UI_MESSAGE_STREAM_HEADERS = {\n\t\"content-type\": \"text/event-stream\",\n\t\"cache-control\": \"no-cache\",\n\tconnection: \"keep-alive\",\n\t\"x-vercel-ai-ui-message-stream\": \"v1\",\n\t\"x-accel-buffering\": \"no\"\n};\n//#endregion\n//#region src/ui-message-stream/create-ui-message-stream-response.ts\n/**\n* Creates a Response object from a UI message stream.\n* The stream is transformed to Server-Sent Events (SSE) format.\n*\n* @param options.status - The HTTP status code for the response.\n* @param options.statusText - The HTTP status text for the response.\n* @param options.headers - Additional HTTP headers to include in the response.\n* @param options.stream - The UI message chunk stream to send.\n* @param options.keepAliveMs - Optional interval for sending SSE keep-alive comments.\n* @param options.consumeSseStream - Optional callback to consume a copy of the SSE stream independently.\n*\n* @returns A `Response` object with the UI message stream as the body.\n*/\nfunction createUIMessageStreamResponse({ status, statusText, headers, stream, keepAliveMs, consumeSseStream }) {\n\tlet sseStream = createSseStreamWithKeepAlive({\n\t\tstream: stream.pipeThrough(new JsonToSseTransformStream()),\n\t\tkeepAliveMs\n\t});\n\tif (consumeSseStream) {\n\t\tconst [stream1, stream2] = sseStream.tee();\n\t\tsseStream = stream1;\n\t\tconsumeSseStream({ stream: stream2 });\n\t}\n\treturn new Response(sseStream.pipeThrough(new TextEncoderStream()), {\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)\n\t});\n}\n//#endregion\n//#region src/ui-message-stream/pipe-ui-message-stream-to-response.ts\n/**\n* Pipes a UI message stream to a Node.js ServerResponse object.\n* The stream is transformed to Server-Sent Events (SSE) format.\n*\n* @param options.response - The Node.js ServerResponse object to write to.\n* @param options.status - The HTTP status code for the response.\n* @param options.statusText - The HTTP status text for the response.\n* @param options.headers - Additional HTTP headers to include in the response.\n* @param options.stream - The UI message chunk stream to send.\n* @param options.keepAliveMs - Optional interval for sending SSE keep-alive comments.\n* @param options.consumeSseStream - Optional callback to consume a copy of the SSE stream independently.\n* @returns A promise that resolves when the stream has been written.\n*/\nfunction pipeUIMessageStreamToResponse({ response, status, statusText, headers, stream, keepAliveMs, consumeSseStream }) {\n\tlet sseStream = createSseStreamWithKeepAlive({\n\t\tstream: stream.pipeThrough(new JsonToSseTransformStream()),\n\t\tkeepAliveMs\n\t});\n\tif (consumeSseStream) {\n\t\tconst [stream1, stream2] = sseStream.tee();\n\t\tsseStream = stream1;\n\t\tconsumeSseStream({ stream: stream2 });\n\t}\n\treturn writeToServerResponse({\n\t\tresponse,\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS),\n\t\tstream: sseStream.pipeThrough(new TextEncoderStream())\n\t});\n}\n//#endregion\n//#region src/ui-message-stream/get-response-ui-message-id.ts\n/**\n* Determines the message ID to use for a response message.\n* If the last message is an assistant message, its ID is reused (continuation).\n* Otherwise, a new ID is generated or the provided ID is used.\n*\n* @param options.originalMessages - The original messages. If not provided, returns `undefined`\n* since client-side ID generation is used in non-persistence mode.\n* @param options.responseMessageId - The response message ID or an ID generator function.\n*\n* @returns The message ID to use, or `undefined` if no persistence mode.\n*/\nfunction getResponseUIMessageId({ originalMessages, responseMessageId }) {\n\tif (originalMessages == null) return;\n\tconst lastMessage = originalMessages[originalMessages.length - 1];\n\treturn lastMessage?.role === \"assistant\" ? lastMessage.id : typeof responseMessageId === \"function\" ? responseMessageId() : responseMessageId;\n}\n//#endregion\n//#region src/ui-message-stream/ui-message-chunks.ts\nconst toolMetadataSchema$1 = z.record(z.string(), jsonValueSchema.optional());\nconst uiMessageChunkSchema = lazySchema(() => zodSchema$1(z.union([\n\tz.looseObject({\n\t\ttype: z.literal(\"text-start\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"text-delta\"),\n\t\tid: z.string(),\n\t\tdelta: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"text-end\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"error\"),\n\t\terrorText: z.string()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-start\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\ttoolMetadata: toolMetadataSchema$1.optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\ttitle: z.string().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-delta\"),\n\t\ttoolCallId: z.string(),\n\t\tinputTextDelta: z.string()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-available\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tinput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\ttoolMetadata: toolMetadataSchema$1.optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\ttitle: z.string().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-error\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tinput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\ttoolMetadata: toolMetadataSchema$1.optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\terrorText: z.string(),\n\t\ttitle: z.string().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-approval-request\"),\n\t\tapprovalId: z.string(),\n\t\ttoolCallId: z.string(),\n\t\tapprovalDescriptor: z.unknown().optional(),\n\t\tinputSchemaInput: z.unknown().optional(),\n\t\treason: z.string().optional(),\n\t\tisAutomatic: z.boolean().optional(),\n\t\tsignature: z.string().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-approval-response\"),\n\t\tapprovalId: z.string(),\n\t\tapproved: z.boolean(),\n\t\treason: z.string().optional(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-output-available\"),\n\t\ttoolCallId: z.string(),\n\t\toutput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\ttoolMetadata: toolMetadataSchema$1.optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\tpreliminary: z.boolean().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-output-error\"),\n\t\ttoolCallId: z.string(),\n\t\terrorText: z.string(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\ttoolMetadata: toolMetadataSchema$1.optional(),\n\t\tdynamic: z.boolean().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-output-denied\"),\n\t\ttoolCallId: z.string()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"reasoning-start\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"reasoning-delta\"),\n\t\tid: z.string(),\n\t\tdelta: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"reasoning-end\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"custom\"),\n\t\tkind: z.string().transform((value) => value),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"source-url\"),\n\t\tsourceId: z.string(),\n\t\turl: z.string(),\n\t\ttitle: z.string().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"source-document\"),\n\t\tsourceId: z.string(),\n\t\tmediaType: z.string(),\n\t\ttitle: z.string(),\n\t\tfilename: z.string().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"file\"),\n\t\turl: z.string(),\n\t\tmediaType: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"reasoning-file\"),\n\t\turl: z.string(),\n\t\tmediaType: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.custom((value) => typeof value === \"string\" && value.startsWith(\"data-\"), { message: \"Type must start with \\\"data-\\\"\" }),\n\t\tid: z.string().optional(),\n\t\tdata: z.unknown(),\n\t\ttransient: z.boolean().optional()\n\t}),\n\tz.looseObject({ type: z.literal(\"start-step\") }),\n\tz.looseObject({ type: z.literal(\"finish-step\") }),\n\tz.looseObject({ type: z.literal(\"reset-step\") }),\n\tz.looseObject({\n\t\ttype: z.literal(\"start\"),\n\t\tmessageId: z.string().optional(),\n\t\tmessageMetadata: z.unknown().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"finish\"),\n\t\tfinishReason: z.enum([\n\t\t\t\"stop\",\n\t\t\t\"length\",\n\t\t\t\"content-filter\",\n\t\t\t\"tool-calls\",\n\t\t\t\"error\",\n\t\t\t\"other\"\n\t\t]).optional(),\n\t\tmessageMetadata: z.unknown().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"abort\"),\n\t\treason: z.string().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"message-metadata\"),\n\t\tmessageMetadata: z.unknown()\n\t})\n])));\nfunction isDataUIMessageChunk(chunk) {\n\treturn chunk.type.startsWith(\"data-\");\n}\n//#endregion\n//#region src/util/create-id-map.ts\n/**\n* Creates a string-keyed map without an object prototype.\n*\n* Use this for lookup tables keyed by IDs or names that may come from outside\n* the SDK, such as streamed chunk IDs or tool call IDs. Unlike `{}`, these maps\n* do not inherit `__proto__`, `constructor`, or other Object prototype members,\n* so a missing untrusted key cannot resolve to a shared prototype object.\n*/\nfunction createIdMap() {\n\treturn Object.create(null);\n}\n//#endregion\n//#region src/ui/ui-messages.ts\n/**\n* Check if a message part is a data part.\n*/\nfunction isDataUIPart(part) {\n\treturn part.type.startsWith(\"data-\");\n}\n/**\n* Type guard to check if a message part is a text part.\n*/\nfunction isTextUIPart(part) {\n\treturn part.type === \"text\";\n}\n/**\n* Type guard to check if a message part is a custom part.\n*/\nfunction isCustomContentUIPart(part) {\n\treturn part.type === \"custom\";\n}\n/**\n* Type guard to check if a message part is a file part.\n*/\nfunction isFileUIPart(part) {\n\treturn part.type === \"file\";\n}\n/**\n* Type guard to check if a message part is a reasoning file part.\n*/\nfunction isReasoningFileUIPart(part) {\n\treturn part.type === \"reasoning-file\";\n}\n/**\n* Type guard to check if a message part is a reasoning part.\n*/\nfunction isReasoningUIPart(part) {\n\treturn part.type === \"reasoning\";\n}\n/**\n* Check if a message part is a static tool part.\n*\n* Static tools are tools for which the types are known at development time.\n*/\nfunction isStaticToolUIPart(part) {\n\treturn part.type.startsWith(\"tool-\");\n}\n/**\n* Check if a message part is a dynamic tool part.\n*\n* Dynamic tools are tools for which the input and output types are unknown.\n*/\nfunction isDynamicToolUIPart(part) {\n\treturn part.type === \"dynamic-tool\";\n}\n/**\n* Check if a message part is a tool part.\n*\n* Tool parts are either static or dynamic tools.\n*\n* Use `isStaticToolUIPart` or `isDynamicToolUIPart` to check the type of the tool.\n*/\nfunction isToolUIPart(part) {\n\treturn isStaticToolUIPart(part) || isDynamicToolUIPart(part);\n}\n/**\n* Check if a message part is a tool output error part.\n*\n* This works for both static and dynamic tools.\n*/\nfunction isToolOutputErrorUIPart(part) {\n\treturn isToolUIPart(part) && part.state === \"output-error\";\n}\n/**\n* Returns the name of the static tool.\n*\n* The possible values are the keys of the tool set.\n*/\nfunction getStaticToolName(part) {\n\treturn part.type.split(\"-\").slice(1).join(\"-\");\n}\n/**\n* Returns the name of the tool (static or dynamic).\n*\n* This function will not restrict the name to the keys of the tool set.\n* If you need to restrict the name to the keys of the tool set, use `getStaticToolName` instead.\n*/\nfunction getToolName(part) {\n\treturn isDynamicToolUIPart(part) ? part.toolName : getStaticToolName(part);\n}\n/**\n* @deprecated Use getToolName instead.\n*/\nconst getToolOrDynamicToolName = getToolName;\n//#endregion\n//#region src/ui/process-ui-message-stream.ts\nfunction createStreamingUIMessageState({ lastMessage, messageId }) {\n\tconst message = lastMessage?.role === \"assistant\" ? lastMessage : {\n\t\tid: messageId,\n\t\tmetadata: void 0,\n\t\trole: \"assistant\",\n\t\tparts: []\n\t};\n\tconst partialToolCalls = createIdMap();\n\tconst lastStepStartIndex = message.parts.findLastIndex((part) => part.type === \"step-start\");\n\tlet staticToolIndex = 0;\n\tfor (const part of message.parts.slice(lastStepStartIndex + 1)) {\n\t\tif (!isToolUIPart(part)) continue;\n\t\tconst index = staticToolIndex;\n\t\tif (isStaticToolUIPart(part)) staticToolIndex++;\n\t\tif (part.state !== \"input-streaming\") continue;\n\t\tpartialToolCalls[part.toolCallId] = {\n\t\t\ttext: part.rawInput ?? \"\",\n\t\t\tindex,\n\t\t\ttoolName: part.type === \"dynamic-tool\" ? part.toolName : getStaticToolName(part),\n\t\t\tdynamic: part.type === \"dynamic-tool\",\n\t\t\ttitle: part.title,\n\t\t\ttoolMetadata: part.toolMetadata\n\t\t};\n\t}\n\treturn {\n\t\tmessage,\n\t\tactiveTextParts: createIdMap(),\n\t\tactiveReasoningParts: createIdMap(),\n\t\tpartialToolCalls\n\t};\n}\nfunction processUIMessageStream({ stream, messageMetadataSchema, dataPartSchemas, runUpdateMessageJob, onError, onToolCall, onData, resetStateOnMessageIdChange = false, resetStateOnFirstMessageStart = false }) {\n\treturn stream.pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\tawait runUpdateMessageJob(async ({ state, write }) => {\n\t\t\tfunction getCurrentStepParts() {\n\t\t\t\tconst parts = state.message.parts;\n\t\t\t\tlet currentStepStartIndex = parts.length - 1;\n\t\t\t\twhile (currentStepStartIndex >= 0 && parts[currentStepStartIndex].type !== \"step-start\") currentStepStartIndex--;\n\t\t\t\treturn parts.slice(currentStepStartIndex + 1);\n\t\t\t}\n\t\t\tfunction getCurrentStepToolInvocations() {\n\t\t\t\treturn getCurrentStepParts().filter(isToolUIPart);\n\t\t\t}\n\t\t\tfunction getToolInvocation(toolCallId) {\n\t\t\t\tlet toolInvocation = getCurrentStepToolInvocations().find((invocation) => invocation.toolCallId === toolCallId);\n\t\t\t\tif (toolInvocation == null) {\n\t\t\t\t\tconst parts = state.message.parts;\n\t\t\t\t\tfor (let i = parts.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tconst part = parts[i];\n\t\t\t\t\t\tif (isToolUIPart(part) && part.toolCallId === toolCallId) {\n\t\t\t\t\t\t\ttoolInvocation = part;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (toolInvocation == null) throw new UIMessageStreamError({\n\t\t\t\t\tchunkType: \"tool-invocation\",\n\t\t\t\t\tchunkId: toolCallId,\n\t\t\t\t\tmessage: `No tool invocation found for tool call ID \"${toolCallId}\".`\n\t\t\t\t});\n\t\t\t\treturn toolInvocation;\n\t\t\t}\n\t\t\tfunction getToolInvocationByApprovalId(approvalId) {\n\t\t\t\tconst toolInvocation = state.message.parts.filter(isToolUIPart).find((invocation) => invocation.approval?.id === approvalId);\n\t\t\t\tif (toolInvocation == null) throw new UIMessageStreamError({\n\t\t\t\t\tchunkType: \"tool-approval-response\",\n\t\t\t\t\tchunkId: approvalId,\n\t\t\t\t\tmessage: `No tool invocation found for approval ID \"${approvalId}\".`\n\t\t\t\t});\n\t\t\t\treturn toolInvocation;\n\t\t\t}\n\t\t\tfunction updateToolPart(options, existingPart) {\n\t\t\t\tconst part = existingPart ?? getCurrentStepParts().find((part) => isStaticToolUIPart(part) && part.toolCallId === options.toolCallId);\n\t\t\t\tconst anyOptions = options;\n\t\t\t\tconst anyPart = part;\n\t\t\t\tif (part != null) {\n\t\t\t\t\tpart.state = options.state;\n\t\t\t\t\tanyPart.input = anyOptions.input;\n\t\t\t\t\tanyPart.output = anyOptions.output;\n\t\t\t\t\tanyPart.errorText = anyOptions.errorText;\n\t\t\t\t\tanyPart.rawInput = anyOptions.rawInput;\n\t\t\t\t\tanyPart.preliminary = anyOptions.preliminary;\n\t\t\t\t\tif (options.title !== void 0) anyPart.title = options.title;\n\t\t\t\t\tif (options.toolMetadata !== void 0) anyPart.toolMetadata = options.toolMetadata;\n\t\t\t\t\tanyPart.providerExecuted = anyOptions.providerExecuted ?? part.providerExecuted;\n\t\t\t\t\tconst providerMetadata = anyOptions.providerMetadata;\n\t\t\t\t\tif (providerMetadata != null) {\n\t\t\t\t\t\tif (options.state === \"output-available\" || options.state === \"output-error\") {\n\t\t\t\t\t\t\tconst resultPart = part;\n\t\t\t\t\t\t\tresultPart.resultProviderMetadata = providerMetadata;\n\t\t\t\t\t\t} else part.callProviderMetadata = providerMetadata;\n\t\t\t\t\t}\n\t\t\t\t} else state.message.parts.push({\n\t\t\t\t\ttype: `tool-${options.toolName}`,\n\t\t\t\t\ttoolCallId: options.toolCallId,\n\t\t\t\t\tstate: options.state,\n\t\t\t\t\ttitle: options.title,\n\t\t\t\t\t...options.toolMetadata !== void 0 ? { toolMetadata: options.toolMetadata } : {},\n\t\t\t\t\tinput: anyOptions.input,\n\t\t\t\t\toutput: anyOptions.output,\n\t\t\t\t\trawInput: anyOptions.rawInput,\n\t\t\t\t\terrorText: anyOptions.errorText,\n\t\t\t\t\tproviderExecuted: anyOptions.providerExecuted,\n\t\t\t\t\tpreliminary: anyOptions.preliminary,\n\t\t\t\t\t...anyOptions.providerMetadata != null && (options.state === \"output-available\" || options.state === \"output-error\") ? { resultProviderMetadata: anyOptions.providerMetadata } : {},\n\t\t\t\t\t...anyOptions.providerMetadata != null && !(options.state === \"output-available\" || options.state === \"output-error\") ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tfunction updateDynamicToolPart(options, existingPart) {\n\t\t\t\tconst part = existingPart ?? getCurrentStepParts().find((part) => part.type === \"dynamic-tool\" && part.toolCallId === options.toolCallId);\n\t\t\t\tconst anyOptions = options;\n\t\t\t\tconst anyPart = part;\n\t\t\t\tif (part != null) {\n\t\t\t\t\tpart.state = options.state;\n\t\t\t\t\tanyPart.toolName = options.toolName;\n\t\t\t\t\tanyPart.input = anyOptions.input;\n\t\t\t\t\tanyPart.output = anyOptions.output;\n\t\t\t\t\tanyPart.errorText = anyOptions.errorText;\n\t\t\t\t\tanyPart.rawInput = anyOptions.rawInput;\n\t\t\t\t\tanyPart.preliminary = anyOptions.preliminary;\n\t\t\t\t\tif (options.title !== void 0) anyPart.title = options.title;\n\t\t\t\t\tif (options.toolMetadata !== void 0) anyPart.toolMetadata = options.toolMetadata;\n\t\t\t\t\tanyPart.providerExecuted = anyOptions.providerExecuted ?? part.providerExecuted;\n\t\t\t\t\tconst providerMetadata = anyOptions.providerMetadata;\n\t\t\t\t\tif (providerMetadata != null) {\n\t\t\t\t\t\tif (options.state === \"output-available\" || options.state === \"output-error\") {\n\t\t\t\t\t\t\tconst resultPart = part;\n\t\t\t\t\t\t\tresultPart.resultProviderMetadata = providerMetadata;\n\t\t\t\t\t\t} else part.callProviderMetadata = providerMetadata;\n\t\t\t\t\t}\n\t\t\t\t} else state.message.parts.push({\n\t\t\t\t\ttype: \"dynamic-tool\",\n\t\t\t\t\ttoolName: options.toolName,\n\t\t\t\t\ttoolCallId: options.toolCallId,\n\t\t\t\t\tstate: options.state,\n\t\t\t\t\tinput: anyOptions.input,\n\t\t\t\t\toutput: anyOptions.output,\n\t\t\t\t\terrorText: anyOptions.errorText,\n\t\t\t\t\tpreliminary: anyOptions.preliminary,\n\t\t\t\t\tproviderExecuted: anyOptions.providerExecuted,\n\t\t\t\t\ttitle: options.title,\n\t\t\t\t\t...options.toolMetadata !== void 0 ? { toolMetadata: options.toolMetadata } : {},\n\t\t\t\t\t...anyOptions.providerMetadata != null && (options.state === \"output-available\" || options.state === \"output-error\") ? { resultProviderMetadata: anyOptions.providerMetadata } : {},\n\t\t\t\t\t...anyOptions.providerMetadata != null && !(options.state === \"output-available\" || options.state === \"output-error\") ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tasync function updateMessageMetadata(metadata) {\n\t\t\t\tif (metadata != null) {\n\t\t\t\t\tconst mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;\n\t\t\t\t\tif (messageMetadataSchema != null) await validateTypes({\n\t\t\t\t\t\tvalue: mergedMetadata,\n\t\t\t\t\t\tschema: messageMetadataSchema,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tfield: \"message.metadata\",\n\t\t\t\t\t\t\tentityId: state.message.id\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tstate.message.metadata = mergedMetadata;\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"text-start\": {\n\t\t\t\t\tconst textPart = {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\tstate: \"streaming\"\n\t\t\t\t\t};\n\t\t\t\t\tstate.activeTextParts[chunk.id] = textPart;\n\t\t\t\t\tstate.message.parts.push(textPart);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-delta\": {\n\t\t\t\t\tconst textPart = state.activeTextParts[chunk.id];\n\t\t\t\t\tif (textPart == null) throw new UIMessageStreamError({\n\t\t\t\t\t\tchunkType: \"text-delta\",\n\t\t\t\t\t\tchunkId: chunk.id,\n\t\t\t\t\t\tmessage: `Received text-delta for missing text part with ID \"${chunk.id}\". Ensure a \"text-start\" chunk is sent before any \"text-delta\" chunks.`\n\t\t\t\t\t});\n\t\t\t\t\ttextPart.text += chunk.delta;\n\t\t\t\t\ttextPart.providerMetadata = chunk.providerMetadata ?? textPart.providerMetadata;\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-end\": {\n\t\t\t\t\tconst textPart = state.activeTextParts[chunk.id];\n\t\t\t\t\tif (textPart == null) throw new UIMessageStreamError({\n\t\t\t\t\t\tchunkType: \"text-end\",\n\t\t\t\t\t\tchunkId: chunk.id,\n\t\t\t\t\t\tmessage: `Received text-end for missing text part with ID \"${chunk.id}\". Ensure a \"text-start\" chunk is sent before any \"text-end\" chunks.`\n\t\t\t\t\t});\n\t\t\t\t\ttextPart.state = \"done\";\n\t\t\t\t\ttextPart.providerMetadata = chunk.providerMetadata ?? textPart.providerMetadata;\n\t\t\t\t\tdelete state.activeTextParts[chunk.id];\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tconst customPart = {\n\t\t\t\t\t\ttype: \"custom\",\n\t\t\t\t\t\tkind: chunk.kind,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\tstate.message.parts.push(customPart);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-start\": {\n\t\t\t\t\tconst reasoningPart = {\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\tstate: \"streaming\"\n\t\t\t\t\t};\n\t\t\t\t\tstate.activeReasoningParts[chunk.id] = reasoningPart;\n\t\t\t\t\tstate.message.parts.push(reasoningPart);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-delta\": {\n\t\t\t\t\tconst reasoningPart = state.activeReasoningParts[chunk.id];\n\t\t\t\t\tif (reasoningPart == null) throw new UIMessageStreamError({\n\t\t\t\t\t\tchunkType: \"reasoning-delta\",\n\t\t\t\t\t\tchunkId: chunk.id,\n\t\t\t\t\t\tmessage: `Received reasoning-delta for missing reasoning part with ID \"${chunk.id}\". Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-delta\" chunks.`\n\t\t\t\t\t});\n\t\t\t\t\treasoningPart.text += chunk.delta;\n\t\t\t\t\treasoningPart.providerMetadata = chunk.providerMetadata ?? reasoningPart.providerMetadata;\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-end\": {\n\t\t\t\t\tconst reasoningPart = state.activeReasoningParts[chunk.id];\n\t\t\t\t\tif (reasoningPart == null) throw new UIMessageStreamError({\n\t\t\t\t\t\tchunkType: \"reasoning-end\",\n\t\t\t\t\t\tchunkId: chunk.id,\n\t\t\t\t\t\tmessage: `Received reasoning-end for missing reasoning part with ID \"${chunk.id}\". Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-end\" chunks.`\n\t\t\t\t\t});\n\t\t\t\t\treasoningPart.providerMetadata = chunk.providerMetadata ?? reasoningPart.providerMetadata;\n\t\t\t\t\treasoningPart.state = \"done\";\n\t\t\t\t\tdelete state.activeReasoningParts[chunk.id];\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"file\":\n\t\t\t\tcase \"reasoning-file\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: chunk.type,\n\t\t\t\t\t\tmediaType: chunk.mediaType,\n\t\t\t\t\t\turl: chunk.url,\n\t\t\t\t\t\t...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"source-url\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"source-url\",\n\t\t\t\t\t\tsourceId: chunk.sourceId,\n\t\t\t\t\t\turl: chunk.url,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"source-document\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"source-document\",\n\t\t\t\t\t\tsourceId: chunk.sourceId,\n\t\t\t\t\t\tmediaType: chunk.mediaType,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\tfilename: chunk.filename,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-input-start\": {\n\t\t\t\t\tconst toolInvocations = getCurrentStepParts().filter(isStaticToolUIPart);\n\t\t\t\t\tstate.partialToolCalls[chunk.toolCallId] = {\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tindex: toolInvocations.length,\n\t\t\t\t\t\tdynamic: chunk.dynamic,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata\n\t\t\t\t\t};\n\t\t\t\t\tif (chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-input-delta\": {\n\t\t\t\t\tconst partialToolCall = state.partialToolCalls[chunk.toolCallId];\n\t\t\t\t\tif (partialToolCall == null) throw new UIMessageStreamError({\n\t\t\t\t\t\tchunkType: \"tool-input-delta\",\n\t\t\t\t\t\tchunkId: chunk.toolCallId,\n\t\t\t\t\t\tmessage: `Received tool-input-delta for missing tool call with ID \"${chunk.toolCallId}\". Ensure a \"tool-input-start\" chunk is sent before any \"tool-input-delta\" chunks.`\n\t\t\t\t\t});\n\t\t\t\t\tpartialToolCall.text += chunk.inputTextDelta;\n\t\t\t\t\tconst { value: partialArgs } = await parsePartialJson(partialToolCall.text);\n\t\t\t\t\tif (partialToolCall.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: partialToolCall.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: partialArgs,\n\t\t\t\t\t\trawInput: partialToolCall.text,\n\t\t\t\t\t\ttitle: partialToolCall.title,\n\t\t\t\t\t\ttoolMetadata: partialToolCall.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: partialToolCall.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: partialArgs,\n\t\t\t\t\t\trawInput: partialToolCall.text,\n\t\t\t\t\t\ttitle: partialToolCall.title,\n\t\t\t\t\t\ttoolMetadata: partialToolCall.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-input-available\":\n\t\t\t\t\tif (chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-available\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-available\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tif (onToolCall && !chunk.providerExecuted) await onToolCall({ toolCall: chunk });\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-input-error\": {\n\t\t\t\t\tconst existingPart = getCurrentStepParts().filter(isToolUIPart).find((p) => p.toolCallId === chunk.toolCallId);\n\t\t\t\t\tif (existingPart != null ? existingPart.type === \"dynamic-tool\" : !!chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-approval-request\": {\n\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\ttoolInvocation.state = \"approval-requested\";\n\t\t\t\t\ttoolInvocation.approval = {\n\t\t\t\t\t\tid: chunk.approvalId,\n\t\t\t\t\t\t...chunk.approvalDescriptor != null ? { descriptor: chunk.approvalDescriptor } : {},\n\t\t\t\t\t\t...Object.prototype.hasOwnProperty.call(chunk, \"inputSchemaInput\") ? { inputSchemaInput: chunk.inputSchemaInput } : {},\n\t\t\t\t\t\t...chunk.reason != null ? { requestReason: chunk.reason } : {},\n\t\t\t\t\t\t...chunk.isAutomatic === true ? { isAutomatic: true } : {},\n\t\t\t\t\t\t...chunk.signature != null ? { signature: chunk.signature } : {}\n\t\t\t\t\t};\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-approval-response\": {\n\t\t\t\t\tconst toolInvocation = getToolInvocationByApprovalId(chunk.approvalId);\n\t\t\t\t\tconst approval = toolInvocation.approval == null ? { id: chunk.approvalId } : toolInvocation.approval;\n\t\t\t\t\ttoolInvocation.state = \"approval-responded\";\n\t\t\t\t\ttoolInvocation.approval = {\n\t\t\t\t\t\t...approval,\n\t\t\t\t\t\tid: chunk.approvalId,\n\t\t\t\t\t\tapproved: chunk.approved,\n\t\t\t\t\t\t...chunk.reason != null ? { reason: chunk.reason } : {}\n\t\t\t\t\t};\n\t\t\t\t\tif (chunk.providerExecuted != null) toolInvocation.providerExecuted = chunk.providerExecuted;\n\t\t\t\t\tif (chunk.providerMetadata != null) toolInvocation.callProviderMetadata = chunk.providerMetadata;\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-output-denied\": {\n\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\ttoolInvocation.state = \"output-denied\";\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-output-available\": {\n\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\tif (toolInvocation.type === \"dynamic-tool\") updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: toolInvocation.toolName,\n\t\t\t\t\t\tstate: \"output-available\",\n\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\toutput: chunk.output,\n\t\t\t\t\t\tpreliminary: chunk.preliminary,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: toolInvocation.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata ?? toolInvocation.toolMetadata\n\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: getStaticToolName(toolInvocation),\n\t\t\t\t\t\tstate: \"output-available\",\n\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\toutput: chunk.output,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tpreliminary: chunk.preliminary,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: toolInvocation.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata ?? toolInvocation.toolMetadata\n\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-output-error\": {\n\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\tif (toolInvocation.type === \"dynamic-tool\") updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: toolInvocation.toolName,\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: toolInvocation.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata ?? toolInvocation.toolMetadata\n\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: getStaticToolName(toolInvocation),\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\trawInput: toolInvocation.rawInput,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: toolInvocation.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata ?? toolInvocation.toolMetadata\n\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"start-step\":\n\t\t\t\t\tstate.message.parts.push({ type: \"step-start\" });\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish-step\": break;\n\t\t\t\tcase \"reset-step\": {\n\t\t\t\t\tconst currentStepParts = getCurrentStepParts();\n\t\t\t\t\tstate.activeTextParts = createIdMap();\n\t\t\t\t\tstate.activeReasoningParts = createIdMap();\n\t\t\t\t\tstate.partialToolCalls = createIdMap();\n\t\t\t\t\tif (currentStepParts.length > 0) {\n\t\t\t\t\t\tstate.message.parts.splice(state.message.parts.length - currentStepParts.length, currentStepParts.length);\n\t\t\t\t\t\twrite();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"start\":\n\t\t\t\t\tif (chunk.messageId != null && (resetStateOnFirstMessageStart || resetStateOnMessageIdChange && chunk.messageId !== state.message.id)) Object.assign(state, createStreamingUIMessageState({\n\t\t\t\t\t\tlastMessage: void 0,\n\t\t\t\t\t\tmessageId: chunk.messageId\n\t\t\t\t\t}), { finishReason: void 0 });\n\t\t\t\t\tif (chunk.messageId != null) state.message.id = chunk.messageId;\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageId != null || chunk.messageMetadata != null) write({ updateStatus: false });\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tif (chunk.finishReason != null) state.finishReason = chunk.finishReason;\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"message-metadata\":\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":\n\t\t\t\t\tonError?.(new Error(chunk.errorText));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: if (isDataUIMessageChunk(chunk)) {\n\t\t\t\t\tif (dataPartSchemas?.[chunk.type] != null) {\n\t\t\t\t\t\tconst partIdx = state.message.parts.findIndex((p) => \"id\" in p && \"data\" in p && p.id === chunk.id && p.type === chunk.type);\n\t\t\t\t\t\tconst actualPartIdx = partIdx >= 0 ? partIdx : state.message.parts.length;\n\t\t\t\t\t\tawait validateTypes({\n\t\t\t\t\t\t\tvalue: chunk.data,\n\t\t\t\t\t\t\tschema: dataPartSchemas[chunk.type],\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\tfield: `message.parts[${actualPartIdx}].data`,\n\t\t\t\t\t\t\t\tentityName: chunk.type,\n\t\t\t\t\t\t\t\tentityId: chunk.id\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst dataChunk = chunk;\n\t\t\t\t\tif (dataChunk.transient) {\n\t\t\t\t\t\tonData?.(dataChunk);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst existingUIPart = dataChunk.id != null ? state.message.parts.find((chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id) : void 0;\n\t\t\t\t\tif (existingUIPart != null) existingUIPart.data = dataChunk.data;\n\t\t\t\t\telse state.message.parts.push(dataChunk);\n\t\t\t\t\tonData?.(dataChunk);\n\t\t\t\t\twrite();\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontroller.enqueue(chunk);\n\t\t});\n\t} }));\n}\n//#endregion\n//#region src/ui-message-stream/handle-ui-message-stream-finish.ts\nfunction handleUIMessageStreamFinish({ messageId, originalMessages = [], onStepEnd, onStepFinish, onEnd, onFinish, onError, stream, getOutcome }) {\n\tlet lastMessage = originalMessages?.[originalMessages.length - 1];\n\tif (lastMessage?.role !== \"assistant\") lastMessage = void 0;\n\telse messageId = lastMessage.id;\n\tlet isAborted = false;\n\tlet hasProcessingFailure = false;\n\tlet processingError;\n\tconst recordProcessingFailure = (error) => {\n\t\thasProcessingFailure = true;\n\t\tprocessingError = error;\n\t};\n\tconst idInjectedStream = stream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\ttry {\n\t\t\tlet outputChunk = chunk;\n\t\t\tif (chunk.type === \"start\") {\n\t\t\t\tconst startChunk = chunk;\n\t\t\t\tif (startChunk.messageId == null && messageId != null) outputChunk = {\n\t\t\t\t\t...startChunk,\n\t\t\t\t\tmessageId\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (chunk.type === \"abort\") isAborted = true;\n\t\t\tcontroller.enqueue(outputChunk);\n\t\t} catch (error) {\n\t\t\trecordProcessingFailure(error);\n\t\t\tthrow error;\n\t\t}\n\t} }));\n\tconst resolvedOnStepEnd = onStepEnd ?? onStepFinish;\n\tconst resolvedOnEnd = onEnd ?? onFinish;\n\tif (resolvedOnEnd == null && resolvedOnStepEnd == null) return idInjectedStream;\n\tconst state = createStreamingUIMessageState({\n\t\tlastMessage: lastMessage ? structuredClone(lastMessage) : void 0,\n\t\tmessageId: messageId ?? \"\"\n\t});\n\tconst runUpdateMessageJob = async (job) => {\n\t\ttry {\n\t\t\tawait job({\n\t\t\t\tstate,\n\t\t\t\twrite: () => {}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\trecordProcessingFailure(error);\n\t\t\tthrow error;\n\t\t}\n\t};\n\tlet finishCalled = false;\n\tconst callOnEnd = async ({ isCancelled }) => {\n\t\tif (finishCalled || !resolvedOnEnd) return;\n\t\tfinishCalled = true;\n\t\tconst isContinuation = state.message.id === lastMessage?.id;\n\t\tconst declaredOutcome = getOutcome?.() ?? { status: \"unknown\" };\n\t\tconst outcome = hasProcessingFailure ? {\n\t\t\tstatus: \"failed\",\n\t\t\terror: processingError\n\t\t} : declaredOutcome.status === \"unknown\" && isAborted ? { status: \"aborted\" } : declaredOutcome;\n\t\tconst isConsumerCancellation = isCancelled && outcome.status === \"unknown\";\n\t\tawait resolvedOnEnd({\n\t\t\tisAborted: isAborted || outcome.status === \"aborted\",\n\t\t\t...isConsumerCancellation ? { isCancelled: true } : {},\n\t\t\tisContinuation,\n\t\t\toutcome,\n\t\t\tresponseMessage: state.message,\n\t\t\tmessages: [...isContinuation ? originalMessages.slice(0, -1) : originalMessages, state.message],\n\t\t\tfinishReason: state.finishReason\n\t\t});\n\t};\n\tconst callOnStepFinish = async () => {\n\t\tif (!resolvedOnStepEnd) return;\n\t\tconst isContinuation = state.message.id === lastMessage?.id;\n\t\ttry {\n\t\t\tawait resolvedOnStepEnd({\n\t\t\t\tisContinuation,\n\t\t\t\tresponseMessage: structuredClone(state.message),\n\t\t\t\tmessages: [...isContinuation ? originalMessages.slice(0, -1) : originalMessages, structuredClone(state.message)]\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tonError(error);\n\t\t}\n\t};\n\treturn processUIMessageStream({\n\t\tstream: idInjectedStream,\n\t\trunUpdateMessageJob,\n\t\tonError\n\t}).pipeThrough(new TransformStream({\n\t\tasync transform(chunk, controller) {\n\t\t\tif (chunk.type === \"finish-step\") await callOnStepFinish();\n\t\t\tcontroller.enqueue(chunk);\n\t\t},\n\t\tasync cancel() {\n\t\t\tawait callOnEnd({ isCancelled: true });\n\t\t},\n\t\tasync flush() {\n\t\t\tawait callOnEnd({ isCancelled: false });\n\t\t}\n\t}));\n}\n//#endregion\n//#region src/ui-message-stream/to-ui-message-chunk.ts\n/**\n* Converts a single `TextStreamPart` (as emitted by `streamText`'s\n* `stream`) into a `UIMessageChunk`.\n*\n* Returns `undefined` for stream parts that do not produce UI message chunks.\n*/\nfunction toUIMessageChunk(part, { tools, sendReasoning = true, sendSources = false, sendStart = true, sendFinish = true, onError = () => \"An error occurred.\", messageMetadata, responseMessageId } = {}) {\n\tconst isDynamic = (toolPart) => {\n\t\tconst tool = tools?.[toolPart.toolName];\n\t\tif (tool == null) return toolPart.dynamic;\n\t\treturn tool?.type === \"dynamic\" ? true : void 0;\n\t};\n\tconst partType = part.type;\n\tswitch (partType) {\n\t\tcase \"text-start\": return {\n\t\t\ttype: \"text-start\",\n\t\t\tid: part.id,\n\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t};\n\t\tcase \"text-delta\": return {\n\t\t\ttype: \"text-delta\",\n\t\t\tid: part.id,\n\t\t\tdelta: part.text,\n\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t};\n\t\tcase \"text-end\": return {\n\t\t\ttype: \"text-end\",\n\t\t\tid: part.id,\n\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t};\n\t\tcase \"reasoning-start\":\n\t\tcase \"reasoning-end\":\n\t\t\tif (!sendReasoning) return;\n\t\t\treturn {\n\t\t\t\ttype: partType,\n\t\t\t\tid: part.id,\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t};\n\t\tcase \"reasoning-delta\":\n\t\t\tif (!sendReasoning) return;\n\t\t\treturn {\n\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\tid: part.id,\n\t\t\t\tdelta: part.text,\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t};\n\t\tcase \"file\":\n\t\tcase \"reasoning-file\":\n\t\t\tif (partType === \"reasoning-file\" && !sendReasoning) return;\n\t\t\treturn {\n\t\t\t\ttype: part.type,\n\t\t\t\tmediaType: part.file.mediaType,\n\t\t\t\turl: `data:${part.file.mediaType};base64,${part.file.base64}`,\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t};\n\t\tcase \"source\":\n\t\t\tif (!sendSources) return;\n\t\t\tif (part.sourceType === \"url\") return {\n\t\t\t\ttype: \"source-url\",\n\t\t\t\tsourceId: part.id,\n\t\t\t\turl: part.url,\n\t\t\t\ttitle: part.title,\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t};\n\t\t\tif (part.sourceType === \"document\") return {\n\t\t\t\ttype: \"source-document\",\n\t\t\t\tsourceId: part.id,\n\t\t\t\tmediaType: part.mediaType,\n\t\t\t\ttitle: part.title,\n\t\t\t\tfilename: part.filename,\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t};\n\t\t\treturn;\n\t\tcase \"custom\": return {\n\t\t\ttype: \"custom\",\n\t\t\tkind: part.kind,\n\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t};\n\t\tcase \"tool-input-start\": {\n\t\t\tconst dynamic = isDynamic(part);\n\t\t\treturn {\n\t\t\t\ttype: \"tool-input-start\",\n\t\t\t\ttoolCallId: part.id,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n\t\t\t\t...dynamic != null ? { dynamic } : {},\n\t\t\t\t...part.title != null ? { title: part.title } : {}\n\t\t\t};\n\t\t}\n\t\tcase \"tool-input-delta\": return {\n\t\t\ttype: \"tool-input-delta\",\n\t\t\ttoolCallId: part.id,\n\t\t\tinputTextDelta: part.delta\n\t\t};\n\t\tcase \"tool-call\": {\n\t\t\tconst dynamic = isDynamic(part);\n\t\t\tif (part.invalid) return {\n\t\t\t\ttype: \"tool-input-error\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\tinput: part.input,\n\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n\t\t\t\t...dynamic != null ? { dynamic } : {},\n\t\t\t\terrorText: onError(part.error),\n\t\t\t\t...part.title != null ? { title: part.title } : {}\n\t\t\t};\n\t\t\treturn {\n\t\t\t\ttype: \"tool-input-available\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\tinput: part.input,\n\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n\t\t\t\t...dynamic != null ? { dynamic } : {},\n\t\t\t\t...part.title != null ? { title: part.title } : {}\n\t\t\t};\n\t\t}\n\t\tcase \"tool-approval-request\": {\n\t\t\tconst inputSchemaInput = getToolCallInputSchemaInput(part.toolCall);\n\t\t\treturn {\n\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\tapprovalId: part.approvalId,\n\t\t\t\ttoolCallId: part.toolCall.toolCallId,\n\t\t\t\t...inputSchemaInput != null && !isDeepEqualData(inputSchemaInput.value, part.toolCall.input) ? { inputSchemaInput: inputSchemaInput.value } : {},\n\t\t\t\t...part.reason != null ? { reason: part.reason } : {},\n\t\t\t\t...part.isAutomatic != null ? { isAutomatic: part.isAutomatic } : {},\n\t\t\t\t...part.signature != null ? { signature: part.signature } : {}\n\t\t\t};\n\t\t}\n\t\tcase \"tool-approval-response\": return {\n\t\t\ttype: \"tool-approval-response\",\n\t\t\tapprovalId: part.approvalId,\n\t\t\tapproved: part.approved,\n\t\t\t...part.reason != null ? { reason: part.reason } : {},\n\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {}\n\t\t};\n\t\tcase \"tool-result\": {\n\t\t\tconst dynamic = isDynamic(part);\n\t\t\treturn {\n\t\t\t\ttype: \"tool-output-available\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\toutput: part.output === void 0 ? null : part.output,\n\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n\t\t\t\t...part.preliminary != null ? { preliminary: part.preliminary } : {},\n\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t};\n\t\t}\n\t\tcase \"tool-error\": {\n\t\t\tconst dynamic = isDynamic(part);\n\t\t\treturn {\n\t\t\t\ttype: \"tool-output-error\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\terrorText: part.providerExecuted ? typeof part.error === \"string\" ? part.error : JSON.stringify(part.error) : onError(part.error),\n\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t};\n\t\t}\n\t\tcase \"tool-output-denied\": return {\n\t\t\ttype: \"tool-output-denied\",\n\t\t\ttoolCallId: part.toolCallId\n\t\t};\n\t\tcase \"error\": return {\n\t\t\ttype: \"error\",\n\t\t\terrorText: onError(part.error)\n\t\t};\n\t\tcase \"start-step\": return { type: \"start-step\" };\n\t\tcase \"finish-step\": return { type: \"finish-step\" };\n\t\tcase \"start\":\n\t\t\tif (!sendStart) return;\n\t\t\treturn {\n\t\t\t\ttype: \"start\",\n\t\t\t\t...messageMetadata != null ? { messageMetadata } : {},\n\t\t\t\t...responseMessageId != null ? { messageId: responseMessageId } : {}\n\t\t\t};\n\t\tcase \"finish\":\n\t\t\tif (!sendFinish) return;\n\t\t\treturn {\n\t\t\t\ttype: \"finish\",\n\t\t\t\tfinishReason: part.finishReason,\n\t\t\t\t...messageMetadata != null ? { messageMetadata } : {}\n\t\t\t};\n\t\tcase \"abort\": return part;\n\t\tcase \"tool-input-end\":\n\t\tcase \"raw\": return;\n\t\tdefault: throw new Error(`Unknown chunk type: ${partType}`);\n\t}\n}\n//#endregion\n//#region src/ui-message-stream/to-ui-message-stream.ts\n/**\n* Converts a stream of `TextStreamPart<TOOLS>` chunks (as emitted by\n* `streamText`'s `stream`) into a stream of `UIMessageChunk`s suitable for\n* UI message streaming, including response message ID injection and\n* step and stream end callbacks.\n*/\nfunction toUIMessageStream({ stream, tools, sendReasoning = true, sendSources = false, sendStart = true, sendFinish = true, onError = () => \"An error occurred.\", messageMetadata, originalMessages, generateMessageId, onStepEnd, onStepFinish, onEnd, onFinish }) {\n\tlet outcome = { status: \"unknown\" };\n\tlet hasFatalFailure = false;\n\tconst setSourceOutcome = (newOutcome) => {\n\t\tif (!hasFatalFailure && outcome.status !== \"completed\" && outcome.status !== \"aborted\" && newOutcome.status !== \"unknown\" && (outcome.status === \"unknown\" || newOutcome.status !== \"failed\")) outcome = newOutcome;\n\t};\n\tconst failOutcome = (error) => {\n\t\thasFatalFailure = true;\n\t\toutcome = {\n\t\t\tstatus: \"failed\",\n\t\t\terror\n\t\t};\n\t};\n\tconst responseMessageId = generateMessageId != null ? getResponseUIMessageId({\n\t\toriginalMessages,\n\t\tresponseMessageId: generateMessageId\n\t}) : void 0;\n\tconst sourceReader = stream.getReader();\n\tlet sourceReaderReleased = false;\n\tlet sourceStreamCancelled = false;\n\tconst releaseSourceReader = () => {\n\t\tif (!sourceReaderReleased) {\n\t\t\tsourceReader.releaseLock();\n\t\t\tsourceReaderReleased = true;\n\t\t}\n\t};\n\treturn handleUIMessageStreamFinish({\n\t\tstream: new ReadableStream({\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst { done, value } = await sourceReader.read();\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\treleaseSourceReader();\n\t\t\t\t\t\tif (!sourceStreamCancelled) controller.close();\n\t\t\t\t\t} else controller.enqueue(value);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treleaseSourceReader();\n\t\t\t\t\tif (!sourceStreamCancelled) {\n\t\t\t\t\t\tfailOutcome(error);\n\t\t\t\t\t\tcontroller.error(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync cancel(reason) {\n\t\t\t\tsourceStreamCancelled = true;\n\t\t\t\tif (sourceReaderReleased) return;\n\t\t\t\ttry {\n\t\t\t\t\tawait sourceReader.cancel(reason);\n\t\t\t\t} finally {\n\t\t\t\t\treleaseSourceReader();\n\t\t\t\t}\n\t\t\t}\n\t\t}).pipeThrough(new TransformStream({ transform: async (part, controller) => {\n\t\t\ttry {\n\t\t\t\tconst messageMetadataValue = messageMetadata?.({ part });\n\t\t\t\tconst uiMessageChunk = toUIMessageChunk(part, {\n\t\t\t\t\ttools,\n\t\t\t\t\tsendReasoning,\n\t\t\t\t\tsendSources,\n\t\t\t\t\tsendStart,\n\t\t\t\t\tsendFinish,\n\t\t\t\t\tonError,\n\t\t\t\t\tmessageMetadata: messageMetadataValue,\n\t\t\t\t\tresponseMessageId\n\t\t\t\t});\n\t\t\t\tif (uiMessageChunk != null && part.type !== \"finish-step\") controller.enqueue(uiMessageChunk);\n\t\t\t\tif (messageMetadataValue != null && part.type !== \"start\" && part.type !== \"finish\") controller.enqueue({\n\t\t\t\t\ttype: \"message-metadata\",\n\t\t\t\t\tmessageMetadata: messageMetadataValue\n\t\t\t\t});\n\t\t\t\tif (uiMessageChunk != null && part.type === \"finish-step\") controller.enqueue(uiMessageChunk);\n\t\t\t\tif (part.type === \"finish\") setSourceOutcome({ status: \"completed\" });\n\t\t\t\telse if (part.type === \"abort\") setSourceOutcome({ status: \"aborted\" });\n\t\t\t\telse if (part.type === \"error\") setSourceOutcome({\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\terror: part.error\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tfailOutcome(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} })),\n\t\tmessageId: responseMessageId ?? generateMessageId?.(),\n\t\toriginalMessages,\n\t\tonStepEnd: onStepEnd ?? onStepFinish,\n\t\tonEnd: onEnd ?? onFinish,\n\t\tonError,\n\t\tgetOutcome: () => outcome\n\t});\n}\n//#endregion\n//#region src/util/async-iterable-stream.ts\n/**\n* Wraps a ReadableStream and returns an object that is both a ReadableStream and an AsyncIterable.\n* This enables consumption of the stream using for-await-of, with proper resource cleanup on early exit or error.\n*\n* @template T The type of the stream's chunks.\n* @param source The source ReadableStream to wrap.\n* @returns An AsyncIterableStream that can be used as both a ReadableStream and an AsyncIterable.\n*/\nfunction createAsyncIterableStream(source) {\n\treturn asAsyncIterableStream(source.pipeThrough(new TransformStream()));\n}\n/**\n* Attaches the async iterator protocol to an existing ReadableStream in place,\n* turning it into an AsyncIterableStream without piping through an additional\n* TransformStream.\n*\n* Use this when the stream is already known to be fresh and exclusively owned\n* (e.g. the readable side of a TransformStream created for this consumer).\n* Adding an extra `pipeThrough` in that situation creates a chain of two\n* transforms fed by an active upstream pipe, which can surface a spurious\n* unhandled `undefined` rejection when the consumer cancels early (observed on\n* Node.js 26). {@link createAsyncIterableStream} wraps this after adding a\n* fresh transform for callers that may pass shared or locked streams.\n*\n* @template T The type of the stream's chunks.\n* @param stream The ReadableStream to augment. It must be fresh and unlocked.\n* @returns The same stream, augmented with the async iterator protocol.\n*/\nfunction asAsyncIterableStream(stream) {\n\t/**\n\t* Implements the async iterator protocol for the stream.\n\t* Ensures proper cleanup (cancelling and releasing the reader) on completion, early exit, or error.\n\t*/\n\tstream[Symbol.asyncIterator] = function() {\n\t\tconst reader = this.getReader();\n\t\tlet finished = false;\n\t\t/**\n\t\t* Cleans up the reader by cancelling and releasing the lock.\n\t\t*/\n\t\tasync function cleanup(cancelStream) {\n\t\t\tif (finished) return;\n\t\t\tfinished = true;\n\t\t\ttry {\n\t\t\t\tif (cancelStream) await reader.cancel?.();\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\treader.releaseLock();\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t/**\n\t\t\t* Reads the next chunk from the stream.\n\t\t\t* @returns A promise resolving to the next IteratorResult.\n\t\t\t*/\n\t\t\tasync next() {\n\t\t\t\tif (finished) return {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t};\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await reader.read();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait cleanup(false);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tconst { done, value } = result;\n\t\t\t\tif (done) {\n\t\t\t\t\tawait cleanup(true);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\tvalue: void 0\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdone: false,\n\t\t\t\t\tvalue\n\t\t\t\t};\n\t\t\t},\n\t\t\t/**\n\t\t\t* May be called on early exit (e.g., break from for-await) or after completion.\n\t\t\t* Ensures the stream is cancelled and resources are released.\n\t\t\t* @returns A promise resolving to a completed IteratorResult.\n\t\t\t*/\n\t\t\tasync return() {\n\t\t\t\tawait cleanup(true);\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t};\n\t\t\t},\n\t\t\t/**\n\t\t\t* Called on early exit with error.\n\t\t\t* Ensures the stream is cancelled and resources are released, then rethrows the error.\n\t\t\t* @param err The error to throw.\n\t\t\t* @returns A promise that rejects with the provided error.\n\t\t\t*/\n\t\t\tasync throw(err) {\n\t\t\t\tawait cleanup(true);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t};\n\t};\n\treturn stream;\n}\n//#endregion\n//#region src/util/consume-stream.ts\n/**\n* Consumes a ReadableStream until it's fully read.\n*\n* This function reads the stream chunk by chunk until the stream is exhausted.\n* It doesn't process or return the data from the stream; it simply ensures\n* that the entire stream is read.\n*\n* @param options - The options for consuming the stream.\n* @param options.stream - The ReadableStream to be consumed.\n* @param options.onError - Optional callback to handle errors that occur during consumption.\n* @returns A promise that resolves when the stream is fully consumed.\n*/\nasync function consumeStream({ stream, onError, abortSignal }) {\n\tconst reader = stream.getReader();\n\tconst cancelOnAbort = () => {\n\t\treader.cancel().catch(() => {});\n\t};\n\tif (abortSignal?.aborted) cancelOnAbort();\n\telse abortSignal?.addEventListener(\"abort\", cancelOnAbort, { once: true });\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done } = await reader.read();\n\t\t\tif (done) break;\n\t\t}\n\t} catch (error) {\n\t\tonError?.(error);\n\t} finally {\n\t\tabortSignal?.removeEventListener(\"abort\", cancelOnAbort);\n\t\treader.releaseLock();\n\t}\n}\n//#endregion\n//#region src/util/create-resolvable-promise.ts\n/**\n* Creates a Promise with externally accessible resolve and reject functions.\n*\n* @template T - The type of the value that the Promise will resolve to.\n* @returns An object containing:\n* - promise: A Promise that can be resolved or rejected externally.\n* - resolve: A function to resolve the Promise with a value of type T.\n* - reject: A function to reject the Promise with an error.\n*/\nfunction createResolvablePromise() {\n\tlet resolve;\n\tlet reject;\n\treturn {\n\t\tpromise: new Promise((res, rej) => {\n\t\t\tresolve = res;\n\t\t\treject = rej;\n\t\t}),\n\t\tresolve,\n\t\treject\n\t};\n}\n//#endregion\n//#region src/util/create-stitchable-stream.ts\n/**\n* Creates a stitchable stream that can pipe one stream at a time.\n*\n* @template T - The type of values emitted by the streams.\n* @returns {Object} An object containing the stitchable stream and control methods.\n*/\nfunction createStitchableStream() {\n\tlet innerStreams = [];\n\tlet controller = null;\n\tlet isClosed = false;\n\tlet isCancelled = false;\n\tlet waitForNewStream = createResolvablePromise();\n\tconst terminate = () => {\n\t\tif (isCancelled) return;\n\t\tisClosed = true;\n\t\twaitForNewStream.resolve();\n\t\tinnerStreams.forEach(({ reader, onCancel }) => {\n\t\t\tonCancel?.();\n\t\t\treader.cancel();\n\t\t});\n\t\tinnerStreams = [];\n\t\tcontroller?.close();\n\t};\n\tconst processPull = async () => {\n\t\tif (isCancelled) return;\n\t\tif (isClosed && innerStreams.length === 0) {\n\t\t\tcontroller?.close();\n\t\t\treturn;\n\t\t}\n\t\tif (innerStreams.length === 0) {\n\t\t\twaitForNewStream = createResolvablePromise();\n\t\t\tawait waitForNewStream.promise;\n\t\t\treturn await processPull();\n\t\t}\n\t\tconst currentStream = innerStreams[0];\n\t\ttry {\n\t\t\tconst { value, done } = await currentStream.reader.read();\n\t\t\tif (isCancelled) return;\n\t\t\tif (done) {\n\t\t\t\tinnerStreams.shift();\n\t\t\t\tif (innerStreams.length === 0 && isClosed) controller?.close();\n\t\t\t\telse await processPull();\n\t\t\t} else controller?.enqueue(value);\n\t\t} catch (error) {\n\t\t\tif (isCancelled) return;\n\t\t\tcurrentStream.onError?.(error);\n\t\t\tcontroller?.error(error);\n\t\t\tinnerStreams.shift();\n\t\t\tterminate();\n\t\t}\n\t};\n\treturn {\n\t\tstream: new ReadableStream({\n\t\t\tstart(controllerParam) {\n\t\t\t\tcontroller = controllerParam;\n\t\t\t},\n\t\t\tpull: processPull,\n\t\t\tasync cancel() {\n\t\t\t\tisCancelled = true;\n\t\t\t\tisClosed = true;\n\t\t\t\twaitForNewStream.resolve();\n\t\t\t\tfor (const { reader, onCancel } of innerStreams) {\n\t\t\t\t\tonCancel?.();\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t}\n\t\t\t\tinnerStreams = [];\n\t\t\t}\n\t\t}),\n\t\taddStream: (innerStream, callbacks) => {\n\t\t\tif (isCancelled) {\n\t\t\t\tcallbacks?.onCancel?.();\n\t\t\t\tinnerStream.cancel().catch(() => {});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isClosed) throw new Error(\"Cannot add inner stream: outer stream is closed\");\n\t\t\tinnerStreams.push({\n\t\t\t\treader: innerStream.getReader(),\n\t\t\t\t...callbacks\n\t\t\t});\n\t\t\twaitForNewStream.resolve();\n\t\t},\n\t\t/**\n\t\t* Gracefully close the outer stream. This will let the inner streams\n\t\t* finish processing and then close the outer stream.\n\t\t*/\n\t\tclose: () => {\n\t\t\tif (isCancelled) return;\n\t\t\tisClosed = true;\n\t\t\twaitForNewStream.resolve();\n\t\t\tif (innerStreams.length === 0) controller?.close();\n\t\t},\n\t\t/**\n\t\t* Immediately close the outer stream. This will cancel all inner streams\n\t\t* and close the outer stream.\n\t\t*/\n\t\tterminate\n\t};\n}\n//#endregion\n//#region src/generate-text/stream-retry-attempt-boundary.ts\nconst streamRetryAttemptBoundarySymbol = Symbol(\"streamRetryAttemptBoundary\");\nfunction createStreamRetryAttemptBoundaryPart({ warnings }) {\n\treturn {\n\t\t[streamRetryAttemptBoundarySymbol]: true,\n\t\twarnings\n\t};\n}\nfunction isStreamRetryAttemptBoundaryPart(part) {\n\treturn typeof part === \"object\" && part != null && streamRetryAttemptBoundarySymbol in part;\n}\n//#endregion\n//#region src/generate-text/execute-tools-from-stream.ts\nfunction executeToolsFromStream({ stream, tools, callId, messages, abortSignal, timeout, experimental_sandbox: sandbox, toolsContext, toolApproval, runtimeContext, toolApprovalSecret, generateId, onToolExecutionStart, onToolExecutionEnd, executeToolInTelemetryContext, runInTracingChannelSpan }) {\n\tconst toolCallsToExecute = [];\n\treturn stream.pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\tcontroller.enqueue(chunk);\n\t\tif (isStreamRetryAttemptBoundaryPart(chunk)) {\n\t\t\ttoolCallsToExecute.length = 0;\n\t\t\treturn;\n\t\t}\n\t\tswitch (chunk.type) {\n\t\t\tcase \"tool-call\": {\n\t\t\t\tif (chunk.invalid) return;\n\t\t\t\tconst tool = getOwn(tools, chunk.toolName);\n\t\t\t\tif (tool == null) return;\n\t\t\t\tconst toolApprovalStatus = await resolveToolApproval({\n\t\t\t\t\ttools,\n\t\t\t\t\ttoolCall: chunk,\n\t\t\t\t\ttoolApproval,\n\t\t\t\t\tmessages,\n\t\t\t\t\ttoolsContext,\n\t\t\t\t\truntimeContext\n\t\t\t\t});\n\t\t\t\tif (toolApprovalStatus.type === \"not-applicable\") {\n\t\t\t\t\tif (tool.execute != null && chunk.providerExecuted !== true) toolCallsToExecute.push(chunk);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst approvalId = generateId();\n\t\t\t\tconst signature = await maybeSignApproval({\n\t\t\t\t\tsecret: toolApprovalSecret,\n\t\t\t\t\tapprovalId,\n\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\tinput: chunk.input\n\t\t\t\t});\n\t\t\t\tswitch (toolApprovalStatus.type) {\n\t\t\t\t\tcase \"user-approval\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\ttoolCall: chunk,\n\t\t\t\t\t\t\t...toolApprovalStatus.reason != null ? { reason: toolApprovalStatus.reason } : {},\n\t\t\t\t\t\t\t...signature != null ? { signature } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\tcase \"denied\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\ttoolCall: chunk,\n\t\t\t\t\t\t\tisAutomatic: true,\n\t\t\t\t\t\t\t...signature != null ? { signature } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-approval-response\",\n\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\tapproved: false,\n\t\t\t\t\t\t\ttoolCall: chunk,\n\t\t\t\t\t\t\treason: toolApprovalStatus.reason,\n\t\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-output-denied\",\n\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\ttoolName: chunk.toolName\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\tcase \"approved\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\ttoolCall: chunk,\n\t\t\t\t\t\t\tisAutomatic: true,\n\t\t\t\t\t\t\t...signature != null ? { signature } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-approval-response\",\n\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\tapproved: true,\n\t\t\t\t\t\t\ttoolCall: chunk,\n\t\t\t\t\t\t\treason: toolApprovalStatus.reason,\n\t\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (tool.execute != null && chunk.providerExecuted !== true) toolCallsToExecute.push(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"model-call-end\":\n\t\t\t\tif (!isToolExecutionAllowedFinishReason(chunk.finishReason)) return;\n\t\t\t\tawait Promise.all(toolCallsToExecute.map(async (toolCall) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await executeToolCall({\n\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\texperimental_sandbox: sandbox,\n\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\tonToolExecutionStart,\n\t\t\t\t\t\t\tonToolExecutionEnd,\n\t\t\t\t\t\t\texecuteToolInTelemetryContext,\n\t\t\t\t\t\t\trunInTracingChannelSpan,\n\t\t\t\t\t\t\tonPreliminaryToolResult: (result) => {\n\t\t\t\t\t\t\t\tcontroller.enqueue(result);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (result != null) {\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"tool-execution-end\",\n\t\t\t\t\t\t\t\ttoolCallId: result.output.toolCallId,\n\t\t\t\t\t\t\t\ttoolExecutionMs: result.toolExecutionMs\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue(result.output);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\terror\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t}\n\t} }));\n}\n//#endregion\n//#region src/generate-text/invoke-tool-callbacks-from-stream.ts\nfunction invokeToolCallbacksFromStream({ stream, tools, stepInputMessages, abortSignal, toolsContext }) {\n\tif (tools == null) return stream;\n\tlet ongoingToolCalls = createIdMap();\n\tconst getValidatedContext = ({ toolCallId, toolName }) => {\n\t\tconst ongoingToolCall = ongoingToolCalls[toolCallId];\n\t\tconst validatedContext = ongoingToolCall?.validatedContexts[toolName];\n\t\tif (validatedContext != null) return validatedContext;\n\t\tconst tool = getOwn(tools, toolName);\n\t\tconst newValidatedContext = validateToolContext({\n\t\t\ttoolName,\n\t\t\tcontext: getOwn(toolsContext, toolName),\n\t\t\tcontextSchema: tool?.contextSchema\n\t\t});\n\t\tif (ongoingToolCall != null) ongoingToolCall.validatedContexts[toolName] = newValidatedContext;\n\t\treturn newValidatedContext;\n\t};\n\treturn stream.pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\tcontroller.enqueue(chunk);\n\t\tif (isStreamRetryAttemptBoundaryPart(chunk)) {\n\t\t\tongoingToolCalls = createIdMap();\n\t\t\treturn;\n\t\t}\n\t\tswitch (chunk.type) {\n\t\t\tcase \"tool-input-start\": {\n\t\t\t\tongoingToolCalls[chunk.id] = {\n\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\tvalidatedContexts: createIdMap()\n\t\t\t\t};\n\t\t\t\tconst tool = getOwn(tools, chunk.toolName);\n\t\t\t\tif (tool?.onInputStart != null) await tool.onInputStart({\n\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\tcontext: await getValidatedContext({\n\t\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\t\ttoolName: chunk.toolName\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool-input-delta\": {\n\t\t\t\tconst toolName = ongoingToolCalls[chunk.id]?.toolName;\n\t\t\t\tconst tool = getOwn(tools, toolName);\n\t\t\t\tif (tool?.onInputDelta != null) await tool.onInputDelta({\n\t\t\t\t\tinputTextDelta: chunk.delta,\n\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\tcontext: await getValidatedContext({\n\t\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\t\ttoolName\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool-call\": {\n\t\t\t\tconst toolName = chunk.toolName;\n\t\t\t\tconst tool = getOwn(tools, toolName);\n\t\t\t\tif (!chunk.invalid && tool?.onInputAvailable != null) {\n\t\t\t\t\tconst validatedContext = getValidatedContext({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName\n\t\t\t\t\t});\n\t\t\t\t\tdelete ongoingToolCalls[chunk.toolCallId];\n\t\t\t\t\tawait tool.onInputAvailable({\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\tcontext: await validatedContext\n\t\t\t\t\t});\n\t\t\t\t} else delete ongoingToolCalls[chunk.toolCallId];\n\t\t\t}\n\t\t}\n\t} }));\n}\n//#endregion\n//#region src/prompt/normalize-stream-provider-error.ts\n/**\n* Normalizes well-formed provider error payloads without changing existing\n* Error instances or malformed/unknown values.\n*/\nfunction normalizeStreamProviderError(error) {\n\tif (isError(error) || AISDKError$1.isInstance(error) || StreamProviderError.isInstance(error)) return error;\n\tconst outer = asRecord(error);\n\tif (outer == null) return error;\n\tconst providerStreamError = isProviderStreamError(error);\n\tconst details = providerStreamError ? outer : asRecord(asRecord(outer.response)?.error) ?? asRecord(outer.error) ?? outer;\n\tif (typeof details.message !== \"string\") return error;\n\tconst type = getString(details.type) ?? getString(outer.type);\n\tconst code = getStringOrNumber(details.code) ?? getStringOrNumber(outer.code);\n\tconst explicitStatusCode = getHttpStatusCode(details.statusCode) ?? getHttpStatusCode(outer.statusCode) ?? getHttpStatusCode(details.status_code) ?? getHttpStatusCode(outer.status_code) ?? getHttpStatusCode(details.status) ?? getHttpStatusCode(outer.status) ?? getHttpStatusCode(details.code) ?? getHttpStatusCode(outer.code);\n\tconst messageMetadata = inferExactMessageMetadata(details.message);\n\tconst statusCode = explicitStatusCode ?? messageMetadata?.statusCode;\n\tconst explicitRetryability = getBoolean(details.isRetryable) ?? getBoolean(outer.isRetryable) ?? getBoolean(details.is_retryable) ?? getBoolean(outer.is_retryable);\n\treturn new StreamProviderError({\n\t\tmessage: details.message,\n\t\ttype,\n\t\tcode,\n\t\tstatusCode,\n\t\tisRetryable: explicitRetryability ?? messageMetadata?.isRetryable ?? isRetryableStatusCode(statusCode),\n\t\tdata: providerStreamError ? error.data : error\n\t});\n}\nfunction inferExactMessageMetadata(message) {\n\tswitch (message.trim().toLowerCase()) {\n\t\tcase \"overloaded\":\n\t\tcase \"overloaded error\":\n\t\tcase \"model overloaded\": return {\n\t\t\tstatusCode: 503,\n\t\t\tisRetryable: true\n\t\t};\n\t\tcase \"internal server error\": return {\n\t\t\tstatusCode: 500,\n\t\t\tisRetryable: true\n\t\t};\n\t\tcase \"service unavailable\": return {\n\t\t\tstatusCode: 503,\n\t\t\tisRetryable: true\n\t\t};\n\t\tdefault: return;\n\t}\n}\nfunction isRetryableStatusCode(statusCode) {\n\treturn statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500);\n}\nfunction asRecord(value) {\n\treturn typeof value === \"object\" && value != null ? value : void 0;\n}\nfunction isError(value) {\n\treturn value instanceof Error || Object.prototype.toString.call(value) === \"[object Error]\";\n}\nfunction getString(value) {\n\treturn typeof value === \"string\" ? value : void 0;\n}\nfunction getStringOrNumber(value) {\n\treturn typeof value === \"string\" || typeof value === \"number\" ? value : void 0;\n}\nfunction getBoolean(value) {\n\treturn typeof value === \"boolean\" ? value : void 0;\n}\nfunction getHttpStatusCode(value) {\n\tconst statusCode = typeof value === \"string\" && /^\\d{3}$/.test(value) ? Number(value) : value;\n\treturn typeof statusCode === \"number\" && Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599 ? statusCode : void 0;\n}\n//#endregion\n//#region src/generate-text/stream-language-model-call.ts\nconst originalGenerateId$3 = createIdGenerator$1({\n\tprefix: \"aitxt\",\n\tsize: 24\n});\nconst originalGenerateCallId$8 = createIdGenerator$1({\n\tprefix: \"call\",\n\tsize: 24\n});\n/**\n* Streams a single language model call after standardizing the prompt and tools.\n*\n* The returned stream emits model call parts together with request and response\n* metadata when available.\n*\n* @param model - The language model to use.\n* @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n* @param output - Output configuration that controls the response format requested from the model.\n* @param toolChoice - The tool choice strategy for the model call.\n*\n* @param system - A system message that will be part of the prompt.\n* @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n* @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n* @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.\n*\n* @param maxOutputTokens - Maximum number of tokens to generate.\n* @param temperature - Temperature setting.\n* The value is passed through to the provider. The range depends on the provider and model.\n* It is recommended to set either `temperature` or `topP`, but not both.\n* @param topP - Nucleus sampling.\n* The value is passed through to the provider. The range depends on the provider and model.\n* It is recommended to set either `temperature` or `topP`, but not both.\n* @param topK - Only sample from the top K options for each subsequent token.\n* Used to remove \"long tail\" low probability responses.\n* Recommended for advanced use cases only. You usually only need to use temperature.\n* @param presencePenalty - Presence penalty setting.\n* It affects the likelihood of the model to repeat information that is already in the prompt.\n* The value is passed through to the provider. The range depends on the provider and model.\n* @param frequencyPenalty - Frequency penalty setting.\n* It affects the likelihood of the model to repeatedly use the same words or phrases.\n* The value is passed through to the provider. The range depends on the provider and model.\n* @param stopSequences - Stop sequences.\n* If set, the model will stop generating text when one of the stop sequences is generated.\n* @param seed - The seed (integer) to use for random sampling.\n* If set and supported by the model, calls will generate deterministic results.\n* @param reasoning - Reasoning configuration for the model call.\n*\n* @param download - A function that downloads URLs as part of prompt conversion.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request.\n* @param includeRawChunks - Whether to include raw provider stream chunks in the model stream.\n* @param providerOptions - Additional provider-specific options.\n* @param repairToolCall - A function that can repair invalid tool calls before they are emitted.\n* @param refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before they are emitted, used for telemetry, or executed.\n* @param onStart - A callback that receives the fully converted prompt before the model call starts.\n*\n* @returns A stream of model call parts together with request and response metadata when available.\n*/\nasync function streamLanguageModelCall({ model, tools, toolOrder, output, toolChoice, prompt, system, instructions, messages, allowSystemInMessages, download, abortSignal, headers, includeRawChunks, providerOptions, repairToolCall, refineToolInput, executeLanguageModelCallInTelemetryContext = async ({ execute }) => await execute(), callId, toolsContext, experimental_sandbox: sandbox, _internal: { generateId = originalGenerateId$3, generateCallId = originalGenerateCallId$8, now: now$3 = now } = {}, onStart, onLanguageModelCallStart, onLanguageModelCallEnd, ...callSettings }) {\n\tconst resolvedModel = resolveLanguageModel(model);\n\tconst effectiveCallId = callId ?? generateCallId();\n\tconst standardizedPrompt = await standardizePrompt({\n\t\tinstructions,\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages\n\t});\n\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\tprompt: {\n\t\t\tinstructions: standardizedPrompt.instructions,\n\t\t\tmessages: standardizedPrompt.messages\n\t\t},\n\t\tsupportedUrls: await resolvedModel.supportedUrls,\n\t\tdownload,\n\t\tabortSignal,\n\t\tprovider: resolvedModel.provider.split(\".\")[0]\n\t});\n\tconst stepTools = await prepareTools({\n\t\ttools,\n\t\ttoolOrder,\n\t\ttoolsContext,\n\t\texperimental_sandbox: sandbox\n\t});\n\tconst stepToolChoice = prepareToolChoice({ toolChoice });\n\tawait notify({\n\t\tevent: { promptMessages },\n\t\tcallbacks: onStart\n\t});\n\tconst languageModelCallStartEvent = {\n\t\tcallId: effectiveCallId,\n\t\tprovider: resolvedModel.provider,\n\t\tmodelId: resolvedModel.modelId,\n\t\tinstructions: standardizedPrompt.instructions,\n\t\tmessages: standardizedPrompt.messages,\n\t\ttools: stepTools,\n\t\t...callSettings\n\t};\n\tawait notify({\n\t\tevent: languageModelCallStartEvent,\n\t\tcallbacks: onLanguageModelCallStart\n\t});\n\tconst callStartTimestampMs = now$3();\n\tconst { stream: languageModelStream, response, request } = await executeLanguageModelCallInTelemetryContext({\n\t\t...languageModelCallStartEvent,\n\t\texecute: async () => await resolvedModel.doStream({\n\t\t\t...callSettings,\n\t\t\ttools: stepTools,\n\t\t\ttoolChoice: stepToolChoice,\n\t\t\tresponseFormat: await output?.responseFormat,\n\t\t\tprompt: promptMessages,\n\t\t\tproviderOptions,\n\t\t\tabortSignal,\n\t\t\theaders,\n\t\t\tincludeRawChunks\n\t\t})\n\t});\n\treturn {\n\t\tstream: createAsyncIterableStream(languageModelStream.pipeThrough(createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({\n\t\t\ttools,\n\t\t\tinstructions: standardizedPrompt.instructions,\n\t\t\tmessages: standardizedPrompt.messages,\n\t\t\trepairToolCall,\n\t\t\trefineToolInput,\n\t\t\tabortSignal,\n\t\t\tcallId: effectiveCallId,\n\t\t\tprovider: resolvedModel.provider,\n\t\t\tmodelId: resolvedModel.modelId,\n\t\t\ttoolChoice: stepToolChoice,\n\t\t\tgenerateId,\n\t\t\tnow: now$3,\n\t\t\tcallStartTimestampMs,\n\t\t\tonLanguageModelCallEnd\n\t\t}))),\n\t\tresponse,\n\t\trequest\n\t};\n}\nfunction createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ tools, instructions, messages, repairToolCall, refineToolInput, abortSignal, callId, provider, modelId, toolChoice, generateId, now, callStartTimestampMs, onLanguageModelCallEnd }) {\n\tconst toolCallsByToolCallId = /* @__PURE__ */ new Map();\n\tconst modelCallContent = [];\n\tconst rawModelCallContent = [];\n\tconst textPartIndexes = /* @__PURE__ */ new Map();\n\tconst reasoningPartIndexes = /* @__PURE__ */ new Map();\n\tconst rawTextPartIndexes = /* @__PURE__ */ new Map();\n\tconst rawReasoningPartIndexes = /* @__PURE__ */ new Map();\n\tlet responseId = generateId();\n\tlet responseModelId = modelId;\n\tlet timeToFirstOutputMs;\n\tlet previousOutputChunkTimestampMs;\n\tconst timeBetweenOutputChunksMs = [];\n\treturn new TransformStream({ async transform(chunk, controller) {\n\t\tif (isOutputChunk$1(chunk)) {\n\t\t\tconst outputChunkTimestampMs = now();\n\t\t\tif (timeToFirstOutputMs == null) timeToFirstOutputMs = outputChunkTimestampMs - callStartTimestampMs;\n\t\t\telse if (previousOutputChunkTimestampMs != null) timeBetweenOutputChunksMs.push(outputChunkTimestampMs - previousOutputChunkTimestampMs);\n\t\t\tpreviousOutputChunkTimestampMs = outputChunkTimestampMs;\n\t\t}\n\t\tswitch (chunk.type) {\n\t\t\tcase \"error\":\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror: normalizeStreamProviderError(chunk.error)\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"text-start\":\n\t\t\t\tupsertTextContentPart({\n\t\t\t\t\tcontent: modelCallContent,\n\t\t\t\t\trawContent: rawModelCallContent,\n\t\t\t\t\tpartIndexes: textPartIndexes,\n\t\t\t\t\trawPartIndexes: rawTextPartIndexes,\n\t\t\t\t\tid: chunk.id,\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t});\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\tbreak;\n\t\t\tcase \"text-delta\":\n\t\t\t\tupsertTextContentPart({\n\t\t\t\t\tcontent: modelCallContent,\n\t\t\t\t\trawContent: rawModelCallContent,\n\t\t\t\t\tpartIndexes: textPartIndexes,\n\t\t\t\t\trawPartIndexes: rawTextPartIndexes,\n\t\t\t\t\tid: chunk.id,\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttextDelta: chunk.delta,\n\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t});\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\tid: chunk.id,\n\t\t\t\t\ttext: chunk.delta,\n\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"text-end\":\n\t\t\t\tupsertTextContentPart({\n\t\t\t\t\tcontent: modelCallContent,\n\t\t\t\t\trawContent: rawModelCallContent,\n\t\t\t\t\tpartIndexes: textPartIndexes,\n\t\t\t\t\trawPartIndexes: rawTextPartIndexes,\n\t\t\t\t\tid: chunk.id,\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t});\n\t\t\t\ttextPartIndexes.delete(chunk.id);\n\t\t\t\trawTextPartIndexes.delete(chunk.id);\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\tbreak;\n\t\t\tcase \"reasoning-start\":\n\t\t\t\tupsertTextContentPart({\n\t\t\t\t\tcontent: modelCallContent,\n\t\t\t\t\trawContent: rawModelCallContent,\n\t\t\t\t\tpartIndexes: reasoningPartIndexes,\n\t\t\t\t\trawPartIndexes: rawReasoningPartIndexes,\n\t\t\t\t\tid: chunk.id,\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t});\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\tbreak;\n\t\t\tcase \"reasoning-delta\":\n\t\t\t\tupsertTextContentPart({\n\t\t\t\t\tcontent: modelCallContent,\n\t\t\t\t\trawContent: rawModelCallContent,\n\t\t\t\t\tpartIndexes: reasoningPartIndexes,\n\t\t\t\t\trawPartIndexes: rawReasoningPartIndexes,\n\t\t\t\t\tid: chunk.id,\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\ttextDelta: chunk.delta,\n\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t});\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\tid: chunk.id,\n\t\t\t\t\ttext: chunk.delta,\n\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"reasoning-end\":\n\t\t\t\tupsertTextContentPart({\n\t\t\t\t\tcontent: modelCallContent,\n\t\t\t\t\trawContent: rawModelCallContent,\n\t\t\t\t\tpartIndexes: reasoningPartIndexes,\n\t\t\t\t\trawPartIndexes: rawReasoningPartIndexes,\n\t\t\t\t\tid: chunk.id,\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t});\n\t\t\t\treasoningPartIndexes.delete(chunk.id);\n\t\t\t\trawReasoningPartIndexes.delete(chunk.id);\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\tbreak;\n\t\t\tcase \"file\":\n\t\t\tcase \"reasoning-file\": {\n\t\t\t\tconst file = new DefaultGeneratedFileWithType({\n\t\t\t\t\tdata: await resolveGeneratedFileData({\n\t\t\t\t\t\tdata: chunk.data,\n\t\t\t\t\t\tabortSignal\n\t\t\t\t\t}),\n\t\t\t\t\tmediaType: chunk.mediaType\n\t\t\t\t});\n\t\t\t\tmodelCallContent.push({\n\t\t\t\t\ttype: chunk.type,\n\t\t\t\t\tfile,\n\t\t\t\t\t...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t\trawModelCallContent.push(chunk);\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: chunk.type,\n\t\t\t\t\tfile,\n\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"finish\": {\n\t\t\t\tconst usage = asLanguageModelUsage(chunk.usage);\n\t\t\t\tconst responseTimeMs = now() - callStartTimestampMs;\n\t\t\t\tconst performance = {\n\t\t\t\t\tresponseTimeMs,\n\t\t\t\t\teffectiveOutputTokensPerSecond: calculateTokensPerSecond({\n\t\t\t\t\t\ttokens: usage.outputTokens,\n\t\t\t\t\t\tdurationMs: responseTimeMs\n\t\t\t\t\t}),\n\t\t\t\t\toutputTokensPerSecond: timeToFirstOutputMs == null ? void 0 : calculateTokensPerSecond({\n\t\t\t\t\t\ttokens: usage.outputTokens,\n\t\t\t\t\t\tdurationMs: responseTimeMs - timeToFirstOutputMs\n\t\t\t\t\t}),\n\t\t\t\t\tinputTokensPerSecond: timeToFirstOutputMs == null ? void 0 : calculateTokensPerSecond({\n\t\t\t\t\t\ttokens: usage.inputTokens,\n\t\t\t\t\t\tdurationMs: timeToFirstOutputMs\n\t\t\t\t\t}),\n\t\t\t\t\teffectiveTotalTokensPerSecond: calculateTokensPerSecond({\n\t\t\t\t\t\ttokens: sumTokenCounts(usage.inputTokens, usage.outputTokens),\n\t\t\t\t\t\tdurationMs: responseTimeMs\n\t\t\t\t\t}),\n\t\t\t\t\ttimeToFirstOutputMs,\n\t\t\t\t\ttimeBetweenOutputChunksMs: timeBetweenOutputChunksMs.length > 0 ? calculateOutputChunkTimingStats(timeBetweenOutputChunksMs) : void 0\n\t\t\t\t};\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\tcallId,\n\t\t\t\t\t\tprovider,\n\t\t\t\t\t\tmodelId: responseModelId,\n\t\t\t\t\t\tfinishReason: chunk.finishReason.unified,\n\t\t\t\t\t\tusage,\n\t\t\t\t\t\tcontent: modelCallContent,\n\t\t\t\t\t\tresponseId,\n\t\t\t\t\t\t...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {},\n\t\t\t\t\t\tperformance\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: onLanguageModelCallEnd\n\t\t\t\t});\n\t\t\t\tconst enforcedToolChoice = toolChoice.type === \"required\" || toolChoice.type === \"tool\" ? toolChoice : void 0;\n\t\t\t\tconst toolChoiceViolationError = enforcedToolChoice != null && ![...toolCallsByToolCallId.values()].some((toolCall) => enforcedToolChoice.type === \"required\" || toolCall.toolName === enforcedToolChoice.toolName) ? new ToolChoiceViolationError({\n\t\t\t\t\ttoolChoice: enforcedToolChoice,\n\t\t\t\t\tfinishReason: chunk.finishReason.unified,\n\t\t\t\t\tprovider,\n\t\t\t\t\tmodelId,\n\t\t\t\t\tcontent: rawModelCallContent\n\t\t\t\t}) : void 0;\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"model-call-end\",\n\t\t\t\t\tfinishReason: toolChoiceViolationError == null ? chunk.finishReason.unified : \"error\",\n\t\t\t\t\trawFinishReason: chunk.finishReason.raw,\n\t\t\t\t\tusage,\n\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\tperformance\n\t\t\t\t});\n\t\t\t\tif (toolChoiceViolationError != null) {\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\terror: toolChoiceViolationError\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool-call\":\n\t\t\t\trawModelCallContent.push(chunk);\n\t\t\t\ttry {\n\t\t\t\t\tconst toolCall = await parseToolCall({\n\t\t\t\t\t\ttoolCall: chunk,\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\trefineToolInput,\n\t\t\t\t\t\tinstructions,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tabortSignal\n\t\t\t\t\t});\n\t\t\t\t\ttoolCallsByToolCallId.set(toolCall.toolCallId, toolCall);\n\t\t\t\t\tcontroller.enqueue(toolCall);\n\t\t\t\t\tmodelCallContent.push(toolCall);\n\t\t\t\t\tif (toolCall.invalid) {\n\t\t\t\t\t\tif (!toolCall.providerExecuted) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\terror: getErrorMessage$1(toolCall.error),\n\t\t\t\t\t\t\tdynamic: true,\n\t\t\t\t\t\t\ttitle: toolCall.title,\n\t\t\t\t\t\t\t...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\terror\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"tool-approval-request\": {\n\t\t\t\trawModelCallContent.push(chunk);\n\t\t\t\tconst toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n\t\t\t\tif (toolCall == null) {\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\terror: new ToolCallNotFoundForApprovalError({\n\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\tapprovalId: chunk.approvalId\n\t\t\t\t\t\t})\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst toolApprovalRequest = {\n\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\tapprovalId: chunk.approvalId,\n\t\t\t\t\ttoolCall\n\t\t\t\t};\n\t\t\t\tcontroller.enqueue(toolApprovalRequest);\n\t\t\t\tmodelCallContent.push(toolApprovalRequest);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool-result\": {\n\t\t\t\trawModelCallContent.push(chunk);\n\t\t\t\tconst toolName = chunk.toolName;\n\t\t\t\tconst toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n\t\t\t\tconst toolResultPart = chunk.isError ? {\n\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\ttoolName,\n\t\t\t\t\tinput: toolCall?.input,\n\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\terror: chunk.result,\n\t\t\t\t\tdynamic: chunk.dynamic,\n\t\t\t\t\t...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {},\n\t\t\t\t\t...toolCall?.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t\t} : {\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\ttoolName,\n\t\t\t\t\tinput: toolCall?.input,\n\t\t\t\t\toutput: chunk.result,\n\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\tdynamic: chunk.dynamic,\n\t\t\t\t\t...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {},\n\t\t\t\t\t...toolCall?.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t\t};\n\t\t\t\tcontroller.enqueue(toolResultPart);\n\t\t\t\tmodelCallContent.push(toolResultPart);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool-input-start\": {\n\t\t\t\tconst tool = getOwn(tools, chunk.toolName);\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t...chunk,\n\t\t\t\t\tdynamic: chunk.dynamic ?? tool?.type === \"dynamic\",\n\t\t\t\t\ttitle: tool?.title,\n\t\t\t\t\t...tool?.metadata != null ? { toolMetadata: tool.metadata } : {}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"stream-start\":\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"model-call-start\",\n\t\t\t\t\twarnings: chunk.warnings\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"response-metadata\":\n\t\t\t\tresponseId = chunk.id ?? responseId;\n\t\t\t\tresponseModelId = chunk.modelId ?? responseModelId;\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"model-call-response-metadata\",\n\t\t\t\t\tid: chunk.id,\n\t\t\t\t\ttimestamp: chunk.timestamp,\n\t\t\t\t\tmodelId: chunk.modelId\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (chunk.type === \"custom\" || chunk.type === \"source\") {\n\t\t\t\t\tmodelCallContent.push(chunk);\n\t\t\t\t\trawModelCallContent.push(chunk);\n\t\t\t\t}\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t}\n\t} });\n}\n/**\n* Returns true for chunks that contain generated model output.\n* Used to measure time-to-first-output for text, reasoning, generated files,\n* and tool calls.\n*/\nfunction isOutputChunk$1(chunk) {\n\treturn chunk.type === \"text-delta\" && chunk.delta.length > 0 || chunk.type === \"reasoning-delta\" && chunk.delta.length > 0 || chunk.type === \"tool-input-delta\" && chunk.delta.length > 0 || chunk.type === \"file\" || chunk.type === \"reasoning-file\" || chunk.type === \"tool-call\";\n}\nfunction calculateOutputChunkTimingStats(timingsMs) {\n\tconst sortedTimingsMs = [...timingsMs].sort((a, b) => a - b);\n\tconst sum = timingsMs.reduce((sum, timingMs) => sum + timingMs, 0);\n\treturn {\n\t\tmin: sortedTimingsMs[0],\n\t\tp10: calculateNearestRankPercentile(sortedTimingsMs, .1),\n\t\tmedian: calculateNearestRankPercentile(sortedTimingsMs, .5),\n\t\tavg: sum / timingsMs.length,\n\t\tp90: calculateNearestRankPercentile(sortedTimingsMs, .9),\n\t\tmax: sortedTimingsMs[sortedTimingsMs.length - 1]\n\t};\n}\nfunction calculateNearestRankPercentile(sortedValues, percentile) {\n\treturn sortedValues[Math.ceil(percentile * sortedValues.length) - 1];\n}\n/**\n* Appends a text or reasoning content part into the content array and updates the part indexes.\n*/\nfunction upsertTextContentPart({ content, rawContent, partIndexes, rawPartIndexes, id, type, textDelta, providerMetadata }) {\n\tlet partIndex = partIndexes.get(id);\n\tif (partIndex == null) {\n\t\tpartIndex = content.push({\n\t\t\ttype,\n\t\t\ttext: \"\",\n\t\t\t...providerMetadata != null ? { providerMetadata } : {}\n\t\t}) - 1;\n\t\tpartIndexes.set(id, partIndex);\n\t}\n\tlet rawPartIndex = rawPartIndexes.get(id);\n\tif (rawPartIndex == null) {\n\t\trawPartIndex = rawContent.push({\n\t\t\ttype,\n\t\t\ttext: \"\",\n\t\t\t...providerMetadata != null ? { providerMetadata } : {}\n\t\t}) - 1;\n\t\trawPartIndexes.set(id, rawPartIndex);\n\t}\n\tconst part = content[partIndex];\n\tconst rawPart = rawContent[rawPartIndex];\n\tif (textDelta != null) {\n\t\tpart.text += textDelta;\n\t\trawPart.text += textDelta;\n\t}\n\tif (providerMetadata != null) {\n\t\tpart.providerMetadata = providerMetadata;\n\t\trawPart.providerMetadata = providerMetadata;\n\t}\n}\n//#endregion\n//#region src/generate-text/stream-text.ts\nconst originalGenerateId$2 = createIdGenerator$1({\n\tprefix: \"aitxt\",\n\tsize: 24\n});\nconst originalGenerateCallId$7 = createIdGenerator$1({\n\tprefix: \"call\",\n\tsize: 24\n});\nconst isOutputChunkType = {\n\tfile: true,\n\tcustom: false,\n\tsource: false,\n\t\"text-start\": false,\n\t\"text-end\": false,\n\t\"text-delta\": true,\n\t\"reasoning-start\": false,\n\t\"reasoning-end\": false,\n\t\"reasoning-delta\": true,\n\t\"reasoning-file\": true,\n\t\"tool-input-start\": false,\n\t\"tool-input-end\": false,\n\t\"tool-input-delta\": true,\n\t\"tool-approval-request\": false,\n\t\"tool-approval-response\": false,\n\t\"tool-call\": true,\n\t\"tool-result\": false,\n\t\"tool-error\": false,\n\t\"tool-output-denied\": false,\n\t\"tool-execution-end\": false,\n\t\"model-call-start\": false,\n\t\"model-call-response-metadata\": false,\n\t\"model-call-end\": false,\n\terror: false,\n\traw: false\n};\nfunction isOutputChunk(chunk) {\n\tif (!isOutputChunkType[chunk.type]) return false;\n\tswitch (chunk.type) {\n\t\tcase \"text-delta\":\n\t\tcase \"reasoning-delta\": return chunk.text.length > 0;\n\t\tcase \"tool-input-delta\": return chunk.delta.length > 0;\n\t\tcase \"file\":\n\t\tcase \"reasoning-file\":\n\t\tcase \"tool-call\": return true;\n\t\tdefault: return false;\n\t}\n}\n/**\n* Generate a text and call tools for a given prompt using a language model.\n*\n* This function streams the output. If you do not want to stream the output, use `generateText` instead.\n*\n* @param model - The language model to use.\n* @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n* @param toolOrder - Controls the order in which tools are sent to the provider. Tools not listed are appended alphabetically.\n*\n* @param system - A system message that will be part of the prompt.\n* @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n* @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n* @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.\n*\n* @param maxOutputTokens - Maximum number of tokens to generate.\n* @param temperature - Temperature setting.\n* The value is passed through to the provider. The range depends on the provider and model.\n* It is recommended to set either `temperature` or `topP`, but not both.\n* @param topP - Nucleus sampling.\n* The value is passed through to the provider. The range depends on the provider and model.\n* It is recommended to set either `temperature` or `topP`, but not both.\n* @param topK - Only sample from the top K options for each subsequent token.\n* Used to remove \"long tail\" low probability responses.\n* Recommended for advanced use cases only. You usually only need to use temperature.\n* @param presencePenalty - Presence penalty setting.\n* It affects the likelihood of the model to repeat information that is already in the prompt.\n* The value is passed through to the provider. The range depends on the provider and model.\n* @param frequencyPenalty - Frequency penalty setting.\n* It affects the likelihood of the model to repeatedly use the same words or phrases.\n* The value is passed through to the provider. The range depends on the provider and model.\n* @param stopSequences - Stop sequences.\n* If set, the model will stop generating text when one of the stop sequences is generated.\n* @param seed - The seed (integer) to use for random sampling.\n* If set and supported by the model, calls will generate deterministic results.\n*\n* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n* @param streamRetries - Maximum number of retries for provider errors received after streaming starts. Set to 0 to disable automatic stream retries while allowing `onError` to request retries. Omit to disable all stream retry behavior. Default: 0.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n*\n* @param experimental_sandbox - The sandbox environment that is passed through to tool execution.\n* @param runtimeContext - User-defined runtime context that flows through the entire generation lifecycle.\n* @param experimental_refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before tools are executed and before outputs, callbacks, and telemetry are recorded.\n*\n* @param onChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.\n* @param onError - Callback that is called when an error occurs during streaming. You can use it to log errors.\n* @param onStart - Callback invoked when generation begins, before any LLM calls.\n* @param experimental_onStart - Deprecated alias for `onStart`.\n* @param onStepStart - Callback invoked when each step begins, before the provider is called.\n* @param experimental_onStepStart - Deprecated alias for `onStepStart`.\n* @param onLanguageModelCallStart - Callback invoked immediately before each provider model call begins.\n* @param experimental_onLanguageModelCallStart - Deprecated alias for `onLanguageModelCallStart`.\n* @param onLanguageModelCallEnd - Callback invoked after each provider model call response is normalized and parsed.\n* @param experimental_onLanguageModelCallEnd - Deprecated alias for `onLanguageModelCallEnd`.\n* @param onToolExecutionStart - Callback invoked before each tool execution begins.\n* @param experimental_onToolCallStart - Deprecated alias for `onToolExecutionStart`.\n* @param onToolExecutionEnd - Callback invoked after each tool execution completes.\n* @param experimental_onToolCallFinish - Deprecated alias for `onToolExecutionEnd`.\n* @param onStepEnd - Callback that is called when each step (LLM call) ends, including intermediate steps.\n* @param onStepFinish - Deprecated alias for `onStepEnd`.\n* @param onEnd - Callback that is called when all steps are finished and the response is complete.\n* @param onFinish - Deprecated alias for `onEnd`.\n*\n* @returns\n* A result object for accessing different stream types and additional information.\n*/\nfunction streamText({ model, tools, toolChoice, instructions, system, prompt, messages, allowSystemInMessages, maxRetries, streamRetries, abortSignal, timeout, headers, stopWhen = isStepCount(1), experimental_sandbox: sandbox, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, experimental_telemetry, telemetry = experimental_telemetry, prepareStep, providerOptions, activeTools, toolOrder, experimental_repairToolCall, repairToolCall = experimental_repairToolCall, experimental_refineToolInput: refineToolInput, experimental_transform: transform, experimental_download: download, includeRawChunks, onChunk, onError: onErrorArg, onFinish, onEnd = onFinish, onAbort, onStepEnd, onStepFinish, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onLanguageModelCallStart, experimental_onLanguageModelCallStart, onLanguageModelCallEnd, experimental_onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, experimental_onToolCallStart, experimental_onToolCallFinish, runtimeContext = {}, toolsContext = {}, experimental_include, include = experimental_include, _internal: { now: now$2 = now, generateId = originalGenerateId$2, generateCallId = originalGenerateCallId$7 } = {}, ...settings }) {\n\tconst totalTimeoutMs = getTotalTimeoutMs(timeout);\n\tconst stepTimeoutMs = getStepTimeoutMs(timeout);\n\tconst firstChunkTimeoutMs = getFirstChunkTimeoutMs(timeout);\n\tconst chunkTimeoutMs = getChunkTimeoutMs(timeout);\n\tconst stepAbortController = stepTimeoutMs != null ? new AbortController() : void 0;\n\tconst firstChunkAbortController = firstChunkTimeoutMs != null ? new AbortController() : void 0;\n\tconst chunkAbortController = chunkTimeoutMs != null ? new AbortController() : void 0;\n\tconst onError = onErrorArg ?? (({ error }) => {\n\t\tconsole.error(error);\n\t});\n\tconst resolvedOnStart = onStart ?? experimental_onStart;\n\tconst resolvedOnStepStart = onStepStart ?? experimental_onStepStart;\n\tconst resolvedOnLanguageModelCallStart = onLanguageModelCallStart ?? experimental_onLanguageModelCallStart;\n\tconst resolvedOnLanguageModelCallEnd = onLanguageModelCallEnd ?? experimental_onLanguageModelCallEnd;\n\tconst resolvedOnToolExecutionStart = onToolExecutionStart ?? experimental_onToolCallStart;\n\tconst resolvedOnToolExecutionEnd = onToolExecutionEnd ?? experimental_onToolCallFinish;\n\tconst resolvedOnStepEnd = onStepEnd ?? onStepFinish;\n\treturn new DefaultStreamTextResult({\n\t\tmodel: resolveLanguageModel(model),\n\t\ttelemetry,\n\t\theaders,\n\t\tsettings,\n\t\tmaxRetries,\n\t\tstreamRetries,\n\t\tabortSignal: mergeAbortSignals(abortSignal, totalTimeoutMs, stepAbortController?.signal, firstChunkAbortController?.signal, chunkAbortController?.signal),\n\t\tstepTimeoutMs,\n\t\tstepAbortController,\n\t\tfirstChunkTimeoutMs,\n\t\tfirstChunkAbortController,\n\t\tchunkTimeoutMs,\n\t\tchunkAbortController,\n\t\tinstructions,\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages,\n\t\texperimental_sandbox: sandbox,\n\t\ttools,\n\t\ttoolsContext,\n\t\truntimeContext,\n\t\ttoolChoice,\n\t\ttransforms: asArray(transform),\n\t\tactiveTools,\n\t\ttoolOrder,\n\t\trepairToolCall,\n\t\trefineToolInput,\n\t\tstopConditions: asArray(stopWhen),\n\t\toutput,\n\t\ttoolApproval,\n\t\texperimental_toolCallers,\n\t\texperimental_toolApprovalSecret,\n\t\tproviderOptions,\n\t\tprepareStep,\n\t\ttimeout,\n\t\tonChunk,\n\t\tonError,\n\t\tcanRetryStreamViaOnError: streamRetries !== void 0 && onErrorArg != null,\n\t\tonEnd,\n\t\tonAbort,\n\t\tonStepFinish: resolvedOnStepEnd,\n\t\tonStart: resolvedOnStart,\n\t\tonStepStart: resolvedOnStepStart,\n\t\tonLanguageModelCallStart: resolvedOnLanguageModelCallStart,\n\t\tonLanguageModelCallEnd: resolvedOnLanguageModelCallEnd,\n\t\tonToolExecutionStart: resolvedOnToolExecutionStart,\n\t\tonToolExecutionEnd: resolvedOnToolExecutionEnd,\n\t\tnow: now$2,\n\t\tgenerateId,\n\t\tgenerateCallId,\n\t\tdownload,\n\t\tinclude: {\n\t\t\trequestBody: include?.requestBody ?? false,\n\t\t\trequestMessages: include?.requestMessages ?? false,\n\t\t\trawChunks: include?.rawChunks ?? includeRawChunks ?? false\n\t\t}\n\t});\n}\nconst streamRetryBoundarySymbol = Symbol(\"streamRetryBoundary\");\nfunction isStreamRetryBoundaryPart(part) {\n\treturn streamRetryBoundarySymbol in part;\n}\nasync function markPromiseAsHandled$1(promise) {\n\ttry {\n\t\tawait promise;\n\t} catch {}\n}\nfunction createOutputTransformStream(output) {\n\tlet firstTextChunkId = void 0;\n\tlet text = \"\";\n\tlet textChunk = \"\";\n\tlet textProviderMetadata = void 0;\n\tlet lastPublishedValue = void 0;\n\tlet hasPublishedValue = false;\n\tfunction resetOutputState() {\n\t\tfirstTextChunkId = void 0;\n\t\ttext = \"\";\n\t\ttextChunk = \"\";\n\t\ttextProviderMetadata = void 0;\n\t\tlastPublishedValue = void 0;\n\t\thasPublishedValue = false;\n\t}\n\tfunction enqueueChunk({ controller, chunk }) {\n\t\tcontroller.enqueue(chunk);\n\t}\n\tfunction publishTextChunk({ controller, partialOutput = void 0 }) {\n\t\tenqueueChunk({\n\t\t\tcontroller,\n\t\t\tchunk: {\n\t\t\t\tpart: {\n\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\tid: firstTextChunkId,\n\t\t\t\t\ttext: textChunk,\n\t\t\t\t\tproviderMetadata: textProviderMetadata\n\t\t\t\t},\n\t\t\t\tpartialOutput\n\t\t\t}\n\t\t});\n\t\ttextChunk = \"\";\n\t}\n\treturn new TransformStream({ async transform(chunk, controller) {\n\t\tif (isStreamRetryBoundaryPart(chunk)) {\n\t\t\tresetOutputState();\n\t\t\tcontroller.enqueue(chunk);\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.type === \"start-step\") resetOutputState();\n\t\tif (chunk.type === \"finish-step\" && textChunk.length > 0) publishTextChunk({ controller });\n\t\tif (chunk.type !== \"text-delta\" && chunk.type !== \"text-start\" && chunk.type !== \"text-end\") {\n\t\t\tenqueueChunk({\n\t\t\t\tcontroller,\n\t\t\t\tchunk: {\n\t\t\t\t\tpart: chunk,\n\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (firstTextChunkId == null) firstTextChunkId = chunk.id;\n\t\telse if (chunk.id !== firstTextChunkId) {\n\t\t\tenqueueChunk({\n\t\t\t\tcontroller,\n\t\t\t\tchunk: {\n\t\t\t\t\tpart: chunk,\n\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.type === \"text-start\") {\n\t\t\tenqueueChunk({\n\t\t\t\tcontroller,\n\t\t\t\tchunk: {\n\t\t\t\t\tpart: chunk,\n\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.type === \"text-end\") {\n\t\t\tif (textChunk.length > 0) publishTextChunk({ controller });\n\t\t\tenqueueChunk({\n\t\t\t\tcontroller,\n\t\t\t\tchunk: {\n\t\t\t\t\tpart: chunk,\n\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\ttext += chunk.text;\n\t\ttextChunk += chunk.text;\n\t\ttextProviderMetadata = chunk.providerMetadata ?? textProviderMetadata;\n\t\tif (chunk.text.length === 0 && chunk.providerMetadata != null) {\n\t\t\tenqueueChunk({\n\t\t\t\tcontroller,\n\t\t\t\tchunk: {\n\t\t\t\t\tpart: chunk,\n\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst result = await output.parsePartialOutput({ text });\n\t\tif (result !== void 0) {\n\t\t\tconst currentValue = typeof result.partial === \"string\" ? result.partial : JSON.stringify(result.partial);\n\t\t\tif (!hasPublishedValue || currentValue !== lastPublishedValue) {\n\t\t\t\tpublishTextChunk({\n\t\t\t\t\tcontroller,\n\t\t\t\t\tpartialOutput: result.partial\n\t\t\t\t});\n\t\t\t\tlastPublishedValue = currentValue;\n\t\t\t\thasPublishedValue = true;\n\t\t\t}\n\t\t}\n\t} });\n}\nfunction applyStreamTextTransforms({ stream, transforms, tools, stopStream }) {\n\tconst sourceReader = stream.getReader();\n\tlet sourceDone = false;\n\tlet pendingBoundary;\n\tlet transformedSegmentReader;\n\tconst createTransformedSegmentReader = () => {\n\t\tlet segment = new ReadableStream({\n\t\t\tasync pull(controller) {\n\t\t\t\tconst { done, value } = await sourceReader.read();\n\t\t\t\tif (done) {\n\t\t\t\t\tsourceDone = true;\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (isStreamRetryBoundaryPart(value)) {\n\t\t\t\t\tpendingBoundary = value;\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcontroller.enqueue(value);\n\t\t\t},\n\t\t\tcancel(reason) {\n\t\t\t\treturn sourceReader.cancel(reason);\n\t\t\t}\n\t\t}, { highWaterMark: 0 });\n\t\tfor (const transform of transforms) segment = segment.pipeThrough(transform({\n\t\t\ttools,\n\t\t\tstopStream\n\t\t}));\n\t\treturn segment.getReader();\n\t};\n\treturn new ReadableStream({\n\t\tasync pull(controller) {\n\t\t\ttransformedSegmentReader ??= createTransformedSegmentReader();\n\t\t\tconst { done, value } = await transformedSegmentReader.read();\n\t\t\tif (!done) {\n\t\t\t\tcontroller.enqueue(value);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttransformedSegmentReader = void 0;\n\t\t\tif (pendingBoundary != null) {\n\t\t\t\tcontroller.enqueue(pendingBoundary);\n\t\t\t\tpendingBoundary = void 0;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (sourceDone) controller.close();\n\t\t},\n\t\tasync cancel(reason) {\n\t\t\tawait transformedSegmentReader?.cancel(reason);\n\t\t\tawait sourceReader.cancel(reason);\n\t\t}\n\t});\n}\nvar DefaultStreamTextResult = class {\n\tconstructor({ model, telemetry, headers, settings, maxRetries: maxRetriesArg, streamRetries: streamRetriesArg, abortSignal, stepTimeoutMs, stepAbortController, firstChunkTimeoutMs, firstChunkAbortController, chunkTimeoutMs, chunkAbortController, instructions, system, prompt, messages, allowSystemInMessages, experimental_sandbox: sandbox, tools, toolChoice, transforms, activeTools, toolOrder, repairToolCall, refineToolInput, stopConditions, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, providerOptions, prepareStep, now, generateId, generateCallId, timeout, onChunk, onError, canRetryStreamViaOnError, onEnd, onAbort, onStepFinish, onStart, onStepStart, onLanguageModelCallStart, onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, runtimeContext, toolsContext, download, include }) {\n\t\tthis._totalUsage = new DelayedPromise();\n\t\tthis._finishReason = new DelayedPromise();\n\t\tthis._rawFinishReason = new DelayedPromise();\n\t\tthis._steps = new DelayedPromise();\n\t\tthis._initialResponseMessages = new DelayedPromise();\n\t\tthis.outputSpecification = output;\n\t\tthis.tools = tools;\n\t\tconst resolvedToolCallers = resolveToolCallerConfiguration({\n\t\t\ttools,\n\t\t\ttoolCallers: experimental_toolCallers\n\t\t});\n\t\tconst prepareToolSearch = createToolSearchState({\n\t\t\ttools,\n\t\t\ttoolCallers: resolvedToolCallers\n\t\t});\n\t\tconst telemetryDispatcher = createRestrictedTelemetryDispatcher$3({\n\t\t\ttelemetry,\n\t\t\tincludeRuntimeContext: telemetry?.includeRuntimeContext,\n\t\t\tincludeToolsContext: telemetry?.includeToolsContext\n\t\t});\n\t\tlet stepFinish;\n\t\tlet recordedContent = [];\n\t\tlet recordedFinishReason = void 0;\n\t\tlet recordedRawFinishReason = void 0;\n\t\tlet recordedTotalUsage = void 0;\n\t\tlet recordedRequest = {};\n\t\tlet recordedRequestMessages = [];\n\t\tlet recordedWarnings = [];\n\t\tconst recordedSteps = [];\n\t\tconst initialResponseMessages = [];\n\t\tlet stepMessagesForNextStep;\n\t\tlet currentStepMessages = [];\n\t\tlet isAborted = false;\n\t\tlet currentStepModel = model;\n\t\tconst createPartIdReserver = () => {\n\t\t\tconst usedIds = /* @__PURE__ */ new Set();\n\t\t\treturn (id) => {\n\t\t\t\tif (!usedIds.has(id)) {\n\t\t\t\t\tusedIds.add(id);\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t\tconst generatedId = generateId();\n\t\t\t\tlet uniqueId = generatedId;\n\t\t\t\tlet suffix = 0;\n\t\t\t\twhile (usedIds.has(uniqueId)) uniqueId = `${generatedId}-${++suffix}`;\n\t\t\t\tusedIds.add(uniqueId);\n\t\t\t\treturn uniqueId;\n\t\t\t};\n\t\t};\n\t\tconst reserveTextPartId = createPartIdReserver();\n\t\tconst reserveReasoningPartId = createPartIdReserver();\n\t\tconst pendingDeferredToolCalls = /* @__PURE__ */ new Map();\n\t\tlet activeTextContent = createIdMap();\n\t\tlet activeReasoningContent = createIdMap();\n\t\tlet recordedNoOutputError;\n\t\tconst errorsHandledForStreamRetry = /* @__PURE__ */ new Set();\n\t\tconst eventProcessor = new TransformStream({\n\t\t\tasync transform(chunk, controller) {\n\t\t\t\tif (isStreamRetryBoundaryPart(chunk)) {\n\t\t\t\t\tconst retryBoundary = chunk[streamRetryBoundarySymbol];\n\t\t\t\t\trecordedContent = [];\n\t\t\t\t\tactiveReasoningContent = createIdMap();\n\t\t\t\t\tactiveTextContent = createIdMap();\n\t\t\t\t\trecordedRequest = retryBoundary.request;\n\t\t\t\t\trecordedRequestMessages = retryBoundary.request.messages ?? [];\n\t\t\t\t\trecordedWarnings = retryBoundary.warnings;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst { part } = chunk;\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\tconst callbacksHandledForStreamRetry = part.type === \"error\" && errorsHandledForStreamRetry.has(part.error);\n\t\t\t\tif (!callbacksHandledForStreamRetry) await notify({\n\t\t\t\t\tevent: { chunk: part },\n\t\t\t\t\tcallbacks: onChunk\n\t\t\t\t});\n\t\t\t\tif (part.type === \"error\") {\n\t\t\t\t\tconst error = wrapGatewayError(part.error);\n\t\t\t\t\tif (NoOutputGeneratedError.isInstance(error)) recordedNoOutputError = error;\n\t\t\t\t\tif (callbacksHandledForStreamRetry) errorsHandledForStreamRetry.delete(part.error);\n\t\t\t\t\telse await notify({\n\t\t\t\t\t\tevent: { error },\n\t\t\t\t\t\tcallbacks: async (event) => {\n\t\t\t\t\t\t\tawait onError(event);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (part.type === \"custom\" || part.type === \"source\" || part.type === \"tool-call\" || part.type === \"tool-approval-request\" || part.type === \"tool-approval-response\" || part.type === \"tool-error\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"text-start\") {\n\t\t\t\t\tactiveTextContent[part.id] = {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\trecordedContent.push(activeTextContent[part.id]);\n\t\t\t\t}\n\t\t\t\tif (part.type === \"text-delta\") {\n\t\t\t\t\tconst activeText = activeTextContent[part.id];\n\t\t\t\t\tif (activeText == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `text part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveText.text += part.text;\n\t\t\t\t\tactiveText.providerMetadata = part.providerMetadata ?? activeText.providerMetadata;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"text-end\") {\n\t\t\t\t\tconst activeText = activeTextContent[part.id];\n\t\t\t\t\tif (activeText == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `text part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveText.providerMetadata = part.providerMetadata ?? activeText.providerMetadata;\n\t\t\t\t\tdelete activeTextContent[part.id];\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-start\") {\n\t\t\t\t\tactiveReasoningContent[part.id] = {\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\trecordedContent.push(activeReasoningContent[part.id]);\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-delta\") {\n\t\t\t\t\tconst activeReasoning = activeReasoningContent[part.id];\n\t\t\t\t\tif (activeReasoning == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `reasoning part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveReasoning.text += part.text;\n\t\t\t\t\tactiveReasoning.providerMetadata = part.providerMetadata ?? activeReasoning.providerMetadata;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-end\") {\n\t\t\t\t\tconst activeReasoning = activeReasoningContent[part.id];\n\t\t\t\t\tif (activeReasoning == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `reasoning part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveReasoning.providerMetadata = part.providerMetadata ?? activeReasoning.providerMetadata;\n\t\t\t\t\tdelete activeReasoningContent[part.id];\n\t\t\t\t}\n\t\t\t\tif (part.type === \"file\" || part.type === \"reasoning-file\") recordedContent.push({\n\t\t\t\t\ttype: part.type,\n\t\t\t\t\tfile: part.file,\n\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t\tif (part.type === \"tool-result\" && !part.preliminary) recordedContent.push(part);\n\t\t\t\tif (part.type === \"start-step\") {\n\t\t\t\t\trecordedContent = [];\n\t\t\t\t\tactiveReasoningContent = createIdMap();\n\t\t\t\t\tactiveTextContent = createIdMap();\n\t\t\t\t\trecordedRequest = part.request;\n\t\t\t\t\trecordedWarnings = part.warnings;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"finish-step\") {\n\t\t\t\t\tconst stepResponseMessages = await toResponseMessages({\n\t\t\t\t\t\tcontent: recordedContent,\n\t\t\t\t\t\ttools\n\t\t\t\t\t});\n\t\t\t\t\tconst currentStepResult = new DefaultStepResult({\n\t\t\t\t\t\tcallId,\n\t\t\t\t\t\tstepNumber: recordedSteps.length,\n\t\t\t\t\t\tprovider: currentStepModel.provider,\n\t\t\t\t\t\tmodelId: currentStepModel.modelId,\n\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\tcontent: recordedContent,\n\t\t\t\t\t\tfinishReason: part.finishReason,\n\t\t\t\t\t\trawFinishReason: part.rawFinishReason,\n\t\t\t\t\t\tusage: part.usage,\n\t\t\t\t\t\tperformance: part.performance,\n\t\t\t\t\t\twarnings: recordedWarnings,\n\t\t\t\t\t\trequest: {\n\t\t\t\t\t\t\t...recordedRequest,\n\t\t\t\t\t\t\tmessages: include.requestMessages ? cloneModelMessages(recordedRequestMessages) : void 0\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t...part.response,\n\t\t\t\t\t\t\tmessages: cloneModelMessages(stepResponseMessages)\n\t\t\t\t\t\t},\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\tawait notify({\n\t\t\t\t\t\tevent: currentStepResult,\n\t\t\t\t\t\tcallbacks: [onStepFinish, telemetryDispatcher.onStepEnd]\n\t\t\t\t\t});\n\t\t\t\t\tlogWarnings({\n\t\t\t\t\t\twarnings: recordedWarnings,\n\t\t\t\t\t\tprovider: currentStepModel.provider,\n\t\t\t\t\t\tmodel: currentStepModel.modelId\n\t\t\t\t\t});\n\t\t\t\t\trecordedSteps.push(currentStepResult);\n\t\t\t\t\tstepMessagesForNextStep = [...currentStepMessages, ...stepResponseMessages];\n\t\t\t\t\tstepFinish.resolve();\n\t\t\t\t}\n\t\t\t\tif (part.type === \"finish\") {\n\t\t\t\t\trecordedTotalUsage = part.totalUsage;\n\t\t\t\t\trecordedFinishReason = part.finishReason;\n\t\t\t\t\trecordedRawFinishReason = part.rawFinishReason;\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync flush(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tif (recordedSteps.length === 0 || recordedNoOutputError != null) {\n\t\t\t\t\t\tconst error = abortSignal?.aborted ? abortSignal.reason : recordedNoOutputError ?? new NoOutputGeneratedError({ message: \"No output generated. Check the stream for errors.\" });\n\t\t\t\t\t\tself.rejectResultPromises(error);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst finishReason = recordedFinishReason ?? \"other\";\n\t\t\t\t\tconst totalUsage = recordedTotalUsage ?? createNullLanguageModelUsage();\n\t\t\t\t\tself._finishReason.resolve(finishReason);\n\t\t\t\t\tself._rawFinishReason.resolve(recordedRawFinishReason);\n\t\t\t\t\tself._totalUsage.resolve(totalUsage);\n\t\t\t\t\tself._steps.resolve(recordedSteps);\n\t\t\t\t\tif (isAborted) return;\n\t\t\t\t\tconst finalStep = recordedSteps[recordedSteps.length - 1];\n\t\t\t\t\tconst content = recordedSteps.flatMap((step) => step.content);\n\t\t\t\t\tconst files = recordedSteps.flatMap((step) => step.files);\n\t\t\t\t\tconst sources = recordedSteps.flatMap((step) => step.sources);\n\t\t\t\t\tconst toolCalls = recordedSteps.flatMap((step) => step.toolCalls);\n\t\t\t\t\tconst staticToolCalls = recordedSteps.flatMap((step) => step.staticToolCalls);\n\t\t\t\t\tconst dynamicToolCalls = recordedSteps.flatMap((step) => step.dynamicToolCalls);\n\t\t\t\t\tconst toolResults = recordedSteps.flatMap((step) => step.toolResults);\n\t\t\t\t\tconst staticToolResults = recordedSteps.flatMap((step) => step.staticToolResults);\n\t\t\t\t\tconst dynamicToolResults = recordedSteps.flatMap((step) => step.dynamicToolResults);\n\t\t\t\t\tconst warnings = recordedSteps.flatMap((step) => step.warnings ?? []);\n\t\t\t\t\tconst onEndWithOutput = onEnd == null ? void 0 : async (event) => {\n\t\t\t\t\t\tconst parsedOutput = output == null ? void 0 : await self.getOutputPromise().catch(() => void 0);\n\t\t\t\t\t\tawait onEnd({\n\t\t\t\t\t\t\t...event,\n\t\t\t\t\t\t\t...output != null ? { output: parsedOutput } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t};\n\t\t\t\t\tconst onEndEvent = {\n\t\t\t\t\t\tcallId,\n\t\t\t\t\t\ttoolsContext: finalStep.toolsContext,\n\t\t\t\t\t\tstepNumber: finalStep.stepNumber,\n\t\t\t\t\t\tmodel: finalStep.model,\n\t\t\t\t\t\truntimeContext: finalStep.runtimeContext,\n\t\t\t\t\t\tfinishReason: finalStep.finishReason,\n\t\t\t\t\t\trawFinishReason: finalStep.rawFinishReason,\n\t\t\t\t\t\tusage: totalUsage,\n\t\t\t\t\t\ttotalUsage,\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\ttext: finalStep.text,\n\t\t\t\t\t\treasoning: finalStep.reasoning,\n\t\t\t\t\t\treasoningText: finalStep.reasoningText,\n\t\t\t\t\t\tfiles,\n\t\t\t\t\t\tsources,\n\t\t\t\t\t\ttoolCalls,\n\t\t\t\t\t\tstaticToolCalls,\n\t\t\t\t\t\tdynamicToolCalls,\n\t\t\t\t\t\ttoolResults,\n\t\t\t\t\t\tstaticToolResults,\n\t\t\t\t\t\tdynamicToolResults,\n\t\t\t\t\t\tresponseMessages: [...initialResponseMessages, ...recordedSteps.flatMap((step) => step.response.messages)],\n\t\t\t\t\t\twarnings,\n\t\t\t\t\t\trequest: finalStep.request,\n\t\t\t\t\t\tresponse: finalStep.response,\n\t\t\t\t\t\tproviderMetadata: finalStep.providerMetadata,\n\t\t\t\t\t\tsteps: recordedSteps,\n\t\t\t\t\t\tfinalStep\n\t\t\t\t\t};\n\t\t\t\t\tawait Promise.all([notify({\n\t\t\t\t\t\tevent: onEndEvent,\n\t\t\t\t\t\tcallbacks: onEndWithOutput\n\t\t\t\t\t}), notify({\n\t\t\t\t\t\tevent: onEndEvent,\n\t\t\t\t\t\tcallbacks: telemetryDispatcher.onEnd\n\t\t\t\t\t})]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tconst stitchableStream = createStitchableStream();\n\t\tthis.addStream = stitchableStream.addStream;\n\t\tthis.closeStream = stitchableStream.close;\n\t\tconst reader = stitchableStream.stream.getReader();\n\t\tconst cancelOnAbort = () => {\n\t\t\tthis.rejectResultPromises(abortSignal?.reason);\n\t\t\treader.cancel(abortSignal?.reason).catch(() => {});\n\t\t};\n\t\tconst removeAbortListener = () => abortSignal?.removeEventListener(\"abort\", cancelOnAbort);\n\t\tlet stream = new ReadableStream({\n\t\t\tasync start(controller) {\n\t\t\t\tcontroller.enqueue({ type: \"start\" });\n\t\t\t\tabortSignal?.addEventListener(\"abort\", cancelOnAbort, { once: true });\n\t\t\t\tif (abortSignal?.aborted) cancelOnAbort();\n\t\t\t},\n\t\t\tasync pull(controller) {\n\t\t\t\tasync function abort() {\n\t\t\t\t\tisAborted = true;\n\t\t\t\t\tremoveAbortListener();\n\t\t\t\t\tawait notify({\n\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\tsteps: recordedSteps,\n\t\t\t\t\t\t\t...abortSignal?.reason !== void 0 ? { reason: abortSignal.reason } : {}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcallbacks: [onAbort, telemetryDispatcher.onAbort]\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"abort\",\n\t\t\t\t\t\t...abortSignal?.reason !== void 0 ? { reason: getErrorMessage$1(abortSignal.reason) } : {}\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.close();\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (abortSignal?.aborted) {\n\t\t\t\t\t\tawait abort();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tremoveAbortListener();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tremoveAbortListener();\n\t\t\t\t\tif (isAbortError(error) && abortSignal?.aborted) await abort();\n\t\t\t\t\telse {\n\t\t\t\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\terror\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontroller.error(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel(reason) {\n\t\t\t\tremoveAbortListener();\n\t\t\t\treturn reader.cancel(reason);\n\t\t\t}\n\t\t});\n\t\tlet isRunning = true;\n\t\tstream = stream.pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\t\tif (isRunning) controller.enqueue(chunk);\n\t\t} }));\n\t\tstream = applyStreamTextTransforms({\n\t\t\tstream,\n\t\t\ttransforms,\n\t\t\ttools,\n\t\t\tstopStream() {\n\t\t\t\tstitchableStream.terminate();\n\t\t\t\tisRunning = false;\n\t\t\t}\n\t\t});\n\t\tthis.baseStream = stream.pipeThrough(createOutputTransformStream(output ?? text())).pipeThrough(eventProcessor);\n\t\tconst { maxRetries } = prepareRetries({\n\t\t\tmaxRetries: maxRetriesArg,\n\t\t\tabortSignal\n\t\t});\n\t\tconst { maxRetries: streamRetries } = prepareRetries({\n\t\t\tmaxRetries: streamRetriesArg,\n\t\t\tabortSignal,\n\t\t\tparameter: \"streamRetries\",\n\t\t\tdefaultMaxRetries: 0\n\t\t});\n\t\tconst callSettings = prepareLanguageModelCallOptions(settings);\n\t\tconst self = this;\n\t\tconst callId = generateCallId();\n\t\t(async () => {\n\t\t\tconst initialPrompt = await standardizePrompt({\n\t\t\t\tinstructions,\n\t\t\t\tsystem,\n\t\t\t\tprompt,\n\t\t\t\tmessages,\n\t\t\t\tallowSystemInMessages\n\t\t\t});\n\t\t\tconst startEvent = {\n\t\t\t\tcallId,\n\t\t\t\toperationId: \"ai.streamText\",\n\t\t\t\tprovider: model.provider,\n\t\t\t\tmodelId: model.modelId,\n\t\t\t\tinstructions: initialPrompt.instructions,\n\t\t\t\tmessages: initialPrompt.messages,\n\t\t\t\ttools,\n\t\t\t\ttoolChoice,\n\t\t\t\tactiveTools,\n\t\t\t\ttoolOrder,\n\t\t\t\tmaxOutputTokens: callSettings.maxOutputTokens,\n\t\t\t\ttemperature: callSettings.temperature,\n\t\t\t\ttopP: callSettings.topP,\n\t\t\t\ttopK: callSettings.topK,\n\t\t\t\tpresencePenalty: callSettings.presencePenalty,\n\t\t\t\tfrequencyPenalty: callSettings.frequencyPenalty,\n\t\t\t\tstopSequences: callSettings.stopSequences,\n\t\t\t\tseed: callSettings.seed,\n\t\t\t\treasoning: callSettings.reasoning,\n\t\t\t\tmaxRetries,\n\t\t\t\ttimeout,\n\t\t\t\theaders,\n\t\t\t\tproviderOptions,\n\t\t\t\toutput,\n\t\t\t\truntimeContext,\n\t\t\t\ttoolsContext\n\t\t\t};\n\t\t\tconst streamTextTracingChannelContext = telemetryDispatcher.startTracingChannelContext?.({\n\t\t\t\ttype: \"streamText\",\n\t\t\t\tevent: startEvent,\n\t\t\t\tcompletion: self._totalUsage.promise.then(() => void 0)\n\t\t\t});\n\t\t\tconst runInStreamTextTracingChannelContext = (execute) => streamTextTracingChannelContext?.run(execute) ?? execute();\n\t\t\tconst runInTracingChannelSpanInStreamText = telemetryDispatcher.runInTracingChannelSpan == null ? void 0 : (options) => runInStreamTextTracingChannelContext(() => telemetryDispatcher.runInTracingChannelSpan(options));\n\t\t\tawait notify({\n\t\t\t\tevent: startEvent,\n\t\t\t\tcallbacks: [onStart, telemetryDispatcher.onStart]\n\t\t\t});\n\t\t\tconst initialMessages = initialPrompt.messages;\n\t\t\tlet instructionsForNextStep = initialPrompt.instructions;\n\t\t\tconst { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ messages: initialMessages });\n\t\t\tif (deniedToolApprovals.length > 0 || approvedToolApprovals.length > 0) {\n\t\t\t\tconst { approvedToolApprovals: localApprovedToolApprovals, deniedToolApprovals: revalidationDeniedToolApprovals, invalidToolApprovals } = await validateApprovedToolApprovals({\n\t\t\t\t\tapprovedToolApprovals: approvedToolApprovals.filter((toolApproval) => !toolApproval.toolCall.providerExecuted),\n\t\t\t\t\ttools,\n\t\t\t\t\ttoolApproval,\n\t\t\t\t\tmessages: initialMessages,\n\t\t\t\t\ttoolsContext,\n\t\t\t\t\truntimeContext,\n\t\t\t\t\ttoolApprovalSecret: experimental_toolApprovalSecret,\n\t\t\t\t\trefineToolInput\n\t\t\t\t});\n\t\t\t\tconst localDeniedToolApprovals = [...deniedToolApprovals.filter((toolApproval) => !toolApproval.toolCall.providerExecuted), ...revalidationDeniedToolApprovals];\n\t\t\t\tconst localDeniedToolApprovalsWithoutResults = localDeniedToolApprovals.filter((toolApproval) => toolApproval.existingToolResult == null);\n\t\t\t\tconst deniedProviderExecutedToolApprovals = deniedToolApprovals.filter((toolApproval) => toolApproval.toolCall.providerExecuted);\n\t\t\t\tlet toolExecutionStepStreamController;\n\t\t\t\tconst toolExecutionStepStream = new ReadableStream({ start(controller) {\n\t\t\t\t\ttoolExecutionStepStreamController = controller;\n\t\t\t\t} });\n\t\t\t\tself.addStream(toolExecutionStepStream);\n\t\t\t\ttry {\n\t\t\t\t\tfor (const toolApproval of [...localDeniedToolApprovals, ...deniedProviderExecutedToolApprovals]) toolExecutionStepStreamController?.enqueue({\n\t\t\t\t\t\ttype: \"tool-output-denied\",\n\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\ttoolName: toolApproval.toolCall.toolName\n\t\t\t\t\t});\n\t\t\t\t\tfor (const toolApproval of invalidToolApprovals) toolExecutionStepStreamController?.enqueue({\n\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\ttoolName: toolApproval.toolCall.toolName,\n\t\t\t\t\t\tinput: toolApproval.toolCall.input,\n\t\t\t\t\t\terror: getErrorMessage$1(toolApproval.error),\n\t\t\t\t\t\ttitle: toolApproval.toolCall.title,\n\t\t\t\t\t\t...toolApproval.toolCall.dynamic === true ? { dynamic: true } : {},\n\t\t\t\t\t\t...toolApproval.toolCall.toolMetadata != null ? { toolMetadata: toolApproval.toolCall.toolMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\tconst toolOutputs = [];\n\t\t\t\t\tawait Promise.all(localApprovedToolApprovals.map(async (toolApproval) => {\n\t\t\t\t\t\tconst result = await executeToolCall({\n\t\t\t\t\t\t\ttoolCall: toolApproval.toolCall,\n\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\tmessages: initialMessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\texperimental_sandbox: sandbox,\n\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\tonToolExecutionStart: filterNullable(onToolExecutionStart, telemetryDispatcher.onToolExecutionStart),\n\t\t\t\t\t\t\tonToolExecutionEnd: filterNullable(onToolExecutionEnd, telemetryDispatcher.onToolExecutionEnd),\n\t\t\t\t\t\t\texecuteToolInTelemetryContext: telemetryDispatcher.executeTool,\n\t\t\t\t\t\t\trunInTracingChannelSpan: runInTracingChannelSpanInStreamText,\n\t\t\t\t\t\t\tonPreliminaryToolResult: (result) => {\n\t\t\t\t\t\t\t\ttoolExecutionStepStreamController?.enqueue(result);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (result != null) {\n\t\t\t\t\t\t\ttoolExecutionStepStreamController?.enqueue(result.output);\n\t\t\t\t\t\t\ttoolOutputs.push(result.output);\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\tif (toolOutputs.length > 0 || localDeniedToolApprovalsWithoutResults.length > 0 || invalidToolApprovals.length > 0) {\n\t\t\t\t\t\tconst localToolContent = [];\n\t\t\t\t\t\tfor (const output of toolOutputs) localToolContent.push({\n\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\ttoolCallId: output.toolCallId,\n\t\t\t\t\t\t\ttoolName: output.toolName,\n\t\t\t\t\t\t\toutput: await createToolModelOutput({\n\t\t\t\t\t\t\t\ttoolCallId: output.toolCallId,\n\t\t\t\t\t\t\t\tinput: output.input,\n\t\t\t\t\t\t\t\ttool: getOwn(tools, output.toolName),\n\t\t\t\t\t\t\t\toutput: output.type === \"tool-result\" ? output.output : output.error,\n\t\t\t\t\t\t\t\terrorMode: output.type === \"tool-error\" ? \"text\" : \"none\"\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t});\n\t\t\t\t\t\tfor (const toolApproval of invalidToolApprovals) localToolContent.push({\n\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\t\ttoolName: toolApproval.toolCall.toolName,\n\t\t\t\t\t\t\toutput: await createToolModelOutput({\n\t\t\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\t\t\tinput: toolApproval.toolCall.input,\n\t\t\t\t\t\t\t\ttool: getOwn(tools, toolApproval.toolCall.toolName),\n\t\t\t\t\t\t\t\toutput: toolApproval.error,\n\t\t\t\t\t\t\t\terrorMode: \"text\"\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t});\n\t\t\t\t\t\tfor (const toolApproval of localDeniedToolApprovalsWithoutResults) localToolContent.push({\n\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\t\ttoolName: toolApproval.toolCall.toolName,\n\t\t\t\t\t\t\toutput: {\n\t\t\t\t\t\t\t\ttype: \"execution-denied\",\n\t\t\t\t\t\t\t\treason: toolApproval.approvalResponse.reason\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tinitialResponseMessages.push({\n\t\t\t\t\t\t\trole: \"tool\",\n\t\t\t\t\t\t\tcontent: localToolContent\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\ttoolExecutionStepStreamController?.close();\n\t\t\t\t}\n\t\t\t}\n\t\t\tself._initialResponseMessages.resolve(initialResponseMessages);\n\t\t\tasync function streamStep({ currentStep, usage }) {\n\t\t\t\tconst stepTimeoutId = setAbortTimeout({\n\t\t\t\t\tabortController: stepAbortController,\n\t\t\t\t\tlabel: \"Step\",\n\t\t\t\t\ttimeoutMs: stepTimeoutMs\n\t\t\t\t});\n\t\t\t\tlet firstChunkTimeoutId = void 0;\n\t\t\t\tfunction startFirstChunkTimeout() {\n\t\t\t\t\tif (abortSignal?.aborted) return;\n\t\t\t\t\tfirstChunkTimeoutId = setAbortTimeout({\n\t\t\t\t\t\tabortController: firstChunkAbortController,\n\t\t\t\t\t\tlabel: \"First chunk\",\n\t\t\t\t\t\ttimeoutMs: firstChunkTimeoutMs\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfunction clearFirstChunkTimeout() {\n\t\t\t\t\tif (firstChunkTimeoutId != null) {\n\t\t\t\t\t\tclearTimeout(firstChunkTimeoutId);\n\t\t\t\t\t\tfirstChunkTimeoutId = void 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlet chunkTimeoutId = void 0;\n\t\t\t\tfunction resetChunkTimeout() {\n\t\t\t\t\tif (chunkTimeoutId != null) clearTimeout(chunkTimeoutId);\n\t\t\t\t\tif (abortSignal?.aborted) return;\n\t\t\t\t\tchunkTimeoutId = setAbortTimeout({\n\t\t\t\t\t\tabortController: chunkAbortController,\n\t\t\t\t\t\tlabel: \"Chunk\",\n\t\t\t\t\t\ttimeoutMs: chunkTimeoutMs\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfunction clearChunkTimeout() {\n\t\t\t\t\tif (chunkTimeoutId != null) {\n\t\t\t\t\t\tclearTimeout(chunkTimeoutId);\n\t\t\t\t\t\tchunkTimeoutId = void 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfunction clearModelOutputTimeouts() {\n\t\t\t\t\tclearFirstChunkTimeout();\n\t\t\t\t\tclearChunkTimeout();\n\t\t\t\t}\n\t\t\t\tfunction clearStepTimeout() {\n\t\t\t\t\tif (stepTimeoutId != null) clearTimeout(stepTimeoutId);\n\t\t\t\t}\n\t\t\t\tfunction clearStepTimeouts() {\n\t\t\t\t\tclearStepTimeout();\n\t\t\t\t\tclearModelOutputTimeouts();\n\t\t\t\t}\n\t\t\t\tfunction cleanupStepTimeouts() {\n\t\t\t\t\tabortSignal?.removeEventListener(\"abort\", cleanupStepTimeouts);\n\t\t\t\t\tclearStepTimeouts();\n\t\t\t\t}\n\t\t\t\tabortSignal?.addEventListener(\"abort\", cleanupStepTimeouts, { once: true });\n\t\t\t\ttry {\n\t\t\t\t\tstepFinish = new DelayedPromise();\n\t\t\t\t\tconst stepTracingChannelContext = telemetryDispatcher.startTracingChannelContext?.({\n\t\t\t\t\t\ttype: \"step\",\n\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\tstepNumber: currentStep\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcompletion: stepFinish.promise\n\t\t\t\t\t});\n\t\t\t\t\tconst runInStepTracingChannelContext = (execute) => stepTracingChannelContext?.run(execute) ?? execute();\n\t\t\t\t\tconst responseMessagesFromPreviousSteps = recordedSteps.flatMap((step) => step.response.messages);\n\t\t\t\t\tconst accumulatedResponseMessages = [...initialResponseMessages, ...responseMessagesFromPreviousSteps];\n\t\t\t\t\tconst stepInputMessages = stepMessagesForNextStep ?? [...initialMessages, ...initialResponseMessages];\n\t\t\t\t\tconst prepareStepResult = await prepareStep?.({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsteps: recordedSteps,\n\t\t\t\t\t\tstepNumber: recordedSteps.length,\n\t\t\t\t\t\tinstructions: instructionsForNextStep,\n\t\t\t\t\t\tinitialInstructions: initialPrompt.instructions,\n\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\tinitialMessages,\n\t\t\t\t\t\tresponseMessages: accumulatedResponseMessages,\n\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\texperimental_sandbox: sandbox\n\t\t\t\t\t});\n\t\t\t\t\tconst stepSandbox = prepareStepResult?.experimental_sandbox ?? sandbox;\n\t\t\t\t\truntimeContext = prepareStepResult?.runtimeContext ?? runtimeContext;\n\t\t\t\t\ttoolsContext = prepareStepResult?.toolsContext ?? toolsContext;\n\t\t\t\t\tconst stepModel = resolveLanguageModel(prepareStepResult?.model ?? model);\n\t\t\t\t\tcurrentStepModel = stepModel;\n\t\t\t\t\tconst stepActiveTools = filterActiveTools({\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\tactiveTools: prepareStepResult?.activeTools ?? activeTools\n\t\t\t\t\t});\n\t\t\t\t\tconst { executionTools: stepExecutionTools, modelTools: stepModelTools, toolCallerMessages } = prepareToolsForToolCallers({\n\t\t\t\t\t\ttools: prepareToolSearch(stepActiveTools, {\n\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\texperimental_sandbox: stepSandbox\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttoolCallers: resolvedToolCallers\n\t\t\t\t\t});\n\t\t\t\t\tconst stepToolOrder = prepareStepResult?.toolOrder ?? toolOrder;\n\t\t\t\t\tconst stepTools = await prepareTools({\n\t\t\t\t\t\ttools: stepModelTools,\n\t\t\t\t\t\ttoolOrder: stepToolOrder,\n\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\texperimental_sandbox: stepSandbox\n\t\t\t\t\t});\n\t\t\t\t\tconst stepToolChoice = prepareToolChoice({ toolChoice: prepareStepResult?.toolChoice ?? toolChoice });\n\t\t\t\t\tconst stepMessages = appendToolCallerMessages({\n\t\t\t\t\t\tmessages: prepareStepResult?.messages ?? stepInputMessages,\n\t\t\t\t\t\ttoolCallerMessages\n\t\t\t\t\t});\n\t\t\t\t\tcurrentStepMessages = stepMessages;\n\t\t\t\t\tconst stepInstructions = prepareStepResult?.instructions ?? prepareStepResult?.system ?? instructionsForNextStep;\n\t\t\t\t\tinstructionsForNextStep = stepInstructions;\n\t\t\t\t\tconst stepProviderOptions = mergeObjects(providerOptions, prepareStepResult?.providerOptions);\n\t\t\t\t\tconst stepCallSettings = prepareStepCallSettings({\n\t\t\t\t\t\tcallSettings,\n\t\t\t\t\t\tstepSettings: prepareStepResult\n\t\t\t\t\t});\n\t\t\t\t\tconst stepStartTimestampMs = now();\n\t\t\t\t\tconst { retry } = prepareRetries({\n\t\t\t\t\t\tmaxRetries,\n\t\t\t\t\t\tabortSignal\n\t\t\t\t\t});\n\t\t\t\t\tlet hasNotifiedStepStart = false;\n\t\t\t\t\tconst callLanguageModel = () => runInStepTracingChannelContext(() => retry(async () => streamLanguageModelCall({\n\t\t\t\t\t\tmodel: prepareStepResult?.model ?? model,\n\t\t\t\t\t\ttools: stepModelTools,\n\t\t\t\t\t\ttoolOrder: stepToolOrder,\n\t\t\t\t\t\ttoolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n\t\t\t\t\t\tinstructions: stepInstructions,\n\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\tallowSystemInMessages,\n\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\trefineToolInput,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tincludeRawChunks: include.rawChunks,\n\t\t\t\t\t\tproviderOptions: stepProviderOptions,\n\t\t\t\t\t\tdownload,\n\t\t\t\t\t\toutput,\n\t\t\t\t\t\tcallId,\n\t\t\t\t\t\texecuteLanguageModelCallInTelemetryContext: telemetryDispatcher.executeLanguageModelCall,\n\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\texperimental_sandbox: stepSandbox,\n\t\t\t\t\t\tonLanguageModelCallStart: filterNullable(onLanguageModelCallStart, telemetryDispatcher.onLanguageModelCallStart),\n\t\t\t\t\t\tonLanguageModelCallEnd: filterNullable(onLanguageModelCallEnd, telemetryDispatcher.onLanguageModelCallEnd),\n\t\t\t\t\t\tonStart: async ({ promptMessages }) => {\n\t\t\t\t\t\t\tif (hasNotifiedStepStart) return;\n\t\t\t\t\t\t\thasNotifiedStepStart = true;\n\t\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\t\tprovider: stepModel.provider,\n\t\t\t\t\t\t\t\t\tmodelId: stepModel.modelId,\n\t\t\t\t\t\t\t\t\tstepNumber: recordedSteps.length,\n\t\t\t\t\t\t\t\t\tinstructions: stepInstructions,\n\t\t\t\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\t\t\ttoolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n\t\t\t\t\t\t\t\t\tactiveTools: prepareStepResult?.activeTools ?? activeTools,\n\t\t\t\t\t\t\t\t\ttoolOrder: stepToolOrder,\n\t\t\t\t\t\t\t\t\tsteps: [...recordedSteps],\n\t\t\t\t\t\t\t\t\tproviderOptions: stepProviderOptions,\n\t\t\t\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\t\t\tpromptMessages,\n\t\t\t\t\t\t\t\t\tstepTools,\n\t\t\t\t\t\t\t\t\tstepToolChoice\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tcallbacks: [onStepStart, telemetryDispatcher.onStepStart]\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t},\n\t\t\t\t\t\t_internal: { now },\n\t\t\t\t\t\t...stepCallSettings\n\t\t\t\t\t})));\n\t\t\t\t\tconst initialLanguageModelCall = await callLanguageModel();\n\t\t\t\t\tlet request = initialLanguageModelCall.request;\n\t\t\t\t\tlet response = initialLanguageModelCall.response;\n\t\t\t\t\tlet languageModelStreamReader = initialLanguageModelCall.stream.getReader();\n\t\t\t\t\tlet automaticStreamRetryCount = 0;\n\t\t\t\t\tlet callbackStreamRetryCount = 0;\n\t\t\t\t\tlet bufferedAttemptParts = [];\n\t\t\t\t\tconst openTextParts = /* @__PURE__ */ new Set();\n\t\t\t\t\tconst openReasoningParts = /* @__PURE__ */ new Set();\n\t\t\t\t\tlet enqueueStreamRetryAttemptBoundary = false;\n\t\t\t\t\tconst shouldBufferToolParts = streamRetries > 0 || canRetryStreamViaOnError;\n\t\t\t\t\tconst languageModelStream = new ReadableStream({\n\t\t\t\t\t\tasync pull(controller) {\n\t\t\t\t\t\t\tconst enqueueAttemptPart = (part) => {\n\t\t\t\t\t\t\t\tswitch (part.type) {\n\t\t\t\t\t\t\t\t\tcase \"text-start\":\n\t\t\t\t\t\t\t\t\t\topenTextParts.add(part.id);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"text-end\":\n\t\t\t\t\t\t\t\t\t\topenTextParts.delete(part.id);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"reasoning-start\":\n\t\t\t\t\t\t\t\t\t\topenReasoningParts.add(part.id);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"reasoning-end\": openReasoningParts.delete(part.id);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontroller.enqueue(part);\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst flushBufferedAttemptParts = () => {\n\t\t\t\t\t\t\t\tfor (const part of bufferedAttemptParts) enqueueAttemptPart(part);\n\t\t\t\t\t\t\t\tbufferedAttemptParts = [];\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst closeOpenAttemptParts = () => {\n\t\t\t\t\t\t\t\tfor (const id of openTextParts) controller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-end\",\n\t\t\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\topenTextParts.clear();\n\t\t\t\t\t\t\t\tfor (const id of openReasoningParts) controller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\topenReasoningParts.clear();\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\t\tlet result;\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tresult = await languageModelStreamReader.read();\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tclearModelOutputTimeouts();\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst { done, value } = result;\n\t\t\t\t\t\t\t\tif (enqueueStreamRetryAttemptBoundary) {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(createStreamRetryAttemptBoundaryPart({ warnings: !done && value.type === \"model-call-start\" ? value.warnings : [] }));\n\t\t\t\t\t\t\t\t\tenqueueStreamRetryAttemptBoundary = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (done) {\n\t\t\t\t\t\t\t\t\tclearModelOutputTimeouts();\n\t\t\t\t\t\t\t\t\tflushBufferedAttemptParts();\n\t\t\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst isToolPart = value.type === \"tool-input-start\" || value.type === \"tool-input-delta\" || value.type === \"tool-input-end\" || value.type === \"tool-call\" || value.type === \"tool-approval-request\" || value.type === \"tool-approval-response\" || value.type === \"tool-result\" || value.type === \"tool-error\";\n\t\t\t\t\t\t\t\tif (value.type === \"model-call-end\") {\n\t\t\t\t\t\t\t\t\tclearModelOutputTimeouts();\n\t\t\t\t\t\t\t\t\tflushBufferedAttemptParts();\n\t\t\t\t\t\t\t\t\tenqueueAttemptPart(value);\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (isOutputChunk(value)) {\n\t\t\t\t\t\t\t\t\tclearFirstChunkTimeout();\n\t\t\t\t\t\t\t\t\tresetChunkTimeout();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (shouldBufferToolParts && value.type !== \"error\" && (isToolPart || bufferedAttemptParts.length > 0)) {\n\t\t\t\t\t\t\t\t\tbufferedAttemptParts.push(value);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (value.type !== \"error\") {\n\t\t\t\t\t\t\t\t\tenqueueAttemptPart(value);\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tclearModelOutputTimeouts();\n\t\t\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\t\t\tevent: { chunk: value },\n\t\t\t\t\t\t\t\t\tcallbacks: onChunk\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst error = wrapGatewayError(value.error);\n\t\t\t\t\t\t\t\tconst isToolChoiceViolation = ToolChoiceViolationError.isInstance(error);\n\t\t\t\t\t\t\t\tlet onErrorResult;\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tonErrorResult = await onError({ error });\n\t\t\t\t\t\t\t\t} catch {}\n\t\t\t\t\t\t\t\tconst callbackRequestedRetry = canRetryStreamViaOnError && typeof onErrorResult === \"object\" && onErrorResult != null && \"retry\" in onErrorResult && onErrorResult.retry === true;\n\t\t\t\t\t\t\t\tconst automaticRetry = !isToolChoiceViolation && automaticStreamRetryCount < streamRetries;\n\t\t\t\t\t\t\t\tif (!automaticRetry && !(!isToolChoiceViolation && !automaticRetry && callbackRequestedRetry && callbackStreamRetryCount < 1)) {\n\t\t\t\t\t\t\t\t\tflushBufferedAttemptParts();\n\t\t\t\t\t\t\t\t\terrorsHandledForStreamRetry.add(value.error);\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (automaticRetry) automaticStreamRetryCount++;\n\t\t\t\t\t\t\t\telse callbackStreamRetryCount++;\n\t\t\t\t\t\t\t\tawait languageModelStreamReader.cancel(error);\n\t\t\t\t\t\t\t\tbufferedAttemptParts = [];\n\t\t\t\t\t\t\t\tcloseOpenAttemptParts();\n\t\t\t\t\t\t\t\tlet retryLanguageModelCall;\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tretryLanguageModelCall = await callLanguageModel();\n\t\t\t\t\t\t\t\t} catch (retryError) {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\t\t\terror: retryError\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\trequest = retryLanguageModelCall.request;\n\t\t\t\t\t\t\t\tresponse = retryLanguageModelCall.response;\n\t\t\t\t\t\t\t\tlanguageModelStreamReader = retryLanguageModelCall.stream.getReader();\n\t\t\t\t\t\t\t\tstartFirstChunkTimeout();\n\t\t\t\t\t\t\t\tenqueueStreamRetryAttemptBoundary = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcancel(reason) {\n\t\t\t\t\t\t\tclearModelOutputTimeouts();\n\t\t\t\t\t\t\treturn languageModelStreamReader.cancel(reason);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tstartFirstChunkTimeout();\n\t\t\t\t\tconst streamAfterToolCallbackInvocation = invokeToolCallbacksFromStream({\n\t\t\t\t\t\tstream: languageModelStream,\n\t\t\t\t\t\ttools: stepExecutionTools,\n\t\t\t\t\t\tstepInputMessages: stepMessages,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\ttoolsContext\n\t\t\t\t\t});\n\t\t\t\t\tconst runInTracingChannelSpanInStep = telemetryDispatcher.runInTracingChannelSpan == null ? void 0 : (options) => runInStepTracingChannelContext(() => telemetryDispatcher.runInTracingChannelSpan(options));\n\t\t\t\t\tconst streamWithToolResults = executeToolsFromStream({\n\t\t\t\t\t\tstream: streamAfterToolCallbackInvocation,\n\t\t\t\t\t\ttools: stepExecutionTools,\n\t\t\t\t\t\tcallId,\n\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\texperimental_sandbox: stepSandbox,\n\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\ttoolApproval,\n\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\ttoolApprovalSecret: experimental_toolApprovalSecret,\n\t\t\t\t\t\tgenerateId,\n\t\t\t\t\t\tonToolExecutionStart: filterNullable(onToolExecutionStart, telemetryDispatcher.onToolExecutionStart),\n\t\t\t\t\t\tonToolExecutionEnd: filterNullable(onToolExecutionEnd, telemetryDispatcher.onToolExecutionEnd),\n\t\t\t\t\t\texecuteToolInTelemetryContext: telemetryDispatcher.executeTool,\n\t\t\t\t\t\trunInTracingChannelSpan: runInTracingChannelSpanInStep\n\t\t\t\t\t});\n\t\t\t\t\tconst getStepRequest = () => ({\n\t\t\t\t\t\t...request,\n\t\t\t\t\t\tbody: include.requestBody ? request?.body : void 0,\n\t\t\t\t\t\tmessages: include.requestMessages ? cloneModelMessages(stepMessages) : void 0\n\t\t\t\t\t});\n\t\t\t\t\trecordedRequestMessages = getStepRequest().messages ?? [];\n\t\t\t\t\tconst stepToolCalls = [];\n\t\t\t\t\tconst stepToolOutputs = [];\n\t\t\t\t\tconst stepToolApprovalResponses = [];\n\t\t\t\t\tlet warnings;\n\t\t\t\t\tlet stepFinishReason = \"other\";\n\t\t\t\t\tlet stepRawFinishReason = void 0;\n\t\t\t\t\tlet hasReceivedTerminalChunk = false;\n\t\t\t\t\tlet hasReceivedOutputChunk = false;\n\t\t\t\t\tlet stepUsage = createNullLanguageModelUsage();\n\t\t\t\t\tlet stepProviderMetadata;\n\t\t\t\t\tlet stepFirstChunk = true;\n\t\t\t\t\tconst createModelCallPerformance = () => ({\n\t\t\t\t\t\tresponseTimeMs: 0,\n\t\t\t\t\t\teffectiveOutputTokensPerSecond: 0,\n\t\t\t\t\t\toutputTokensPerSecond: void 0,\n\t\t\t\t\t\tinputTokensPerSecond: void 0,\n\t\t\t\t\t\teffectiveTotalTokensPerSecond: 0,\n\t\t\t\t\t\ttimeToFirstOutputMs: void 0,\n\t\t\t\t\t\ttimeBetweenOutputChunksMs: void 0\n\t\t\t\t\t});\n\t\t\t\t\tlet modelCallPerformance = createModelCallPerformance();\n\t\t\t\t\tconst toolExecutionMs = {};\n\t\t\t\t\tconst createStepResponse = () => ({\n\t\t\t\t\t\tid: generateId(),\n\t\t\t\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\t\t\t\tmodelId: stepModel.modelId\n\t\t\t\t\t});\n\t\t\t\t\tlet stepResponse = createStepResponse();\n\t\t\t\t\tconst textPartIds = /* @__PURE__ */ new Map();\n\t\t\t\t\tconst reasoningPartIds = /* @__PURE__ */ new Map();\n\t\t\t\t\tconst enqueueStepPart = (controller, part) => {\n\t\t\t\t\t\tcontroller.enqueue(part);\n\t\t\t\t\t};\n\t\t\t\t\tself.addStream(streamWithToolResults.pipeThrough(new TransformStream({\n\t\t\t\t\t\tasync transform(chunk, controller) {\n\t\t\t\t\t\t\tif (isStreamRetryAttemptBoundaryPart(chunk)) {\n\t\t\t\t\t\t\t\twarnings = chunk.warnings;\n\t\t\t\t\t\t\t\tstepFinishReason = \"other\";\n\t\t\t\t\t\t\t\tstepRawFinishReason = void 0;\n\t\t\t\t\t\t\t\thasReceivedTerminalChunk = false;\n\t\t\t\t\t\t\t\thasReceivedOutputChunk = false;\n\t\t\t\t\t\t\t\tstepUsage = createNullLanguageModelUsage();\n\t\t\t\t\t\t\t\tstepProviderMetadata = void 0;\n\t\t\t\t\t\t\t\tmodelCallPerformance = createModelCallPerformance();\n\t\t\t\t\t\t\t\tstepResponse = createStepResponse();\n\t\t\t\t\t\t\t\ttextPartIds.clear();\n\t\t\t\t\t\t\t\treasoningPartIds.clear();\n\t\t\t\t\t\t\t\tcontroller.enqueue({ [streamRetryBoundarySymbol]: {\n\t\t\t\t\t\t\t\t\trequest: getStepRequest(),\n\t\t\t\t\t\t\t\t\twarnings\n\t\t\t\t\t\t\t\t} });\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (chunk.type === \"model-call-start\") {\n\t\t\t\t\t\t\t\twarnings = chunk.warnings;\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (stepFirstChunk) {\n\t\t\t\t\t\t\t\tstepFirstChunk = false;\n\t\t\t\t\t\t\t\tenqueueStepPart(controller, {\n\t\t\t\t\t\t\t\t\ttype: \"start-step\",\n\t\t\t\t\t\t\t\t\trequest: getStepRequest(),\n\t\t\t\t\t\t\t\t\twarnings: warnings ?? []\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst chunkType = chunk.type;\n\t\t\t\t\t\t\tif (isOutputChunk(chunk)) hasReceivedOutputChunk = true;\n\t\t\t\t\t\t\tswitch (chunkType) {\n\t\t\t\t\t\t\t\tcase \"file\":\n\t\t\t\t\t\t\t\tcase \"custom\":\n\t\t\t\t\t\t\t\tcase \"source\":\n\t\t\t\t\t\t\t\tcase \"reasoning-file\":\n\t\t\t\t\t\t\t\tcase \"tool-input-start\":\n\t\t\t\t\t\t\t\tcase \"tool-input-end\":\n\t\t\t\t\t\t\t\tcase \"tool-input-delta\":\n\t\t\t\t\t\t\t\tcase \"tool-approval-request\":\n\t\t\t\t\t\t\t\tcase \"tool-output-denied\":\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"text-start\": {\n\t\t\t\t\t\t\t\t\tconst id = reserveTextPartId(chunk.id);\n\t\t\t\t\t\t\t\t\ttextPartIds.set(chunk.id, id);\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, {\n\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\t\t\t\tif (chunk.text.length > 0 || chunk.providerMetadata != null) enqueueStepPart(controller, {\n\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\tid: textPartIds.get(chunk.id) ?? chunk.id\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"text-end\":\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, {\n\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\tid: textPartIds.get(chunk.id) ?? chunk.id\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\ttextPartIds.delete(chunk.id);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"reasoning-start\": {\n\t\t\t\t\t\t\t\t\tconst id = reserveReasoningPartId(chunk.id);\n\t\t\t\t\t\t\t\t\treasoningPartIds.set(chunk.id, id);\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, {\n\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"reasoning-delta\":\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, {\n\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\tid: reasoningPartIds.get(chunk.id) ?? chunk.id\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"reasoning-end\":\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, {\n\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\tid: reasoningPartIds.get(chunk.id) ?? chunk.id\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\treasoningPartIds.delete(chunk.id);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-call\":\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, chunk);\n\t\t\t\t\t\t\t\t\tstepToolCalls.push(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-approval-response\":\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, chunk);\n\t\t\t\t\t\t\t\t\tstepToolApprovalResponses.push(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-result\":\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, chunk);\n\t\t\t\t\t\t\t\t\tif (!chunk.preliminary) stepToolOutputs.push(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-error\":\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, chunk);\n\t\t\t\t\t\t\t\t\tstepToolOutputs.push(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-execution-end\":\n\t\t\t\t\t\t\t\t\ttoolExecutionMs[chunk.toolCallId] = chunk.toolExecutionMs;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"model-call-response-metadata\":\n\t\t\t\t\t\t\t\t\tstepResponse = {\n\t\t\t\t\t\t\t\t\t\tid: chunk.id ?? stepResponse.id,\n\t\t\t\t\t\t\t\t\t\ttimestamp: chunk.timestamp ?? stepResponse.timestamp,\n\t\t\t\t\t\t\t\t\t\tmodelId: chunk.modelId ?? stepResponse.modelId\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"model-call-end\":\n\t\t\t\t\t\t\t\t\thasReceivedTerminalChunk = true;\n\t\t\t\t\t\t\t\t\tstepUsage = chunk.usage;\n\t\t\t\t\t\t\t\t\tstepFinishReason = chunk.finishReason;\n\t\t\t\t\t\t\t\t\tstepRawFinishReason = chunk.rawFinishReason;\n\t\t\t\t\t\t\t\t\tstepProviderMetadata = chunk.providerMetadata;\n\t\t\t\t\t\t\t\t\tmodelCallPerformance = chunk.performance;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\t\t\t\thasReceivedTerminalChunk = true;\n\t\t\t\t\t\t\t\t\tenqueueStepPart(controller, chunk);\n\t\t\t\t\t\t\t\t\tstepFinishReason = \"error\";\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"raw\":\n\t\t\t\t\t\t\t\t\tif (include.rawChunks) enqueueStepPart(controller, chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tdefault: throw new Error(`Unknown chunk type: ${chunkType}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tasync flush(controller) {\n\t\t\t\t\t\t\tif (!hasReceivedTerminalChunk && !hasReceivedOutputChunk) {\n\t\t\t\t\t\t\t\tenqueueStepPart(controller, {\n\t\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\t\terror: new NoOutputGeneratedError({ message: \"No output generated. The model stream ended without a finish chunk.\" })\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcleanupStepTimeouts();\n\t\t\t\t\t\t\t\tself.closeStream();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst stepTimeMs = now() - stepStartTimestampMs;\n\t\t\t\t\t\t\tconst finishStepPart = {\n\t\t\t\t\t\t\t\ttype: \"finish-step\",\n\t\t\t\t\t\t\t\tfinishReason: stepFinishReason,\n\t\t\t\t\t\t\t\trawFinishReason: stepRawFinishReason,\n\t\t\t\t\t\t\t\tusage: stepUsage,\n\t\t\t\t\t\t\t\tperformance: {\n\t\t\t\t\t\t\t\t\tstepTimeMs,\n\t\t\t\t\t\t\t\t\ttoolExecutionMs,\n\t\t\t\t\t\t\t\t\t...modelCallPerformance\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tproviderMetadata: stepProviderMetadata,\n\t\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\t\t...stepResponse,\n\t\t\t\t\t\t\t\t\theaders: response?.headers\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tenqueueStepPart(controller, finishStepPart);\n\t\t\t\t\t\t\tconst combinedUsage = addLanguageModelUsage(usage, stepUsage);\n\t\t\t\t\t\t\tawait stepFinish.promise;\n\t\t\t\t\t\t\tconst clientToolCalls = stepToolCalls.filter((toolCall) => toolCall.providerExecuted !== true);\n\t\t\t\t\t\t\tconst clientToolOutputs = stepToolOutputs.filter((toolOutput) => toolOutput.providerExecuted !== true);\n\t\t\t\t\t\t\tconst deniedToolApprovalResponses = stepToolApprovalResponses.filter((toolApprovalResponse) => toolApprovalResponse.approved === false);\n\t\t\t\t\t\t\tfor (const toolCall of stepToolCalls) {\n\t\t\t\t\t\t\t\tif (toolCall.providerExecuted !== true) continue;\n\t\t\t\t\t\t\t\tconst tool = getOwn(stepExecutionTools, toolCall.toolName);\n\t\t\t\t\t\t\t\tif (tool?.type === \"provider\" && tool.supportsDeferredResults) {\n\t\t\t\t\t\t\t\t\tif (!stepToolOutputs.some((output) => (output.type === \"tool-result\" || output.type === \"tool-error\") && output.toolCallId === toolCall.toolCallId)) pendingDeferredToolCalls.set(toolCall.toolCallId, { toolName: toolCall.toolName });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (const output of stepToolOutputs) if (output.type === \"tool-result\" || output.type === \"tool-error\") pendingDeferredToolCalls.delete(output.toolCallId);\n\t\t\t\t\t\t\tcleanupStepTimeouts();\n\t\t\t\t\t\t\tif (clientToolCalls.length === clientToolOutputs.length + deniedToolApprovalResponses.length && (clientToolCalls.length > 0 || pendingDeferredToolCalls.size > 0) && !await isStopConditionMet({\n\t\t\t\t\t\t\t\tstopConditions,\n\t\t\t\t\t\t\t\tsteps: recordedSteps\n\t\t\t\t\t\t\t})) try {\n\t\t\t\t\t\t\t\tawait runInStreamTextTracingChannelContext(() => streamStep({\n\t\t\t\t\t\t\t\t\tcurrentStep: currentStep + 1,\n\t\t\t\t\t\t\t\t\tusage: combinedUsage\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tenqueueStepPart(controller, {\n\t\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tself.closeStream();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tenqueueStepPart(controller, {\n\t\t\t\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\t\t\t\tfinishReason: stepFinishReason,\n\t\t\t\t\t\t\t\t\trawFinishReason: stepRawFinishReason,\n\t\t\t\t\t\t\t\t\ttotalUsage: combinedUsage\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tself.closeStream();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})), {\n\t\t\t\t\t\tonError: cleanupStepTimeouts,\n\t\t\t\t\t\tonCancel: cleanupStepTimeouts\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcleanupStepTimeouts();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait runInStreamTextTracingChannelContext(() => streamStep({\n\t\t\t\tcurrentStep: 0,\n\t\t\t\tusage: createNullLanguageModelUsage()\n\t\t\t}));\n\t\t})().catch(async (error) => {\n\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\tcallId,\n\t\t\t\terror\n\t\t\t});\n\t\t\tself._initialResponseMessages.reject(error);\n\t\t\tmarkPromiseAsHandled$1(self._initialResponseMessages.promise);\n\t\t\tself.addStream(new ReadableStream({ start(controller) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tcontroller.close();\n\t\t\t} }));\n\t\t\tself.closeStream();\n\t\t});\n\t}\n\tget steps() {\n\t\tthis.consumeStream();\n\t\treturn this._steps.promise;\n\t}\n\tget finalStep() {\n\t\treturn this.steps.then((steps) => steps.at(-1));\n\t}\n\tget content() {\n\t\treturn this.steps.then((steps) => steps.flatMap((step) => step.content));\n\t}\n\tget warnings() {\n\t\treturn this.steps.then((steps) => steps.flatMap((step) => step.warnings ?? []));\n\t}\n\tget providerMetadata() {\n\t\treturn this.finalStep.then((step) => step.providerMetadata);\n\t}\n\tget text() {\n\t\treturn this.finalStep.then((step) => step.text);\n\t}\n\tget reasoningText() {\n\t\treturn this.finalStep.then((step) => step.reasoningText);\n\t}\n\tget reasoning() {\n\t\treturn this.finalStep.then((step) => convertToReasoningOutputs(step.reasoning));\n\t}\n\tget sources() {\n\t\treturn this.steps.then((steps) => steps.flatMap((step) => step.sources));\n\t}\n\tget files() {\n\t\treturn this.steps.then((steps) => steps.flatMap((step) => step.files));\n\t}\n\tget toolCalls() {\n\t\treturn this.steps.then((steps) => steps.flatMap((step) => step.toolCalls));\n\t}\n\tget staticToolCalls() {\n\t\treturn this.steps.then((steps) => steps.flatMap((step) => step.staticToolCalls));\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.steps.then((steps) => steps.flatMap((step) => step.dynamicToolCalls));\n\t}\n\tget toolResults() {\n\t\treturn this.steps.then((steps) => steps.flatMap((step) => step.toolResults));\n\t}\n\tget staticToolResults() {\n\t\treturn this.steps.then((steps) => steps.flatMap((step) => step.staticToolResults));\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.steps.then((steps) => steps.flatMap((step) => step.dynamicToolResults));\n\t}\n\tget usage() {\n\t\treturn this.totalUsage;\n\t}\n\tget request() {\n\t\treturn this.finalStep.then((step) => step.request);\n\t}\n\tget response() {\n\t\treturn this.finalStep.then((step) => step.response);\n\t}\n\tget responseMessages() {\n\t\treturn Promise.all([this._initialResponseMessages.promise, this.steps]).then(([initialResponseMessages, steps]) => [...initialResponseMessages, ...steps.flatMap((step) => step.response.messages)]);\n\t}\n\tget totalUsage() {\n\t\tthis.consumeStream();\n\t\treturn this._totalUsage.promise;\n\t}\n\tget finishReason() {\n\t\tthis.consumeStream();\n\t\treturn this._finishReason.promise;\n\t}\n\tget rawFinishReason() {\n\t\tthis.consumeStream();\n\t\treturn this._rawFinishReason.promise;\n\t}\n\t/**\n\t* Split out a new stream from the original stream.\n\t* The original stream is replaced to allow for further splitting,\n\t* since we do not know how many times the stream will be split.\n\t*\n\t* Note: this leads to buffering the stream content on the server.\n\t* However, the LLM results are expected to be small enough to not cause issues.\n\t*/\n\tteeStream() {\n\t\tconst [stream1, stream2] = this.baseStream.tee();\n\t\tthis.baseStream = stream2;\n\t\treturn stream1;\n\t}\n\tget textStream() {\n\t\treturn createAsyncIterableStream(toTextStream({ stream: this.stream }));\n\t}\n\tget stream() {\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ part }, controller) {\n\t\t\tcontroller.enqueue(part);\n\t\t} })));\n\t}\n\tget fullStream() {\n\t\treturn this.stream;\n\t}\n\trejectResultPromises(error) {\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._finishReason,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._rawFinishReason,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._totalUsage,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._steps,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._initialResponseMessages,\n\t\t\terror\n\t\t});\n\t}\n\trejectResultPromise({ delayedPromise, error }) {\n\t\tif (delayedPromise.isPending()) {\n\t\t\tdelayedPromise.reject(error);\n\t\t\tmarkPromiseAsHandled$1(delayedPromise.promise);\n\t\t}\n\t}\n\tasync consumeStream(options) {\n\t\ttry {\n\t\t\tawait consumeStream({\n\t\t\t\tstream: this.stream,\n\t\t\t\tonError: (error) => {\n\t\t\t\t\tthis.rejectResultPromises(error);\n\t\t\t\t\toptions?.onError?.(error);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.rejectResultPromises(error);\n\t\t\toptions?.onError?.(error);\n\t\t}\n\t}\n\tget experimental_partialOutputStream() {\n\t\treturn this.partialOutputStream;\n\t}\n\tget partialOutputStream() {\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ partialOutput }, controller) {\n\t\t\tif (partialOutput !== void 0) controller.enqueue(partialOutput);\n\t\t} })));\n\t}\n\tget elementStream() {\n\t\tconst transform = this.outputSpecification?.createElementStreamTransform();\n\t\tif (transform == null) throw new UnsupportedFunctionalityError$1({ functionality: `element streams in ${this.outputSpecification?.name ?? \"text\"} mode` });\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(transform));\n\t}\n\tgetOutputPromise() {\n\t\tif (this.outputPromise == null) this.outputPromise = this.finalStep.then((step) => {\n\t\t\treturn (this.outputSpecification ?? text()).parseCompleteOutput({ text: step.text }, {\n\t\t\t\tresponse: step.response,\n\t\t\t\tusage: step.usage,\n\t\t\t\tfinishReason: step.finishReason\n\t\t\t});\n\t\t});\n\t\treturn this.outputPromise;\n\t}\n\tget output() {\n\t\treturn this.getOutputPromise();\n\t}\n\ttoUIMessageStream({ originalMessages, generateMessageId, onStepEnd, onStepFinish, onEnd, onFinish, messageMetadata, sendReasoning, sendSources, sendStart, sendFinish, onError } = {}) {\n\t\treturn createAsyncIterableStream(toUIMessageStream({\n\t\t\tstream: this.stream,\n\t\t\ttools: this.tools,\n\t\t\toriginalMessages,\n\t\t\tgenerateMessageId,\n\t\t\tonStepEnd: onStepEnd ?? onStepFinish,\n\t\t\tonEnd: onEnd ?? onFinish,\n\t\t\tmessageMetadata,\n\t\t\tsendReasoning,\n\t\t\tsendSources,\n\t\t\tsendStart,\n\t\t\tsendFinish,\n\t\t\tonError\n\t\t}));\n\t}\n\tpipeUIMessageStreamToResponse(response, { originalMessages, generateMessageId, onStepEnd, onStepFinish, onEnd, onFinish, messageMetadata, sendReasoning, sendSources, sendFinish, sendStart, onError, ...init } = {}) {\n\t\treturn pipeUIMessageStreamToResponse({\n\t\t\tresponse,\n\t\t\tstream: this.toUIMessageStream({\n\t\t\t\toriginalMessages,\n\t\t\t\tgenerateMessageId,\n\t\t\t\tonStepEnd: onStepEnd ?? onStepFinish,\n\t\t\t\tonEnd: onEnd ?? onFinish,\n\t\t\t\tmessageMetadata,\n\t\t\t\tsendReasoning,\n\t\t\t\tsendSources,\n\t\t\t\tsendFinish,\n\t\t\t\tsendStart,\n\t\t\t\tonError\n\t\t\t}),\n\t\t\t...init\n\t\t});\n\t}\n\tpipeTextStreamToResponse(response, init) {\n\t\treturn pipeTextStreamToResponse({\n\t\t\tresponse,\n\t\t\tstream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n\ttoUIMessageStreamResponse({ originalMessages, generateMessageId, onStepEnd, onStepFinish, onEnd, onFinish, messageMetadata, sendReasoning, sendSources, sendFinish, sendStart, onError, ...init } = {}) {\n\t\treturn createUIMessageStreamResponse({\n\t\t\tstream: this.toUIMessageStream({\n\t\t\t\toriginalMessages,\n\t\t\t\tgenerateMessageId,\n\t\t\t\tonStepEnd: onStepEnd ?? onStepFinish,\n\t\t\t\tonEnd: onEnd ?? onFinish,\n\t\t\t\tmessageMetadata,\n\t\t\t\tsendReasoning,\n\t\t\t\tsendSources,\n\t\t\t\tsendFinish,\n\t\t\t\tsendStart,\n\t\t\t\tonError\n\t\t\t}),\n\t\t\t...init\n\t\t});\n\t}\n\ttoTextStreamResponse(init) {\n\t\treturn createTextStreamResponse({\n\t\t\tstream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n};\n//#endregion\n//#region src/agent/default-stop-condition.ts\n/**\n* Stop conditions are only evaluated when the tool loop can otherwise continue,\n* so logging here avoids warning when a call finishes naturally at the limit.\n*/\nfunction createDefaultStopCondition(stepCount) {\n\treturn ({ steps }) => {\n\t\tif (steps.length !== stepCount) return false;\n\t\tconst { provider, modelId } = steps[steps.length - 1].model;\n\t\tlogWarnings({\n\t\t\tprovider,\n\t\t\tmodel: modelId,\n\t\t\twarnings: [{\n\t\t\t\ttype: \"other\",\n\t\t\t\tmessage: `The tool loop stopped because it reached the default stopWhen condition, isStepCount(${stepCount}). To allow more steps, set stopWhen to isStepCount(...) with a higher limit or provide a custom stop condition. Learn more: https://ai-sdk.dev/docs/agents/loop-control`\n\t\t\t}]\n\t\t});\n\t\treturn true;\n\t};\n}\n//#endregion\n//#region src/agent/tool-loop-agent.ts\n/**\n* A tool loop agent is an agent that runs tools in a loop. In each step,\n* it calls the LLM, and if there are tool calls, it executes the tools\n* and calls the LLM again in a new step with the tool results.\n*\n* The loop continues until:\n* - A finish reasoning other than tool-calls is returned, or\n* - A tool that is invoked does not have an execute function, or\n* - A tool call needs approval via `toolApproval` or tool-level `needsApproval`, or\n* - A stop condition is met (default stop condition is isStepCount(20))\n*/\nvar ToolLoopAgent = class {\n\tconstructor(settings) {\n\t\tthis.version = \"agent-v1\";\n\t\tconst { onFinish, onEnd = onFinish } = settings;\n\t\tthis.settings = {\n\t\t\t...settings,\n\t\t\tonEnd\n\t\t};\n\t}\n\t/**\n\t* The id of the agent.\n\t*/\n\tget id() {\n\t\treturn this.settings.id;\n\t}\n\t/**\n\t* The tools that the agent can use.\n\t*/\n\tget tools() {\n\t\treturn this.settings.tools;\n\t}\n\tasync prepareCall(options) {\n\t\tif (this.settings.callOptionsSchema != null && options.options !== void 0) {\n\t\t\tconst validatedOptions = await validateTypes({\n\t\t\t\tvalue: options.options,\n\t\t\t\tschema: this.settings.callOptionsSchema,\n\t\t\t\tcontext: { field: \"options\" }\n\t\t\t});\n\t\t\toptions = {\n\t\t\t\t...options,\n\t\t\t\toptions: validatedOptions\n\t\t\t};\n\t\t}\n\t\tconst { onStart: _settingsStableOnStart, experimental_onStart: _settingsExperimentalOnStart, onStepStart: _settingsStableOnStepStart, experimental_onStepStart: _settingsExperimentalOnStepStart, onToolExecutionStart: _settingsOnToolExecutionStart, onToolExecutionEnd: _settingsOnToolExecutionEnd, onStepEnd: _settingsOnStepEnd, onStepFinish: _settingsOnStepFinish, onFinish: _settingsOnFinish, onEnd: _settingsOnEnd, ...settingsWithoutCallbacks } = this.settings;\n\t\tconst baseCallArgs = {\n\t\t\t...settingsWithoutCallbacks,\n\t\t\tstopWhen: this.settings.stopWhen ?? createDefaultStopCondition(20),\n\t\t\t...options\n\t\t};\n\t\tconst { instructions, allowSystemInMessages, messages, prompt, runtimeContext, ...callArgs } = await this.settings.prepareCall?.(baseCallArgs) ?? baseCallArgs;\n\t\tconst promptArgs = {\n\t\t\tinstructions,\n\t\t\tallowSystemInMessages,\n\t\t\tmessages,\n\t\t\tprompt\n\t\t};\n\t\tif (runtimeContext === void 0) return {\n\t\t\t...callArgs,\n\t\t\t...promptArgs\n\t\t};\n\t\treturn {\n\t\t\t...callArgs,\n\t\t\truntimeContext,\n\t\t\t...promptArgs\n\t\t};\n\t}\n\t/**\n\t* Tags outgoing requests so usage can be attributed to ToolLoopAgent. Chains\n\t* with the `ai/<version>` and `ai-sdk/<provider>/<version>` suffixes added\n\t* downstream by generateText/streamText and the provider.\n\t*/\n\tagentHeaders(preparedCall) {\n\t\treturn withUserAgentSuffix(preparedCall.headers ?? {}, \"ai-sdk-agent/tool-loop\");\n\t}\n\t/**\n\t* Generates an output from the agent (non-streaming).\n\t*/\n\tasync generate({ abortSignal, timeout, experimental_sandbox: sandbox, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onToolExecutionStart, onToolExecutionEnd, onStepEnd, onStepFinish, onFinish, onEnd = onFinish, ...options }) {\n\t\tconst generate = generateText;\n\t\tconst preparedCall = await this.prepareCall({\n\t\t\t...options,\n\t\t\texperimental_sandbox: sandbox\n\t\t});\n\t\tconst callbackArgs = {\n\t\t\tabortSignal,\n\t\t\ttimeout: timeout ?? preparedCall.timeout,\n\t\t\texperimental_sandbox: sandbox,\n\t\t\tonStart: mergeCallbacks(this.settings.onStart ?? this.settings.experimental_onStart, onStart ?? experimental_onStart),\n\t\t\tonStepStart: mergeCallbacks(this.settings.onStepStart ?? this.settings.experimental_onStepStart, onStepStart ?? experimental_onStepStart),\n\t\t\tonToolExecutionStart: mergeCallbacks(this.settings.onToolExecutionStart, onToolExecutionStart),\n\t\t\tonToolExecutionEnd: mergeCallbacks(this.settings.onToolExecutionEnd, onToolExecutionEnd),\n\t\t\tonStepEnd: mergeCallbacks(this.settings.onStepEnd ?? this.settings.onStepFinish, onStepEnd ?? onStepFinish),\n\t\t\tonEnd: mergeCallbacks(this.settings.onEnd, onEnd)\n\t\t};\n\t\treturn await generate({\n\t\t\t...preparedCall,\n\t\t\t...callbackArgs,\n\t\t\theaders: this.agentHeaders(preparedCall)\n\t\t});\n\t}\n\t/**\n\t* Streams an output from the agent (streaming).\n\t*/\n\tasync stream({ abortSignal, timeout, experimental_sandbox: sandbox, experimental_transform, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onToolExecutionStart, onToolExecutionEnd, onStepEnd, onStepFinish, onFinish, onEnd = onFinish, ...options }) {\n\t\tconst stream = streamText;\n\t\tconst preparedCall = await this.prepareCall({\n\t\t\t...options,\n\t\t\texperimental_sandbox: sandbox\n\t\t});\n\t\tconst callbackArgs = {\n\t\t\tabortSignal,\n\t\t\ttimeout: timeout ?? preparedCall.timeout,\n\t\t\texperimental_sandbox: sandbox,\n\t\t\texperimental_transform,\n\t\t\tonStart: mergeCallbacks(this.settings.onStart ?? this.settings.experimental_onStart, onStart ?? experimental_onStart),\n\t\t\tonStepStart: mergeCallbacks(this.settings.onStepStart ?? this.settings.experimental_onStepStart, onStepStart ?? experimental_onStepStart),\n\t\t\tonToolExecutionStart: mergeCallbacks(this.settings.onToolExecutionStart, onToolExecutionStart),\n\t\t\tonToolExecutionEnd: mergeCallbacks(this.settings.onToolExecutionEnd, onToolExecutionEnd),\n\t\t\tonStepEnd: mergeCallbacks(this.settings.onStepEnd ?? this.settings.onStepFinish, onStepEnd ?? onStepFinish),\n\t\t\tonEnd: mergeCallbacks(this.settings.onEnd, onEnd)\n\t\t};\n\t\treturn await stream({\n\t\t\t...preparedCall,\n\t\t\t...callbackArgs,\n\t\t\theaders: this.agentHeaders(preparedCall)\n\t\t});\n\t}\n};\n//#endregion\n//#region src/ui-message-stream/create-ui-message-stream.ts\n/**\n* Creates a UI message stream that can be used to send messages to the client.\n*\n* @param options.execute - A function that is called with a writer to write UI message chunks to the stream.\n* @param options.onError - A function that extracts an error message from an error. Defaults to `() => 'An error occurred.'` so server-side error details are not leaked to the client; supply your own to surface richer messages.\n* @param options.originalMessages - The original messages. If provided, persistence mode is assumed\n* and a message ID is provided for the response message.\n* @param options.onStepEnd - A callback that is called when each step ends. Useful for persisting intermediate messages.\n* @param options.onStepFinish - Deprecated alias for `onStepEnd`.\n* @param options.onEnd - A callback that is called when the stream ends.\n* @param options.onFinish - Deprecated alias for `onEnd`.\n* @param options.generateId - A function that generates a unique ID. Defaults to the built-in ID generator.\n*\n* @returns A `ReadableStream` of UI message chunks.\n*/\nfunction createUIMessageStream({ execute, onError = () => \"An error occurred.\", originalMessages, onStepEnd, onStepFinish, onEnd, onFinish, generateId = generateId$1 }) {\n\tlet controller;\n\tconst ongoingStreamPromises = [];\n\tconst activeReaders = /* @__PURE__ */ new Set();\n\tlet isCancelled = false;\n\tlet cancelReason;\n\tlet outcome = { status: \"unknown\" };\n\tconst stream = new ReadableStream({\n\t\tstart(controllerArg) {\n\t\t\tcontroller = controllerArg;\n\t\t},\n\t\tasync cancel(reason) {\n\t\t\tisCancelled = true;\n\t\t\tcancelReason = reason;\n\t\t\tawait Promise.all(Array.from(activeReaders, (reader) => reader.cancel(reason)));\n\t\t}\n\t});\n\tfunction safeEnqueue(data) {\n\t\ttry {\n\t\t\tcontroller.enqueue(data);\n\t\t} catch {}\n\t}\n\tfunction setOutcome(newOutcome) {\n\t\tif (outcome.status === \"unknown\" && newOutcome.status !== \"unknown\") outcome = newOutcome;\n\t}\n\tfunction failOutcome(error) {\n\t\toutcome = {\n\t\t\tstatus: \"failed\",\n\t\t\terror\n\t\t};\n\t}\n\tfunction safeError(error) {\n\t\ttry {\n\t\t\tcontroller.error(error);\n\t\t} catch {}\n\t}\n\tfunction handleError(error) {\n\t\tfailOutcome(error);\n\t\tlet errorText;\n\t\ttry {\n\t\t\terrorText = onError(error);\n\t\t} catch (onErrorError) {\n\t\t\tfailOutcome(onErrorError);\n\t\t\tsafeError(onErrorError);\n\t\t\treturn;\n\t\t}\n\t\tsafeEnqueue({\n\t\t\ttype: \"error\",\n\t\t\terrorText\n\t\t});\n\t}\n\ttry {\n\t\tconst result = execute({ writer: {\n\t\t\twrite(part) {\n\t\t\t\tsafeEnqueue(part);\n\t\t\t},\n\t\t\tmerge(streamArg) {\n\t\t\t\tif (isCancelled) {\n\t\t\t\t\tstreamArg.cancel(cancelReason).catch(() => {});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tongoingStreamPromises.push((async () => {\n\t\t\t\t\tconst reader = streamArg.getReader();\n\t\t\t\t\tactiveReaders.add(reader);\n\t\t\t\t\ttry {\n\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\t\t\tif (done) break;\n\t\t\t\t\t\t\tsafeEnqueue(value);\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tactiveReaders.delete(reader);\n\t\t\t\t\t\treader.releaseLock();\n\t\t\t\t\t}\n\t\t\t\t})().catch((error) => {\n\t\t\t\t\thandleError(error);\n\t\t\t\t}));\n\t\t\t},\n\t\t\tsetOutcome,\n\t\t\tonError\n\t\t} });\n\t\tif (result) ongoingStreamPromises.push(result.catch((error) => {\n\t\t\thandleError(error);\n\t\t}));\n\t} catch (error) {\n\t\thandleError(error);\n\t}\n\t(async () => {\n\t\twhile (ongoingStreamPromises.length > 0) await ongoingStreamPromises.shift();\n\t})().finally(() => {\n\t\ttry {\n\t\t\tcontroller.close();\n\t\t} catch {}\n\t});\n\treturn handleUIMessageStreamFinish({\n\t\tstream,\n\t\tmessageId: generateId(),\n\t\toriginalMessages,\n\t\tonStepEnd: onStepEnd ?? onStepFinish,\n\t\tonEnd: onEnd ?? onFinish,\n\t\tonError,\n\t\tgetOutcome: () => outcome\n\t});\n}\n//#endregion\n//#region src/ui-message-stream/read-ui-message-stream.ts\nfunction createUIMessageSnapshot(message) {\n\tconst textByPartIndex = /* @__PURE__ */ new Map();\n\tconst messageWithoutText = {\n\t\t...message,\n\t\tparts: message.parts.map((part, index) => {\n\t\t\tif (part.type === \"text\" || part.type === \"reasoning\") {\n\t\t\t\ttextByPartIndex.set(index, part.text);\n\t\t\t\treturn {\n\t\t\t\t\t...part,\n\t\t\t\t\ttext: \"\"\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn part;\n\t\t})\n\t};\n\tconst snapshot = structuredClone(messageWithoutText);\n\tfor (const [index, text] of textByPartIndex) {\n\t\tconst part = snapshot.parts[index];\n\t\tif (part.type === \"text\" || part.type === \"reasoning\") part.text = text;\n\t}\n\treturn snapshot;\n}\n/**\n* Transforms a stream of `UIMessageChunk`s into an `AsyncIterableStream` of `UIMessage`s.\n*\n* @param options.message - The last assistant message to use as a starting point when the conversation is resumed. Otherwise undefined.\n* @param options.stream - The stream of `UIMessageChunk`s to read.\n* @param options.terminateOnError - Whether to terminate the stream if an error occurs.\n* @param options.onError - A function that is called when an error occurs.\n*\n* @returns An `AsyncIterableStream` of `UIMessage`s. Each stream part is a different state of the same message\n* as it is being completed.\n*/\nfunction readUIMessageStream({ message, stream, onError, terminateOnError = false }) {\n\tlet controller;\n\tlet hasErrored = false;\n\tlet isCancelled = false;\n\tconst abortController = new AbortController();\n\tconst outputStream = new ReadableStream({\n\t\tstart(controllerParam) {\n\t\t\tcontroller = controllerParam;\n\t\t},\n\t\tcancel() {\n\t\t\tisCancelled = true;\n\t\t\tabortController.abort();\n\t\t}\n\t});\n\tconst state = createStreamingUIMessageState({\n\t\tmessageId: message?.id ?? \"\",\n\t\tlastMessage: message\n\t});\n\tconst handleError = (error) => {\n\t\tonError?.(error);\n\t\tif (!hasErrored && terminateOnError) {\n\t\t\thasErrored = true;\n\t\t\tcontroller?.error(error);\n\t\t}\n\t};\n\tconsumeStream({\n\t\tstream: processUIMessageStream({\n\t\t\tstream,\n\t\t\tresetStateOnMessageIdChange: true,\n\t\t\trunUpdateMessageJob(job) {\n\t\t\t\treturn job({\n\t\t\t\t\tstate,\n\t\t\t\t\twrite: () => {\n\t\t\t\t\t\tif (!isCancelled) controller?.enqueue(createUIMessageSnapshot(state.message));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\tonError: handleError\n\t\t}),\n\t\tonError: handleError,\n\t\tabortSignal: abortController.signal\n\t}).finally(() => {\n\t\tif (!hasErrored && !isCancelled) controller?.close();\n\t});\n\treturn createAsyncIterableStream(outputStream);\n}\n//#endregion\n//#region src/ui/unavailable-tool.ts\nfunction markToolPartAsUnavailable(part) {\n\tpart.dynamic = false;\n\treturn part;\n}\nfunction isToolPartFromUnavailableTool(part) {\n\treturn part.type === \"dynamic-tool\" && part.dynamic === false;\n}\n//#endregion\n//#region src/ui/warn-if-ui-message-has-deprecated-raw-input.ts\nconst rawInputDeprecationWarning = {\n\ttype: \"deprecated\",\n\tsetting: \"rawInput in output-error UI message parts\",\n\tmessage: \"Use the \\\"input\\\" field instead. The \\\"rawInput\\\" field will be removed in the next major version.\"\n};\nfunction warnIfUIMessageHasDeprecatedRawInput(messages) {\n\tif (messages.some((message) => message.parts.some((part) => part != null && typeof part === \"object\" && \"type\" in part && typeof part.type === \"string\" && (part.type === \"dynamic-tool\" || part.type.startsWith(\"tool-\")) && \"state\" in part && part.state === \"output-error\" && Object.prototype.hasOwnProperty.call(part, \"rawInput\") && \"rawInput\" in part && part.rawInput !== void 0))) logWarnings({ warnings: [rawInputDeprecationWarning] });\n}\n//#endregion\n//#region src/ui/convert-to-model-messages.ts\n/**\n* Converts an array of UI messages from useChat into an array of ModelMessages that can be used\n* with the AI functions (e.g. `streamText`, `generateText`).\n*\n* @param messages - The UI messages to convert.\n* @param options.tools - The tools to use.\n* @param options.ignoreIncompleteToolCalls - Whether to ignore incomplete tool calls. Default is `false`.\n* @param options.convertDataPart - Optional function to convert data parts to text or file model message parts. Returns `undefined` if the part should be ignored.\n*\n* @returns An array of ModelMessages.\n*/\nasync function convertToModelMessages(messages, options) {\n\tconst modelMessages = [];\n\twarnIfUIMessageHasDeprecatedRawInput(messages);\n\tconst lastUserMessageIndex = messages.reduce((lastIndex, message, index) => message.role === \"user\" ? index : lastIndex, -1);\n\tif (options?.ignoreIncompleteToolCalls || lastUserMessageIndex > 0) messages = messages.map((message, messageIndex) => ({\n\t\t...message,\n\t\tparts: message.parts.filter((part) => !isToolUIPart(part) || (part.state !== \"approval-requested\" || messageIndex >= lastUserMessageIndex) && (!options?.ignoreIncompleteToolCalls || part.state === \"approval-responded\" || part.state === \"output-available\" && part.preliminary !== true || part.state === \"output-error\" || part.state === \"output-denied\"))\n\t}));\n\tasync function createModelOutput({ toolPart, toolName, output, errorMode }) {\n\t\tconst tool = getOwn(options?.tools, toolName);\n\t\tif (errorMode === \"none\" && tool == null && isToolPartFromUnavailableTool(toolPart)) return {\n\t\t\ttype: \"text\",\n\t\t\tvalue: \"Tool output omitted because the tool is no longer available.\"\n\t\t};\n\t\treturn createToolModelOutput({\n\t\t\ttoolCallId: toolPart.toolCallId,\n\t\t\tinput: toolPart.input,\n\t\t\toutput,\n\t\t\ttool,\n\t\t\terrorMode\n\t\t});\n\t}\n\tfor (const message of messages) switch (message.role) {\n\t\tcase \"system\": {\n\t\t\tconst textParts = message.parts.filter((part) => part.type === \"text\");\n\t\t\tconst providerMetadata = textParts.reduce((acc, part) => {\n\t\t\t\tif (part.providerMetadata != null) return {\n\t\t\t\t\t...acc,\n\t\t\t\t\t...part.providerMetadata\n\t\t\t\t};\n\t\t\t\treturn acc;\n\t\t\t}, {});\n\t\t\tmodelMessages.push({\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: textParts.map((part) => part.text).join(\"\"),\n\t\t\t\t...Object.keys(providerMetadata).length > 0 ? { providerOptions: providerMetadata } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"user\":\n\t\t\tmodelMessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: message.parts.map((part) => {\n\t\t\t\t\tif (isTextUIPart(part)) return {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t};\n\t\t\t\t\tif (isFileUIPart(part)) return {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\tdata: part.providerReference != null ? {\n\t\t\t\t\t\t\ttype: \"reference\",\n\t\t\t\t\t\t\treference: part.providerReference\n\t\t\t\t\t\t} : {\n\t\t\t\t\t\t\ttype: \"url\",\n\t\t\t\t\t\t\turl: new URL(part.url)\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t};\n\t\t\t\t\tif (isDataUIPart(part)) return options?.convertDataPart?.(part);\n\t\t\t\t}).filter(isNonNullable)\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"assistant\":\n\t\t\tif (message.parts != null) {\n\t\t\t\tlet block = [];\n\t\t\t\tasync function processBlock() {\n\t\t\t\t\tif (block.length === 0) return;\n\t\t\t\t\tconst content = [];\n\t\t\t\t\tfor (const part of block) if (isTextUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\telse if (isCustomContentUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"custom\",\n\t\t\t\t\t\tkind: part.kind,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\telse if (isFileUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\tdata: part.providerReference != null ? {\n\t\t\t\t\t\t\ttype: \"reference\",\n\t\t\t\t\t\t\treference: part.providerReference\n\t\t\t\t\t\t} : {\n\t\t\t\t\t\t\ttype: \"url\",\n\t\t\t\t\t\t\turl: new URL(part.url)\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\telse if (isReasoningFileUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"reasoning-file\",\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\ttype: \"url\",\n\t\t\t\t\t\t\turl: new URL(part.url)\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse if (isReasoningUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse if (isToolUIPart(part)) {\n\t\t\t\t\t\tconst toolName = getToolName(part);\n\t\t\t\t\t\tif (part.state !== \"input-streaming\") {\n\t\t\t\t\t\t\tconst callProviderMetadata = part.callProviderMetadata ?? (part.state === \"output-error\" ? part.resultProviderMetadata : void 0);\n\t\t\t\t\t\t\tcontent.push({\n\t\t\t\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\tinput: part.state === \"output-error\" ? part.input ?? (\"rawInput\" in part ? part.rawInput : void 0) : part.input,\n\t\t\t\t\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\t\t\t\t\t...callProviderMetadata != null ? { providerOptions: callProviderMetadata } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (part.approval != null) content.push({\n\t\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\t\tapprovalId: part.approval.id,\n\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\tisAutomatic: part.approval.isAutomatic,\n\t\t\t\t\t\t\t\t...part.approval.requestReason != null ? { reason: part.approval.requestReason } : {},\n\t\t\t\t\t\t\t\t...Object.prototype.hasOwnProperty.call(part.approval, \"inputSchemaInput\") ? { inputSchemaInput: part.approval.inputSchemaInput } : {},\n\t\t\t\t\t\t\t\t...part.approval.signature != null ? { signature: part.approval.signature } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (part.providerExecuted === true && part.state !== \"approval-responded\" && (part.state === \"output-available\" || part.state === \"output-error\")) {\n\t\t\t\t\t\t\t\tconst resultProviderMetadata = part.resultProviderMetadata ?? part.callProviderMetadata;\n\t\t\t\t\t\t\t\tcontent.push({\n\t\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\toutput: await createModelOutput({\n\t\t\t\t\t\t\t\t\t\ttoolPart: part,\n\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\toutput: part.state === \"output-error\" ? part.errorText : part.output,\n\t\t\t\t\t\t\t\t\t\terrorMode: part.state === \"output-error\" ? \"json\" : \"none\"\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t...resultProviderMetadata != null ? { providerOptions: resultProviderMetadata } : {}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (isDataUIPart(part)) {\n\t\t\t\t\t\tconst dataPart = options?.convertDataPart?.(part);\n\t\t\t\t\t\tif (dataPart != null) content.push(dataPart);\n\t\t\t\t\t} else throw new Error(`Unsupported part: ${part}`);\n\t\t\t\t\tif (content.length > 0) modelMessages.push({\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent\n\t\t\t\t\t});\n\t\t\t\t\tconst toolParts = block.filter((part) => isToolUIPart(part) && (part.providerExecuted !== true || part.approval?.approved != null));\n\t\t\t\t\tif (toolParts.length > 0) {\n\t\t\t\t\t\tconst content = [];\n\t\t\t\t\t\tfor (const toolPart of toolParts) {\n\t\t\t\t\t\t\tif (toolPart.approval?.approved != null) content.push({\n\t\t\t\t\t\t\t\ttype: \"tool-approval-response\",\n\t\t\t\t\t\t\t\tapprovalId: toolPart.approval.id,\n\t\t\t\t\t\t\t\tapproved: toolPart.approval.approved,\n\t\t\t\t\t\t\t\treason: toolPart.approval.reason,\n\t\t\t\t\t\t\t\tproviderExecuted: toolPart.providerExecuted\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (toolPart.state === \"approval-responded\" && toolPart.approval?.approved === false) content.push({\n\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\ttoolCallId: toolPart.toolCallId,\n\t\t\t\t\t\t\t\ttoolName: getToolName(toolPart),\n\t\t\t\t\t\t\t\toutput: {\n\t\t\t\t\t\t\t\t\ttype: \"execution-denied\",\n\t\t\t\t\t\t\t\t\treason: toolPart.approval.reason\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (toolPart.providerExecuted === true) continue;\n\t\t\t\t\t\t\tswitch (toolPart.state) {\n\t\t\t\t\t\t\t\tcase \"output-denied\":\n\t\t\t\t\t\t\t\t\tcontent.push({\n\t\t\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\t\t\ttoolCallId: toolPart.toolCallId,\n\t\t\t\t\t\t\t\t\t\ttoolName: getToolName(toolPart),\n\t\t\t\t\t\t\t\t\t\toutput: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"error-text\",\n\t\t\t\t\t\t\t\t\t\t\tvalue: toolPart.approval?.reason ?? \"Tool call execution denied.\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"output-error\":\n\t\t\t\t\t\t\t\tcase \"output-available\": {\n\t\t\t\t\t\t\t\t\tconst toolName = getToolName(toolPart);\n\t\t\t\t\t\t\t\t\tcontent.push({\n\t\t\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\t\t\ttoolCallId: toolPart.toolCallId,\n\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\toutput: await createModelOutput({\n\t\t\t\t\t\t\t\t\t\t\ttoolPart,\n\t\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\t\toutput: toolPart.state === \"output-error\" ? toolPart.errorText : toolPart.output,\n\t\t\t\t\t\t\t\t\t\t\terrorMode: toolPart.state === \"output-error\" ? \"text\" : \"none\"\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (content.length > 0) modelMessages.push({\n\t\t\t\t\t\t\trole: \"tool\",\n\t\t\t\t\t\t\tcontent\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tblock = [];\n\t\t\t\t}\n\t\t\t\tfor (const part of message.parts) if (isCustomContentUIPart(part) || isTextUIPart(part) || isReasoningUIPart(part) || isReasoningFileUIPart(part) || isFileUIPart(part) || isToolUIPart(part) || isDataUIPart(part)) block.push(part);\n\t\t\t\telse if (part.type === \"step-start\") await processBlock();\n\t\t\t\tawait processBlock();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck = message.role;\n\t\t\tthrow new MessageConversionError({\n\t\t\t\toriginalMessage: message,\n\t\t\t\tmessage: `Unsupported role: ${_exhaustiveCheck}`\n\t\t\t});\n\t\t}\n\t}\n\treturn modelMessages;\n}\n//#endregion\n//#region src/ui/validate-ui-messages.ts\nconst toolMetadataSchema = z.record(z.string(), jsonValueSchema.optional());\nconst providerReferenceSchema = z.record(z.string(), z.string());\nfunction isEmptyObject(value) {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value) && Object.keys(value).length === 0;\n}\nfunction asDynamicToolPart(toolPart) {\n\tconst { type, ...part } = toolPart;\n\treturn markToolPartAsUnavailable({\n\t\t...part,\n\t\ttype: \"dynamic-tool\",\n\t\ttoolName: type.slice(5)\n\t});\n}\nfunction getToolPartInputSchemaInput(toolPart) {\n\treturn toolPart.approval != null && Object.prototype.hasOwnProperty.call(toolPart.approval, \"inputSchemaInput\") ? { value: toolPart.approval.inputSchemaInput } : void 0;\n}\nconst uiMessagesSchema = lazySchema(() => {\n\tconst approvalRequestedSchema = z.object({\n\t\tid: z.string(),\n\t\tapproved: z.never().optional(),\n\t\tdescriptor: z.unknown().optional(),\n\t\trequestReason: z.string().optional(),\n\t\treason: z.never().optional(),\n\t\tisAutomatic: z.boolean().optional(),\n\t\tsignature: z.string().optional(),\n\t\tinputSchemaInput: z.unknown().optional()\n\t});\n\tconst approvalRespondedSchema = approvalRequestedSchema.extend({\n\t\tapproved: z.boolean(),\n\t\treason: z.string().optional()\n\t});\n\tconst approvalGrantedSchema = approvalRespondedSchema.extend({ approved: z.literal(true) });\n\tconst approvalDeniedSchema = approvalRespondedSchema.extend({ approved: z.literal(false) });\n\treturn zodSchema$1(z.array(z.object({\n\t\tid: z.string(),\n\t\trole: z.enum([\n\t\t\t\"system\",\n\t\t\t\"user\",\n\t\t\t\"assistant\"\n\t\t]),\n\t\tmetadata: z.unknown().optional(),\n\t\tparts: z.array(z.union([\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"text\"),\n\t\t\t\ttext: z.string(),\n\t\t\t\tstate: z.enum([\"streaming\", \"done\"]).optional(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"reasoning\"),\n\t\t\t\tid: z.string().optional(),\n\t\t\t\ttext: z.string(),\n\t\t\t\tstate: z.enum([\"streaming\", \"done\"]).optional(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"custom\"),\n\t\t\t\tkind: z.string(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"source-url\"),\n\t\t\t\tsourceId: z.string(),\n\t\t\t\turl: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"source-document\"),\n\t\t\t\tsourceId: z.string(),\n\t\t\t\tmediaType: z.string(),\n\t\t\t\ttitle: z.string(),\n\t\t\t\tfilename: z.string().optional(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"file\"),\n\t\t\t\tmediaType: z.string(),\n\t\t\t\tfilename: z.string().optional(),\n\t\t\t\turl: z.string(),\n\t\t\t\tproviderReference: providerReferenceSchema.optional(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"reasoning-file\"),\n\t\t\t\tmediaType: z.string(),\n\t\t\t\turl: z.string(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({ type: z.literal(\"step-start\") }),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"data-\"),\n\t\t\t\tid: z.string().optional(),\n\t\t\t\tdata: z.unknown()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"input-streaming\"),\n\t\t\t\tinput: z.unknown().optional(),\n\t\t\t\trawInput: z.string().optional(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tapproval: z.never().optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"input-available\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: z.never().optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"approval-requested\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalRequestedSchema\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"approval-responded\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalRespondedSchema\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"output-available\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.unknown(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tpreliminary: z.boolean().optional(),\n\t\t\t\tapproval: approvalGrantedSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"output-error\"),\n\t\t\t\tinput: z.unknown().optional(),\n\t\t\t\trawInput: z.unknown().optional(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.string(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalGrantedSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"output-denied\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalDeniedSchema\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"input-streaming\"),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tinput: z.unknown().optional(),\n\t\t\t\trawInput: z.string().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tapproval: z.never().optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"input-available\"),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: z.never().optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"approval-requested\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalRequestedSchema\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"approval-responded\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalRespondedSchema\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"output-available\"),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\toutput: z.unknown(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tpreliminary: z.boolean().optional(),\n\t\t\t\tapproval: approvalGrantedSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"output-error\"),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tinput: z.unknown().optional(),\n\t\t\t\trawInput: z.unknown().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.string(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalGrantedSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\t\t\tstate: z.literal(\"output-denied\"),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalDeniedSchema\n\t\t\t})\n\t\t]))\n\t}).superRefine((message, context) => {\n\t\tif (message.role !== \"assistant\" && message.parts.length === 0) context.addIssue({\n\t\t\torigin: \"array\",\n\t\t\tcode: \"too_small\",\n\t\t\tminimum: 1,\n\t\t\tinclusive: true,\n\t\t\tinput: message.parts,\n\t\t\tpath: [\"parts\"],\n\t\t\tmessage: \"Message must contain at least one part\"\n\t\t});\n\t})).nonempty(\"Messages array must not be empty\"));\n});\nasync function safeValidateUIMessagesInternal({ messages, metadataSchema, dataSchemas, tools, experimental_refineToolInput }, { convertMissingTerminalToolsToDynamic }) {\n\ttry {\n\t\tif (messages == null) return {\n\t\t\tsuccess: false,\n\t\t\terror: new InvalidArgumentError({\n\t\t\t\tparameter: \"messages\",\n\t\t\t\tvalue: messages,\n\t\t\t\tmessage: \"messages parameter must be provided\"\n\t\t\t})\n\t\t};\n\t\tconst validatedMessages = await validateTypes({\n\t\t\tvalue: messages,\n\t\t\tschema: uiMessagesSchema\n\t\t});\n\t\twarnIfUIMessageHasDeprecatedRawInput(validatedMessages);\n\t\tif (metadataSchema) for (const [msgIdx, message] of validatedMessages.entries()) message.metadata = await validateTypes({\n\t\t\tvalue: message.metadata,\n\t\t\tschema: metadataSchema,\n\t\t\tcontext: {\n\t\t\t\tfield: `messages[${msgIdx}].metadata`,\n\t\t\t\tentityId: message.id\n\t\t\t}\n\t\t});\n\t\tconst shouldValidateToolParts = tools != null || convertMissingTerminalToolsToDynamic;\n\t\tif (dataSchemas || shouldValidateToolParts) for (const [msgIdx, message] of validatedMessages.entries()) for (const [partIdx, part] of message.parts.entries()) {\n\t\t\tif (dataSchemas && part.type.startsWith(\"data-\")) {\n\t\t\t\tconst dataPart = part;\n\t\t\t\tconst dataName = dataPart.type.slice(5);\n\t\t\t\tconst dataSchema = dataSchemas[dataName];\n\t\t\t\tif (!dataSchema) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: new TypeValidationError$1({\n\t\t\t\t\t\tvalue: dataPart.data,\n\t\t\t\t\t\tcause: `No data schema found for data part ${dataName}`,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].data`,\n\t\t\t\t\t\t\tentityName: dataName,\n\t\t\t\t\t\t\tentityId: dataPart.id\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t\tdataPart.data = await validateTypes({\n\t\t\t\t\tvalue: dataPart.data,\n\t\t\t\t\tschema: dataSchema,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].data`,\n\t\t\t\t\t\tentityName: dataName,\n\t\t\t\t\t\tentityId: dataPart.id\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (shouldValidateToolParts && part.type.startsWith(\"tool-\")) {\n\t\t\t\tconst toolPart = part;\n\t\t\t\tconst toolName = toolPart.type.slice(5);\n\t\t\t\tconst tool = tools == null ? void 0 : getOwn(tools, toolName);\n\t\t\t\tconst isTerminal = toolPart.state === \"output-available\" || toolPart.state === \"output-error\" || toolPart.state === \"output-denied\";\n\t\t\t\tif (!tool && isTerminal) {\n\t\t\t\t\tif (tools != null || convertMissingTerminalToolsToDynamic) message.parts[partIdx] = asDynamicToolPart(toolPart);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!tool) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: new TypeValidationError$1({\n\t\t\t\t\t\tvalue: toolPart.input,\n\t\t\t\t\t\tcause: `No tool schema found for tool part ${toolName}`,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].input`,\n\t\t\t\t\t\t\tentityName: toolName,\n\t\t\t\t\t\t\tentityId: toolPart.toolCallId\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t\tconst inputValidationContext = {\n\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].input`,\n\t\t\t\t\tentityName: toolName,\n\t\t\t\t\tentityId: toolPart.toolCallId\n\t\t\t\t};\n\t\t\t\tconst inputSchemaInput = getToolPartInputSchemaInput(toolPart);\n\t\t\t\tconst inputToValidate = inputSchemaInput == null ? toolPart.input : inputSchemaInput.value;\n\t\t\t\tlet convertToDynamic = false;\n\t\t\t\tif (toolPart.state !== \"input-streaming\" && (toolPart.state !== \"output-error\" || inputSchemaInput != null || toolPart.input !== void 0)) {\n\t\t\t\t\tconst result = await safeValidateTypes({\n\t\t\t\t\t\tvalue: inputToValidate,\n\t\t\t\t\t\tschema: tool.inputSchema,\n\t\t\t\t\t\tcontext: inputValidationContext\n\t\t\t\t\t});\n\t\t\t\t\tlet inputError;\n\t\t\t\t\tif (!result.success) inputError = result.error;\n\t\t\t\t\telse if (inputSchemaInput != null) try {\n\t\t\t\t\t\tconst refine = getOwn(experimental_refineToolInput, toolName);\n\t\t\t\t\t\tif (!isDeepEqualData(refine == null ? result.value : await refine(result.value), toolPart.input)) inputError = new TypeValidationError$1({\n\t\t\t\t\t\t\tvalue: toolPart.input,\n\t\t\t\t\t\t\tcause: \"Tool input does not match the output reconstructed from inputSchemaInput.\",\n\t\t\t\t\t\t\tcontext: inputValidationContext\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tinputError = new TypeValidationError$1({\n\t\t\t\t\t\t\tvalue: inputToValidate,\n\t\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\t\tcontext: inputValidationContext\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (inputError != null) {\n\t\t\t\t\t\tif (toolPart.state === \"output-error\" || toolPart.state === \"output-available\" && isEmptyObject(toolPart.input)) convertToDynamic = true;\n\t\t\t\t\t\telse throw inputError;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (toolPart.state === \"output-available\" && tool.outputSchema) await validateTypes({\n\t\t\t\t\tvalue: toolPart.output,\n\t\t\t\t\tschema: tool.outputSchema,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].output`,\n\t\t\t\t\t\tentityName: toolName,\n\t\t\t\t\t\tentityId: toolPart.toolCallId\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (convertToDynamic) message.parts[partIdx] = asDynamicToolPart(toolPart);\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: validatedMessages\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror\n\t\t};\n\t}\n}\n/**\n* Validates a list of UI messages like `validateUIMessages`,\n* but instead of throwing it returns `{ success: true, data }`\n* or `{ success: false, error }`.\n*/\nasync function safeValidateUIMessages(options) {\n\treturn safeValidateUIMessagesInternal(options, { convertMissingTerminalToolsToDynamic: false });\n}\n/**\n* Validates a list of UI messages.\n*\n* Metadata, data parts, and generic tool call structures are only validated if\n* the corresponding schemas are provided. Otherwise, they are assumed to be\n* valid.\n*/\nasync function validateUIMessages(options) {\n\tconst response = await safeValidateUIMessages(options);\n\tif (!response.success) throw response.error;\n\treturn response.data;\n}\nasync function validateUIMessagesForAgent(options) {\n\tconst response = await safeValidateUIMessagesInternal(options, { convertMissingTerminalToolsToDynamic: true });\n\tif (!response.success) throw response.error;\n\treturn response.data;\n}\n//#endregion\n//#region src/agent/create-agent-ui-stream.ts\n/**\n* Runs the agent and stream the output as a UI message stream.\n*\n* @param agent - The agent to run.\n* @param uiMessages - The input UI messages.\n* @param convertDataPart - Optional function to convert custom data parts to text or file model message parts.\n* @param abortSignal - The abort signal. Optional.\n* @param timeout - Timeout in milliseconds. Optional.\n* @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional.\n* @param options - The options for the agent.\n* @param experimental_transform - The stream transformations. Optional.\n* @param onStepEnd - Callback that is called when each step ends. Optional.\n* @param onStepFinish - Deprecated alias for `onStepEnd`. Optional.\n* @param onUIMessageStepEnd - Callback with the accumulated UI message after each step. Optional.\n*\n* @returns The UI message stream.\n*/\nasync function createAgentUIStream({ agent, uiMessages, convertDataPart, options, abortSignal, timeout, experimental_sandbox: sandbox, experimental_transform, onStepEnd, onStepFinish, onUIMessageStepEnd, ...uiMessageStreamOptions }) {\n\tconst validatedMessages = await validateUIMessagesForAgent({\n\t\tmessages: uiMessages,\n\t\ttools: agent.tools\n\t});\n\tconst modelMessages = await convertToModelMessages(validatedMessages, {\n\t\ttools: agent.tools,\n\t\tconvertDataPart\n\t});\n\tconst result = await agent.stream({\n\t\tprompt: modelMessages,\n\t\toptions,\n\t\tabortSignal,\n\t\ttimeout,\n\t\texperimental_sandbox: sandbox,\n\t\texperimental_transform,\n\t\tonStepEnd: onStepEnd ?? onStepFinish\n\t});\n\tconst originalMessages = uiMessageStreamOptions.originalMessages ?? validatedMessages;\n\treturn createAsyncIterableStream(toUIMessageStream({\n\t\t...uiMessageStreamOptions,\n\t\toriginalMessages,\n\t\tonStepEnd: onUIMessageStepEnd,\n\t\tstream: result.stream,\n\t\ttools: agent.tools\n\t}));\n}\n//#endregion\n//#region src/agent/create-agent-ui-stream-response.ts\n/**\n* Runs the agent and returns a response object with a UI message stream.\n*\n* @param agent - The agent to run.\n* @param uiMessages - The input UI messages.\n* @param convertDataPart - Optional function to convert custom data parts to text or file model message parts.\n* @param abortSignal - Abort signal. Optional.\n* @param timeout - Timeout in milliseconds. Optional.\n* @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional.\n* @param options - The options for the agent. Optional.\n* @param experimental_transform - Stream transformations. Optional.\n* @param onStepEnd - Callback that is called when each step ends. Optional.\n* @param onStepFinish - Deprecated alias for `onStepEnd`. Optional.\n* @param onUIMessageStepEnd - Callback with the accumulated UI message after each step. Optional.\n* @param headers - Additional headers for the response. Optional.\n* @param status - The status code for the response. Optional.\n* @param statusText - The status text for the response. Optional.\n* @param keepAliveMs - Optional interval for sending SSE keep-alive comments.\n* @param consumeSseStream - Whether to consume the SSE stream. Optional.\n*\n* @returns The response object.\n*/\nasync function createAgentUIStreamResponse({ headers, status, statusText, keepAliveMs, consumeSseStream, ...options }) {\n\treturn createUIMessageStreamResponse({\n\t\theaders,\n\t\tstatus,\n\t\tstatusText,\n\t\tkeepAliveMs,\n\t\tconsumeSseStream,\n\t\tstream: await createAgentUIStream(options)\n\t});\n}\n//#endregion\n//#region src/agent/pipe-agent-ui-stream-to-response.ts\n/**\n* Pipes the agent UI message stream to a Node.js ServerResponse object.\n*\n* @param response - The Node.js ServerResponse object to pipe to.\n* @param agent - The agent to run.\n* @param uiMessages - The input UI messages.\n* @param convertDataPart - Optional function to convert custom data parts to text or file model message parts.\n* @param abortSignal - Abort signal. Optional.\n* @param timeout - Timeout in milliseconds. Optional.\n* @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional.\n* @param options - The options for the agent. Optional.\n* @param experimental_transform - Stream transformations. Optional.\n* @param onStepEnd - Callback that is called when each step ends. Optional.\n* @param onStepFinish - Deprecated alias for `onStepEnd`. Optional.\n* @param onUIMessageStepEnd - Callback with the accumulated UI message after each step. Optional.\n* @param headers - Additional headers for the response. Optional.\n* @param status - The status code for the response. Optional.\n* @param statusText - The status text for the response. Optional.\n* @param keepAliveMs - Optional interval for sending SSE keep-alive comments.\n* @param consumeSseStream - Whether to consume the SSE stream. Optional.\n*/\nasync function pipeAgentUIStreamToResponse({ response, headers, status, statusText, keepAliveMs, consumeSseStream, ...options }) {\n\treturn pipeUIMessageStreamToResponse({\n\t\tresponse,\n\t\theaders,\n\t\tstatus,\n\t\tstatusText,\n\t\tkeepAliveMs,\n\t\tconsumeSseStream,\n\t\tstream: await createAgentUIStream(options)\n\t});\n}\n//#endregion\n//#region src/util/set-own.ts\n/**\n* Writes an enumerable own property without invoking inherited setters such as\n* `Object.prototype.__proto__`. Keeps the target object's prototype unchanged.\n*/\nfunction setOwn(object, key, value) {\n\tObject.defineProperty(object, key, {\n\t\tvalue,\n\t\tenumerable: true,\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n}\n//#endregion\n//#region src/prompt/data-content.ts\n/**\n* Converts data content to a base64-encoded string.\n*\n* @param content - Data content to convert.\n* @returns Base64-encoded string.\n*/\nfunction convertDataContentToBase64String(content) {\n\tif (typeof content === \"string\") return content;\n\tif (content instanceof ArrayBuffer) return convertUint8ArrayToBase64(new Uint8Array(content));\n\treturn convertUint8ArrayToBase64(content);\n}\n/**\n* Converts data content to a Uint8Array.\n*\n* @param content - Data content to convert.\n* @returns Uint8Array.\n*/\nfunction convertDataContentToUint8Array(content) {\n\tif (content instanceof Uint8Array) return content;\n\tif (typeof content === \"string\") try {\n\t\treturn convertBase64ToUint8Array(content);\n\t} catch (error) {\n\t\tthrow new InvalidDataContentError({\n\t\t\tmessage: \"Invalid data content. Content string is not a base64-encoded media.\",\n\t\t\tcontent,\n\t\t\tcause: error\n\t\t});\n\t}\n\tif (content instanceof ArrayBuffer) return new Uint8Array(content);\n\tthrow new InvalidDataContentError({ content });\n}\n//#endregion\n//#region src/generate-image/generate-image.ts\nconst gatewayCostMetadataKeys = [\n\t\"cost\",\n\t\"gatewayCost\",\n\t\"inferenceCost\",\n\t\"inputInferenceCost\",\n\t\"marketCost\",\n\t\"outputInferenceCost\",\n\t\"surchargeCost\"\n];\nvar RetryableNoImageResultError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"No image generated.\");\n\t\tthis.name = \"RetryableNoImageResultError\";\n\t}\n};\n/**\n* Generates images using an image model.\n*\n* @param model - The image model to use.\n* @param prompt - The prompt that should be used to generate the image.\n* @param n - Number of images to generate. Default: 1.\n* @param maxImagesPerCall - Maximum number of images to generate in a single API call.\n* @param size - Size of the images to generate. Must have the format `{width}x{height}`.\n* @param aspectRatio - Aspect ratio of the images to generate. Must have the format `{width}:{height}`.\n* @param seed - Seed for the image generation.\n* @param providerOptions - Additional provider-specific options that are passed through to the provider\n* as body parameters.\n* @param maxRetries - Maximum number of retries per image model call, including retries after unclassified empty responses. Empty responses marked as not retryable by the provider are not retried. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n*\n* @returns A result object that contains the generated images.\n*/\nasync function generateImage({ model: modelArg, prompt: promptArg, n = 1, maxImagesPerCall, size, aspectRatio, seed, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers }) {\n\tconst model = resolveImageModel(modelArg);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal,\n\t\tadditionalRetryableError: (error) => error instanceof RetryableNoImageResultError\n\t});\n\tconst maxImagesPerCallWithDefault = maxImagesPerCall ?? await invokeModelMaxImagesPerCall(model) ?? 1;\n\tconst callCount = Math.ceil(n / maxImagesPerCallWithDefault);\n\tconst callImageCounts = Array.from({ length: callCount }, (_, i) => {\n\t\tif (i < callCount - 1) return maxImagesPerCallWithDefault;\n\t\tconst remainder = n % maxImagesPerCallWithDefault;\n\t\treturn remainder === 0 ? maxImagesPerCallWithDefault : remainder;\n\t});\n\tconst results = (await Promise.all(callImageCounts.map(async (callImageCount) => {\n\t\tconst callResults = [];\n\t\ttry {\n\t\t\tawait retry(async () => {\n\t\t\t\tconst { prompt, files, mask } = normalizePrompt$1(promptArg);\n\t\t\t\tconst result = await model.doGenerate({\n\t\t\t\t\tprompt,\n\t\t\t\t\tfiles,\n\t\t\t\t\tmask,\n\t\t\t\t\tn: callImageCount,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\tsize,\n\t\t\t\t\taspectRatio,\n\t\t\t\t\tseed,\n\t\t\t\t\tproviderOptions: providerOptions ?? {}\n\t\t\t\t});\n\t\t\t\tcallResults.push(result);\n\t\t\t\tif (result.images.length === 0 && result.isRetryable !== false) throw new RetryableNoImageResultError();\n\t\t\t\treturn result;\n\t\t\t});\n\t\t\treturn callResults;\n\t\t} catch (error) {\n\t\t\tif ((error instanceof RetryableNoImageResultError ? error : RetryError.isInstance(error) && error.lastError instanceof RetryableNoImageResultError ? error.lastError : void 0) != null) return callResults;\n\t\t\tthrow error;\n\t\t}\n\t}))).flat();\n\tconst images = [];\n\tconst calls = [];\n\tconst warnings = [];\n\tconst responses = [];\n\tconst providerMetadata = {};\n\tlet totalUsage = {\n\t\tinputTokens: void 0,\n\t\toutputTokens: void 0,\n\t\ttotalTokens: void 0\n\t};\n\tfor (const result of results) {\n\t\tconst callImages = result.images.map((image, index) => new DefaultGeneratedFile({\n\t\t\tdata: image,\n\t\t\tmediaType: detectMediaType({\n\t\t\t\tdata: image,\n\t\t\t\ttopLevelType: \"image\"\n\t\t\t}) ?? \"image/png\",\n\t\t\tproviderMetadata: getImageProviderMetadata(result.providerMetadata, index)\n\t\t}));\n\t\timages.push(...callImages);\n\t\tcalls.push({\n\t\t\timages: callImages,\n\t\t\tproviderMetadata: result.providerMetadata,\n\t\t\tresponse: result.response,\n\t\t\twarnings: result.warnings,\n\t\t\tusage: result.usage\n\t\t});\n\t\twarnings.push(...result.warnings);\n\t\tif (result.usage != null) totalUsage = addImageModelUsage(totalUsage, result.usage);\n\t\tif (result.providerMetadata) for (const [providerName, metadata] of Object.entries(result.providerMetadata)) if (providerName === \"gateway\") {\n\t\t\tconst currentEntry = providerMetadata[providerName];\n\t\t\tif (currentEntry != null && typeof currentEntry === \"object\") {\n\t\t\t\tconst currentGatewayMetadata = currentEntry;\n\t\t\t\tconst newGatewayMetadata = metadata;\n\t\t\t\tproviderMetadata[providerName] = {\n\t\t\t\t\t...currentEntry,\n\t\t\t\t\t...metadata,\n\t\t\t\t\t...Object.fromEntries(gatewayCostMetadataKeys.flatMap((key) => {\n\t\t\t\t\t\tconst total = addDecimalStrings(currentGatewayMetadata[key], newGatewayMetadata[key]);\n\t\t\t\t\t\treturn total == null ? [] : [[key, total]];\n\t\t\t\t\t}))\n\t\t\t\t};\n\t\t\t} else providerMetadata[providerName] = { ...metadata };\n\t\t\tconst imagesValue = providerMetadata[providerName].images;\n\t\t\tif (Array.isArray(imagesValue) && imagesValue.length === 0) delete providerMetadata[providerName].images;\n\t\t} else {\n\t\t\tconst currentEntry = getOwn(providerMetadata, providerName) ?? { images: [] };\n\t\t\tcurrentEntry.images.push(...metadata.images);\n\t\t\tsetOwn(providerMetadata, providerName, currentEntry);\n\t\t}\n\t\tresponses.push(result.response);\n\t}\n\tlogWarnings({\n\t\twarnings,\n\t\tprovider: model.provider,\n\t\tmodel: model.modelId\n\t});\n\tif (!images.length) throw new NoImageGeneratedError({\n\t\tcalls,\n\t\tresponses\n\t});\n\treturn new DefaultGenerateImageResult({\n\t\timages,\n\t\tcalls,\n\t\twarnings,\n\t\tresponses,\n\t\tproviderMetadata,\n\t\tusage: totalUsage\n\t});\n}\nvar DefaultGenerateImageResult = class {\n\tconstructor(options) {\n\t\tthis.images = options.images;\n\t\tthis.calls = options.calls;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.usage = options.usage;\n\t}\n\tget image() {\n\t\treturn this.images[0];\n\t}\n};\n/**\n* Extracts per-image metadata from the legacy `providerMetadata.<provider>.images` result shape.\n*/\nfunction getImageProviderMetadata(providerMetadata, imageIndex) {\n\tif (providerMetadata == null) return;\n\tlet imageMetadata;\n\tfor (const [providerName, metadata] of Object.entries(providerMetadata)) {\n\t\tconst value = metadata.images?.[imageIndex];\n\t\tif (isJSONObject(value) && !Array.isArray(value)) setOwn(imageMetadata ??= {}, providerName, value);\n\t}\n\treturn imageMetadata;\n}\nasync function invokeModelMaxImagesPerCall(model) {\n\tif (!(model.maxImagesPerCall instanceof Function)) return model.maxImagesPerCall;\n\treturn model.maxImagesPerCall({ modelId: model.modelId });\n}\nfunction addDecimalStrings(value1, value2) {\n\tif (typeof value1 !== \"string\" || typeof value2 !== \"string\" || !/^\\d+(?:\\.\\d+)?$/.test(value1) || !/^\\d+(?:\\.\\d+)?$/.test(value2)) return;\n\tconst [integer1, fraction1 = \"\"] = value1.split(\".\");\n\tconst [integer2, fraction2 = \"\"] = value2.split(\".\");\n\tconst precision = Math.max(fraction1.length, fraction2.length);\n\tconst sumString = (BigInt(integer1 + fraction1.padEnd(precision, \"0\")) + BigInt(integer2 + fraction2.padEnd(precision, \"0\"))).toString().padStart(precision + 1, \"0\");\n\treturn precision === 0 ? sumString : `${sumString.slice(0, -precision)}.${sumString.slice(-precision)}`.replace(/\\.?0+$/, \"\");\n}\nfunction normalizePrompt$1(prompt) {\n\tif (typeof prompt === \"string\") return {\n\t\tprompt,\n\t\tfiles: void 0,\n\t\tmask: void 0\n\t};\n\treturn {\n\t\tprompt: prompt.text,\n\t\tfiles: prompt.images.map(toImageModelV4File),\n\t\tmask: prompt.mask ? toImageModelV4File(prompt.mask) : void 0\n\t};\n}\nfunction toImageModelV4File(dataContent) {\n\tif (typeof dataContent === \"string\" && dataContent.startsWith(\"http\")) return {\n\t\ttype: \"url\",\n\t\turl: dataContent\n\t};\n\tif (typeof dataContent === \"string\" && dataContent.startsWith(\"data:\")) {\n\t\tconst { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(dataContent);\n\t\tif (base64Content != null) {\n\t\t\tconst uint8Data = convertBase64ToUint8Array(base64Content);\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tdata: uint8Data,\n\t\t\t\tmediaType: dataUrlMediaType || detectMediaType({\n\t\t\t\t\tdata: uint8Data,\n\t\t\t\t\ttopLevelType: \"image\"\n\t\t\t\t}) || \"image/png\"\n\t\t\t};\n\t\t}\n\t}\n\tconst uint8Data = convertDataContentToUint8Array(dataContent);\n\treturn {\n\t\ttype: \"file\",\n\t\tdata: uint8Data,\n\t\tmediaType: detectMediaType({\n\t\t\tdata: uint8Data,\n\t\t\ttopLevelType: \"image\"\n\t\t}) || \"image/png\"\n\t};\n}\n//#endregion\n//#region src/batch/batch.ts\n/**\n* Requests cancellation of a batch.\n*/\nasync function cancelBatch({ provider, batch, providerOptions, abortSignal, headers, timeout }) {\n\tconst batchApi = resolveBatchApi(provider);\n\tvalidateBatchReference({\n\t\tbatchApi,\n\t\tbatch\n\t});\n\tif (batchApi.doCancelBatch == null) throw new UnsupportedFunctionalityError$1({\n\t\tfunctionality: \"batch cancellation\",\n\t\tmessage: \"The provider does not support batch cancellation.\"\n\t});\n\tconst operationAbortSignal = mergeAbortSignals(abortSignal, getTotalTimeoutMs(timeout));\n\ttry {\n\t\treturn await batchApi.doCancelBatch({\n\t\t\tbatchId: batch.id,\n\t\t\tproviderOptions,\n\t\t\tabortSignal: operationAbortSignal,\n\t\t\theaders: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`)\n\t\t});\n\t} catch (error) {\n\t\tthrow wrapGatewayError(error);\n\t}\n}\n/**\n* Lists a page of batches.\n*/\nasync function listBatches({ provider, providerOptions, limit, cursor, maxRetries, abortSignal, headers, timeout } = {}) {\n\tconst batchApi = resolveBatchApi(provider);\n\tconst doListBatches = batchApi.doListBatches?.bind(batchApi);\n\tif (doListBatches == null) throw new UnsupportedFunctionalityError$1({\n\t\tfunctionality: \"batch listing\",\n\t\tmessage: \"The provider does not support listing batches.\"\n\t});\n\tconst operationAbortSignal = mergeAbortSignals(abortSignal, getTotalTimeoutMs(timeout));\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries,\n\t\tabortSignal: operationAbortSignal\n\t});\n\ttry {\n\t\tconst { batches, nextCursor, providerMetadata } = await retry(() => doListBatches({\n\t\t\tproviderOptions,\n\t\t\tabortSignal: operationAbortSignal,\n\t\t\theaders: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n\t\t\t...limit != null && { limit },\n\t\t\t...cursor != null && { cursor }\n\t\t}));\n\t\treturn {\n\t\t\tbatches: batches.map(({ batchId, ...status }) => ({\n\t\t\t\tversion: 2,\n\t\t\t\tid: batchId,\n\t\t\t\tprovider: batchApi.provider,\n\t\t\t\t...status\n\t\t\t})),\n\t\t\t...nextCursor != null && { nextCursor },\n\t\t\t...providerMetadata != null && { providerMetadata }\n\t\t};\n\t} catch (error) {\n\t\tthrow wrapGatewayError(error);\n\t}\n}\n/**\n* Starts a batch.\n*/\nasync function startBatch({ provider, requests, providerOptions, webhookUrl, abortSignal, headers, timeout }) {\n\tvalidateRequests(requests);\n\tconst batchApi = resolveBatchApi(provider);\n\tconst operationAbortSignal = mergeAbortSignals(abortSignal, getTotalTimeoutMs(timeout));\n\tconst supportedUrls = await batchApi.supportedUrls;\n\toperationAbortSignal?.throwIfAborted();\n\tconst normalizedRequests = [];\n\tconst toolsByName = /* @__PURE__ */ new Map();\n\tfor (const request of requests) {\n\t\tconst requestType = request.type;\n\t\tswitch (requestType) {\n\t\t\tcase \"text\": {\n\t\t\t\tconst standardizedPrompt = await standardizePrompt(request);\n\t\t\t\tconst preparedTools = await prepareTools({\n\t\t\t\t\ttools: request.tools,\n\t\t\t\t\ttoolOrder: request.toolOrder,\n\t\t\t\t\ttoolsContext: request.toolsContext\n\t\t\t\t});\n\t\t\t\tvalidateCompatibleTools({\n\t\t\t\t\trequestId: request.id,\n\t\t\t\t\ttools: preparedTools,\n\t\t\t\t\ttoolsByName\n\t\t\t\t});\n\t\t\t\tnormalizedRequests.push({\n\t\t\t\t\tid: request.id,\n\t\t\t\t\ttype: request.type,\n\t\t\t\t\tmodelId: request.model,\n\t\t\t\t\toptions: {\n\t\t\t\t\t\t...prepareLanguageModelCallOptions(request),\n\t\t\t\t\t\tprompt: await convertToLanguageModelPrompt({\n\t\t\t\t\t\t\tprompt: standardizedPrompt,\n\t\t\t\t\t\t\tsupportedUrls,\n\t\t\t\t\t\t\tdownload: void 0,\n\t\t\t\t\t\t\tabortSignal: operationAbortSignal,\n\t\t\t\t\t\t\tprovider: batchApi.provider.split(\".\")[0]\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttools: preparedTools,\n\t\t\t\t\t\ttoolChoice: prepareToolChoice({ toolChoice: request.toolChoice }),\n\t\t\t\t\t\tproviderOptions: request.providerOptions\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"image\": {\n\t\t\t\tconst { prompt, files, mask } = normalizePrompt$1(request.prompt);\n\t\t\t\tnormalizedRequests.push({\n\t\t\t\t\tid: request.id,\n\t\t\t\t\ttype: request.type,\n\t\t\t\t\tmodelId: request.model,\n\t\t\t\t\toptions: {\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tn: request.n ?? 1,\n\t\t\t\t\t\tsize: request.size,\n\t\t\t\t\t\taspectRatio: request.aspectRatio,\n\t\t\t\t\t\tseed: request.seed,\n\t\t\t\t\t\tfiles,\n\t\t\t\t\t\tmask,\n\t\t\t\t\t\tproviderOptions: request.providerOptions ?? {}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustiveCheck = requestType;\n\t\t\t\tthrow new InvalidArgumentError({\n\t\t\t\t\tparameter: \"requests\",\n\t\t\t\t\tvalue: _exhaustiveCheck,\n\t\t\t\t\tmessage: `Unsupported batch request type \"${_exhaustiveCheck}\".`\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\toperationAbortSignal?.throwIfAborted();\n\t}\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\ttry {\n\t\tconst { batchId, warnings, ...status } = await batchApi.doStartBatch({\n\t\t\trequests: normalizedRequests,\n\t\t\tproviderOptions,\n\t\t\tabortSignal: operationAbortSignal,\n\t\t\theaders: headersWithUserAgent,\n\t\t\t...webhookUrl != null && { webhookUrl }\n\t\t});\n\t\tconst modelByRequestId = new Map(normalizedRequests.map((request) => [request.id, request.modelId]));\n\t\tfor (const { requestId, warning } of warnings) logWarnings({\n\t\t\twarnings: [warning],\n\t\t\tprovider: batchApi.provider,\n\t\t\tmodel: requestId == null ? void 0 : modelByRequestId.get(requestId)\n\t\t});\n\t\treturn {\n\t\t\tversion: 2,\n\t\t\tid: batchId,\n\t\t\tprovider: batchApi.provider,\n\t\t\t...status,\n\t\t\twarnings\n\t\t};\n\t} catch (error) {\n\t\tthrow wrapGatewayError(error);\n\t}\n}\nfunction validateCompatibleTools({ requestId, tools, toolsByName }) {\n\tfor (const tool of tools ?? []) {\n\t\tconst previousTool = toolsByName.get(tool.name);\n\t\tif (previousTool != null && !isDeepEqualData(previousTool, tool)) throw new InvalidArgumentError({\n\t\t\tparameter: \"requests\",\n\t\t\tvalue: requestId,\n\t\t\tmessage: `tool \"${tool.name}\" must have the same definition in every batch request`\n\t\t});\n\t\ttoolsByName.set(tool.name, tool);\n\t}\n}\n/**\n* Retrieves the latest normalized status for a batch.\n*/\nasync function getBatchStatus({ provider, batch, providerOptions, maxRetries, abortSignal, headers, timeout }) {\n\tconst batchApi = resolveBatchApi(provider);\n\tvalidateBatchReference({\n\t\tbatchApi,\n\t\tbatch\n\t});\n\tconst operationAbortSignal = mergeAbortSignals(abortSignal, getTotalTimeoutMs(timeout));\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries,\n\t\tabortSignal: operationAbortSignal\n\t});\n\ttry {\n\t\treturn await retry(() => batchApi.doGetBatchStatus({\n\t\t\tbatchId: batch.id,\n\t\t\tproviderOptions,\n\t\t\tabortSignal: operationAbortSignal,\n\t\t\theaders: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`)\n\t\t}));\n\t} catch (error) {\n\t\tthrow wrapGatewayError(error);\n\t}\n}\n/**\n* Streams complete terminal results for the requests in a batch.\n*/\nfunction getBatchResults({ provider, batch, tools, providerOptions, maxRetries, abortSignal, headers, timeout }) {\n\tconst batchApi = resolveBatchApi(provider);\n\tvalidateBatchReference({\n\t\tbatchApi,\n\t\tbatch\n\t});\n\tconst streamAbortController = new AbortController();\n\tconst operationAbortSignal = mergeAbortSignals(abortSignal, getTotalTimeoutMs(timeout), streamAbortController.signal);\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries,\n\t\tabortSignal: operationAbortSignal\n\t});\n\tconst transform = new TransformStream({\n\t\tasync transform(item, controller) {\n\t\t\tcontroller.enqueue(await convertBatchItemResult({\n\t\t\t\titem,\n\t\t\t\ttools,\n\t\t\t\tabortSignal: operationAbortSignal\n\t\t\t}));\n\t\t},\n\t\tcancel(reason) {\n\t\t\tstreamAbortController.abort(reason ?? /* @__PURE__ */ new Error(\"Batch results stream was cancelled.\"));\n\t\t}\n\t});\n\t(async () => {\n\t\ttry {\n\t\t\tawait (await retry(() => batchApi.doGetBatchResults({\n\t\t\t\tbatchId: batch.id,\n\t\t\t\tproviderOptions,\n\t\t\t\tabortSignal: operationAbortSignal,\n\t\t\t\theaders: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`)\n\t\t\t}))).pipeTo(transform.writable, { signal: operationAbortSignal });\n\t\t} catch (error) {\n\t\t\tawait transform.writable.abort(wrapGatewayError(error)).catch(() => {});\n\t\t}\n\t})();\n\treturn asAsyncIterableStream(transform.readable);\n}\nfunction resolveBatchApi(provider) {\n\tprovider ??= asProviderV4(globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway$1);\n\tif (isBatchApi(provider)) return provider;\n\tif (!hasBatchFactory(provider)) throw new UnsupportedFunctionalityError$1({\n\t\tfunctionality: \"batch processing\",\n\t\tmessage: \"The provider does not support batch processing. Make sure it exposes an experimental_batch() method.\"\n\t});\n\treturn provider.experimental_batch();\n}\nfunction hasBatchFactory(provider) {\n\treturn typeof provider.experimental_batch === \"function\";\n}\nfunction isBatchApi(provider) {\n\tconst candidate = provider;\n\treturn typeof candidate.doStartBatch === \"function\" && typeof candidate.doGetBatchStatus === \"function\" && typeof candidate.doGetBatchResults === \"function\";\n}\nfunction validateRequests(requests) {\n\tif (requests.length === 0) throw new InvalidArgumentError({\n\t\tparameter: \"requests\",\n\t\tvalue: requests,\n\t\tmessage: \"requests must not be empty\"\n\t});\n\tconst ids = /* @__PURE__ */ new Set();\n\tfor (const request of requests) {\n\t\tif (request.id.trim().length === 0) throw new InvalidArgumentError({\n\t\t\tparameter: \"requests\",\n\t\t\tvalue: requests,\n\t\t\tmessage: \"request IDs must not be empty\"\n\t\t});\n\t\tif (ids.has(request.id)) throw new InvalidArgumentError({\n\t\t\tparameter: \"requests\",\n\t\t\tvalue: requests,\n\t\t\tmessage: `request IDs must be unique; duplicate ID \"${request.id}\"`\n\t\t});\n\t\tids.add(request.id);\n\t}\n}\nfunction validateBatchReference({ batchApi, batch }) {\n\tif (batch.version !== 2) throw new InvalidArgumentError({\n\t\tparameter: \"batch\",\n\t\tvalue: batch,\n\t\tmessage: \"batch must be a supported batch reference\"\n\t});\n\tif (batch.provider !== batchApi.provider) throw new InvalidArgumentError({\n\t\tparameter: \"provider\",\n\t\tvalue: batchApi,\n\t\tmessage: `provider ${batchApi.provider} is not compatible with batch provider ${batch.provider}`\n\t});\n}\nasync function convertBatchItemResult({ item, tools, abortSignal }) {\n\tswitch (item.type) {\n\t\tcase \"text\": switch (item.status) {\n\t\t\tcase \"succeeded\": return {\n\t\t\t\ttype: item.type,\n\t\t\t\tid: item.id,\n\t\t\t\tstatus: item.status,\n\t\t\t\t...await convertGenerateResult({\n\t\t\t\t\tresult: item.result,\n\t\t\t\t\ttools,\n\t\t\t\t\tabortSignal\n\t\t\t\t})\n\t\t\t};\n\t\t\tcase \"failed\": return {\n\t\t\t\ttype: item.type,\n\t\t\t\tid: item.id,\n\t\t\t\tstatus: item.status,\n\t\t\t\terror: item.error,\n\t\t\t\tproviderMetadata: item.providerMetadata\n\t\t\t};\n\t\t\tcase \"cancelled\":\n\t\t\tcase \"expired\": return {\n\t\t\t\ttype: item.type,\n\t\t\t\tid: item.id,\n\t\t\t\tstatus: item.status,\n\t\t\t\terror: item.error,\n\t\t\t\tproviderMetadata: item.providerMetadata\n\t\t\t};\n\t\t}\n\t\tcase \"image\": switch (item.status) {\n\t\t\tcase \"succeeded\": return {\n\t\t\t\ttype: item.type,\n\t\t\t\tid: item.id,\n\t\t\t\tstatus: item.status,\n\t\t\t\t...convertImageResult(item.result)\n\t\t\t};\n\t\t\tcase \"failed\": return {\n\t\t\t\ttype: item.type,\n\t\t\t\tid: item.id,\n\t\t\t\tstatus: item.status,\n\t\t\t\terror: item.error,\n\t\t\t\tproviderMetadata: item.providerMetadata\n\t\t\t};\n\t\t\tcase \"cancelled\":\n\t\t\tcase \"expired\": return {\n\t\t\t\ttype: item.type,\n\t\t\t\tid: item.id,\n\t\t\t\tstatus: item.status,\n\t\t\t\terror: item.error,\n\t\t\t\tproviderMetadata: item.providerMetadata\n\t\t\t};\n\t\t}\n\t}\n}\nfunction convertImageResult(result) {\n\treturn {\n\t\timages: result.images.map((image, index) => new DefaultGeneratedFile({\n\t\t\tdata: image,\n\t\t\tmediaType: detectMediaType({\n\t\t\t\tdata: image,\n\t\t\t\ttopLevelType: \"image\"\n\t\t\t}) ?? \"image/png\",\n\t\t\tproviderMetadata: getImageProviderMetadata(result.providerMetadata, index)\n\t\t})),\n\t\twarnings: result.warnings,\n\t\tresponse: {\n\t\t\ttimestamp: result.response.timestamp,\n\t\t\tmodelId: result.response.modelId,\n\t\t\theaders: result.response.headers\n\t\t},\n\t\tproviderMetadata: result.providerMetadata,\n\t\tusage: result.usage\n\t};\n}\nasync function convertGenerateResult({ result, tools, abortSignal }) {\n\tconst toolCalls = await Promise.all(result.content.filter((part) => part.type === \"tool-call\").map((toolCall) => parseToolCall({\n\t\ttoolCall,\n\t\ttools,\n\t\trepairToolCall: void 0,\n\t\trefineToolInput: void 0,\n\t\tinstructions: void 0,\n\t\tmessages: []\n\t})));\n\treturn {\n\t\tcontent: await convertLanguageModelContent({\n\t\t\tcontent: result.content,\n\t\t\ttoolCalls,\n\t\t\ttoolOutputs: [],\n\t\t\ttoolApprovalRequests: [],\n\t\t\ttoolApprovalResponses: [],\n\t\t\ttools,\n\t\t\tabortSignal\n\t\t}),\n\t\ttext: result.content.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\"),\n\t\tfinishReason: result.finishReason.unified,\n\t\trawFinishReason: result.finishReason.raw,\n\t\tusage: asLanguageModelUsage(result.usage),\n\t\t...result.response != null ? { response: {\n\t\t\tid: result.response.id,\n\t\t\ttimestamp: result.response.timestamp?.toISOString(),\n\t\t\tmodelId: result.response.modelId\n\t\t} } : {},\n\t\tproviderMetadata: result.providerMetadata\n\t};\n}\n//#endregion\n//#region src/embed/restricted-telemetry-dispatcher.ts\n/**\n* Filters runtime context before sending operation events to telemetry integrations.\n* User callbacks continue to receive the original context.\n*/\nfunction createRestrictedTelemetryDispatcher$2({ telemetry }) {\n\tconst dispatcher = createTelemetryDispatcher({ telemetry });\n\treturn {\n\t\t...dispatcher,\n\t\tonStart: (event) => dispatcher.onStart?.({\n\t\t\t...event,\n\t\t\truntimeContext: filterIncludedContext({\n\t\t\t\tcontext: event.runtimeContext,\n\t\t\t\tincludeContext: telemetry?.includeRuntimeContext\n\t\t\t})\n\t\t}),\n\t\tonEnd: (event) => dispatcher.onEnd?.({\n\t\t\t...event,\n\t\t\truntimeContext: filterIncludedContext({\n\t\t\t\tcontext: event.runtimeContext,\n\t\t\t\tincludeContext: telemetry?.includeRuntimeContext\n\t\t\t})\n\t\t})\n\t};\n}\n//#endregion\n//#region src/embed/validate-embedding-dimensions.ts\nfunction validateEmbeddingDimensions(dimensions) {\n\tif (dimensions !== void 0 && (!Number.isInteger(dimensions) || dimensions <= 0)) throw new InvalidArgumentError({\n\t\tparameter: \"dimensions\",\n\t\tvalue: dimensions,\n\t\tmessage: \"dimensions must be a positive integer\"\n\t});\n}\n//#endregion\n//#region src/embed/embed.ts\nconst originalGenerateCallId$6 = createIdGenerator$1({\n\tprefix: \"call\",\n\tsize: 24\n});\n/**\n* Embed a value using an embedding model. The type of the value is defined by the embedding model.\n*\n* @param model - The embedding model to use.\n* @param value - The value that should be embedded.\n*\n* @param dimensions - Requested output dimensions. Must be a positive integer. Requires provider support.\n*\n* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n*\n* @param telemetry - Optional telemetry configuration.\n* @param runtimeContext - User-defined runtime context passed to callbacks and, when explicitly included, telemetry.\n*\n* @param providerOptions - Additional provider-specific options. They are passed through\n* to the provider from the AI SDK and enable provider-specific\n* functionality that can be fully encapsulated in the provider.\n*\n* @returns A result object that contains the embedding, the value, and additional information.\n*/\nasync function embed({ model: modelArg, value, dimensions, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry, telemetry = experimental_telemetry, runtimeContext = {}, onStart, experimental_onStart, onEnd, experimental_onEnd, _internal: { generateCallId = originalGenerateCallId$6 } = {} }) {\n\tvalidateEmbeddingDimensions(dimensions);\n\tconst model = resolveEmbeddingModel(modelArg);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst resolvedOnStart = onStart ?? experimental_onStart;\n\tconst resolvedOnEnd = onEnd ?? experimental_onEnd;\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst callId = generateCallId();\n\tconst telemetryDispatcher = createRestrictedTelemetryDispatcher$2({ telemetry });\n\tconst runInTracingChannelSpan = telemetryDispatcher.runInTracingChannelSpan ?? (async ({ execute }) => await execute());\n\tconst startEvent = {\n\t\tcallId,\n\t\toperationId: \"ai.embed\",\n\t\truntimeContext,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId,\n\t\tvalue,\n\t\tdimensions,\n\t\tmaxRetries,\n\t\theaders: headersWithUserAgent,\n\t\tproviderOptions\n\t};\n\treturn await runInTracingChannelSpan({\n\t\ttype: \"embed\",\n\t\tevent: startEvent,\n\t\texecute: async () => {\n\t\t\tawait notify({\n\t\t\t\tevent: startEvent,\n\t\t\t\tcallbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tconst { embedding, usage, warnings, response, providerMetadata } = await retry(async () => {\n\t\t\t\t\tconst embedCallId = generateCallId();\n\t\t\t\t\tawait notify({\n\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\tembedCallId,\n\t\t\t\t\t\t\toperationId: \"ai.embed.doEmbed\",\n\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\t\tvalues: [value],\n\t\t\t\t\t\t\tdimensions\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcallbacks: [telemetryDispatcher.onEmbedStart]\n\t\t\t\t\t});\n\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\tvalues: [value],\n\t\t\t\t\t\tdimensions,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t});\n\t\t\t\t\tconst embedding = modelResponse.embeddings[0];\n\t\t\t\t\tconst usage = modelResponse.usage ?? { tokens: NaN };\n\t\t\t\t\tawait notify({\n\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\tembedCallId,\n\t\t\t\t\t\t\toperationId: \"ai.embed.doEmbed\",\n\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\t\tvalues: [value],\n\t\t\t\t\t\t\tembeddings: modelResponse.embeddings,\n\t\t\t\t\t\t\tusage\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcallbacks: [telemetryDispatcher.onEmbedEnd]\n\t\t\t\t\t});\n\t\t\t\t\tif (embedding == null) throw new InvalidResponseDataError({\n\t\t\t\t\t\tdata: modelResponse.embeddings,\n\t\t\t\t\t\tmessage: \"No embedding generated.\"\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\tembedding,\n\t\t\t\t\t\tusage,\n\t\t\t\t\t\twarnings: modelResponse.warnings ?? [],\n\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t\t\tlogWarnings({\n\t\t\t\t\twarnings,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.modelId\n\t\t\t\t});\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\tcallId,\n\t\t\t\t\t\toperationId: \"ai.embed\",\n\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\tembedding,\n\t\t\t\t\t\tusage,\n\t\t\t\t\t\twarnings,\n\t\t\t\t\t\tproviderMetadata,\n\t\t\t\t\t\tresponse\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: [resolvedOnEnd, telemetryDispatcher.onEnd]\n\t\t\t\t});\n\t\t\t\treturn new DefaultEmbedResult({\n\t\t\t\t\tvalue,\n\t\t\t\t\tembedding,\n\t\t\t\t\tusage,\n\t\t\t\t\twarnings,\n\t\t\t\t\tproviderMetadata,\n\t\t\t\t\tresponse\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\t\tcallId,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t});\n}\nvar DefaultEmbedResult = class {\n\tconstructor(options) {\n\t\tthis.value = options.value;\n\t\tthis.embedding = options.embedding;\n\t\tthis.usage = options.usage;\n\t\tthis.warnings = options.warnings;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.response = options.response;\n\t}\n};\n//#endregion\n//#region src/model/get-embedding-model-max-input-bytes-per-call.ts\nfunction getEmbeddingModelMaxInputBytesPerCall(model) {\n\treturn model[EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL];\n}\n//#endregion\n//#region src/model/get-embedding-model-provider-options-transformer.ts\nfunction getEmbeddingModelProviderOptionsTransformer(model) {\n\treturn model[EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER];\n}\n//#endregion\n//#region src/util/split-array.ts\n/**\n* Splits an array into chunks of a specified size.\n*\n* @template T - The type of elements in the array.\n* @param {T[]} array - The array to split.\n* @param {number} chunkSize - The size of each chunk.\n* @returns {T[][]} - A new array containing the chunks.\n* @throws {InvalidArgumentError} If the chunk size is not greater than 0.\n*/\nfunction splitArray(array, chunkSize) {\n\tif (chunkSize <= 0) throw new InvalidArgumentError({\n\t\tparameter: \"chunkSize\",\n\t\tvalue: chunkSize,\n\t\tmessage: \"chunkSize must be greater than 0\"\n\t});\n\tconst result = [];\n\tfor (let i = 0; i < array.length; i += chunkSize) result.push(array.slice(i, i + chunkSize));\n\treturn result;\n}\n//#endregion\n//#region src/embed/embed-many.ts\nconst originalGenerateCallId$5 = createIdGenerator$1({\n\tprefix: \"call\",\n\tsize: 24\n});\n/**\n* Embed several values using an embedding model. The type of the value is defined\n* by the embedding model.\n*\n* `embedMany` automatically splits large requests into smaller chunks when the\n* model has a limit on either the number of embeddings or the UTF-8 input bytes\n* that can be processed in a single call.\n*\n* @param model - The embedding model to use.\n* @param values - The values that should be embedded.\n*\n* @param dimensions - Requested output dimensions. Must be a positive integer. Requires provider support.\n*\n* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n*\n* @param maxParallelCalls - Maximum number of concurrent requests when a request is split into\n* multiple model calls. Must be greater than 0 when the model supports parallel calls.\n* Default: Infinity.\n*\n* @param telemetry - Optional telemetry configuration.\n* @param runtimeContext - User-defined runtime context passed to callbacks and, when explicitly included, telemetry.\n*\n* @param providerOptions - Additional provider-specific options. They are passed through\n* to the provider from the AI SDK and enable provider-specific\n* functionality that can be fully encapsulated in the provider.\n*\n* @returns A result object that contains the embeddings, the value, and additional information.\n*/\nasync function embedMany({ model: modelArg, values, dimensions, maxParallelCalls = Infinity, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry, telemetry = experimental_telemetry, runtimeContext = {}, onStart, experimental_onStart, onEnd, experimental_onEnd, _internal: { generateCallId = originalGenerateCallId$5 } = {} }) {\n\tvalidateEmbeddingDimensions(dimensions);\n\tconst model = resolveEmbeddingModel(modelArg);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst resolvedOnStart = onStart ?? experimental_onStart;\n\tconst resolvedOnEnd = onEnd ?? experimental_onEnd;\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst callId = generateCallId();\n\tconst telemetryDispatcher = createRestrictedTelemetryDispatcher$2({ telemetry });\n\tconst runInTracingChannelSpan = telemetryDispatcher.runInTracingChannelSpan ?? (async ({ execute }) => await execute());\n\tconst startEvent = {\n\t\tcallId,\n\t\toperationId: \"ai.embedMany\",\n\t\truntimeContext,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId,\n\t\tvalue: values,\n\t\tdimensions,\n\t\tmaxRetries,\n\t\theaders: headersWithUserAgent,\n\t\tproviderOptions\n\t};\n\treturn await runInTracingChannelSpan({\n\t\ttype: \"embedMany\",\n\t\tevent: startEvent,\n\t\texecute: async () => {\n\t\t\tawait notify({\n\t\t\t\tevent: startEvent,\n\t\t\t\tcallbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tconst [maxEmbeddingsPerCall, maxInputBytesPerCall, supportsParallelCalls] = await Promise.all([\n\t\t\t\t\tmodel.maxEmbeddingsPerCall,\n\t\t\t\t\tgetEmbeddingModelMaxInputBytesPerCall(model),\n\t\t\t\t\tmodel.supportsParallelCalls\n\t\t\t\t]);\n\t\t\t\tconst hasEmbeddingLimit = maxEmbeddingsPerCall != null && maxEmbeddingsPerCall !== Infinity;\n\t\t\t\tconst hasInputByteLimit = maxInputBytesPerCall != null && maxInputBytesPerCall !== Infinity;\n\t\t\t\tif (!hasEmbeddingLimit && !hasInputByteLimit) {\n\t\t\t\t\tconst { embeddings, usage, warnings, response, providerMetadata } = await retry(async () => {\n\t\t\t\t\t\tconst embedCallId = generateCallId();\n\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\tembedCallId,\n\t\t\t\t\t\t\t\toperationId: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\t\tdimensions\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcallbacks: [telemetryDispatcher.onEmbedStart]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\tdimensions,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst embeddings = modelResponse.embeddings;\n\t\t\t\t\t\tconst usage = modelResponse.usage ?? { tokens: NaN };\n\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\tembedCallId,\n\t\t\t\t\t\t\t\toperationId: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\t\tembeddings,\n\t\t\t\t\t\t\t\tusage\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcallbacks: [telemetryDispatcher.onEmbedEnd]\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tembeddings,\n\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\twarnings: modelResponse.warnings ?? [],\n\t\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t\t};\n\t\t\t\t\t});\n\t\t\t\t\tvalidateEmbeddingCount({\n\t\t\t\t\t\tembeddings,\n\t\t\t\t\t\tvalues\n\t\t\t\t\t});\n\t\t\t\t\tlogWarnings({\n\t\t\t\t\t\twarnings,\n\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\tmodel: model.modelId\n\t\t\t\t\t});\n\t\t\t\t\tawait notify({\n\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\toperationId: \"ai.embedMany\",\n\t\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\t\tvalue: values,\n\t\t\t\t\t\t\tembedding: embeddings,\n\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\twarnings,\n\t\t\t\t\t\t\tproviderMetadata,\n\t\t\t\t\t\t\tresponse: [response]\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcallbacks: [resolvedOnEnd, telemetryDispatcher.onEnd]\n\t\t\t\t\t});\n\t\t\t\t\treturn new DefaultEmbedManyResult({\n\t\t\t\t\t\tvalues,\n\t\t\t\t\t\tembeddings,\n\t\t\t\t\t\tusage,\n\t\t\t\t\t\twarnings,\n\t\t\t\t\t\tproviderMetadata,\n\t\t\t\t\t\tresponses: [response]\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst valueChunks = splitByEmbeddingLimits({\n\t\t\t\t\tvalues,\n\t\t\t\t\tmaxEmbeddingsPerCall: hasEmbeddingLimit ? maxEmbeddingsPerCall : Infinity,\n\t\t\t\t\tmaxInputBytesPerCall: hasInputByteLimit ? maxInputBytesPerCall : Infinity\n\t\t\t\t});\n\t\t\t\tconst providerOptionsTransformer = getEmbeddingModelProviderOptionsTransformer(model);\n\t\t\t\tconst embeddings = [];\n\t\t\t\tconst warnings = [];\n\t\t\t\tconst responses = [];\n\t\t\t\tlet tokens = 0;\n\t\t\t\tlet providerMetadata;\n\t\t\t\tconst parallelChunks = splitArray(valueChunks, supportsParallelCalls ? maxParallelCalls : 1);\n\t\t\t\tlet nextChunkStartIndex = 0;\n\t\t\t\tfor (const parallelChunk of parallelChunks) {\n\t\t\t\t\tconst results = await Promise.all(parallelChunk.map(async (chunk) => {\n\t\t\t\t\t\tconst startIndex = nextChunkStartIndex;\n\t\t\t\t\t\tnextChunkStartIndex += chunk.length;\n\t\t\t\t\t\tconst chunkProviderOptions = providerOptionsTransformer ? await providerOptionsTransformer({\n\t\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\tstartIndex,\n\t\t\t\t\t\t\tendIndex: startIndex + chunk.length\n\t\t\t\t\t\t}) : providerOptions;\n\t\t\t\t\t\tconst result = await retry(async () => {\n\t\t\t\t\t\t\tconst embedCallId = generateCallId();\n\t\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\t\tembedCallId,\n\t\t\t\t\t\t\t\t\toperationId: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\t\t\t\tvalues: chunk,\n\t\t\t\t\t\t\t\t\tdimensions\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tcallbacks: [telemetryDispatcher.onEmbedStart]\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\t\t\tvalues: chunk,\n\t\t\t\t\t\t\t\tdimensions,\n\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\t\t\tproviderOptions: chunkProviderOptions\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst chunkEmbeddings = modelResponse.embeddings;\n\t\t\t\t\t\t\tconst usage = modelResponse.usage ?? { tokens: NaN };\n\t\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\t\tembedCallId,\n\t\t\t\t\t\t\t\t\toperationId: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\t\t\t\tvalues: chunk,\n\t\t\t\t\t\t\t\t\tembeddings: chunkEmbeddings,\n\t\t\t\t\t\t\t\t\tusage\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tcallbacks: [telemetryDispatcher.onEmbedEnd]\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tembeddings: chunkEmbeddings,\n\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\twarnings: modelResponse.warnings ?? [],\n\t\t\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t});\n\t\t\t\t\t\tvalidateEmbeddingCount({\n\t\t\t\t\t\t\tembeddings: result.embeddings,\n\t\t\t\t\t\t\tvalues: chunk\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}));\n\t\t\t\t\tfor (const result of results) {\n\t\t\t\t\t\tembeddings.push(...result.embeddings);\n\t\t\t\t\t\twarnings.push(...result.warnings);\n\t\t\t\t\t\tresponses.push(result.response);\n\t\t\t\t\t\ttokens += result.usage.tokens;\n\t\t\t\t\t\tif (result.providerMetadata) {\n\t\t\t\t\t\t\tif (!providerMetadata) providerMetadata = { ...result.providerMetadata };\n\t\t\t\t\t\t\telse for (const [providerName, metadata] of Object.entries(result.providerMetadata)) setOwn(providerMetadata, providerName, {\n\t\t\t\t\t\t\t\t...getOwn(providerMetadata, providerName),\n\t\t\t\t\t\t\t\t...metadata\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlogWarnings({\n\t\t\t\t\twarnings,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.modelId\n\t\t\t\t});\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\tcallId,\n\t\t\t\t\t\toperationId: \"ai.embedMany\",\n\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\tvalue: values,\n\t\t\t\t\t\tembedding: embeddings,\n\t\t\t\t\t\tusage: { tokens },\n\t\t\t\t\t\twarnings,\n\t\t\t\t\t\tproviderMetadata,\n\t\t\t\t\t\tresponse: responses\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: [resolvedOnEnd, telemetryDispatcher.onEnd]\n\t\t\t\t});\n\t\t\t\treturn new DefaultEmbedManyResult({\n\t\t\t\t\tvalues,\n\t\t\t\t\tembeddings,\n\t\t\t\t\tusage: { tokens },\n\t\t\t\t\twarnings,\n\t\t\t\t\tproviderMetadata,\n\t\t\t\t\tresponses\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\t\tcallId,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t});\n}\nfunction validateEmbeddingCount({ embeddings, values }) {\n\tif (embeddings.length !== values.length) throw new InvalidResponseDataError$1({\n\t\tdata: embeddings,\n\t\tmessage: `Expected ${values.length} embeddings, but received ${embeddings.length}.`\n\t});\n}\nconst textEncoder = new TextEncoder();\nfunction splitByEmbeddingLimits({ values, maxEmbeddingsPerCall, maxInputBytesPerCall }) {\n\tif (maxEmbeddingsPerCall <= 0) throw new Error(\"maxEmbeddingsPerCall must be greater than 0\");\n\tif (maxInputBytesPerCall <= 0) throw new Error(\"maxInputBytesPerCall must be greater than 0\");\n\tif (values.length === 0) return [];\n\tconst chunks = [];\n\tlet currentChunk = [];\n\tlet currentInputBytes = 0;\n\tfor (const value of values) {\n\t\tconst inputBytes = textEncoder.encode(value).length;\n\t\tif (currentChunk.length > 0 && (currentChunk.length >= maxEmbeddingsPerCall || currentInputBytes + inputBytes > maxInputBytesPerCall)) {\n\t\t\tchunks.push(currentChunk);\n\t\t\tcurrentChunk = [];\n\t\t\tcurrentInputBytes = 0;\n\t\t}\n\t\tcurrentChunk.push(value);\n\t\tcurrentInputBytes += inputBytes;\n\t}\n\tchunks.push(currentChunk);\n\treturn chunks;\n}\nvar DefaultEmbedManyResult = class {\n\tconstructor(options) {\n\t\tthis.values = options.values;\n\t\tthis.embeddings = options.embeddings;\n\t\tthis.usage = options.usage;\n\t\tthis.warnings = options.warnings;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.responses = options.responses;\n\t}\n};\n//#endregion\n//#region src/decide/decision-state.ts\nfunction isDecisionStateParts(state) {\n\treturn Array.isArray(state);\n}\nasync function prepareDecisionState(state, abortSignal) {\n\tif (typeof state === \"string\") return [{\n\t\ttype: \"text\",\n\t\ttext: state\n\t}];\n\tif (!isDecisionStateParts(state)) return [{\n\t\ttype: \"json\",\n\t\tvalue: state\n\t}];\n\tif (state.every((part) => part.type !== \"file\")) return state;\n\tconst message = (await convertToLanguageModelPrompt({\n\t\tprompt: {\n\t\t\tinstructions: void 0,\n\t\t\tmessages: [{\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: state.filter((part) => part.type === \"file\")\n\t\t\t}]\n\t\t},\n\t\tsupportedUrls: {},\n\t\tdownload: void 0,\n\t\tabortSignal\n\t}))[0];\n\tif (message.role !== \"user\") throw new Error(\"Expected user message.\");\n\tlet fileIndex = 0;\n\treturn state.map((part) => part.type === \"file\" ? message.content[fileIndex++] : part);\n}\n//#endregion\n//#region src/decide/restricted-telemetry-dispatcher.ts\nfunction createRestrictedTelemetryDispatcher$1({ telemetry }) {\n\tconst dispatcher = createTelemetryDispatcher({ telemetry });\n\treturn {\n\t\t...dispatcher,\n\t\tonStart: (event) => dispatcher.experimental_onDecideStart?.({\n\t\t\t...event,\n\t\t\truntimeContext: filterIncludedContext({\n\t\t\t\tcontext: event.runtimeContext,\n\t\t\t\tincludeContext: telemetry?.includeRuntimeContext\n\t\t\t})\n\t\t}),\n\t\tonEnd: (event) => dispatcher.experimental_onDecideEnd?.({\n\t\t\t...event,\n\t\t\truntimeContext: filterIncludedContext({\n\t\t\t\tcontext: event.runtimeContext,\n\t\t\t\tincludeContext: telemetry?.includeRuntimeContext\n\t\t\t})\n\t\t})\n\t};\n}\n//#endregion\n//#region src/decide/validate-decision.ts\nconst tolerance = 1e-6;\nfunction isRecord$1(value) {\n\tif (value == null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\nfunction isJSON(value, ancestors = /* @__PURE__ */ new Set()) {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n\tif (typeof value === \"number\") return Number.isFinite(value);\n\tif (typeof value !== \"object\" || !Array.isArray(value) && !isRecord$1(value)) return false;\n\tif (ancestors.has(value)) return false;\n\tancestors.add(value);\n\tconst valid = Object.getOwnPropertySymbols(value).length === 0 && (Array.isArray(value) ? Array.from(value).every((item) => isJSON(item, ancestors)) : Object.values(value).every((item) => isJSON(item, ancestors)));\n\tancestors.delete(value);\n\treturn valid;\n}\nfunction isInput(value) {\n\treturn (typeof value === \"string\" || Array.isArray(value) || isRecord$1(value)) && isJSON(value);\n}\nfunction invalidInput(parameter, value, message) {\n\tthrow new InvalidArgumentError({\n\t\tparameter,\n\t\tvalue,\n\t\tmessage\n\t});\n}\nfunction validateDecisionInput({ state, questions }) {\n\tif (!(Array.isArray(state) ? Array.from(state).every((part) => {\n\t\tif (!isRecord$1(part)) return false;\n\t\tswitch (part.type) {\n\t\t\tcase \"text\": return textPartSchema.safeParse(part).success;\n\t\t\tcase \"file\": return filePartSchema.safeParse(part).success;\n\t\t\tcase \"json\": return isJSON(part.value);\n\t\t\tdefault: return false;\n\t\t}\n\t}) : (typeof state === \"string\" || isRecord$1(state)) && isJSON(state))) invalidInput(\"state\", state, \"must be a string, JSON object, or array of text, file, or json parts\");\n\tif (!isRecord$1(questions) || Object.keys(questions).length === 0) invalidInput(\"questions\", questions, \"must be a nonempty question map\");\n\tfor (const [id, question] of Object.entries(questions)) {\n\t\tconst parameter = `questions.${id}`;\n\t\tif (!isRecord$1(question) || !isInput(question.instructions)) invalidInput(parameter, question, \"instructions must be a JSON-compatible string, object, or array\");\n\t\tconst criteria = question.criteria;\n\t\tswitch (question.type) {\n\t\t\tcase \"choice\":\n\t\t\t\tif (!isRecord$1(criteria) || Object.keys(criteria).length === 0) invalidInput(parameter, question, \"choice criteria must be a nonempty option map\");\n\t\t\t\tbreak;\n\t\t\tcase \"score\":\n\t\t\t\tif (!Array.isArray(criteria) || criteria.length < 2) invalidInput(parameter, question, \"score criteria must contain at least two ordered levels\");\n\t\t\t\tbreak;\n\t\t\tcase \"boolean\":\n\t\t\t\tif (criteria === void 0) continue;\n\t\t\t\tif (!isRecord$1(criteria) || Object.keys(criteria).some((key) => key !== \"true\" && key !== \"false\")) invalidInput(parameter, question, \"boolean criteria may only describe true and false\");\n\t\t\t\tbreak;\n\t\t\tdefault: invalidInput(parameter, question, \"question type must be choice, score, or boolean\");\n\t\t}\n\t\tif (!isJSON(criteria) || Object.values(criteria).some((value) => value !== null && !isInput(value))) invalidInput(parameter, question, \"criteria descriptions must be JSON-compatible strings, objects, arrays, or null\");\n\t}\n}\nfunction invalidAnswer(answers, message) {\n\tthrow new InvalidResponseDataError$1({\n\t\tdata: answers,\n\t\tmessage\n\t});\n}\nfunction isProbability(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0 && value <= 1;\n}\nfunction hasExactKeys(value, keys) {\n\treturn Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));\n}\nfunction validateDistribution(value, keys, answers, id, roundingError) {\n\tif (!isRecord$1(value) || !hasExactKeys(value, keys) || !Object.values(value).every(isProbability)) invalidAnswer(answers, `Question \"${id}\" must have a complete distribution of finite probabilities in [0, 1].`);\n\tconst sum = Object.values(value).reduce((total, probability) => total + probability, 0);\n\tif (Math.abs(sum - 1) > tolerance + keys.length * roundingError) invalidAnswer(answers, `Question \"${id}\" probabilities must sum to 1 within the declared rounding precision.`);\n}\nfunction validateDecisionAnswers({ questions, answers, rounding }) {\n\tfunction roundingError(decimals) {\n\t\tif (decimals === void 0) return 0;\n\t\tif (!Number.isInteger(decimals) || decimals < 0 || decimals > 15) invalidAnswer(answers, \"Decision rounding decimals must be integers between 0 and 15.\");\n\t\treturn .5 * 10 ** -decimals;\n\t}\n\tconst probabilityError = roundingError(rounding?.probabilityDecimals);\n\tconst scoreError = roundingError(rounding?.scoreDecimals);\n\tif (!isRecord$1(answers) || !hasExactKeys(answers, Object.keys(questions))) invalidAnswer(answers, \"Decision must return exactly one answer for every question.\");\n\tfor (const [id, question] of Object.entries(questions)) {\n\t\tconst answer = answers[id];\n\t\tif (isRecord$1(answer) && answer.type === \"refusal\") continue;\n\t\tif (!isRecord$1(answer) || answer.type !== question.type) invalidAnswer(answers, `Question \"${id}\" returned an answer with the wrong type.`);\n\t\tswitch (question.type) {\n\t\t\tcase \"choice\":\n\t\t\t\tif (typeof answer.choice !== \"string\" || !Object.hasOwn(question.criteria, answer.choice)) invalidAnswer(answers, `Question \"${id}\" selected an unknown option.`);\n\t\t\t\tif (answer.probabilities !== void 0) {\n\t\t\t\t\tvalidateDistribution(answer.probabilities, Object.keys(question.criteria), answers, id, probabilityError);\n\t\t\t\t\tconst selected = answer.probabilities[answer.choice];\n\t\t\t\t\tif (Object.values(answer.probabilities).some((probability) => probability > selected + tolerance)) invalidAnswer(answers, `Question \"${id}\" did not select a highest-probability option.`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"score\":\n\t\t\t\tif (typeof answer.score !== \"number\" || !Number.isFinite(answer.score) || answer.score < 0 || answer.score > question.criteria.length - 1) invalidAnswer(answers, `Question \"${id}\" score must be in [0, ${question.criteria.length - 1}].`);\n\t\t\t\tif (answer.probabilities !== void 0) {\n\t\t\t\t\tconst keys = question.criteria.map((_, index) => String(index));\n\t\t\t\t\tvalidateDistribution(answer.probabilities, keys, answers, id, probabilityError);\n\t\t\t\t\tconst mean = Object.entries(answer.probabilities).reduce((total, [index, probability]) => total + Number(index) * probability, 0);\n\t\t\t\t\tconst meanRoundingError = keys.reduce((total, index) => total + Number(index) * probabilityError, 0);\n\t\t\t\t\tif (Math.abs(mean - answer.score) > tolerance + meanRoundingError + scoreError) invalidAnswer(answers, `Question \"${id}\" score must equal the probability-weighted mean within the declared rounding precision.`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"boolean\": if (!isProbability(answer.probability)) invalidAnswer(answers, `Question \"${id}\" must return P(true) as a finite probability in [0, 1].`);\n\t\t}\n\t}\n}\n//#endregion\n//#region src/decide/decide.ts\nconst originalGenerateCallId$4 = createIdGenerator$1({\n\tprefix: \"call\",\n\tsize: 24\n});\n/** Decide answers to typed questions against one shared state. Experimental. */\nasync function decide({ model: modelArg, state, questions, maxRetries, abortSignal, headers, providerOptions = {}, telemetry, runtimeContext = {}, onStart, onEnd, _internal: { generateCallId = originalGenerateCallId$4 } = {} }) {\n\tconst model = resolveDecisionModel(modelArg);\n\tvalidateDecisionInput({\n\t\tstate,\n\t\tquestions\n\t});\n\tfor (const [questionId, question] of Object.entries(questions)) if (!model.supportedQuestionTypes.includes(question.type)) throw new Experimental_DecisionUnsupportedQuestionTypeError$1({\n\t\tquestionId,\n\t\tquestionType: question.type,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\tconst callId = generateCallId();\n\tconst { maxRetries: resolvedMaxRetries, retry } = prepareRetries({\n\t\tmaxRetries,\n\t\tabortSignal\n\t});\n\tconst telemetryDispatcher = createRestrictedTelemetryDispatcher$1({ telemetry });\n\tconst runInTracingChannelSpan = telemetryDispatcher.runInTracingChannelSpan ?? (async ({ execute }) => await execute());\n\tconst startEvent = {\n\t\tcallId,\n\t\toperationId: \"ai.decide\",\n\t\truntimeContext,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId,\n\t\tstate,\n\t\tquestions,\n\t\tmaxRetries: resolvedMaxRetries,\n\t\theaders,\n\t\tproviderOptions\n\t};\n\treturn await runInTracingChannelSpan({\n\t\ttype: \"experimental_decide\",\n\t\tevent: startEvent,\n\t\texecute: async () => {\n\t\t\tawait notify({\n\t\t\t\tevent: startEvent,\n\t\t\t\tcallbacks: [onStart, telemetryDispatcher.onStart]\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tconst preparedState = await prepareDecisionState(state, abortSignal);\n\t\t\t\tconst modelCallEvent = {\n\t\t\t\t\tcallId,\n\t\t\t\t\toperationId: \"ai.decide.doDecide\",\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\tstate: preparedState,\n\t\t\t\t\tquestions\n\t\t\t\t};\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: modelCallEvent,\n\t\t\t\t\tcallbacks: [telemetryDispatcher.experimental_onDecisionModelCallStart]\n\t\t\t\t});\n\t\t\t\tconst result = await retry(async () => {\n\t\t\t\t\tabortSignal?.throwIfAborted();\n\t\t\t\t\treturn await model.doDecide({\n\t\t\t\t\t\tstate: preparedState,\n\t\t\t\t\t\tquestions,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\theaders: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tabortSignal?.throwIfAborted();\n\t\t\t\tvalidateDecisionAnswers({\n\t\t\t\t\tquestions,\n\t\t\t\t\tanswers: result.answers,\n\t\t\t\t\trounding: result.rounding\n\t\t\t\t});\n\t\t\t\tconst refusedQuestionIds = Object.keys(questions).filter((id) => result.answers[id]?.type === \"refusal\");\n\t\t\t\tif (refusedQuestionIds.length > 0) throw new Experimental_DecisionRefusalError$1({\n\t\t\t\t\tquestionIds: refusedQuestionIds,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodelId: model.modelId\n\t\t\t\t});\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\t...modelCallEvent,\n\t\t\t\t\t\t...result\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: [telemetryDispatcher.experimental_onDecisionModelCallEnd]\n\t\t\t\t});\n\t\t\t\tlogWarnings({\n\t\t\t\t\twarnings: result.warnings,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.modelId\n\t\t\t\t});\n\t\t\t\tconst inputTokens = result.usage?.inputTokens;\n\t\t\t\tconst outputTokens = result.usage?.outputTokens;\n\t\t\t\tconst decisionResult = {\n\t\t\t\t\tanswers: result.answers,\n\t\t\t\t\tusage: {\n\t\t\t\t\t\tinputTokens,\n\t\t\t\t\t\toutputTokens,\n\t\t\t\t\t\ttotalTokens: inputTokens != null && outputTokens != null ? inputTokens + outputTokens : void 0\n\t\t\t\t\t},\n\t\t\t\t\twarnings: result.warnings,\n\t\t\t\t\trounding: result.rounding,\n\t\t\t\t\tproviderMetadata: result.providerMetadata,\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\t...result.response,\n\t\t\t\t\t\ttimestamp: result.response?.timestamp ?? /* @__PURE__ */ new Date(),\n\t\t\t\t\t\tmodelId: result.response?.modelId ?? model.modelId\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\t...startEvent,\n\t\t\t\t\t\t...decisionResult\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: [onEnd, telemetryDispatcher.onEnd]\n\t\t\t\t});\n\t\t\t\treturn decisionResult;\n\t\t\t} catch (error) {\n\t\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\t\tcallId,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t});\n}\n//#endregion\n//#region src/decide/index.ts\n/** @deprecated Use `experimental_decide` instead. */\nconst experimental_evaluate = decide;\n//#endregion\n//#region src/generate-text/extract-reasoning-content.ts\nfunction extractReasoningContent(content) {\n\tconst parts = content.filter((content) => content.type === \"reasoning\");\n\treturn parts.length === 0 ? void 0 : parts.map((content) => content.text).join(\"\\n\");\n}\n//#endregion\n//#region src/generate-text/extract-text-content.ts\nfunction extractTextContent(content) {\n\tconst parts = content.filter((content) => content.type === \"text\");\n\tif (parts.length === 0) return;\n\treturn parts.map((content) => content.text).join(\"\");\n}\n//#endregion\n//#region src/generate-object/output-strategy.ts\nconst noSchemaOutputStrategy = {\n\ttype: \"no-schema\",\n\tjsonSchema: async () => void 0,\n\tasync validatePartialResult({ value, textDelta }) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: {\n\t\t\t\tpartial: value,\n\t\t\t\ttextDelta\n\t\t\t}\n\t\t};\n\t},\n\tasync validateFinalResult(value, context) {\n\t\treturn value === void 0 ? {\n\t\t\tsuccess: false,\n\t\t\terror: new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\ttext: context.text,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t})\n\t\t} : {\n\t\t\tsuccess: true,\n\t\t\tvalue\n\t\t};\n\t},\n\tcreateElementStream() {\n\t\tthrow new UnsupportedFunctionalityError$1({ functionality: \"element streams in no-schema mode\" });\n\t}\n};\nconst objectOutputStrategy = (schema) => ({\n\ttype: \"object\",\n\tjsonSchema: async () => await schema.jsonSchema,\n\tasync validatePartialResult({ value, textDelta }) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: {\n\t\t\t\tpartial: value,\n\t\t\t\ttextDelta\n\t\t\t}\n\t\t};\n\t},\n\tasync validateFinalResult(value) {\n\t\treturn safeValidateTypes({\n\t\t\tvalue,\n\t\t\tschema\n\t\t});\n\t},\n\tcreateElementStream() {\n\t\tthrow new UnsupportedFunctionalityError$1({ functionality: \"element streams in object mode\" });\n\t}\n});\nconst arrayOutputStrategy = (schema) => {\n\treturn {\n\t\ttype: \"array\",\n\t\tjsonSchema: async () => {\n\t\t\tconst { $schema: _$schema, definitions, $defs, ...itemSchema } = await schema.jsonSchema;\n\t\t\treturn {\n\t\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\t\t...definitions != null && { definitions },\n\t\t\t\t...$defs != null && { $defs },\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { elements: {\n\t\t\t\t\ttype: \"array\",\n\t\t\t\t\titems: itemSchema\n\t\t\t\t} },\n\t\t\t\trequired: [\"elements\"],\n\t\t\t\tadditionalProperties: false\n\t\t\t};\n\t\t},\n\t\tasync validatePartialResult({ value, latestObject, isFirstDelta, isFinalDelta }) {\n\t\t\tif (!isJSONObject(value) || !isJSONArray(value.elements)) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError$1({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains an array of elements\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst inputArray = value.elements;\n\t\t\tconst resultArray = [];\n\t\t\tfor (let i = 0; i < inputArray.length; i++) {\n\t\t\t\tconst element = inputArray[i];\n\t\t\t\tconst result = await safeValidateTypes({\n\t\t\t\t\tvalue: element,\n\t\t\t\t\tschema\n\t\t\t\t});\n\t\t\t\tif (i === inputArray.length - 1 && !isFinalDelta) continue;\n\t\t\t\tif (!result.success) return result;\n\t\t\t\tresultArray.push(result.value);\n\t\t\t}\n\t\t\tconst publishedElementCount = latestObject?.length ?? 0;\n\t\t\tlet textDelta = \"\";\n\t\t\tif (isFirstDelta) textDelta += \"[\";\n\t\t\tif (publishedElementCount > 0) textDelta += \",\";\n\t\t\ttextDelta += resultArray.slice(publishedElementCount).map((element) => JSON.stringify(element)).join(\",\");\n\t\t\tif (isFinalDelta) textDelta += \"]\";\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: {\n\t\t\t\t\tpartial: resultArray,\n\t\t\t\t\ttextDelta\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tasync validateFinalResult(value) {\n\t\t\tif (!isJSONObject(value) || !isJSONArray(value.elements)) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError$1({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains an array of elements\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst inputArray = value.elements;\n\t\t\tconst resultArray = [];\n\t\t\tfor (const element of inputArray) {\n\t\t\t\tconst result = await safeValidateTypes({\n\t\t\t\t\tvalue: element,\n\t\t\t\t\tschema\n\t\t\t\t});\n\t\t\t\tif (!result.success) return result;\n\t\t\t\tresultArray.push(result.value);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: resultArray\n\t\t\t};\n\t\t},\n\t\tcreateElementStream(originalStream) {\n\t\t\tlet publishedElements = 0;\n\t\t\treturn createAsyncIterableStream(originalStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\tcase \"object\": {\n\t\t\t\t\t\tconst array = chunk.object;\n\t\t\t\t\t\tfor (; publishedElements < array.length; publishedElements++) controller.enqueue(array[publishedElements]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\tcase \"finish\":\n\t\t\t\t\tcase \"error\": break;\n\t\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t\t}\n\t\t\t} })));\n\t\t}\n\t};\n};\nconst enumOutputStrategy = (enumValues) => {\n\treturn {\n\t\ttype: \"enum\",\n\t\tjsonSchema: async () => ({\n\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\ttype: \"object\",\n\t\t\tproperties: { result: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tenum: enumValues\n\t\t\t} },\n\t\t\trequired: [\"result\"],\n\t\t\tadditionalProperties: false\n\t\t}),\n\t\tasync validateFinalResult(value) {\n\t\t\tif (!isJSONObject(value) || typeof value.result !== \"string\") return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError$1({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains a string in the \\\"result\\\" property.\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst result = value.result;\n\t\t\treturn enumValues.includes(result) ? {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: result\n\t\t\t} : {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError$1({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be a string in the enum\"\n\t\t\t\t})\n\t\t\t};\n\t\t},\n\t\tasync validatePartialResult({ value, textDelta }) {\n\t\t\tif (!isJSONObject(value) || typeof value.result !== \"string\") return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError$1({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains a string in the \\\"result\\\" property.\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst result = value.result;\n\t\t\tconst possibleEnumValues = enumValues.filter((enumValue) => enumValue.startsWith(result));\n\t\t\tif (value.result.length === 0 || possibleEnumValues.length === 0) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError$1({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be a string in the enum\"\n\t\t\t\t})\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: {\n\t\t\t\t\tpartial: possibleEnumValues.length > 1 ? result : possibleEnumValues[0],\n\t\t\t\t\ttextDelta\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tcreateElementStream() {\n\t\t\tthrow new UnsupportedFunctionalityError$1({ functionality: \"element streams in enum mode\" });\n\t\t}\n\t};\n};\nfunction getOutputStrategy({ output, schema, enumValues }) {\n\tswitch (output) {\n\t\tcase \"object\": return objectOutputStrategy(asSchema$1(schema));\n\t\tcase \"array\": return arrayOutputStrategy(asSchema$1(schema));\n\t\tcase \"enum\": return enumOutputStrategy(enumValues);\n\t\tcase \"no-schema\": return noSchemaOutputStrategy;\n\t\tdefault: throw new Error(`Unsupported output: ${output}`);\n\t}\n}\n//#endregion\n//#region src/generate-object/parse-and-validate-object-result.ts\n/**\n* Parses and validates a result string by parsing it as JSON and validating against the output strategy.\n*\n* @param result - The result string to parse and validate\n* @param outputStrategy - The output strategy containing validation logic\n* @param context - Additional context for error reporting\n* @returns The validated result\n* @throws NoObjectGeneratedError if parsing or validation fails\n*/\nasync function parseAndValidateObjectResult(result, outputStrategy, context) {\n\tconst parseResult = await safeParseJSON({ text: result });\n\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\tmessage: \"No object generated: could not parse the response.\",\n\t\tcause: parseResult.error,\n\t\ttext: result,\n\t\tresponse: context.response,\n\t\tusage: context.usage,\n\t\tfinishReason: context.finishReason\n\t});\n\tconst validationResult = await outputStrategy.validateFinalResult(parseResult.value, {\n\t\ttext: result,\n\t\tresponse: context.response,\n\t\tusage: context.usage\n\t});\n\tif (!validationResult.success) throw new NoObjectGeneratedError({\n\t\tmessage: \"No object generated: response did not match schema.\",\n\t\tcause: validationResult.error,\n\t\ttext: result,\n\t\tresponse: context.response,\n\t\tusage: context.usage,\n\t\tfinishReason: context.finishReason\n\t});\n\treturn validationResult.value;\n}\n/**\n* Parses and validates a result string by parsing it as JSON and validating against the output strategy.\n* If the result cannot be parsed, it attempts to repair the result using the repairText function.\n*\n* @param result - The result string to parse and validate\n* @param outputStrategy - The output strategy containing validation logic\n* @param repairText - A function that attempts to repair the result string\n* @param context - Additional context for error reporting\n* @returns The validated result\n* @throws NoObjectGeneratedError if parsing or validation fails\n*/\nasync function parseAndValidateObjectResultWithRepair(result, outputStrategy, repairText, context) {\n\ttry {\n\t\treturn await parseAndValidateObjectResult(result, outputStrategy, context);\n\t} catch (error) {\n\t\tif (repairText != null && NoObjectGeneratedError.isInstance(error) && (JSONParseError$1.isInstance(error.cause) || TypeValidationError$1.isInstance(error.cause))) {\n\t\t\tconst repairedText = await repairText({\n\t\t\t\ttext: result,\n\t\t\t\terror: error.cause\n\t\t\t});\n\t\t\tif (repairedText === null) throw error;\n\t\t\treturn await parseAndValidateObjectResult(repairedText, outputStrategy, context);\n\t\t}\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/generate-object/validate-object-generation-input.ts\nfunction validateObjectGenerationInput({ output, schema, schemaName, schemaDescription, enumValues }) {\n\tif (output != null && output !== \"object\" && output !== \"array\" && output !== \"enum\" && output !== \"no-schema\") throw new InvalidArgumentError({\n\t\tparameter: \"output\",\n\t\tvalue: output,\n\t\tmessage: \"Invalid output type.\"\n\t});\n\tif (output === \"no-schema\") {\n\t\tif (schema != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is not supported for no-schema output.\"\n\t\t});\n\t\tif (schemaDescription != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaDescription\",\n\t\t\tvalue: schemaDescription,\n\t\t\tmessage: \"Schema description is not supported for no-schema output.\"\n\t\t});\n\t\tif (schemaName != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaName\",\n\t\t\tvalue: schemaName,\n\t\t\tmessage: \"Schema name is not supported for no-schema output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for no-schema output.\"\n\t\t});\n\t}\n\tif (output === \"object\") {\n\t\tif (schema == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is required for object output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for object output.\"\n\t\t});\n\t}\n\tif (output === \"array\") {\n\t\tif (schema == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Element schema is required for array output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for array output.\"\n\t\t});\n\t}\n\tif (output === \"enum\") {\n\t\tif (schema != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is not supported for enum output.\"\n\t\t});\n\t\tif (schemaDescription != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaDescription\",\n\t\t\tvalue: schemaDescription,\n\t\t\tmessage: \"Schema description is not supported for enum output.\"\n\t\t});\n\t\tif (schemaName != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaName\",\n\t\t\tvalue: schemaName,\n\t\t\tmessage: \"Schema name is not supported for enum output.\"\n\t\t});\n\t\tif (enumValues == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are required for enum output.\"\n\t\t});\n\t\tfor (const value of enumValues) if (typeof value !== \"string\") throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue,\n\t\t\tmessage: \"Enum values must be strings.\"\n\t\t});\n\t}\n}\n//#endregion\n//#region src/generate-object/generate-object.ts\nconst originalGenerateId$1 = createIdGenerator$1({\n\tprefix: \"aiobj\",\n\tsize: 24\n});\n/**\n* Generate a structured, typed object for a given prompt and schema using a language model.\n*\n* This function does not stream the output. If you want to stream the output, use `streamObject` instead.\n*\n* @param model - The language model to use.\n*\n* @param system - A system message that will be part of the prompt.\n* @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n* @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n* @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.\n*\n* @param maxOutputTokens - Maximum number of tokens to generate.\n* @param temperature - Temperature setting.\n* The value is passed through to the provider. The range depends on the provider and model.\n* It is recommended to set either `temperature` or `topP`, but not both.\n* @param topP - Nucleus sampling.\n* The value is passed through to the provider. The range depends on the provider and model.\n* It is recommended to set either `temperature` or `topP`, but not both.\n* @param topK - Only sample from the top K options for each subsequent token.\n* Used to remove \"long tail\" low probability responses.\n* Recommended for advanced use cases only. You usually only need to use temperature.\n* @param presencePenalty - Presence penalty setting.\n* It affects the likelihood of the model to repeat information that is already in the prompt.\n* The value is passed through to the provider. The range depends on the provider and model.\n* @param frequencyPenalty - Frequency penalty setting.\n* It affects the likelihood of the model to repeatedly use the same words or phrases.\n* The value is passed through to the provider. The range depends on the provider and model.\n* @param stopSequences - Stop sequences.\n* If set, the model will stop generating text when one of the stop sequences is generated.\n* @param seed - The seed (integer) to use for random sampling.\n* If set and supported by the model, calls will generate deterministic results.\n*\n* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n*\n* @param schema - The schema of the object that the model should generate.\n* @param schemaName - Optional name of the output that should be generated.\n* Used by some providers for additional LLM guidance, e.g.\n* via tool or schema name.\n* @param schemaDescription - Optional description of the output that should be generated.\n* Used by some providers for additional LLM guidance, e.g.\n* via tool or schema description.\n*\n* @param output - The type of the output.\n*\n* - 'object': The output is an object.\n* - 'array': The output is an array.\n* - 'enum': The output is an enum.\n* - 'no-schema': The output is not a schema.\n*\n* @param repairText - A function that attempts to repair the raw output of the model\n* to enable JSON parsing.\n* @param experimental_repairText - Deprecated alias for `repairText`.\n*\n* @param telemetry - Optional telemetry configuration.\n*\n* @param providerOptions - Additional provider-specific options. They are passed through\n* to the provider from the AI SDK and enable provider-specific\n* functionality that can be fully encapsulated in the provider.\n*\n* @param onStart - Callback invoked when generation begins, before the LLM call.\n* @param experimental_onStart - Deprecated alias for `onStart`.\n* @param onStepStart - Callback invoked when the model call begins.\n* @param experimental_onStepStart - Deprecated alias for `onStepStart`.\n* @param onStepEnd - Callback invoked when the model call completes with the raw result.\n* @param onStepFinish - Deprecated alias for `onStepEnd`.\n* @param onFinish - Callback invoked when the entire operation completes with the parsed object.\n*\n* @returns\n* A result object that contains the generated object, the finish reason, the token usage, and additional information.\n*\n* @deprecated Use `generateText` with an `output` setting instead.\n*/\nasync function generateObject(options) {\n\tlogWarnings({ warnings: [{\n\t\ttype: \"deprecated\",\n\t\tsetting: \"generateObject\",\n\t\tmessage: \"Use generateText with an output setting instead.\"\n\t}] });\n\tconst { model: modelArg, output = \"object\", instructions, system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, headers, experimental_repairText, repairText = experimental_repairText, experimental_telemetry, telemetry = experimental_telemetry, experimental_download: download, providerOptions, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onStepEnd, onStepFinish, onFinish, _internal: { generateId = originalGenerateId$1, currentDate = () => /* @__PURE__ */ new Date() } = {}, ...settings } = options;\n\tconst model = resolveLanguageModel(modelArg);\n\tconst enumValues = \"enum\" in options ? options.enum : void 0;\n\tconst { schema: inputSchema, schemaDescription, schemaName } = \"schema\" in options ? options : {};\n\tvalidateObjectGenerationInput({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tenumValues\n\t});\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst outputStrategy = getOutputStrategy({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tenumValues\n\t});\n\tconst callSettings = prepareLanguageModelCallOptions(settings);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst telemetryDispatcher = createTelemetryDispatcher({ telemetry });\n\tconst resolvedOnStart = onStart ?? experimental_onStart;\n\tconst resolvedOnStepStart = onStepStart ?? experimental_onStepStart;\n\tconst resolvedOnStepEnd = onStepEnd ?? onStepFinish;\n\tconst jsonSchema = await outputStrategy.jsonSchema();\n\tconst callId = generateId();\n\tawait notify({\n\t\tevent: {\n\t\t\tcallId,\n\t\t\toperationId: \"ai.generateObject\",\n\t\t\tprovider: model.provider,\n\t\t\tmodelId: model.modelId,\n\t\t\tsystem: instructions ?? system,\n\t\t\tprompt,\n\t\t\tmessages,\n\t\t\tmaxOutputTokens: callSettings.maxOutputTokens,\n\t\t\ttemperature: callSettings.temperature,\n\t\t\ttopP: callSettings.topP,\n\t\t\ttopK: callSettings.topK,\n\t\t\tpresencePenalty: callSettings.presencePenalty,\n\t\t\tfrequencyPenalty: callSettings.frequencyPenalty,\n\t\t\tseed: callSettings.seed,\n\t\t\tmaxRetries,\n\t\t\theaders: headersWithUserAgent,\n\t\t\tproviderOptions,\n\t\t\toutput: outputStrategy.type,\n\t\t\tschema: jsonSchema,\n\t\t\tschemaName,\n\t\t\tschemaDescription\n\t\t},\n\t\tcallbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n\t});\n\ttry {\n\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\tprompt: await standardizePrompt({\n\t\t\t\tinstructions,\n\t\t\t\tsystem,\n\t\t\t\tprompt,\n\t\t\t\tmessages,\n\t\t\t\tallowSystemInMessages\n\t\t\t}),\n\t\t\tsupportedUrls: await model.supportedUrls,\n\t\t\tdownload,\n\t\t\tabortSignal,\n\t\t\tprovider: model.provider.split(\".\")[0]\n\t\t});\n\t\tawait notify({\n\t\t\tevent: {\n\t\t\t\tcallId,\n\t\t\t\tstepNumber: 0,\n\t\t\t\tprovider: model.provider,\n\t\t\t\tmodelId: model.modelId,\n\t\t\t\tproviderOptions,\n\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\tpromptMessages\n\t\t\t},\n\t\t\tcallbacks: [resolvedOnStepStart, telemetryDispatcher.onObjectStepStart]\n\t\t});\n\t\tconst generateResult = await retry(() => model.doGenerate({\n\t\t\tresponseFormat: {\n\t\t\t\ttype: \"json\",\n\t\t\t\tschema: jsonSchema,\n\t\t\t\tname: schemaName,\n\t\t\t\tdescription: schemaDescription\n\t\t\t},\n\t\t\t...prepareLanguageModelCallOptions(settings),\n\t\t\tprompt: promptMessages,\n\t\t\tproviderOptions,\n\t\t\tabortSignal,\n\t\t\theaders: headersWithUserAgent\n\t\t}));\n\t\tconst responseData = {\n\t\t\tid: generateResult.response?.id ?? generateId(),\n\t\t\ttimestamp: generateResult.response?.timestamp ?? currentDate(),\n\t\t\tmodelId: generateResult.response?.modelId ?? model.modelId,\n\t\t\theaders: generateResult.response?.headers,\n\t\t\tbody: generateResult.response?.body\n\t\t};\n\t\tconst text = extractTextContent(generateResult.content);\n\t\tconst reasoning = extractReasoningContent(generateResult.content);\n\t\tif (text === void 0) throw new NoObjectGeneratedError({\n\t\t\tmessage: \"No object generated: the model did not return a response.\",\n\t\t\tresponse: responseData,\n\t\t\tusage: asLanguageModelUsage(generateResult.usage),\n\t\t\tfinishReason: generateResult.finishReason.unified\n\t\t});\n\t\tconst finishReason = generateResult.finishReason.unified;\n\t\tconst usage = asLanguageModelUsage(generateResult.usage);\n\t\tconst warnings = generateResult.warnings;\n\t\tconst resultProviderMetadata = generateResult.providerMetadata;\n\t\tconst request = generateResult.request ?? {};\n\t\tconst response = responseData;\n\t\tlogWarnings({\n\t\t\twarnings,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.modelId\n\t\t});\n\t\tawait notify({\n\t\t\tevent: {\n\t\t\t\tcallId,\n\t\t\t\tstepNumber: 0,\n\t\t\t\tprovider: model.provider,\n\t\t\t\tmodelId: model.modelId,\n\t\t\t\tfinishReason,\n\t\t\t\tusage,\n\t\t\t\tobjectText: text,\n\t\t\t\tmsToFirstChunk: void 0,\n\t\t\t\treasoning,\n\t\t\t\twarnings,\n\t\t\t\trequest,\n\t\t\t\tresponse,\n\t\t\t\tproviderMetadata: resultProviderMetadata\n\t\t\t},\n\t\t\tcallbacks: [resolvedOnStepEnd, telemetryDispatcher.onObjectStepEnd]\n\t\t});\n\t\tconst object = await parseAndValidateObjectResultWithRepair(text, outputStrategy, repairText, {\n\t\t\tresponse,\n\t\t\tusage,\n\t\t\tfinishReason\n\t\t});\n\t\tawait notify({\n\t\t\tevent: {\n\t\t\t\tcallId,\n\t\t\t\tobject,\n\t\t\t\terror: void 0,\n\t\t\t\treasoning,\n\t\t\t\tfinishReason,\n\t\t\t\tusage,\n\t\t\t\twarnings,\n\t\t\t\trequest,\n\t\t\t\tresponse,\n\t\t\t\tproviderMetadata: resultProviderMetadata\n\t\t\t},\n\t\t\tcallbacks: [onFinish, telemetryDispatcher.onEnd]\n\t\t});\n\t\treturn new DefaultGenerateObjectResult({\n\t\t\tobject,\n\t\t\treasoning,\n\t\t\tfinishReason,\n\t\t\tusage,\n\t\t\twarnings,\n\t\t\trequest,\n\t\t\tresponse,\n\t\t\tproviderMetadata: resultProviderMetadata\n\t\t});\n\t} catch (error) {\n\t\tawait telemetryDispatcher.onError?.({\n\t\t\tcallId,\n\t\t\terror\n\t\t});\n\t\tthrow wrapGatewayError(error);\n\t}\n}\nvar DefaultGenerateObjectResult = class {\n\tconstructor(options) {\n\t\tthis.object = options.object;\n\t\tthis.finishReason = options.finishReason;\n\t\tthis.usage = options.usage;\n\t\tthis.warnings = options.warnings;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.response = options.response;\n\t\tthis.request = options.request;\n\t\tthis.reasoning = options.reasoning;\n\t}\n\ttoJsonResponse(init) {\n\t\treturn new Response(JSON.stringify(this.object), {\n\t\t\tstatus: init?.status ?? 200,\n\t\t\theaders: prepareHeaders(init?.headers, { \"content-type\": \"application/json; charset=utf-8\" })\n\t\t});\n\t}\n};\n//#endregion\n//#region src/util/cosine-similarity.ts\n/**\n* Calculates the cosine similarity between two vectors. This is a useful metric for\n* comparing the similarity of two vectors such as embeddings.\n*\n* @param vector1 - The first vector.\n* @param vector2 - The second vector.\n*\n* @returns The cosine similarity between vector1 and vector2, or 0 if either vector is the zero vector.\n*\n* @throws {InvalidArgumentError} If the vectors do not have the same length.\n*/\nfunction cosineSimilarity(vector1, vector2) {\n\tif (vector1.length !== vector2.length) throw new InvalidArgumentError({\n\t\tparameter: \"vector1,vector2\",\n\t\tvalue: {\n\t\t\tvector1Length: vector1.length,\n\t\t\tvector2Length: vector2.length\n\t\t},\n\t\tmessage: `Vectors must have the same length`\n\t});\n\tconst n = vector1.length;\n\tif (n === 0) return 0;\n\tlet magnitudeSquared1 = 0;\n\tlet magnitudeSquared2 = 0;\n\tlet dotProduct = 0;\n\tfor (let i = 0; i < n; i++) {\n\t\tconst value1 = vector1[i];\n\t\tconst value2 = vector2[i];\n\t\tmagnitudeSquared1 += value1 * value1;\n\t\tmagnitudeSquared2 += value2 * value2;\n\t\tdotProduct += value1 * value2;\n\t}\n\treturn magnitudeSquared1 === 0 || magnitudeSquared2 === 0 ? 0 : dotProduct / (Math.sqrt(magnitudeSquared1) * Math.sqrt(magnitudeSquared2));\n}\n//#endregion\n//#region src/util/download/create-download.ts\n/**\n* Creates a download function with configurable options.\n*\n* @param options - Configuration options for the download function.\n* @param options.maxBytes - Maximum allowed download size in bytes. Default: 2 GiB.\n* @returns A download function that can be passed to `transcribe()` or `experimental_generateVideo()`.\n*/\nfunction createDownload(options) {\n\treturn ({ url, abortSignal }) => download({\n\t\turl,\n\t\tmaxBytes: options?.maxBytes,\n\t\tabortSignal\n\t});\n}\n//#endregion\n//#region src/util/data-url.ts\nconst { atob: atob$1 } = globalThis;\n/**\n* Converts a data URL of type text/* to a text string.\n*\n* @throws {InvalidArgumentError} If the data URL is malformed or cannot be decoded.\n*/\nfunction getTextFromDataUrl(dataUrl) {\n\tconst [header, base64Content] = dataUrl.split(\",\");\n\tconst mediaType = header.split(\";\")[0].split(\":\")[1];\n\tconst charsetMatch = /(?:^|;)\\s*charset\\s*=\\s*(?:\"([^\"]+)\"|([^;\\s]+))/i.exec(header);\n\tconst charset = charsetMatch?.[1] ?? charsetMatch?.[2];\n\tif (mediaType == null || base64Content == null) throw new InvalidArgumentError({\n\t\tparameter: \"dataUrl\",\n\t\tvalue: dataUrl,\n\t\tmessage: \"Invalid data URL format\"\n\t});\n\ttry {\n\t\tconst byteString = atob$1(base64Content);\n\t\tif (charset == null) return byteString;\n\t\treturn new TextDecoder(charset).decode(Uint8Array.from(byteString, (byte) => byte.codePointAt(0)));\n\t} catch {\n\t\tthrow new InvalidArgumentError({\n\t\t\tparameter: \"dataUrl\",\n\t\t\tvalue: dataUrl,\n\t\t\tmessage: \"Error decoding data URL\"\n\t\t});\n\t}\n}\n//#endregion\n//#region src/util/serial-job-executor.ts\nvar SerialJobExecutor = class {\n\tconstructor() {\n\t\tthis.queue = [];\n\t\tthis.isProcessing = false;\n\t\tthis.idleWaiters = [];\n\t}\n\tasync processQueue() {\n\t\tif (this.isProcessing) return;\n\t\tthis.isProcessing = true;\n\t\ttry {\n\t\t\twhile (this.queue.length > 0) {\n\t\t\t\tawait this.queue[0]();\n\t\t\t\tthis.queue.shift();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.isProcessing = false;\n\t\t\tfor (const resolve of this.idleWaiters.splice(0)) resolve();\n\t\t}\n\t}\n\tasync run(job) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.queue.push(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait job();\n\t\t\t\t\tresolve();\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis.processQueue();\n\t\t});\n\t}\n\tasync waitForIdle() {\n\t\tif (!this.isProcessing && this.queue.length === 0) return;\n\t\tawait new Promise((resolve) => {\n\t\t\tthis.idleWaiters.push(resolve);\n\t\t});\n\t}\n};\n//#endregion\n//#region src/util/simulate-readable-stream.ts\n/**\n* Creates a ReadableStream that emits the provided values with an optional delay between each value.\n*\n* @param options - The configuration options\n* @param options.chunks - Array of values to be emitted by the stream\n* @param options.initialDelayInMs - Optional initial delay in milliseconds before emitting the first value (default: 0). Can be set to `null` to skip the initial delay. The difference between `initialDelayInMs: null` and `initialDelayInMs: 0` is that `initialDelayInMs: null` will emit the values without any delay, while `initialDelayInMs: 0` will emit the values with a delay of 0 milliseconds.\n* @param options.chunkDelayInMs - Optional delay in milliseconds between emitting each value (default: 0). Can be set to `null` to skip the delay. The difference between `chunkDelayInMs: null` and `chunkDelayInMs: 0` is that `chunkDelayInMs: null` will emit the values without any delay, while `chunkDelayInMs: 0` will emit the values with a delay of 0 milliseconds.\n* @returns A ReadableStream that emits the provided values\n*/\nfunction simulateReadableStream({ chunks, initialDelayInMs = 0, chunkDelayInMs = 0, _internal }) {\n\tconst delay$3 = _internal?.delay ?? delay;\n\tlet index = 0;\n\treturn new ReadableStream({ async pull(controller) {\n\t\tif (index < chunks.length) {\n\t\t\tawait delay$3(index === 0 ? initialDelayInMs : chunkDelayInMs);\n\t\t\tcontroller.enqueue(chunks[index++]);\n\t\t} else controller.close();\n\t} });\n}\n//#endregion\n//#region src/generate-object/stream-object.ts\nconst originalGenerateId = createIdGenerator$1({\n\tprefix: \"aiobj\",\n\tsize: 24\n});\nasync function markPromiseAsHandled(promise) {\n\ttry {\n\t\tawait promise;\n\t} catch {}\n}\n/**\n* Generate a structured, typed object for a given prompt and schema using a language model.\n*\n* This function streams the output. If you do not want to stream the output, use `generateObject` instead.\n*\n* @param model - The language model to use.\n*\n* @param system - A system message that will be part of the prompt.\n* @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n* @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n* @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.\n*\n* @param maxOutputTokens - Maximum number of tokens to generate.\n* @param temperature - Temperature setting.\n* The value is passed through to the provider. The range depends on the provider and model.\n* It is recommended to set either `temperature` or `topP`, but not both.\n* @param topP - Nucleus sampling.\n* The value is passed through to the provider. The range depends on the provider and model.\n* It is recommended to set either `temperature` or `topP`, but not both.\n* @param topK - Only sample from the top K options for each subsequent token.\n* Used to remove \"long tail\" low probability responses.\n* Recommended for advanced use cases only. You usually only need to use temperature.\n* @param presencePenalty - Presence penalty setting.\n* It affects the likelihood of the model to repeat information that is already in the prompt.\n* The value is passed through to the provider. The range depends on the provider and model.\n* @param frequencyPenalty - Frequency penalty setting.\n* It affects the likelihood of the model to repeatedly use the same words or phrases.\n* The value is passed through to the provider. The range depends on the provider and model.\n* @param stopSequences - Stop sequences.\n* If set, the model will stop generating text when one of the stop sequences is generated.\n* @param seed - The seed (integer) to use for random sampling.\n* If set and supported by the model, calls will generate deterministic results.\n*\n* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n*\n* @param schema - The schema of the object that the model should generate.\n* @param schemaName - Optional name of the output that should be generated.\n* Used by some providers for additional LLM guidance, e.g.\n* via tool or schema name.\n* @param schemaDescription - Optional description of the output that should be generated.\n* Used by some providers for additional LLM guidance, e.g.\n* via tool or schema description.\n*\n* @param output - The type of the output.\n*\n* - 'object': The output is an object.\n* - 'array': The output is an array.\n* - 'enum': The output is an enum.\n* - 'no-schema': The output is not a schema.\n*\n* @param repairText - A function that attempts to repair the raw output of the model\n* to enable JSON parsing.\n* @param experimental_repairText - Deprecated alias for `repairText`.\n*\n* @param telemetry - Optional telemetry configuration.\n*\n* @param providerOptions - Additional provider-specific options. They are passed through\n* to the provider from the AI SDK and enable provider-specific\n* functionality that can be fully encapsulated in the provider.\n*\n* @returns\n* A result object for accessing the partial object stream and additional information.\n*\n* @deprecated Use `streamText` with an `output` setting instead.\n*/\nfunction streamObject(options) {\n\tlogWarnings({ warnings: [{\n\t\ttype: \"deprecated\",\n\t\tsetting: \"streamObject\",\n\t\tmessage: \"Use streamText with an output setting instead.\"\n\t}] });\n\tconst { model, output = \"object\", instructions, system, prompt, messages, allowSystemInMessages, maxRetries, abortSignal, headers, experimental_repairText, repairText = experimental_repairText, experimental_telemetry, telemetry = experimental_telemetry, experimental_download: download, providerOptions, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onStepEnd, onStepFinish, onError = ({ error }) => {\n\t\tconsole.error(error);\n\t}, onFinish, _internal: { generateId = originalGenerateId, currentDate = () => /* @__PURE__ */ new Date(), now: now$1 = now } = {}, ...settings } = options;\n\tconst enumValues = \"enum\" in options && options.enum ? options.enum : void 0;\n\tconst { schema: inputSchema, schemaDescription, schemaName } = \"schema\" in options ? options : {};\n\tvalidateObjectGenerationInput({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tenumValues\n\t});\n\treturn new DefaultStreamObjectResult({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders,\n\t\tsettings,\n\t\tmaxRetries,\n\t\tabortSignal,\n\t\toutputStrategy: getOutputStrategy({\n\t\t\toutput,\n\t\t\tschema: inputSchema,\n\t\t\tenumValues\n\t\t}),\n\t\tinstructions,\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tproviderOptions,\n\t\trepairText,\n\t\tonStart: onStart ?? experimental_onStart,\n\t\tonStepStart: onStepStart ?? experimental_onStepStart,\n\t\tonStepFinish: onStepEnd ?? onStepFinish,\n\t\tonError,\n\t\tonFinish,\n\t\tdownload,\n\t\tgenerateId,\n\t\tcurrentDate,\n\t\tnow: now$1\n\t});\n}\nvar DefaultStreamObjectResult = class {\n\tconstructor({ model: modelArg, headers, telemetry, settings, maxRetries: maxRetriesArg, abortSignal, outputStrategy, instructions, system, prompt, messages, allowSystemInMessages, schemaName, schemaDescription, providerOptions, repairText, onStart, onStepStart, onStepFinish, onError, onFinish, download, generateId, currentDate, now }) {\n\t\tthis._object = new DelayedPromise();\n\t\tthis._usage = new DelayedPromise();\n\t\tthis._providerMetadata = new DelayedPromise();\n\t\tthis._warnings = new DelayedPromise();\n\t\tthis._request = new DelayedPromise();\n\t\tthis._response = new DelayedPromise();\n\t\tthis._finishReason = new DelayedPromise();\n\t\tconst model = resolveLanguageModel(modelArg);\n\t\tconst { maxRetries, retry } = prepareRetries({\n\t\t\tmaxRetries: maxRetriesArg,\n\t\t\tabortSignal\n\t\t});\n\t\tconst callSettings = prepareLanguageModelCallOptions(settings);\n\t\tconst telemetryDispatcher = createTelemetryDispatcher({ telemetry });\n\t\tconst self = this;\n\t\tconst stitchableStream = createStitchableStream();\n\t\tconst eventProcessor = new TransformStream({ transform(chunk, controller) {\n\t\t\tcontroller.enqueue(chunk);\n\t\t\tif (chunk.type === \"error\") notify({\n\t\t\t\tevent: { error: wrapGatewayError(chunk.error) },\n\t\t\t\tcallbacks: onError\n\t\t\t});\n\t\t} });\n\t\tthis.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);\n\t\tconst callId = generateId();\n\t\t(async () => {\n\t\t\tconst jsonSchema = await outputStrategy.jsonSchema();\n\t\t\tawait notify({\n\t\t\t\tevent: {\n\t\t\t\t\tcallId,\n\t\t\t\t\toperationId: \"ai.streamObject\",\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\tsystem: instructions ?? system,\n\t\t\t\t\tprompt,\n\t\t\t\t\tmessages,\n\t\t\t\t\tmaxOutputTokens: callSettings.maxOutputTokens,\n\t\t\t\t\ttemperature: callSettings.temperature,\n\t\t\t\t\ttopP: callSettings.topP,\n\t\t\t\t\ttopK: callSettings.topK,\n\t\t\t\t\tpresencePenalty: callSettings.presencePenalty,\n\t\t\t\t\tfrequencyPenalty: callSettings.frequencyPenalty,\n\t\t\t\t\tseed: callSettings.seed,\n\t\t\t\t\tmaxRetries,\n\t\t\t\t\theaders,\n\t\t\t\t\tproviderOptions,\n\t\t\t\t\toutput: outputStrategy.type,\n\t\t\t\t\tschema: jsonSchema,\n\t\t\t\t\tschemaName,\n\t\t\t\t\tschemaDescription\n\t\t\t\t},\n\t\t\t\tcallbacks: [onStart, telemetryDispatcher.onStart]\n\t\t\t});\n\t\t\tconst standardizedPrompt = await standardizePrompt({\n\t\t\t\tinstructions,\n\t\t\t\tsystem,\n\t\t\t\tprompt,\n\t\t\t\tmessages,\n\t\t\t\tallowSystemInMessages\n\t\t\t});\n\t\t\tconst callOptions = {\n\t\t\t\tresponseFormat: {\n\t\t\t\t\ttype: \"json\",\n\t\t\t\t\tschema: jsonSchema,\n\t\t\t\t\tname: schemaName,\n\t\t\t\t\tdescription: schemaDescription\n\t\t\t\t},\n\t\t\t\t...prepareLanguageModelCallOptions(settings),\n\t\t\t\tprompt: await convertToLanguageModelPrompt({\n\t\t\t\t\tprompt: standardizedPrompt,\n\t\t\t\t\tsupportedUrls: await model.supportedUrls,\n\t\t\t\t\tdownload,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\tprovider: model.provider.split(\".\")[0]\n\t\t\t\t}),\n\t\t\t\tproviderOptions,\n\t\t\t\tabortSignal,\n\t\t\t\theaders,\n\t\t\t\tincludeRawChunks: false\n\t\t\t};\n\t\t\tawait notify({\n\t\t\t\tevent: {\n\t\t\t\t\tcallId,\n\t\t\t\t\tstepNumber: 0,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\tproviderOptions,\n\t\t\t\t\theaders,\n\t\t\t\t\tpromptMessages: callOptions.prompt\n\t\t\t\t},\n\t\t\t\tcallbacks: [onStepStart, telemetryDispatcher.onObjectStepStart]\n\t\t\t});\n\t\t\tconst transformer = { transform: (chunk, controller) => {\n\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\tcontroller.enqueue(chunk.delta);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\tcase \"finish\":\n\t\t\t\t\tcase \"error\":\n\t\t\t\t\tcase \"stream-start\": controller.enqueue(chunk);\n\t\t\t\t}\n\t\t\t} };\n\t\t\tconst startTimestampMs = now();\n\t\t\tconst { stream, response, request } = await retry(() => model.doStream(callOptions));\n\t\t\tself._request.resolve(request ?? {});\n\t\t\tlet warnings;\n\t\t\tlet usage = createNullLanguageModelUsage();\n\t\t\tlet finishReason;\n\t\t\tlet providerMetadata;\n\t\t\tlet object;\n\t\t\tlet error;\n\t\t\tlet terminalError;\n\t\t\tlet msToFirstChunk = void 0;\n\t\t\tlet accumulatedText = \"\";\n\t\t\tlet textDelta = \"\";\n\t\t\tlet fullResponse = {\n\t\t\t\tid: generateId(),\n\t\t\t\ttimestamp: currentDate(),\n\t\t\t\tmodelId: model.modelId\n\t\t\t};\n\t\t\tlet latestObjectJson = void 0;\n\t\t\tlet latestObject = void 0;\n\t\t\tlet isFirstChunk = true;\n\t\t\tlet isFirstDelta = true;\n\t\t\tconst transformedStream = stream.pipeThrough(new TransformStream(transformer)).pipeThrough(new TransformStream({\n\t\t\t\tasync transform(chunk, controller) {\n\t\t\t\t\tif (typeof chunk === \"object\" && chunk.type === \"stream-start\") {\n\t\t\t\t\t\twarnings = chunk.warnings;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (isFirstChunk) {\n\t\t\t\t\t\tmsToFirstChunk = now() - startTimestampMs;\n\t\t\t\t\t\tisFirstChunk = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof chunk === \"string\") {\n\t\t\t\t\t\taccumulatedText += chunk;\n\t\t\t\t\t\ttextDelta += chunk;\n\t\t\t\t\t\tconst { value: currentObjectJson, state: parseState } = await parsePartialJson(accumulatedText);\n\t\t\t\t\t\tif (currentObjectJson !== void 0 && !isDeepEqualData(latestObjectJson, currentObjectJson)) {\n\t\t\t\t\t\t\tconst validationResult = await outputStrategy.validatePartialResult({\n\t\t\t\t\t\t\t\tvalue: currentObjectJson,\n\t\t\t\t\t\t\t\ttextDelta,\n\t\t\t\t\t\t\t\tlatestObject,\n\t\t\t\t\t\t\t\tisFirstDelta,\n\t\t\t\t\t\t\t\tisFinalDelta: parseState === \"successful-parse\"\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (validationResult.success && !isDeepEqualData(latestObject, validationResult.value.partial)) {\n\t\t\t\t\t\t\t\tlatestObjectJson = currentObjectJson;\n\t\t\t\t\t\t\t\tlatestObject = validationResult.value.partial;\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tobject: latestObject\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\ttextDelta: validationResult.value.textDelta\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\ttextDelta = \"\";\n\t\t\t\t\t\t\t\tisFirstDelta = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\t\t\tfullResponse = {\n\t\t\t\t\t\t\t\tid: chunk.id ?? fullResponse.id,\n\t\t\t\t\t\t\t\ttimestamp: chunk.timestamp ?? fullResponse.timestamp,\n\t\t\t\t\t\t\t\tmodelId: chunk.modelId ?? fullResponse.modelId\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\t\tif (terminalError === void 0) {\n\t\t\t\t\t\t\t\tconst wrappedError = wrapGatewayError(chunk.error);\n\t\t\t\t\t\t\t\tterminalError = { error: wrappedError };\n\t\t\t\t\t\t\t\terror = wrappedError;\n\t\t\t\t\t\t\t\tfinishReason = \"error\";\n\t\t\t\t\t\t\t\tself.rejectResultPromises(wrappedError);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"finish\":\n\t\t\t\t\t\t\tif (textDelta !== \"\") controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\ttextDelta\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tfinishReason = terminalError === void 0 ? chunk.finishReason.unified : \"error\";\n\t\t\t\t\t\t\tusage = asLanguageModelUsage(chunk.usage);\n\t\t\t\t\t\t\tproviderMetadata = chunk.providerMetadata;\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\tfinishReason,\n\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\tresponse: fullResponse\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tlogWarnings({\n\t\t\t\t\t\t\t\twarnings: warnings ?? [],\n\t\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\t\tmodel: model.modelId\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (terminalError !== void 0) break;\n\t\t\t\t\t\t\tself._usage.resolve(usage);\n\t\t\t\t\t\t\tself._providerMetadata.resolve(providerMetadata);\n\t\t\t\t\t\t\tself._warnings.resolve(warnings);\n\t\t\t\t\t\t\tself._response.resolve({\n\t\t\t\t\t\t\t\t...fullResponse,\n\t\t\t\t\t\t\t\theaders: response?.headers\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tself._finishReason.resolve(finishReason ?? \"other\");\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tobject = await parseAndValidateObjectResultWithRepair(accumulatedText, outputStrategy, repairText, {\n\t\t\t\t\t\t\t\t\tresponse: fullResponse,\n\t\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\t\tfinishReason\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tself._object.resolve(object);\n\t\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\t\terror = e;\n\t\t\t\t\t\t\t\tself._object.reject(e);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault: controller.enqueue(chunk);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tasync flush(controller) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst finalUsage = usage ?? {\n\t\t\t\t\t\t\tpromptTokens: NaN,\n\t\t\t\t\t\t\tcompletionTokens: NaN,\n\t\t\t\t\t\t\ttotalTokens: NaN\n\t\t\t\t\t\t};\n\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\tstepNumber: 0,\n\t\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\t\t\tfinishReason: finishReason ?? \"other\",\n\t\t\t\t\t\t\t\tusage: finalUsage,\n\t\t\t\t\t\t\t\tobjectText: accumulatedText,\n\t\t\t\t\t\t\t\tmsToFirstChunk,\n\t\t\t\t\t\t\t\treasoning: void 0,\n\t\t\t\t\t\t\t\twarnings,\n\t\t\t\t\t\t\t\trequest: request ?? {},\n\t\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\t\t...fullResponse,\n\t\t\t\t\t\t\t\t\theaders: response?.headers\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tproviderMetadata\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcallbacks: [onStepFinish, telemetryDispatcher.onObjectStepEnd]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\tobject,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\treasoning: void 0,\n\t\t\t\t\t\t\t\tfinishReason: finishReason ?? \"other\",\n\t\t\t\t\t\t\t\tusage: finalUsage,\n\t\t\t\t\t\t\t\twarnings,\n\t\t\t\t\t\t\t\trequest: request ?? {},\n\t\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\t\t...fullResponse,\n\t\t\t\t\t\t\t\t\theaders: response?.headers\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tproviderMetadata\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcallbacks: [onFinish, telemetryDispatcher.onEnd]\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\terror\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}));\n\t\t\tstitchableStream.addStream(transformedStream, { onError(error) {\n\t\t\t\tconst wrappedError = wrapGatewayError(error);\n\t\t\t\tself.rejectResultPromises(wrappedError);\n\t\t\t\tnotify({\n\t\t\t\t\tevent: { error: wrappedError },\n\t\t\t\t\tcallbacks: onError\n\t\t\t\t});\n\t\t\t} });\n\t\t})().catch(async (error) => {\n\t\t\tself.rejectResultPromises(error);\n\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\tcallId,\n\t\t\t\terror\n\t\t\t});\n\t\t\tstitchableStream.addStream(new ReadableStream({ start(controller) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tcontroller.close();\n\t\t\t} }));\n\t\t}).finally(() => {\n\t\t\tstitchableStream.close();\n\t\t});\n\t\tthis.outputStrategy = outputStrategy;\n\t}\n\trejectResultPromises(error) {\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._object,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._usage,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._providerMetadata,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._warnings,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._request,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._response,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._finishReason,\n\t\t\terror\n\t\t});\n\t}\n\trejectResultPromise({ delayedPromise, error }) {\n\t\tif (delayedPromise.isPending()) {\n\t\t\tdelayedPromise.reject(error);\n\t\t\tmarkPromiseAsHandled(delayedPromise.promise);\n\t\t}\n\t}\n\tget object() {\n\t\treturn this._object.promise;\n\t}\n\tget usage() {\n\t\treturn this._usage.promise;\n\t}\n\tget providerMetadata() {\n\t\treturn this._providerMetadata.promise;\n\t}\n\tget warnings() {\n\t\treturn this._warnings.promise;\n\t}\n\tget request() {\n\t\treturn this._request.promise;\n\t}\n\tget response() {\n\t\treturn this._response.promise;\n\t}\n\tget finishReason() {\n\t\treturn this._finishReason.promise;\n\t}\n\tget partialObjectStream() {\n\t\treturn createAsyncIterableStream(this.baseStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"object\":\n\t\t\t\t\tcontroller.enqueue(chunk.object);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"text-delta\":\n\t\t\t\tcase \"finish\":\n\t\t\t\tcase \"error\": break;\n\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t}\n\t\t} })));\n\t}\n\tget elementStream() {\n\t\treturn this.outputStrategy.createElementStream(this.baseStream);\n\t}\n\tget textStream() {\n\t\treturn createAsyncIterableStream(this.baseStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"text-delta\":\n\t\t\t\t\tcontroller.enqueue(chunk.textDelta);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"object\":\n\t\t\t\tcase \"finish\":\n\t\t\t\tcase \"error\": break;\n\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t}\n\t\t} })));\n\t}\n\tget fullStream() {\n\t\treturn createAsyncIterableStream(this.baseStream);\n\t}\n\tpipeTextStreamToResponse(response, init) {\n\t\treturn pipeTextStreamToResponse({\n\t\t\tresponse,\n\t\t\tstream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n\ttoTextStreamResponse(init) {\n\t\treturn createTextStreamResponse({\n\t\t\tstream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n};\n//#endregion\n//#region src/generate-speech/generated-audio-file.ts\nvar DefaultGeneratedAudioFile = class extends DefaultGeneratedFile {\n\tconstructor({ data, mediaType }) {\n\t\tsuper({\n\t\t\tdata,\n\t\t\tmediaType\n\t\t});\n\t\tlet format = \"mp3\";\n\t\tif (mediaType) {\n\t\t\tconst mediaTypeParts = mediaType.split(\"/\");\n\t\t\tif (mediaTypeParts.length === 2) {\n\t\t\t\tif (mediaType !== \"audio/mpeg\") format = mediaTypeParts[1];\n\t\t\t}\n\t\t}\n\t\tif (!format) throw new InvalidResponseDataError$1({\n\t\t\tdata: mediaType,\n\t\t\tmessage: `Could not determine audio format from media type: ${mediaType}`\n\t\t});\n\t\tthis.format = format;\n\t}\n};\n//#endregion\n//#region src/generate-speech/generate-speech.ts\nconst originalGenerateCallId$3 = createIdGenerator$1({\n\tprefix: \"call\",\n\tsize: 24\n});\n/**\n* Generates speech audio using a speech model.\n*\n* @param model - The speech model to use.\n* @param text - The text to convert to speech.\n* @param voice - The voice to use for speech generation.\n* @param outputFormat - The output format to use for speech generation e.g. \"mp3\", \"wav\", etc.\n* @param instructions - Instructions for the speech generation e.g. \"Speak in a slow and steady tone\".\n* @param speed - The speed of the speech generation.\n* @param language - The language for speech generation (ISO 639-1 code e.g. \"en\", \"es\", \"fr\") or \"auto\" for automatic detection.\n* @param providerOptions - Additional provider-specific options that are passed through to the provider\n* as body parameters.\n* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n* @param telemetry - Optional telemetry configuration.\n*\n* @returns A result object that contains the generated audio data.\n*/\nasync function generateSpeech({ model, text, voice, outputFormat, instructions, speed, language, providerOptions = {}, maxRetries: maxRetriesArg, abortSignal, headers, telemetry, _internal: { generateCallId = originalGenerateCallId$3 } = {} }) {\n\tconst resolvedModel = resolveSpeechModel(model);\n\tif (!resolvedModel) throw new Error(\"Model could not be resolved\");\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst callId = generateCallId();\n\tconst telemetryDispatcher = createTelemetryDispatcher({ telemetry });\n\tconst runInTracingChannelSpan = telemetryDispatcher.runInTracingChannelSpan ?? (async ({ execute }) => await execute());\n\tconst startEvent = {\n\t\tcallId,\n\t\toperationId: \"ai.generateSpeech\",\n\t\tprovider: resolvedModel.provider,\n\t\tmodelId: resolvedModel.modelId,\n\t\ttext,\n\t\tvoice,\n\t\toutputFormat,\n\t\tinstructions,\n\t\tspeed,\n\t\tlanguage,\n\t\tmaxRetries,\n\t\theaders,\n\t\tproviderOptions\n\t};\n\treturn await runInTracingChannelSpan({\n\t\ttype: \"generateSpeech\",\n\t\tevent: startEvent,\n\t\texecute: async () => {\n\t\t\tawait notify({\n\t\t\t\tevent: startEvent,\n\t\t\t\tcallbacks: [telemetryDispatcher.onStart]\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tconst result = await retry(() => resolvedModel.doGenerate({\n\t\t\t\t\ttext,\n\t\t\t\t\tvoice,\n\t\t\t\t\toutputFormat,\n\t\t\t\t\tinstructions,\n\t\t\t\t\tspeed,\n\t\t\t\t\tlanguage,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\tproviderOptions\n\t\t\t\t}));\n\t\t\t\tif (!result.audio || result.audio.length === 0) throw new NoSpeechGeneratedError({ responses: [result.response] });\n\t\t\t\tlogWarnings({\n\t\t\t\t\twarnings: result.warnings,\n\t\t\t\t\tprovider: resolvedModel.provider,\n\t\t\t\t\tmodel: resolvedModel.modelId\n\t\t\t\t});\n\t\t\t\tconst detectedMediaType = detectMediaType({\n\t\t\t\t\tdata: result.audio,\n\t\t\t\t\ttopLevelType: \"audio\"\n\t\t\t\t});\n\t\t\t\tconst audio = new DefaultGeneratedAudioFile({\n\t\t\t\t\tdata: result.audio,\n\t\t\t\t\tmediaType: detectedMediaType ?? getResponseAudioMediaType(result.response.headers) ?? getOutputFormatMediaType(outputFormat) ?? \"audio/mp3\"\n\t\t\t\t});\n\t\t\t\tif (telemetryDispatcher.onEnd != null) await notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\tcallId,\n\t\t\t\t\t\toperationId: \"ai.generateSpeech\",\n\t\t\t\t\t\tprovider: resolvedModel.provider,\n\t\t\t\t\t\tmodelId: resolvedModel.modelId,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\taudio: {\n\t\t\t\t\t\t\tbyteLength: getBase64OrBinaryByteLength(result.audio),\n\t\t\t\t\t\t\tmediaType: audio.mediaType,\n\t\t\t\t\t\t\tformat: audio.format\n\t\t\t\t\t\t},\n\t\t\t\t\t\tusage: result.usage,\n\t\t\t\t\t\twarnings: result.warnings,\n\t\t\t\t\t\tproviderMetadata: result.providerMetadata,\n\t\t\t\t\t\tresponse: getTelemetryResponseMetadata(result.response)\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: [telemetryDispatcher.onEnd]\n\t\t\t\t});\n\t\t\t\treturn new DefaultSpeechResult({\n\t\t\t\t\taudio,\n\t\t\t\t\twarnings: result.warnings,\n\t\t\t\t\tresponses: [result.response],\n\t\t\t\t\tproviderMetadata: result.providerMetadata\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\t\tcallId,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t});\n}\nfunction getBase64OrBinaryByteLength(audio) {\n\tif (audio instanceof Uint8Array) return audio.byteLength;\n\tlet characterCount = 0;\n\tlet lastCharacter = \"\";\n\tlet secondLastCharacter = \"\";\n\tfor (const character of audio) {\n\t\tif (/\\s/.test(character)) continue;\n\t\tcharacterCount++;\n\t\tsecondLastCharacter = lastCharacter;\n\t\tlastCharacter = character;\n\t}\n\tconst padding = lastCharacter === \"=\" ? secondLastCharacter === \"=\" ? 2 : 1 : 0;\n\treturn Math.floor(characterCount * 3 / 4) - padding;\n}\nfunction getTelemetryResponseMetadata(response) {\n\treturn {\n\t\ttimestamp: response.timestamp,\n\t\tmodelId: response.modelId,\n\t\theaders: response.headers\n\t};\n}\nfunction getResponseAudioMediaType(headers) {\n\tconst mediaType = Object.entries(headers ?? {}).find(([name]) => name.toLowerCase() === \"content-type\")?.[1];\n\tif (mediaType == null) return;\n\tconst normalizedMediaType = mediaType.split(\";\", 1)[0].trim().toLowerCase();\n\tif (normalizedMediaType.length === 0) return;\n\treturn normalizedMediaType.startsWith(\"audio/\") ? normalizedMediaType : void 0;\n}\nfunction getOutputFormatMediaType(outputFormat) {\n\tif (outputFormat == null) return;\n\tswitch (outputFormat.trim().toLowerCase()) {\n\t\tcase \"pcm\":\n\t\tcase \"audio/pcm\": return \"audio/pcm\";\n\t\tcase \"audio/l16\": return \"audio/l16\";\n\t\tcase \"mulaw\":\n\t\tcase \"audio/mulaw\": return \"audio/mulaw\";\n\t\tcase \"alaw\":\n\t\tcase \"audio/alaw\": return \"audio/alaw\";\n\t\tdefault: return;\n\t}\n}\nvar DefaultSpeechResult = class {\n\tconstructor(options) {\n\t\tthis.audio = options.audio;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = options.providerMetadata ?? {};\n\t}\n};\n//#endregion\n//#region src/generate-speech/index.ts\n/**\n* @deprecated Use `generateSpeech` instead.\n*/\nconst experimental_generateSpeech = (options) => {\n\tlogWarnings({ warnings: [{\n\t\ttype: \"deprecated\",\n\t\tsetting: \"experimental_generateSpeech\",\n\t\tmessage: \"Use generateSpeech instead.\"\n\t}] });\n\treturn generateSpeech(options);\n};\n//#endregion\n//#region src/generate-text/prune-messages.ts\n/**\n* Prunes model messages from a list of model messages.\n*\n* @param messages - The list of model messages to prune.\n* @param reasoning - How to remove reasoning content from assistant messages. Default is `'none'`.\n* @param toolCalls - How to prune tool call/results/approval content. Default is `[]`.\n* @param emptyMessages - Whether to keep or remove messages whose content is empty after pruning. Default is `'remove'`.\n*\n* @returns The pruned list of model messages.\n*/\nfunction pruneMessages({ messages, reasoning = \"none\", toolCalls = [], emptyMessages = \"remove\" }) {\n\tif (reasoning === \"all\" || reasoning === \"before-last-message\") messages = messages.map((message, messageIndex) => {\n\t\tif (message.role !== \"assistant\" || typeof message.content === \"string\" || reasoning === \"before-last-message\" && messageIndex === messages.length - 1) return message;\n\t\treturn {\n\t\t\t...message,\n\t\t\tcontent: message.content.filter((part) => part.type !== \"reasoning\" && part.type !== \"reasoning-file\")\n\t\t};\n\t});\n\tif (toolCalls === \"none\") toolCalls = [];\n\telse if (toolCalls === \"all\") toolCalls = [{ type: \"all\" }];\n\telse if (toolCalls === \"before-last-message\") toolCalls = [{ type: \"before-last-message\" }];\n\telse if (typeof toolCalls === \"string\") toolCalls = [{ type: toolCalls }];\n\tfor (const toolCall of toolCalls) {\n\t\tconst keepLastMessagesCount = toolCall.type === \"all\" ? void 0 : toolCall.type === \"before-last-message\" ? 1 : Number(toolCall.type.slice(12).slice(0, -9));\n\t\tconst keptToolCallIds = /* @__PURE__ */ new Set();\n\t\tconst keptApprovalIds = /* @__PURE__ */ new Set();\n\t\tif (keepLastMessagesCount != null && keepLastMessagesCount !== 0) {\n\t\t\tfor (const message of messages.slice(-keepLastMessagesCount)) if ((message.role === \"assistant\" || message.role === \"tool\") && typeof message.content !== \"string\") {\n\t\t\t\tfor (const part of message.content) if (part.type === \"tool-call\" || part.type === \"tool-result\") keptToolCallIds.add(part.toolCallId);\n\t\t\t\telse if (part.type === \"tool-approval-request\" || part.type === \"tool-approval-response\") keptApprovalIds.add(part.approvalId);\n\t\t\t}\n\t\t}\n\t\tconst toolCallIdToToolName = /* @__PURE__ */ new Map();\n\t\tfor (const message of messages) if ((message.role === \"assistant\" || message.role === \"tool\") && typeof message.content !== \"string\") {\n\t\t\tfor (const part of message.content) if (part.type === \"tool-call\" || part.type === \"tool-result\") toolCallIdToToolName.set(part.toolCallId, part.toolName);\n\t\t}\n\t\tconst approvalIdToToolCallId = /* @__PURE__ */ new Map();\n\t\tconst approvalIdToToolName = /* @__PURE__ */ new Map();\n\t\tfor (const message of messages) if ((message.role === \"assistant\" || message.role === \"tool\") && typeof message.content !== \"string\") {\n\t\t\tfor (const part of message.content) if (part.type === \"tool-approval-request\") {\n\t\t\t\tapprovalIdToToolCallId.set(part.approvalId, part.toolCallId);\n\t\t\t\tconst toolName = toolCallIdToToolName.get(part.toolCallId);\n\t\t\t\tif (toolName != null) approvalIdToToolName.set(part.approvalId, toolName);\n\t\t\t}\n\t\t}\n\t\tfor (const approvalId of keptApprovalIds) {\n\t\t\tconst toolCallId = approvalIdToToolCallId.get(approvalId);\n\t\t\tif (toolCallId != null) keptToolCallIds.add(toolCallId);\n\t\t}\n\t\tmessages = messages.map((message, messageIndex) => {\n\t\t\tif (message.role !== \"assistant\" && message.role !== \"tool\" || typeof message.content === \"string\" || keepLastMessagesCount && messageIndex >= messages.length - keepLastMessagesCount) return message;\n\t\t\treturn {\n\t\t\t\t...message,\n\t\t\t\tcontent: message.content.filter((part) => {\n\t\t\t\t\tif (part.type !== \"tool-call\" && part.type !== \"tool-result\" && part.type !== \"tool-approval-request\" && part.type !== \"tool-approval-response\") return true;\n\t\t\t\t\tif ((part.type === \"tool-call\" || part.type === \"tool-result\") && keptToolCallIds.has(part.toolCallId) || (part.type === \"tool-approval-request\" || part.type === \"tool-approval-response\") && keptApprovalIds.has(part.approvalId)) return true;\n\t\t\t\t\tconst partToolName = part.type === \"tool-call\" || part.type === \"tool-result\" ? part.toolName : approvalIdToToolName.get(part.approvalId);\n\t\t\t\t\treturn toolCall.tools != null && partToolName != null && !toolCall.tools.includes(partToolName);\n\t\t\t\t})\n\t\t\t};\n\t\t});\n\t}\n\tif (emptyMessages === \"remove\") messages = messages.filter((message) => message.content.length > 0);\n\treturn messages;\n}\n//#endregion\n//#region src/generate-text/smooth-stream.ts\nconst CHUNKING_REGEXPS = {\n\tword: /\\S+\\s+/m,\n\tline: /\\n+/m\n};\nfunction isDocumentHidden() {\n\treturn typeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n}\n/**\n* Smooths text and reasoning streaming output.\n*\n* @param delayInMs - The delay in milliseconds between each chunk. Defaults to 10ms. Can be set to `null` to skip the delay. The delay is skipped while the document is hidden (e.g. browser background tabs), where timer throttling would otherwise stall the stream.\n* @param chunking - Controls how the text is chunked for streaming. Use \"word\" to stream word by word (default), \"line\" to stream line by line, provide a custom RegExp pattern that does not match the empty string for custom chunking, provide an Intl.Segmenter for locale-aware word segmentation (recommended for CJK languages), or provide a custom ChunkDetector function.\n*\n* @returns A transform stream that smooths text streaming output.\n*/\nfunction smoothStream({ delayInMs = 10, chunking = \"word\", _internal: { delay: delay$2 = delay } = {} } = {}) {\n\tlet detectChunk;\n\tif (chunking != null && typeof chunking === \"object\" && \"segment\" in chunking && typeof chunking.segment === \"function\") {\n\t\tconst segmenter = chunking;\n\t\tdetectChunk = (buffer) => {\n\t\t\tif (buffer.length === 0) return null;\n\t\t\treturn segmenter.segment(buffer)[Symbol.iterator]().next().value?.segment || null;\n\t\t};\n\t} else if (typeof chunking === \"function\") detectChunk = (buffer) => {\n\t\tconst match = chunking(buffer);\n\t\tif (match == null) return null;\n\t\tif (!match.length) throw new Error(`Chunking function must return a non-empty string.`);\n\t\tif (!buffer.startsWith(match)) throw new Error(`Chunking function must return a match that is a prefix of the buffer. Received: \"${match}\" expected to start with \"${buffer}\"`);\n\t\treturn match;\n\t};\n\telse {\n\t\tconst chunkingRegex = typeof chunking === \"string\" ? CHUNKING_REGEXPS[chunking] : chunking instanceof RegExp ? chunking : void 0;\n\t\tif (chunkingRegex == null) throw new InvalidArgumentError$1({\n\t\t\targument: \"chunking\",\n\t\t\tmessage: `Chunking must be \"word\", \"line\", a RegExp, an Intl.Segmenter, or a ChunkDetector function. Received: ${chunking}`\n\t\t});\n\t\tdetectChunk = (buffer) => {\n\t\t\tconst lastIndex = chunkingRegex.lastIndex;\n\t\t\tchunkingRegex.lastIndex = 0;\n\t\t\tlet match;\n\t\t\ttry {\n\t\t\t\tmatch = chunkingRegex.exec(buffer);\n\t\t\t} finally {\n\t\t\t\tchunkingRegex.lastIndex = lastIndex;\n\t\t\t}\n\t\t\tif (!match) return null;\n\t\t\tif (!match[0].length) throw new Error(`Chunking RegExp must not match an empty string.`);\n\t\t\treturn buffer.slice(0, match.index) + match[0];\n\t\t};\n\t}\n\treturn () => {\n\t\tlet buffer = \"\";\n\t\tlet id = \"\";\n\t\tlet type = void 0;\n\t\tlet providerMetadata = void 0;\n\t\tfunction flushBuffer(controller) {\n\t\t\tif (type !== void 0 && (buffer.length > 0 || providerMetadata != null)) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype,\n\t\t\t\t\ttext: buffer,\n\t\t\t\t\tid,\n\t\t\t\t\t...providerMetadata != null ? { providerMetadata } : {}\n\t\t\t\t});\n\t\t\t\tbuffer = \"\";\n\t\t\t\tproviderMetadata = void 0;\n\t\t\t}\n\t\t}\n\t\treturn new TransformStream({ async transform(chunk, controller) {\n\t\t\tif (chunk.type !== \"text-delta\" && chunk.type !== \"reasoning-delta\") {\n\t\t\t\tflushBuffer(controller);\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (chunk.text.length === 0 && chunk.providerMetadata != null) {\n\t\t\t\tflushBuffer(controller);\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (buffer.length > 0 && (chunk.type !== type || chunk.id !== id || providerMetadata != null || chunk.providerMetadata != null)) flushBuffer(controller);\n\t\t\tbuffer += chunk.text;\n\t\t\tid = chunk.id;\n\t\t\ttype = chunk.type;\n\t\t\tproviderMetadata = chunk.providerMetadata;\n\t\t\tlet match;\n\t\t\twhile ((match = detectChunk(buffer)) != null) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype,\n\t\t\t\t\ttext: match,\n\t\t\t\t\tid,\n\t\t\t\t\t...providerMetadata != null ? { providerMetadata } : {}\n\t\t\t\t});\n\t\t\t\tbuffer = buffer.slice(match.length);\n\t\t\t\tawait delay$2(isDocumentHidden() ? null : delayInMs);\n\t\t\t}\n\t\t\tif (buffer.length === 0) providerMetadata = void 0;\n\t\t} });\n\t};\n}\n//#endregion\n//#region src/generate-text/tool-fingerprint.ts\n/**\n* Tag a tool description for hashing. A function description is developer-owned\n* (evaluated per call from local context), not a server-controlled \"rug pull\"\n* vector, so only its presence is pinned, not its identity. The tagged shape\n* keeps a literal string equal to some placeholder from ever hashing like a\n* function.\n*/\nfunction tagDescription(description) {\n\tif (typeof description === \"string\") return {\n\t\ttype: \"string\",\n\t\tvalue: description\n\t};\n\tif (description == null) return { type: \"none\" };\n\treturn { type: \"function\" };\n}\n/**\n* Fingerprint the server-controlled, security-relevant fields of each tool in a\n* `ToolSet`: `description` (string form only), the resolved input JSON schema,\n* and `title`. Returns a map of tool name to a stable digest.\n*\n* Capture a baseline at trust time (first connect, human-reviewed) and compare\n* later fetches with {@link detectToolDrift} to catch MCP tool-definition drift\n* (\"rug pull\"). Baseline storage and the drift response are the app's concern.\n*/\nasync function fingerprintTools(tools) {\n\tconst entries = await Promise.all(Object.keys(tools).map(async (name) => {\n\t\tconst tool = tools[name];\n\t\treturn [name, await hashCanonical({\n\t\t\tdescription: tagDescription(tool.description),\n\t\t\tinputSchema: await asSchema$1(tool.inputSchema).jsonSchema,\n\t\t\ttitle: tool.title\n\t\t})];\n\t}));\n\treturn Object.fromEntries(entries);\n}\n/**\n* Pure diff of two fingerprint maps produced by {@link fingerprintTools}.\n* `added`/`removed` are tools present in only one map; `changed` are tools whose\n* pinned definition differs. Uses own-property lookups so a tool literally named\n* `constructor` or `toString` diffs correctly.\n*/\nfunction detectToolDrift(current, baseline) {\n\tconst added = [];\n\tconst removed = [];\n\tconst changed = [];\n\tfor (const name of Object.keys(current)) if (!Object.hasOwn(baseline, name)) added.push(name);\n\telse if (current[name] !== baseline[name]) changed.push(name);\n\tfor (const name of Object.keys(baseline)) if (!Object.hasOwn(current, name)) removed.push(name);\n\treturn {\n\t\tadded,\n\t\tremoved,\n\t\tchanged\n\t};\n}\n//#endregion\n//#region src/generate-video/generate-video.ts\n/**\n* Generates videos using a video model.\n*\n* @param model - The video model to use.\n* @param prompt - The prompt that should be used to generate the video.\n* @param n - Number of videos to generate. Default: 1.\n* @param aspectRatio - Aspect ratio of the videos to generate. Must have the format `{width}:{height}`, or `'adaptive'`.\n* @param resolution - Resolution of the videos to generate. Must have the format `{width}x{height}`.\n* @param duration - Duration of the video in seconds.\n* @param fps - Frames per second for the video.\n* @param seed - Seed for the video generation.\n* @param frameImages - Role-tagged image inputs for image-to-video and first-last-frame generation.\n* @param inputReferences - Reference image or video inputs for reference-to-video generation.\n* @param generateAudio - Whether the model should generate audio alongside the video.\n* @param providerOptions - Additional provider-specific options that are passed through to the provider\n* as body parameters.\n* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n* @param poll - Polling configuration for models that support the start/status flow.\n* @param webhook - Webhook factory for models that support the start/status flow.\n*\n* @returns A result object that contains the generated videos.\n*/\nconst defaultDownload$1 = createDownload();\nasync function experimental_generateVideo({ model: modelArg, prompt: promptArg, n = 1, maxVideosPerCall, aspectRatio, resolution, duration, fps, seed, frameImages, inputReferences, generateAudio, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, download: downloadFn = defaultDownload$1, poll, webhook }) {\n\tconst model = resolveVideoModel(modelArg);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst { prompt, resolvedImage, normalizedFrameImages, effectiveInputReferences, warnings } = normalizeVideoCallInputs({\n\t\tpromptArg,\n\t\tframeImages,\n\t\tinputReferences\n\t});\n\tconst maxVideosPerCallWithDefault = maxVideosPerCall ?? await invokeModelMaxVideosPerCall(model) ?? 1;\n\tconst hasStartStatus = model.doStart != null && model.doStatus != null;\n\tconst useStartStatus = hasStartStatus && (poll != null || webhook != null || model.doGenerate == null);\n\tif (model.doGenerate == null && !hasStartStatus) throw new Error(`Video model ${model.modelId} does not implement doGenerate or doStart/doStatus.`);\n\tif ((poll != null || webhook != null) && !hasStartStatus) logWarnings({\n\t\twarnings: [{\n\t\t\ttype: \"other\",\n\t\t\tmessage: \"poll/webhook options were provided but the model does not support doStart/doStatus. Falling back to doGenerate.\"\n\t\t}],\n\t\tprovider: model.provider,\n\t\tmodel: model.modelId\n\t});\n\tconst callCount = Math.ceil(n / maxVideosPerCallWithDefault);\n\tconst callVideoCounts = Array.from({ length: callCount }, (_, index) => {\n\t\tconst remaining = n - index * maxVideosPerCallWithDefault;\n\t\treturn Math.min(remaining, maxVideosPerCallWithDefault);\n\t});\n\tconst results = await Promise.all(callVideoCounts.map(async (callVideoCount) => {\n\t\tconst callOptions = {\n\t\t\tprompt,\n\t\t\tn: callVideoCount,\n\t\t\taspectRatio,\n\t\t\tresolution,\n\t\t\tduration,\n\t\t\tfps,\n\t\t\tseed,\n\t\t\timage: resolvedImage,\n\t\t\tframeImages: normalizedFrameImages,\n\t\t\tinputReferences: effectiveInputReferences,\n\t\t\tgenerateAudio,\n\t\t\tproviderOptions: providerOptions ?? {},\n\t\t\theaders: headersWithUserAgent,\n\t\t\tabortSignal\n\t\t};\n\t\tif (useStartStatus) return executeStartStatusFlow({\n\t\t\tmodel,\n\t\t\tcallOptions,\n\t\t\tpoll,\n\t\t\twebhook,\n\t\t\tmaxRetries,\n\t\t\tretry\n\t\t});\n\t\treturn retry(() => model.doGenerate(callOptions));\n\t}));\n\tconst videos = [];\n\tconst responses = [];\n\tconst providerMetadata = {};\n\tfor (const result of results) {\n\t\tfor (const videoData of result.videos) switch (videoData.type) {\n\t\t\tcase \"url\": {\n\t\t\t\tconst { data, mediaType: downloadedMediaType } = await downloadFn({\n\t\t\t\t\turl: new URL(videoData.url),\n\t\t\t\t\tabortSignal\n\t\t\t\t});\n\t\t\t\tconst isUsableMediaType = (type) => !!type && type !== \"application/octet-stream\";\n\t\t\t\tconst mediaType = isUsableMediaType(videoData.mediaType) && videoData.mediaType || isUsableMediaType(downloadedMediaType) && downloadedMediaType || detectMediaType({\n\t\t\t\t\tdata,\n\t\t\t\t\ttopLevelType: \"video\"\n\t\t\t\t}) || \"video/mp4\";\n\t\t\t\tvideos.push(new DefaultGeneratedFile({\n\t\t\t\t\tdata,\n\t\t\t\t\tmediaType\n\t\t\t\t}));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"base64\":\n\t\t\t\tvideos.push(new DefaultGeneratedFile({\n\t\t\t\t\tdata: videoData.data,\n\t\t\t\t\tmediaType: videoData.mediaType || \"video/mp4\"\n\t\t\t\t}));\n\t\t\t\tbreak;\n\t\t\tcase \"binary\": {\n\t\t\t\tconst mediaType = videoData.mediaType || detectMediaType({\n\t\t\t\t\tdata: videoData.data,\n\t\t\t\t\ttopLevelType: \"video\"\n\t\t\t\t}) || \"video/mp4\";\n\t\t\t\tvideos.push(new DefaultGeneratedFile({\n\t\t\t\t\tdata: videoData.data,\n\t\t\t\t\tmediaType\n\t\t\t\t}));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\twarnings.push(...result.warnings);\n\t\tresponses.push({\n\t\t\ttimestamp: result.response.timestamp,\n\t\t\tmodelId: result.response.modelId,\n\t\t\theaders: result.response.headers,\n\t\t\tproviderMetadata: result.providerMetadata\n\t\t});\n\t\tif (result.providerMetadata != null) mergeProviderMetadata(providerMetadata, result.providerMetadata);\n\t}\n\tif (videos.length === 0) throw new NoVideoGeneratedError({ responses });\n\tif (warnings.length > 0) logWarnings({\n\t\twarnings,\n\t\tprovider: model.provider,\n\t\tmodel: model.modelId\n\t});\n\treturn {\n\t\tvideo: videos[0],\n\t\tvideos,\n\t\twarnings,\n\t\tresponses,\n\t\tproviderMetadata\n\t};\n}\nasync function executeStartStatusFlow({ model, callOptions, poll: pollConfig, webhook: webhookFactory, maxRetries, retry }) {\n\tconst earlyWarnings = [];\n\tlet webhookUrl;\n\tlet webhookReceived;\n\tif (webhookFactory != null) {\n\t\tif (model.handleWebhookOption != null) {\n\t\t\tconst result = await model.handleWebhookOption({ webhook: webhookFactory });\n\t\t\twebhookReceived = Promise.resolve(result.received);\n\t\t\twebhookReceived.catch(() => {});\n\t\t\twebhookUrl = result.webhookUrl;\n\t\t} else earlyWarnings.push({\n\t\t\ttype: \"unsupported\",\n\t\t\tfeature: \"webhook\",\n\t\t\tdetails: \"This model does not support webhooks. Falling back to polling.\"\n\t\t});\n\t}\n\tconst callerIdempotencyKey = Object.entries(callOptions.headers ?? {}).find(([key, value]) => key.toLowerCase() === \"idempotency-key\" && value !== void 0);\n\tconst startCallOptions = {\n\t\t...callOptions,\n\t\theaders: {\n\t\t\t...callOptions.headers,\n\t\t\t...callerIdempotencyKey ? {} : { \"idempotency-key\": `aisdk_vid_${generateId$1()}` }\n\t\t},\n\t\twebhookUrl\n\t};\n\tconst startResult = await retry(() => model.doStart(startCallOptions));\n\tconst allWarnings = [...earlyWarnings, ...startResult.warnings];\n\tlet operationProviderMetadata = startResult.providerMetadata == null ? void 0 : { ...startResult.providerMetadata };\n\tconst intervalMs = pollConfig?.intervalMs ?? 5e3;\n\tconst timeoutMs = pollConfig?.timeoutMs ?? 6e5;\n\tconst delay$1 = pollConfig?.delay ?? delay;\n\tconst startTime = Date.now();\n\tconst pollingTimeoutError = /* @__PURE__ */ new Error(`Video generation timed out after ${timeoutMs}ms.`);\n\tif (webhookReceived != null) await waitForWebhook({\n\t\treceived: webhookReceived,\n\t\ttimeoutMs,\n\t\tabortSignal: callOptions.abortSignal,\n\t\tdelay: delay$1\n\t});\n\twhile (true) {\n\t\tif (webhookReceived == null) {\n\t\t\tconst elapsedMs = Date.now() - startTime;\n\t\t\tif (elapsedMs >= timeoutMs) throw pollingTimeoutError;\n\t\t\tawait delay$1(Math.min(intervalMs, timeoutMs - elapsedMs), { abortSignal: callOptions.abortSignal });\n\t\t\tif (Date.now() - startTime >= timeoutMs) throw pollingTimeoutError;\n\t\t}\n\t\tlet statusResult;\n\t\tif (webhookReceived != null) statusResult = await retry(() => model.doStatus({\n\t\t\toperation: startResult.operation,\n\t\t\tabortSignal: callOptions.abortSignal,\n\t\t\theaders: callOptions.headers\n\t\t}));\n\t\telse {\n\t\t\tconst statusTimeoutController = new AbortController();\n\t\t\tconst statusAbortSignal = mergeAbortSignals(callOptions.abortSignal, statusTimeoutController.signal);\n\t\t\tconst statusTimeoutId = setTimeout(() => statusTimeoutController.abort(pollingTimeoutError), timeoutMs - (Date.now() - startTime));\n\t\t\tconst statusTimeoutPromise = new Promise((_, reject) => {\n\t\t\t\tstatusTimeoutController.signal.addEventListener(\"abort\", () => reject(pollingTimeoutError), { once: true });\n\t\t\t});\n\t\t\tconst { retry: statusRetry } = prepareRetries({\n\t\t\t\tmaxRetries,\n\t\t\t\tabortSignal: statusAbortSignal\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tstatusResult = await Promise.race([statusRetry(() => model.doStatus({\n\t\t\t\t\toperation: startResult.operation,\n\t\t\t\t\tabortSignal: statusAbortSignal,\n\t\t\t\t\theaders: callOptions.headers\n\t\t\t\t})), statusTimeoutPromise]);\n\t\t\t} catch (error) {\n\t\t\t\tif (statusTimeoutController.signal.aborted) throw pollingTimeoutError;\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tclearTimeout(statusTimeoutId);\n\t\t\t}\n\t\t}\n\t\tif (statusResult.status === \"error\") throw new Error(statusResult.error);\n\t\tif (statusResult.warnings != null) allWarnings.push(...statusResult.warnings);\n\t\tif (statusResult.providerMetadata != null) {\n\t\t\toperationProviderMetadata ??= {};\n\t\t\tmergeProviderMetadata(operationProviderMetadata, statusResult.providerMetadata);\n\t\t}\n\t\tif (statusResult.status === \"completed\") return {\n\t\t\tvideos: statusResult.videos,\n\t\t\twarnings: allWarnings,\n\t\t\tproviderMetadata: operationProviderMetadata,\n\t\t\tresponse: statusResult.response\n\t\t};\n\t\tif (webhookReceived != null) throw new Error(\"Video generation did not complete after webhook notification.\");\n\t}\n}\nasync function waitForWebhook({ received, timeoutMs, abortSignal, delay }) {\n\tconst timeoutController = typeof globalThis.AbortController === \"function\" ? new globalThis.AbortController() : void 0;\n\ttry {\n\t\tawait Promise.race([received, delay(timeoutMs, { abortSignal: timeoutController == null ? abortSignal : mergeAbortSignals(abortSignal, timeoutController.signal) }).then(() => {\n\t\t\tthrow new Error(`Video generation timed out after ${timeoutMs}ms.`);\n\t\t})]);\n\t} finally {\n\t\ttimeoutController?.abort();\n\t}\n}\nfunction mergeProviderMetadata(target, source) {\n\tfor (const [providerName, metadataValue] of Object.entries(source)) {\n\t\tconst existingMetadata = getOwn(target, providerName);\n\t\tif (existingMetadata != null && typeof existingMetadata === \"object\" && metadataValue != null && typeof metadataValue === \"object\") {\n\t\t\tsetOwn(target, providerName, {\n\t\t\t\t...existingMetadata,\n\t\t\t\t...metadataValue\n\t\t\t});\n\t\t\tif (\"videos\" in existingMetadata && Array.isArray(existingMetadata.videos) && \"videos\" in metadataValue && Array.isArray(metadataValue.videos)) target[providerName].videos = [...existingMetadata.videos, ...metadataValue.videos];\n\t\t} else setOwn(target, providerName, metadataValue);\n\t}\n}\nfunction normalizePrompt(promptArg) {\n\tif (typeof promptArg === \"string\") return {\n\t\tprompt: promptArg,\n\t\timage: void 0\n\t};\n\treturn {\n\t\tprompt: promptArg.text,\n\t\timage: promptArg.image != null ? normalizeImageData(promptArg.image) : void 0\n\t};\n}\n/**\n* Shared input normalization for `experimental_generateVideo` and\n* `experimental_startVideo`: prompt/image plus the frameImages /\n* inputReferences precedence rules and their warnings.\n*/\nfunction normalizeVideoCallInputs({ promptArg, frameImages, inputReferences }) {\n\tconst { prompt, image } = normalizePrompt(promptArg);\n\tconst normalizedFrameImages = frameImages?.flatMap((frame) => {\n\t\tconst normalizedImage = normalizeImageData(frame.image);\n\t\treturn normalizedImage != null ? [{\n\t\t\timage: normalizedImage,\n\t\t\tframeType: frame.frameType\n\t\t}] : [];\n\t});\n\tconst normalizedInputReferences = inputReferences?.flatMap((reference) => {\n\t\tconst normalized = normalizeReferenceData(reference);\n\t\treturn normalized != null ? [normalized] : [];\n\t});\n\tconst effectiveInputReferences = normalizedFrameImages != null && normalizedFrameImages.length > 0 ? void 0 : normalizedInputReferences;\n\tconst warnings = [];\n\tif (normalizedFrameImages != null && normalizedFrameImages.length > 0 && normalizedInputReferences != null && normalizedInputReferences.length > 0) warnings.push({\n\t\ttype: \"other\",\n\t\tmessage: \"inputReferences were ignored because frameImages were provided; frameImages and inputReferences cannot be combined.\"\n\t});\n\tconst firstFrameImage = normalizedFrameImages?.find((frame) => frame.frameType === \"first_frame\")?.image;\n\tif (image != null && firstFrameImage != null) warnings.push({\n\t\ttype: \"other\",\n\t\tmessage: \"prompt.image was ignored because a first_frame frameImage was provided; the first_frame frameImage takes precedence as the start image.\"\n\t});\n\treturn {\n\t\tprompt,\n\t\tresolvedImage: firstFrameImage ?? image,\n\t\tnormalizedFrameImages,\n\t\teffectiveInputReferences,\n\t\twarnings\n\t};\n}\nfunction detectFileMediaType(data, restrictToImages) {\n\treturn (restrictToImages ? detectMediaType({\n\t\tdata,\n\t\ttopLevelType: \"image\"\n\t}) : detectMediaType({ data })) ?? \"image/png\";\n}\n/**\n* Normalizes a {@link DataContent} image into a {@link Experimental_VideoModelV4File}.\n* Accepts a URL string, a data URL, a base64 string, or binary image data.\n*/\nfunction normalizeImageData(dataContent, { restrictToImages = true } = {}) {\n\tif (typeof dataContent === \"string\") {\n\t\tif (dataContent.startsWith(\"http://\") || dataContent.startsWith(\"https://\")) return {\n\t\t\ttype: \"url\",\n\t\t\turl: dataContent\n\t\t};\n\t\tif (dataContent.startsWith(\"data:\")) {\n\t\t\tconst { mediaType, base64Content } = splitDataUrl(dataContent);\n\t\t\tconst data = convertBase64ToUint8Array(base64Content ?? \"\");\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmediaType: mediaType ?? detectFileMediaType(data, restrictToImages),\n\t\t\t\tdata\n\t\t\t};\n\t\t}\n\t\tconst bytes = convertBase64ToUint8Array(dataContent);\n\t\treturn {\n\t\t\ttype: \"file\",\n\t\t\tmediaType: detectFileMediaType(bytes, restrictToImages),\n\t\t\tdata: bytes\n\t\t};\n\t}\n\tif (dataContent instanceof Uint8Array || dataContent instanceof ArrayBuffer) {\n\t\tconst bytes = dataContent instanceof Uint8Array ? dataContent : new Uint8Array(dataContent);\n\t\treturn {\n\t\t\ttype: \"file\",\n\t\t\tmediaType: detectFileMediaType(bytes, restrictToImages),\n\t\t\tdata: bytes\n\t\t};\n\t}\n}\n/**\n* Normalizes a reference input into a {@link Experimental_VideoModelV4File},\n* accepting either a plain {@link DataContent} or the object form that carries\n* an explicit `mediaType`.\n*/\nfunction normalizeReferenceData(reference) {\n\tif (!(typeof reference === \"object\" && reference != null && !(reference instanceof Uint8Array) && !(reference instanceof ArrayBuffer) && \"data\" in reference)) return normalizeImageData(reference, { restrictToImages: false });\n\tconst normalized = normalizeImageData(reference.data, { restrictToImages: false });\n\tif (normalized == null) return normalized;\n\treturn {\n\t\t...normalized,\n\t\t...reference.mediaType != null ? { mediaType: reference.mediaType } : {}\n\t};\n}\nasync function invokeModelMaxVideosPerCall(model) {\n\tif (typeof model.maxVideosPerCall === \"function\") return await model.maxVideosPerCall({ modelId: model.modelId });\n\treturn model.maxVideosPerCall;\n}\n//#endregion\n//#region src/generate-video/start-video.ts\n/**\n* Starts an asynchronous video generation and returns immediately with an\n* opaque `operation` reference — without waiting for the video to finish.\n*\n* This is the fire-and-forget counterpart to `experimental_generateVideo`:\n* use it to fan out many jobs, to submit from a process that will not stay\n* alive, or together with `webhookUrl` so the provider notifies your endpoint\n* at the terminal state. Check the outcome with `experimental_getVideoStatus`,\n* or let your webhook receiver fetch the result.\n*\n* @param model - The video model to use. Must implement `doStart`.\n* @param prompt - The prompt that should be used to generate the video.\n* @param n - Number of videos to generate. Default: 1. Must not exceed the\n* model's `maxVideosPerCall` — fan out with multiple `startVideo` calls.\n* @param aspectRatio - Aspect ratio of the videos to generate. Must have the format `{width}:{height}`, or `'adaptive'`.\n* @param resolution - Resolution of the videos to generate. Must have the format `{width}x${height}`.\n* @param duration - Duration of the video in seconds.\n* @param fps - Frames per second for the video.\n* @param seed - Seed for the video generation.\n* @param frameImages - Role-tagged image inputs for image-to-video and first-last-frame generation.\n* @param inputReferences - Reference image or video inputs for reference-to-video generation.\n* @param generateAudio - Whether the model should generate audio alongside the video.\n* @param providerOptions - Additional provider-specific options that are passed through to the provider\n* as body parameters.\n* @param maxRetries - Maximum number of retries for the start call. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n* @param webhookUrl - A URL the provider should notify when the generation\n* reaches a terminal state.\n*\n* @returns A result object that contains the opaque `operation` reference,\n* warnings, provider metadata (including the provider's job id), and response\n* metadata.\n*/\nasync function experimental_startVideo({ model: modelArg, prompt: promptArg, n = 1, maxVideosPerCall, aspectRatio, resolution, duration, fps, seed, frameImages, inputReferences, generateAudio, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, webhookUrl }) {\n\tconst model = resolveVideoModel(modelArg);\n\tif (model.doStart == null) throw new Error(`Video model ${model.modelId} does not implement doStart. Use generateVideo for models without an asynchronous start/status flow.`);\n\tif (!Number.isInteger(n) || n < 1) throw new Error(`Invalid n: expected a positive integer, received ${JSON.stringify(n)}.`);\n\tconst knownMaxVideosPerCall = maxVideosPerCall ?? (typeof model.maxVideosPerCall === \"function\" ? await model.maxVideosPerCall({ modelId: model.modelId }) : model.maxVideosPerCall);\n\tif (knownMaxVideosPerCall != null && n > knownMaxVideosPerCall) throw new Error(`Video model ${model.modelId} supports at most ${knownMaxVideosPerCall} video(s) per call, but ${n} were requested. Split the batch across multiple startVideo calls.`);\n\tconst { prompt, resolvedImage, normalizedFrameImages, effectiveInputReferences, warnings } = normalizeVideoCallInputs({\n\t\tpromptArg,\n\t\tframeImages,\n\t\tinputReferences\n\t});\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst callerIdempotencyKey = Object.entries(headers ?? {}).find(([key, value]) => key.toLowerCase() === \"idempotency-key\" && value !== void 0);\n\tconst callOptions = {\n\t\tprompt,\n\t\tn,\n\t\taspectRatio,\n\t\tresolution,\n\t\tduration,\n\t\tfps,\n\t\tseed,\n\t\timage: resolvedImage,\n\t\tframeImages: normalizedFrameImages,\n\t\tinputReferences: effectiveInputReferences,\n\t\tgenerateAudio,\n\t\tproviderOptions: providerOptions ?? {},\n\t\theaders: {\n\t\t\t...withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n\t\t\t...callerIdempotencyKey ? {} : { \"idempotency-key\": `aisdk_vid_${generateId$1()}` }\n\t\t},\n\t\tabortSignal,\n\t\twebhookUrl\n\t};\n\tconst startResult = await retry(() => model.doStart(callOptions));\n\treturn {\n\t\toperation: startResult.operation,\n\t\twarnings: [...warnings, ...startResult.warnings],\n\t\tproviderMetadata: startResult.providerMetadata,\n\t\tresponse: startResult.response\n\t};\n}\n//#endregion\n//#region src/generate-video/get-video-status.ts\n/**\n* Checks the status of an asynchronous video generation started with\n* `experimental_startVideo`.\n*\n* A single check — no polling loop. Poll by calling this on your own\n* schedule, or skip polling entirely when the start used `webhookUrl` and\n* your receiver fetches the result after the terminal notification arrives.\n*\n* @param model - The video model the operation was started on.\n* @param operation - The opaque reference returned by `experimental_startVideo`.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param maxRetries - Maximum number of retries for the status call. Set to 0 to disable retries. Default: 2.\n*/\nasync function experimental_getVideoStatus(modelArg, { operation, headers, abortSignal, maxRetries: maxRetriesArg }) {\n\tconst model = resolveVideoModel(modelArg);\n\tif (model.doStatus == null) throw new Error(`Video model ${model.modelId} does not implement doStatus.`);\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\treturn retry(() => model.doStatus({\n\t\toperation,\n\t\theaders: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n\t\tabortSignal\n\t}));\n}\n//#endregion\n//#region src/middleware/default-embedding-settings-middleware.ts\n/**\n* Applies default settings for an embedding model.\n*/\nfunction defaultEmbeddingSettingsMiddleware({ settings }) {\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\ttransformParams: async ({ params }) => {\n\t\t\treturn mergeObjects(settings, params);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/middleware/default-instructions-middleware.ts\n/**\n* Applies default instructions to a language model when a call does not\n* already contain a system message.\n*/\nfunction defaultInstructionsMiddleware({ instructions }) {\n\tconst defaultSystemMessages = typeof instructions === \"string\" ? [{\n\t\trole: \"system\",\n\t\tcontent: instructions\n\t}] : asArray(instructions).map((message) => ({\n\t\trole: \"system\",\n\t\tcontent: message.content,\n\t\tproviderOptions: message.providerOptions\n\t}));\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\ttransformParams: async ({ params }) => {\n\t\t\tif (defaultSystemMessages.length === 0 || params.prompt.some((message) => message.role === \"system\")) return params;\n\t\t\treturn {\n\t\t\t\t...params,\n\t\t\t\tprompt: [...defaultSystemMessages, ...params.prompt]\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/middleware/default-settings-middleware.ts\n/**\n* Applies default settings for a language model.\n*/\nfunction defaultSettingsMiddleware({ settings }) {\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\ttransformParams: async ({ params }) => {\n\t\t\treturn mergeObjects(settings, params);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/middleware/extract-json-middleware.ts\n/**\n* Default transform function that strips markdown code fences from text.\n*/\nfunction defaultTransform(text) {\n\treturn text.replace(/^```(?:json)?\\s*\\n?/, \"\").replace(/\\n?```\\s*$/, \"\").trim();\n}\nfunction stripMarkdownCodeFenceSuffix(text) {\n\treturn text.replace(/\\n?```\\s*$/, \"\").trimEnd();\n}\nfunction getPotentialSuffixStart(text) {\n\tlet index = text.length;\n\twhile (index > 0 && /\\s/.test(text[index - 1])) index--;\n\tlet backtickCount = 0;\n\twhile (index > 0 && backtickCount < 3 && text[index - 1] === \"`\") {\n\t\tindex--;\n\t\tbacktickCount++;\n\t}\n\tif (backtickCount > 0) while (index > 0 && /\\s/.test(text[index - 1])) index--;\n\treturn index;\n}\n/**\n* Middleware that extracts JSON from text content by stripping\n* markdown code fences and other formatting.\n*\n* This is useful when using Output.object() with models that wrap\n* JSON responses in markdown code blocks.\n*\n* @param options - Configuration options for the middleware.\n* @param options.transform - Custom transform function. If provided, this will be\n* used instead of the default markdown fence stripping.\n*/\nfunction extractJsonMiddleware(options) {\n\tconst transform = options?.transform ?? defaultTransform;\n\tconst hasCustomTransform = options?.transform !== void 0;\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\twrapGenerate: async ({ doGenerate }) => {\n\t\t\tconst { content, ...rest } = await doGenerate();\n\t\t\tconst transformedContent = [];\n\t\t\tfor (const part of content) {\n\t\t\t\tif (part.type !== \"text\") {\n\t\t\t\t\ttransformedContent.push(part);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\t...part,\n\t\t\t\t\ttext: transform(part.text)\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: transformedContent,\n\t\t\t\t...rest\n\t\t\t};\n\t\t},\n\t\twrapStream: async ({ doStream }) => {\n\t\t\tconst { stream, ...rest } = await doStream();\n\t\t\tconst textBlocks = createIdMap();\n\t\t\treturn {\n\t\t\t\tstream: stream.pipeThrough(new TransformStream({ transform: (chunk, controller) => {\n\t\t\t\t\tif (chunk.type === \"text-start\") {\n\t\t\t\t\t\ttextBlocks[chunk.id] = {\n\t\t\t\t\t\t\tstartEvent: chunk,\n\t\t\t\t\t\t\tphase: hasCustomTransform ? \"buffering\" : \"prefix\",\n\t\t\t\t\t\t\tbuffer: \"\",\n\t\t\t\t\t\t\tprefixStripped: false\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type === \"text-delta\") {\n\t\t\t\t\t\tconst block = textBlocks[chunk.id];\n\t\t\t\t\t\tif (!block) {\n\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblock.buffer += chunk.delta;\n\t\t\t\t\t\tif (block.phase === \"buffering\") return;\n\t\t\t\t\t\tif (block.phase === \"prefix\") {\n\t\t\t\t\t\t\tif (block.buffer.length > 0 && !block.buffer.startsWith(\"`\")) {\n\t\t\t\t\t\t\t\tblock.phase = \"streaming\";\n\t\t\t\t\t\t\t\tcontroller.enqueue(block.startEvent);\n\t\t\t\t\t\t\t} else if (block.buffer.startsWith(\"```\")) {\n\t\t\t\t\t\t\t\tif (block.buffer.includes(\"\\n\")) {\n\t\t\t\t\t\t\t\t\tconst prefixMatch = block.buffer.match(/^```(?:json)?\\s*\\n/);\n\t\t\t\t\t\t\t\t\tif (prefixMatch) {\n\t\t\t\t\t\t\t\t\t\tblock.buffer = block.buffer.slice(prefixMatch[0].length);\n\t\t\t\t\t\t\t\t\t\tblock.prefixStripped = true;\n\t\t\t\t\t\t\t\t\t\tblock.phase = \"streaming\";\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(block.startEvent);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tblock.phase = \"streaming\";\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(block.startEvent);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (block.buffer.length >= 3 && !block.buffer.startsWith(\"```\")) {\n\t\t\t\t\t\t\t\tblock.phase = \"streaming\";\n\t\t\t\t\t\t\t\tcontroller.enqueue(block.startEvent);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (block.phase === \"streaming\") {\n\t\t\t\t\t\t\tconst potentialSuffixStart = getPotentialSuffixStart(block.buffer);\n\t\t\t\t\t\t\tconst toStream = block.buffer.slice(0, potentialSuffixStart);\n\t\t\t\t\t\t\tblock.buffer = block.buffer.slice(potentialSuffixStart);\n\t\t\t\t\t\t\tif (toStream.length === 0) return;\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\t\t\tdelta: toStream\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type === \"text-end\") {\n\t\t\t\t\t\tconst block = textBlocks[chunk.id];\n\t\t\t\t\t\tif (block) {\n\t\t\t\t\t\t\tif (block.phase === \"prefix\" || block.phase === \"buffering\") controller.enqueue(block.startEvent);\n\t\t\t\t\t\t\tlet remaining = block.buffer;\n\t\t\t\t\t\t\tif (block.phase === \"buffering\") remaining = transform(remaining);\n\t\t\t\t\t\t\telse if (block.prefixStripped) remaining = stripMarkdownCodeFenceSuffix(remaining);\n\t\t\t\t\t\t\telse if (block.phase === \"prefix\") remaining = transform(remaining);\n\t\t\t\t\t\t\telse remaining = stripMarkdownCodeFenceSuffix(remaining);\n\t\t\t\t\t\t\tif (remaining.length > 0) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\t\t\tdelta: remaining\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\tdelete textBlocks[chunk.id];\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t} })),\n\t\t\t\t...rest\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/util/get-potential-start-index.ts\n/**\n* Finds the potential starting index where searchedText could begin in text.\n*\n* This function checks for both complete and partial matches:\n* - If searchedText is found as a complete substring, returns the index of the first occurrence.\n* - If the end of text matches the beginning of searchedText (partial match),\n* returns the index where that partial match starts.\n*\n* @param text - The text to search within.\n* @param searchedText - The text to search for.\n* @returns The starting index of the match (complete or partial), or null if\n* searchedText is empty or no match is found.\n*/\nfunction getPotentialStartIndex(text, searchedText) {\n\tif (searchedText.length === 0) return null;\n\tconst directIndex = text.indexOf(searchedText);\n\tif (directIndex !== -1) return directIndex;\n\tfor (let i = text.length - 1; i >= 0; i--) {\n\t\tconst suffix = text.substring(i);\n\t\tif (searchedText.startsWith(suffix)) return i;\n\t}\n\treturn null;\n}\n//#endregion\n//#region src/middleware/extract-reasoning-middleware.ts\n/**\n* Extracts a delimited reasoning section from the generated text and exposes it\n* as a `reasoning` property on the result.\n*\n* @param tagName - An XML tag name (without angle brackets), or literal opening\n* and closing delimiters for formats such as Gemma's thought channel.\n* @param separator - The separator to use between reasoning and text sections.\n* @param startWithReasoning - Whether to start with reasoning tokens.\n*/\nfunction extractReasoningMiddleware({ tagName, separator = \"\\n\", startWithReasoning = false }) {\n\tconst openingTag = typeof tagName === \"string\" ? `<${tagName}>` : tagName.opening;\n\tconst closingTag = typeof tagName === \"string\" ? `</${tagName}>` : tagName.closing;\n\tif (openingTag.length === 0 || closingTag.length === 0) throw new InvalidArgumentError({\n\t\tparameter: \"tagName\",\n\t\tvalue: tagName,\n\t\tmessage: \"Reasoning delimiters must not be empty.\"\n\t});\n\tconst escapedOpeningTag = openingTag.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\tconst escapedClosingTag = closingTag.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\twrapGenerate: async ({ doGenerate }) => {\n\t\t\tconst { content, ...rest } = await doGenerate();\n\t\t\tconst transformedContent = [];\n\t\t\tfor (const part of content) {\n\t\t\t\tif (part.type !== \"text\") {\n\t\t\t\t\ttransformedContent.push(part);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst text = startWithReasoning ? openingTag + part.text : part.text;\n\t\t\t\tconst regexp = new RegExp(`${escapedOpeningTag}(.*?)${escapedClosingTag}`, \"gs\");\n\t\t\t\tconst matches = Array.from(text.matchAll(regexp));\n\t\t\t\tif (!matches.length) {\n\t\t\t\t\ttransformedContent.push(part);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst reasoningText = matches.map((match) => match[1]).join(separator);\n\t\t\t\tlet textWithoutReasoning = text;\n\t\t\t\tfor (let i = matches.length - 1; i >= 0; i--) {\n\t\t\t\t\tconst match = matches[i];\n\t\t\t\t\tconst beforeMatch = textWithoutReasoning.slice(0, match.index);\n\t\t\t\t\tconst afterMatch = textWithoutReasoning.slice(match.index + match[0].length);\n\t\t\t\t\ttextWithoutReasoning = beforeMatch + (beforeMatch.length > 0 && afterMatch.length > 0 ? separator : \"\") + afterMatch;\n\t\t\t\t}\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\ttext: reasoningText\n\t\t\t\t});\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: textWithoutReasoning\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: transformedContent,\n\t\t\t\t...rest\n\t\t\t};\n\t\t},\n\t\twrapStream: async ({ doStream }) => {\n\t\t\tconst { stream, ...rest } = await doStream();\n\t\t\tconst reasoningExtractions = createIdMap();\n\t\t\tlet reasoningIdCounter = 0;\n\t\t\tconst delayedTextStarts = createIdMap();\n\t\t\treturn {\n\t\t\t\tstream: stream.pipeThrough(new TransformStream({ transform: (chunk, controller) => {\n\t\t\t\t\tif (chunk.type === \"text-start\") {\n\t\t\t\t\t\tdelayedTextStarts[chunk.id] = chunk;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type !== \"text-delta\" && chunk.type !== \"text-end\") {\n\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type === \"text-delta\" && reasoningExtractions[chunk.id] == null) reasoningExtractions[chunk.id] = {\n\t\t\t\t\t\tisFirstReasoning: true,\n\t\t\t\t\t\tisFirstText: true,\n\t\t\t\t\t\tafterSwitch: false,\n\t\t\t\t\t\tisReasoning: startWithReasoning,\n\t\t\t\t\t\tbuffer: \"\",\n\t\t\t\t\t\treasoningId: void 0,\n\t\t\t\t\t\ttextId: chunk.id\n\t\t\t\t\t};\n\t\t\t\t\tconst activeExtraction = reasoningExtractions[chunk.id];\n\t\t\t\t\tif (activeExtraction == null) {\n\t\t\t\t\t\tif (delayedTextStarts[chunk.id] != null) {\n\t\t\t\t\t\t\tcontroller.enqueue(delayedTextStarts[chunk.id]);\n\t\t\t\t\t\t\tdelete delayedTextStarts[chunk.id];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tfunction getReasoningId() {\n\t\t\t\t\t\treturn activeExtraction.reasoningId ??= `reasoning-${reasoningIdCounter++}`;\n\t\t\t\t\t}\n\t\t\t\t\tfunction publish(text) {\n\t\t\t\t\t\tif (text.length > 0) {\n\t\t\t\t\t\t\tconst prefix = activeExtraction.afterSwitch && (activeExtraction.isReasoning ? !activeExtraction.isFirstReasoning : !activeExtraction.isFirstText) ? separator : \"\";\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning && (activeExtraction.afterSwitch || activeExtraction.isFirstReasoning)) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\t\tid: getReasoningId()\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\tdelta: prefix + text,\n\t\t\t\t\t\t\t\tid: getReasoningId()\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (delayedTextStarts[activeExtraction.textId] != null) {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(delayedTextStarts[activeExtraction.textId]);\n\t\t\t\t\t\t\t\t\tdelete delayedTextStarts[activeExtraction.textId];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\tdelta: prefix + text,\n\t\t\t\t\t\t\t\t\tid: activeExtraction.textId\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tactiveExtraction.afterSwitch = false;\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) activeExtraction.isFirstReasoning = false;\n\t\t\t\t\t\t\telse activeExtraction.isFirstText = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type === \"text-end\") {\n\t\t\t\t\t\tpublish(activeExtraction.buffer);\n\t\t\t\t\t\tactiveExtraction.buffer = \"\";\n\t\t\t\t\t\tif (delayedTextStarts[chunk.id] != null) {\n\t\t\t\t\t\t\tcontroller.enqueue(delayedTextStarts[chunk.id]);\n\t\t\t\t\t\t\tdelete delayedTextStarts[chunk.id];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveExtraction.buffer += chunk.delta;\n\t\t\t\t\tdo {\n\t\t\t\t\t\tconst nextTag = activeExtraction.isReasoning ? closingTag : openingTag;\n\t\t\t\t\t\tconst startIndex = getPotentialStartIndex(activeExtraction.buffer, nextTag);\n\t\t\t\t\t\tif (startIndex == null) {\n\t\t\t\t\t\t\tpublish(activeExtraction.buffer);\n\t\t\t\t\t\t\tactiveExtraction.buffer = \"\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpublish(activeExtraction.buffer.slice(0, startIndex));\n\t\t\t\t\t\tif (startIndex + nextTag.length <= activeExtraction.buffer.length) {\n\t\t\t\t\t\t\tactiveExtraction.buffer = activeExtraction.buffer.slice(startIndex + nextTag.length);\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) {\n\t\t\t\t\t\t\t\tif (activeExtraction.isFirstReasoning) controller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\t\t\tid: getReasoningId()\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\t\t\tid: getReasoningId()\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tactiveExtraction.reasoningId = void 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tactiveExtraction.isReasoning = !activeExtraction.isReasoning;\n\t\t\t\t\t\t\tactiveExtraction.afterSwitch = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tactiveExtraction.buffer = activeExtraction.buffer.slice(startIndex);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (true);\n\t\t\t\t} })),\n\t\t\t\t...rest\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/middleware/simulate-streaming-middleware.ts\n/**\n* Simulates streaming chunks with the response from a generate call.\n*/\nfunction simulateStreamingMiddleware() {\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\twrapStream: async ({ doGenerate }) => {\n\t\t\tconst result = await doGenerate();\n\t\t\tlet id = 0;\n\t\t\treturn {\n\t\t\t\tstream: new ReadableStream({ start(controller) {\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"stream-start\",\n\t\t\t\t\t\twarnings: result.warnings\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"response-metadata\",\n\t\t\t\t\t\t...result.response\n\t\t\t\t\t});\n\t\t\t\t\tfor (const part of result.content) switch (part.type) {\n\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\tif (part.text.length > 0) {\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-start\",\n\t\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\t\tdelta: part.text\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-end\",\n\t\t\t\t\t\t\t\t\tid: String(id)\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tid++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"reasoning\":\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\tdelta: part.text\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\t\tid: String(id)\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tid++;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault: controller.enqueue(part);\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\tfinishReason: result.finishReason,\n\t\t\t\t\t\tusage: result.usage,\n\t\t\t\t\t\tproviderMetadata: result.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} }),\n\t\t\t\trequest: result.request,\n\t\t\t\tresponse: result.response\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/middleware/add-tool-input-examples-middleware.ts\nfunction defaultFormatExample(example) {\n\treturn JSON.stringify(example.input);\n}\n/**\n* Middleware that appends input examples to tool descriptions.\n*\n* This is useful for providers that don't natively support the `inputExamples`\n* property. The middleware serializes examples into the tool's description text.\n*\n* @param options - Configuration options for the middleware.\n* @param options.prefix - A prefix to prepend before the examples. Default: 'Input Examples:'\n* @param options.format - Optional custom formatter for each example.\n* Receives the example object and its index. Default: JSON.stringify(example.input)\n* @param options.remove - Whether to remove the inputExamples property\n* after adding them to the description. Default: true\n*\n* @example\n* ```ts\n* import { wrapLanguageModel, addToolInputExamplesMiddleware } from 'ai';\n*\n* const model = wrapLanguageModel({\n* model: yourModel,\n* middleware: addToolInputExamplesMiddleware(),\n* });\n* ```\n*/\nfunction addToolInputExamplesMiddleware({ prefix = \"Input Examples:\", format = defaultFormatExample, remove = true } = {}) {\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\ttransformParams: async ({ params }) => {\n\t\t\tif (!params.tools?.length) return params;\n\t\t\tconst transformedTools = params.tools.map((tool) => {\n\t\t\t\tif (tool.type !== \"function\" || !tool.inputExamples?.length) return tool;\n\t\t\t\tconst examplesSection = `${prefix}\\n${tool.inputExamples.map((example, index) => format(example, index)).join(\"\\n\")}`;\n\t\t\t\tconst toolDescription = tool.description ? `${tool.description}\\n\\n${examplesSection}` : examplesSection;\n\t\t\t\treturn {\n\t\t\t\t\t...tool,\n\t\t\t\t\tdescription: toolDescription,\n\t\t\t\t\tinputExamples: remove ? void 0 : tool.inputExamples\n\t\t\t\t};\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...params,\n\t\t\t\ttools: transformedTools\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/middleware/wrap-language-model.ts\n/**\n* Wraps a LanguageModelV4 instance with middleware functionality.\n* This function allows you to apply middleware to transform parameters,\n* wrap generate operations, and wrap stream operations of a language model.\n*\n* @param options - Configuration options for wrapping the language model.\n* @param options.model - The original LanguageModelV4 instance to be wrapped.\n* @param options.middleware - The middleware to be applied to the language model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n* @param options.modelId - Optional custom model ID to override the original model's ID.\n* @param options.providerId - Optional custom provider ID to override the original model's provider ID.\n* @returns A new LanguageModelV4 instance with middleware applied.\n*/\nconst wrapLanguageModel = ({ model: inputModel, middleware: middlewareArg, modelId, providerId }) => {\n\tconst model = asLanguageModelV4(inputModel);\n\treturn [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n\t\treturn doWrap$2({\n\t\t\tmodel: wrappedModel,\n\t\t\tmiddleware,\n\t\t\tmodelId,\n\t\t\tproviderId\n\t\t});\n\t}, model);\n};\nconst doWrap$2 = ({ model, middleware: { transformParams, wrapGenerate, wrapStream, overrideProvider, overrideModelId, overrideSupportedUrls }, modelId, providerId }) => {\n\tasync function doTransform({ params, type }) {\n\t\treturn transformParams ? await transformParams({\n\t\t\tparams,\n\t\t\ttype,\n\t\t\tmodel\n\t\t}) : params;\n\t}\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\tprovider: providerId ?? overrideProvider?.({ model }) ?? model.provider,\n\t\tmodelId: modelId ?? overrideModelId?.({ model }) ?? model.modelId,\n\t\tsupportedUrls: overrideSupportedUrls?.({ model }) ?? model.supportedUrls,\n\t\tasync doGenerate(params) {\n\t\t\tconst transformedParams = await doTransform({\n\t\t\t\tparams,\n\t\t\t\ttype: \"generate\"\n\t\t\t});\n\t\t\tconst doGenerate = async () => await model.doGenerate(transformedParams);\n\t\t\tconst doStream = async () => await model.doStream(transformedParams);\n\t\t\treturn wrapGenerate ? await wrapGenerate({\n\t\t\t\tdoGenerate,\n\t\t\t\tdoStream,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : await doGenerate();\n\t\t},\n\t\tasync doStream(params) {\n\t\t\tconst transformedParams = await doTransform({\n\t\t\t\tparams,\n\t\t\t\ttype: \"stream\"\n\t\t\t});\n\t\t\tconst doGenerate = async () => await model.doGenerate(transformedParams);\n\t\t\tconst doStream = async () => await model.doStream(transformedParams);\n\t\t\treturn wrapStream ? await wrapStream({\n\t\t\t\tdoGenerate,\n\t\t\t\tdoStream,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : await doStream();\n\t\t}\n\t};\n};\n//#endregion\n//#region src/middleware/wrap-embedding-model.ts\n/**\n* Wraps an EmbeddingModelV4 instance with middleware functionality.\n* This function allows you to apply middleware to transform parameters,\n* wrap embed operations of an embedding model.\n*\n* @param options - Configuration options for wrapping the embedding model.\n* @param options.model - The original EmbeddingModelV4 instance to be wrapped.\n* @param options.middleware - The middleware to be applied to the embedding model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n* @param options.modelId - Optional custom model ID to override the original model's ID.\n* @param options.providerId - Optional custom provider ID to override the original model's provider ID.\n* @returns A new EmbeddingModelV4 instance with middleware applied.\n*/\nconst wrapEmbeddingModel = ({ model: inputModel, middleware: middlewareArg, modelId, providerId }) => {\n\tconst model = asEmbeddingModelV4(inputModel);\n\treturn [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n\t\treturn doWrap$1({\n\t\t\tmodel: wrappedModel,\n\t\t\tmiddleware,\n\t\t\tmodelId,\n\t\t\tproviderId\n\t\t});\n\t}, model);\n};\nconst doWrap$1 = ({ model, middleware: { transformParams, wrapEmbed, overrideProvider, overrideModelId, overrideMaxEmbeddingsPerCall, overrideSupportsParallelCalls }, modelId, providerId }) => {\n\tasync function doTransform({ params }) {\n\t\treturn transformParams ? await transformParams({\n\t\t\tparams,\n\t\t\tmodel\n\t\t}) : params;\n\t}\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\tprovider: providerId ?? overrideProvider?.({ model }) ?? model.provider,\n\t\tmodelId: modelId ?? overrideModelId?.({ model }) ?? model.modelId,\n\t\tmaxEmbeddingsPerCall: overrideMaxEmbeddingsPerCall?.({ model }) ?? model.maxEmbeddingsPerCall,\n\t\t[EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL]: getEmbeddingModelMaxInputBytesPerCall(model),\n\t\t[EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER]: getEmbeddingModelProviderOptionsTransformer(model),\n\t\tsupportsParallelCalls: overrideSupportsParallelCalls?.({ model }) ?? model.supportsParallelCalls,\n\t\tasync doEmbed(params) {\n\t\t\tconst transformedParams = await doTransform({ params });\n\t\t\tconst doEmbed = async () => await model.doEmbed(transformedParams);\n\t\t\treturn wrapEmbed ? await wrapEmbed({\n\t\t\t\tdoEmbed,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : await doEmbed();\n\t\t}\n\t};\n};\n//#endregion\n//#region src/middleware/wrap-image-model.ts\n/**\n* Wraps an ImageModelV4 instance with middleware functionality.\n* This function allows you to apply middleware to transform parameters\n* and wrap generate operations of an image model.\n*\n* @param options - Configuration options for wrapping the image model.\n* @param options.model - The original ImageModelV4 instance to be wrapped.\n* @param options.middleware - The middleware to be applied to the image model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n* @param options.modelId - Optional custom model ID to override the original model's ID.\n* @param options.providerId - Optional custom provider ID to override the original model's provider ID.\n* @returns A new ImageModelV4 instance with middleware applied.\n*/\nconst wrapImageModel = ({ model: inputModel, middleware: middlewareArg, modelId, providerId }) => {\n\tconst model = asImageModelV4(inputModel);\n\treturn [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n\t\treturn doWrap({\n\t\t\tmodel: wrappedModel,\n\t\t\tmiddleware,\n\t\t\tmodelId,\n\t\t\tproviderId\n\t\t});\n\t}, model);\n};\nconst doWrap = ({ model, middleware: { transformParams, wrapGenerate, overrideProvider, overrideModelId, overrideMaxImagesPerCall, overrideSupportsFileInputs, overrideSupportsMaskInputs }, modelId, providerId }) => {\n\tasync function doTransform({ params }) {\n\t\treturn transformParams ? await transformParams({\n\t\t\tparams,\n\t\t\tmodel\n\t\t}) : params;\n\t}\n\tconst maxImagesPerCallRaw = overrideMaxImagesPerCall?.({ model }) ?? model.maxImagesPerCall;\n\tconst maxImagesPerCall = maxImagesPerCallRaw instanceof Function ? maxImagesPerCallRaw.bind(model) : maxImagesPerCallRaw;\n\tconst supportsFileInputs = overrideSupportsFileInputs !== void 0 ? overrideSupportsFileInputs({ model }) : model.supportsFileInputs;\n\tconst supportsMaskInputs = overrideSupportsMaskInputs !== void 0 ? overrideSupportsMaskInputs({ model }) : model.supportsMaskInputs;\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\tprovider: providerId ?? overrideProvider?.({ model }) ?? model.provider,\n\t\tmodelId: modelId ?? overrideModelId?.({ model }) ?? model.modelId,\n\t\tmaxImagesPerCall,\n\t\tsupportsFileInputs,\n\t\tsupportsMaskInputs,\n\t\tasync doGenerate(params) {\n\t\t\tconst transformedParams = await doTransform({ params });\n\t\t\tconst doGenerate = async () => await model.doGenerate(transformedParams);\n\t\t\treturn wrapGenerate ? await wrapGenerate({\n\t\t\t\tdoGenerate,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : await doGenerate();\n\t\t}\n\t};\n};\n//#endregion\n//#region src/middleware/wrap-provider.ts\n/**\n* Wraps a ProviderV4 instance with middleware functionality.\n* This function allows you to apply middleware to all language models\n* from the provider, enabling you to transform parameters, wrap generate\n* operations, and wrap stream operations for every language model.\n*\n* @param options - Configuration options for wrapping the provider.\n* @param options.provider - The original ProviderV4 instance to be wrapped.\n* @param options.languageModelMiddleware - The middleware to be applied to all language models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n* @param options.imageModelMiddleware - Optional middleware to be applied to all image models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n* @returns A new ProviderV4 instance with middleware applied to all language models.\n*/\nfunction wrapProvider({ provider, languageModelMiddleware, imageModelMiddleware }) {\n\tconst providerV4 = asProviderV4(provider);\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\tlanguageModel: (modelId) => wrapLanguageModel({\n\t\t\tmodel: providerV4.languageModel(modelId),\n\t\t\tmiddleware: languageModelMiddleware\n\t\t}),\n\t\tembeddingModel: providerV4.embeddingModel,\n\t\timageModel: (modelId) => {\n\t\t\tlet model = providerV4.imageModel(modelId);\n\t\t\tif (imageModelMiddleware != null) model = wrapImageModel({\n\t\t\t\tmodel,\n\t\t\t\tmiddleware: imageModelMiddleware\n\t\t\t});\n\t\t\treturn model;\n\t\t},\n\t\ttranscriptionModel: providerV4.transcriptionModel,\n\t\tspeechModel: providerV4.speechModel,\n\t\trerankingModel: providerV4.rerankingModel,\n\t\t...providerV4.files != null ? { files: providerV4.files } : {},\n\t\t...providerV4.skills != null ? { skills: providerV4.skills } : {}\n\t};\n}\n//#endregion\n//#region src/realtime/audio-utils.ts\n/**\n* Converts Float32 audio samples to a base64-encoded PCM16 string\n* for sending to a realtime model via input_audio_buffer.append.\n*\n* Samples are expected to be in the range [-1.0, 1.0].\n* Output is 16-bit signed integer, little-endian, base64-encoded.\n*/\nfunction encodeRealtimeAudio(float32Array) {\n\tconst buffer = /* @__PURE__ */ new ArrayBuffer(float32Array.length * 2);\n\tconst view = new DataView(buffer);\n\tfor (let i = 0; i < float32Array.length; i++) {\n\t\tconst s = Math.max(-1, Math.min(1, float32Array[i]));\n\t\tview.setInt16(i * 2, s < 0 ? s * 32768 : s * 32767, true);\n\t}\n\tconst bytes = new Uint8Array(buffer);\n\tconst chunkSize = 32768;\n\tlet binary = \"\";\n\tfor (let i = 0; i < bytes.length; i += chunkSize) {\n\t\tconst chunk = bytes.subarray(i, i + chunkSize);\n\t\tbinary += String.fromCharCode(...chunk);\n\t}\n\treturn btoa(binary);\n}\n/**\n* Converts a base64-encoded PCM16 string (from a realtime model's\n* audio-delta event) back to Float32 audio samples.\n*\n* Input is expected to be 16-bit signed integer, little-endian, base64-encoded.\n* Output samples are in the range [-1.0, 1.0].\n*/\nfunction decodeRealtimeAudio(base64Audio) {\n\tconst binaryString = atob(base64Audio);\n\tconst bytes = new Uint8Array(binaryString.length);\n\tfor (let i = 0; i < binaryString.length; i++) bytes[i] = binaryString.charCodeAt(i);\n\tconst pcm16 = new Int16Array(bytes.buffer);\n\tconst float32 = new Float32Array(pcm16.length);\n\tfor (let i = 0; i < pcm16.length; i++) float32[i] = pcm16[i] / 32768;\n\treturn float32;\n}\n/**\n* Resamples audio from one sample rate to another using linear\n* interpolation. Suitable for voice audio.\n*\n* @param input - Float32 audio samples at the input sample rate.\n* @param inputRate - The sample rate of the input audio (e.g. 48000).\n* @param outputRate - The desired output sample rate (e.g. 24000).\n* @returns Float32 audio samples at the output sample rate.\n*/\nfunction resampleAudio(input, inputRate, outputRate) {\n\tif (inputRate === outputRate) return input;\n\tconst ratio = inputRate / outputRate;\n\tconst outputLength = Math.round(input.length / ratio);\n\tconst output = new Float32Array(outputLength);\n\tfor (let i = 0; i < outputLength; i++) {\n\t\tconst srcIndex = i * ratio;\n\t\tconst srcIndexFloor = Math.floor(srcIndex);\n\t\tconst srcIndexCeil = Math.min(srcIndexFloor + 1, input.length - 1);\n\t\tconst fraction = srcIndex - srcIndexFloor;\n\t\toutput[i] = input[srcIndexFloor] * (1 - fraction) + input[srcIndexCeil] * fraction;\n\t}\n\treturn output;\n}\n//#endregion\n//#region src/realtime/get-realtime-tool-definitions.ts\nasync function getRealtimeToolDefinitions({ tools, toolsContext = {} }) {\n\tconst definitions = [];\n\tfor (const [name, tool] of Object.entries(tools)) {\n\t\tconst toolType = tool.type;\n\t\tswitch (toolType) {\n\t\t\tcase void 0:\n\t\t\tcase \"function\":\n\t\t\tcase \"dynamic\": {\n\t\t\t\tconst description = resolveRealtimeToolDescription({\n\t\t\t\t\ttool,\n\t\t\t\t\ttoolName: name,\n\t\t\t\t\ttoolsContext\n\t\t\t\t});\n\t\t\t\tdefinitions.push({\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tname,\n\t\t\t\t\tdescription,\n\t\t\t\t\tparameters: await asSchema$1(tool.inputSchema).jsonSchema\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"provider\": break;\n\t\t\tdefault: throw new Error(`Unsupported tool type: ${toolType}`);\n\t\t}\n\t}\n\treturn definitions;\n}\nfunction resolveRealtimeToolDescription({ tool, toolName, toolsContext }) {\n\treturn tool.description === void 0 ? void 0 : typeof tool.description === \"string\" ? tool.description : tool.description({ context: toolsContext[toolName] });\n}\n//#endregion\n//#region src/realtime/browser-realtime-audio.ts\nvar BrowserRealtimeAudio = class {\n\tconstructor(options) {\n\t\tthis.captureContext = null;\n\t\tthis.captureProcessor = null;\n\t\tthis.captureSource = null;\n\t\tthis.captureStream = null;\n\t\tthis.ownsCaptureStream = true;\n\t\tthis.captureCleanup = [];\n\t\tthis.captureGeneration = 0;\n\t\tthis.playbackContext = null;\n\t\tthis.playbackQueue = [];\n\t\tthis.playbackTime = 0;\n\t\tthis.playbackStartTime = 0;\n\t\tthis.activeSources = /* @__PURE__ */ new Set();\n\t\tthis.isPlaying = false;\n\t\tthis.playbackPaused = false;\n\t\tthis.captureSampleRate = options.captureSampleRate;\n\t\tthis.playbackSampleRate = options.playbackSampleRate;\n\t\tthis.onAudio = options.onAudio;\n\t\tthis.onPlayingChange = options.onPlayingChange;\n\t\tthis.maxPlaybackSeconds = options.maxPlaybackSeconds ?? Infinity;\n\t\tthis.onError = options.onError;\n\t\tthis.onCapturingChange = options.onCapturingChange;\n\t}\n\tensurePlaybackContext() {\n\t\tif (this.playbackContext == null) {\n\t\t\tthis.playbackContext = new AudioContext({ sampleRate: this.playbackSampleRate });\n\t\t\tconst context = this.playbackContext;\n\t\t\tcontext.onstatechange = () => {\n\t\t\t\tif (this.playbackContext === context) this.setPlaying(context.state === \"running\" && this.activeSources.size > 0);\n\t\t\t};\n\t\t}\n\t}\n\tasync resumePlayback() {\n\t\tthis.ensurePlaybackContext();\n\t\tconst context = this.playbackContext;\n\t\tif (this.playbackPaused) this.stopPlayback();\n\t\tif (this.playbackContext !== context) return;\n\t\tawait context?.resume();\n\t\tif (this.playbackContext !== context) return;\n\t\tthis.playbackPaused = false;\n\t\tthis.setPlaying(this.playbackContext?.state === \"running\" && this.activeSources.size > 0);\n\t}\n\tstartCapture(stream, options) {\n\t\tconst generation = this.captureGeneration + 1;\n\t\tthis.stopCapture();\n\t\tif (generation !== this.captureGeneration) {\n\t\t\tif (options?.ownsStream ?? true) stream.getTracks().forEach((track) => track.stop());\n\t\t\treturn;\n\t\t}\n\t\tthis.captureStream = stream;\n\t\tthis.ownsCaptureStream = options?.ownsStream ?? true;\n\t\tconst ctx = new AudioContext({ sampleRate: this.captureSampleRate });\n\t\tthis.captureContext = ctx;\n\t\tctx.resume().catch((error) => {\n\t\t\tif (this.captureContext === ctx) this.onError?.(error);\n\t\t});\n\t\tconst source = ctx.createMediaStreamSource(stream);\n\t\tthis.captureSource = source;\n\t\tconst processor = ctx.createScriptProcessor(1024, 1, 1);\n\t\tthis.captureProcessor = processor;\n\t\tprocessor.onaudioprocess = (event) => {\n\t\t\tif (this.captureContext !== ctx) return;\n\t\t\tconst inputData = event.inputBuffer.getChannelData(0);\n\t\t\tconst samples = resampleAudio(new Float32Array(inputData), ctx.sampleRate, this.captureSampleRate);\n\t\t\ttry {\n\t\t\t\tthis.onAudio(encodeRealtimeAudio(samples));\n\t\t\t} catch (error) {\n\t\t\t\tthis.onError?.(error instanceof Error ? error : new Error(String(error)));\n\t\t\t}\n\t\t};\n\t\tsource.connect(processor);\n\t\tprocessor.connect(ctx.destination);\n\t\tconst updateCapturing = () => this.onCapturingChange(stream.getAudioTracks().some((track) => track.enabled && !track.muted && track.readyState === \"live\"));\n\t\tfor (const track of stream.getAudioTracks()) for (const event of [\n\t\t\t\"ended\",\n\t\t\t\"mute\",\n\t\t\t\"unmute\"\n\t\t]) {\n\t\t\ttrack.addEventListener(event, updateCapturing);\n\t\t\tthis.captureCleanup.push(() => track.removeEventListener(event, updateCapturing));\n\t\t}\n\t\tupdateCapturing();\n\t}\n\tstopCapture() {\n\t\tthis.captureGeneration++;\n\t\tif (this.captureProcessor != null) this.captureProcessor.onaudioprocess = null;\n\t\tfor (const cleanup of this.captureCleanup) cleanup();\n\t\tthis.captureCleanup = [];\n\t\tthis.captureProcessor?.disconnect();\n\t\tthis.captureSource?.disconnect();\n\t\tthis.captureContext?.close().catch(() => {});\n\t\tif (this.ownsCaptureStream) this.captureStream?.getTracks().forEach((track) => track.stop());\n\t\tthis.captureProcessor = null;\n\t\tthis.captureSource = null;\n\t\tthis.captureContext = null;\n\t\tthis.captureStream = null;\n\t\tthis.onCapturingChange(false);\n\t}\n\tplayAudio(base64Audio) {\n\t\tif (this.playbackPaused) return;\n\t\tthis.ensurePlaybackContext();\n\t\tconst samples = decodeRealtimeAudio(base64Audio);\n\t\tif (Math.max(0, this.playbackTime - (this.playbackContext?.currentTime ?? 0)) + samples.length / this.playbackSampleRate > this.maxPlaybackSeconds) {\n\t\t\tthis.playbackPaused = true;\n\t\t\tthis.stopPlayback();\n\t\t\tthis.onError?.(/* @__PURE__ */ new Error(\"Realtime audio playback buffer is full; playback paused, call resumePlayback() to resume at the live edge\"));\n\t\t\treturn;\n\t\t}\n\t\tthis.playbackQueue.push(samples);\n\t\tthis.schedulePlayback();\n\t}\n\tstopPlayback() {\n\t\tthis.playbackQueue = [];\n\t\tfor (const source of this.activeSources) try {\n\t\t\tsource.onended = null;\n\t\t\tsource.stop();\n\t\t\tsource.disconnect();\n\t\t} catch {}\n\t\tthis.activeSources.clear();\n\t\tif (this.playbackContext != null) this.playbackTime = this.playbackContext.currentTime;\n\t\tthis.setPlaying(false);\n\t}\n\tgetPlaybackOffsetMs() {\n\t\tconst ctx = this.playbackContext;\n\t\tif (ctx == null) return 0;\n\t\treturn (ctx.currentTime - this.playbackStartTime) * 1e3;\n\t}\n\tdispose() {\n\t\tthis.stopCapture();\n\t\tthis.stopPlayback();\n\t\tif (this.playbackContext != null) this.playbackContext.onstatechange = null;\n\t\tthis.playbackContext?.close().catch(() => {});\n\t\tthis.playbackContext = null;\n\t\tthis.playbackTime = 0;\n\t\tthis.playbackPaused = false;\n\t}\n\tsetPlaying(isPlaying) {\n\t\tif (isPlaying && !this.isPlaying) this.playbackStartTime = this.playbackContext?.currentTime ?? 0;\n\t\tif (this.isPlaying !== isPlaying) {\n\t\t\tthis.isPlaying = isPlaying;\n\t\t\tthis.onPlayingChange(isPlaying);\n\t\t}\n\t}\n\tschedulePlayback() {\n\t\tconst ctx = this.playbackContext;\n\t\tif (ctx == null || this.playbackQueue.length === 0) return;\n\t\twhile (this.playbackQueue.length > 0) {\n\t\t\tconst samples = this.playbackQueue.shift();\n\t\t\tconst buffer = ctx.createBuffer(1, samples.length, this.playbackSampleRate);\n\t\t\tbuffer.getChannelData(0).set(samples);\n\t\t\tconst source = ctx.createBufferSource();\n\t\t\tsource.buffer = buffer;\n\t\t\tsource.connect(ctx.destination);\n\t\t\tconst startTime = Math.max(this.playbackTime, ctx.currentTime);\n\t\t\tsource.start(startTime);\n\t\t\tthis.playbackTime = startTime + buffer.duration;\n\t\t\tthis.activeSources.add(source);\n\t\t\tthis.setPlaying(ctx.state === \"running\");\n\t\t\tif (this.playbackContext !== ctx) return;\n\t\t\tsource.onended = () => {\n\t\t\t\tsource.disconnect();\n\t\t\t\tthis.activeSources.delete(source);\n\t\t\t\tif (this.playbackQueue.length === 0 && this.activeSources.size === 0) this.setPlaying(false);\n\t\t\t};\n\t\t}\n\t}\n};\n//#endregion\n//#region src/realtime/realtime-event-channel.ts\n/** One codec queue per connection; retired connections cannot deliver late work. */\nvar RealtimeEventChannel = class {\n\tconstructor(options) {\n\t\tthis.options = options;\n\t\tthis.active = true;\n\t\tthis.finishing = false;\n\t\tthis.incoming = Promise.resolve();\n\t\tthis.outgoing = Promise.resolve();\n\t\tthis.incomingCount = 0;\n\t\tthis.incomingBytes = 0;\n\t\tthis.outgoingCount = 0;\n\t\tthis.parse = options.model.createServerEventParser?.() ?? options.model.parseServerEvent.bind(options.model);\n\t}\n\tget hasPendingIncoming() {\n\t\treturn this.incomingCount > 0;\n\t}\n\tdispose() {\n\t\tthis.active = false;\n\t}\n\t/** Stop accepting messages, but deliver already received terminal events. */\n\tasync finish() {\n\t\tthis.stopWriting();\n\t\tawait this.incoming;\n\t\tthis.dispose();\n\t}\n\tstopWriting() {\n\t\tthis.finishing = true;\n\t}\n\tsend(event, shouldSend) {\n\t\tif (!this.active || this.finishing) throw new Error(\"Realtime connection is closed\");\n\t\tif (this.outgoingCount >= (this.options.maxPending ?? 512)) throw new Error(\"Realtime outgoing queue is full\");\n\t\tthis.outgoingCount++;\n\t\tconst operation = this.outgoing.then(async () => {\n\t\t\tif (!this.active || this.finishing) throw new Error(\"Realtime connection is closed\");\n\t\t\tif (shouldSend?.() === false) return;\n\t\t\tif (!this.active || this.finishing) throw new Error(\"Realtime connection is closed\");\n\t\t\tconst data = await this.options.model.serializeClientEvent(event);\n\t\t\tif (!this.active || this.finishing) throw new Error(\"Realtime connection is closed\");\n\t\t\tif (shouldSend?.() === false) return;\n\t\t\tif (!this.active || this.finishing) throw new Error(\"Realtime connection is closed\");\n\t\t\tif (data != null) this.options.send(data);\n\t\t});\n\t\tthis.outgoing = operation.catch((error) => {\n\t\t\tif (!this.finishing) {\n\t\t\t\tif (event.type !== \"input-audio-append\" && event.type !== \"session-close\") this.report(error);\n\t\t\t}\n\t\t}).finally(() => {\n\t\t\tthis.outgoingCount--;\n\t\t});\n\t\treturn operation;\n\t}\n\treceive(data) {\n\t\tif (!this.active || this.finishing) return;\n\t\tconst bytes = typeof data === \"string\" ? data.length * 2 : data instanceof Blob ? data.size : data.byteLength ?? 0;\n\t\tif (this.incomingCount >= (this.options.maxPending ?? 512) || this.incomingBytes + bytes > (this.options.maxPendingBytes ?? 8388608)) {\n\t\t\tthis.finishing = true;\n\t\t\tthis.fatal(/* @__PURE__ */ new Error(\"Realtime incoming queue is full; input protocol continuity was lost\"));\n\t\t\treturn;\n\t\t}\n\t\tthis.incomingCount++;\n\t\tthis.incomingBytes += bytes;\n\t\tthis.incoming = this.incoming.then(async () => {\n\t\t\tif (!this.active) return;\n\t\t\tconst text = typeof data === \"string\" ? data : data instanceof Blob ? await data.text() : new TextDecoder().decode(data);\n\t\t\tconst parsed = await safeParseJSON({ text });\n\t\t\tif (!this.active) return;\n\t\t\tif (!parsed.success) throw new Error(\"Invalid JSON in realtime server message\", { cause: parsed.error });\n\t\t\tconst health = this.options.model.getHealthCheckResponse?.(parsed.value);\n\t\t\tif (!this.active) return;\n\t\t\tif (health != null && !this.finishing) this.options.send(health);\n\t\t\tif (!this.active) return;\n\t\t\tconst result = this.parse(parsed.value);\n\t\t\tfor (const event of Array.isArray(result) ? result : [result]) {\n\t\t\t\tif (!this.active) return;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.options.onEvent(event);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.report(error);\n\t\t\t\t}\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tthis.finishing = true;\n\t\t\tthis.fatal(error instanceof Error ? error : new Error(String(error)));\n\t\t}).finally(() => {\n\t\t\tthis.incomingCount--;\n\t\t\tthis.incomingBytes -= bytes;\n\t\t});\n\t}\n\tfatal(error) {\n\t\tif (!this.active) return;\n\t\tif (this.options.onFatalError != null) this.options.onFatalError(error);\n\t\telse this.report(error);\n\t}\n\treport(error) {\n\t\tif (!this.active) return;\n\t\ttry {\n\t\t\tthis.options.onError(error instanceof Error ? error : new Error(String(error)));\n\t\t} catch {}\n\t}\n};\n//#endregion\n//#region src/realtime/encode-realtime-frame.ts\n/** Private Live continuous wire budgets; legacy transports do not enforce them. */\nconst REALTIME_MAX_FRAME_BYTES = 131072;\nconst REALTIME_MAX_BUFFERED_BYTES = 131072;\n/** Serialize once, measuring the exact payload passed to the browser. */\nfunction encodeRealtimeFrame(value) {\n\tif (value instanceof ArrayBuffer) return {\n\t\tdata: value,\n\t\tbyteLength: value.byteLength\n\t};\n\tif (ArrayBuffer.isView(value)) return {\n\t\tdata: value,\n\t\tbyteLength: value.byteLength\n\t};\n\tif (value instanceof Blob) return {\n\t\tdata: value,\n\t\tbyteLength: value.size\n\t};\n\tconst data = typeof value === \"string\" ? value : JSON.stringify(value);\n\tif (data === void 0) throw new Error(\"Realtime event could not be encoded as JSON\");\n\treturn {\n\t\tdata,\n\t\tbyteLength: new TextEncoder().encode(data).byteLength\n\t};\n}\nfunction assertRealtimeFrameBudget(frame, bufferedAmount) {\n\tif (frame.byteLength > 131072) throw new Error(`Realtime frame exceeds the ${REALTIME_MAX_FRAME_BYTES}-byte limit; reduce the event payload`);\n\tif (bufferedAmount + frame.byteLength > 131072) throw new Error(`Realtime send buffer is full (${REALTIME_MAX_BUFFERED_BYTES}-byte limit); wait before retrying`);\n}\n//#endregion\n//#region src/realtime/browser-realtime-transport.ts\nfunction getCloseError(event) {\n\tif (event.code === 1e3 && event.wasClean) return void 0;\n\treturn /* @__PURE__ */ new Error(`Realtime WebSocket closed unexpectedly (code ${event.code}${event.reason === \"\" ? \"\" : `: ${event.reason}`})`);\n}\nvar BrowserRealtimeTransport = class {\n\tconstructor(options) {\n\t\tthis.options = options;\n\t\tthis.ws = null;\n\t\tthis.epoch = 0;\n\t\tthis.failing = false;\n\t\tthis.closing = false;\n\t\tthis.model = options.model;\n\t\tthis.continuous = options.model.capabilities?.conversation === \"continuous\";\n\t\tthis.onServerEvent = options.onServerEvent;\n\t\tthis.onError = options.onError;\n\t\tthis.onClose = options.onClose;\n\t}\n\tget isOpen() {\n\t\treturn !this.closing && !this.failing && this.ws?.readyState === WebSocket.OPEN;\n\t}\n\tconnect({ mode, token, url, onOpen, protocols }) {\n\t\tthis.disconnect();\n\t\tconst epoch = this.epoch;\n\t\tif (mode !== \"relay\" && (mode !== \"client-secret\" || typeof token !== \"string\" || token.trim() === \"\")) throw new Error(\"Realtime client-secret connection requires a nonempty token\");\n\t\tconst wsConfig = mode === \"relay\" ? {\n\t\t\turl,\n\t\t\tprotocols\n\t\t} : this.model.getWebSocketConfig?.({\n\t\t\ttoken,\n\t\t\turl\n\t\t});\n\t\tif (this.epoch !== epoch) return;\n\t\tif (wsConfig == null) throw new Error(\"Model does not support client-secret WebSockets\");\n\t\tconst finalUrl = wsConfig.url;\n\t\tconst finalProtocols = wsConfig.protocols;\n\t\tif (this.epoch !== epoch) return;\n\t\ttry {\n\t\t\tif (typeof finalUrl !== \"string\" || !/^wss?:\\/\\//i.test(finalUrl)) throw new Error(\"Invalid realtime WebSocket URL\");\n\t\t\tconst parsed = new URL(finalUrl);\n\t\t\tif (![\"ws:\", \"wss:\"].includes(parsed.protocol) || parsed.hostname === \"\" || finalUrl.includes(\"#\")) throw new Error(\"Invalid realtime WebSocket URL\");\n\t\t} catch {\n\t\t\tthrow new Error(\"Invalid realtime WebSocket URL; expected an absolute ws:// or wss:// URL with a host and no fragment\");\n\t\t}\n\t\tif (this.epoch !== epoch) return;\n\t\tconst ws = new WebSocket(finalUrl, finalProtocols);\n\t\tthis.ws = ws;\n\t\tlet starting = false;\n\t\tlet connectionError;\n\t\tconst codec = new RealtimeEventChannel({\n\t\t\tmodel: this.model,\n\t\t\tsend: (data) => {\n\t\t\t\tif (this.epoch !== epoch || this.ws !== ws || !this.isOpen) throw new Error(\"Realtime WebSocket is not open\");\n\t\t\t\tthis.sendRaw(data);\n\t\t\t},\n\t\t\tonEvent: this.onServerEvent,\n\t\t\tonError: (error) => {\n\t\t\t\tif (!starting) this.onError(error);\n\t\t\t},\n\t\t\tonFatalError: (error) => this.fail(error)\n\t\t});\n\t\tif (this.epoch !== epoch) {\n\t\t\tcodec.dispose();\n\t\t\treturn;\n\t\t}\n\t\tthis.codec = codec;\n\t\tws.onopen = () => {\n\t\t\tif (this.ws !== ws) return;\n\t\t\tstarting = true;\n\t\t\ttry {\n\t\t\t\tPromise.resolve(onOpen()).catch((error) => {\n\t\t\t\t\tif (this.ws === ws) this.fail(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t}).finally(() => {\n\t\t\t\t\tstarting = false;\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (this.epoch === epoch) this.fail(error instanceof Error ? error : new Error(String(error)));\n\t\t\t}\n\t\t};\n\t\tws.onmessage = (messageEvent) => {\n\t\t\tif (this.ws === ws) this.codec?.receive(messageEvent.data);\n\t\t};\n\t\tws.onerror = () => {\n\t\t\tif (this.ws === ws) {\n\t\t\t\tconnectionError = /* @__PURE__ */ new Error(\"WebSocket connection error\");\n\t\t\t\tthis.failing = true;\n\t\t\t}\n\t\t};\n\t\tws.onclose = (event) => {\n\t\t\tif (this.ws === ws) {\n\t\t\t\tthis.ws = null;\n\t\t\t\tconst closeError = getCloseError(event) ?? connectionError;\n\t\t\t\tconst reportCloseErrorImmediately = closeError != null && !codec.hasPendingIncoming;\n\t\t\t\tcodec.stopWriting();\n\t\t\t\tthis.notifyClosing();\n\t\t\t\tif (this.epoch !== epoch) return;\n\t\t\t\tconst drain = codec.finish();\n\t\t\t\tif (reportCloseErrorImmediately) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.onError(closeError);\n\t\t\t\t\t} catch {}\n\t\t\t\t\tif (this.epoch !== epoch) return;\n\t\t\t\t}\n\t\t\t\tconst complete = () => {\n\t\t\t\t\tif (this.epoch !== epoch) return;\n\t\t\t\t\tclearTimeout(this.drainTimer);\n\t\t\t\t\tthis.epoch++;\n\t\t\t\t\tcodec.dispose();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.onClose(closeError);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.reportCallbackError(error);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tthis.drainTimer = setTimeout(complete, 1e3);\n\t\t\t\tthis.awaitDrain(drain, complete);\n\t\t\t}\n\t\t};\n\t}\n\tdisconnect() {\n\t\tthis.epoch++;\n\t\tclearTimeout(this.drainTimer);\n\t\tconst ws = this.ws;\n\t\tthis.ws = null;\n\t\tthis.codec?.dispose();\n\t\tthis.codec = void 0;\n\t\tthis.failing = false;\n\t\tthis.closing = false;\n\t\tws?.close();\n\t}\n\tsendEvent(event, shouldSend, automaticAudio = false) {\n\t\tif (this.failing || this.closing) throw new Error(\"Realtime connection is closed\");\n\t\tif (this.codec == null) return Promise.resolve();\n\t\tconst epoch = this.epoch;\n\t\tconst failed = (error) => {\n\t\t\tif (automaticAudio && this.epoch === epoch && this.isOpen) this.fail(error instanceof Error ? error : new Error(String(error)));\n\t\t};\n\t\ttry {\n\t\t\tconst sent = this.codec.send(event, shouldSend);\n\t\t\tsent.catch(failed);\n\t\t\treturn sent;\n\t\t} catch (error) {\n\t\t\tfailed(error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\tfinish() {\n\t\treturn this.codec?.finish() ?? Promise.resolve();\n\t}\n\t/** Drain accepted events when media or protocol continuity is lost. */\n\tfail(error) {\n\t\tif (this.failing) return;\n\t\tthis.failing = true;\n\t\tconst epoch = this.epoch;\n\t\tconst ws = this.ws;\n\t\tthis.ws = null;\n\t\tthis.codec?.stopWriting();\n\t\tws?.close();\n\t\tthis.notifyClosing();\n\t\tif (this.epoch !== epoch) return;\n\t\tconst drain = this.finish();\n\t\tif (this.options.onFatalError != null) this.options.onFatalError(error, drain);\n\t\telse {\n\t\t\tconst complete = () => {\n\t\t\t\tif (epoch !== this.epoch) return;\n\t\t\t\tthis.disconnect();\n\t\t\t\ttry {\n\t\t\t\t\tthis.onClose();\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tthis.reportCallbackError(cause);\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.drainTimer = setTimeout(complete, 1e3);\n\t\t\tthis.awaitDrain(drain, complete);\n\t\t\tthis.reportCallbackError(error);\n\t\t}\n\t}\n\tnotifyClosing() {\n\t\tif (this.closing) return;\n\t\tthis.closing = true;\n\t\ttry {\n\t\t\tthis.options.onClosing?.();\n\t\t} catch (error) {\n\t\t\tthis.reportCallbackError(error);\n\t\t}\n\t}\n\tasync awaitDrain(drain, complete) {\n\t\ttry {\n\t\t\tawait drain;\n\t\t} catch {}\n\t\ttry {\n\t\t\tcomplete();\n\t\t} catch (error) {\n\t\t\tthis.reportCallbackError(error);\n\t\t}\n\t}\n\treportCallbackError(error) {\n\t\ttry {\n\t\t\tthis.onError(error instanceof Error ? error : new Error(String(error)));\n\t\t} catch {}\n\t}\n\tsendRaw(data) {\n\t\tconst ws = this.ws;\n\t\tconst epoch = this.epoch;\n\t\tif (ws == null || !this.isOpen) return;\n\t\tconst frame = encodeRealtimeFrame(data);\n\t\tif (this.epoch !== epoch || this.ws !== ws || !this.isOpen) throw new Error(\"Realtime connection is closed\");\n\t\tif (this.continuous) assertRealtimeFrameBudget(frame, ws.bufferedAmount);\n\t\tws.send(frame.data);\n\t}\n\tdispose() {\n\t\tthis.disconnect();\n\t}\n};\n//#endregion\n//#region src/realtime/browser-realtime-live-websocket.ts\n/** Continuous PCM16 audio-chunk media for an application-owned WebSocket relay. */\nvar BrowserRealtimeLiveWebSocket = class {\n\tconstructor(options) {\n\t\tthis.options = options;\n\t\tthis.generation = 0;\n\t\tthis.ready = false;\n\t\tthis.capturingStarted = false;\n\t\tthis.pendingAudio = 0;\n\t\tthis.captureGeneration = 0;\n\t\tthis.captureEnabled = true;\n\t\tconst input = options.sessionConfig?.inputAudioFormat;\n\t\tconst output = options.sessionConfig?.outputAudioFormat;\n\t\tconst sampleRate = input?.rate ?? output?.rate ?? options.sampleRate ?? 24e3;\n\t\tconst format = {\n\t\t\ttype: input?.type ?? output?.type ?? \"audio/pcm\",\n\t\t\trate: sampleRate\n\t\t};\n\t\tthis.config = {\n\t\t\t...options.sessionConfig,\n\t\t\tinputAudioFormat: {\n\t\t\t\t...format,\n\t\t\t\t...input\n\t\t\t},\n\t\t\toutputAudioFormat: {\n\t\t\t\t...format,\n\t\t\t\t...output\n\t\t\t}\n\t\t};\n\t\tthis.transport = new BrowserRealtimeTransport({\n\t\t\tmodel: options.model,\n\t\t\tonServerEvent: options.onEvent,\n\t\t\tonError: options.onError,\n\t\t\tonFatalError: options.onFatalError,\n\t\t\tonClosing: () => {\n\t\t\t\tconst generation = this.generation;\n\t\t\t\toptions.onClosing?.();\n\t\t\t\tif (generation === this.generation) this.stopCapture();\n\t\t\t},\n\t\t\tonClose: options.onClose\n\t\t});\n\t\tthis.audio = new BrowserRealtimeAudio({\n\t\t\tcaptureSampleRate: this.config.inputAudioFormat?.rate ?? sampleRate,\n\t\t\tplaybackSampleRate: this.config.outputAudioFormat?.rate ?? sampleRate,\n\t\t\tmaxPlaybackSeconds: options.maxPlaybackBufferSeconds ?? 2,\n\t\t\tonAudio: (audio) => this.sendAudio(audio),\n\t\t\tonError: options.onError,\n\t\t\tonCapturingChange: options.onCapturing,\n\t\t\tonPlayingChange: options.onPlaying\n\t\t});\n\t}\n\tconnect(options) {\n\t\tconst generation = this.generation + 1;\n\t\tthis.dispose();\n\t\tif (generation !== this.generation) return;\n\t\tfor (const format of [this.config.inputAudioFormat, this.config.outputAudioFormat]) {\n\t\t\tif (format?.type !== \"audio/pcm\") throw new UnsupportedFunctionalityError$1({ functionality: \"Continuous browser WebSocket audio supports PCM16 only\" });\n\t\t\tif (format.rate == null || !Number.isFinite(format.rate) || format.rate < 8e3 || format.rate > 96e3) throw new Error(\"Invalid realtime PCM sample rate\");\n\t\t}\n\t\tthis.stream = options.stream;\n\t\tthis.captureEnabled = options.capture !== false;\n\t\tthis.audio.ensurePlaybackContext();\n\t\tthis.audio.resumePlayback().catch((error) => {\n\t\t\tif (generation === this.generation) this.options.onError(error);\n\t\t});\n\t\tthis.transport.connect({\n\t\t\tmode: \"relay\",\n\t\t\turl: options.url,\n\t\t\tprotocols: options.protocols,\n\t\t\tonOpen: () => {\n\t\t\t\treturn this.transport.sendEvent({\n\t\t\t\t\ttype: this.options.model.capabilities?.startup ?? \"session-update\",\n\t\t\t\t\tconfig: this.config\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\tstartCapture() {\n\t\tthis.ready = true;\n\t\tif (!this.captureEnabled || this.capturingStarted) return;\n\t\tthis.resumeCapture().catch((error) => this.options.onError(error));\n\t}\n\tasync resumeCapture(suppliedStream) {\n\t\tconst generation = this.captureGeneration + 1;\n\t\tthis.stopCapture();\n\t\tif (generation !== this.captureGeneration) return;\n\t\tthis.ready = true;\n\t\tthis.capturingStarted = true;\n\t\tthis.captureEnabled = true;\n\t\tif (suppliedStream != null) this.stream = suppliedStream;\n\t\tconst supplied = this.stream;\n\t\tconst stream = supplied ?? await navigator.mediaDevices.getUserMedia({ audio: true });\n\t\tif (generation !== this.captureGeneration || !this.ready) {\n\t\t\tif (supplied == null) stream.getTracks().forEach((track) => track.stop());\n\t\t\treturn;\n\t\t}\n\t\tif (!stream.getAudioTracks().some((track) => track.readyState === \"live\")) {\n\t\t\tif (supplied == null) stream.getTracks().forEach((track) => track.stop());\n\t\t\tthrow new Error(\"Realtime requires a live audio track\");\n\t\t}\n\t\tthis.audio.startCapture(stream, { ownsStream: supplied == null });\n\t}\n\tsendAudio(audio) {\n\t\tif (!this.ready || !this.transport.isOpen) return;\n\t\tif (this.pendingAudio >= 8) {\n\t\t\tthis.transport.fail(/* @__PURE__ */ new Error(\"Realtime audio send queue is full\"));\n\t\t\treturn;\n\t\t}\n\t\tconst generation = this.generation;\n\t\tlet sent;\n\t\ttry {\n\t\t\tsent = this.transport.sendEvent({\n\t\t\t\ttype: \"input-audio-append\",\n\t\t\t\taudio\n\t\t\t}, void 0, true);\n\t\t} catch (error) {\n\t\t\tif (!this.ready || !this.transport.isOpen) return;\n\t\t\tthrow error;\n\t\t}\n\t\tthis.pendingAudio++;\n\t\tsent.then(() => {\n\t\t\tif (generation === this.generation) this.pendingAudio--;\n\t\t}, (error) => {\n\t\t\tif (generation === this.generation && this.ready && this.transport.isOpen) this.options.onFatalError(error);\n\t\t});\n\t}\n\tsendEvent(event, shouldSend) {\n\t\tif (event.type === \"session-update\") for (const key of [\"inputAudioFormat\", \"outputAudioFormat\"]) {\n\t\t\tconst update = event.config[key];\n\t\t\tif (update != null && (update.type !== this.config[key]?.type || update.rate != null && update.rate !== this.config[key]?.rate)) throw new Error(\"Changing Live WebSocket audio format requires reconnecting\");\n\t\t}\n\t\treturn this.transport.sendEvent(event, shouldSend);\n\t}\n\tplayAudio(audio) {\n\t\ttry {\n\t\t\tthis.audio.playAudio(audio);\n\t\t} catch (error) {\n\t\t\tthis.options.onError(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n\tstopPlayback() {\n\t\tthis.audio.stopPlayback();\n\t}\n\tresumePlayback() {\n\t\treturn this.audio.resumePlayback();\n\t}\n\tstopCapture() {\n\t\tthis.captureGeneration++;\n\t\tthis.ready = false;\n\t\tthis.capturingStarted = false;\n\t\tthis.captureEnabled = false;\n\t\tthis.audio.stopCapture();\n\t}\n\tfinish() {\n\t\treturn this.transport.finish();\n\t}\n\tdispose() {\n\t\tthis.generation++;\n\t\tthis.stopCapture();\n\t\tthis.ready = false;\n\t\tthis.capturingStarted = false;\n\t\tthis.pendingAudio = 0;\n\t\tthis.stream = void 0;\n\t\tthis.transport.disconnect();\n\t\tthis.audio.dispose();\n\t}\n};\n//#endregion\n//#region src/realtime/browser-realtime-webrtc.ts\nconst MAX_SESSION_ANSWER_BYTES = 1048576;\nasync function readSessionAnswer(response) {\n\tconst reader = response.body?.getReader();\n\tif (reader == null) throw new Error(\"Invalid realtime session answer\");\n\tconst decoder = new TextDecoder();\n\tlet bytes = 0;\n\tlet text = \"\";\n\ttry {\n\t\tif (Number(response.headers.get(\"content-length\")) > MAX_SESSION_ANSWER_BYTES) throw new Error(\"Realtime session answer exceeds the 1 MiB limit\");\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) return text + decoder.decode();\n\t\t\tbytes += value.byteLength;\n\t\t\tif (bytes > MAX_SESSION_ANSWER_BYTES) throw new Error(\"Realtime session answer exceeds the 1 MiB limit\");\n\t\t\ttext += decoder.decode(value, { stream: true });\n\t\t}\n\t} catch (error) {\n\t\treader.cancel(error).catch(() => {});\n\t\tthrow error;\n\t} finally {\n\t\treader.releaseLock();\n\t}\n}\nfunction selectAudioTrack(stream) {\n\tconst live = stream.getAudioTracks().filter((track) => track.readyState === \"live\");\n\treturn live.find((track) => track.enabled && !track.muted) ?? live[0];\n}\nvar BrowserRealtimeWebRTC = class {\n\tconstructor(options) {\n\t\tthis.options = options;\n\t\tthis.ownsStream = false;\n\t\tthis.generation = 0;\n\t\tthis.closingNotified = false;\n\t\tthis.captureGeneration = 0;\n\t\tthis.senderOperations = Promise.resolve();\n\t\tthis.trackCleanups = [];\n\t}\n\tasync connect({ api, sessionConfig, stream, timeoutMs, capture = true }) {\n\t\tconst generation = this.generation + 1;\n\t\tthis.dispose();\n\t\tconst current = () => generation === this.generation;\n\t\tif (!current()) return;\n\t\tconst config = this.options.model.getWebRTCConfig?.();\n\t\tif (!current()) return;\n\t\tif (config == null) throw new Error(\"This model does not support WebRTC configuration\");\n\t\tconst abort = new AbortController();\n\t\tthis.abort = abort;\n\t\tconst timeout = setTimeout(() => abort.abort(/* @__PURE__ */ new Error(\"Realtime startup timed out\")), timeoutMs);\n\t\tconst cancelled = new Promise((_, reject) => {\n\t\t\tabort.signal.addEventListener(\"abort\", () => reject(abort.signal.reason), { once: true });\n\t\t});\n\t\tconst start = async () => {\n\t\t\tconst captureGeneration = this.captureGeneration;\n\t\t\tlet media = capture ? stream ?? await navigator.mediaDevices.getUserMedia({ audio: true }) : void 0;\n\t\t\tif (!current() || abort.signal.aborted) {\n\t\t\t\tif (stream == null) media?.getTracks().forEach((track) => track.stop());\n\t\t\t\tthrow new Error(\"Realtime connection cancelled\");\n\t\t\t}\n\t\t\tif (captureGeneration !== this.captureGeneration) {\n\t\t\t\tif (stream == null) media?.getTracks().forEach((track) => track.stop());\n\t\t\t\tmedia = void 0;\n\t\t\t}\n\t\t\tthis.stream = media;\n\t\t\tthis.ownsStream = stream == null;\n\t\t\tconst track = media == null ? void 0 : selectAudioTrack(media);\n\t\t\tif (media != null && track == null) throw new Error(\"Realtime requires a live audio track\");\n\t\t\tconst pc = new RTCPeerConnection();\n\t\t\tthis.pc = pc;\n\t\t\tconst audio = document.createElement(\"audio\");\n\t\t\taudio.autoplay = true;\n\t\t\tthis.audio = audio;\n\t\t\taudio.onplaying = () => {\n\t\t\t\tif (current()) this.options.onPlaying(true);\n\t\t\t};\n\t\t\tconst stopped = () => {\n\t\t\t\tif (current()) this.options.onPlaying(false);\n\t\t\t};\n\t\t\taudio.onpause = stopped;\n\t\t\taudio.onended = stopped;\n\t\t\taudio.onwaiting = stopped;\n\t\t\tpc.ontrack = (event) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\taudio.srcObject = event.streams[0] ?? new MediaStream([event.track]);\n\t\t\t\taudio.play().catch((error) => {\n\t\t\t\t\tif (current()) this.options.onError(error);\n\t\t\t\t});\n\t\t\t};\n\t\t\tpc.onconnectionstatechange = () => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tif (pc.connectionState === \"connected\") clearTimeout(this.disconnectTimer);\n\t\t\t\telse if (pc.connectionState === \"disconnected\") {\n\t\t\t\t\tclearTimeout(this.disconnectTimer);\n\t\t\t\t\tthis.disconnectTimer = setTimeout(() => {\n\t\t\t\t\t\tif (current() && pc.connectionState === \"disconnected\") this.fail(/* @__PURE__ */ new Error(\"Realtime peer disconnected beyond recovery grace period\"));\n\t\t\t\t\t}, this.options.disconnectTimeoutMs ?? 5e3);\n\t\t\t\t} else if (pc.connectionState === \"closed\") this.drainClose(/* @__PURE__ */ new Error(\"Realtime peer connection closed\"));\n\t\t\t\telse if (pc.connectionState === \"failed\") this.fail(/* @__PURE__ */ new Error(`Realtime peer connection ${pc.connectionState}`));\n\t\t\t};\n\t\t\tpc.oniceconnectionstatechange = () => {\n\t\t\t\tif (current() && pc.iceConnectionState === \"failed\") this.fail(/* @__PURE__ */ new Error(\"Realtime ICE connection failed\"));\n\t\t\t};\n\t\t\tconst dc = pc.createDataChannel(config.dataChannelLabel);\n\t\t\tthis.dc = dc;\n\t\t\tconst codec = new RealtimeEventChannel({\n\t\t\t\tmodel: this.options.model,\n\t\t\t\tonEvent: this.options.onEvent,\n\t\t\t\tonError: this.options.onError,\n\t\t\t\tonFatalError: (error) => {\n\t\t\t\t\tif (current()) this.fail(error);\n\t\t\t\t},\n\t\t\t\tsend: (data) => {\n\t\t\t\t\tif (!current() || this.finishing || dc.readyState !== \"open\") throw new Error(\"Realtime data channel is not open\");\n\t\t\t\t\tif (dc.bufferedAmount > 1048576) throw new Error(\"Realtime data channel buffer is full\");\n\t\t\t\t\tconst encoded = typeof data === \"string\" ? data : JSON.stringify(data);\n\t\t\t\t\tif (!current() || this.finishing || dc.readyState !== \"open\") throw new Error(\"Realtime data channel is not open\");\n\t\t\t\t\tdc.send(encoded);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (!current()) {\n\t\t\t\tcodec.dispose();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.codec = codec;\n\t\t\tdc.onmessage = (event) => {\n\t\t\t\tif (current()) this.codec?.receive(event.data);\n\t\t\t};\n\t\t\tdc.onclose = () => {\n\t\t\t\tif (current()) this.drainClose(/* @__PURE__ */ new Error(\"Realtime data channel closed\"));\n\t\t\t};\n\t\t\tdc.onerror = () => {\n\t\t\t\tif (current()) this.fail(/* @__PURE__ */ new Error(\"Realtime data channel error\"));\n\t\t\t};\n\t\t\tconst opened = new Promise((resolve, reject) => {\n\t\t\t\tthis.rejectStartup = reject;\n\t\t\t\tdc.onopen = () => {\n\t\t\t\t\tthis.rejectStartup = void 0;\n\t\t\t\t\tresolve();\n\t\t\t\t};\n\t\t\t});\n\t\t\topened.catch(() => {});\n\t\t\tconst gathered = new Promise((resolve) => {\n\t\t\t\tpc.onicegatheringstatechange = () => {\n\t\t\t\t\tif (pc.iceGatheringState === \"complete\") resolve();\n\t\t\t\t};\n\t\t\t});\n\t\t\tthis.sender = media != null && track != null ? pc.addTrack(track, media) : pc.addTransceiver(\"audio\", { direction: \"sendrecv\" }).sender;\n\t\t\tthis.observeCapture();\n\t\t\tif (!current() || abort.signal.aborted) return;\n\t\t\tconst offer = await pc.createOffer();\n\t\t\tif (!current() || abort.signal.aborted) return;\n\t\t\tawait pc.setLocalDescription(offer);\n\t\t\tif (pc.iceGatheringState !== \"complete\") await Promise.race([gathered, cancelled]);\n\t\t\tif (!current() || abort.signal.aborted) return;\n\t\t\tconst sdp = pc.localDescription?.sdp;\n\t\t\tif (sdp == null) throw new Error(\"Realtime offer has no SDP\");\n\t\t\tconst response = await fetch(api, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tsdp,\n\t\t\t\t\tsessionConfig\n\t\t\t\t}),\n\t\t\t\tsignal: abort.signal\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`Failed to create realtime session: ${response.status}`);\n\t\t\tconst parsed = await safeParseJSON({ text: await readSessionAnswer(response) });\n\t\t\tif (!current() || abort.signal.aborted) return;\n\t\t\tif (!parsed.success || typeof parsed.value !== \"object\" || parsed.value == null || !(\"sdp\" in parsed.value) || typeof parsed.value.sdp !== \"string\" || parsed.value.sdp.trim().length === 0 || !(\"sessionId\" in parsed.value) || typeof parsed.value.sessionId !== \"string\" || parsed.value.sessionId.trim().length === 0) throw new Error(\"Invalid realtime session answer\");\n\t\t\tawait pc.setRemoteDescription({\n\t\t\t\ttype: \"answer\",\n\t\t\t\tsdp: parsed.value.sdp\n\t\t\t});\n\t\t\tawait Promise.race([opened, cancelled]);\n\t\t};\n\t\ttry {\n\t\t\tawait Promise.race([start(), cancelled]);\n\t\t} catch (error) {\n\t\t\tif (current()) this.dispose();\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t\tthis.rejectStartup = void 0;\n\t\t}\n\t}\n\tsendEvent(event, shouldSend) {\n\t\tif (this.finishing || this.dc?.readyState !== \"open\") throw new Error(\"Realtime data channel is not open\");\n\t\treturn this.codec?.send(event, shouldSend) ?? Promise.resolve();\n\t}\n\tasync resumePlayback() {\n\t\tif (this.audio == null) throw new Error(\"Realtime playback is not connected\");\n\t\tawait this.audio.play();\n\t}\n\tstopPlayback() {\n\t\tthis.audio?.pause();\n\t}\n\tfinish() {\n\t\treturn this.codec?.finish() ?? Promise.resolve();\n\t}\n\tfail(error) {\n\t\tif (this.finishing === \"failure\") return;\n\t\tthis.finishing = \"failure\";\n\t\tclearTimeout(this.finishTimer);\n\t\tif (this.rejectStartup != null) {\n\t\t\tthis.rejectStartup(error);\n\t\t\tthis.abort?.abort(error);\n\t\t\treturn;\n\t\t}\n\t\tconst generation = this.generation;\n\t\tconst drain = this.finish();\n\t\tthis.notifyClosing();\n\t\tif (generation !== this.generation) return;\n\t\tthis.stopCaptureForShutdown(generation);\n\t\tif (generation !== this.generation) return;\n\t\tif (this.options.onFatalError != null) {\n\t\t\tthis.options.onFatalError(error, drain);\n\t\t\treturn;\n\t\t}\n\t\tconst complete = () => {\n\t\t\tif (generation !== this.generation) return;\n\t\t\tthis.dispose();\n\t\t\ttry {\n\t\t\t\tthis.options.onClose();\n\t\t\t} catch (cause) {\n\t\t\t\tthis.reportCallbackError(cause);\n\t\t\t}\n\t\t};\n\t\tthis.finishTimer = setTimeout(complete, 1e3);\n\t\tthis.awaitDrain(drain, complete);\n\t\ttry {\n\t\t\tthis.options.onError(error);\n\t\t} catch {}\n\t}\n\tdrainClose(error) {\n\t\tif (this.finishing) return;\n\t\tif (this.rejectStartup != null) {\n\t\t\tthis.fail(error);\n\t\t\treturn;\n\t\t}\n\t\tthis.finishing = \"close\";\n\t\tconst generation = this.generation;\n\t\tconst complete = () => {\n\t\t\tif (generation !== this.generation || this.finishing !== \"close\") return;\n\t\t\tclearTimeout(this.finishTimer);\n\t\t\ttry {\n\t\t\t\tthis.options.onClose(error);\n\t\t\t} catch (cause) {\n\t\t\t\tthis.reportCallbackError(cause);\n\t\t\t} finally {\n\t\t\t\tif (generation === this.generation) this.dispose();\n\t\t\t}\n\t\t};\n\t\tthis.finishTimer = setTimeout(complete, 1e3);\n\t\tthis.awaitDrain(this.finish(), complete);\n\t\tthis.notifyClosing();\n\t\tif (generation !== this.generation) return;\n\t\tthis.stopCaptureForShutdown(generation);\n\t}\n\tnotifyClosing() {\n\t\tif (this.closingNotified) return;\n\t\tthis.closingNotified = true;\n\t\ttry {\n\t\t\tthis.options.onClosing?.();\n\t\t} catch (error) {\n\t\t\tthis.reportCallbackError(error);\n\t\t}\n\t}\n\tasync stopCaptureForShutdown(generation) {\n\t\ttry {\n\t\t\tawait this.stopCapture();\n\t\t} catch (cause) {\n\t\t\tif (generation !== this.generation || this.finishing !== \"close\") return;\n\t\t\ttry {\n\t\t\t\tthis.fail(cause instanceof Error ? cause : new Error(String(cause)));\n\t\t\t} catch (error) {\n\t\t\t\tthis.reportCallbackError(error);\n\t\t\t}\n\t\t}\n\t}\n\tasync awaitDrain(drain, complete) {\n\t\ttry {\n\t\t\tawait drain;\n\t\t} catch {}\n\t\ttry {\n\t\t\tcomplete();\n\t\t} catch (error) {\n\t\t\tthis.reportCallbackError(error);\n\t\t}\n\t}\n\treportCallbackError(error) {\n\t\ttry {\n\t\t\tthis.options.onError(error instanceof Error ? error : new Error(String(error)));\n\t\t} catch {}\n\t}\n\tasync stopCapture() {\n\t\tconst generation = ++this.captureGeneration;\n\t\tfor (const cleanup of this.trackCleanups) cleanup();\n\t\tthis.trackCleanups = [];\n\t\tif (this.ownsStream) this.stream?.getTracks().forEach((track) => track.stop());\n\t\tthis.stream = void 0;\n\t\tconst pc = this.pc;\n\t\tconst sender = this.sender;\n\t\tawait this.queueSenderOperation(async () => {\n\t\t\tif (pc !== this.pc || sender !== this.sender) return;\n\t\t\tif (pc != null && sender != null) await this.detachSender(pc, sender);\n\t\t\tif (generation === this.captureGeneration && pc === this.pc) this.options.onCapturing(false);\n\t\t});\n\t}\n\tasync startCapture(supplied) {\n\t\tconst generation = this.captureGeneration + 1;\n\t\tawait this.stopCapture();\n\t\tif (generation !== this.captureGeneration || this.pc == null || this.finishing) return;\n\t\tconst media = supplied ?? await navigator.mediaDevices.getUserMedia({ audio: true });\n\t\tif (generation !== this.captureGeneration || this.pc == null || this.finishing) {\n\t\t\tif (supplied == null) media.getTracks().forEach((track) => track.stop());\n\t\t\treturn;\n\t\t}\n\t\tconst track = selectAudioTrack(media);\n\t\tif (track == null) {\n\t\t\tif (supplied == null) media.getTracks().forEach((track) => track.stop());\n\t\t\tthrow new Error(\"Realtime requires a live audio track\");\n\t\t}\n\t\tconst pc = this.pc;\n\t\tconst sender = this.sender;\n\t\tawait this.queueSenderOperation(async () => {\n\t\t\tconst current = () => generation === this.captureGeneration && pc === this.pc && sender === this.sender && pc.connectionState !== \"closed\" && !this.finishing;\n\t\t\tlet attached = false;\n\t\t\ttry {\n\t\t\t\tif (!current() || sender == null) return;\n\t\t\t\tawait sender.replaceTrack(track);\n\t\t\t\tif (!current()) {\n\t\t\t\t\tif (pc === this.pc) await this.detachSender(pc, sender);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.stream = media;\n\t\t\t\tthis.ownsStream = supplied == null;\n\t\t\t\tattached = true;\n\t\t\t\tthis.observeCapture();\n\t\t\t} finally {\n\t\t\t\tif (!attached && supplied == null) media.getTracks().forEach((track) => track.stop());\n\t\t\t}\n\t\t});\n\t}\n\tqueueSenderOperation(operation) {\n\t\tconst pending = this.senderOperations.then(operation);\n\t\tthis.senderOperations = pending.catch(() => {});\n\t\treturn pending;\n\t}\n\tasync detachSender(pc, sender) {\n\t\tif (pc.connectionState === \"closed\") return;\n\t\ttry {\n\t\t\tawait sender.replaceTrack(null);\n\t\t} catch (error) {\n\t\t\tif (pc !== this.pc) return;\n\t\t\tthis.closePeer(pc);\n\t\t\tthis.fail(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t}\n\tclosePeer(pc) {\n\t\tpc.ontrack = null;\n\t\tpc.onconnectionstatechange = null;\n\t\tpc.oniceconnectionstatechange = null;\n\t\tpc.onicegatheringstatechange = null;\n\t\tif (pc.connectionState !== \"closed\") pc.close();\n\t}\n\tobserveCapture() {\n\t\tconst generation = this.captureGeneration;\n\t\tconst sender = this.sender;\n\t\tconst track = sender?.track;\n\t\tconst update = () => {\n\t\t\tif (generation === this.captureGeneration && this.sender === sender) this.options.onCapturing(sender?.track != null && sender.track.readyState === \"live\" && sender.track.enabled && !sender.track.muted);\n\t\t};\n\t\tif (track != null) for (const event of [\n\t\t\t\"ended\",\n\t\t\t\"mute\",\n\t\t\t\"unmute\"\n\t\t]) {\n\t\t\ttrack.addEventListener(event, update);\n\t\t\tthis.trackCleanups.push(() => track.removeEventListener(event, update));\n\t\t}\n\t\tupdate();\n\t}\n\tdispose() {\n\t\tthis.generation++;\n\t\tthis.captureGeneration++;\n\t\tclearTimeout(this.finishTimer);\n\t\tclearTimeout(this.disconnectTimer);\n\t\tthis.finishing = void 0;\n\t\tthis.closingNotified = false;\n\t\tthis.senderOperations = Promise.resolve();\n\t\tthis.abort?.abort(/* @__PURE__ */ new Error(\"Realtime connection cancelled\"));\n\t\tthis.abort = void 0;\n\t\tthis.codec?.dispose();\n\t\tthis.codec = void 0;\n\t\tif (this.dc != null) {\n\t\t\tthis.dc.onopen = null;\n\t\t\tthis.dc.onclose = null;\n\t\t\tthis.dc.onerror = null;\n\t\t\tthis.dc.onmessage = null;\n\t\t\tthis.dc.close();\n\t\t\tthis.dc = void 0;\n\t\t}\n\t\tif (this.pc != null) {\n\t\t\tthis.closePeer(this.pc);\n\t\t\tthis.pc = void 0;\n\t\t}\n\t\tfor (const cleanup of this.trackCleanups) cleanup();\n\t\tthis.trackCleanups = [];\n\t\tif (this.ownsStream) this.stream?.getTracks().forEach((track) => track.stop());\n\t\tthis.stream = void 0;\n\t\tthis.sender = void 0;\n\t\tif (this.audio != null) {\n\t\t\tthis.audio.onplaying = null;\n\t\t\tthis.audio.onpause = null;\n\t\t\tthis.audio.onended = null;\n\t\t\tthis.audio.onwaiting = null;\n\t\t\tthis.audio.pause();\n\t\t\tthis.audio.srcObject = null;\n\t\t\tthis.audio = void 0;\n\t\t}\n\t\tthis.options.onCapturing(false);\n\t\tthis.options.onPlaying(false);\n\t}\n};\n//#endregion\n//#region src/realtime/realtime-attempt.ts\n/** Cancellation and settlement belong to one connection attempt. */\nvar RealtimeAttempt = class {\n\tconstructor() {\n\t\tthis.abort = new AbortController();\n\t\tthis.timers = /* @__PURE__ */ new Map();\n\t\tthis.active = true;\n\t\tthis.ready = false;\n\t\tthis.closing = false;\n\t\tthis.transportClosing = false;\n\t}\n\ttimer(name, duration, callback) {\n\t\tthis.clearTimer(name);\n\t\tthis.timers.set(name, setTimeout(() => {\n\t\t\tthis.timers.delete(name);\n\t\t\tif (this.active) callback();\n\t\t}, duration));\n\t}\n\tclearTimer(name) {\n\t\tclearTimeout(this.timers.get(name));\n\t\tthis.timers.delete(name);\n\t}\n\tbeginClose() {\n\t\tthis.closing = true;\n\t\treturn this.closePromise ??= new Promise((resolve) => {\n\t\t\tthis.settleClose = resolve;\n\t\t});\n\t}\n\tretire() {\n\t\tif (!this.active) return;\n\t\tthis.active = false;\n\t\tthis.abort.abort();\n\t\tfor (const timer of this.timers.values()) clearTimeout(timer);\n\t\tthis.timers.clear();\n\t\tthis.settleClose?.();\n\t\tthis.settleClose = void 0;\n\t}\n};\n//#endregion\n//#region src/realtime/realtime-command-tracker.ts\n/** Attempt-local ACK correlation; unresolved commands are never evicted. */\nvar RealtimeCommandTracker = class {\n\tconstructor(sendCommand) {\n\t\tthis.sendCommand = sendCommand;\n\t\tthis.pending = /* @__PURE__ */ new Map();\n\t\tthis.recent = /* @__PURE__ */ new Set();\n\t}\n\tvalidateId(id) {\n\t\tif (this.pending.has(id) || this.recent.has(id)) throw new Error(\"Realtime command ID was already used; retry with a fresh eventId\");\n\t\tif (this.pending.size >= 512) throw new Error(\"Too many pending realtime commands\");\n\t}\n\tcomplete(id) {\n\t\tconst command = this.pending.get(id);\n\t\tif (command == null) return;\n\t\tthis.pending.delete(id);\n\t\tthis.recent.add(id);\n\t\tif (this.recent.size > 4096) {\n\t\t\tconst oldest = this.recent.values().next().value;\n\t\t\tif (oldest != null) this.recent.delete(oldest);\n\t\t}\n\t\treturn command;\n\t}\n\tsend(event) {\n\t\tconst muted = event.type === \"input-audio-mute\" ? true : event.type === \"input-audio-unmute\" ? false : void 0;\n\t\tif (event.type === \"input-audio-mute\" || event.type === \"input-audio-unmute\") event = {\n\t\t\t...event,\n\t\t\teventId: event.eventId ?? generateId$1()\n\t\t};\n\t\tconst id = \"eventId\" in event ? event.eventId : void 0;\n\t\tif (id != null) {\n\t\t\tthis.validateId(id);\n\t\t\tthis.pending.set(id, { muted });\n\t\t}\n\t\tconst awaitsAcknowledgement = event.type === \"context-append\" || event.type === \"session-update\" || muted != null;\n\t\ttry {\n\t\t\tconst sent = this.sendCommand(event);\n\t\t\tsent.then(() => {\n\t\t\t\tif (id != null && !awaitsAcknowledgement) this.complete(id);\n\t\t\t}, () => {\n\t\t\t\tif (id != null) this.complete(id);\n\t\t\t});\n\t\t\treturn sent;\n\t\t} catch (error) {\n\t\t\tif (id != null) this.complete(id);\n\t\t\tthrow error;\n\t\t}\n\t}\n\treceive(event) {\n\t\tif (event.type === \"command-acknowledged\" && event.clientEventId != null) return this.complete(event.clientEventId);\n\t\tif (event.type === \"error\" && event.clientEventId != null) this.complete(event.clientEventId);\n\t}\n};\n//#endregion\n//#region src/realtime/validate-realtime-setup.ts\nconst setupSchema = z.object({\n\ttoken: z.string().refine((value) => value.trim().length > 0),\n\turl: z.string().refine((value) => {\n\t\ttry {\n\t\t\tconst url = new URL(value);\n\t\t\treturn (url.protocol === \"ws:\" || url.protocol === \"wss:\") && url.hostname !== \"\";\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}),\n\texpiresAt: z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),\n\ttools: z.array(z.object({\n\t\ttype: z.literal(\"function\"),\n\t\tname: z.string().min(1),\n\t\tdescription: z.string().optional(),\n\t\tparameters: z.record(z.string(), z.unknown())\n\t})).optional()\n});\nfunction validateRealtimeSetup(payload) {\n\tconst result = setupSchema.safeParse(payload);\n\tif (!result.success) throw new Error(\"Invalid realtime setup: expected a nonempty token, a ws(s) URL, and valid optional expiresAt/tools\");\n\treturn result.data;\n}\n//#endregion\n//#region src/realtime/realtime-session-state.ts\nfunction createSessionState() {\n\treturn {\n\t\ttranscripts: [],\n\t\tdelegations: [],\n\t\tisInputMuted: false,\n\t\tfinalization: \"pending\"\n\t};\n}\nfunction reduceSessionState(state, event, limit, muted) {\n\tswitch (event.type) {\n\t\tcase \"session-started\": return {\n\t\t\t...state,\n\t\t\tsessionId: event.sessionId,\n\t\t\tdelegationMode: event.delegationMode\n\t\t};\n\t\tcase \"session-usage\": return {\n\t\t\t...state,\n\t\t\tusage: event.usage\n\t\t};\n\t\tcase \"session-closed\": return {\n\t\t\t...state,\n\t\t\tsessionId: event.sessionId ?? state.sessionId,\n\t\t\tusage: event.usage,\n\t\t\tterminationReason: event.reason,\n\t\t\tfinalization: \"confirmed\"\n\t\t};\n\t\tcase \"transcript-fragment\": return {\n\t\t\t...state,\n\t\t\ttranscripts: [...state.transcripts, event].slice(-limit)\n\t\t};\n\t\tcase \"delegation-created\": return state.delegations.some((item) => item.delegationId === event.delegationId) ? state : {\n\t\t\t...state,\n\t\t\tdelegations: [...state.delegations, event].slice(-limit)\n\t\t};\n\t\tcase \"command-acknowledged\": return muted == null ? state : {\n\t\t\t...state,\n\t\t\tisInputMuted: muted\n\t\t};\n\t\tdefault: return state;\n\t}\n}\n//#endregion\n//#region src/realtime/realtime-event-reducer.ts\nfunction createInitialRealtimeState() {\n\treturn {\n\t\tstatus: \"disconnected\",\n\t\tmessages: [],\n\t\tevents: [],\n\t\tisCapturing: false,\n\t\tisPlaying: false\n\t};\n}\nvar RealtimeEventReducer = class {\n\tconstructor(maxEvents = 500) {\n\t\tthis.maxEvents = maxEvents;\n\t\tthis.currentAssistantMessageId = null;\n\t\tthis.textAccumulators = /* @__PURE__ */ new Map();\n\t\tthis.toolArgAccumulators = /* @__PURE__ */ new Map();\n\t\tthis.toolCallIdToMessageId = /* @__PURE__ */ new Map();\n\t\tthis.toolCallIdToName = /* @__PURE__ */ new Map();\n\t\tthis.inputAudioMessageInsertIndex = /* @__PURE__ */ new Map();\n\t\tthis.itemIdToPartLocation = /* @__PURE__ */ new Map();\n\t}\n\tsetStatus(state, status) {\n\t\treturn {\n\t\t\t...state,\n\t\t\tstatus\n\t\t};\n\t}\n\tsetCapturing(state, isCapturing) {\n\t\treturn {\n\t\t\t...state,\n\t\t\tisCapturing\n\t\t};\n\t}\n\tsetPlaying(state, isPlaying) {\n\t\treturn {\n\t\t\t...state,\n\t\t\tisPlaying\n\t\t};\n\t}\n\taddUserTextMessage(state, text) {\n\t\treturn {\n\t\t\t...state,\n\t\t\tmessages: [...state.messages, {\n\t\t\t\tid: `user-${Date.now()}`,\n\t\t\t\trole: \"user\",\n\t\t\t\tparts: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext,\n\t\t\t\t\tstate: \"done\"\n\t\t\t\t}]\n\t\t\t}]\n\t\t};\n\t}\n\taddToolOutput(state, callId, result) {\n\t\treturn {\n\t\t\tstate: this.updateToolPartState(state, callId, result),\n\t\t\toutput: {\n\t\t\t\tcallId,\n\t\t\t\tname: this.toolCallIdToName.get(callId),\n\t\t\t\toutput: JSON.stringify(result)\n\t\t\t}\n\t\t};\n\t}\n\tasync reduceServerEvent(state, event) {\n\t\tlet nextState = this.pushEvent(state, event);\n\t\tconst effects = [];\n\t\tswitch (event.type) {\n\t\t\tcase \"session-created\":\n\t\t\tcase \"session-updated\":\n\t\t\t\tif (nextState.status === \"connecting\") nextState = this.setStatus(nextState, \"connected\");\n\t\t\t\tbreak;\n\t\t\tcase \"audio-delta\":\n\t\t\t\teffects.push({\n\t\t\t\t\ttype: \"play-audio\",\n\t\t\t\t\titemId: event.itemId,\n\t\t\t\t\tdelta: event.delta\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"audio-committed\":\n\t\t\t\tif (event.itemId != null) this.inputAudioMessageInsertIndex.set(event.itemId, nextState.messages.length);\n\t\t\t\tbreak;\n\t\t\tcase \"audio-transcript-delta\":\n\t\t\tcase \"text-delta\":\n\t\t\t\tnextState = this.appendTextDelta(nextState, event.itemId, event.delta);\n\t\t\t\tbreak;\n\t\t\tcase \"audio-transcript-done\":\n\t\t\t\tnextState = this.finalizeText(nextState, event.itemId, event.transcript);\n\t\t\t\tbreak;\n\t\t\tcase \"text-done\":\n\t\t\t\tnextState = this.finalizeText(nextState, event.itemId, event.text);\n\t\t\t\tbreak;\n\t\t\tcase \"input-transcription-completed\":\n\t\t\t\tnextState = this.addInputTranscriptionMessage(nextState, event.itemId, event.transcript);\n\t\t\t\tbreak;\n\t\t\tcase \"response-created\":\n\t\t\tcase \"response-done\":\n\t\t\t\tthis.currentAssistantMessageId = null;\n\t\t\t\tbreak;\n\t\t\tcase \"speech-started\":\n\t\t\t\tthis.currentAssistantMessageId = null;\n\t\t\t\teffects.push({ type: \"speech-started\" });\n\t\t\t\tbreak;\n\t\t\tcase \"function-call-arguments-delta\": {\n\t\t\t\tconst { state: updatedState, messageId } = this.getOrCreateAssistantMessage(nextState);\n\t\t\t\tnextState = updatedState;\n\t\t\t\tthis.toolCallIdToMessageId.set(event.callId, messageId);\n\t\t\t\tconst acc = this.toolArgAccumulators.get(event.callId) ?? \"\";\n\t\t\t\tthis.toolArgAccumulators.set(event.callId, acc + event.delta);\n\t\t\t\tnextState = this.ensureToolPart(nextState, messageId, event.callId);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"function-call-arguments-done\": {\n\t\t\t\tthis.toolArgAccumulators.delete(event.callId);\n\t\t\t\tthis.toolCallIdToName.set(event.callId, event.name);\n\t\t\t\tconst parseResult = await safeParseJSON({ text: event.arguments });\n\t\t\t\tconst parsedInput = parseResult.success ? parseResult.value : {};\n\t\t\t\tconst messageId = this.toolCallIdToMessageId.get(event.callId);\n\t\t\t\tif (messageId != null) nextState = this.markToolInputAvailable(nextState, messageId, event.callId, event.name, parsedInput);\n\t\t\t\tif (!parseResult.success) effects.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror: /* @__PURE__ */ new Error(`Failed to parse tool arguments: ${event.arguments}`)\n\t\t\t\t});\n\t\t\t\telse effects.push({\n\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\tcallId: event.callId,\n\t\t\t\t\tname: event.name,\n\t\t\t\t\targs: parsedInput,\n\t\t\t\t\trawArguments: event.arguments\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"error\": effects.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\terror: new Error(event.message)\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tstate: nextState,\n\t\t\teffects\n\t\t};\n\t}\n\tpushEvent(state, event) {\n\t\tconst events = [...state.events, event];\n\t\treturn {\n\t\t\t...state,\n\t\t\tevents: events.length > this.maxEvents ? events.slice(-this.maxEvents) : events\n\t\t};\n\t}\n\tgetOrCreateAssistantMessage(state) {\n\t\tif (this.currentAssistantMessageId != null) return {\n\t\t\tstate,\n\t\t\tmessageId: this.currentAssistantMessageId\n\t\t};\n\t\tconst messageId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;\n\t\tthis.currentAssistantMessageId = messageId;\n\t\treturn {\n\t\t\tstate: {\n\t\t\t\t...state,\n\t\t\t\tmessages: [...state.messages, {\n\t\t\t\t\tid: messageId,\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tparts: []\n\t\t\t\t}]\n\t\t\t},\n\t\t\tmessageId\n\t\t};\n\t}\n\taddInputTranscriptionMessage(state, itemId, transcript) {\n\t\tconst messageId = `user-${itemId}`;\n\t\tif (state.messages.find((message) => message.id === messageId) != null) return {\n\t\t\t...state,\n\t\t\tmessages: state.messages.map((message) => message.id === messageId ? {\n\t\t\t\t...message,\n\t\t\t\tparts: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: transcript,\n\t\t\t\t\tstate: \"done\"\n\t\t\t\t}]\n\t\t\t} : message)\n\t\t};\n\t\tconst insertIndex = Math.min(this.inputAudioMessageInsertIndex.get(itemId) ?? state.messages.length, state.messages.length);\n\t\tconst messages = [...state.messages];\n\t\tmessages.splice(insertIndex, 0, {\n\t\t\tid: messageId,\n\t\t\trole: \"user\",\n\t\t\tparts: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: transcript,\n\t\t\t\tstate: \"done\"\n\t\t\t}]\n\t\t});\n\t\treturn {\n\t\t\t...state,\n\t\t\tmessages\n\t\t};\n\t}\n\tappendTextDelta(state, itemId, delta) {\n\t\tconst { state: stateWithMessage, messageId } = this.getOrCreateAssistantMessage(state);\n\t\tconst text = (this.textAccumulators.get(itemId) ?? \"\") + delta;\n\t\tthis.textAccumulators.set(itemId, text);\n\t\tconst location = this.itemIdToPartLocation.get(itemId);\n\t\tif (location != null) return this.updateMessagePart(stateWithMessage, location.messageId, location.partIndex, {\n\t\t\ttype: \"text\",\n\t\t\ttext,\n\t\t\tstate: \"streaming\"\n\t\t});\n\t\treturn {\n\t\t\t...stateWithMessage,\n\t\t\tmessages: stateWithMessage.messages.map((message) => {\n\t\t\t\tif (message.id !== messageId) return message;\n\t\t\t\tconst partIndex = message.parts.length;\n\t\t\t\tthis.itemIdToPartLocation.set(itemId, {\n\t\t\t\t\tmessageId,\n\t\t\t\t\tpartIndex\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\t...message,\n\t\t\t\t\tparts: [...message.parts, {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\tstate: \"streaming\"\n\t\t\t\t\t}]\n\t\t\t\t};\n\t\t\t})\n\t\t};\n\t}\n\tfinalizeText(state, itemId, finalText) {\n\t\tconst text = finalText ?? this.textAccumulators.get(itemId) ?? \"\";\n\t\tthis.textAccumulators.delete(itemId);\n\t\tconst location = this.itemIdToPartLocation.get(itemId);\n\t\tif (location == null) return state;\n\t\tthis.itemIdToPartLocation.delete(itemId);\n\t\treturn this.updateMessagePart(state, location.messageId, location.partIndex, {\n\t\t\ttype: \"text\",\n\t\t\ttext,\n\t\t\tstate: \"done\"\n\t\t});\n\t}\n\tensureToolPart(state, messageId, callId) {\n\t\treturn {\n\t\t\t...state,\n\t\t\tmessages: state.messages.map((message) => {\n\t\t\t\tif (message.id !== messageId) return message;\n\t\t\t\tif (message.parts.find((part) => part.type === \"dynamic-tool\" && part.toolCallId === callId) != null) return message;\n\t\t\t\treturn {\n\t\t\t\t\t...message,\n\t\t\t\t\tparts: [...message.parts, {\n\t\t\t\t\t\ttype: \"dynamic-tool\",\n\t\t\t\t\t\ttoolName: \"\",\n\t\t\t\t\t\ttoolCallId: callId,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: void 0\n\t\t\t\t\t}]\n\t\t\t\t};\n\t\t\t})\n\t\t};\n\t}\n\tmarkToolInputAvailable(state, messageId, callId, name, input) {\n\t\treturn {\n\t\t\t...state,\n\t\t\tmessages: state.messages.map((message) => {\n\t\t\t\tif (message.id !== messageId) return message;\n\t\t\t\treturn {\n\t\t\t\t\t...message,\n\t\t\t\t\tparts: message.parts.map((part) => {\n\t\t\t\t\t\tif (part.type !== \"dynamic-tool\") return part;\n\t\t\t\t\t\tconst toolPart = part;\n\t\t\t\t\t\tif (toolPart.toolCallId !== callId) return part;\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t...toolPart,\n\t\t\t\t\t\t\ttoolName: name,\n\t\t\t\t\t\t\tstate: \"input-available\",\n\t\t\t\t\t\t\tinput\n\t\t\t\t\t\t};\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t})\n\t\t};\n\t}\n\tupdateToolPartState(state, callId, result) {\n\t\tconst messageId = this.toolCallIdToMessageId.get(callId);\n\t\tif (messageId == null) return state;\n\t\treturn {\n\t\t\t...state,\n\t\t\tmessages: state.messages.map((message) => {\n\t\t\t\tif (message.id !== messageId) return message;\n\t\t\t\treturn {\n\t\t\t\t\t...message,\n\t\t\t\t\tparts: message.parts.map((part) => {\n\t\t\t\t\t\tif (part.type !== \"dynamic-tool\") return part;\n\t\t\t\t\t\tconst toolPart = part;\n\t\t\t\t\t\tif (toolPart.toolCallId !== callId) return part;\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t...toolPart,\n\t\t\t\t\t\t\tstate: \"output-available\",\n\t\t\t\t\t\t\toutput: result\n\t\t\t\t\t\t};\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t})\n\t\t};\n\t}\n\tupdateMessagePart(state, messageId, partIndex, part) {\n\t\treturn {\n\t\t\t...state,\n\t\t\tmessages: state.messages.map((message) => {\n\t\t\t\tif (message.id !== messageId) return message;\n\t\t\t\tconst parts = [...message.parts];\n\t\t\t\tparts[partIndex] = part;\n\t\t\t\treturn {\n\t\t\t\t\t...message,\n\t\t\t\t\tparts\n\t\t\t\t};\n\t\t\t})\n\t\t};\n\t}\n};\n//#endregion\n//#region src/realtime/realtime-session.ts\nvar AbstractRealtimeSession = class {\n\tconstructor(options) {\n\t\tthis.options = options;\n\t\tthis.state = createInitialRealtimeState();\n\t\tthis.publication = 0;\n\t\tthis.captureGeneration = 0;\n\t\tthis.captureRequested = false;\n\t\tthis.currentResponseItemId = null;\n\t\tthis.toolCallsInResponse = /* @__PURE__ */ new Set();\n\t\tthis.submittedToolOutputs = /* @__PURE__ */ new Set();\n\t\tthis.responseToolCallsClosed = false;\n\t\tconst capabilities = options.model.capabilities;\n\t\tthis.sessionLifecycle = capabilities?.startup === \"session-start\" || capabilities?.finalization === \"session-close\";\n\t\tthis.continuous = capabilities?.conversation === \"continuous\";\n\t\tthis.maxEvents = options.maxEvents ?? 500;\n\t\tif (!Number.isSafeInteger(this.maxEvents) || this.maxEvents < 1) throw new Error(\"maxEvents must be a positive integer\");\n\t\tfor (const timeout of [\n\t\t\toptions.startupTimeoutMs ?? 3e4,\n\t\t\toptions.closeTimeoutMs ?? 15e3,\n\t\t\toptions.rtcDisconnectTimeoutMs ?? 5e3\n\t\t]) if (!Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw new Error(\"Realtime timeouts must be positive finite timer durations\");\n\t\tconst budget = options.maxPlaybackBufferSeconds ?? 2;\n\t\tif (!Number.isFinite(budget) || budget <= 0) throw new Error(\"maxPlaybackBufferSeconds must be positive and finite\");\n\t\tthis.reducer = new RealtimeEventReducer(this.maxEvents);\n\t\tthis.onToolCall = options.onToolCall;\n\t\tthis.onEvent = options.onEvent;\n\t\tthis.onError = options.onError;\n\t}\n\tvalidateConnection() {\n\t\tconst { model, api } = this.options;\n\t\tif ((!this.continuous || api.session != null) && this.options.maxPlaybackBufferSeconds != null) throw new Error(\"maxPlaybackBufferSeconds is supported only for continuous PCM sessions\");\n\t\tconst connection = api.session != null ? \"webrtc\" : api.token != null ? \"client-secret-websocket\" : \"server-websocket\";\n\t\tif (!(model.capabilities?.connections ?? [\"client-secret-websocket\"]).includes(connection) || model.capabilities?.transports != null && !model.capabilities.transports.includes(api.session != null ? \"webrtc\" : \"websocket\")) throw new Error(`Realtime model does not support ${connection}`);\n\t\tif (api.session != null) {\n\t\t\tif (model.getWebRTCConfig == null) throw new Error(\"Realtime model does not support WebRTC configuration\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.continuous && api.websocket == null) throw new Error(\"Continuous PCM sessions require an application WebSocket relay\");\n\t\tif (api.token != null && model.getWebSocketConfig == null) throw new Error(\"Realtime model does not support client-secret WebSocket configuration\");\n\t}\n\tasync connect(connectOptions) {\n\t\tif (this.attempt?.active) throw new Error(\"Realtime session is already active\");\n\t\tconst attempt = new RealtimeAttempt();\n\t\tthis.attempt = attempt;\n\t\tconst current = () => this.attempt === attempt && attempt.active;\n\t\ttry {\n\t\t\tthis.applyState({\n\t\t\t\t...this.state,\n\t\t\t\tstatus: \"connecting\"\n\t\t\t});\n\t\t\tif (!current()) return;\n\t\t\tthis.validateConnection();\n\t\t\tconst { model, api, sessionConfig } = this.options;\n\t\t\tif (connectOptions?.capture === false) this.stopAudioCapture();\n\t\t\tif (!current()) return;\n\t\t\tif (connectOptions?.stream != null && connectOptions.stream !== this.suppliedStream) {\n\t\t\t\tif (this.captureRequested && !this.sessionLifecycle && !this.continuous && api.session == null) this.startAudioCapture(connectOptions.stream);\n\t\t\t\telse this.suppliedStream = connectOptions.stream;\n\t\t\t}\n\t\t\tif (!current()) return;\n\t\t\tthis.reducer = new RealtimeEventReducer(this.maxEvents);\n\t\t\tthis.currentResponseItemId = null;\n\t\t\tthis.toolCallsInResponse.clear();\n\t\t\tthis.submittedToolOutputs.clear();\n\t\t\tthis.responseToolCallsClosed = false;\n\t\t\tif (this.sessionLifecycle) this.applyState({\n\t\t\t\t...this.state,\n\t\t\t\tsession: createSessionState()\n\t\t\t});\n\t\t\tif (!current()) return;\n\t\t\tthis.commands = new RealtimeCommandTracker((event) => {\n\t\t\t\tconst writable = () => current() && !attempt.transportClosing && attempt.cause == null && (!attempt.closing || event.type === \"session-close\");\n\t\t\t\tif (!writable()) throw new Error(\"Realtime connection is closed\");\n\t\t\t\treturn this.sendTransport(event, writable);\n\t\t\t});\n\t\t\tattempt.timer(\"startup\", this.options.startupTimeoutMs ?? 3e4, () => {\n\t\t\t\tif (current()) this.fail(/* @__PURE__ */ new Error(\"Realtime session startup timed out\"));\n\t\t\t});\n\t\t\tconst reportedTransportErrors = /* @__PURE__ */ new WeakSet();\n\t\t\tconst callbacks = {\n\t\t\t\tmodel,\n\t\t\t\tonEvent: async (event) => {\n\t\t\t\t\tif (!current()) return;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.handleServerEvent(event, attempt);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (current()) this.fail(error, (this.rtc ?? this.pcm ?? this.transport)?.finish());\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tonError: (error) => {\n\t\t\t\t\tif (current()) {\n\t\t\t\t\t\treportedTransportErrors.add(error);\n\t\t\t\t\t\tthis.reportError(error, attempt);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tonFatalError: (error, drain) => {\n\t\t\t\t\tif (current()) this.fail(error, drain);\n\t\t\t\t},\n\t\t\t\tonClosing: () => {\n\t\t\t\t\tif (!current()) return;\n\t\t\t\t\tattempt.beginClose();\n\t\t\t\t\tattempt.transportClosing = true;\n\t\t\t\t\tattempt.clearTimer(\"startup\");\n\t\t\t\t\tattempt.clearTimer(\"close\");\n\t\t\t\t\tthis.stopAudioCapture();\n\t\t\t\t\tif (!current()) return;\n\t\t\t\t\tthis.applyState({\n\t\t\t\t\t\t...this.state,\n\t\t\t\t\t\tstatus: attempt.cause == null ? \"closing\" : \"error\"\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tonClose: (error) => {\n\t\t\t\t\tif (!current()) return;\n\t\t\t\t\tconst finalizationConfirmed = model.capabilities?.finalization === \"session-close\" && this.state.session?.finalization === \"confirmed\";\n\t\t\t\t\tif (error != null && !finalizationConfirmed) this.fail(error, void 0, !reportedTransportErrors.has(error));\n\t\t\t\t\telse if (!attempt.ready && !finalizationConfirmed) this.fail(/* @__PURE__ */ new Error(\"Realtime connection closed before becoming ready\"));\n\t\t\t\t\telse this.disconnect();\n\t\t\t\t},\n\t\t\t\tonCapturing: (isCapturing) => {\n\t\t\t\t\tif (current()) this.applyState({\n\t\t\t\t\t\t...this.state,\n\t\t\t\t\t\tisCapturing\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tonPlaying: (isPlaying) => {\n\t\t\t\t\tif (current()) this.applyState({\n\t\t\t\t\t\t...this.state,\n\t\t\t\t\t\tisPlaying\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (api.session != null) {\n\t\t\t\tthis.rtc = new BrowserRealtimeWebRTC({\n\t\t\t\t\t...callbacks,\n\t\t\t\t\tdisconnectTimeoutMs: this.options.rtcDisconnectTimeoutMs\n\t\t\t\t});\n\t\t\t\tawait this.rtc.connect({\n\t\t\t\t\tapi: api.session,\n\t\t\t\t\tsessionConfig,\n\t\t\t\t\tstream: connectOptions?.stream,\n\t\t\t\t\tcapture: connectOptions?.capture,\n\t\t\t\t\ttimeoutMs: this.options.startupTimeoutMs ?? 3e4\n\t\t\t\t});\n\t\t\t} else if (api.websocket != null && model.capabilities?.conversation === \"continuous\") {\n\t\t\t\tthis.pcm = new BrowserRealtimeLiveWebSocket({\n\t\t\t\t\t...callbacks,\n\t\t\t\t\tsessionConfig,\n\t\t\t\t\tsampleRate: this.options.sampleRate,\n\t\t\t\t\tmaxPlaybackBufferSeconds: this.options.maxPlaybackBufferSeconds\n\t\t\t\t});\n\t\t\t\tthis.pcm.connect({\n\t\t\t\t\turl: api.websocket,\n\t\t\t\t\tprotocols: api.protocols,\n\t\t\t\t\tstream: connectOptions?.stream,\n\t\t\t\t\tcapture: connectOptions?.capture\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tthis.ensureAudio();\n\t\t\t\tlet config = sessionConfig ?? {};\n\t\t\t\tlet token;\n\t\t\t\tlet url = api.websocket;\n\t\t\t\tif (api.token != null) {\n\t\t\t\t\tconst response = await fetch(api.token, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\t\tbody: JSON.stringify({ sessionConfig }),\n\t\t\t\t\t\tsignal: attempt.abort.signal\n\t\t\t\t\t});\n\t\t\t\t\tif (!current()) return;\n\t\t\t\t\tif (!response.ok) throw new Error(`Failed to fetch realtime setup: ${response.status}`);\n\t\t\t\t\tconst payload = await response.json().catch(() => {\n\t\t\t\t\t\tthrow new Error(\"Invalid realtime setup response\");\n\t\t\t\t\t});\n\t\t\t\t\tif (!current() || attempt.closing) return;\n\t\t\t\t\tconst setup = validateRealtimeSetup(payload);\n\t\t\t\t\ttoken = setup.token;\n\t\t\t\t\turl = setup.url;\n\t\t\t\t\tconfig = {\n\t\t\t\t\t\t...sessionConfig,\n\t\t\t\t\t\t...setup.tools == null ? {} : { tools: setup.tools }\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (url == null) throw new Error(\"Realtime WebSocket URL is missing\");\n\t\t\t\tif (api.token != null && token == null) throw new Error(\"Realtime client-secret connection requires a token\");\n\t\t\t\tthis.ensureAudio().ensurePlaybackContext();\n\t\t\t\tif (!current()) return;\n\t\t\t\tthis.transport = new BrowserRealtimeTransport({\n\t\t\t\t\t...callbacks,\n\t\t\t\t\tonServerEvent: callbacks.onEvent\n\t\t\t\t});\n\t\t\t\tthis.transport.connect({\n\t\t\t\t\t...token != null ? {\n\t\t\t\t\t\tmode: \"client-secret\",\n\t\t\t\t\t\ttoken\n\t\t\t\t\t} : {\n\t\t\t\t\t\tmode: \"relay\",\n\t\t\t\t\t\tprotocols: api.protocols\n\t\t\t\t\t},\n\t\t\t\t\turl,\n\t\t\t\t\tonOpen: () => {\n\t\t\t\t\t\tconst writable = () => current() && !attempt.closing && attempt.cause == null;\n\t\t\t\t\t\tif (!writable()) return;\n\t\t\t\t\t\treturn this.sendTransport({\n\t\t\t\t\t\t\ttype: model.capabilities?.startup ?? \"session-update\",\n\t\t\t\t\t\t\tconfig\n\t\t\t\t\t\t}, writable);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (current()) this.fail(error);\n\t\t}\n\t}\n\tfail(error, drain, report = true) {\n\t\tconst attempt = this.attempt;\n\t\tif (attempt == null || !attempt.active || attempt.cause != null) return;\n\t\tattempt.cause = error instanceof Error ? error : new Error(String(error));\n\t\tif (drain != null) attempt.beginClose();\n\t\tthis.applyState({\n\t\t\t...this.state,\n\t\t\tstatus: \"error\"\n\t\t});\n\t\tif (this.attempt !== attempt || !attempt.active) return;\n\t\tthis.stopAudioCapture();\n\t\tif (this.attempt !== attempt || !attempt.active) return;\n\t\tif (drain == null) this.disconnect();\n\t\telse this.drainAttempt(attempt, drain);\n\t\tif (report) this.reportError(attempt.cause, attempt);\n\t}\n\tasync drainAttempt(attempt, drain) {\n\t\tif (this.attempt === attempt && attempt.active) attempt.timer(\"drain\", 1e3, () => this.finishAttempt(attempt));\n\t\ttry {\n\t\t\tawait drain;\n\t\t} catch {}\n\t\tthis.finishAttempt(attempt);\n\t}\n\tfinishAttempt(attempt) {\n\t\tif (this.attempt !== attempt || !attempt.active) return;\n\t\ttry {\n\t\t\tthis.disconnect();\n\t\t} catch (error) {\n\t\t\tthis.reportError(error, attempt);\n\t\t}\n\t}\n\tcloseFailed(attempt, error) {\n\t\tif (this.attempt !== attempt || !attempt.active || attempt.transportClosing) return;\n\t\tattempt.clearTimer(\"close\");\n\t\tconst transport = this.rtc ?? this.pcm ?? this.transport;\n\t\tthis.drainAttempt(attempt, transport?.finish());\n\t\tthis.reportError(error, attempt);\n\t}\n\tdisconnect() {\n\t\tconst attempt = this.attempt;\n\t\tthis.captureGeneration++;\n\t\tthis.captureRequested = false;\n\t\tthis.suppliedStream = void 0;\n\t\tconst transport = this.transport;\n\t\tconst audio = this.audio;\n\t\tconst pcm = this.pcm;\n\t\tconst rtc = this.rtc;\n\t\tthis.transport = void 0;\n\t\tthis.audio = void 0;\n\t\tthis.pcm = void 0;\n\t\tthis.rtc = void 0;\n\t\tthis.commands = void 0;\n\t\tattempt?.retire();\n\t\ttransport?.dispose();\n\t\taudio?.dispose();\n\t\tpcm?.dispose();\n\t\trtc?.dispose();\n\t\tif (this.attempt !== attempt) return;\n\t\tconst session = this.state.session;\n\t\tthis.applyState({\n\t\t\t...this.state,\n\t\t\tstatus: attempt?.cause != null ? \"error\" : \"disconnected\",\n\t\t\tisCapturing: false,\n\t\t\tisPlaying: false,\n\t\t\t...session != null ? { session: session.finalization === \"confirmed\" ? session : {\n\t\t\t\t...session,\n\t\t\t\tfinalization: \"unconfirmed\"\n\t\t\t} } : {}\n\t\t});\n\t}\n\t/** Wait for final usage when the model supports a session-close acknowledgement. */\n\tclose(options) {\n\t\tconst attempt = this.attempt;\n\t\tif (attempt?.closePromise != null) return attempt.closePromise;\n\t\tif (this.state.status !== \"connected\" || this.options.model.capabilities?.finalization !== \"session-close\" || attempt == null) {\n\t\t\tthis.disconnect();\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tif (options?.eventId != null) this.commands?.validateId(options.eventId);\n\t\tconst promise = attempt.beginClose();\n\t\tthis.applyState({\n\t\t\t...this.state,\n\t\t\tstatus: \"closing\"\n\t\t});\n\t\tif (this.attempt !== attempt || !attempt.active || attempt.transportClosing) return promise;\n\t\tthis.stopAudioCapture();\n\t\tif (this.attempt !== attempt || !attempt.active || attempt.transportClosing) return promise;\n\t\tattempt.timer(\"close\", this.options.closeTimeoutMs ?? 15e3, () => this.finishAttempt(attempt));\n\t\tconst failed = (error) => this.closeFailed(attempt, error);\n\t\ttry {\n\t\t\tthis.commands?.send({\n\t\t\t\ttype: \"session-close\",\n\t\t\t\teventId: options?.eventId\n\t\t\t}).catch(failed);\n\t\t} catch (error) {\n\t\t\tfailed(error);\n\t\t}\n\t\treturn promise;\n\t}\n\tsendTransport(event, guard, automaticAudio = false) {\n\t\tconst transport = this.rtc ?? this.pcm ?? this.transport;\n\t\tif (transport == null) throw new Error(\"Realtime connection is not open\");\n\t\tif (transport === this.transport) return this.transport.sendEvent(event, guard, automaticAudio);\n\t\treturn transport.sendEvent(event, guard);\n\t}\n\tsendEvent(event) {\n\t\tif (this.state.status === \"error\" || this.state.status === \"closing\" || this.attempt?.closing || !this.attempt?.active) throw new Error(\"Realtime session is not accepting submissions\");\n\t\tif (this.sessionLifecycle && this.state.status !== \"connected\") throw new Error(\"Realtime session is not accepting submissions\");\n\t\tif (this.rtc != null && event.type === \"input-audio-append\" || (this.continuous || this.rtc != null) && (event.type === \"input-audio-commit\" || event.type === \"input-audio-clear\")) throw new UnsupportedFunctionalityError$1({ functionality: \"JSON audio commands unsupported for this session transport\" });\n\t\tif (event.type === \"session-close\") return this.close({ eventId: event.eventId });\n\t\tif (event.type === \"session-start\" && this.sessionLifecycle) throw new Error(\"Realtime session has already started\");\n\t\tif (!this.sessionLifecycle && this.state.session == null) {\n\t\t\tconst attempt = this.attempt;\n\t\t\treturn this.sendTransport(event, () => this.attempt === attempt && attempt.active && !attempt.closing && attempt.cause == null);\n\t\t}\n\t\treturn this.commands?.send(event) ?? this.sendTransport(event);\n\t}\n\tsendTextMessage(text) {\n\t\tif (this.continuous) throw new UnsupportedFunctionalityError$1({ functionality: \"sendTextMessage for continuous sessions; client-delegation text is application-owned, use context-append for context\" });\n\t\tthis.sendEvent({\n\t\t\ttype: \"conversation-item-create\",\n\t\t\titem: {\n\t\t\t\ttype: \"text-message\",\n\t\t\t\trole: \"user\",\n\t\t\t\ttext\n\t\t\t}\n\t\t});\n\t\tthis.sendEvent({ type: \"response-create\" });\n\t\tthis.applyState(this.reducer.addUserTextMessage(this.state, text));\n\t}\n\tsendAudio(audio) {\n\t\tconst attempt = this.attempt;\n\t\tthis.sendEvent({\n\t\t\ttype: \"input-audio-append\",\n\t\t\taudio\n\t\t}).catch((error) => {\n\t\t\tif (attempt?.active && this.attempt === attempt) this.reportError(error, attempt);\n\t\t});\n\t}\n\tcommitAudio() {\n\t\tthis.sendEvent({ type: \"input-audio-commit\" });\n\t}\n\tclearAudioBuffer() {\n\t\tthis.sendEvent({ type: \"input-audio-clear\" });\n\t}\n\trequestResponse(options) {\n\t\tthis.sendEvent({\n\t\t\ttype: \"response-create\",\n\t\t\t...options != null ? { options } : {}\n\t\t});\n\t}\n\tcancelResponse() {\n\t\tthis.sendEvent({ type: \"response-cancel\" });\n\t}\n\tsendAutomaticAudio(audio) {\n\t\tif (this.state.status !== \"connected\" || !this.attempt?.active || this.attempt.closing) return;\n\t\tconst attempt = this.attempt;\n\t\tconst failed = (error) => {\n\t\t\tif (attempt?.active && this.attempt === attempt && !attempt.closing) this.fail(error);\n\t\t};\n\t\ttry {\n\t\t\tthis.sendTransport({\n\t\t\t\ttype: \"input-audio-append\",\n\t\t\t\taudio\n\t\t\t}, () => this.attempt === attempt && attempt.active && !attempt.closing, true).catch(failed);\n\t\t} catch (error) {\n\t\t\tfailed(error);\n\t\t}\n\t}\n\taddToolOutput(callId, result) {\n\t\tif (this.continuous) throw new UnsupportedFunctionalityError$1({ functionality: \"addToolOutput for continuous sessions; client delegation is application-owned\" });\n\t\tconst attempt = this.attempt;\n\t\tif (!attempt?.active || attempt.closing || attempt.cause != null) throw new Error(\"Realtime session is not accepting submissions\");\n\t\tconst { state, output } = this.reducer.addToolOutput(this.state, callId, result);\n\t\tthis.applyState(state);\n\t\tif (this.attempt !== attempt || !attempt?.active) return;\n\t\tthis.sendEvent({\n\t\t\ttype: \"conversation-item-create\",\n\t\t\titem: {\n\t\t\t\ttype: \"function-call-output\",\n\t\t\t\t...output\n\t\t\t}\n\t\t});\n\t\tthis.submittedToolOutputs.add(callId);\n\t\tthis.maybeRequestToolResponse();\n\t}\n\tmaybeRequestToolResponse() {\n\t\tif (this.state.status !== \"connected\" || this.attempt?.closing || !this.responseToolCallsClosed || this.toolCallsInResponse.size === 0 || [...this.toolCallsInResponse].some((id) => !this.submittedToolOutputs.has(id))) return;\n\t\tthis.sendEvent({ type: \"response-create\" });\n\t\tthis.toolCallsInResponse.clear();\n\t\tthis.submittedToolOutputs.clear();\n\t\tthis.responseToolCallsClosed = false;\n\t}\n\tstartAudioCapture(stream) {\n\t\tconst legacy = !this.sessionLifecycle && !this.continuous && this.options.api.session == null;\n\t\tif (!legacy && this.state.status !== \"connected\") throw new Error(\"Realtime session is not accepting capture\");\n\t\tif (this.attempt?.active && (this.attempt.closing || this.attempt.cause != null)) throw new Error(\"Realtime session is not accepting capture\");\n\t\tthis.suppliedStream = stream;\n\t\tif (legacy) {\n\t\t\tthis.captureGeneration++;\n\t\t\tthis.captureRequested = true;\n\t\t\tthis.ensureAudio().startCapture(stream);\n\t\t\treturn;\n\t\t}\n\t\tconst attempt = this.attempt;\n\t\tthis.resumeAudioCapture().catch((error) => {\n\t\t\tif (attempt?.active) this.reportError(error, attempt);\n\t\t});\n\t}\n\tasync resumeAudioCapture() {\n\t\tconst accepting = () => !this.attempt?.closing && this.attempt?.cause == null && (this.state.status === \"connected\" || !this.sessionLifecycle && this.state.status === \"connecting\");\n\t\tif (!accepting()) throw new Error(\"Realtime session is not accepting capture\");\n\t\tthis.captureRequested = true;\n\t\tif (this.rtc != null) return this.rtc.startCapture(this.suppliedStream);\n\t\tif (this.pcm != null) return this.pcm.resumeCapture(this.suppliedStream);\n\t\tconst audio = this.audio;\n\t\tif (audio == null) throw new Error(\"Realtime capture transport is not ready\");\n\t\tconst captureGeneration = ++this.captureGeneration;\n\t\tconst attempt = this.attempt;\n\t\tconst supplied = this.suppliedStream;\n\t\tconst stream = supplied ?? await navigator.mediaDevices.getUserMedia({ audio: true });\n\t\tif (!attempt?.active || this.attempt !== attempt || this.audio !== audio || !accepting() || captureGeneration !== this.captureGeneration) {\n\t\t\tif (supplied == null) stream.getTracks().forEach((track) => track.stop());\n\t\t\treturn;\n\t\t}\n\t\taudio.startCapture(stream, { ownsStream: supplied == null || !this.sessionLifecycle || this.options.api.token != null });\n\t}\n\tstopAudioCapture() {\n\t\tthis.captureGeneration++;\n\t\tthis.captureRequested = false;\n\t\tif (this.audio != null && (!this.sessionLifecycle || this.options.api.token != null)) this.suppliedStream = void 0;\n\t\tconst pcm = this.pcm;\n\t\tconst audio = this.audio;\n\t\tconst rtc = this.rtc;\n\t\tconst attempt = this.attempt;\n\t\tif (rtc != null) rtc.stopCapture().catch((error) => {\n\t\t\tif (attempt?.active && this.attempt === attempt) this.reportError(error, attempt);\n\t\t});\n\t\tpcm?.stopCapture();\n\t\taudio?.stopCapture();\n\t}\n\tstopPlayback() {\n\t\t(this.rtc ?? this.pcm ?? this.audio)?.stopPlayback();\n\t}\n\tasync resumePlayback() {\n\t\tawait (this.rtc ?? this.pcm ?? this.audio)?.resumePlayback();\n\t}\n\tdispose() {\n\t\tthis.disconnect();\n\t}\n\tensureAudio() {\n\t\tif (this.audio != null) return this.audio;\n\t\tconst { sessionConfig, sampleRate } = this.options;\n\t\tconst audio = new BrowserRealtimeAudio({\n\t\t\tcaptureSampleRate: sessionConfig?.inputAudioFormat?.rate ?? sampleRate ?? 24e3,\n\t\t\tplaybackSampleRate: sessionConfig?.outputAudioFormat?.rate ?? sampleRate ?? 24e3,\n\t\t\tonAudio: (value) => {\n\t\t\t\tif (this.audio === audio) this.sendAutomaticAudio(value);\n\t\t\t},\n\t\t\tonError: (error) => {\n\t\t\t\tif (this.audio !== audio) return;\n\t\t\t\tthis.reportError(error, this.attempt);\n\t\t\t},\n\t\t\tonCapturingChange: (isCapturing) => {\n\t\t\t\tif (this.audio === audio) this.applyState({\n\t\t\t\t\t...this.state,\n\t\t\t\t\tisCapturing\n\t\t\t\t});\n\t\t\t},\n\t\t\tonPlayingChange: (isPlaying) => {\n\t\t\t\tif (this.audio === audio) this.applyState({\n\t\t\t\t\t...this.state,\n\t\t\t\t\tisPlaying\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\tthis.audio = audio;\n\t\treturn audio;\n\t}\n\tapplyState(nextState) {\n\t\tconst publication = ++this.publication;\n\t\tconst previous = this.state;\n\t\tthis.state = nextState;\n\t\tconst update = (key) => {\n\t\t\tif (publication === this.publication && previous[key] !== nextState[key]) this.setState(key, nextState[key]);\n\t\t};\n\t\tupdate(\"status\");\n\t\tupdate(\"messages\");\n\t\tupdate(\"events\");\n\t\tupdate(\"isCapturing\");\n\t\tupdate(\"isPlaying\");\n\t\tupdate(\"session\");\n\t}\n\tasync executeTool(callId, name, args, attempt) {\n\t\tif (this.continuous || this.attempt !== attempt || !attempt.active || attempt.closing || attempt.cause != null) return;\n\t\ttry {\n\t\t\tif (this.onToolCall == null) {\n\t\t\t\tthis.reportError(/* @__PURE__ */ new Error(`No handler provided for tool \"${name}\"`), attempt);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst result = await this.onToolCall({ toolCall: {\n\t\t\t\ttoolCallId: callId,\n\t\t\t\ttoolName: name,\n\t\t\t\targs\n\t\t\t} });\n\t\t\tif (result !== void 0 && this.attempt === attempt && attempt?.active && this.state.status === \"connected\") this.addToolOutput(callId, result);\n\t\t} catch (error) {\n\t\t\tif (attempt.active) this.reportError(error, attempt);\n\t\t}\n\t}\n\tasync handleServerEvent(event, attempt) {\n\t\tconst current = () => this.attempt === attempt && attempt.active;\n\t\tif (!current()) return;\n\t\tif (event.type === \"session-started\" && event.delegationMode === \"provider\") throw new UnsupportedFunctionalityError$1({ functionality: \"Provider delegation mode; this realtime runtime supports client delegation only\" });\n\t\tif (this.continuous && event.type === \"audio-delta\") throw new UnsupportedFunctionalityError$1({ functionality: \"Turn-based audio-delta in a continuous PCM session; use audio-chunk\" });\n\t\tconst command = this.commands?.receive(event);\n\t\tconst result = await this.reducer.reduceServerEvent(this.state, event);\n\t\tif (!current()) return;\n\t\tconst session = this.state.session ?? (event.type === \"session-started\" ? createSessionState() : void 0);\n\t\tthis.applyState({\n\t\t\t...result.state,\n\t\t\tstatus: this.state.status,\n\t\t\t...session == null ? {} : { session: reduceSessionState(session, event, this.maxEvents, command?.muted) }\n\t\t});\n\t\tif (!current()) return;\n\t\tfor (const effect of result.effects) {\n\t\t\tthis.handleReducerEffect(effect, attempt);\n\t\t\tif (!current()) return;\n\t\t}\n\t\tif (event.type === \"audio-chunk\") (this.pcm ?? this.audio)?.playAudio(event.delta);\n\t\tif (!current()) return;\n\t\tif (event.type === \"response-done\" && this.toolCallsInResponse.size > 0) {\n\t\t\tthis.responseToolCallsClosed = true;\n\t\t\tthis.maybeRequestToolResponse();\n\t\t}\n\t\tif (!current()) return;\n\t\tif (event.type === \"session-closed\" && session != null) {\n\t\t\tthis.disconnect();\n\t\t\tthis.notifyEvent(event, attempt, true);\n\t\t\treturn;\n\t\t}\n\t\tif ((event.type === \"session-started\" || event.type === \"session-created\" || event.type === \"session-updated\") && attempt.active && !attempt.closing && attempt.cause == null) {\n\t\t\tif (this.options.model.capabilities?.startup === \"session-start\" ? event.type === \"session-started\" : event.type !== \"session-started\") {\n\t\t\t\tattempt.ready = true;\n\t\t\t\tattempt.clearTimer(\"startup\");\n\t\t\t\tthis.applyState({\n\t\t\t\t\t...this.state,\n\t\t\t\t\tstatus: \"connected\"\n\t\t\t\t});\n\t\t\t\tif (!current() || attempt.closing) return;\n\t\t\t\tthis.pcm?.startCapture();\n\t\t\t}\n\t\t}\n\t\tif (current()) this.notifyEvent(event, attempt);\n\t}\n\thandleReducerEffect(effect, attempt) {\n\t\tswitch (effect.type) {\n\t\t\tcase \"play-audio\":\n\t\t\t\tthis.currentResponseItemId = effect.itemId;\n\t\t\t\tthis.audio?.playAudio(effect.delta);\n\t\t\t\tbreak;\n\t\t\tcase \"speech-started\":\n\t\t\t\tif (!this.continuous && this.state.isPlaying) {\n\t\t\t\t\tconst playedMs = this.audio?.getPlaybackOffsetMs() ?? 0;\n\t\t\t\t\tconst itemId = this.currentResponseItemId;\n\t\t\t\t\tthis.audio?.stopPlayback();\n\t\t\t\t\tif (this.attempt !== attempt || !attempt.active) return;\n\t\t\t\t\tif (itemId != null && !attempt.closing && attempt.cause == null) this.sendEvent({\n\t\t\t\t\t\ttype: \"conversation-item-truncate\",\n\t\t\t\t\t\titemId,\n\t\t\t\t\t\tcontentIndex: 0,\n\t\t\t\t\t\taudioEndMs: Math.round(playedMs)\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"tool-call\":\n\t\t\t\tif (this.continuous) break;\n\t\t\t\tthis.toolCallsInResponse.add(effect.callId);\n\t\t\t\tthis.executeTool(effect.callId, effect.name, effect.args, attempt);\n\t\t\t\tbreak;\n\t\t\tcase \"error\": this.reportError(effect.error, attempt);\n\t\t}\n\t}\n\tasync reportError(error, attempt) {\n\t\tif (this.attempt !== attempt) return;\n\t\ttry {\n\t\t\tawait this.onError?.(error instanceof Error ? error : new Error(String(error)));\n\t\t} catch {}\n\t}\n\tnotifyEvent(event, attempt, terminal = false) {\n\t\tif (this.attempt !== attempt || !attempt.active && !terminal) return;\n\t\tconst report = (error) => {\n\t\t\tif (attempt.active || terminal) this.reportError(error, attempt);\n\t\t};\n\t\ttry {\n\t\t\tPromise.resolve(this.onEvent?.(event)).catch(report);\n\t\t} catch (error) {\n\t\t\treport(error);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/registry/custom-provider.ts\n/**\n* Creates a custom provider with specified language models, text embedding models, image models, transcription models, speech models, file APIs, skill APIs, and an optional fallback provider.\n*\n* @param {Object} options - The options for creating the custom provider.\n* @param {Record<string, LanguageModel>} [options.languageModels] - A record of language models, where keys are model IDs and values are language model instances.\n* @param {Record<string, EmbeddingModel>} [options.embeddingModels] - A record of text embedding models, where keys are model IDs and values are embedding model instances.\n* @param {Record<string, ImageModel>} [options.imageModels] - A record of image models, where keys are model IDs and values are image model instances.\n* @param {Record<string, TranscriptionModel>} [options.transcriptionModels] - A record of transcription models, where keys are model IDs and values are transcription model instances.\n* @param {Record<string, SpeechModel>} [options.speechModels] - A record of speech models, where keys are model IDs and values are speech model instances.\n* @param {Record<string, RerankingModel>} [options.rerankingModels] - A record of reranking models, where keys are model IDs and values are reranking model instances.\n* @param {Record<string, VideoModel>} [options.videoModels] - A record of video models, where keys are model IDs and values are video model instances.\n* @param {Record<string, DecisionModel>} [options.decisionModels] - Experimental decision models or default-provider model IDs, keyed by alias.\n* @param {FilesV4} [options.files] - A files interface for uploading files.\n* @param {SkillsV4} [options.skills] - A skills interface for uploading skills.\n* @param {ProviderV2 | ProviderV3 | ProviderV4} [options.fallbackProvider] - An optional fallback provider to use when a requested model is not found in the custom provider.\n* @returns {ProviderV4} A ProviderV4 object with languageModel, embeddingModel, imageModel, transcriptionModel, speechModel, rerankingModel, and videoModel methods.\n*\n* @throws {NoSuchModelError} Throws when a requested model is not found and no fallback provider is available.\n*/\nfunction customProvider({ languageModels, embeddingModels, imageModels, transcriptionModels, speechModels, rerankingModels, videoModels, decisionModels: decisionModelsArg, evaluationModels, files, skills, fallbackProvider: fallbackProviderArg }) {\n\tconst decisionModels = decisionModelsArg ?? evaluationModels;\n\tconst fallbackProvider = fallbackProviderArg == null ? void 0 : asProviderV4(fallbackProviderArg);\n\tconst baseProvider = {\n\t\tspecificationVersion: \"v4\",\n\t\tlanguageModel(modelId) {\n\t\t\tif (languageModels != null && modelId in languageModels) return resolveLanguageModel(languageModels[modelId]);\n\t\t\tif (fallbackProvider) return fallbackProvider.languageModel(modelId);\n\t\t\tthrow new NoSuchModelError$1({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"languageModel\"\n\t\t\t});\n\t\t},\n\t\tembeddingModel(modelId) {\n\t\t\tif (embeddingModels != null && modelId in embeddingModels) return resolveEmbeddingModel(embeddingModels[modelId]);\n\t\t\tif (fallbackProvider) return fallbackProvider.embeddingModel(modelId);\n\t\t\tthrow new NoSuchModelError$1({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"embeddingModel\"\n\t\t\t});\n\t\t},\n\t\timageModel(modelId) {\n\t\t\tif (imageModels != null && modelId in imageModels) return resolveImageModel(imageModels[modelId]);\n\t\t\tif (fallbackProvider?.imageModel) return fallbackProvider.imageModel(modelId);\n\t\t\tthrow new NoSuchModelError$1({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"imageModel\"\n\t\t\t});\n\t\t},\n\t\ttranscriptionModel(modelId) {\n\t\t\tif (transcriptionModels != null && modelId in transcriptionModels) {\n\t\t\t\tconst model = resolveTranscriptionModel(transcriptionModels[modelId]);\n\t\t\t\tif (model != null) return model;\n\t\t\t}\n\t\t\tif (fallbackProvider?.transcriptionModel) return fallbackProvider.transcriptionModel(modelId);\n\t\t\tthrow new NoSuchModelError$1({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"transcriptionModel\"\n\t\t\t});\n\t\t},\n\t\tspeechModel(modelId) {\n\t\t\tif (speechModels != null && modelId in speechModels) {\n\t\t\t\tconst model = resolveSpeechModel(speechModels[modelId]);\n\t\t\t\tif (model != null) return model;\n\t\t\t}\n\t\t\tif (fallbackProvider?.speechModel) return fallbackProvider.speechModel(modelId);\n\t\t\tthrow new NoSuchModelError$1({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"speechModel\"\n\t\t\t});\n\t\t},\n\t\trerankingModel(modelId) {\n\t\t\tif (rerankingModels != null && modelId in rerankingModels) return resolveRerankingModel(rerankingModels[modelId]);\n\t\t\tif (fallbackProvider?.rerankingModel) return fallbackProvider.rerankingModel(modelId);\n\t\t\tthrow new NoSuchModelError$1({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"rerankingModel\"\n\t\t\t});\n\t\t},\n\t\tdecisionModel(modelId) {\n\t\t\tif (decisionModels != null && Object.hasOwn(decisionModels, modelId)) return resolveDecisionModel(decisionModels[modelId]);\n\t\t\tconst provider = fallbackProviderArg;\n\t\t\tconst factory = provider?.decisionModel ?? provider?.evaluationModel;\n\t\t\tif (typeof factory === \"function\") {\n\t\t\t\tconst model = factory.call(provider, modelId);\n\t\t\t\tif (model != null) return resolveDecisionModel(model);\n\t\t\t}\n\t\t\tthrow new NoSuchModelError$1({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"decisionModel\"\n\t\t\t});\n\t\t},\n\t\tevaluationModel(modelId) {\n\t\t\treturn asEvaluationModel(this.decisionModel(modelId));\n\t\t},\n\t\tvideoModel(modelId) {\n\t\t\tif (videoModels != null && modelId in videoModels) return resolveVideoModel(videoModels[modelId]);\n\t\t\tconst provider = fallbackProviderArg;\n\t\t\tif (provider?.videoModel) return resolveVideoModel(provider.videoModel(modelId));\n\t\t\tthrow new NoSuchModelError$1({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"videoModel\"\n\t\t\t});\n\t\t}\n\t};\n\tconst filesAndSkills = {\n\t\t...files != null || fallbackProvider?.files != null ? { files() {\n\t\t\treturn files ?? fallbackProvider.files();\n\t\t} } : {},\n\t\t...skills != null || fallbackProvider?.skills != null ? { skills() {\n\t\t\treturn skills ?? fallbackProvider.skills();\n\t\t} } : {}\n\t};\n\treturn Object.assign(baseProvider, filesAndSkills);\n}\n//#endregion\n//#region src/registry/no-such-provider-error.ts\nconst name = \"AI_NoSuchProviderError\";\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\nvar NoSuchProviderError = class extends NoSuchModelError$1 {\n\tconstructor({ modelId, modelType, providerId, availableProviders, message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})` }) {\n\t\tsuper({\n\t\t\terrorName: name,\n\t\t\tmodelId,\n\t\t\tmodelType,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol] = true;\n\t\tthis.providerId = providerId;\n\t\tthis.availableProviders = availableProviders;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError$1.hasMarker(error, marker);\n\t}\n};\n//#endregion\n//#region src/registry/provider-registry.ts\n/**\n* Creates a registry for the given providers with optional middleware functionality.\n* This function allows you to register multiple providers and optionally apply middleware\n* to all language models from the registry, enabling you to transform parameters, wrap generate\n* operations, and wrap stream operations for every language model accessed through the registry.\n*\n* @param providers - A record of provider instances to be registered in the registry.\n* @param options - Configuration options for the provider registry.\n* @param options.separator - The separator used between provider ID and model ID in the combined identifier. Defaults to ':'.\n* @param options.languageModelMiddleware - Optional middleware to be applied to all language models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n* @param options.imageModelMiddleware - Optional middleware to be applied to all image models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n* @returns A new ProviderRegistryProvider instance that provides access to all registered providers with optional middleware applied to language and image models.\n*/\nfunction createProviderRegistry(providers, { separator = \":\", languageModelMiddleware, imageModelMiddleware } = {}) {\n\tconst registry = new DefaultProviderRegistry({\n\t\tseparator,\n\t\tlanguageModelMiddleware,\n\t\timageModelMiddleware\n\t});\n\tfor (const [id, provider] of Object.entries(providers)) registry.registerProvider({\n\t\tid,\n\t\tprovider\n\t});\n\treturn registry;\n}\n/**\n* @deprecated Use `createProviderRegistry` instead.\n*/\nconst experimental_createProviderRegistry = createProviderRegistry;\nvar DefaultProviderRegistry = class {\n\tconstructor({ separator, languageModelMiddleware, imageModelMiddleware }) {\n\t\tthis.providers = Object.create(null);\n\t\tthis.separator = separator;\n\t\tthis.languageModelMiddleware = languageModelMiddleware;\n\t\tthis.imageModelMiddleware = imageModelMiddleware;\n\t}\n\tregisterProvider({ id, provider }) {\n\t\tconst providerV4 = asProviderV4(provider);\n\t\tconst videoModel = provider.videoModel?.bind(provider);\n\t\tconst decisionProvider = provider;\n\t\tconst decisionModel = (decisionProvider.decisionModel ?? decisionProvider.evaluationModel)?.bind(provider);\n\t\tconst registeredProvider = videoModel == null ? providerV4 : Object.assign(Object.create(Object.getPrototypeOf(providerV4)), {\n\t\t\t...providerV4,\n\t\t\tvideoModel: (modelId) => asVideoModelV4(videoModel(modelId))\n\t\t});\n\t\tif (registeredProvider !== provider && decisionModel != null) Object.assign(registeredProvider, { decisionModel });\n\t\tthis.providers[id] = registeredProvider;\n\t}\n\tgetProvider(id, modelType) {\n\t\tconst provider = this.providers[id];\n\t\tif (provider == null) throw new NoSuchProviderError({\n\t\t\tmodelId: id,\n\t\t\tmodelType,\n\t\t\tproviderId: id,\n\t\t\tavailableProviders: Object.keys(this.providers)\n\t\t});\n\t\treturn provider;\n\t}\n\tsplitId(id, modelType) {\n\t\tconst index = id.indexOf(this.separator);\n\t\tif (index === -1) throw new NoSuchModelError$1({\n\t\t\tmodelId: id,\n\t\t\tmodelType,\n\t\t\tmessage: `Invalid ${modelType} id for registry: ${id} (must be in the format \"providerId${this.separator}modelId\")`\n\t\t});\n\t\treturn [id.slice(0, index), id.slice(index + this.separator.length)];\n\t}\n\tlanguageModel(id) {\n\t\tconst [providerId, modelId] = this.splitId(id, \"languageModel\");\n\t\tlet model = this.getProvider(providerId, \"languageModel\").languageModel?.(modelId);\n\t\tif (model == null) throw new NoSuchModelError$1({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"languageModel\"\n\t\t});\n\t\tif (this.languageModelMiddleware != null) model = wrapLanguageModel({\n\t\t\tmodel,\n\t\t\tmiddleware: this.languageModelMiddleware\n\t\t});\n\t\treturn model;\n\t}\n\tembeddingModel(id) {\n\t\tconst [providerId, modelId] = this.splitId(id, \"embeddingModel\");\n\t\tconst model = this.getProvider(providerId, \"embeddingModel\").embeddingModel?.(modelId);\n\t\tif (model == null) throw new NoSuchModelError$1({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"embeddingModel\"\n\t\t});\n\t\treturn model;\n\t}\n\timageModel(id) {\n\t\tconst [providerId, modelId] = this.splitId(id, \"imageModel\");\n\t\tlet model = this.getProvider(providerId, \"imageModel\").imageModel?.(modelId);\n\t\tif (model == null) throw new NoSuchModelError$1({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"imageModel\"\n\t\t});\n\t\tif (this.imageModelMiddleware != null) model = wrapImageModel({\n\t\t\tmodel,\n\t\t\tmiddleware: this.imageModelMiddleware\n\t\t});\n\t\treturn model;\n\t}\n\ttranscriptionModel(id) {\n\t\tconst [providerId, modelId] = this.splitId(id, \"transcriptionModel\");\n\t\tconst model = this.getProvider(providerId, \"transcriptionModel\").transcriptionModel?.(modelId);\n\t\tif (model == null) throw new NoSuchModelError$1({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"transcriptionModel\"\n\t\t});\n\t\treturn model;\n\t}\n\tspeechModel(id) {\n\t\tconst [providerId, modelId] = this.splitId(id, \"speechModel\");\n\t\tconst model = this.getProvider(providerId, \"speechModel\").speechModel?.(modelId);\n\t\tif (model == null) throw new NoSuchModelError$1({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"speechModel\"\n\t\t});\n\t\treturn model;\n\t}\n\trerankingModel(id) {\n\t\tconst [providerId, modelId] = this.splitId(id, \"rerankingModel\");\n\t\tconst model = this.getProvider(providerId, \"rerankingModel\").rerankingModel?.(modelId);\n\t\tif (model == null) throw new NoSuchModelError$1({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"rerankingModel\"\n\t\t});\n\t\treturn model;\n\t}\n\tvideoModel(id) {\n\t\tconst [providerId, modelId] = this.splitId(id, \"videoModel\");\n\t\tconst model = this.getProvider(providerId, \"videoModel\").videoModel?.(modelId);\n\t\tif (model == null) throw new NoSuchModelError$1({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"videoModel\"\n\t\t});\n\t\treturn asVideoModelV4(model);\n\t}\n\tdecisionModel(id) {\n\t\tconst [providerId, modelId] = this.splitId(id, \"decisionModel\");\n\t\tconst provider = this.getProvider(providerId, \"decisionModel\");\n\t\tconst model = (provider.decisionModel ?? provider.evaluationModel)?.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError$1({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"decisionModel\"\n\t\t});\n\t\treturn resolveDecisionModel(model);\n\t}\n\t/** @deprecated Use `decisionModel` instead. */\n\tevaluationModel(id) {\n\t\treturn asEvaluationModel(this.decisionModel(id));\n\t}\n\tfiles(id) {\n\t\tconst files = this.getProvider(id, \"languageModel\").files?.();\n\t\tif (files == null) throw new Error(`The provider \"${id}\" does not support file uploads. Make sure it exposes a files() method.`);\n\t\treturn files;\n\t}\n\tskills(id) {\n\t\tconst skills = this.getProvider(id, \"languageModel\").skills?.();\n\t\tif (skills == null) throw new Error(`The provider \"${id}\" does not support skills. Make sure it exposes a skills() method.`);\n\t\treturn skills;\n\t}\n};\n//#endregion\n//#region src/rerank/restricted-telemetry-dispatcher.ts\n/**\n* Filters runtime context before sending operation events to telemetry integrations.\n* User callbacks continue to receive the original context.\n*/\nfunction createRestrictedTelemetryDispatcher({ telemetry }) {\n\tconst dispatcher = createTelemetryDispatcher({ telemetry });\n\treturn {\n\t\t...dispatcher,\n\t\tonStart: (event) => dispatcher.onStart?.({\n\t\t\t...event,\n\t\t\truntimeContext: filterIncludedContext({\n\t\t\t\tcontext: event.runtimeContext,\n\t\t\t\tincludeContext: telemetry?.includeRuntimeContext\n\t\t\t})\n\t\t}),\n\t\tonEnd: (event) => dispatcher.onEnd?.({\n\t\t\t...event,\n\t\t\truntimeContext: filterIncludedContext({\n\t\t\t\tcontext: event.runtimeContext,\n\t\t\t\tincludeContext: telemetry?.includeRuntimeContext\n\t\t\t})\n\t\t})\n\t};\n}\n//#endregion\n//#region src/rerank/rerank.ts\nconst originalGenerateCallId$2 = createIdGenerator$1({\n\tprefix: \"call\",\n\tsize: 24\n});\n/**\n* Rerank documents using a reranking model. The type of the value is defined by the reranking model.\n*\n* @param model - The reranking model to use.\n* @param documents - The documents that should be reranked.\n* @param query - The query to rerank the documents against.\n* @param topN - Number of top documents to return.\n*\n* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n* @param providerOptions - Additional provider-specific options.\n* @param telemetry - Optional telemetry configuration.\n* @param runtimeContext - User-defined runtime context passed to callbacks and, when explicitly included, telemetry.\n*\n* @returns A result object that contains the reranked documents, the reranked indices, and additional information.\n*/\nasync function rerank({ model: modelArg, documents, query, topN, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry, telemetry = experimental_telemetry, runtimeContext = {}, onStart, experimental_onStart, onEnd, experimental_onEnd, _internal: { generateCallId = originalGenerateCallId$2 } = {} }) {\n\tconst model = resolveRerankingModel(modelArg);\n\tconst callId = generateCallId();\n\tconst resolvedOnStart = onStart ?? experimental_onStart;\n\tconst resolvedOnEnd = onEnd ?? experimental_onEnd;\n\tconst telemetryDispatcher = createRestrictedTelemetryDispatcher({ telemetry });\n\tconst runInTracingChannelSpan = telemetryDispatcher.runInTracingChannelSpan ?? (async ({ execute }) => await execute());\n\tif (documents.length === 0) {\n\t\tawait notify({\n\t\t\tevent: {\n\t\t\t\tcallId,\n\t\t\t\toperationId: \"ai.rerank\",\n\t\t\t\truntimeContext,\n\t\t\t\tprovider: model.provider,\n\t\t\t\tmodelId: model.modelId,\n\t\t\t\tdocuments,\n\t\t\t\tquery,\n\t\t\t\ttopN,\n\t\t\t\tmaxRetries: maxRetriesArg ?? 2,\n\t\t\t\theaders,\n\t\t\t\tproviderOptions\n\t\t\t},\n\t\t\tcallbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n\t\t});\n\t\tawait notify({\n\t\t\tevent: {\n\t\t\t\tcallId,\n\t\t\t\toperationId: \"ai.rerank\",\n\t\t\t\truntimeContext,\n\t\t\t\tprovider: model.provider,\n\t\t\t\tmodelId: model.modelId,\n\t\t\t\tdocuments,\n\t\t\t\tquery,\n\t\t\t\tranking: [],\n\t\t\t\twarnings: [],\n\t\t\t\tproviderMetadata: void 0,\n\t\t\t\tresponse: {\n\t\t\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\t\t\tmodelId: model.modelId\n\t\t\t\t}\n\t\t\t},\n\t\t\tcallbacks: [resolvedOnEnd, telemetryDispatcher.onEnd]\n\t\t});\n\t\treturn new DefaultRerankResult({\n\t\t\toriginalDocuments: [],\n\t\t\tranking: [],\n\t\t\tproviderMetadata: void 0,\n\t\t\tresponse: {\n\t\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\t\tmodelId: model.modelId\n\t\t\t}\n\t\t});\n\t}\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst documentsToSend = typeof documents[0] === \"string\" ? {\n\t\ttype: \"text\",\n\t\tvalues: documents\n\t} : {\n\t\ttype: \"object\",\n\t\tvalues: documents\n\t};\n\tconst startEvent = {\n\t\tcallId,\n\t\toperationId: \"ai.rerank\",\n\t\truntimeContext,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId,\n\t\tdocuments,\n\t\tquery,\n\t\ttopN,\n\t\tmaxRetries,\n\t\theaders,\n\t\tproviderOptions\n\t};\n\treturn await runInTracingChannelSpan({\n\t\ttype: \"rerank\",\n\t\tevent: startEvent,\n\t\texecute: async () => {\n\t\t\tawait notify({\n\t\t\t\tevent: startEvent,\n\t\t\t\tcallbacks: [resolvedOnStart, telemetryDispatcher.onStart]\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tconst { ranking, response, providerMetadata, warnings } = await retry(async () => {\n\t\t\t\t\tawait notify({\n\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\toperationId: \"ai.rerank.doRerank\",\n\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\t\tdocuments,\n\t\t\t\t\t\t\tdocumentsType: documentsToSend.type,\n\t\t\t\t\t\t\tquery,\n\t\t\t\t\t\t\ttopN\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcallbacks: [telemetryDispatcher.onRerankStart]\n\t\t\t\t\t});\n\t\t\t\t\tconst modelResponse = await model.doRerank({\n\t\t\t\t\t\tdocuments: documentsToSend,\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\ttopN,\n\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\theaders\n\t\t\t\t\t});\n\t\t\t\t\tconst ranking = modelResponse.ranking;\n\t\t\t\t\tawait notify({\n\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\toperationId: \"ai.rerank.doRerank\",\n\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\t\tdocumentsType: documentsToSend.type,\n\t\t\t\t\t\t\tranking\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcallbacks: [telemetryDispatcher.onRerankEnd]\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\tranking,\n\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\tresponse: modelResponse.response,\n\t\t\t\t\t\twarnings: modelResponse.warnings\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t\t\tvalidateRankingIndices({\n\t\t\t\t\tranking,\n\t\t\t\t\tdocuments\n\t\t\t\t});\n\t\t\t\tlogWarnings({\n\t\t\t\t\twarnings: warnings ?? [],\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.modelId\n\t\t\t\t});\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\tcallId,\n\t\t\t\t\t\toperationId: \"ai.rerank\",\n\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\tmodelId: model.modelId,\n\t\t\t\t\t\tdocuments,\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\tranking: ranking.map((ranking) => ({\n\t\t\t\t\t\t\toriginalIndex: ranking.index,\n\t\t\t\t\t\t\tscore: ranking.relevanceScore,\n\t\t\t\t\t\t\tdocument: documents[ranking.index]\n\t\t\t\t\t\t})),\n\t\t\t\t\t\twarnings: warnings ?? [],\n\t\t\t\t\t\tproviderMetadata,\n\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\tid: response?.id,\n\t\t\t\t\t\t\ttimestamp: response?.timestamp ?? /* @__PURE__ */ new Date(),\n\t\t\t\t\t\t\tmodelId: response?.modelId ?? model.modelId,\n\t\t\t\t\t\t\theaders: response?.headers,\n\t\t\t\t\t\t\tbody: response?.body\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: [resolvedOnEnd, telemetryDispatcher.onEnd]\n\t\t\t\t});\n\t\t\t\treturn new DefaultRerankResult({\n\t\t\t\t\toriginalDocuments: documents,\n\t\t\t\t\tranking: ranking.map((ranking) => ({\n\t\t\t\t\t\toriginalIndex: ranking.index,\n\t\t\t\t\t\tscore: ranking.relevanceScore,\n\t\t\t\t\t\tdocument: documents[ranking.index]\n\t\t\t\t\t})),\n\t\t\t\t\tproviderMetadata,\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\tid: response?.id,\n\t\t\t\t\t\ttimestamp: response?.timestamp ?? /* @__PURE__ */ new Date(),\n\t\t\t\t\t\tmodelId: response?.modelId ?? model.modelId,\n\t\t\t\t\t\theaders: response?.headers,\n\t\t\t\t\t\tbody: response?.body\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\t\tcallId,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t});\n}\nfunction validateRankingIndices({ ranking, documents }) {\n\tfor (const { index } of ranking) if (!Number.isInteger(index) || index < 0 || index >= documents.length) throw new InvalidResponseDataError$1({\n\t\tdata: ranking,\n\t\tmessage: `Invalid ranking index ${index}. Expected an integer between 0 and ${documents.length - 1}.`\n\t});\n}\nvar DefaultRerankResult = class {\n\tconstructor(options) {\n\t\tthis.originalDocuments = options.originalDocuments;\n\t\tthis.ranking = options.ranking;\n\t\tthis.response = options.response;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t}\n\tget rerankedDocuments() {\n\t\treturn this.ranking.map((ranking) => ranking.document);\n\t}\n};\n//#endregion\n//#region src/transcribe/transcribe.ts\nconst originalGenerateCallId$1 = createIdGenerator$1({\n\tprefix: \"call\",\n\tsize: 24\n});\n/**\n* Generates transcripts using a transcription model.\n*\n* @param model - The transcription model to use.\n* @param audio - The audio data to transcribe as DataContent (string | Uint8Array | ArrayBuffer | Buffer) or a URL.\n* @param providerOptions - Additional provider-specific options that are passed through to the provider\n* as body parameters.\n* @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n* @param telemetry - Optional telemetry configuration.\n*\n* @returns A result object that contains the generated transcript.\n*/\nconst defaultDownload = createDownload();\nasync function transcribe({ model, audio, providerOptions = {}, maxRetries: maxRetriesArg, abortSignal, headers, telemetry, download: downloadFn = defaultDownload, _internal: { generateCallId = originalGenerateCallId$1 } = {} }) {\n\tconst resolvedModel = resolveTranscriptionModel(model);\n\tif (!resolvedModel) throw new Error(\"Model could not be resolved\");\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst callId = generateCallId();\n\tconst telemetryDispatcher = createTelemetryDispatcher({ telemetry });\n\tconst runInTracingChannelSpan = telemetryDispatcher.runInTracingChannelSpan ?? (async ({ execute }) => await execute());\n\tconst createStartEvent = ({ byteLength, mediaType }) => ({\n\t\tcallId,\n\t\toperationId: \"ai.transcribe\",\n\t\tprovider: resolvedModel.provider,\n\t\tmodelId: resolvedModel.modelId,\n\t\taudio: {\n\t\t\tbyteLength,\n\t\t\tmediaType\n\t\t},\n\t\tinputAudioFormat: void 0,\n\t\tmaxRetries,\n\t\theaders,\n\t\tproviderOptions\n\t});\n\tconst executeWithStartEvent = async ({ startEvent, execute }) => await runInTracingChannelSpan({\n\t\ttype: \"transcribe\",\n\t\tevent: startEvent,\n\t\texecute: async () => {\n\t\t\tawait notify({\n\t\t\t\tevent: startEvent,\n\t\t\t\tcallbacks: [telemetryDispatcher.onStart]\n\t\t\t});\n\t\t\treturn await execute();\n\t\t}\n\t});\n\tlet preparationError;\n\tlet preparationFailed = false;\n\tlet audioData;\n\tlet downloadedMediaType;\n\ttry {\n\t\tif (audio instanceof URL) {\n\t\t\tconst downloadResult = await downloadFn({\n\t\t\t\turl: audio,\n\t\t\t\tabortSignal\n\t\t\t});\n\t\t\taudioData = downloadResult.data;\n\t\t\tdownloadedMediaType = downloadResult.mediaType;\n\t\t} else audioData = convertDataContentToUint8Array(audio);\n\t} catch (error) {\n\t\tpreparationFailed = true;\n\t\tpreparationError = error;\n\t\taudioData = /* @__PURE__ */ new Uint8Array();\n\t}\n\tif (preparationFailed) {\n\t\tconst startEvent = createStartEvent({\n\t\t\tbyteLength: void 0,\n\t\t\tmediaType: void 0\n\t\t});\n\t\ttry {\n\t\t\treturn await executeWithStartEvent({\n\t\t\t\tstartEvent,\n\t\t\t\texecute: () => {\n\t\t\t\t\tthrow preparationError;\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\tcallId,\n\t\t\t\terror\n\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t}\n\tconst mediaType = downloadedMediaType ?? detectMediaType({\n\t\tdata: audioData,\n\t\ttopLevelType: \"audio\"\n\t}) ?? \"audio/wav\";\n\tconst startEvent = createStartEvent({\n\t\tbyteLength: audioData.byteLength,\n\t\tmediaType\n\t});\n\ttry {\n\t\treturn await executeWithStartEvent({\n\t\t\tstartEvent,\n\t\t\texecute: async () => {\n\t\t\t\tconst result = await retry(() => resolvedModel.doGenerate({\n\t\t\t\t\taudio: audioData,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\tproviderOptions,\n\t\t\t\t\tmediaType\n\t\t\t\t}));\n\t\t\t\tlogWarnings({\n\t\t\t\t\twarnings: result.warnings,\n\t\t\t\t\tprovider: resolvedModel.provider,\n\t\t\t\t\tmodel: resolvedModel.modelId\n\t\t\t\t});\n\t\t\t\tif (result.text == null) throw new NoTranscriptGeneratedError({ responses: [result.response] });\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\tcallId,\n\t\t\t\t\t\toperationId: \"ai.transcribe\",\n\t\t\t\t\t\tprovider: resolvedModel.provider,\n\t\t\t\t\t\tmodelId: resolvedModel.modelId,\n\t\t\t\t\t\taudio: {\n\t\t\t\t\t\t\tbyteLength: audioData.byteLength,\n\t\t\t\t\t\t\tmediaType\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttext: result.text,\n\t\t\t\t\t\tsegments: result.segments,\n\t\t\t\t\t\tlanguage: result.language,\n\t\t\t\t\t\tdurationInSeconds: result.durationInSeconds,\n\t\t\t\t\t\tusage: result.usage,\n\t\t\t\t\t\twarnings: result.warnings,\n\t\t\t\t\t\tproviderMetadata: result.providerMetadata,\n\t\t\t\t\t\tresponse: result.response\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: [telemetryDispatcher.onEnd]\n\t\t\t\t});\n\t\t\t\treturn new DefaultTranscriptionResult({\n\t\t\t\t\ttext: result.text,\n\t\t\t\t\tsegments: result.segments,\n\t\t\t\t\tlanguage: result.language,\n\t\t\t\t\tdurationInSeconds: result.durationInSeconds,\n\t\t\t\t\twarnings: result.warnings,\n\t\t\t\t\tresponses: [result.response],\n\t\t\t\t\tproviderMetadata: result.providerMetadata\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t} catch (error) {\n\t\tawait telemetryDispatcher.onError?.({\n\t\t\tcallId,\n\t\t\terror\n\t\t});\n\t\tthrow error;\n\t}\n}\nvar DefaultTranscriptionResult = class {\n\tconstructor(options) {\n\t\tthis.text = options.text;\n\t\tthis.segments = options.segments;\n\t\tthis.language = options.language;\n\t\tthis.durationInSeconds = options.durationInSeconds;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = options.providerMetadata ?? {};\n\t}\n};\n//#endregion\n//#region src/transcribe/stream-transcribe.ts\nconst originalGenerateCallId = createIdGenerator$1({\n\tprefix: \"call\",\n\tsize: 24\n});\n/**\n* Streams transcripts using a transcription model.\n*\n* @param model - The transcription model to use.\n* @param audio - Raw audio chunks to transcribe.\n* @param inputAudioFormat - The input audio format for the raw audio chunks.\n* @param providerOptions - Additional provider-specific options.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP/WebSocket headers to send when supported by the provider.\n* @param telemetry - Optional telemetry configuration.\n*\n* @returns A result object that contains the streaming transcript and final transcript metadata.\n*/\nfunction streamTranscribe({ model, audio, inputAudioFormat, providerOptions = {}, abortSignal, headers, includeRawChunks, telemetry, _internal: { currentDate = () => /* @__PURE__ */ new Date(), generateCallId = originalGenerateCallId } = {} }) {\n\tconst resolvedModel = resolveTranscriptionModel(model);\n\tif (!resolvedModel) throw new Error(\"Model could not be resolved\");\n\tconst doStream = resolvedModel.doStream?.bind(resolvedModel);\n\tif (doStream == null) throw new UnsupportedFunctionalityError$1({\n\t\tfunctionality: \"streaming transcription\",\n\t\tmessage: `The ${resolvedModel.provider} model \"${resolvedModel.modelId}\" does not support streaming transcription.` + (typeof model === \"string\" ? \" String model IDs resolve through the global provider (AI Gateway by default). If that provider does not support streaming transcription, pass a provider model instance instead (e.g. openai.transcription('gpt-realtime-whisper')) or upgrade @ai-sdk/gateway to a version with streaming transcription support.\" : \"\")\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst callId = generateCallId();\n\tconst telemetryDispatcher = createTelemetryDispatcher({ telemetry });\n\tconst runInTracingChannelSpan = telemetryDispatcher.runInTracingChannelSpan ?? (async ({ execute }) => await execute());\n\tlet audioByteLength = 0;\n\tconst countedAudio = telemetryDispatcher.experimental_onStreamTranscriptionEnd != null ? createByteCountingStream(audio, (byteLength) => {\n\t\taudioByteLength += byteLength;\n\t}) : audio;\n\tconst startEvent = {\n\t\tcallId,\n\t\toperationId: \"ai.streamTranscribe\",\n\t\tprovider: resolvedModel.provider,\n\t\tmodelId: resolvedModel.modelId,\n\t\taudio: {\n\t\t\tbyteLength: void 0,\n\t\t\tmediaType: inputAudioFormat.type\n\t\t},\n\t\tinputAudioFormat,\n\t\tmaxRetries: void 0,\n\t\theaders,\n\t\tproviderOptions\n\t};\n\tconst textPromise = new DelayedPromise();\n\tconst segmentsPromise = new DelayedPromise();\n\tconst languagePromise = new DelayedPromise();\n\tconst durationInSecondsPromise = new DelayedPromise();\n\tconst warningsPromise = new DelayedPromise();\n\tconst responsesPromise = new DelayedPromise();\n\tconst providerMetadataPromise = new DelayedPromise();\n\tlet warnings = [];\n\tlet telemetrySettled = false;\n\tconst rejectPendingPromises = (error) => {\n\t\tfor (const promise of [\n\t\t\ttextPromise,\n\t\t\tsegmentsPromise,\n\t\t\tlanguagePromise,\n\t\t\tdurationInSecondsPromise,\n\t\t\twarningsPromise,\n\t\t\tresponsesPromise,\n\t\t\tproviderMetadataPromise\n\t\t]) if (promise.isPending()) promise.reject(error);\n\t};\n\tconst startedAt = currentDate();\n\tlet response;\n\tconst currentResponseMetadata = () => response ?? {\n\t\ttimestamp: startedAt,\n\t\tmodelId: resolvedModel.modelId\n\t};\n\tconst resolveWarnings = (resolvedWarnings) => {\n\t\twarnings = resolvedWarnings;\n\t\twarningsPromise.resolve(resolvedWarnings);\n\t\tlogWarnings({\n\t\t\twarnings: resolvedWarnings,\n\t\t\tprovider: resolvedModel.provider,\n\t\t\tmodel: resolvedModel.modelId\n\t\t});\n\t};\n\tconst pipeAbortController = new AbortController();\n\tconst transform = new TransformStream({\n\t\tasync transform(value, controller) {\n\t\t\tswitch (value.type) {\n\t\t\t\tcase \"stream-start\":\n\t\t\t\t\tresolveWarnings(value.warnings);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\tresponse = {\n\t\t\t\t\t\ttimestamp: value.timestamp ?? currentResponseMetadata().timestamp,\n\t\t\t\t\t\tmodelId: value.modelId ?? currentResponseMetadata().modelId,\n\t\t\t\t\t\theaders: value.headers ?? response?.headers\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"transcript-delta\":\n\t\t\t\tcase \"transcript-partial\":\n\t\t\t\tcase \"transcript-final\":\n\t\t\t\tcase \"raw\":\n\t\t\t\tcase \"error\":\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tif (!warningsPromise.isResolved()) resolveWarnings([]);\n\t\t\t\t\tif (!value.text) throw new NoTranscriptGeneratedError({ responses: [currentResponseMetadata()] });\n\t\t\t\t\ttextPromise.resolve(value.text);\n\t\t\t\t\tsegmentsPromise.resolve(value.segments);\n\t\t\t\t\tlanguagePromise.resolve(value.language);\n\t\t\t\t\tdurationInSecondsPromise.resolve(value.durationInSeconds);\n\t\t\t\t\tresponsesPromise.resolve([currentResponseMetadata()]);\n\t\t\t\t\tproviderMetadataPromise.resolve(value.providerMetadata ?? {});\n\t\t\t\t\ttelemetrySettled = true;\n\t\t\t\t\tif (telemetryDispatcher.experimental_onStreamTranscriptionEnd != null) await notify({\n\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\toperationId: \"ai.streamTranscribe\",\n\t\t\t\t\t\t\tprovider: resolvedModel.provider,\n\t\t\t\t\t\t\tmodelId: resolvedModel.modelId,\n\t\t\t\t\t\t\taudio: {\n\t\t\t\t\t\t\t\tbyteLength: audioByteLength,\n\t\t\t\t\t\t\t\tmediaType: inputAudioFormat.type\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttext: value.text,\n\t\t\t\t\t\t\tsegments: value.segments,\n\t\t\t\t\t\t\tlanguage: value.language,\n\t\t\t\t\t\t\tdurationInSeconds: value.durationInSeconds,\n\t\t\t\t\t\t\tusage: value.usage,\n\t\t\t\t\t\t\twarnings,\n\t\t\t\t\t\t\tproviderMetadata: value.providerMetadata,\n\t\t\t\t\t\t\tresponse: currentResponseMetadata()\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcallbacks: [telemetryDispatcher.experimental_onStreamTranscriptionEnd]\n\t\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\tflush() {\n\t\t\tif (textPromise.isPending()) throw new NoTranscriptGeneratedError({ responses: [currentResponseMetadata()] });\n\t\t},\n\t\tcancel(reason) {\n\t\t\tpipeAbortController.abort(reason ?? /* @__PURE__ */ new Error(\"Transcription stream was cancelled.\"));\n\t\t}\n\t});\n\trunInTracingChannelSpan({\n\t\ttype: \"streamTranscribe\",\n\t\tevent: startEvent,\n\t\texecute: async () => {\n\t\t\tawait notify({\n\t\t\t\tevent: startEvent,\n\t\t\t\tcallbacks: [telemetryDispatcher.experimental_onStreamTranscriptionStart]\n\t\t\t});\n\t\t\tconst result = await doStream({\n\t\t\t\taudio: countedAudio,\n\t\t\t\tinputAudioFormat,\n\t\t\t\tproviderOptions,\n\t\t\t\tabortSignal: mergeAbortSignals(abortSignal, pipeAbortController.signal),\n\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\tincludeRawChunks\n\t\t\t});\n\t\t\tresponse = {\n\t\t\t\ttimestamp: result.response?.timestamp ?? startedAt,\n\t\t\t\tmodelId: result.response?.modelId ?? resolvedModel.modelId,\n\t\t\t\theaders: result.response?.headers\n\t\t\t};\n\t\t\tawait result.stream.pipeTo(transform.writable, { signal: pipeAbortController.signal });\n\t\t}\n\t}).catch(async (error) => {\n\t\tconst reason = error ?? /* @__PURE__ */ new Error(\"Transcription stream was cancelled or errored.\");\n\t\trejectPendingPromises(reason);\n\t\tif (!telemetrySettled) {\n\t\t\ttelemetrySettled = true;\n\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\tcallId,\n\t\t\t\terror: reason\n\t\t\t});\n\t\t}\n\t\tcountedAudio.cancel(reason).catch(() => {});\n\t\ttransform.writable.abort(reason).catch(() => {});\n\t});\n\tlet streamOwner = \"unclaimed\";\n\tfunction consumeStream() {\n\t\tif (streamOwner === \"full-stream\" || streamOwner === \"result-promises\") return;\n\t\tstreamOwner = \"result-promises\";\n\t\tconst reader = transform.readable.getReader();\n\t\t(async () => {\n\t\t\twhile (!(await reader.read()).done);\n\t\t})().catch(() => {});\n\t}\n\tfunction getFullStream() {\n\t\tif (streamOwner !== \"unclaimed\") throw new Error(streamOwner === \"full-stream\" ? \"fullStream can only be accessed once.\" : \"fullStream cannot be accessed after a result promise.\");\n\t\tstreamOwner = \"full-stream\";\n\t\treturn asAsyncIterableStream(transform.readable);\n\t}\n\treturn {\n\t\tget text() {\n\t\t\tconsumeStream();\n\t\t\treturn textPromise.promise;\n\t\t},\n\t\tget segments() {\n\t\t\tconsumeStream();\n\t\t\treturn segmentsPromise.promise;\n\t\t},\n\t\tget language() {\n\t\t\tconsumeStream();\n\t\t\treturn languagePromise.promise;\n\t\t},\n\t\tget durationInSeconds() {\n\t\t\tconsumeStream();\n\t\t\treturn durationInSecondsPromise.promise;\n\t\t},\n\t\tget warnings() {\n\t\t\tconsumeStream();\n\t\t\treturn warningsPromise.promise;\n\t\t},\n\t\tget responses() {\n\t\t\tconsumeStream();\n\t\t\treturn responsesPromise.promise;\n\t\t},\n\t\tget providerMetadata() {\n\t\t\tconsumeStream();\n\t\t\treturn providerMetadataPromise.promise;\n\t\t},\n\t\tget fullStream() {\n\t\t\treturn getFullStream();\n\t\t}\n\t};\n}\nfunction createByteCountingStream(audio, onChunk) {\n\tlet audioReader;\n\treturn new ReadableStream({\n\t\tasync pull(controller) {\n\t\t\taudioReader ??= audio.getReader();\n\t\t\tconst { done, value } = await audioReader.read();\n\t\t\tif (done) {\n\t\t\t\tcontroller.close();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tonChunk(typeof value === \"string\" ? getBase64ByteLength(value) : value.byteLength);\n\t\t\tcontroller.enqueue(value);\n\t\t},\n\t\tasync cancel(reason) {\n\t\t\tif (audioReader != null) await audioReader.cancel(reason);\n\t\t\telse await audio.cancel(reason);\n\t\t}\n\t});\n}\nfunction getBase64ByteLength(value) {\n\tlet characterCount = 0;\n\tlet lastCharacter = \"\";\n\tlet secondLastCharacter = \"\";\n\tfor (const character of value) {\n\t\tif (/\\s/.test(character)) continue;\n\t\tcharacterCount++;\n\t\tsecondLastCharacter = lastCharacter;\n\t\tlastCharacter = character;\n\t}\n\tconst padding = lastCharacter === \"=\" ? secondLastCharacter === \"=\" ? 2 : 1 : 0;\n\treturn Math.floor(characterCount * 3 / 4) - padding;\n}\n//#endregion\n//#region src/transcribe/index.ts\n/**\n* @deprecated Use `transcribe` instead.\n*/\nconst experimental_transcribe = (options) => {\n\tlogWarnings({ warnings: [{\n\t\ttype: \"deprecated\",\n\t\tsetting: \"experimental_transcribe\",\n\t\tmessage: \"Use transcribe instead.\"\n\t}] });\n\treturn transcribe(options);\n};\n//#endregion\n//#region src/translate/stream-translate.ts\n/**\n* Streams speech-to-speech translations using a speech translation model.\n*\n* @param model - The speech translation model to use.\n* @param audio - Raw audio chunks to translate.\n* @param inputAudioFormat - The input audio format for the raw audio chunks.\n* @param targetLanguage - The language to translate the audio into.\n* @param sourceLanguage - The language of the source audio. Auto-detected when absent.\n* @param outputAudioFormat - The desired audio format for translated audio chunks.\n* @param providerOptions - Additional provider-specific options.\n* @param abortSignal - An optional abort signal that can be used to cancel the call.\n* @param headers - Additional HTTP/WebSocket headers to send when supported by the provider.\n* @param includeRawChunks - When true, providers include raw provider chunks in the stream as `raw` parts.\n*\n* @returns A result object that contains the streaming translation and final translation metadata.\n*/\nfunction streamTranslate({ model, audio, inputAudioFormat, targetLanguage, sourceLanguage, outputAudioFormat, providerOptions = {}, abortSignal, headers, includeRawChunks, _internal: { currentDate = () => /* @__PURE__ */ new Date() } = {} }) {\n\tconst resolvedModel = resolveSpeechTranslationModel(model);\n\tconst doStream = resolvedModel.doStream.bind(resolvedModel);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst sourceTextPromise = new DelayedPromise();\n\tconst translationTextPromise = new DelayedPromise();\n\tconst durationInSecondsPromise = new DelayedPromise();\n\tconst usagePromise = new DelayedPromise();\n\tconst warningsPromise = new DelayedPromise();\n\tconst responsePromise = new DelayedPromise();\n\tconst providerMetadataPromise = new DelayedPromise();\n\tconst rejectPendingPromises = (error) => {\n\t\tfor (const promise of [\n\t\t\tsourceTextPromise,\n\t\t\ttranslationTextPromise,\n\t\t\tdurationInSecondsPromise,\n\t\t\tusagePromise,\n\t\t\twarningsPromise,\n\t\t\tresponsePromise,\n\t\t\tproviderMetadataPromise\n\t\t]) if (promise.isPending()) promise.reject(error);\n\t};\n\tconst startedAt = currentDate();\n\tlet response;\n\tconst currentResponseMetadata = () => response ?? {\n\t\ttimestamp: startedAt,\n\t\tmodelId: resolvedModel.modelId\n\t};\n\tconst resolveWarnings = (warnings) => {\n\t\twarningsPromise.resolve(warnings);\n\t\tlogWarnings({\n\t\t\twarnings,\n\t\t\tprovider: resolvedModel.provider,\n\t\t\tmodel: resolvedModel.modelId\n\t\t});\n\t};\n\tconst pipeAbortController = new AbortController();\n\tlet hasAudioOutput = false;\n\tconst transform = new TransformStream({\n\t\ttransform(value, controller) {\n\t\t\tswitch (value.type) {\n\t\t\t\tcase \"stream-start\":\n\t\t\t\t\tresolveWarnings(value.warnings);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\tresponse = {\n\t\t\t\t\t\ttimestamp: value.timestamp ?? currentResponseMetadata().timestamp,\n\t\t\t\t\t\tmodelId: value.modelId ?? currentResponseMetadata().modelId,\n\t\t\t\t\t\theaders: value.headers ?? response?.headers\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"audio\":\n\t\t\t\t\thasAudioOutput = true;\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"output-text-delta\":\n\t\t\t\tcase \"output-text-final\":\n\t\t\t\tcase \"source-transcript-delta\":\n\t\t\t\tcase \"source-transcript-partial\":\n\t\t\t\tcase \"source-transcript-final\":\n\t\t\t\tcase \"raw\":\n\t\t\t\tcase \"error\":\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tif (!warningsPromise.isResolved()) resolveWarnings([]);\n\t\t\t\t\tif (!hasAudioOutput && !value.outputText) throw new NoTranslationGeneratedError({ response: currentResponseMetadata() });\n\t\t\t\t\tsourceTextPromise.resolve(value.sourceText);\n\t\t\t\t\ttranslationTextPromise.resolve(value.outputText);\n\t\t\t\t\tdurationInSecondsPromise.resolve(value.durationInSeconds);\n\t\t\t\t\tusagePromise.resolve(value.usage);\n\t\t\t\t\tresponsePromise.resolve(currentResponseMetadata());\n\t\t\t\t\tproviderMetadataPromise.resolve(value.providerMetadata ?? {});\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: throw new Error(`Unsupported part type: ${value}`);\n\t\t\t}\n\t\t},\n\t\tflush() {\n\t\t\tif (translationTextPromise.isPending()) throw new NoTranslationGeneratedError({ response: currentResponseMetadata() });\n\t\t},\n\t\tcancel(reason) {\n\t\t\tpipeAbortController.abort(reason ?? /* @__PURE__ */ new Error(\"Translation stream was cancelled.\"));\n\t\t}\n\t});\n\t(async () => {\n\t\tconst result = await doStream({\n\t\t\taudio,\n\t\t\tinputAudioFormat,\n\t\t\ttargetLanguage,\n\t\t\tsourceLanguage,\n\t\t\toutputAudioFormat,\n\t\t\tproviderOptions,\n\t\t\tabortSignal: mergeAbortSignals(abortSignal, pipeAbortController.signal),\n\t\t\theaders: headersWithUserAgent,\n\t\t\tincludeRawChunks\n\t\t});\n\t\tresponse = {\n\t\t\ttimestamp: result.response?.timestamp ?? startedAt,\n\t\t\tmodelId: result.response?.modelId ?? resolvedModel.modelId,\n\t\t\theaders: result.response?.headers\n\t\t};\n\t\tawait result.stream.pipeTo(transform.writable, { signal: pipeAbortController.signal });\n\t})().catch((error) => {\n\t\tconst reason = error ?? /* @__PURE__ */ new Error(\"Translation stream was cancelled or errored.\");\n\t\trejectPendingPromises(reason);\n\t\taudio.cancel(reason).catch(() => {});\n\t\ttransform.writable.abort(reason).catch(() => {});\n\t});\n\tlet streamOwner = \"unclaimed\";\n\tfunction consumeStream() {\n\t\tif (streamOwner === \"full-stream\" || streamOwner === \"result-promises\") return;\n\t\tstreamOwner = \"result-promises\";\n\t\tconst reader = transform.readable.getReader();\n\t\t(async () => {\n\t\t\twhile (!(await reader.read()).done);\n\t\t})().catch(() => {});\n\t}\n\tfunction getFullStream() {\n\t\tif (streamOwner !== \"unclaimed\") throw new Error(streamOwner === \"full-stream\" ? \"fullStream can only be accessed once.\" : \"fullStream cannot be accessed after a result promise.\");\n\t\tstreamOwner = \"full-stream\";\n\t\treturn asAsyncIterableStream(transform.readable);\n\t}\n\treturn {\n\t\tget sourceText() {\n\t\t\tconsumeStream();\n\t\t\treturn sourceTextPromise.promise;\n\t\t},\n\t\tget translationText() {\n\t\t\tconsumeStream();\n\t\t\treturn translationTextPromise.promise;\n\t\t},\n\t\tget durationInSeconds() {\n\t\t\tconsumeStream();\n\t\t\treturn durationInSecondsPromise.promise;\n\t\t},\n\t\tget usage() {\n\t\t\tconsumeStream();\n\t\t\treturn usagePromise.promise;\n\t\t},\n\t\tget warnings() {\n\t\t\tconsumeStream();\n\t\t\treturn warningsPromise.promise;\n\t\t},\n\t\tget response() {\n\t\t\tconsumeStream();\n\t\t\treturn responsePromise.promise;\n\t\t},\n\t\tget providerMetadata() {\n\t\t\tconsumeStream();\n\t\t\treturn providerMetadataPromise.promise;\n\t\t},\n\t\tget fullStream() {\n\t\t\treturn getFullStream();\n\t\t}\n\t};\n}\n//#endregion\n//#region src/ui/create-ui-api-call-error.ts\nasync function createUIApiCallError({ response, url, fallbackMessage }) {\n\tconst responseBody = await response.text();\n\treturn new APICallError$1({\n\t\tmessage: responseBody || fallbackMessage,\n\t\turl,\n\t\trequestBodyValues: void 0,\n\t\tstatusCode: response.status,\n\t\tresponseBody\n\t});\n}\n//#endregion\n//#region src/ui/process-text-stream.ts\nasync function processTextStream({ stream, onTextPart }) {\n\tconst reader = stream.pipeThrough(new TextDecoderStream()).getReader();\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\tawait onTextPart(value);\n\t}\n}\n//#endregion\n//#region src/ui/call-completion-api.ts\nconst getOriginalFetch = () => fetch;\nasync function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol = \"data\", setCompletion, setLoading, setError, setAbortController, getAbortController, onFinish, onError, fetch = getOriginalFetch() }) {\n\tconst abortController = new AbortController();\n\tconst isCurrentRequest = () => getAbortController == null || getAbortController() === abortController;\n\ttry {\n\t\tsetLoading(true);\n\t\tsetError(void 0);\n\t\tsetAbortController(abortController);\n\t\tsetCompletion(\"\");\n\t\tconst response = await fetch(api, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\tprompt,\n\t\t\t\t...body\n\t\t\t}),\n\t\t\tcredentials,\n\t\t\theaders: withUserAgentSuffix({\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...headers\n\t\t\t}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tsignal: abortController.signal\n\t\t}).catch((err) => {\n\t\t\tthrow err;\n\t\t});\n\t\tif (!response.ok) throw await createUIApiCallError({\n\t\t\tresponse,\n\t\t\turl: api,\n\t\t\tfallbackMessage: \"Failed to fetch the chat response.\"\n\t\t});\n\t\tif (!response.body) throw new EmptyResponseBodyError$1({ message: \"The response body is empty.\" });\n\t\tlet result = \"\";\n\t\tswitch (streamProtocol) {\n\t\t\tcase \"text\":\n\t\t\t\tawait processTextStream({\n\t\t\t\t\tstream: response.body,\n\t\t\t\t\tonTextPart: (chunk) => {\n\t\t\t\t\t\tresult += chunk;\n\t\t\t\t\t\tif (isCurrentRequest()) setCompletion(result);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"data\":\n\t\t\t\tawait consumeStream({\n\t\t\t\t\tstream: parseJsonEventStream$1({\n\t\t\t\t\t\tstream: response.body,\n\t\t\t\t\t\tschema: uiMessageChunkSchema\n\t\t\t\t\t}).pipeThrough(new TransformStream({ async transform(part) {\n\t\t\t\t\t\tif (!part.success) throw part.error;\n\t\t\t\t\t\tconst streamPart = part.value;\n\t\t\t\t\t\tif (streamPart.type === \"text-delta\") {\n\t\t\t\t\t\t\tresult += streamPart.delta;\n\t\t\t\t\t\t\tif (isCurrentRequest()) setCompletion(result);\n\t\t\t\t\t\t} else if (streamPart.type === \"error\") throw new UIMessageStreamError({\n\t\t\t\t\t\t\tchunkType: \"error\",\n\t\t\t\t\t\t\tchunkId: \"\",\n\t\t\t\t\t\t\tmessage: streamPart.errorText\n\t\t\t\t\t\t});\n\t\t\t\t\t} })),\n\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault: {\n\t\t\t\tconst exhaustiveCheck = streamProtocol;\n\t\t\t\tthrow new InvalidArgumentError({\n\t\t\t\t\tparameter: \"streamProtocol\",\n\t\t\t\t\tvalue: exhaustiveCheck,\n\t\t\t\t\tmessage: `Unknown stream protocol: ${exhaustiveCheck}`\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (onFinish) onFinish(prompt, result);\n\t\treturn result;\n\t} catch (err) {\n\t\tif (err.name === \"AbortError\") return null;\n\t\tif (err instanceof Error) {\n\t\t\tif (onError) onError(err);\n\t\t}\n\t\tif (isCurrentRequest()) setError(err);\n\t} finally {\n\t\tif (isCurrentRequest()) {\n\t\t\tsetAbortController(null);\n\t\t\tsetLoading(false);\n\t\t}\n\t}\n}\n//#endregion\n//#region src/ui/convert-file-list-to-file-ui-parts.ts\nasync function convertFileListToFileUIParts(files) {\n\tif (files == null) return [];\n\tif (!globalThis.FileList || !(files instanceof globalThis.FileList)) throw new UnsupportedFunctionalityError$1({\n\t\tfunctionality: \"FileList\",\n\t\tmessage: \"FileList is not supported in the current environment\"\n\t});\n\treturn Promise.all(Array.from(files).map(async (file) => {\n\t\tconst { name, type } = file;\n\t\treturn {\n\t\t\ttype: \"file\",\n\t\t\tmediaType: type,\n\t\t\tfilename: name,\n\t\t\turl: await new Promise((resolve, reject) => {\n\t\t\t\tconst reader = new FileReader();\n\t\t\t\treader.onload = (readerEvent) => {\n\t\t\t\t\tresolve(readerEvent.target?.result);\n\t\t\t\t};\n\t\t\t\treader.onerror = (error) => reject(error);\n\t\t\t\treader.readAsDataURL(file);\n\t\t\t})\n\t\t};\n\t}));\n}\n//#endregion\n//#region src/ui/http-chat-transport.ts\nfunction appendPathToUrl(url, path) {\n\tconst queryOrFragmentStart = url.search(/[?#]/);\n\tconst urlPath = queryOrFragmentStart === -1 ? url : url.slice(0, queryOrFragmentStart);\n\tconst suffix = queryOrFragmentStart === -1 ? \"\" : url.slice(queryOrFragmentStart);\n\treturn `${urlPath.endsWith(\"/\") && path.startsWith(\"/\") ? urlPath.slice(0, -1) : urlPath}${path}${suffix}`;\n}\nvar HttpChatTransport = class {\n\tconstructor({ api = \"/api/chat\", credentials, headers, body, fetch, prepareSendMessagesRequest, prepareReconnectToStreamRequest }) {\n\t\tthis.api = api;\n\t\tthis.credentials = credentials;\n\t\tthis.headers = headers;\n\t\tthis.body = body;\n\t\tthis.fetch = fetch;\n\t\tthis.prepareSendMessagesRequest = prepareSendMessagesRequest;\n\t\tthis.prepareReconnectToStreamRequest = prepareReconnectToStreamRequest;\n\t}\n\tasync sendMessages({ abortSignal, ...options }) {\n\t\tconst resolvedBody = await resolve(this.body);\n\t\tconst resolvedHeaders = await resolve(this.headers);\n\t\tconst resolvedCredentials = await resolve(this.credentials);\n\t\tconst baseHeaders = {\n\t\t\t...normalizeHeaders(resolvedHeaders),\n\t\t\t...normalizeHeaders(options.headers)\n\t\t};\n\t\tconst preparedRequest = await this.prepareSendMessagesRequest?.({\n\t\t\tapi: this.api,\n\t\t\tid: options.chatId,\n\t\t\tmessages: options.messages,\n\t\t\tbody: {\n\t\t\t\t...resolvedBody,\n\t\t\t\t...options.body\n\t\t\t},\n\t\t\theaders: baseHeaders,\n\t\t\tcredentials: resolvedCredentials,\n\t\t\trequestMetadata: options.metadata,\n\t\t\ttrigger: options.trigger,\n\t\t\tmessageId: options.messageId\n\t\t});\n\t\tconst api = preparedRequest?.api ?? this.api;\n\t\tconst headers = preparedRequest?.headers !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n\t\tconst body = preparedRequest?.body !== void 0 ? preparedRequest.body : {\n\t\t\t...resolvedBody,\n\t\t\t...options.body,\n\t\t\tid: options.chatId,\n\t\t\tmessages: options.messages,\n\t\t\ttrigger: options.trigger,\n\t\t\tmessageId: options.messageId\n\t\t};\n\t\tconst credentials = preparedRequest?.credentials ?? resolvedCredentials;\n\t\tconst response = await (this.fetch ?? globalThis.fetch)(api, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t...headers\n\t\t\t},\n\t\t\tbody: JSON.stringify(body),\n\t\t\tcredentials,\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tif (!response.ok) throw await createUIApiCallError({\n\t\t\tresponse,\n\t\t\turl: api,\n\t\t\tfallbackMessage: \"Failed to fetch the chat response.\"\n\t\t});\n\t\tif (!response.body) throw new EmptyResponseBodyError$1({ message: \"The response body is empty.\" });\n\t\treturn this.processResponseStream(response.body);\n\t}\n\tasync reconnectToStream(options) {\n\t\tconst resolvedBody = await resolve(this.body);\n\t\tconst resolvedHeaders = await resolve(this.headers);\n\t\tconst resolvedCredentials = await resolve(this.credentials);\n\t\tconst baseHeaders = {\n\t\t\t...normalizeHeaders(resolvedHeaders),\n\t\t\t...normalizeHeaders(options.headers)\n\t\t};\n\t\tconst preparedRequest = await this.prepareReconnectToStreamRequest?.({\n\t\t\tapi: this.api,\n\t\t\tid: options.chatId,\n\t\t\tbody: {\n\t\t\t\t...resolvedBody,\n\t\t\t\t...options.body\n\t\t\t},\n\t\t\theaders: baseHeaders,\n\t\t\tcredentials: resolvedCredentials,\n\t\t\trequestMetadata: options.metadata\n\t\t});\n\t\tlet api = preparedRequest?.api;\n\t\tif (api == null) {\n\t\t\tif (options.chatId === \".\" || options.chatId === \"..\") throw new InvalidArgumentError({\n\t\t\t\tparameter: \"chatId\",\n\t\t\t\tvalue: options.chatId,\n\t\t\t\tmessage: \"Chat IDs must not be \\\".\\\" or \\\"..\\\" when using the default reconnect URL.\"\n\t\t\t});\n\t\t\tapi = appendPathToUrl(this.api, `/${encodeURIComponent(options.chatId)}/stream`);\n\t\t}\n\t\tconst headers = preparedRequest?.headers !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n\t\tconst credentials = preparedRequest?.credentials ?? resolvedCredentials;\n\t\tconst response = await (this.fetch ?? globalThis.fetch)(api, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders,\n\t\t\tcredentials,\n\t\t\tsignal: options.abortSignal\n\t\t});\n\t\tif (response.status === 204) return null;\n\t\tif (!response.ok) throw await createUIApiCallError({\n\t\t\tresponse,\n\t\t\turl: api,\n\t\t\tfallbackMessage: \"Failed to fetch the chat response.\"\n\t\t});\n\t\tif (!response.body) throw new EmptyResponseBodyError$1({ message: \"The response body is empty.\" });\n\t\treturn this.processResponseStream(response.body);\n\t}\n};\n//#endregion\n//#region src/ui/default-chat-transport.ts\nvar DefaultChatTransport = class extends HttpChatTransport {\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t}\n\tprocessResponseStream(stream) {\n\t\treturn parseJsonEventStream$1({\n\t\t\tstream,\n\t\t\tschema: uiMessageChunkSchema\n\t\t}).pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\t\tif (!chunk.success) throw chunk.error;\n\t\t\tcontroller.enqueue(chunk.value);\n\t\t} }));\n\t}\n};\n//#endregion\n//#region src/ui/chat.ts\nvar AbstractChat = class {\n\tconstructor({ generateId = generateId$1, id = generateId(), transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen }) {\n\t\tthis.pendingMessagePreparations = /* @__PURE__ */ new Set();\n\t\tthis.activeResponse = void 0;\n\t\tthis.activeResumeRequest = void 0;\n\t\tthis.resumableStreamState = void 0;\n\t\tthis.jobExecutor = new SerialJobExecutor();\n\t\tthis.activeStopCount = 0;\n\t\tthis.stopGeneration = 0;\n\t\tthis.sendMessage = async (message, options) => {\n\t\t\tif (message == null) {\n\t\t\t\tlet messageId = this.pendingApprovalMessageId;\n\t\t\t\tif (messageId == null) {\n\t\t\t\t\tmessageId = this.lastMessage?.id;\n\t\t\t\t\tfor (let i = this.state.messages.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tconst candidate = this.state.messages[i];\n\t\t\t\t\t\tif (candidate.role === \"assistant\" && candidate.parts.some((part) => isToolUIPart(part) && part.state === \"approval-responded\")) {\n\t\t\t\t\t\t\tmessageId = candidate.id;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst pendingApprovalMessageIndex = messageId != null && messageId === this.pendingApprovalMessageId ? this.state.messages.findIndex((message) => message.id === messageId) : -1;\n\t\t\t\tawait this.makeRequestForToolApproval({\n\t\t\t\t\tmessageId,\n\t\t\t\t\tmessageIndex: pendingApprovalMessageIndex,\n\t\t\t\t\t...options\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet uiMessage;\n\t\t\tif (\"text\" in message || \"files\" in message) {\n\t\t\t\tconst abortController = new AbortController();\n\t\t\t\tthis.pendingMessagePreparations.add(abortController);\n\t\t\t\tlet fileParts;\n\t\t\t\ttry {\n\t\t\t\t\tfileParts = Array.isArray(message.files) ? message.files : await convertFileListToFileUIParts(message.files);\n\t\t\t\t} finally {\n\t\t\t\t\tthis.pendingMessagePreparations.delete(abortController);\n\t\t\t\t}\n\t\t\t\tif (abortController.signal.aborted) return;\n\t\t\t\tuiMessage = { parts: [...fileParts, ...\"text\" in message && message.text != null ? [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: message.text\n\t\t\t\t}] : []] };\n\t\t\t} else uiMessage = message;\n\t\t\tif (message.messageId != null) {\n\t\t\t\tconst messageIndex = this.state.messages.findIndex((m) => m.id === message.messageId);\n\t\t\t\tif (messageIndex === -1) throw new InvalidArgumentError({\n\t\t\t\t\tparameter: \"message.messageId\",\n\t\t\t\t\tvalue: message.messageId,\n\t\t\t\t\tmessage: `message with id ${message.messageId} not found`\n\t\t\t\t});\n\t\t\t\tif (this.state.messages[messageIndex].role !== \"user\") throw new InvalidArgumentError({\n\t\t\t\t\tparameter: \"message.messageId\",\n\t\t\t\t\tvalue: message.messageId,\n\t\t\t\t\tmessage: `message with id ${message.messageId} is not a user message`\n\t\t\t\t});\n\t\t\t\tthis.state.messages = this.state.messages.slice(0, messageIndex + 1);\n\t\t\t\tthis.state.replaceMessage(messageIndex, {\n\t\t\t\t\tid: message.messageId,\n\t\t\t\t\t...uiMessage,\n\t\t\t\t\trole: uiMessage.role ?? \"user\",\n\t\t\t\t\tmetadata: message.metadata\n\t\t\t\t});\n\t\t\t} else this.state.pushMessage({\n\t\t\t\t...uiMessage,\n\t\t\t\tid: uiMessage.id ?? this.generateId(),\n\t\t\t\trole: uiMessage.role ?? \"user\",\n\t\t\t\tmetadata: message.metadata\n\t\t\t});\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\tmessageId: message.messageId,\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\tthis.regenerate = async ({ messageId, ...options } = {}) => {\n\t\t\tconst messageIndex = messageId == null ? this.state.messages.length - 1 : this.state.messages.findIndex((message) => message.id === messageId);\n\t\t\tif (messageIndex === -1) throw new InvalidArgumentError({\n\t\t\t\tparameter: \"messageId\",\n\t\t\t\tvalue: messageId,\n\t\t\t\tmessage: `message ${messageId} not found`\n\t\t\t});\n\t\t\tthis.state.messages = this.state.messages.slice(0, this.messages[messageIndex].role === \"assistant\" ? messageIndex : messageIndex + 1);\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"regenerate-message\",\n\t\t\t\tmessageId,\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\tthis.resumeStream = async (options = {}) => {\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"resume-stream\",\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\tthis.clearError = () => {\n\t\t\tif (this.status === \"error\") {\n\t\t\t\tthis.state.error = void 0;\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t}\n\t\t};\n\t\tthis.addToolApprovalResponse = async ({ id, approved, reason, options }) => this.jobExecutor.run(async () => {\n\t\t\tconst messages = this.state.messages;\n\t\t\tconst updatePart = (part) => isToolUIPart(part) && part.state === \"approval-requested\" && part.approval.id === id ? {\n\t\t\t\t...part,\n\t\t\t\tstate: \"approval-responded\",\n\t\t\t\tapproval: {\n\t\t\t\t\t...part.approval,\n\t\t\t\t\tid,\n\t\t\t\t\tapproved,\n\t\t\t\t\treason\n\t\t\t\t}\n\t\t\t} : part;\n\t\t\tconst messageIndex = messages.findIndex((message) => message.parts.some((part) => isToolUIPart(part) && part.state === \"approval-requested\" && part.approval.id === id));\n\t\t\tif (messageIndex !== -1) {\n\t\t\t\tconst message = messages[messageIndex];\n\t\t\t\tthis.state.replaceMessage(messageIndex, {\n\t\t\t\t\t...message,\n\t\t\t\t\tparts: message.parts.map(updatePart)\n\t\t\t\t});\n\t\t\t\tthis.pendingApprovalMessageId = message.id;\n\t\t\t}\n\t\t\tif (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);\n\t\t\tif (messageIndex !== -1 && this.status !== \"streaming\" && this.status !== \"submitted\" && this.sendAutomaticallyWhen) {\n\t\t\t\tconst shouldSend = await this.shouldSendAutomatically();\n\t\t\t\tif (shouldSend) this.runAutomaticRequest(() => {\n\t\t\t\t\tconst messageId = messageIndex === -1 ? this.lastMessage?.id : messages[messageIndex].id;\n\t\t\t\t\treturn this.makeRequestForToolApproval({\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmessageIndex,\n\t\t\t\t\t\t...options\n\t\t\t\t\t});\n\t\t\t\t}, shouldSend);\n\t\t\t}\n\t\t});\n\t\tthis.addToolOutput = async ({ state, toolCallId, output, errorText, options }) => this.jobExecutor.run(async () => {\n\t\t\tconst messages = this.state.messages;\n\t\t\tconst lastMessage = messages[messages.length - 1];\n\t\t\tconst updatePart = (part) => {\n\t\t\t\tif (!isToolUIPart(part) || part.toolCallId !== toolCallId) return part;\n\t\t\t\tconst { approval: existingApproval, ...toolPart } = part;\n\t\t\t\tconst approval = existingApproval?.approved === true ? { approval: {\n\t\t\t\t\t...existingApproval,\n\t\t\t\t\tapproved: existingApproval.approved\n\t\t\t\t} } : {};\n\t\t\t\treturn state === \"output-error\" ? {\n\t\t\t\t\t...toolPart,\n\t\t\t\t\t...approval,\n\t\t\t\t\tstate,\n\t\t\t\t\tinput: part.input,\n\t\t\t\t\toutput: void 0,\n\t\t\t\t\terrorText\n\t\t\t\t} : {\n\t\t\t\t\t...toolPart,\n\t\t\t\t\t...approval,\n\t\t\t\t\tstate: \"output-available\",\n\t\t\t\t\tinput: part.input,\n\t\t\t\t\toutput,\n\t\t\t\t\terrorText: void 0\n\t\t\t\t};\n\t\t\t};\n\t\t\tthis.state.replaceMessage(messages.length - 1, {\n\t\t\t\t...lastMessage,\n\t\t\t\tparts: lastMessage.parts.map(updatePart)\n\t\t\t});\n\t\t\tif (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);\n\t\t\tif (this.status !== \"streaming\" && this.status !== \"submitted\" && this.sendAutomaticallyWhen) {\n\t\t\t\tconst shouldSend = await this.shouldSendAutomatically();\n\t\t\t\tif (shouldSend) this.runAutomaticRequest(() => this.makeRequest({\n\t\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\t\tmessageId: this.lastMessage?.id,\n\t\t\t\t\t...options\n\t\t\t\t}), shouldSend);\n\t\t\t}\n\t\t});\n\t\tthis.addToolResult = this.addToolOutput;\n\t\tthis.stop = async () => {\n\t\t\tthis.activeStopCount++;\n\t\t\tthis.stopGeneration++;\n\t\t\ttry {\n\t\t\t\tconst activeResumeRequest = this.activeResumeRequest;\n\t\t\t\tconst activeResponse = this.activeResponse;\n\t\t\t\tfor (const controller of this.pendingMessagePreparations) controller.abort();\n\t\t\t\tactiveResumeRequest?.abortController.abort();\n\t\t\t\tactiveResponse?.abortController.abort();\n\t\t\t\tawait Promise.all([activeResumeRequest?.completionPromise, activeResponse?.completionPromise]);\n\t\t\t\tawait this.jobExecutor.waitForIdle();\n\t\t\t} finally {\n\t\t\t\tthis.activeStopCount--;\n\t\t\t}\n\t\t};\n\t\tthis.dispose = async () => {\n\t\t\tawait this.stop();\n\t\t\tthis.transport.close?.();\n\t\t};\n\t\tthis.id = id;\n\t\tthis.transport = transport;\n\t\tthis.generateId = generateId;\n\t\tthis.messageMetadataSchema = messageMetadataSchema;\n\t\tthis.dataPartSchemas = dataPartSchemas;\n\t\tthis.state = state;\n\t\tthis.onError = onError;\n\t\tthis.onToolCall = onToolCall;\n\t\tthis.onFinish = onFinish;\n\t\tthis.onData = onData;\n\t\tthis.sendAutomaticallyWhen = sendAutomaticallyWhen;\n\t}\n\t/**\n\t* Hook status:\n\t*\n\t* - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n\t* - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n\t* - `ready`: The full response has been received and processed; a new user message can be submitted.\n\t* - `error`: An error occurred during the API request, preventing successful completion.\n\t*/\n\tget status() {\n\t\treturn this.state.status;\n\t}\n\tsetStatus({ status, error }) {\n\t\tif (this.status === status) {\n\t\t\tif (this.error !== error) this.state.error = error;\n\t\t\treturn;\n\t\t}\n\t\tthis.state.status = status;\n\t\tthis.state.error = error;\n\t}\n\tget error() {\n\t\treturn this.state.error;\n\t}\n\tget messages() {\n\t\treturn this.state.messages;\n\t}\n\tget lastMessage() {\n\t\treturn this.state.messages[this.state.messages.length - 1];\n\t}\n\tset messages(messages) {\n\t\tthis.state.messages = messages;\n\t}\n\tasync shouldSendAutomatically() {\n\t\tif (!this.sendAutomaticallyWhen) return false;\n\t\tconst result = this.sendAutomaticallyWhen({ messages: this.state.messages });\n\t\tif (result && typeof result === \"object\" && \"then\" in result) return await result;\n\t\treturn result;\n\t}\n\tasync runAutomaticRequest(request, shouldSend) {\n\t\tconst stopGeneration = this.stopGeneration;\n\t\tconst startedWhileStopping = this.activeStopCount > 0;\n\t\tif (!(shouldSend ?? await this.shouldSendAutomatically())) return;\n\t\tif (startedWhileStopping || stopGeneration !== this.stopGeneration || this.activeStopCount > 0) return;\n\t\tawait request();\n\t}\n\tasync makeRequestForToolApproval({ messageId, messageIndex, ...options }) {\n\t\tconst consumesPendingApproval = messageId != null && messageId === this.pendingApprovalMessageId;\n\t\tif (consumesPendingApproval) this.pendingApprovalMessageId = void 0;\n\t\tawait this.makeRequest({\n\t\t\ttrigger: \"submit-message\",\n\t\t\tmessageId,\n\t\t\t...options\n\t\t});\n\t\tif (consumesPendingApproval && this.status === \"error\" && this.pendingApprovalMessageId == null) this.pendingApprovalMessageId = this.state.messages[messageIndex]?.id ?? messageId;\n\t}\n\tasync makeRequest(options) {\n\t\tconst completion = createResolvablePromise();\n\t\ttry {\n\t\t\tawait this.makeRequestImpl({\n\t\t\t\t...options,\n\t\t\t\tcompletionPromise: completion.promise\n\t\t\t});\n\t\t} finally {\n\t\t\tcompletion.resolve();\n\t\t}\n\t}\n\tasync makeRequestImpl({ trigger, metadata, headers, body, messageId, completionPromise }) {\n\t\tif (trigger !== \"resume-stream\") this.resumableStreamState = void 0;\n\t\tconst abortController = new AbortController();\n\t\tconst activeResumeRequest = trigger === \"resume-stream\" ? {\n\t\t\tabortController,\n\t\t\tcompletionPromise\n\t\t} : void 0;\n\t\tif (activeResumeRequest) {\n\t\t\tthis.activeResumeRequest?.abortController.abort();\n\t\t\tthis.activeResumeRequest = activeResumeRequest;\n\t\t}\n\t\tconst isCurrentRequest = () => activeResumeRequest == null || this.activeResumeRequest === activeResumeRequest;\n\t\tconst clearActiveResumeRequest = () => {\n\t\t\tif (this.activeResumeRequest === activeResumeRequest) this.activeResumeRequest = void 0;\n\t\t};\n\t\tlet resumeStream;\n\t\tif (trigger === \"resume-stream\") try {\n\t\t\tconst reconnect = await this.transport.reconnectToStream({\n\t\t\t\tchatId: this.id,\n\t\t\t\tabortSignal: abortController.signal,\n\t\t\t\tmetadata,\n\t\t\t\theaders,\n\t\t\t\tbody\n\t\t\t});\n\t\t\tif (abortController.signal.aborted || !isCurrentRequest()) {\n\t\t\t\tawait reconnect?.cancel().catch(() => {});\n\t\t\t\tif (isCurrentRequest()) {\n\t\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\t\tthis.resumableStreamState = void 0;\n\t\t\t\t}\n\t\t\t\tclearActiveResumeRequest();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (reconnect == null) {\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\tthis.resumableStreamState = void 0;\n\t\t\t\tclearActiveResumeRequest();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresumeStream = reconnect;\n\t\t} catch (err) {\n\t\t\tif (abortController.signal.aborted || err.name === \"AbortError\") {\n\t\t\t\tif (isCurrentRequest()) {\n\t\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\t\tthis.resumableStreamState = void 0;\n\t\t\t\t}\n\t\t\t\tclearActiveResumeRequest();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!isCurrentRequest()) return;\n\t\t\tif (this.onError && err instanceof Error) this.onError(err);\n\t\t\tthis.setStatus({\n\t\t\t\tstatus: \"error\",\n\t\t\t\terror: err\n\t\t\t});\n\t\t\tclearActiveResumeRequest();\n\t\t\treturn;\n\t\t}\n\t\tthis.setStatus({\n\t\t\tstatus: \"submitted\",\n\t\t\terror: void 0\n\t\t});\n\t\tconst lastMessage = this.lastMessage;\n\t\tconst responseMessageIndex = trigger === \"submit-message\" && messageId != null ? this.state.messages.findIndex((message) => message.id === messageId) : this.state.messages.length - 1;\n\t\tconst responseMessage = responseMessageIndex === -1 ? lastMessage : this.state.messages[responseMessageIndex];\n\t\tconst resumableResponseMessage = trigger === \"resume-stream\" && responseMessage?.role === \"assistant\" && responseMessage.parts.some((part) => isToolUIPart(part) && (part.state === \"input-streaming\" || part.state === \"input-available\" && part.providerExecuted || part.state === \"approval-responded\")) ? this.state.snapshot(responseMessage) : void 0;\n\t\tconst usesEarlierAssistantMessage = responseMessageIndex !== -1 && responseMessageIndex < this.state.messages.length - 1 && responseMessage?.role === \"assistant\";\n\t\tlet isAbort = false;\n\t\tlet isDisconnect = false;\n\t\tlet isError = false;\n\t\tlet activeResponse;\n\t\ttry {\n\t\t\tconst response = {\n\t\t\t\tstate: trigger === \"resume-stream\" && this.resumableStreamState != null ? this.resumableStreamState : createStreamingUIMessageState({\n\t\t\t\t\tlastMessage: trigger === \"resume-stream\" ? resumableResponseMessage : trigger === \"regenerate-message\" ? void 0 : this.state.snapshot(responseMessage),\n\t\t\t\t\tmessageId: this.generateId()\n\t\t\t\t}),\n\t\t\t\tabortController,\n\t\t\t\tcompletionPromise\n\t\t\t};\n\t\t\tactiveResponse = response;\n\t\t\tresponse.abortController.signal.addEventListener(\"abort\", () => {\n\t\t\t\tisAbort = true;\n\t\t\t});\n\t\t\tthis.activeResponse = response;\n\t\t\tlet stream;\n\t\t\tif (trigger === \"resume-stream\") stream = resumeStream;\n\t\t\telse stream = await this.transport.sendMessages({\n\t\t\t\tchatId: this.id,\n\t\t\t\tmessages: this.state.messages,\n\t\t\t\tabortSignal: response.abortController.signal,\n\t\t\t\tmetadata,\n\t\t\t\theaders,\n\t\t\t\tbody,\n\t\t\t\ttrigger,\n\t\t\t\tmessageId\n\t\t\t});\n\t\t\tconst runUpdateMessageJob = (job) => this.jobExecutor.run(() => {\n\t\t\t\tif (response.abortController.signal.aborted) return Promise.resolve();\n\t\t\t\treturn job({\n\t\t\t\t\tstate: response.state,\n\t\t\t\t\twrite: ({ updateStatus = true } = {}) => {\n\t\t\t\t\t\tif (response.abortController.signal.aborted) return;\n\t\t\t\t\t\tif (updateStatus) this.setStatus({ status: \"streaming\" });\n\t\t\t\t\t\tif (usesEarlierAssistantMessage) this.state.replaceMessage(responseMessageIndex, response.state.message);\n\t\t\t\t\t\telse if (response.state.message.id === this.lastMessage?.id) this.state.replaceMessage(this.state.messages.length - 1, response.state.message);\n\t\t\t\t\t\telse this.state.pushMessage(response.state.message);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t\tawait consumeStream({\n\t\t\t\tstream: processUIMessageStream({\n\t\t\t\t\tstream,\n\t\t\t\t\tresetStateOnMessageIdChange: trigger === \"resume-stream\",\n\t\t\t\t\tresetStateOnFirstMessageStart: trigger === \"resume-stream\" && this.transport.resumeStreamIsReplay,\n\t\t\t\t\tonToolCall: this.onToolCall,\n\t\t\t\t\tonData: this.onData,\n\t\t\t\t\tmessageMetadataSchema: this.messageMetadataSchema,\n\t\t\t\t\tdataPartSchemas: this.dataPartSchemas,\n\t\t\t\t\trunUpdateMessageJob,\n\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\tabortSignal: response.abortController.signal,\n\t\t\t\tonError: (error) => {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (isAbort) {\n\t\t\t\tif (isCurrentRequest()) {\n\t\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\t\tif (this.resumableStreamState === response.state) this.resumableStreamState = void 0;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (isCurrentRequest()) {\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\tif (this.resumableStreamState === response.state) this.resumableStreamState = void 0;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tif (isAbort || err.name === \"AbortError\") {\n\t\t\t\tisAbort = true;\n\t\t\t\tif (isCurrentRequest()) {\n\t\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\t\tif (this.resumableStreamState === activeResponse?.state) this.resumableStreamState = void 0;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!isCurrentRequest()) return null;\n\t\t\tisError = true;\n\t\t\tif (err instanceof TypeError) {\n\t\t\t\tconst message = err.message.toLowerCase();\n\t\t\t\tisDisconnect = message.includes(\"fetch\") || message.includes(\"network\") || message === \"load failed\";\n\t\t\t}\n\t\t\tif (isDisconnect) this.resumableStreamState = activeResponse?.state;\n\t\t\telse if (this.resumableStreamState === activeResponse?.state) this.resumableStreamState = void 0;\n\t\t\tif (this.onError && err instanceof Error) this.onError(err);\n\t\t\tthis.setStatus({\n\t\t\t\tstatus: \"error\",\n\t\t\t\terror: err\n\t\t\t});\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tif (activeResponse) this.onFinish?.({\n\t\t\t\t\tmessage: activeResponse.state.message,\n\t\t\t\t\tmessages: this.state.messages,\n\t\t\t\t\tisAbort,\n\t\t\t\t\tisDisconnect,\n\t\t\t\t\tisError,\n\t\t\t\t\tfinishReason: activeResponse.state.finishReason\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tif (this.activeResponse === activeResponse) this.activeResponse = void 0;\n\t\t\t\tclearActiveResumeRequest();\n\t\t\t}\n\t\t}\n\t\tif (!isAbort && !isError) await this.runAutomaticRequest(() => this.makeRequest({\n\t\t\ttrigger: \"submit-message\",\n\t\t\tmessageId: this.lastMessage?.id,\n\t\t\tmetadata,\n\t\t\theaders,\n\t\t\tbody\n\t\t}));\n\t}\n};\n//#endregion\n//#region src/ui/direct-chat-transport.ts\n/**\n* A transport that directly communicates with an Agent in-process,\n* without going through HTTP. This is useful for:\n* - Server-side rendering scenarios\n* - Testing without network\n* - Single-process applications\n*\n* @example\n* ```tsx\n* import { useChat } from '@ai-sdk/react';\n* import { DirectChatTransport } from 'ai';\n* import { myAgent } from './my-agent';\n*\n* const { messages, sendMessage } = useChat({\n* transport: new DirectChatTransport({ agent: myAgent }),\n* });\n* ```\n*/\nvar DirectChatTransport = class {\n\tconstructor({ agent, options, ...uiMessageStreamOptions }) {\n\t\tthis.agent = agent;\n\t\tthis.agentOptions = options;\n\t\tthis.uiMessageStreamOptions = uiMessageStreamOptions;\n\t}\n\tasync sendMessages({ messages, abortSignal }) {\n\t\tconst validatedMessages = await validateUIMessagesForAgent({\n\t\t\tmessages,\n\t\t\ttools: this.agent.tools\n\t\t});\n\t\tconst modelMessages = await convertToModelMessages(validatedMessages, { tools: this.agent.tools });\n\t\tconst result = await this.agent.stream({\n\t\t\tprompt: modelMessages,\n\t\t\tabortSignal,\n\t\t\t...this.agentOptions !== void 0 ? { options: this.agentOptions } : {}\n\t\t});\n\t\treturn toUIMessageStream({\n\t\t\t...this.uiMessageStreamOptions,\n\t\t\toriginalMessages: this.uiMessageStreamOptions.originalMessages ?? validatedMessages,\n\t\t\tstream: result.stream,\n\t\t\ttools: this.agent.tools\n\t\t});\n\t}\n\t/**\n\t* Direct transport does not support reconnection since there is no\n\t* persistent server-side stream to reconnect to.\n\t*\n\t* @returns Always returns `null`\n\t*/\n\tasync reconnectToStream(_options) {\n\t\treturn null;\n\t}\n};\n//#endregion\n//#region src/ui/last-assistant-message-is-complete-with-approval-responses.ts\n/**\n* Check if the last message is an assistant message with completed tool call approvals.\n* The last step of the message must have at least one tool approval response and\n* all tool approvals must have a response.\n*/\nfunction lastAssistantMessageIsCompleteWithApprovalResponses({ messages }) {\n\tconst message = messages[messages.length - 1];\n\tif (!message) return false;\n\tif (message.role !== \"assistant\") return false;\n\tconst lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n\t\treturn part.type === \"step-start\" ? index : lastIndex;\n\t}, -1);\n\tconst lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter(isToolUIPart);\n\treturn lastStepToolInvocations.filter((part) => part.state === \"approval-responded\").length > 0 && lastStepToolInvocations.every((part) => part.state === \"output-available\" && part.preliminary !== true || part.state === \"output-error\" || part.state === \"output-denied\" || part.state === \"approval-responded\");\n}\n//#endregion\n//#region src/ui/last-assistant-message-is-complete-with-tool-calls.ts\n/**\n* Check if the last message is an assistant message with completed tool calls.\n* The last step of the message must have at least one tool invocation and\n* all tool invocations must have a result. Completed model text may follow\n* the tool invocation because client-side tool results update parts in place,\n* but trailing text without a completed stream state prevents resubmission.\n*/\nfunction lastAssistantMessageIsCompleteWithToolCalls({ messages }) {\n\tconst message = messages[messages.length - 1];\n\tif (!message) return false;\n\tif (message.role !== \"assistant\") return false;\n\tconst lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n\t\treturn part.type === \"step-start\" ? index : lastIndex;\n\t}, -1);\n\tconst lastStepParts = message.parts.slice(lastStepStartIndex + 1);\n\tconst lastStepToolInvocations = lastStepParts.filter(isToolUIPart).filter((part) => !part.providerExecuted);\n\tconst lastToolInvocationIndex = lastStepParts.reduce((lastIndex, part, index) => isToolUIPart(part) && !part.providerExecuted ? index : lastIndex, -1);\n\treturn lastStepToolInvocations.length > 0 && !lastStepParts.slice(lastToolInvocationIndex + 1).some((part) => part.type === \"text\" && part.state !== \"done\") && lastStepToolInvocations.every((part) => part.state === \"output-available\" && part.preliminary !== true || part.state === \"output-error\");\n}\n//#endregion\n//#region src/ui/transform-text-to-ui-message-stream.ts\nfunction transformTextToUiMessageStream({ stream }) {\n\treturn stream.pipeThrough(new TransformStream({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue({ type: \"start\" });\n\t\t\tcontroller.enqueue({ type: \"start-step\" });\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-start\",\n\t\t\t\tid: \"text-1\"\n\t\t\t});\n\t\t},\n\t\tasync transform(part, controller) {\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-delta\",\n\t\t\t\tid: \"text-1\",\n\t\t\t\tdelta: part\n\t\t\t});\n\t\t},\n\t\tasync flush(controller) {\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-end\",\n\t\t\t\tid: \"text-1\"\n\t\t\t});\n\t\t\tcontroller.enqueue({ type: \"finish-step\" });\n\t\t\tcontroller.enqueue({ type: \"finish\" });\n\t\t}\n\t}));\n}\n//#endregion\n//#region src/ui/text-stream-chat-transport.ts\nvar TextStreamChatTransport = class extends HttpChatTransport {\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t}\n\tprocessResponseStream(stream) {\n\t\treturn transformTextToUiMessageStream({ stream: stream.pipeThrough(new TextDecoderStream()) });\n\t}\n};\n//#endregion\n//#region src/ui/websocket-chat-transport.ts\nconst WEBSOCKET_OPEN_STATE = 1;\nfunction createAbortError(signal) {\n\tconst reason = signal?.reason;\n\tif (reason instanceof Error) return reason;\n\tconst error = /* @__PURE__ */ new Error(\"The WebSocket chat request was aborted.\");\n\terror.name = \"AbortError\";\n\treturn error;\n}\nfunction asError(error) {\n\treturn error instanceof Error ? error : new Error(String(error));\n}\nfunction isRecord(value) {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction isStringRecord(value) {\n\treturn isRecord(value) && Object.values(value).every((item) => typeof item === \"string\");\n}\nfunction isSequence(value) {\n\treturn Number.isSafeInteger(value) && value >= 0;\n}\n/**\n* Validates an untrusted client-to-server WebSocket chat frame.\n*/\nasync function safeValidateWebSocketChatTransportRequest({ value }) {\n\ttry {\n\t\tif (!isRecord(value) || typeof value.type !== \"string\") throw new Error(\"Invalid WebSocket chat request frame.\");\n\t\tif (value.type === \"abort\") {\n\t\t\tif (typeof value.requestId !== \"string\") throw new Error(\"Invalid WebSocket chat abort request.\");\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: value\n\t\t\t};\n\t\t}\n\t\tif (typeof value.requestId !== \"string\" || typeof value.id !== \"string\" || !isStringRecord(value.headers) || !isRecord(value.body)) throw new Error(\"Invalid WebSocket chat request frame.\");\n\t\tif (value.type === \"resume\") {\n\t\t\tif (value.lastSequence !== void 0 && !isSequence(value.lastSequence)) throw new Error(\"Invalid WebSocket chat resume sequence.\");\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: value\n\t\t\t};\n\t\t}\n\t\tif (value.type !== \"send\" || ![\"submit-message\", \"regenerate-message\"].includes(value.trigger) || value.messageId !== void 0 && typeof value.messageId !== \"string\") throw new Error(\"Invalid WebSocket chat send request.\");\n\t\tconst messages = await safeValidateUIMessages({ messages: value.messages });\n\t\tif (!messages.success) throw new Error(\"Invalid UI messages in WebSocket chat request.\", { cause: messages.error });\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\t...value,\n\t\t\t\tmessages: messages.data\n\t\t\t}\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: asError(error)\n\t\t};\n\t}\n}\n/**\n* A `ChatTransport` that multiplexes correlated UI message streams over one\n* persistent WebSocket connection.\n*\n* The server must implement the protocol represented by\n* `WebSocketChatTransportRequest` and `WebSocketChatTransportResponse`.\n*/\nvar WebSocketChatTransport = class {\n\tconstructor(options) {\n\t\tthis.resumeStreamIsReplay = true;\n\t\tthis.activeRequests = /* @__PURE__ */ new Map();\n\t\tthis.sendQueue = Promise.resolve();\n\t\tthis.url = options.url;\n\t\tthis.protocols = options.protocols;\n\t\tthis.params = options.params;\n\t\tthis.headers = options.headers;\n\t\tthis.body = options.body;\n\t\tthis.webSocket = options.webSocket;\n\t\tthis.prepareSendMessagesRequest = options.prepareSendMessagesRequest;\n\t\tthis.prepareReconnectToStreamRequest = options.prepareReconnectToStreamRequest;\n\t}\n\tasync sendMessages({ abortSignal, ...options }) {\n\t\tthis.throwIfAborted(abortSignal);\n\t\tconst [resolvedHeaders, resolvedBody] = await Promise.all([resolve(this.headers), resolve(this.body)]);\n\t\tthis.throwIfAborted(abortSignal);\n\t\tconst headers = {\n\t\t\t...normalizeHeaders(resolvedHeaders),\n\t\t\t...normalizeHeaders(options.headers)\n\t\t};\n\t\tconst body = {\n\t\t\t...resolvedBody,\n\t\t\t...options.body\n\t\t};\n\t\tconst preparedRequest = await this.prepareSendMessagesRequest?.({\n\t\t\tid: options.chatId,\n\t\t\tmessages: options.messages,\n\t\t\trequestMetadata: options.metadata,\n\t\t\tbody,\n\t\t\theaders,\n\t\t\ttrigger: options.trigger,\n\t\t\tmessageId: options.messageId\n\t\t});\n\t\tthis.throwIfAborted(abortSignal);\n\t\tconst socket = await this.getSocket(abortSignal);\n\t\tconst requestId = generateId$1();\n\t\tconst request = this.createActiveRequest({\n\t\t\trequestId,\n\t\t\tkind: \"send\",\n\t\t\tlastSequence: -1,\n\t\t\tabortSignal\n\t\t});\n\t\tconst frame = {\n\t\t\ttype: \"send\",\n\t\t\trequestId,\n\t\t\tid: options.chatId,\n\t\t\ttrigger: options.trigger,\n\t\t\tmessageId: options.messageId,\n\t\t\tmessages: preparedRequest?.messages ?? options.messages,\n\t\t\theaders: preparedRequest?.headers == null ? headers : normalizeHeaders(preparedRequest.headers),\n\t\t\tbody: preparedRequest?.body ?? body,\n\t\t\tmetadata: options.metadata\n\t\t};\n\t\ttry {\n\t\t\tawait this.sendFrame(socket, frame, abortSignal);\n\t\t\treturn request.stream;\n\t\t} catch (error) {\n\t\t\tconst requestError = asError(error);\n\t\t\tthis.failRequest(request, requestError);\n\t\t\tthrow requestError;\n\t\t}\n\t}\n\tasync reconnectToStream(options) {\n\t\tthis.throwIfAborted(options.abortSignal);\n\t\tconst [resolvedHeaders, resolvedBody] = await Promise.all([resolve(this.headers), resolve(this.body)]);\n\t\tthis.throwIfAborted(options.abortSignal);\n\t\tconst headers = {\n\t\t\t...normalizeHeaders(resolvedHeaders),\n\t\t\t...normalizeHeaders(options.headers)\n\t\t};\n\t\tconst body = {\n\t\t\t...resolvedBody,\n\t\t\t...options.body\n\t\t};\n\t\tconst preparedRequest = await this.prepareReconnectToStreamRequest?.({\n\t\t\tid: options.chatId,\n\t\t\trequestMetadata: options.metadata,\n\t\t\tbody,\n\t\t\theaders\n\t\t});\n\t\tthis.throwIfAborted(options.abortSignal);\n\t\tconst socket = await this.getSocket(options.abortSignal);\n\t\tconst requestId = generateId$1();\n\t\tlet resolveResponse;\n\t\tlet rejectResponse;\n\t\tconst responsePromise = new Promise((resolve, reject) => {\n\t\t\tresolveResponse = resolve;\n\t\t\trejectResponse = reject;\n\t\t});\n\t\tresponsePromise.catch(() => {});\n\t\tconst request = this.createActiveRequest({\n\t\t\trequestId,\n\t\t\tkind: \"resume\",\n\t\t\tlastSequence: -1,\n\t\t\tabortSignal: options.abortSignal,\n\t\t\tresolveResponse,\n\t\t\trejectResponse\n\t\t});\n\t\tconst frame = {\n\t\t\ttype: \"resume\",\n\t\t\trequestId,\n\t\t\tid: options.chatId,\n\t\t\tlastSequence: void 0,\n\t\t\theaders: preparedRequest?.headers == null ? headers : normalizeHeaders(preparedRequest.headers),\n\t\t\tbody: preparedRequest?.body ?? body,\n\t\t\tmetadata: options.metadata\n\t\t};\n\t\ttry {\n\t\t\tawait this.sendFrame(socket, frame, options.abortSignal);\n\t\t} catch (error) {\n\t\t\tconst requestError = asError(error);\n\t\t\trequest.responseSettled = true;\n\t\t\tthis.failRequest(request, requestError);\n\t\t\tthrow requestError;\n\t\t}\n\t\treturn responsePromise;\n\t}\n\t/**\n\t* Closes the current connection and errors any active response streams.\n\t* A later request opens a new connection.\n\t*/\n\tclose() {\n\t\tconst error = /* @__PURE__ */ new Error(\"WebSocket chat transport was closed.\");\n\t\tconst connection = this.connection;\n\t\tthis.connection = void 0;\n\t\tthis.failAllRequests(error);\n\t\tif (connection != null) {\n\t\t\tthis.rejectConnection(connection, error);\n\t\t\ttry {\n\t\t\t\tconnection.socket?.close(1e3, \"Client closed transport\");\n\t\t\t} catch {}\n\t\t}\n\t}\n\tthrowIfAborted(abortSignal) {\n\t\tif (abortSignal?.aborted) throw createAbortError(abortSignal);\n\t}\n\tasync getSocket(abortSignal) {\n\t\tconst existingSocket = this.connection?.socket;\n\t\tif (existingSocket?.readyState === WEBSOCKET_OPEN_STATE) return existingSocket;\n\t\tif (this.connection == null) {\n\t\t\tlet resolveConnection;\n\t\t\tlet rejectConnection;\n\t\t\tconst connection = {\n\t\t\t\tpromise: new Promise((resolve, reject) => {\n\t\t\t\t\tresolveConnection = resolve;\n\t\t\t\t\trejectConnection = reject;\n\t\t\t\t}),\n\t\t\t\tresolve: resolveConnection,\n\t\t\t\treject: rejectConnection,\n\t\t\t\tsettled: false\n\t\t\t};\n\t\t\tthis.connection = connection;\n\t\t\tthis.initializeConnection(connection);\n\t\t}\n\t\tconst connection = this.connection;\n\t\tif (connection == null) throw new Error(\"Failed to initialize WebSocket connection.\");\n\t\treturn this.waitForConnection(connection.promise, abortSignal);\n\t}\n\tasync initializeConnection(connection) {\n\t\ttry {\n\t\t\tconst params = await resolve(this.params);\n\t\t\tif (this.connection !== connection) return;\n\t\t\tconst url = this.buildUrl(params);\n\t\t\tconst socket = new (getWebSocketConstructor(this.webSocket))(url, this.protocols);\n\t\t\tconnection.socket = socket;\n\t\t\tlet messageTail = Promise.resolve();\n\t\t\tsocket.onopen = () => {\n\t\t\t\tif (this.connection !== connection) return;\n\t\t\t\tthis.resolveConnection(connection, socket);\n\t\t\t};\n\t\t\tsocket.onmessage = (event) => {\n\t\t\t\tmessageTail = messageTail.then(() => readWebSocketMessageText(event.data)).then((text) => this.handleResponseFrame(connection, text)).catch((error) => {\n\t\t\t\t\tthis.terminateConnection(connection, asError(error));\n\t\t\t\t});\n\t\t\t};\n\t\t\tsocket.onerror = () => {\n\t\t\t\tthis.terminateConnection(connection, /* @__PURE__ */ new TypeError(\"WebSocket chat network connection failed.\"));\n\t\t\t};\n\t\t\tsocket.onclose = (event) => {\n\t\t\t\tmessageTail = messageTail.then(() => {\n\t\t\t\t\tif (this.connection !== connection) return;\n\t\t\t\t\tconst closeEvent = event;\n\t\t\t\t\tconst code = typeof closeEvent?.code === \"number\" ? closeEvent.code : void 0;\n\t\t\t\t\tconst reason = typeof closeEvent?.reason === \"string\" && closeEvent.reason !== \"\" ? `: ${closeEvent.reason}` : \"\";\n\t\t\t\t\tthis.terminateConnection(connection, /* @__PURE__ */ new TypeError(`WebSocket chat network connection closed${code == null ? \"\" : ` (code ${code}${reason})`}.`), false);\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tthis.terminateConnection(connection, asError(error));\n\t\t\t\t});\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthis.terminateConnection(connection, asError(error), false);\n\t\t}\n\t}\n\tbuildUrl(params) {\n\t\tlet url;\n\t\ttry {\n\t\t\tconst baseUrl = typeof globalThis.location === \"undefined\" ? void 0 : globalThis.location.href;\n\t\t\turl = new URL(this.url, baseUrl);\n\t\t\turl = toWebSocketUrl(url);\n\t\t} catch {\n\t\t\tthrow new Error(\"Invalid WebSocket chat URL. Use an absolute URL outside the browser.\");\n\t\t}\n\t\tif (![\"ws:\", \"wss:\"].includes(url.protocol) || url.hostname === \"\") throw new Error(\"Invalid WebSocket chat URL. Expected ws:// or wss://.\");\n\t\tif (url.hash !== \"\") throw new Error(\"Invalid WebSocket chat URL. Fragments are not allowed.\");\n\t\tfor (const [key, value] of Object.entries(params ?? {})) url.searchParams.set(key, value);\n\t\treturn url;\n\t}\n\twaitForConnection(promise, abortSignal) {\n\t\tif (abortSignal == null) return promise;\n\t\tif (abortSignal.aborted) return Promise.reject(createAbortError(abortSignal));\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst onAbort = () => {\n\t\t\t\treject(createAbortError(abortSignal));\n\t\t\t};\n\t\t\tabortSignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tpromise.then((socket) => {\n\t\t\t\tabortSignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(socket);\n\t\t\t}, (error) => {\n\t\t\t\tabortSignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t});\n\t\t});\n\t}\n\tresolveConnection(connection, socket) {\n\t\tif (connection.settled) return;\n\t\tconnection.settled = true;\n\t\tconnection.resolve(socket);\n\t}\n\trejectConnection(connection, error) {\n\t\tif (connection.settled) return;\n\t\tconnection.settled = true;\n\t\tconnection.reject(error);\n\t}\n\tterminateConnection(connection, error, closeSocket = true) {\n\t\tif (this.connection !== connection) return;\n\t\tthis.connection = void 0;\n\t\tthis.rejectConnection(connection, error);\n\t\tthis.failAllRequests(error);\n\t\tif (closeSocket) try {\n\t\t\tconnection.socket?.close(1011, \"WebSocket chat transport error\");\n\t\t} catch {}\n\t}\n\tcreateActiveRequest({ requestId, kind, lastSequence, abortSignal, resolveResponse, rejectResponse }) {\n\t\tlet controller;\n\t\tconst request = {\n\t\t\trequestId,\n\t\t\tkind,\n\t\t\tlastSequence,\n\t\t\tstream: new ReadableStream({\n\t\t\t\tstart(streamController) {\n\t\t\t\t\tcontroller = streamController;\n\t\t\t\t},\n\t\t\t\tcancel: () => {\n\t\t\t\t\tthis.abortRequest(requestId, false);\n\t\t\t\t}\n\t\t\t}),\n\t\t\tcontroller,\n\t\t\tresponseSettled: false,\n\t\t\tresolveResponse,\n\t\t\trejectResponse,\n\t\t\tabortSignal\n\t\t};\n\t\tthis.activeRequests.set(requestId, request);\n\t\tif (abortSignal != null) {\n\t\t\tconst abortListener = () => {\n\t\t\t\tthis.abortRequest(requestId, true);\n\t\t\t};\n\t\t\trequest.abortListener = abortListener;\n\t\t\tabortSignal.addEventListener(\"abort\", abortListener, { once: true });\n\t\t\tif (abortSignal.aborted) abortListener();\n\t\t}\n\t\treturn request;\n\t}\n\tabortRequest(requestId, closeStream) {\n\t\tconst request = this.activeRequests.get(requestId);\n\t\tif (request == null) return;\n\t\tconst error = createAbortError(request.abortSignal);\n\t\tif (request.kind === \"resume\" && !request.responseSettled) {\n\t\t\trequest.responseSettled = true;\n\t\t\trequest.rejectResponse?.(error);\n\t\t}\n\t\tthis.cleanupRequest(request);\n\t\tif (closeStream) try {\n\t\t\trequest.controller.close();\n\t\t} catch {}\n\t\tconst socket = this.connection?.socket;\n\t\tif (socket?.readyState === WEBSOCKET_OPEN_STATE) this.sendFrame(socket, {\n\t\t\ttype: \"abort\",\n\t\t\trequestId\n\t\t}).catch(() => {});\n\t}\n\tcleanupRequest(request) {\n\t\tthis.activeRequests.delete(request.requestId);\n\t\tif (request.abortListener != null) {\n\t\t\trequest.abortSignal?.removeEventListener(\"abort\", request.abortListener);\n\t\t\trequest.abortListener = void 0;\n\t\t}\n\t}\n\tfailRequest(request, error) {\n\t\tif (!this.activeRequests.has(request.requestId)) return;\n\t\tif (request.kind === \"resume\" && !request.responseSettled) {\n\t\t\trequest.responseSettled = true;\n\t\t\trequest.rejectResponse?.(error);\n\t\t}\n\t\tthis.cleanupRequest(request);\n\t\ttry {\n\t\t\trequest.controller.error(error);\n\t\t} catch {}\n\t}\n\tfailAllRequests(error) {\n\t\tfor (const request of [...this.activeRequests.values()]) this.failRequest(request, error);\n\t}\n\tresolveResumeStream(request) {\n\t\tif (request.kind !== \"resume\" || request.responseSettled) return;\n\t\trequest.responseSettled = true;\n\t\trequest.resolveResponse?.(request.stream);\n\t}\n\tasync validateResponseChunk(value) {\n\t\tconst chunk = await safeValidateTypes({\n\t\t\tvalue,\n\t\t\tschema: uiMessageChunkSchema\n\t\t});\n\t\tif (!chunk.success) throw new Error(\"Invalid UI message chunk in WebSocket response.\");\n\t\treturn chunk.value;\n\t}\n\tasync handleResponseFrame(connection, text) {\n\t\tif (this.connection !== connection) return;\n\t\tconst parsed = await safeParseJSON({ text });\n\t\tif (!parsed.success || !isRecord(parsed.value)) throw new Error(\"Invalid WebSocket chat response frame.\");\n\t\tconst type = parsed.value.type;\n\t\tconst requestId = parsed.value.requestId;\n\t\tif (typeof type !== \"string\" || typeof requestId !== \"string\") throw new Error(\"Invalid WebSocket chat response frame.\");\n\t\tconst request = this.activeRequests.get(requestId);\n\t\tif (request == null) return;\n\t\tswitch (type) {\n\t\t\tcase \"start\":\n\t\t\t\tthis.resolveResumeStream(request);\n\t\t\t\treturn;\n\t\t\tcase \"chunk\": {\n\t\t\t\tif (!isSequence(parsed.value.sequence)) throw new Error(\"Invalid WebSocket chat chunk sequence.\");\n\t\t\t\tif (parsed.value.sequence <= request.lastSequence) return;\n\t\t\t\tif (parsed.value.sequence !== request.lastSequence + 1) throw new Error(\"Out-of-order WebSocket chat chunk sequence.\");\n\t\t\t\tconst chunk = await this.validateResponseChunk(parsed.value.chunk);\n\t\t\t\tif (this.activeRequests.get(requestId) !== request) return;\n\t\t\t\tthis.resolveResumeStream(request);\n\t\t\t\ttry {\n\t\t\t\t\trequest.controller.enqueue(chunk);\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\trequest.lastSequence = parsed.value.sequence;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"end\":\n\t\t\t\tthis.resolveResumeStream(request);\n\t\t\t\tthis.cleanupRequest(request);\n\t\t\t\trequest.controller.close();\n\t\t\t\treturn;\n\t\t\tcase \"no-active\":\n\t\t\t\tif (request.kind === \"resume\" && !request.responseSettled) {\n\t\t\t\t\trequest.responseSettled = true;\n\t\t\t\t\trequest.resolveResponse?.(null);\n\t\t\t\t}\n\t\t\t\tthis.cleanupRequest(request);\n\t\t\t\trequest.controller.close();\n\t\t\t\treturn;\n\t\t\tcase \"error\":\n\t\t\t\tif (parsed.value.errorText !== void 0 && typeof parsed.value.errorText !== \"string\") throw new Error(\"Invalid WebSocket chat error response.\");\n\t\t\t\tthis.failRequest(request, new Error(parsed.value.errorText ?? \"WebSocket chat server returned an error.\"));\n\t\t\t\treturn;\n\t\t\tdefault: throw new Error(`Unknown WebSocket chat response type: ${type}.`);\n\t\t}\n\t}\n\tasync sendFrame(socket, frame, abortSignal) {\n\t\tconst send = this.sendQueue.then(async () => {\n\t\t\tawait waitForWebSocketBufferDrain(socket, { abortSignal });\n\t\t\tthis.throwIfAborted(abortSignal);\n\t\t\tif (this.connection?.socket !== socket || socket.readyState !== WEBSOCKET_OPEN_STATE) throw new TypeError(\"WebSocket chat network connection is not open.\");\n\t\t\tsocket.send(JSON.stringify(frame));\n\t\t});\n\t\tthis.sendQueue = send.catch(() => {});\n\t\treturn send;\n\t}\n};\n//#endregion\n//#region src/upload-file/upload-file.ts\n/**\n* Uploads a file using a files API interface.\n*\n* @param api - The Files API interface to use for uploading.\n* @param data - The file data to upload (tagged `{ type: 'data' | 'text' | 'stream' }`).\n* Stream data is sent without buffering by providers that support streaming\n* uploads (others reject with `UnsupportedFunctionalityError`); the provider\n* consumes the stream — any failed upload, including validation failures\n* before a request is made, cancels it. Do not reuse it.\n* @param mediaType - Optional IANA media type. Auto-detected from file bytes\n* when omitted (falls back to `text/plain` for the `text` variant and\n* `application/octet-stream` for the `stream` variant, which cannot be sniffed).\n* @param filename - Optional filename for the uploaded file. Multipart-based\n* providers default it to `\"blob\"` when omitted.\n* @param abortSignal - Optional signal to cancel the upload.\n* @param headers - Optional additional HTTP headers for the request.\n* @param providerOptions - Additional provider-specific options.\n*\n* @returns A result object containing the provider reference, optional\n* metadata, and — when reported by the provider — `byteSize`, `createdAt`,\n* and `expiresAt` (the provider-applied retention expiry).\n*/\nasync function uploadFile({ api, data: dataArg, mediaType: mediaTypeArg, filename, abortSignal, headers, providerOptions }) {\n\tconst data = dataArg instanceof Uint8Array || typeof dataArg === \"string\" ? {\n\t\ttype: \"data\",\n\t\tdata: dataArg\n\t} : dataArg;\n\tconst mediaType = mediaTypeArg ?? (data.type === \"text\" ? \"text/plain\" : data.type === \"stream\" ? \"application/octet-stream\" : detectMediaType({ data: data.data }) ?? (isLikelyText(data.data) ? \"text/plain\" : \"application/octet-stream\"));\n\tlet result;\n\ttry {\n\t\tresult = await (\"uploadFile\" in api ? api : typeof api.files === \"function\" ? api.files() : (() => {\n\t\t\tthrow new Error(\"The provider does not support file uploads. Make sure it exposes a files() method.\");\n\t\t})()).uploadFile({\n\t\t\tdata,\n\t\t\tmediaType,\n\t\t\tfilename,\n\t\t\tabortSignal,\n\t\t\theaders,\n\t\t\tproviderOptions\n\t\t});\n\t} catch (error) {\n\t\tif (data.type === \"stream\") await data.stream.cancel(error).catch(() => {});\n\t\tthrow error;\n\t}\n\treturn new DefaultUploadFileResult({\n\t\tproviderReference: result.providerReference,\n\t\tmediaType: result.mediaType,\n\t\tfilename: result.filename,\n\t\tbyteSize: result.byteSize,\n\t\tcreatedAt: result.createdAt,\n\t\texpiresAt: result.expiresAt,\n\t\tproviderMetadata: result.providerMetadata,\n\t\twarnings: result.warnings\n\t});\n}\nvar DefaultUploadFileResult = class {\n\tconstructor(options) {\n\t\tthis.providerReference = options.providerReference;\n\t\tthis.mediaType = options.mediaType;\n\t\tthis.filename = options.filename;\n\t\tthis.byteSize = options.byteSize;\n\t\tthis.createdAt = options.createdAt;\n\t\tthis.expiresAt = options.expiresAt;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.warnings = options.warnings;\n\t}\n};\nfunction isLikelyText(data) {\n\tconst CHECK_LENGTH = 512;\n\tconst BASE64_CHECK_LENGTH = Math.ceil(172) * 4;\n\tconst bytes = typeof data === \"string\" ? convertBase64ToUint8Array(data.substring(0, Math.min(data.length, BASE64_CHECK_LENGTH))) : data;\n\tconst checkLength = Math.min(bytes.length, CHECK_LENGTH);\n\tif (checkLength === 0) return false;\n\tfor (let i = 0; i < checkLength; i++) {\n\t\tconst byte = bytes[i];\n\t\tif (byte === 0 || byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) return false;\n\t}\n\treturn true;\n}\n//#endregion\n//#region src/upload-skill/upload-skill.ts\nasync function uploadSkill({ api, files, displayTitle, providerOptions }) {\n\tconst skillsApi = \"uploadSkill\" in api ? api : typeof api.skills === \"function\" ? api.skills() : (() => {\n\t\tthrow new Error(\"The provider does not support skills. Make sure it exposes a skills() method.\");\n\t})();\n\tconst normalizedFiles = files.map((file) => ({\n\t\t...file,\n\t\tdata: file.data instanceof Uint8Array || typeof file.data === \"string\" ? {\n\t\t\ttype: \"data\",\n\t\t\tdata: file.data\n\t\t} : file.data\n\t}));\n\treturn await skillsApi.uploadSkill({\n\t\tfiles: normalizedFiles,\n\t\tdisplayTitle,\n\t\tproviderOptions\n\t});\n}\n//#endregion\nexport { AISDKError, AI_SDK_TELEMETRY_TRACING_CHANNEL, APICallError, AbstractChat, DefaultChatTransport, DefaultGeneratedFile, DirectChatTransport, DownloadError, EmptyResponseBodyError, AbstractRealtimeSession as Experimental_AbstractRealtimeSession, ToolLoopAgent as Experimental_Agent, ToolLoopAgent, Experimental_DecisionRefusalError, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_EvaluationUnsupportedQuestionTypeError, HttpChatTransport, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidPromptError, InvalidResponseDataError, InvalidStreamPartError, InvalidToolApprovalError, InvalidToolApprovalSignatureError, InvalidToolInputError, JSONParseError, JsonToSseTransformStream, LoadAPIKeyError, LoadSettingError, MessageConversionError, MissingToolResultsError, NoContentGeneratedError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoSpeechGeneratedError, NoSuchModelError, NoSuchProviderError, NoSuchProviderReferenceError, NoSuchToolError, NoTranscriptGeneratedError, NoTranslationGeneratedError, NoVideoGeneratedError, output_exports as Output, RetryError, SerialJobExecutor, StreamProviderError, TextStreamChatTransport, TooManyEmbeddingValuesForCallError, ToolCallNotFoundForApprovalError, ToolCallRepairError, ToolChoiceViolationError, TypeValidationError, UIMessageStreamError, UI_MESSAGE_STREAM_HEADERS, UnsupportedFunctionalityError, UnsupportedModelVersionError, WebSocketChatTransport, addToolInputExamplesMiddleware, asSchema, assistantModelMessageSchema, callCompletionApi, consumeStream, convertDataContentToBase64String, convertFileListToFileUIParts, convertToModelMessages, cosineSimilarity, createAgentUIStream, createAgentUIStreamResponse, createDownload, createGateway, createIdGenerator, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultEmbeddingSettingsMiddleware, defaultInstructionsMiddleware, defaultSettingsMiddleware, detectToolDrift, dynamicTool, embed, embedMany, cancelBatch as experimental_cancelBatch, experimental_createProviderRegistry, decide as experimental_decide, decodeRealtimeAudio as experimental_decodeRealtimeAudio, encodeRealtimeAudio as experimental_encodeRealtimeAudio, experimental_evaluate, filterActiveTools as experimental_filterActiveTools, experimental_generateSpeech, experimental_generateVideo, getBatchResults as experimental_getBatchResults, getBatchStatus as experimental_getBatchStatus, getRealtimeToolDefinitions as experimental_getRealtimeToolDefinitions, experimental_getVideoStatus, listBatches as experimental_listBatches, resampleAudio as experimental_resampleAudio, startBatch as experimental_startBatch, experimental_startVideo, streamLanguageModelCall as experimental_streamLanguageModelCall, streamTranscribe as experimental_streamTranscribe, streamTranslate as experimental_streamTranslate, experimental_toolCaller, experimental_transcribe, extractJsonMiddleware, extractReasoningMiddleware, fingerprintTools, gateway, generateId, generateImage, generateObject, generateSpeech, generateText, getChunkTimeoutMs, getFirstChunkTimeoutMs, getStaticToolName, getStepTimeoutMs, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, getToolTimeoutMs, getTotalTimeoutMs, hasToolCall, isCustomContentUIPart, isDataUIPart, isDeepEqualData, isDynamicToolUIPart, isFileUIPart, isLoopFinished, isReasoningFileUIPart, isReasoningUIPart, isStaticToolUIPart, isStepCount, isStepCount as stepCountIs, isTextUIPart, isToolOutputErrorUIPart, isToolUIPart, jsonSchema, lastAssistantMessageIsCompleteWithApprovalResponses, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parseJsonEventStream, parsePartialJson, pipeAgentUIStreamToResponse, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, registerTelemetry, rerank, safeValidateUIMessages, safeValidateWebSocketChatTransportRequest, simulateReadableStream, simulateStreamingMiddleware, smoothStream, streamObject, streamText, systemModelMessageSchema, toTextStream, toUIMessageChunk, toUIMessageStream, tool, toolModelMessageSchema, toolSearch, transcribe, uiMessageChunkSchema, uploadFile, uploadSkill, userModelMessageSchema, validateUIMessages, wrapEmbeddingModel, wrapImageModel, wrapLanguageModel, wrapProvider, zodSchema };\n\n//# sourceMappingURL=index.js.map","// From https://github.com/vercel/swr/blob/master/src/libs/hash.ts\n// use WeakMap to store the object->key mapping\n// so the objects can be garbage collected.\n// WeakMap uses a hashtable under the hood, so the lookup\n// complexity is almost O(1).\nvar table = new WeakMap();\n// counter of the key\nvar counter = 0;\n// hashes an array of objects and returns a string\nexport default function hash(args) {\n if (!args.length)\n return '';\n var key = 'arg';\n for (var i = 0; i < args.length; ++i) {\n var _hash = void 0;\n if (args[i] === null ||\n (typeof args[i] !== 'object' && typeof args[i] !== 'function')) {\n // need to consider the case that args[i] is a string:\n // args[i] _hash\n // \"undefined\" -> '\"undefined\"'\n // undefined -> 'undefined'\n // 123 -> '123'\n // null -> 'null'\n // \"null\" -> '\"null\"'\n if (typeof args[i] === 'string') {\n _hash = '\"' + args[i] + '\"';\n }\n else {\n _hash = String(args[i]);\n }\n }\n else {\n if (!table.has(args[i])) {\n _hash = counter;\n table.set(args[i], counter++);\n }\n else {\n _hash = table.get(args[i]);\n }\n }\n key += '@' + _hash;\n }\n return key;\n}\n//# sourceMappingURL=hash.js.map","import hash from '../lib/hash';\nfunction serializeKeyDefault(key) {\n if (typeof key === 'function') {\n try {\n key = key();\n }\n catch (err) {\n // dependencies not ready\n key = '';\n }\n }\n if (Array.isArray(key)) {\n key = hash(key);\n }\n else {\n // convert null to ''\n key = String(key || '');\n }\n return key;\n}\nvar SWRVCache = /** @class */ (function () {\n function SWRVCache(ttl) {\n if (ttl === void 0) { ttl = 0; }\n this.items = new Map();\n this.ttl = ttl;\n }\n SWRVCache.prototype.serializeKey = function (key) {\n return serializeKeyDefault(key);\n };\n SWRVCache.prototype.get = function (k) {\n var _key = this.serializeKey(k);\n return this.items.get(_key);\n };\n SWRVCache.prototype.set = function (k, v, ttl) {\n var _key = this.serializeKey(k);\n var timeToLive = ttl || this.ttl;\n var now = Date.now();\n var item = {\n data: v,\n createdAt: now,\n expiresAt: timeToLive ? now + timeToLive : Infinity\n };\n this.dispatchExpire(timeToLive, item, _key);\n this.items.set(_key, item);\n };\n SWRVCache.prototype.dispatchExpire = function (ttl, item, serializedKey) {\n var _this = this;\n ttl && setTimeout(function () {\n var current = Date.now();\n var hasExpired = current >= item.expiresAt;\n if (hasExpired)\n _this.delete(serializedKey);\n }, ttl);\n };\n SWRVCache.prototype.delete = function (serializedKey) {\n this.items.delete(serializedKey);\n };\n return SWRVCache;\n}());\nexport default SWRVCache;\n//# sourceMappingURL=index.js.map","function isOnline() {\n if (typeof navigator.onLine !== 'undefined') {\n return navigator.onLine;\n }\n // always assume it's online\n return true;\n}\nfunction isDocumentVisible() {\n if (typeof document !== 'undefined' &&\n typeof document.visibilityState !== 'undefined') {\n return document.visibilityState !== 'hidden';\n }\n // always assume it's visible\n return true;\n}\nvar fetcher = function (url) { return fetch(url).then(function (res) { return res.json(); }); };\nexport default {\n isOnline: isOnline,\n isDocumentVisible: isDocumentVisible,\n fetcher: fetcher\n};\n//# sourceMappingURL=web-preset.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\n/** ____\n *--------------/ \\.------------------/\n * / swrv \\. / //\n * / / /\\. / //\n * / _____/ / \\. /\n * / / ____/ . \\. /\n * / \\ \\_____ \\. /\n * / . \\_____ \\ \\ / //\n * \\ _____/ / ./ / //\n * \\ / _____/ ./ /\n * \\ / / . ./ /\n * \\ / / ./ /\n * . \\/ ./ / //\n * \\ ./ / //\n * \\.. / /\n * . ||| /\n * ||| /\n * . ||| / //\n * ||| / //\n * ||| /\n */\nimport { reactive, watch, ref, toRefs, \n// isRef,\ngetCurrentScope, onScopeDispose, isReadonly } from 'vue';\nimport webPreset from './lib/web-preset';\nimport SWRVCache from './cache';\nvar DATA_CACHE = new SWRVCache();\nvar REF_CACHE = new SWRVCache();\nvar PROMISES_CACHE = new SWRVCache();\nvar defaultConfig = {\n cache: DATA_CACHE,\n refreshInterval: 0,\n ttl: 0,\n serverTTL: 1000,\n dedupingInterval: 2000,\n revalidateOnFocus: true,\n revalidateDebounce: 0,\n shouldRetryOnError: true,\n errorRetryInterval: 5000,\n errorRetryCount: 5,\n fetcher: webPreset.fetcher,\n isOnline: webPreset.isOnline,\n isDocumentVisible: webPreset.isDocumentVisible\n};\n/**\n * Cache the refs for later revalidation\n */\nfunction setRefCache(key, theRef, ttl) {\n var refCacheItem = REF_CACHE.get(key);\n if (refCacheItem) {\n refCacheItem.data.push(theRef);\n }\n else {\n // #51 ensures ref cache does not evict too soon\n var gracePeriod = 5000;\n REF_CACHE.set(key, [theRef], ttl > 0 ? ttl + gracePeriod : ttl);\n }\n}\nfunction onErrorRetry(revalidate, errorRetryCount, config) {\n if (!config.isDocumentVisible()) {\n return;\n }\n if (config.errorRetryCount !== undefined && errorRetryCount > config.errorRetryCount) {\n return;\n }\n var count = Math.min(errorRetryCount || 0, config.errorRetryCount);\n var timeout = count * config.errorRetryInterval;\n setTimeout(function () {\n revalidate(null, { errorRetryCount: count + 1, shouldRetryOnError: true });\n }, timeout);\n}\n/**\n * Evaluate shouldRetryOnError option\n */\nfunction resolveRetryFlag(_a) {\n var _b = _a.shouldRetry, shouldRetry = _b === void 0 ? undefined : _b, error = _a.error;\n if (typeof shouldRetry === 'function') {\n return shouldRetry(error);\n }\n if (typeof shouldRetry === 'boolean') {\n return shouldRetry;\n }\n return defaultConfig.shouldRetryOnError;\n}\n/**\n * Main mutation function for receiving data from promises to change state and\n * set data cache\n */\nvar mutate = function (key, res, cache, ttl) {\n if (cache === void 0) { cache = DATA_CACHE; }\n if (ttl === void 0) { ttl = defaultConfig.ttl; }\n return __awaiter(void 0, void 0, void 0, function () {\n var data, error, isValidating, err_1, newData, stateRef, refs_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!isPromise(res)) return [3 /*break*/, 5];\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4 /*yield*/, res];\n case 2:\n data = _a.sent();\n return [3 /*break*/, 4];\n case 3:\n err_1 = _a.sent();\n error = err_1;\n return [3 /*break*/, 4];\n case 4: return [3 /*break*/, 6];\n case 5:\n data = res;\n _a.label = 6;\n case 6:\n // eslint-disable-next-line prefer-const\n isValidating = false;\n newData = { data: data, error: error, isValidating: isValidating };\n if (typeof data !== 'undefined') {\n try {\n cache.set(key, newData, ttl);\n }\n catch (err) {\n console.error('swrv(mutate): failed to set cache', err);\n }\n }\n stateRef = REF_CACHE.get(key);\n if (stateRef && stateRef.data.length) {\n refs_1 = stateRef.data.filter(function (r) { return r.key === key; });\n refs_1.forEach(function (r, idx) {\n if (typeof newData.data !== 'undefined') {\n r.data = newData.data;\n }\n r.error = newData.error;\n r.isValidating = newData.isValidating;\n r.isLoading = newData.isValidating;\n var isLast = idx === refs_1.length - 1;\n if (!isLast) {\n // Clean up refs that belonged to old keys\n delete refs_1[idx];\n }\n });\n refs_1 = refs_1.filter(Boolean);\n }\n return [2 /*return*/, newData];\n }\n });\n });\n};\nfunction useSWRV() {\n var _this = this;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var key;\n var fn;\n var config = __assign({}, defaultConfig);\n var unmounted = false;\n var isHydrated = false;\n if (!getCurrentScope()) {\n console.error('useSWRV must be called inside setup() or an active effectScope().');\n return null;\n }\n var IS_SERVER = typeof window === 'undefined' || typeof document === 'undefined';\n // #region ssr\n /**\n const isSsrHydration = Boolean(\n \\!IS_SERVER &&\n vm.$vnode &&\n vm.$vnode.elm &&\n vm.$vnode.elm.dataset &&\n vm.$vnode.elm.dataset.swrvKey)\n */\n // #endregion\n if (args.length >= 1) {\n key = args[0];\n }\n if (args.length >= 2) {\n fn = args[1];\n }\n if (args.length > 2) {\n config = __assign(__assign({}, config), args[2]);\n }\n var ttl = IS_SERVER ? config.serverTTL : config.ttl;\n var keyRef = typeof key === 'function' ? key : ref(key);\n if (typeof fn === 'undefined') {\n // use the global fetcher\n fn = config.fetcher;\n }\n var stateRef = null;\n // #region ssr\n // if (isSsrHydration) {\n // // component was ssrHydrated, so make the ssr reactive as the initial data\n // const swrvState = (window as any).__SWRV_STATE__ ||\n // ((window as any).__NUXT__ && (window as any).__NUXT__.swrv) || []\n // const swrvKey = +(vm as any).$vnode.elm.dataset.swrvKey\n // if (swrvKey !== undefined && swrvKey !== null) {\n // const nodeState = swrvState[swrvKey] || []\n // const instanceState = nodeState[isRef(keyRef) ? keyRef.value : keyRef()]\n // if (instanceState) {\n // stateRef = reactive(instanceState)\n // isHydrated = true\n // }\n // }\n // }\n // #endregion\n if (!stateRef) {\n stateRef = reactive({\n data: undefined,\n error: undefined,\n isValidating: true,\n isLoading: true,\n key: null\n });\n }\n /**\n * Revalidate the cache, mutate data\n */\n var revalidate = function (data, opts) { return __awaiter(_this, void 0, void 0, function () {\n var isFirstFetch, keyVal, cacheItem, newData, fetcher, shouldRevalidate, trigger;\n var _this = this;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n isFirstFetch = stateRef.data === undefined;\n keyVal = keyRef.value;\n if (!keyVal) {\n return [2 /*return*/];\n }\n cacheItem = config.cache.get(keyVal);\n newData = cacheItem && cacheItem.data;\n stateRef.isValidating = true;\n stateRef.isLoading = !newData;\n if (newData) {\n stateRef.data = newData.data;\n stateRef.error = newData.error;\n }\n fetcher = data || fn;\n if (!fetcher ||\n (!config.isDocumentVisible() && !isFirstFetch) ||\n ((opts === null || opts === void 0 ? void 0 : opts.forceRevalidate) !== undefined && !(opts === null || opts === void 0 ? void 0 : opts.forceRevalidate))) {\n stateRef.isValidating = false;\n stateRef.isLoading = false;\n return [2 /*return*/];\n }\n // Dedupe items that were created in the last interval #76\n if (cacheItem) {\n shouldRevalidate = Boolean(((Date.now() - cacheItem.createdAt) >= config.dedupingInterval) || (opts === null || opts === void 0 ? void 0 : opts.forceRevalidate));\n if (!shouldRevalidate) {\n stateRef.isValidating = false;\n stateRef.isLoading = false;\n return [2 /*return*/];\n }\n }\n trigger = function () { return __awaiter(_this, void 0, void 0, function () {\n var promiseFromCache, fetcherArgs, newPromise, configAllows, optsAllows, shouldRetryOnError;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n promiseFromCache = PROMISES_CACHE.get(keyVal);\n if (!!promiseFromCache) return [3 /*break*/, 2];\n fetcherArgs = Array.isArray(keyVal) ? keyVal : [keyVal];\n newPromise = fetcher.apply(void 0, __spreadArray([], __read(fetcherArgs), false));\n PROMISES_CACHE.set(keyVal, newPromise, config.dedupingInterval);\n return [4 /*yield*/, mutate(keyVal, newPromise, config.cache, ttl)];\n case 1:\n _a.sent();\n return [3 /*break*/, 4];\n case 2: return [4 /*yield*/, mutate(keyVal, promiseFromCache.data, config.cache, ttl)];\n case 3:\n _a.sent();\n _a.label = 4;\n case 4:\n stateRef.isValidating = false;\n stateRef.isLoading = false;\n PROMISES_CACHE.delete(keyVal);\n if (stateRef.error !== undefined) {\n configAllows = resolveRetryFlag({ shouldRetry: config.shouldRetryOnError, error: stateRef.error });\n optsAllows = resolveRetryFlag({\n shouldRetry: opts ? opts.shouldRetryOnError : true,\n error: stateRef.error\n });\n shouldRetryOnError = !unmounted && configAllows && optsAllows;\n if (shouldRetryOnError) {\n onErrorRetry(revalidate, opts ? opts.errorRetryCount : 1, config);\n }\n }\n return [2 /*return*/];\n }\n });\n }); };\n if (!(newData && config.revalidateDebounce)) return [3 /*break*/, 1];\n setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!!unmounted) return [3 /*break*/, 2];\n return [4 /*yield*/, trigger()];\n case 1:\n _a.sent();\n _a.label = 2;\n case 2: return [2 /*return*/];\n }\n });\n }); }, config.revalidateDebounce);\n return [3 /*break*/, 3];\n case 1: return [4 /*yield*/, trigger()];\n case 2:\n _a.sent();\n _a.label = 3;\n case 3: return [2 /*return*/];\n }\n });\n }); };\n var revalidateCall = function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {\n return [2 /*return*/, revalidate(null, { shouldRetryOnError: false })];\n }); }); };\n var timer = null;\n if (!IS_SERVER) {\n var tick_1 = function () { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!(!stateRef.error && config.isOnline())) return [3 /*break*/, 2];\n // if API request errored, we stop polling in this round\n // and let the error retry function handle it\n return [4 /*yield*/, revalidate()];\n case 1:\n // if API request errored, we stop polling in this round\n // and let the error retry function handle it\n _a.sent();\n return [3 /*break*/, 3];\n case 2:\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n _a.label = 3;\n case 3:\n if (config.refreshInterval && !unmounted) {\n timer = setTimeout(tick_1, config.refreshInterval);\n }\n return [2 /*return*/];\n }\n });\n }); };\n if (config.refreshInterval) {\n timer = setTimeout(tick_1, config.refreshInterval);\n }\n if (config.revalidateOnFocus) {\n document.addEventListener('visibilitychange', revalidateCall, false);\n window.addEventListener('focus', revalidateCall, false);\n }\n }\n onScopeDispose(function () {\n unmounted = true;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (!IS_SERVER && config.revalidateOnFocus) {\n document.removeEventListener('visibilitychange', revalidateCall, false);\n window.removeEventListener('focus', revalidateCall, false);\n }\n var refCacheItem = REF_CACHE.get(keyRef.value);\n if (refCacheItem) {\n refCacheItem.data = refCacheItem.data.filter(function (ref) { return ref !== stateRef; });\n }\n });\n // #region ssr\n // if (IS_SERVER) {\n // // make sure srwv exists in ssrContext\n // let swrvRes = []\n // if (vm.$ssrContext) {\n // swrvRes = vm.$ssrContext.swrv = vm.$ssrContext.swrv || swrvRes\n // }\n // const ssrKey = swrvRes.length\n // if (!vm.$vnode || (vm.$node && !vm.$node.data)) {\n // vm.$vnode = {\n // data: { attrs: { 'data-swrv-key': ssrKey } }\n // }\n // }\n // const attrs = (vm.$vnode.data.attrs = vm.$vnode.data.attrs || {})\n // attrs['data-swrv-key'] = ssrKey\n // // Nuxt compatibility\n // if (vm.$ssrContext && vm.$ssrContext.nuxt) {\n // vm.$ssrContext.nuxt.swrv = swrvRes\n // }\n // onServerPrefetch(async () => {\n // await revalidate()\n // if (!swrvRes[ssrKey]) swrvRes[ssrKey] = {}\n // swrvRes[ssrKey][keyRef.value] = {\n // data: stateRef.data,\n // error: stateRef.error,\n // isValidating: stateRef.isValidating\n // }\n // })\n // }\n // #endregion\n /**\n * Revalidate when key dependencies change\n */\n try {\n watch(keyRef, function (val) {\n if (!isReadonly(keyRef)) {\n keyRef.value = val;\n }\n stateRef.key = val;\n stateRef.isValidating = Boolean(val);\n setRefCache(keyRef.value, stateRef, ttl);\n if (!IS_SERVER && !isHydrated && keyRef.value) {\n revalidate();\n }\n isHydrated = false;\n }, {\n immediate: true\n });\n }\n catch (_a) {\n // do nothing\n }\n var res = __assign(__assign({}, toRefs(stateRef)), { mutate: function (data, opts) { return revalidate(data, __assign(__assign({}, opts), { forceRevalidate: true })); } });\n return res;\n}\nfunction isPromise(p) {\n return p !== null && typeof p === 'object' && typeof p.then === 'function';\n}\nexport { mutate };\nexport default useSWRV;\n//# sourceMappingURL=use-swrv.js.map","import SWRVCache from './cache';\nimport useSWRV, { mutate } from './use-swrv';\nexport { mutate, SWRVCache };\nexport default useSWRV;\n//# sourceMappingURL=index.js.map","import { isAbortError, safeValidateTypes } from \"@ai-sdk/provider-utils\";\nimport { AbstractChat, asSchema, callCompletionApi, isDeepEqualData, parsePartialJson } from \"ai\";\nimport swrv from \"swrv\";\nimport { computed, getCurrentScope, onScopeDispose, ref, shallowRef, toValue, unref, watch } from \"vue\";\n//#region src/use-object.ts\nconst getOriginalFetch = () => fetch;\nlet uniqueId$1 = 0;\nconst useSWRV$1 = swrv.default || swrv;\nconst store$1 = {};\nfunction useObject({ api, id, schema, initialValue, fetch, onError, onFinish, headers, credentials }) {\n\tconst completionId = id || `completion-${uniqueId$1++}`;\n\tconst key = `${api}|${completionId}`;\n\tconst { data, mutate: originalMutate } = useSWRV$1(key, () => key in store$1 ? store$1[key] : initialValue);\n\tconst { data: isLoading, mutate: mutateLoading } = useSWRV$1(`${completionId}-loading`, null);\n\tisLoading.value ??= false;\n\tdata.value ||= initialValue;\n\tconst mutateObject = (value) => {\n\t\tstore$1[key] = value;\n\t\treturn originalMutate();\n\t};\n\tconst error = ref(void 0);\n\tlet abortController = null;\n\tconst stop = async () => {\n\t\tif (abortController) try {\n\t\t\tabortController.abort();\n\t\t} catch {} finally {\n\t\t\tabortController = null;\n\t\t}\n\t\tawait mutateLoading(() => false);\n\t};\n\tconst clearObject = async () => {\n\t\terror.value = void 0;\n\t\tawait mutateLoading(() => false);\n\t\tawait mutateObject(void 0);\n\t\tdata.value = void 0;\n\t};\n\tconst clear = async () => {\n\t\tawait stop();\n\t\tawait clearObject();\n\t};\n\tconst submit = async (input) => {\n\t\ttry {\n\t\t\tawait clearObject();\n\t\t\tawait mutateLoading(() => true);\n\t\t\tabortController = new AbortController();\n\t\t\tconst response = await (fetch ?? getOriginalFetch())(api, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...headers\n\t\t\t\t},\n\t\t\t\tcredentials: credentials ?? \"same-origin\",\n\t\t\t\tsignal: abortController.signal,\n\t\t\t\tbody: JSON.stringify(input)\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(await response.text() || \"Failed to fetch the response.\");\n\t\t\tif (!response.body) throw new Error(\"The response body is empty.\");\n\t\t\tlet accumulatedText = \"\";\n\t\t\tlet latestObject = void 0;\n\t\t\tawait response.body.pipeThrough(new TextDecoderStream()).pipeTo(new WritableStream({\n\t\t\t\tasync write(chunk) {\n\t\t\t\t\taccumulatedText += chunk;\n\t\t\t\t\tconst { value } = await parsePartialJson(accumulatedText);\n\t\t\t\t\tconst currentObject = value;\n\t\t\t\t\tif (!isDeepEqualData(latestObject, currentObject)) {\n\t\t\t\t\t\tlatestObject = currentObject;\n\t\t\t\t\t\tawait mutateObject(currentObject);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tasync close() {\n\t\t\t\t\tawait mutateLoading(() => false);\n\t\t\t\t\tabortController = null;\n\t\t\t\t\tif (onFinish) {\n\t\t\t\t\t\tconst validationResult = await safeValidateTypes({\n\t\t\t\t\t\t\tvalue: latestObject,\n\t\t\t\t\t\t\tschema: asSchema(schema)\n\t\t\t\t\t\t});\n\t\t\t\t\t\tonFinish(validationResult.success ? {\n\t\t\t\t\t\t\tobject: validationResult.value,\n\t\t\t\t\t\t\terror: void 0\n\t\t\t\t\t\t} : {\n\t\t\t\t\t\t\tobject: void 0,\n\t\t\t\t\t\t\terror: validationResult.error\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}));\n\t\t} catch (err) {\n\t\t\tif (isAbortError(err)) return;\n\t\t\tif (onError && err instanceof Error) onError(err);\n\t\t\tawait mutateLoading(() => false);\n\t\t\terror.value = err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t};\n\treturn {\n\t\tsubmit,\n\t\tobject: data,\n\t\terror,\n\t\tisLoading,\n\t\tstop,\n\t\tclear\n\t};\n}\n//#endregion\n//#region src/use-completion.ts\nlet uniqueId = 0;\nconst useSWRV = swrv.default || swrv;\nconst store = {};\nfunction useCompletion({ api = \"/api/completion\", id, initialCompletion = \"\", initialInput = \"\", credentials, headers, body, streamProtocol, onFinish, onError, fetch } = {}) {\n\tconst completionId = id || `completion-${uniqueId++}`;\n\tconst key = `${api}|${completionId}`;\n\tconst { data, mutate: originalMutate } = useSWRV(key, () => store[key] ?? initialCompletion);\n\tconst { data: isLoading, mutate: mutateLoading } = useSWRV(`${completionId}-loading`, null);\n\tisLoading.value ??= false;\n\tdata.value ??= initialCompletion;\n\tconst mutate = (data) => {\n\t\tstore[key] = data;\n\t\treturn originalMutate();\n\t};\n\tconst completion = data;\n\tconst error = ref(void 0);\n\tlet abortController = null;\n\tasync function triggerRequest(prompt, options) {\n\t\treturn callCompletionApi({\n\t\t\tapi,\n\t\t\tprompt,\n\t\t\tcredentials,\n\t\t\theaders: {\n\t\t\t\t...headers,\n\t\t\t\t...options?.headers\n\t\t\t},\n\t\t\tbody: {\n\t\t\t\t...unref(body),\n\t\t\t\t...options?.body\n\t\t\t},\n\t\t\tstreamProtocol,\n\t\t\tsetCompletion: mutate,\n\t\t\tsetLoading: (loading) => mutateLoading(() => loading),\n\t\t\tsetError: (err) => {\n\t\t\t\terror.value = err;\n\t\t\t},\n\t\t\tsetAbortController: (controller) => {\n\t\t\t\tabortController = controller;\n\t\t\t},\n\t\t\tgetAbortController: () => abortController,\n\t\t\tonFinish,\n\t\t\tonError,\n\t\t\tfetch\n\t\t});\n\t}\n\tconst complete = async (prompt, options) => {\n\t\treturn triggerRequest(prompt, options);\n\t};\n\tconst stop = () => {\n\t\tif (abortController) abortController.abort();\n\t};\n\tconst setCompletion = (completion) => {\n\t\tmutate(completion);\n\t};\n\tconst input = ref(initialInput);\n\tconst handleSubmit = (event) => {\n\t\tevent?.preventDefault?.();\n\t\tconst inputValue = input.value;\n\t\treturn inputValue ? complete(inputValue) : void 0;\n\t};\n\treturn {\n\t\tcompletion,\n\t\tcomplete,\n\t\terror,\n\t\tstop,\n\t\tsetCompletion,\n\t\tinput,\n\t\thandleSubmit,\n\t\tisLoading\n\t};\n}\n//#endregion\n//#region src/chat.vue.ts\nvar VueChatState$1 = class {\n\tconstructor(messages) {\n\t\tthis.statusRef = ref(\"ready\");\n\t\tthis.errorRef = ref(void 0);\n\t\tthis.pushMessage = (message) => {\n\t\t\tthis.messagesRef.value = [...this.messagesRef.value, message];\n\t\t};\n\t\tthis.popMessage = () => {\n\t\t\tthis.messagesRef.value = this.messagesRef.value.slice(0, -1);\n\t\t};\n\t\tthis.replaceMessage = (index, message) => {\n\t\t\tthis.messagesRef.value[index] = { ...message };\n\t\t};\n\t\tthis.snapshot = (value) => value;\n\t\tthis.messagesRef = ref(messages ?? []);\n\t}\n\tget messages() {\n\t\treturn this.messagesRef.value;\n\t}\n\tset messages(messages) {\n\t\tthis.messagesRef.value = messages;\n\t}\n\tget status() {\n\t\treturn this.statusRef.value;\n\t}\n\tset status(status) {\n\t\tthis.statusRef.value = status;\n\t}\n\tget error() {\n\t\treturn this.errorRef.value;\n\t}\n\tset error(error) {\n\t\tthis.errorRef.value = error;\n\t}\n};\n/**\n* @deprecated Use the {@link useChat} composable instead. It exposes reactive\n* refs and automatically recreates the chat when its init object changes.\n*/\nvar Chat = class extends AbstractChat {\n\tconstructor({ messages, ...init }) {\n\t\tsuper({\n\t\t\t...init,\n\t\t\tstate: new VueChatState$1(messages)\n\t\t});\n\t}\n};\n//#endregion\n//#region src/use-chat.ts\nfunction cloneMetadata(metadata) {\n\tif (Array.isArray(metadata)) return [...metadata];\n\tif (metadata != null && typeof metadata === \"object\" && (Object.getPrototypeOf(metadata) === Object.prototype || Object.getPrototypeOf(metadata) === null)) return { ...metadata };\n\treturn metadata;\n}\nfunction snapshotValue(value) {\n\tif (value == null || typeof value !== \"object\" || !(\"parts\" in value) || !Array.isArray(value.parts)) return value;\n\tconst message = value;\n\tconst snapshot = {\n\t\t...message,\n\t\tparts: message.parts.map((part) => ({ ...part }))\n\t};\n\tif (\"metadata\" in message) snapshot.metadata = cloneMetadata(message.metadata);\n\treturn snapshot;\n}\nvar VueChatState = class {\n\tconstructor({ initialMessages, messagesRef, statusRef, errorRef, throttleWaitMs }) {\n\t\tthis.publishedMessages = [];\n\t\tthis.publishedMessageSources = [];\n\t\tthis.dirtyMessageIndices = /* @__PURE__ */ new Set();\n\t\tthis.statusValue = \"ready\";\n\t\tthis.hasPendingPublication = false;\n\t\tthis.isActive = true;\n\t\tthis.isPublishing = false;\n\t\tthis.pushMessage = (message) => {\n\t\t\tthis.messagesValue.push(message);\n\t\t\tthis.dirtyMessageIndices.add(this.messagesValue.length - 1);\n\t\t\tthis.schedulePublication();\n\t\t};\n\t\tthis.popMessage = () => {\n\t\t\tthis.messagesValue.pop();\n\t\t\tthis.schedulePublication();\n\t\t};\n\t\tthis.replaceMessage = (index, message) => {\n\t\t\tthis.messagesValue[index] = message;\n\t\t\tthis.dirtyMessageIndices.add(index);\n\t\t\tthis.schedulePublication();\n\t\t};\n\t\tthis.snapshot = snapshotValue;\n\t\tthis.handleIntervalEnd = () => {\n\t\t\tthis.timeout = void 0;\n\t\t\tif (!this.isActive || !this.hasPendingPublication) return;\n\t\t\tthis.hasPendingPublication = false;\n\t\t\tthis.publishMessages();\n\t\t\tthis.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);\n\t\t};\n\t\tthis.messagesValue = initialMessages;\n\t\tthis.messagesRef = messagesRef;\n\t\tthis.statusRef = statusRef;\n\t\tthis.errorRef = errorRef;\n\t\tthis.throttleWaitMs = throttleWaitMs != null && Number.isFinite(throttleWaitMs) && throttleWaitMs > 0 ? throttleWaitMs : void 0;\n\t}\n\tget messages() {\n\t\treturn this.messagesValue;\n\t}\n\tset messages(messages) {\n\t\tconst previousMessages = this.messagesValue;\n\t\tthis.messagesValue = messages;\n\t\tfor (let index = 0; index < messages.length; index++) if (messages[index] !== previousMessages[index]) this.dirtyMessageIndices.add(index);\n\t\tthis.schedulePublication();\n\t}\n\tget status() {\n\t\treturn this.statusValue;\n\t}\n\tset status(status) {\n\t\tthis.statusValue = status;\n\t\tif (!this.isActive) return;\n\t\tif (status === \"ready\" || status === \"error\") this.flushPublication();\n\t\tthis.statusRef.value = status;\n\t}\n\tget error() {\n\t\treturn this.errorValue;\n\t}\n\tset error(error) {\n\t\tthis.errorValue = error;\n\t\tif (this.isActive) this.errorRef.value = error;\n\t}\n\tpublishInitialState() {\n\t\tthis.publishMessages();\n\t\tthis.statusRef.value = this.statusValue;\n\t\tthis.errorRef.value = this.errorValue;\n\t}\n\tsetMessagesFromConsumer(messages) {\n\t\tthis.messagesValue = messages;\n\t\tthis.publishedMessages = messages;\n\t\tthis.publishedMessageSources = messages;\n\t\tthis.dirtyMessageIndices.clear();\n\t}\n\tdispose() {\n\t\tthis.isActive = false;\n\t\tthis.hasPendingPublication = false;\n\t\tthis.dirtyMessageIndices.clear();\n\t\tthis.publishedMessages = [];\n\t\tthis.publishedMessageSources = [];\n\t\tif (this.timeout != null) {\n\t\t\tclearTimeout(this.timeout);\n\t\t\tthis.timeout = void 0;\n\t\t}\n\t}\n\tschedulePublication() {\n\t\tif (!this.isActive) return;\n\t\tif (this.throttleWaitMs == null) {\n\t\t\tthis.publishMessages();\n\t\t\treturn;\n\t\t}\n\t\tif (this.timeout == null) {\n\t\t\tthis.publishMessages();\n\t\t\tthis.timeout = setTimeout(this.handleIntervalEnd, this.throttleWaitMs);\n\t\t} else this.hasPendingPublication = true;\n\t}\n\tflushPublication() {\n\t\tif (this.timeout != null) {\n\t\t\tclearTimeout(this.timeout);\n\t\t\tthis.timeout = void 0;\n\t\t}\n\t\tthis.hasPendingPublication = false;\n\t\tthis.publishMessages();\n\t}\n\tpublishMessages() {\n\t\tif (!this.isActive) return;\n\t\tconst publishedMessages = this.messagesValue.map((message, index) => this.dirtyMessageIndices.has(index) || this.publishedMessageSources[index] !== message ? snapshotValue(message) : this.publishedMessages[index]);\n\t\tthis.publishedMessages = publishedMessages;\n\t\tthis.publishedMessageSources = [...this.messagesValue];\n\t\tthis.dirtyMessageIndices.clear();\n\t\tthis.isPublishing = true;\n\t\ttry {\n\t\t\tthis.messagesRef.value = publishedMessages;\n\t\t} finally {\n\t\t\tthis.isPublishing = false;\n\t\t}\n\t}\n};\n/**\n* @internal\n*/\nvar VueChat = class extends AbstractChat {\n\tconstructor({ state, ...init }) {\n\t\tsuper({\n\t\t\t...init,\n\t\t\tstate\n\t\t});\n\t}\n};\n/**\n* Composable to access messages, status, and other chat properties and\n* methods. Accepts an optional reactive initial configuration object\n*\n* @example\n*\n* ```ts\n* // passing a getter if any reactive properties are used within\n* // the init object\n* const { messages, sendMessage } = useChat(() => ({\n* // ...\n* })\n* ```\n*\n* @see BaseChatInit\n*/\nfunction useChat(init) {\n\tconst messages = shallowRef([]);\n\tconst status = shallowRef(\"ready\");\n\tconst error = shallowRef();\n\tconst chatInstance = shallowRef();\n\tlet chatState;\n\twatch(messages, (messageList) => {\n\t\tif (chatState != null && !chatState.isPublishing) chatState.setMessagesFromConsumer(messageList);\n\t}, { flush: \"sync\" });\n\twatch(() => toValue(init), (opts) => {\n\t\tchatState?.dispose();\n\t\tconst { throttle, ...chatInit } = opts ?? {};\n\t\tconst nextChatState = new VueChatState({\n\t\t\tinitialMessages: chatInit.messages ?? [],\n\t\t\tmessagesRef: messages,\n\t\t\tstatusRef: status,\n\t\t\terrorRef: error,\n\t\t\tthrottleWaitMs: throttle\n\t\t});\n\t\tchatState = nextChatState;\n\t\tnextChatState.publishInitialState();\n\t\tchatInstance.value = new VueChat({\n\t\t\t...chatInit,\n\t\t\tstate: nextChatState\n\t\t});\n\t}, { immediate: true });\n\tif (getCurrentScope() != null) onScopeDispose(() => {\n\t\tchatState?.dispose();\n\t});\n\treturn {\n\t\tid: computed(() => chatInstance.value.id),\n\t\tstatus,\n\t\tmessages,\n\t\terror,\n\t\taddToolApprovalResponse: (opts) => chatInstance.value.addToolApprovalResponse(opts),\n\t\taddToolOutput: (opts) => chatInstance.value.addToolOutput(opts),\n\t\tclearError: () => chatInstance.value.clearError(),\n\t\tregenerate: (opts) => chatInstance.value.regenerate(opts),\n\t\tsendMessage: (...args) => chatInstance.value.sendMessage(...args),\n\t\tstop: () => chatInstance.value.stop(),\n\t\tresumeStream: (opts) => chatInstance.value.resumeStream(opts)\n\t};\n}\n//#endregion\n//#region src/index.ts\n/**\n* @deprecated Use `useObject` instead.\n*/\nconst experimental_useObject = useObject;\n//#endregion\nexport { Chat, experimental_useObject, useChat, useCompletion, useObject };\n\n//# sourceMappingURL=index.js.map","import {\n DefaultChatTransport,\n lastAssistantMessageIsCompleteWithApprovalResponses,\n} from 'ai'\nimport type { FileUIPart } from 'ai'\nimport { computed, ref, watch, watchEffect } from 'vue'\nimport { useI18n } from 'vue-i18n'\nimport { usePreferredDark } from '@vueuse/core'\nimport { generateId } from 'ai'\nimport { Chat } from '@ai-sdk/vue'\nimport { defineStore } from 'pinia'\nimport { useSafeLocalStorage } from '../useSafeLocalStorage'\nimport { isUserAnsweredTool, TOOL_TERMINAL_STATES } from 'models'\nimport type {\n Chat as ChatRecord,\n AgentFileUpload,\n AgentInterface,\n AgentModel,\n AgentVoiceCapability,\n AgentGatewayOptions,\n ChatMessageActions,\n MessageFeedback,\n RevisedAnswer,\n UIChatMessage,\n AgentTools,\n} from 'models'\nimport {\n collectDeviceContext,\n collectGeolocation,\n} from 'utils/src/device-context'\nimport { logger } from 'utils/src/logger'\nimport {\n getTextPart,\n withAudioTranscripts,\n type AudioTranscriptUpdate,\n} from 'utils'\nimport { createChatbotApiClient, type ChatbotFile } from './api'\nimport type { PendingAttachment } from './types'\n\n// The store exposes `chat` (a `Chat<UIChatMessage>` computed) whose inferred\n// type transitively references JSONObject. Re-export it so consumers can emit\n// portable declarations that name the type (TS2883) without an unused import.\n// This only works while the whole workspace resolves ONE @ai-sdk/provider: the\n// declaration emitter needs the name to point at the very file the type came\n// from, so the peer ranges on `ai`, `@ai-sdk/vue` and `@ai-sdk/provider` here\n// and in `components` are pinned to the same versions the root installs.\nexport type { JSONObject } from '@ai-sdk/provider'\n\n/**\n * Id prefix of the spoken QUESTIONS the client shows before the server has\n * them. Their own id space is what lets a reload replace them instead of\n * duplicating them (see {@link unpersistedVoiceLines}). What the agent says\n * never gets one: a spoken answer reaches the screen only as the written turn\n * the server persisted, whole, with its sources and its widgets.\n */\nexport const VOICE_LINE_ID_PREFIX = 'voice-'\n\n/** Whitespace-collapsed lowercase text, for comparing two transcripts. */\nconst normalizeSpoken = (text: string): string =>\n text.replace(/\\s+/g, ' ').trim().toLowerCase()\n\n/** Text of a message, whitespace-collapsed, for comparing two transcripts. */\nconst spokenText = (message: UIChatMessage): string =>\n normalizeSpoken(\n message.parts\n .filter((part) => part.type === 'text')\n .map((part) => ('text' in part ? part.text : ''))\n .join(' '),\n )\n\n/**\n * The spoken questions the reload would silently drop.\n *\n * A question is shown the moment the provider transcribes it, while the server\n * writes it only when the turn it belongs to has been answered. So between the\n * two there is always a window, and replacing the list with the persisted one\n * wholesale made the caller's own words vanish from the screen while they were\n * still speaking (reported 2026-08-06).\n *\n * A line counts as persisted when a server message says the same thing, or\n * ENDS with it: the provider can prepend its own lead-in to what it heard, so\n * the spoken line is the persisted one with a prefix. Nothing looser than\n * that: matching on \"contains\" either way round let a short persisted turn\n * (\"no\", \"sì\") swallow a whole question the server did not have yet, which is\n * the disappearance this was supposed to fix.\n *\n * Only questions are considered because only questions are shown: what the\n * agent says arrives as the written turn and nothing else (see\n * {@link VOICE_LINE_ID_PREFIX}).\n */\nconst SHORTEST_MATCHABLE_LINE = 8\n\nconst unpersistedVoiceLines = (\n persisted: UIChatMessage[],\n shown: UIChatMessage[],\n): UIChatMessage[] => {\n // Consumed as they match, one persisted line for one spoken line. With a\n // plain `some` a single persisted \"sì\" accounted for every later \"sì\" the\n // caller said, and the new one vanished from the screen before the server\n // had it.\n const server = persisted\n .filter((message) => message.role === 'user')\n .map((message) => ({ text: spokenText(message), taken: false }))\n return shown.filter((message) => {\n if (\n !message.id.startsWith(VOICE_LINE_ID_PREFIX) ||\n message.role !== 'user'\n ) {\n return false\n }\n const text = spokenText(message)\n const match = server.find(\n (other) =>\n !other.taken &&\n other.text.length > 0 &&\n (other.text === text ||\n (other.text.length >= SHORTEST_MATCHABLE_LINE &&\n text.endsWith(other.text))),\n )\n if (!match) {\n return true\n }\n match.taken = true\n return false\n })\n}\n\n/** Tool name of a tool invocation part, '' for any other part. */\nconst partToolName = (part: UIChatMessage['parts'][number]): string => {\n const type = (part as { type?: string }).type ?? ''\n if (type === 'dynamic-tool') {\n return (part as { toolName?: string }).toolName ?? ''\n }\n return type.startsWith('tool-') ? type.slice('tool-'.length) : ''\n}\n\n/**\n * True when the last assistant step carries a client tool the user has\n * answered, and nothing left in it for the user to answer.\n *\n * Replaces the SDK's `lastAssistantMessageIsCompleteWithToolCalls`, which asks\n * for an output from EVERY tool part of the step. Most client tools never get\n * one: they render from the call input and there is nothing to send back (see\n * USER_ANSWERED_TOOLS). So a step that shows a form NEXT TO another widget\n * never satisfied that condition, the submitted answers stayed in the browser\n * and the turn was never resumed: the user filled the form and the agent went\n * silent. Reported on 2026-08-27 for showForm + showSources, the routine\n * pairing on a knowledge-base turn, where the sources closure is synthesized\n * server-side into the same step.\n *\n * At least one answered tool is required, so a turn ending on display-only\n * widgets still sends nothing.\n */\nexport const lastAssistantMessageIsCompleteWithAnsweredClientTools = ({\n messages,\n}: {\n messages: UIChatMessage[]\n}): boolean => {\n const message = messages[messages.length - 1]\n if (!message || message.role !== 'assistant') {\n return false\n }\n const lastStepStartIndex = message.parts.reduce(\n (last, part, index) => (part.type === 'step-start' ? index : last),\n -1,\n )\n const userAnsweredParts = message.parts\n .slice(lastStepStartIndex + 1)\n .filter(\n (part) =>\n !(part as { providerExecuted?: boolean }).providerExecuted &&\n isUserAnsweredTool(partToolName(part)),\n )\n return (\n userAnsweredParts.length > 0 &&\n userAnsweredParts.every((part) =>\n TOOL_TERMINAL_STATES.has((part as { state?: string }).state ?? ''),\n )\n )\n}\n\ntype ChatbotView = 'chat' | 'conversations' | 'profile' | 'auth' | 'files'\n\nexport function useChatbotStore(agentId: string) {\n return defineStore(`chatbot-${agentId}`, () => {\n const { t, te, locale } = useI18n({ useScope: 'global' })\n\n // === Configuration state ===\n const baseUrl = ref('')\n const basePath = ref<string | undefined>()\n const agentIdRef = ref(agentId)\n const name = ref<string | undefined>()\n const agentType = ref<'chat' | 'reasoning' | undefined>()\n const userId = ref<string | undefined>()\n const agentInterface = ref<AgentInterface | undefined>()\n const agentModel = ref<AgentModel | undefined>()\n const agentTools = ref<AgentTools | undefined>()\n const headers = ref<Record<string, string> | undefined>()\n const revisedAnswers = ref<RevisedAnswer[] | undefined>()\n /** Compatibility with PkChatbot `model` prop — overrides agentModel.model when set */\n const model = ref<string | undefined>()\n /** Raw actions from parent prop, filtered by agentType into `actions` */\n const actionsInput = ref<ChatMessageActions[] | undefined>()\n /** File upload configuration from agent settings */\n const agentFileUpload = ref<AgentFileUpload | undefined>()\n /** Voice configuration from agent settings: absent means no voice. */\n const agentVoice = ref<AgentVoiceCapability | undefined>()\n /** Fallback models for AI Gateway routing */\n const fallbackModels = ref<string[] | undefined>()\n /** Gateway options (ZDR, provider timeouts) */\n const gatewayOptions = ref<Partial<AgentGatewayOptions> | undefined>()\n /** External context set by the host application (e.g. via setContext() on the custom element). Validated server-side against the agent's externalContextSchema. */\n const externalContext = ref<Record<string, unknown> | undefined>()\n /** System-level theme override passed by the host application */\n const systemTheme = ref<'light' | 'dark' | undefined>()\n /** Hide the synthetic welcome message built from `initialMessage` (the fullscreen layout shows a greeting in its place) */\n const hideWelcomeMessage = ref(false)\n\n const prefersDark = usePreferredDark()\n const isDark = computed(() => {\n let theme = agentInterface.value?.theme\n if (!theme || theme === 'auto') {\n theme = systemTheme.value\n }\n if (!theme) {\n return prefersDark.value\n }\n return theme === 'dark'\n })\n\n const isReasoningAgent = computed(() => agentType.value === 'reasoning')\n\n const actions = computed<ChatMessageActions[] | undefined>(() => {\n if (!isReasoningAgent.value) {\n return actionsInput.value\n }\n return actionsInput.value?.filter(\n (action) =>\n !['upvote', 'downvote', 'feedback'].includes(action),\n )\n })\n\n // === LocalStorage chatId ===\n const storageId = useSafeLocalStorage<string | null>(\n computed(() => `${agentIdRef.value}-chatId`),\n null,\n )\n\n watchEffect(() => {\n if (!storageId.value) {\n storageId.value = generateId()\n }\n })\n\n const localChatId = computed({\n get: () => storageId.value!,\n set: (value: string) => {\n storageId.value = value\n },\n })\n\n // === Chat error ===\n const chatError = ref<Error | undefined>()\n const isConversationBlocked = ref(false)\n\n const isConversationBlockedError = computed(\n () =>\n chatError.value?.message\n ?.toLowerCase()\n .includes('conversation-blocked') ?? false,\n )\n\n function isEntityNotFoundError(error: Error): boolean {\n try {\n const parsed = JSON.parse(error.message)\n return (\n parsed.status === 404 ||\n parsed.type?.includes('entity-not-found')\n )\n } catch {\n return false\n }\n }\n\n /**\n * When an anonymous session expires and rotates, the server returns a\n * 404 (entity-not-found) because the existing chatId belongs to the\n * previous userId. In that case we transparently generate a new chatId\n * and re-send the last user message so the conversation restarts\n * without the user noticing.\n */\n function handleChatError(error: Error) {\n if (isEntityNotFoundError(error)) {\n const pendingMessages = chat.value.messages.filter(\n (m) => m.role === 'user',\n )\n const lastUserMessage =\n pendingMessages[pendingMessages.length - 1]\n const lastUserText = lastUserMessage\n ? getTextPart(lastUserMessage)\n : undefined\n\n localChatId.value = generateId()\n chat.value.clearError()\n chatError.value = undefined\n\n if (lastUserText) {\n chat.value.sendMessage({ text: lastUserText })\n }\n return\n }\n\n logger.error(error)\n chatError.value = error\n if (isConversationBlockedError.value) {\n isConversationBlocked.value = true\n }\n }\n\n // === API client ===\n const apiClient = computed(() =>\n createChatbotApiClient({\n baseUrl: baseUrl.value,\n basePath: basePath.value,\n headers: () => headers.value,\n }),\n )\n\n // === Chat streaming instance ===\n const storedGeolocation = ref<{\n geolocationLatitude: number\n geolocationLongitude: number\n geolocationAccuracy?: number\n geolocationCity?: string\n } | null>(null)\n\n /**\n * The device this conversation is happening on, plus the position if\n * the user has shared it. Sent with every typed turn and, once, when a\n * call opens: a spoken turn reaches the backend from the voice provider\n * and can carry nothing of its own.\n */\n const buildDeviceContext = () => ({\n ...collectDeviceContext(),\n ...(storedGeolocation.value ?? {}),\n })\n\n const chat = computed(\n () =>\n new Chat<UIChatMessage>({\n id: localChatId.value,\n transport: new DefaultChatTransport({\n api: apiClient.value.getChatEndpoint(\n agentIdRef.value,\n isReasoningAgent.value ? 'reasoning' : 'chat',\n ),\n prepareSendMessagesRequest: ({\n messages: msgs,\n id,\n }) => ({\n body: {\n id,\n messages: [msgs[msgs.length - 1]],\n model: model.value,\n prompt: agentModel.value?.prompt,\n maxOutputTokens:\n agentModel.value?.maxOutputTokens,\n temperature: agentModel.value?.temperature,\n presencePenalty:\n agentModel.value?.presencePenalty,\n frequencyPenalty:\n agentModel.value?.frequencyPenalty,\n searchMode: agentModel.value?.searchMode,\n limit: agentModel.value?.limit,\n reasoning: agentModel.value?.reasoning,\n webSearch: agentTools.value?.webSearch,\n smoothStream:\n agentInterface.value?.smoothStream,\n deviceContext: buildDeviceContext(),\n externalContext: externalContext.value,\n disabledTools: agentTools.value?.disabled,\n fallbackModels: fallbackModels.value,\n gatewayOptions: gatewayOptions.value,\n },\n }),\n credentials: 'include',\n // Resolved per-request: reading `headers.value` here\n // would make this computed recreate the Chat (wiping\n // its messages) on every auth token rotation.\n headers: () => headers.value ?? {},\n }),\n // Two resume triggers: a client tool the user answered,\n // and a tool approval the user just answered. Without the\n // second one the approval response would sit in the\n // browser and the suspended call would never run.\n sendAutomaticallyWhen: (options) =>\n lastAssistantMessageIsCompleteWithAnsweredClientTools(\n options,\n ) ||\n lastAssistantMessageIsCompleteWithApprovalResponses(\n options,\n ),\n onError: handleChatError,\n // The transcripts of the audio just sent, streamed before\n // the answer: the stored message has them, this copy of\n // it gets them here (spec `audio-file-transcription.md`).\n onData: (part) => {\n if (part.type === 'data-audioTranscripts') {\n chat.value.messages = withAudioTranscripts(\n chat.value.messages,\n part.data as AudioTranscriptUpdate[],\n )\n }\n },\n // Chat UI init keeps `onFinish` in v7 (the onEnd rename\n // only applies to generateText/streamText callbacks).\n onFinish: () => {\n // A new chat is persisted on the backend only after the\n // first message: reload the list if it's not there yet.\n const id = localChatId.value\n if (\n !isReasoningAgent.value &&\n !conversations.value.some((c) => c.id === id)\n ) {\n loadConversations(agentIdRef.value)\n }\n },\n }),\n )\n\n // === Messages ===\n const initialMessageResolved = computed(() => {\n const val = agentInterface.value?.initialMessage\n if (!val?.[locale.value]) {\n return te('message.defaultAgentWelcome')\n ? t('message.defaultAgentWelcome')\n : ''\n }\n return val[locale.value]\n })\n\n // Stable across recomputations (locale or config changes), so keyed\n // renders don't remount the welcome bubble and feedback stays attached.\n const welcomeMessageId = generateId()\n const welcomeMessage = computed<UIChatMessage>(() => ({\n id: welcomeMessageId,\n role: 'assistant',\n parts: [{ type: 'text', text: initialMessageResolved.value }],\n }))\n\n const messages = computed(() => {\n // Resolve any remaining `attachment://` URLs that haven't been\n // resolved server-side yet (e.g. in-flight streaming messages).\n const resolveInFlight = (msgs: UIChatMessage[]) =>\n msgs.map((msg) => {\n if (msg.role !== 'user') {\n return msg\n }\n const hasFileParts = msg.parts.some(\n (p) => p.type === 'file',\n )\n if (!hasFileParts) {\n return msg\n }\n return {\n ...msg,\n parts: msg.parts.map((p) => {\n if (p.type !== 'file') {\n return p\n }\n const fp = p as FileUIPart\n if (fp.url.startsWith('attachment://')) {\n const storedFileName = fp.url.slice(\n 'attachment://'.length,\n )\n return {\n ...fp,\n url: apiClient.value.getMediaUrl(\n agentIdRef.value,\n localChatId.value,\n storedFileName,\n ),\n } as FileUIPart\n }\n // Blob URLs (from pending uploads) are already\n // usable as-is — don't append auth tokens.\n if (fp.url.startsWith('blob:')) {\n return fp\n }\n return {\n ...fp,\n url: apiClient.value.appendAuthToken(fp.url),\n } as FileUIPart\n }),\n }\n })\n\n if (isReasoningAgent.value) {\n return resolveInFlight(chat.value.messages)\n }\n if (\n !hideWelcomeMessage.value &&\n chat.value.messages?.[0]?.role !== 'assistant'\n ) {\n return [\n welcomeMessage.value,\n ...resolveInFlight(chat.value.messages),\n ]\n }\n return resolveInFlight(chat.value.messages)\n })\n\n // === Localized placeholder ===\n const inputMessagePlaceholder = computed(() => {\n const val = agentInterface.value?.messagePlaceholder\n if (!val?.[locale.value]) {\n return te('placeholder.askAnything')\n ? t('placeholder.askAnything')\n : ''\n }\n return val[locale.value]\n })\n\n // === Conversations ===\n const conversations = ref<ChatRecord[]>([])\n const isLoadingConversations = ref(false)\n const chatFiles = ref<ChatbotFile[]>([])\n const isLoadingChatFiles = ref(false)\n\n // === Navigation ===\n const activeView = ref<ChatbotView>('chat')\n\n // === Message feedback state ===\n const messageFeedbacks = ref<MessageFeedback[]>([])\n const feedbackDialogMessage = ref<UIChatMessage | undefined>()\n const isFeedbackSubmitting = ref(false)\n const isFeedbackSubmitted = ref(false)\n const feedbackSubmitError = ref<string | undefined>()\n\n // === Lead form state ===\n const isLeadSubmitted = ref(false)\n const isLoadingSubmitLead = ref(false)\n const submitLeadError = ref<string | undefined>()\n\n // === Input ===\n const input = ref('')\n const pendingAttachments = ref<PendingAttachment[]>([])\n const lastSubmittedInput = ref('')\n const messageCountBeforeSubmit = ref(0)\n\n // === Internal loaders ===\n async function loadConversations(id: string) {\n if (isReasoningAgent.value) {\n conversations.value = []\n return\n }\n isLoadingConversations.value = true\n try {\n conversations.value = await apiClient.value.getConversations(\n id,\n userId.value,\n )\n } catch {\n conversations.value = []\n } finally {\n isLoadingConversations.value = false\n }\n }\n\n // Files uploaded in the current chat (the user's \"My files\" entries\n // tied to this conversation). No chat → nothing to load.\n async function loadChatFiles() {\n const chatId = localChatId.value\n if (!chatId) {\n chatFiles.value = []\n return\n }\n isLoadingChatFiles.value = true\n try {\n chatFiles.value = await apiClient.value.getChatFiles(chatId)\n } catch {\n chatFiles.value = []\n } finally {\n isLoadingChatFiles.value = false\n }\n }\n\n function getChatFileUrl(documentId: string, inline = false) {\n return apiClient.value.getChatFileDownloadUrl(documentId, inline)\n }\n\n function getChatFilePreviewUrl(documentId: string) {\n return apiClient.value.getChatFilePreviewUrl(documentId)\n }\n\n // Exclude a file from the user's KB (soft-delete server-side); drop it\n // from the local list on success. A spreadsheet is deleted with every\n // version written of it, so they all leave the list.\n async function deleteChatFile(documentId: string) {\n await apiClient.value.deleteChatFile(documentId)\n const removed = chatFiles.value.find(\n (file) => file.documentId === documentId,\n )\n const rootId =\n removed?.kind === 'spreadsheet'\n ? (removed.sourceAttachmentId ?? removed.documentId)\n : undefined\n chatFiles.value = chatFiles.value.filter(\n (file) =>\n file.documentId !== documentId &&\n (!rootId ||\n (file.documentId !== rootId &&\n file.sourceAttachmentId !== rootId)),\n )\n }\n\n async function loadChat(id: string, chatId: string) {\n // Reasoning chats are never persisted and the Chat instance is\n // recreated empty on every chatId/agentId change: nothing to load.\n if (isReasoningAgent.value) {\n return\n }\n try {\n const data = await apiClient.value.getChat(id, chatId)\n // The chat may have advanced while the request was in flight\n // (the user submitted a message, or the chatId rotated): never\n // clobber local messages with a stale response. A wiped list\n // mid-stream also suppresses the synthetic welcome message,\n // because the streamed reply gets re-pushed at index 0.\n if (\n chatId !== localChatId.value ||\n chat.value.status !== 'ready' ||\n chat.value.messages.length > 0\n ) {\n return\n }\n if (data) {\n chat.value.messages = data.messages as UIChatMessage[]\n isConversationBlocked.value = data.blocked ?? false\n }\n } catch {\n // A new chat 404s here: the instance already starts empty,\n // clearing messages would race with the first submit.\n }\n }\n\n /**\n * A written turn is in flight, so the message list must not be replaced\n * under it. Read through a widened local on purpose: the status changes\n * across an await, which the compiler otherwise narrows away.\n */\n const isTurnInFlight = (): boolean => {\n const status: string = chat.value.status\n return status === 'submitted' || status === 'streaming'\n }\n\n /** Ordering of the concurrent reloads: see `refreshMessages`. */\n let refreshSequence = 0\n let refreshApplied = 0\n\n /**\n * Replaces the message list with what the server persisted.\n *\n * `loadChat` deliberately refuses to touch a non-empty list, because it\n * runs on mount and must never clobber a stream in flight. A voice turn\n * is the opposite case: the answer was produced by the provider calling\n * our backend, so the persisted chat is ahead of what this client shows\n * (the transcript we appended is text only, without sources or tool\n * results). Still guarded on an idle chat, for the same reason as there.\n *\n * Returns 'pending' when the server was still BEHIND what the client\n * shows, so the caller comes back for the rest: a USER line with no\n * persisted counterpart means the turn it belongs to has not been\n * written yet, and with it are missing the tool results and sources\n * that only the reload can bring (an agent line proves nothing: the\n * spoken fallback sentence exists only in the audio stream). Returns\n * 'caught-up' only when a reload was actually applied and nothing is\n * missing; everything else (a failed request, a stale response, a\n * written turn in flight) is 'indeterminate', which a poller must\n * treat as \"try again\", not as done: a killed voice turn persists\n * minutes after the call, and stopping on a failure left it off the\n * screen until the page was reloaded by hand (seen live 2026-08-26).\n *\n * A later reload wins over an earlier one, whatever order they answer\n * in: out-of-order answers are the normal case on a call, and a slow\n * fetch that started first would otherwise land last and take the\n * newest messages, their tool results and their sources off the screen.\n */\n async function refreshMessages(): Promise<\n 'pending' | 'caught-up' | 'indeterminate'\n > {\n // Only a turn in flight is a reason not to reload. Requiring\n // 'ready' also refused to reload after a failed submit ('error'),\n // which on a call left the conversation frozen on screen until the\n // page was reloaded by hand.\n if (isReasoningAgent.value || isTurnInFlight()) {\n return 'indeterminate'\n }\n const chatId = localChatId.value\n const mine = (refreshSequence += 1)\n try {\n const data = await apiClient.value.getChat(\n agentIdRef.value,\n chatId,\n )\n if (\n !data ||\n chatId !== localChatId.value ||\n isTurnInFlight() ||\n mine <= refreshApplied\n ) {\n return 'indeterminate'\n }\n refreshApplied = mine\n const persisted = data.messages as UIChatMessage[]\n const pending = unpersistedVoiceLines(\n persisted,\n chat.value.messages,\n )\n chat.value.messages = [...persisted, ...pending]\n isConversationBlocked.value = data.blocked ?? false\n return pending.length > 0 ? 'pending' : 'caught-up'\n } catch {\n // Nothing persisted yet (a new conversation is created by its\n // first write, so until then this request has nothing to\n // find), or a fetch that failed: either way not proof of\n // anything, so not 'caught-up'.\n }\n return 'indeterminate'\n }\n\n /**\n * Appends a message the client already knows about, without sending\n * anything: the voice transcript, whose turn is answered server-side.\n */\n function appendMessage(message: UIChatMessage) {\n chat.value.messages = [...chat.value.messages, message]\n }\n\n async function loadMessageFeedbacks(chatId: string) {\n try {\n messageFeedbacks.value =\n await apiClient.value.getMessageFeedbacks(chatId)\n } catch {\n messageFeedbacks.value = []\n }\n }\n\n function upsertLocalFeedback(feedback: MessageFeedback) {\n const idx = messageFeedbacks.value.findIndex(\n (f) => f.messageId === feedback.messageId,\n )\n if (idx >= 0) {\n messageFeedbacks.value[idx] = feedback\n } else {\n messageFeedbacks.value.push(feedback)\n }\n }\n\n function extractFeedbackContext(message: UIChatMessage) {\n const msgList = messages.value\n const idx = msgList.findIndex((m) => m.id === message.id)\n const assistantMessage = getTextPart(message) ?? ''\n const prevUser = msgList\n .slice(0, idx)\n .reverse()\n .find((m) => m.role === 'user')\n const userQuestion = getTextPart(prevUser ?? message) ?? ''\n return { userQuestion, assistantMessage }\n }\n\n // === Actions ===\n async function initialize(id: string, chatId: string) {\n await Promise.all([\n loadChat(id, chatId),\n loadConversations(id),\n loadMessageFeedbacks(chatId),\n ])\n\n if (!storedGeolocation.value) {\n collectGeolocation((lat, lon) =>\n apiClient.value.reverseGeocode(lat, lon, locale.value),\n ).then((geo) => {\n if (geo) {\n storedGeolocation.value = geo\n }\n })\n }\n }\n\n async function handleSubmit() {\n // Snapshot text and attachments before any async operation to avoid\n // them being cleared by startNewChat() (reasoning agents) or by a\n // concurrent store update from the component.\n const text = input.value.trim()\n const fileParts: FileUIPart[] = pendingAttachments.value\n .filter(\n (\n att,\n ): att is PendingAttachment & {\n state: 'done'\n mediaSource: NonNullable<\n PendingAttachment['mediaSource']\n >\n } => att.state === 'done' && att.mediaSource !== undefined,\n )\n .map((att) => {\n return {\n type: 'file' as const,\n mediaType: att.mediaSource.mimeType,\n url: att.localUrl,\n filename: att.mediaSource.name,\n providerMetadata: {\n '8bot': {\n media: att.mediaSource,\n },\n },\n }\n })\n\n if (isReasoningAgent.value && messages.value.length > 0) {\n await startNewChat()\n }\n\n // Snapshot state before sending so we can rollback on stop\n lastSubmittedInput.value = text\n messageCountBeforeSubmit.value = chat.value.messages.length\n\n // Chat<UIChatMessage> can't resolve the correct sendMessage overload\n // when using a custom message generic — cast is intentional.\n const sendMessage = chat.value.sendMessage as unknown as (msg: {\n text: string\n files?: FileUIPart[]\n }) => void\n sendMessage({\n text,\n files: fileParts.length > 0 ? fileParts : undefined,\n })\n input.value = ''\n clearPendingAttachments()\n }\n\n /**\n * Programmatically send a user message without the input snapshot/rollback\n * logic. Logs a warning and does nothing if the chat is not ready.\n */\n function sendMessage(text: string) {\n const trimmed = text.trim()\n if (!trimmed) {\n return\n }\n if (chat.value.status !== 'ready') {\n logger.warn(\n '[useChatbotStore] sendMessage called before chat is ready. Listen for the \"ready\" event on the widget element.',\n )\n return\n }\n const send = chat.value.sendMessage as unknown as (msg: {\n text: string\n }) => void\n send({ text: trimmed })\n }\n\n async function stopGeneration() {\n const shouldRollback = lastSubmittedInput.value.length > 0\n await chat.value.stop()\n if (shouldRollback) {\n input.value = lastSubmittedInput.value\n chat.value.messages = chat.value.messages.slice(\n 0,\n messageCountBeforeSubmit.value,\n )\n lastSubmittedInput.value = ''\n }\n }\n\n // Clear rollback state when generation completes naturally\n watch(\n () => chat.value.status,\n (status) => {\n if (status === 'ready' && lastSubmittedInput.value.length > 0) {\n lastSubmittedInput.value = ''\n }\n },\n )\n\n function clearPendingAttachments(revokeAll = false) {\n for (const att of pendingAttachments.value) {\n // 'done' attachment localUrls may still be referenced in\n // FileUIPart.url inside message parts — skip revocation unless\n // explicitly requested (e.g. when starting a new chat).\n if (revokeAll || att.state !== 'done') {\n URL.revokeObjectURL(att.localUrl)\n }\n }\n pendingAttachments.value = []\n fileLimitError.value = null\n }\n\n async function startNewChat() {\n lastSubmittedInput.value = ''\n await stopGeneration()\n localChatId.value = generateId()\n chat.value.clearError()\n chatError.value = undefined\n isConversationBlocked.value = false\n clearPendingAttachments(true)\n navigate('chat')\n return localChatId.value\n }\n\n async function regenerate(\n options?: Parameters<typeof chat.value.regenerate>[0],\n ) {\n if (chat.value.status !== 'ready') {\n lastSubmittedInput.value = ''\n await stopGeneration()\n }\n await chat.value.regenerate(options)\n }\n\n function addToolOutput(params: {\n tool: string\n toolCallId: string\n output: unknown\n }) {\n if (params.tool === 'requestGeolocation') {\n const output = params.output as\n | {\n latitude: number\n longitude: number\n accuracy?: number\n city?: string\n }\n | { error: string }\n if ('latitude' in output) {\n storedGeolocation.value = {\n geolocationLatitude: output.latitude,\n geolocationLongitude: output.longitude,\n geolocationAccuracy: output.accuracy,\n geolocationCity: output.city,\n }\n }\n }\n chat.value.addToolOutput(params)\n }\n\n /**\n * Answers a tool approval request. The response rides the same chat\n * stream: `sendAutomaticallyWhen` submits it, the backend re-validates\n * it against the persisted request and the SDK resumes (or denies) the\n * suspended call.\n */\n function addToolApprovalResponse(params: {\n id: string\n approved: boolean\n reason?: string\n }) {\n chat.value.addToolApprovalResponse(params)\n }\n\n // Files already committed to prior messages in this chat.\n const sentFileCount = computed(() =>\n chat.value.messages.reduce(\n (n, m) => n + m.parts.filter((p) => p.type === 'file').length,\n 0,\n ),\n )\n\n // Single source of truth for the attachment limits (see AgentFileUpload).\n // The per-message cap counts the current draft's attachments; the\n // per-chat cap counts those plus everything already sent.\n const maxFilesPerMessage = computed(\n () => agentFileUpload.value?.maxFilesPerMessage ?? 5,\n )\n const maxFilesPerChat = computed(\n () => agentFileUpload.value?.maxFilesPerChat ?? 20,\n )\n const remainingAttachmentSlots = computed(() =>\n Math.max(\n 0,\n Math.min(\n maxFilesPerMessage.value - pendingAttachments.value.length,\n maxFilesPerChat.value -\n sentFileCount.value -\n pendingAttachments.value.length,\n ),\n ),\n )\n const isAttachmentLimitReached = computed(\n () => remainingAttachmentSlots.value <= 0,\n )\n\n // Reactive notice surfaced to the input when a file gets rejected.\n const fileLimitError = ref<{\n reason: 'per-message' | 'per-chat'\n max: number\n } | null>(null)\n const clearFileLimitError = () => {\n fileLimitError.value = null\n }\n\n // The notice is only true while at capacity: drop it once room frees up.\n watch(isAttachmentLimitReached, (reached) => {\n if (!reached) {\n fileLimitError.value = null\n }\n })\n\n async function handleFileSelect(file: File) {\n if (isAttachmentLimitReached.value) {\n // Whichever cap is tighter is the one that blocked this file.\n fileLimitError.value =\n maxFilesPerChat.value -\n sentFileCount.value -\n pendingAttachments.value.length <=\n maxFilesPerMessage.value - pendingAttachments.value.length\n ? { reason: 'per-chat', max: maxFilesPerChat.value }\n : {\n reason: 'per-message',\n max: maxFilesPerMessage.value,\n }\n return\n }\n const id = generateId()\n const localUrl = URL.createObjectURL(file)\n const attachment: PendingAttachment = {\n id,\n file,\n localUrl,\n state: 'uploading',\n }\n pendingAttachments.value = [...pendingAttachments.value, attachment]\n\n try {\n const mediaSource = await apiClient.value.uploadMedia(\n agentIdRef.value,\n localChatId.value,\n file,\n )\n pendingAttachments.value = pendingAttachments.value.map((a) =>\n a.id === id ? { ...a, state: 'done', mediaSource } : a,\n )\n } catch (err) {\n const message =\n err instanceof Error ? err.message : 'Upload failed'\n pendingAttachments.value = pendingAttachments.value.map((a) =>\n a.id === id ? { ...a, state: 'error', error: message } : a,\n )\n }\n }\n\n async function submitVote(\n message: UIChatMessage,\n vote: 'upvote' | 'downvote',\n ) {\n const { userQuestion, assistantMessage } =\n extractFeedbackContext(message)\n const feedback = await apiClient.value.submitMessageFeedback({\n messageId: message.id,\n chatId: localChatId.value,\n agentId: agentIdRef.value,\n vote,\n userQuestion,\n assistantMessage,\n })\n upsertLocalFeedback(feedback)\n }\n\n async function onUpvote(message: UIChatMessage) {\n await submitVote(message, 'upvote')\n }\n\n async function onDownvote(message: UIChatMessage) {\n await submitVote(message, 'downvote')\n }\n\n function onFeedback(message: UIChatMessage) {\n isFeedbackSubmitted.value = false\n feedbackSubmitError.value = undefined\n feedbackDialogMessage.value = message\n }\n\n async function onFeedbackSubmit(comment: string) {\n if (!feedbackDialogMessage.value) {\n return\n }\n try {\n isFeedbackSubmitting.value = true\n isFeedbackSubmitted.value = false\n feedbackSubmitError.value = undefined\n const { userQuestion, assistantMessage } =\n extractFeedbackContext(feedbackDialogMessage.value)\n const feedback = await apiClient.value.submitMessageFeedback({\n messageId: feedbackDialogMessage.value.id,\n chatId: localChatId.value,\n agentId: agentIdRef.value,\n userQuestion,\n assistantMessage,\n comment,\n })\n upsertLocalFeedback(feedback)\n isFeedbackSubmitted.value = true\n await loadMessageFeedbacks(localChatId.value)\n } catch {\n feedbackSubmitError.value = te('message.feedbackSubmitError')\n ? t('message.feedbackSubmitError')\n : 'Failed to submit feedback'\n } finally {\n isFeedbackSubmitting.value = false\n }\n }\n\n async function onLeadSubmit(data: Record<string, unknown>) {\n try {\n isLoadingSubmitLead.value = true\n isLeadSubmitted.value = false\n submitLeadError.value = undefined\n await apiClient.value.submitLead({\n agentId: agentIdRef.value,\n chatId: localChatId.value,\n ...data,\n })\n isLeadSubmitted.value = true\n } catch {\n submitLeadError.value = te('message.leadSubmitError')\n ? t('message.leadSubmitError')\n : 'Failed to submit lead'\n } finally {\n isLoadingSubmitLead.value = false\n }\n }\n\n async function renameChatTitle(chatId: string, title: string) {\n const updated = await apiClient.value.updateChatTitle(\n agentIdRef.value,\n chatId,\n title,\n )\n conversations.value = conversations.value.map((c) =>\n c.id === chatId ? { ...c, title: updated.title } : c,\n )\n }\n\n async function deleteChat(chatId: string) {\n await apiClient.value.deleteChat(agentIdRef.value, chatId)\n conversations.value = conversations.value.filter(\n (c) => c.id !== chatId,\n )\n if (localChatId.value === chatId) {\n await startNewChat()\n }\n }\n\n function navigate(view: ChatbotView) {\n activeView.value = view\n }\n\n // === Identity switches ===\n /**\n * Last userId the chat state was bound to. Starts undefined: adopting\n * the first identity of the page must not reset anything, because in\n * every same-user flow (anonymous re-auth, restored session) the\n * persisted chatId belongs to it, while `loadChat` leaves foreign\n * chats empty on a fresh page load anyway.\n */\n let boundUserId: string | undefined\n\n /**\n * GET the current chat as the new user, retrying once on failure: a\n * transient network error must not be mistaken for \"not owned\" and\n * wipe a conversation the user actually keeps. After the retry it\n * still fails closed (privacy wins over continuity).\n */\n function isChatReadable(chatId: string): Promise<boolean> {\n const probe = () =>\n apiClient.value\n .getChat(agentIdRef.value, chatId)\n .then((data) => data !== null)\n return probe().catch(() => probe().catch(() => false))\n }\n\n /**\n * The persisted chatId and the in-memory messages survive auth\n * changes, so when the session identity changes (host login via\n * external token, sign-out followed by a fresh anonymous user) the\n * previous user's conversation would keep showing. The server\n * enforces chat ownership, so ask it whether the current chat is\n * readable by the new user: it is only when it was transferred along\n * (in-widget sign-in links the anonymous user and moves their chats).\n * Otherwise drop the previous user's state and start a fresh chat.\n */\n watch(userId, async (newUserId) => {\n if (!newUserId || newUserId === boundUserId) {\n // Sign-out (undefined) keeps the state: it is either followed\n // by a new identity (anonymous fallback / next login), which\n // resets here, or no chat is rendered at all.\n return\n }\n const previousUserId = boundUserId\n boundUserId = newUserId\n if (previousUserId === undefined) {\n return\n }\n const verifiedChatId = localChatId.value\n // Reasoning chats are never persisted server-side, so the probe\n // could only fail: skip it and reset directly.\n const isChatOwnedByNewUser = isReasoningAgent.value\n ? false\n : await isChatReadable(verifiedChatId)\n if (\n userId.value !== newUserId ||\n localChatId.value !== verifiedChatId\n ) {\n // Superseded: another identity change or a chat rotation won\n return\n }\n if (isChatOwnedByNewUser) {\n // Same conversation, new owner (anonymous → linked account):\n // keep the messages, refresh the user-scoped list.\n loadConversations(agentIdRef.value)\n return\n }\n conversations.value = []\n messageFeedbacks.value = []\n chatFiles.value = []\n // Rotating the chatId recreates the Chat instance (clearing the\n // previous user's messages) and re-triggers `initialize` in the\n // components watching it, which reloads the user-scoped data.\n await startNewChat()\n input.value = ''\n })\n\n return {\n // Configuration\n apiClient,\n baseUrl,\n basePath,\n agentId: agentIdRef,\n name,\n agentType,\n userId,\n agentInterface,\n agentModel,\n agentTools,\n headers,\n revisedAnswers,\n model,\n actionsInput,\n actions,\n agentFileUpload,\n agentVoice,\n fallbackModels,\n gatewayOptions,\n externalContext,\n systemTheme,\n hideWelcomeMessage,\n isDark,\n // Chat state\n chat,\n messages,\n conversations,\n isLoadingConversations,\n chatFiles,\n isLoadingChatFiles,\n input,\n pendingAttachments,\n isAttachmentLimitReached,\n fileLimitError,\n localChatId,\n isConversationBlocked,\n inputMessagePlaceholder,\n chatError,\n // Navigation\n activeView,\n // Feedback state\n messageFeedbacks,\n feedbackDialogMessage,\n isFeedbackSubmitting,\n isFeedbackSubmitted,\n feedbackSubmitError,\n // Lead state\n isLeadSubmitted,\n isLoadingSubmitLead,\n submitLeadError,\n // Actions\n buildDeviceContext,\n initialize,\n loadConversations,\n loadChatFiles,\n refreshMessages,\n appendMessage,\n getChatFileUrl,\n getChatFilePreviewUrl,\n deleteChatFile,\n handleSubmit,\n sendMessage,\n stopGeneration,\n startNewChat,\n regenerate,\n addToolOutput,\n addToolApprovalResponse,\n handleFileSelect,\n clearFileLimitError,\n clearPendingAttachments,\n onUpvote,\n onDownvote,\n onFeedback,\n onFeedbackSubmit,\n onLeadSubmit,\n navigate,\n renameChatTitle,\n deleteChat,\n }\n })()\n}\n"],"ignoreList":[1,2,3,4,5,6,7,8,9,10,11],"mappings":";;;;;;;;;;;AAgBA,SAAgBkF,KAAuB;CACnC,IAAMC,IACF,UACF,YAEIC,IACF,UACF;CAEF,OAAO;EACH,2BAAU,IAAI,KAAK,EAAA,CAAE,YAAY;EACjC,UAAU,KAAK,eAAe,CAAC,CAAC,gBAAgB,CAAC,CAAC;EAClD,UAAU,UAAU;EACpB,WAAW,CAAC,GAAG,UAAU,SAAS;EAClC,KAAK,OAAO,SAAS;EAC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