@8wave/ai-elements 0.126.0-beta.31 → 0.126.0-beta.33
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-COa7L9GK.js → Agent-DZEyfr8D.js} +2 -1
- package/dist/_chunks/Agent-DZEyfr8D.js.map +1 -0
- package/dist/_chunks/{PkFilePreview-SBGa95Ca.js → PkFilePreview-C6ZZablL.js} +3 -3
- package/dist/_chunks/{PkFilePreview-SBGa95Ca.js.map → PkFilePreview-C6ZZablL.js.map} +1 -1
- package/dist/_chunks/{PkFilePreviewDialog-Cc7iZWCl.js → PkFilePreviewDialog-BzBHAt8l.js} +2 -2
- package/dist/_chunks/{PkFilePreviewDialog-Cc7iZWCl.js.map → PkFilePreviewDialog-BzBHAt8l.js.map} +1 -1
- package/dist/_chunks/{PkImageEditorDialog-D13bWv-N.js → PkImageEditorDialog-Dm34WFmS.js} +2 -2
- package/dist/_chunks/{PkImageEditorDialog-D13bWv-N.js.map → PkImageEditorDialog-Dm34WFmS.js.map} +1 -1
- package/dist/_chunks/{PkSelectionActions-BaX_rsCt.js → PkSelectionActions-CYqbMEjg.js} +2 -2
- package/dist/_chunks/{PkSelectionActions-BaX_rsCt.js.map → PkSelectionActions-CYqbMEjg.js.map} +1 -1
- package/dist/_chunks/{PkStreamingMarkdown-GRB3Gg_x.js → PkStreamingMarkdown-B8rZbprU.js} +3 -3
- package/dist/_chunks/{PkStreamingMarkdown-GRB3Gg_x.js.map → PkStreamingMarkdown-B8rZbprU.js.map} +1 -1
- package/dist/_chunks/{PkToolChatFile-DTm5-CE4.js → PkToolChatFile-C0emIVfS.js} +3 -3
- package/dist/_chunks/{PkToolChatFile-DTm5-CE4.js.map → PkToolChatFile-C0emIVfS.js.map} +1 -1
- package/dist/_chunks/{PkToolRequestGeolocation-DZenn1az.js → PkToolRequestGeolocation-DNzNRszE.js} +2 -2
- package/dist/_chunks/{PkToolRequestGeolocation-DZenn1az.js.map → PkToolRequestGeolocation-DNzNRszE.js.map} +1 -1
- package/dist/_chunks/{PkToolRequestOAuthConnection-Dz0qfYu5.js → PkToolRequestOAuthConnection-BDxYXz4s.js} +2 -2
- package/dist/_chunks/{PkToolRequestOAuthConnection-Dz0qfYu5.js.map → PkToolRequestOAuthConnection-BDxYXz4s.js.map} +1 -1
- package/dist/_chunks/{PkToolShowArtifact-C9_DHr5Y.js → PkToolShowArtifact-B_KIIjEn.js} +2 -2
- package/dist/_chunks/{PkToolShowArtifact-C9_DHr5Y.js.map → PkToolShowArtifact-B_KIIjEn.js.map} +1 -1
- package/dist/_chunks/{PkToolShowContactForm-DhyelktO.js → PkToolShowContactForm-DiHb3fRQ.js} +2 -2
- package/dist/_chunks/{PkToolShowContactForm-DhyelktO.js.map → PkToolShowContactForm-DiHb3fRQ.js.map} +1 -1
- package/dist/_chunks/{PkToolShowForm-Dz2Hnzts.js → PkToolShowForm-BmUAhIQy.js} +4 -4
- package/dist/_chunks/{PkToolShowForm-Dz2Hnzts.js.map → PkToolShowForm-BmUAhIQy.js.map} +1 -1
- package/dist/_chunks/{PkToolShowImageGallery-CiDfIboY.js → PkToolShowImageGallery-CZ394fdT.js} +2 -2
- package/dist/_chunks/{PkToolShowImageGallery-CiDfIboY.js.map → PkToolShowImageGallery-CZ394fdT.js.map} +1 -1
- package/dist/_chunks/{PkToolShowProductList-CY96IGWn.js → PkToolShowProductList-uNvUr2s9.js} +2 -2
- package/dist/_chunks/{PkToolShowProductList-CY96IGWn.js.map → PkToolShowProductList-uNvUr2s9.js.map} +1 -1
- package/dist/_chunks/{PkToolShowSources-CRk-MOoE.js → PkToolShowSources-Dm0L4prK.js} +3 -3
- package/dist/_chunks/{PkToolShowSources-CRk-MOoE.js.map → PkToolShowSources-Dm0L4prK.js.map} +1 -1
- package/dist/_chunks/{PkToolShowSuggestedReply-DKuV4mmV.js → PkToolShowSuggestedReply-B_dRrZfj.js} +2 -2
- package/dist/_chunks/{PkToolShowSuggestedReply-DKuV4mmV.js.map → PkToolShowSuggestedReply-B_dRrZfj.js.map} +1 -1
- package/dist/_chunks/{PkToolShowVideo-DI6ohcVU.js → PkToolShowVideo-DLgQjTq_.js} +2 -2
- package/dist/_chunks/{PkToolShowVideo-DI6ohcVU.js.map → PkToolShowVideo-DLgQjTq_.js.map} +1 -1
- package/dist/_chunks/{PkToolShowWebPages-Dh6L_n9T.js → PkToolShowWebPages-Cj2mJrs5.js} +2 -2
- package/dist/_chunks/{PkToolShowWebPages-Dh6L_n9T.js.map → PkToolShowWebPages-Cj2mJrs5.js.map} +1 -1
- package/dist/_chunks/{chatImagePolicy-Ckz-KAHA.js → chatImagePolicy-DMt6O5iK.js} +2 -2
- package/dist/_chunks/{chatImagePolicy-Ckz-KAHA.js.map → chatImagePolicy-DMt6O5iK.js.map} +1 -1
- package/dist/_chunks/{markdown-DHayRAiy.js → markdown-nw5sXwU0.js} +2 -2
- package/dist/_chunks/{markdown-DHayRAiy.js.map → markdown-nw5sXwU0.js.map} +1 -1
- package/dist/_chunks/{utils-3jpXeGGy.js → utils-DPGBO-HU.js} +2 -2
- package/dist/_chunks/{utils-3jpXeGGy.js.map → utils-DPGBO-HU.js.map} +1 -1
- package/dist/ai-elements.es.js +3927 -3858
- package/dist/ai-elements.es.js.map +1 -1
- package/dist-vue/PkChatbot.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-CRwhrv5Z.js → Agent-CBAd3F7k.js} +2 -1
- package/dist-vue/_chunks/Agent-CBAd3F7k.js.map +1 -0
- package/dist-vue/_chunks/{Document-Bp-qpa8v.js → Document-B3w5H0R0.js} +2 -2
- package/dist-vue/_chunks/{Document-Bp-qpa8v.js.map → Document-B3w5H0R0.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbot-CtrcDgBe.js → PkChatbot-CXpftmWm.js} +8 -8
- package/dist-vue/_chunks/{PkChatbot-CtrcDgBe.js.map → PkChatbot-CXpftmWm.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotEmptyState-BF3Odn3v.js → PkChatbotEmptyState-vA2v4FES.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotEmptyState-BF3Odn3v.js.map → PkChatbotEmptyState-vA2v4FES.js.map} +1 -1
- package/dist-vue/_chunks/PkChatbotInput-CIIJ1bpF.js +584 -0
- package/dist-vue/_chunks/PkChatbotInput-CIIJ1bpF.js.map +1 -0
- package/dist-vue/_chunks/{PkChatbotMessages-10eBKpC5.js → PkChatbotMessages-15R8RxAq.js} +18 -18
- package/dist-vue/_chunks/{PkChatbotMessages-10eBKpC5.js.map → PkChatbotMessages-15R8RxAq.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotStepPayload-C4ahOq6Z.js → PkChatbotStepPayload-BbNSav-U.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotStepPayload-C4ahOq6Z.js.map → PkChatbotStepPayload-BbNSav-U.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotStepToolDetail-CkIX0aKu.js → PkChatbotStepToolDetail-B_4pmbLe.js} +3 -3
- package/dist-vue/_chunks/{PkChatbotStepToolDetail-CkIX0aKu.js.map → PkChatbotStepToolDetail-B_4pmbLe.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotSteps-BalLo6DZ.js → PkChatbotSteps-h4E6DH_g.js} +5 -5
- package/dist-vue/_chunks/{PkChatbotSteps-BalLo6DZ.js.map → PkChatbotSteps-h4E6DH_g.js.map} +1 -1
- package/dist-vue/_chunks/PkChatbotViewChat-CLQ0J9_f.js +1382 -0
- package/dist-vue/_chunks/PkChatbotViewChat-CLQ0J9_f.js.map +1 -0
- package/dist-vue/_chunks/{PkChatbotViewConversations-D0vDYTyo.js → PkChatbotViewConversations-DFBbypGg.js} +3 -3
- package/dist-vue/_chunks/{PkChatbotViewConversations-D0vDYTyo.js.map → PkChatbotViewConversations-DFBbypGg.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewFiles-BwfAnywk.js → PkChatbotViewFiles-PHdrHZOf.js} +3 -3
- package/dist-vue/_chunks/{PkChatbotViewFiles-BwfAnywk.js.map → PkChatbotViewFiles-PHdrHZOf.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewProfile-GW0WuMOy.js → PkChatbotViewProfile-B0AZvHTr.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotViewProfile-GW0WuMOy.js.map → PkChatbotViewProfile-B0AZvHTr.js.map} +1 -1
- package/dist-vue/_chunks/{PkFilePreview-qizsvSVW.js → PkFilePreview-Cb-1YRPN.js} +616 -666
- package/dist-vue/_chunks/PkFilePreview-Cb-1YRPN.js.map +1 -0
- package/dist-vue/_chunks/{PkFilePreviewDialog-WsVzH9hg.js → PkFilePreviewDialog-Bd7kEoCB.js} +2 -2
- package/dist-vue/_chunks/{PkFilePreviewDialog-WsVzH9hg.js.map → PkFilePreviewDialog-Bd7kEoCB.js.map} +1 -1
- package/dist-vue/_chunks/{PkImageEditorDialog-NQFpdqCU.js → PkImageEditorDialog-Bj4sUHXM.js} +2 -2
- package/dist-vue/_chunks/{PkImageEditorDialog-NQFpdqCU.js.map → PkImageEditorDialog-Bj4sUHXM.js.map} +1 -1
- package/dist-vue/_chunks/{PkStreamingMarkdown-CMxiJTMR.js → PkStreamingMarkdown-BcUq4ThC.js} +3 -3
- package/dist-vue/_chunks/{PkStreamingMarkdown-CMxiJTMR.js.map → PkStreamingMarkdown-BcUq4ThC.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolChatFile-Bd6Ci7i1.js → PkToolChatFile-BOexrlLt.js} +3 -3
- package/dist-vue/_chunks/{PkToolChatFile-Bd6Ci7i1.js.map → PkToolChatFile-BOexrlLt.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolRequestGeolocation-C2OmF31d.js → PkToolRequestGeolocation-CyL_M1Rm.js} +2 -2
- package/dist-vue/_chunks/{PkToolRequestGeolocation-C2OmF31d.js.map → PkToolRequestGeolocation-CyL_M1Rm.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolRequestOAuthConnection-CgD-o99C.js → PkToolRequestOAuthConnection-DWkeVLpx.js} +2 -2
- package/dist-vue/_chunks/{PkToolRequestOAuthConnection-CgD-o99C.js.map → PkToolRequestOAuthConnection-DWkeVLpx.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowArtifact-rlZ-AGWh.js → PkToolShowArtifact-C4gHB6lH.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowArtifact-rlZ-AGWh.js.map → PkToolShowArtifact-C4gHB6lH.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowChart-B8xJi1yY.js → PkToolShowChart-CsPXNAb9.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowChart-B8xJi1yY.js.map → PkToolShowChart-CsPXNAb9.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowContactForm-BVBL7Unx.js → PkToolShowContactForm-2_HBPZaa.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowContactForm-BVBL7Unx.js.map → PkToolShowContactForm-2_HBPZaa.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowDiagram-Bs39QQZ3.js → PkToolShowDiagram-cCbeL6MK.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowDiagram-Bs39QQZ3.js.map → PkToolShowDiagram-cCbeL6MK.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowForm-D-RJeA2F.js → PkToolShowForm-DjB3fji5.js} +4 -4
- package/dist-vue/_chunks/{PkToolShowForm-D-RJeA2F.js.map → PkToolShowForm-DjB3fji5.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowImageGallery-CrkkKCVI.js → PkToolShowImageGallery-C22TCUKW.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowImageGallery-CrkkKCVI.js.map → PkToolShowImageGallery-C22TCUKW.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowProductList-BwfUG41_.js → PkToolShowProductList-BvtmiHBf.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowProductList-BwfUG41_.js.map → PkToolShowProductList-BvtmiHBf.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowSources-q9gQIuam.js → PkToolShowSources-uKO4MQgd.js} +3 -3
- package/dist-vue/_chunks/{PkToolShowSources-q9gQIuam.js.map → PkToolShowSources-uKO4MQgd.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowSuggestedReply-75Kc8-OQ.js → PkToolShowSuggestedReply-wKgwHTRO.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowSuggestedReply-75Kc8-OQ.js.map → PkToolShowSuggestedReply-wKgwHTRO.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowVideo-BK-jDVJd.js → PkToolShowVideo-DKj5N1vo.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowVideo-BK-jDVJd.js.map → PkToolShowVideo-DKj5N1vo.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowWebPages-K3Jml1f7.js → PkToolShowWebPages-BNZmbCSf.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowWebPages-K3Jml1f7.js.map → PkToolShowWebPages-BNZmbCSf.js.map} +1 -1
- package/dist-vue/_chunks/{createChatbotApiClient-Pb7_cU2s.js → createChatbotApiClient-DBKfGL6y.js} +5 -2
- package/dist-vue/_chunks/{createChatbotApiClient-Pb7_cU2s.js.map → createChatbotApiClient-DBKfGL6y.js.map} +1 -1
- package/dist-vue/_chunks/{useChatbotStore-ChrZVIDt.js → useChatbotStore-Hb5EjISl.js} +94 -85
- package/dist-vue/_chunks/useChatbotStore-Hb5EjISl.js.map +1 -0
- package/dist-vue/_chunks/{utils-Bdk5kFfi.js → utils-waie4Gfn.js} +2 -2
- package/dist-vue/_chunks/{utils-Bdk5kFfi.js.map → utils-waie4Gfn.js.map} +1 -1
- package/dist-vue/api.js +1 -1
- package/dist-vue/apps/web-component/src/composables/useChatbotAgent.d.ts +2 -0
- package/dist-vue/composables.js +8 -8
- package/dist-vue/index.js +408 -389
- package/dist-vue/index.js.map +1 -1
- package/dist-vue/locales.js +6 -0
- package/dist-vue/packages/components/src/chat/PkAgentSettingsPanel.d.ts +9 -2
- package/dist-vue/packages/components/src/chat/PkChatbotInput.d.ts +6 -0
- package/dist-vue/packages/composable/src/chatbot/api/createChatbotApiClient.d.ts +5 -0
- package/dist-vue/packages/composable/src/chatbot/useChatbotStore.d.ts +10 -1
- package/dist-vue/packages/models/src/schema/Agent.d.ts +8 -0
- package/dist-vue/packages/models/src/schema/ReasoningChat.d.ts +2 -0
- package/dist-vue/packages/models/src/schema/SubAgent.d.ts +2 -0
- package/dist-vue/packages/models/src/schema/constants.d.ts +11 -2
- package/dist-vue/style.css +1 -1
- package/package.json +1 -1
- package/dist/_chunks/Agent-COa7L9GK.js.map +0 -1
- package/dist-vue/_chunks/Agent-CRwhrv5Z.js.map +0 -1
- package/dist-vue/_chunks/PkChatbotInput-DNXvFvyG.js +0 -520
- package/dist-vue/_chunks/PkChatbotInput-DNXvFvyG.js.map +0 -1
- package/dist-vue/_chunks/PkChatbotViewChat-U6T-gG-c.js +0 -1336
- package/dist-vue/_chunks/PkChatbotViewChat-U6T-gG-c.js.map +0 -1
- package/dist-vue/_chunks/PkFilePreview-qizsvSVW.js.map +0 -1
- package/dist-vue/_chunks/useChatbotStore-ChrZVIDt.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useChatbotStore-Hb5EjISl.js","names":["InvalidArgumentError","name$1","marker$1","symbol$1","InvalidArgumentError","en","EventSourceParserStream$1","parse.parse","parse.parseAsync","parse.safeParse","parse.safeParseAsync","core.clone","core._string","core._number","core._int","core._boolean","core._unknown","core._never","util.normalizeParams","util.extend","core._custom","core._refine","AISDKError$1","DownloadError$1","createIdGenerator$1","enum$1","instanceof$1","null$1","zodSchema$1","APICallError$1","UnsupportedFunctionalityError$1","EmptyResponseBodyError$1","parseJsonEventStream$1","generateId$1","generateId","webPreset","useSWRV","useSWRV","swrv","$ZodObject","_int","_string","_boolean","toJSONSchema","_nonnegative","$ZodBoolean","_unknown","_number","$ZodEnum","$ZodCustom","_positive","_lte","_minLength","_never","$ZodNumberFormat","_refine","unknown$1","safeParseAsync","en_default","$ZodArray","$ZodNever","$ZodLiteral","$ZodNumber","clone","_null","$ZodType","string$1","normalizeParams","parse","safeParseAsync$1","$ZodOptional","object$1","config","number$1","NEVER","_instanceof","$ZodTransform","_custom","custom$1","parseAsync","literal$1","$constructor","$ZodRecord","array$1","$ZodUnion","lazy","$ZodDiscriminatedUnion","$ZodString","boolean$1","$ZodUnknown","$ZodPipe","discriminatedUnion$1","safeParse","extend$1","union$1","own","record$1","installLazyProp","_startsWith","useSafeSessionStorage","useSafeLocalStorage","TOOL_TERMINAL_STATES","CHAT_LIST_WITHOUT_PROJECT","createChatbotApiClient","PageAccessLevel","isUserAnsweredTool","PAGE_TOOL_FEATURES","HOST_TOOL_SOURCE","isReservedHostToolName","pageAccessAllows","hostToolNoAnswerText","isHostToolPart","withAudioTranscripts","getTextPart","logger","collectDeviceContext","connection","uaData","collectGeolocation","resolve","reject","latitude","longitude","accuracy","reverseGeocode","PAGE_NAVIGATION_KEY","isDeferred","value","isHostToolCall","toolCall","declaredHostTools","capability","registry","allowed","declared","tool","_execute","_confirmation","_policy","definition","createHostToolRunner","generation","pending","setPending","deps","tail","inFlight","awaitingResume","letGo","result","needsConfirmation","answer","call","fail","run","isCurrent","callGeneration","candidate","timeoutMs","card","asked","byAgentRules","asks","kept","confirmed","controller","timer","running","aborted","settled","abandon","reached","error","timedOut","marker$18","symbol$18","AISDKError","message","name","cause","markerSymbol","marker","name$16","marker$16","symbol$16","APICallError","statusCode","url","requestBodyValues","responseHeaders","responseBody","isRetryable","data","name$15","marker$15","symbol$15","EmptyResponseBodyError","getErrorMessage","name$11","marker$11","symbol$11","InvalidArgumentError$1","argument","name$8","marker$8","symbol$8","JSONParseError","text","name$1$1","marker$1$1","symbol$1$1","TypeValidationError","contextPrefix","context","parts","symbol","UnsupportedFunctionalityError","functionality","ParseError","options","LF","CR","SPACE","noop","createParser","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","btoa$1","atob$2","typedArrayTag","arrayBufferByteLength","isUint8Array","isArrayBuffer","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","literal","ALPHA_NUMERIC","source","stringifyRegExpWithFlags","regex","flags","pattern","isEscaped","inCharGroup","inCharRange","parseRecordDef","_type","keyType","parseMapDef","parseNativeEnumDef","object","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","ZodMiniType","inst","params","checks","ch","reg","meta","args","fn","ZodMiniString","string","ZodMiniNumber","number","ZodMiniNumberFormat","int","ZodMiniBoolean","boolean","ZodMiniUnknown","unknown","ZodMiniNever","never","ZodMiniArray","array","ZodMiniObject","self","looseObject","extend","ZodMiniUnion","union","ZodMiniDiscriminatedUnion","discriminatedUnion","ZodMiniRecord","record","valueType","ZodMiniEnum","_enum","v","ZodMiniLiteral","ZodMiniTransform","transform","ZodMiniOptional","optional","ZodMiniPipe","pipe","in_","ZodMiniCustom","custom","_params","refine","name$23","marker$23","symbol$23","InvalidArgumentError","parameter","name$5","marker$5","symbol$5","UIMessageStreamError","chunkType","chunkId","mergeObjects","overrides","overridesValue","baseValue","isSourceObject","isTargetObject","fixJson","stack","lastValidIndex","literalStart","unicodeEscapeDigits","isHexDigit","char","processValueStart","swapState","processAfterObjectValue","processAfterArrayValue","partialLiteral","parsePartialJson","jsonText","z$1","z","jsonValueSchema","providerMetadataSchema$1","citationSchema","toolMetadataSchema$1","uiMessageChunkSchema","isDataUIMessageChunk","createIdMap","isStaticToolUIPart","part","isDynamicToolUIPart","isToolUIPart","getStaticToolName","createStreamingUIMessageState","lastMessage","messageId","partialToolCalls","lastStepStartIndex","staticToolIndex","processUIMessageStream","isFirstMessageStart","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","shouldReset","resetStateOnFirstMessageStart","resetStateOnMessageIdChange","dataPartSchema","dataPartSchemas","partIdx","actualPartIdx","dataChunk","existingUIPart","chunkArg","onData","consumeStream","reader","cancelOnAbort","abortSignal","done","createResolvablePromise","rej","findInvalidJsonValuePath","path","visited","keys","invalidPath","withJsonValueCheck","jsonValue","jsonValuePath","atob$1","SerialJobExecutor","job","fileInlineDataSchema","providerReferenceSchema","textPartSchema","imagePartSchema","taggedFileDataSchema","taggedReasoningFileDataSchema","filePartSchema","reasoningPartSchema","customPartSchema","reasoningFilePartSchema","toolCallPartSchema","outputSchema","toolResultPartSchema","toolApprovalRequestSchema","toolApprovalResponseSchema","systemModelMessageSchema","userModelMessageSchema","assistantModelMessageSchema","toolModelMessageSchema","createUIApiCallError","response","fallbackMessage","convertFileListToFileUIParts","files","file","readerEvent","appendPathToUrl","queryOrFragmentStart","urlPath","suffix","HttpChatTransport","api","credentials","body","fetch","prepareSendMessagesRequest","prepareReconnectToStreamRequest","resolvedBody","resolvedHeaders","resolvedCredentials","baseHeaders","preparedRequest","DefaultChatTransport","resumeStreamIsReplay","AbstractChat","generateId$3","queued","stopGeneration","pendingApprovalMessageIndex","uiMessage","abortController","fileParts","queuedMessage","messageIndex","m","activeResponse","shouldResume","messages","updatePart","shouldSend","existingApproval","toolPart","activeResumeRequest","transport","onFinish","sendAutomaticallyWhen","experimental_queue","status","experimental_queuedMessages","deferredApprovalSend","skipWaitForUser","isInterrupted","startedWhileStopping","request","consumesPendingApproval","completion","trigger","isCurrentRequest","clearActiveResumeRequest","resumeStream","reconnect","err","responseMessageIndex","responseMessage","originalResponseMessageId","resumableResponseMessage","usesEarlierAssistantMessage","isAbort","isDisconnect","isError","updateStatus","existingMessageIndex","originalMessageIndex","finishReason","lastAssistantMessageIsCompleteWithApprovalResponses","lastIndex","lastStepToolInvocations","table","counter","hash","_hash","serializeKeyDefault","SWRVCache","ttl","_key","k","timeToLive","now","_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","unmounted","isHydrated","getCurrentScope","IS_SERVER","keyRef","ref","reactive","revalidate","isFirstFetch","keyVal","cacheItem","fetcher","shouldRevalidate","opts","promiseFromCache","fetcherArgs","newPromise","configAllows","optsAllows","shouldRetryOnError","revalidateCall","tick_1","isReadonly","val","toRefs","esm_default","cloneMetadata","snapshotValue","snapshot","VueChatState","initialMessages","messagesRef","statusRef","errorRef","queuedMessagesRef","throttleWaitMs","previousMessages","publishedMessages","VueChat","init","useChat","shallowRef","chatInstance","chatState","watch","messageList","toValue","chatInit","nextChatState","throttle","onScopeDispose","computed","VOICE_LINE_ID_PREFIX","VOICE_RESULT_SEND_MS","awaitsApproval","normalizeSpoken","spokenText","SHORTEST_MATCHABLE_LINE","unpersistedVoiceLines","onScreen","shown","server","persisted","match","other","FOLLOW_TURN_TIMEOUT_MS","FOLLOW_TURN_RETRY_MS","RUNNING_TURNS_POLL_MS","RUNNING_TURNS_MAX_IDS","BACKGROUND_START_GRACE_MS","QUEUE_WRITE_WAIT_MS","QUEUE_WRITE_RETRY_MS","QUEUE_WRITE_ASK_MS","QUEUE_SEPARATOR","partToolName","awaitsToolAnswer","lastAssistantMessageIsCompleteWithAnsweredClientTools","last","userAnsweredParts","useChatbotStore","defineStore","agentId","useI18n","baseUrl","basePath","agentIdRef","agentType","userId","agentInterface","agentModel","agentTools","revisedAnswers","model","actionsInput","agentFileUpload","agentVoice","fallbackModels","gatewayOptions","externalContext","agentHostTools","hostToolRegistry","hostToolsPending","voicePageCallsPending","agentPageAccess","agentConfirmations","agentSelectionActions","pageToolRegistry","pageFormsProvider","pageAction","pagePointer","pagePointerStart","pagePointing","hostStepTitles","hostStepChanges","pageControlActive","requestCount","systemTheme","hideWelcomeMessage","prefersDark","usePreferredDark","isDark","theme","isReasoningAgent","actions","action","storageId","localChatId","pageAccessOff","activePageTools","pageForms","pageAccessAvailable","confirmationChoice","confirmationsAvailable","confirmationMode","setConfirmationMode","mode","pagePointerAvailable","available","pageNoticeClosedAt","pageNoticeLevel","level","closePageNotice","chatError","isConversationBlocked","isConversationBlockedError","isEntityNotFoundError","parsed","handleChatError","isReadOnlyChat","pendingMessages","chat","lastUserMessage","lastUserText","nextTick","apiClient","storedGeolocation","buildDeviceContext","waitForResume","startedBefore","stop","hostConfirmation","askHostConfirmation","confirmation","approved","respondHostConfirmation","reportSkippedCard","detail","declarePageTools","forms","showPageActivity","described","hostToolRunner","output","voicePageCalls","voicePageCallCount","settleVoicePageCall","settle","voicePageToolRunner","current","voiceCallConfirmationMode","voicePageTools","declaration","parameters","lastChatMessage","cancelVoicePageCalls","stopHostActions","cancelHostCalls","setPageAccessOff","off","isResumingTurn","followedTurn","followedChatId","turnStreamId","serverRunningChatIds","backgroundTurns","answeredInBackground","backgroundQuestions","backgroundLeftAt","seenRunning","noteBackgroundTurn","chatId","started","question","runningTurnsTimer","scheduleRunningTurns","forgetBackgroundQuestion","forgetBackgroundTurn","chatHelpers","msgs","newChatProjectOf","conversations","c","loadConversations","leftChatId","isTurnInFlight","questions","workingTimer","initialMessageResolved","locale","te","welcomeMessageId","welcomeMessage","resolveInFlight","msg","fp","storedFileName","chatMessages","inputMessagePlaceholder","projectsEnabled","chatOwnership","describeChat","details","ownershipOf","chatAuthorId","chatProjectId","ownership","conversationListFilter","isLoadingConversations","conversationsPage","hasMoreConversations","isLoadingMoreConversations","conversationsOwner","chatFiles","isLoadingChatFiles","activeView","inputFocusRequest","messageFeedbacks","feedbackDialogMessage","isFeedbackSubmitting","isFeedbackSubmitted","feedbackSubmitError","isLeadSubmitted","isLoadingSubmitLead","submitLeadError","pendingAttachments","lastSubmittedInput","lastSubmittedToInput","lastSubmittedPointer","messageCountBeforeSubmit","queues","queuedMessages","canQueue","setQueue","others","takeQueue","restoreInput","removeQueuedMessage","editQueuedMessage","listed","listedIds","leftRunning","owner","leftRunningIds","older","watchedTurns","conversation","loadMoreConversations","page","known","searchConversations","loadChatFiles","getChatFileUrl","documentId","inline","getChatFilePreviewUrl","deleteChatFile","removed","rootId","loadChat","continueAfterLoad","turnInProgress","followTurn","resumeAfterPageNavigation","flushQueue","turn","isFollowing","deadline","clickedAt","attempt","open","reads","isTurnBusy","awaitsUser","flushingChats","submitTurn","refreshSequence","refreshApplied","refreshMessages","mine","appendMessage","loadMessageFeedbacks","upsertLocalFeedback","feedback","extractFeedbackContext","msgList","assistantMessage","prevUser","initialize","lat","lon","geo","handleSubmit","att","pointer","startNewChat","clearPendingAttachments","sendSelection","trimmed","toInput","sendMessage","send","answerCalledHost","submittedText","submittedToInput","submittedPointer","shouldRollback","countBeforeSubmit","wasFollowing","streamId","queuedText","restoreInputAfterStop","movedOn","stopped","waiting","pageControlTimer","voicePending","isWorking","busy","runningChatIds","documentVisibility","useDocumentVisibility","runningTurnsSequence","runningTurnsApplied","refreshRunningTurns","suggestNextMessage","askedIds","chatIds","absent","unstarted","expired","ended","endedInBackground","visibility","backgroundAnswers","openBackgroundAnswer","navigate","dismissBackgroundAnswer","previous","previousId","revokeAll","projectId","regenerate","addToolOutput","addToolApprovalResponse","sentFileCount","maxFilesPerMessage","maxFilesPerChat","remainingAttachmentSlots","isAttachmentLimitReached","fileLimitError","clearFileLimitError","handleFileSelect","attachment","newPendingAttachment","uploadPendingAttachment","replacePendingAttachment","replaced","discardPendingAttachment","retryPendingAttachment","failed","mediaSource","discardUpload","submitVote","onUpvote","onDownvote","onFeedback","onFeedbackSubmit","onLeadSubmit","renameChatTitle","updated","deleteChat","view","focusInput","boundUserId","readChatAsNewUser","probe","newUserId","previousUserId","verifiedChatId","readable"],"sources":["../../../../packages/utils/src/device-context.ts","../../../../packages/composable/src/chatbot/hostTools.ts","../../../../node_modules/.pnpm/@ai-sdk+provider@4.0.38/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.81_zod@4.6.7/node_modules/@ai-sdk/provider-utils/dist/index.js","../../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/mini/schemas.js","../../../../node_modules/.pnpm/ai@7.0.173_zod@4.6.7/node_modules/ai/dist/index.js","../../../../node_modules/.pnpm/swrv@1.2.0_vue@3.5.45_typescript@6.0.3_/node_modules/swrv/esm/lib/hash.js","../../../../node_modules/.pnpm/swrv@1.2.0_vue@3.5.45_typescript@6.0.3_/node_modules/swrv/esm/cache/index.js","../../../../node_modules/.pnpm/swrv@1.2.0_vue@3.5.45_typescript@6.0.3_/node_modules/swrv/esm/lib/web-preset.js","../../../../node_modules/.pnpm/swrv@1.2.0_vue@3.5.45_typescript@6.0.3_/node_modules/swrv/esm/use-swrv.js","../../../../node_modules/.pnpm/swrv@1.2.0_vue@3.5.45_typescript@6.0.3_/node_modules/swrv/esm/index.js","../../../../node_modules/.pnpm/@ai-sdk+vue@4.0.173_vue@3.5.45_typescript@6.0.3__zod@4.6.7/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","import {\n HOST_TOOL_REFUSED_TEXT,\n HOST_TOOL_SOURCE,\n hostToolNoAnswerText,\n isReservedHostToolName,\n type HostToolDefinition,\n type HostToolResult,\n type HostToolsCapability,\n} from 'models'\n\n/**\n * A tool the host registered, in the shape of WebMCP's\n * `navigator.modelContext.registerTool`: the MCP definition plus the function\n * that runs it (spec `host-tools.md`).\n */\nexport type RegisteredHostTool = HostToolDefinition & {\n execute: (\n input: unknown,\n options: { signal: AbortSignal; callId: string; messageId: string },\n ) => Promise<HostToolResult | HostToolDeferredResult>\n /**\n * A tool the widget itself provides (the page tools of spec\n * `page-tools.md`) carries its own policy, and does not depend on the\n * agent's host tool settings.\n */\n policy?: { timeoutMs: number }\n /**\n * Decides per call whether the user confirms first: the question to ask\n * (or the whole card), or nothing. On the widget's own tools (with a\n * `policy`) it replaces the agent's rules for the tool. On a host's tool\n * it can only add a confirmation: the agent's rules still ask when the\n * question is nothing.\n */\n confirmation?: (input: unknown) => string | HostToolConfirmation | undefined\n /**\n * What a step of this call says it does, naming its target (\"Clicking\n * “Create”\"): the control bar and the chat show it while the page is open\n * (spec `page-tools-improvements.md`, M8). Never a value the call writes.\n */\n describe?: (input: unknown) => string | undefined\n}\n\n/**\n * The confirmation card of a call (spec `page-tools-improvements.md`, M2).\n * It stays in the browser: neither the details nor the question reach the\n * backend, the model or the saved chat.\n */\nexport type HostToolConfirmation = {\n question: string\n /**\n * Lines under the question. With `before` they are changes, shown as a\n * table of what each field was and becomes (a submit's fields the agent\n * changed); without, plain label and value.\n */\n details?: { label: string; value: string; before?: string }[]\n /** The fields a submit sends unchanged, folded under the details. */\n unchanged?: { label: string; value: string }[]\n /** What the model reads when the user says no, in place of the plain refusal. */\n refusal?: string\n /**\n * Asks whatever confirmations the user chose (spec\n * `auto-confirmations.md`): a deletion, the site's own \"are you sure?\",\n * an element the site marks, leaving the site. Without it, a card the\n * automatic confirmations may skip.\n */\n keep?: boolean\n}\n\n/** The confirmations the user chose in the chat (spec `auto-confirmations.md`). */\nexport type ConfirmationMode = 'manual' | 'automatic'\n\n/** `card` as one that asks whatever confirmations the user chose. */\nexport const alwaysAsked = (\n card: string | HostToolConfirmation,\n): HostToolConfirmation => ({\n ...(typeof card === 'string' ? { question: card } : card),\n keep: true,\n})\n\n/**\n * A tool a page registers on the element, as the registry keeps it: the\n * public fields only. `policy` belongs to the widget's own tools, so a page\n * can neither lift the agent's timeout nor replace its confirmations. The\n * functions are called on the page's own object, so a tool written as a class\n * instance keeps its `this`.\n */\nexport const hostToolFromPage = (\n tool: RegisteredHostTool,\n): RegisteredHostTool => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n annotations: tool.annotations,\n execute: (input, options) => tool.execute(input, options),\n confirmation:\n typeof tool.confirmation === 'function'\n ? (input) => tool.confirmation?.(input)\n : undefined,\n})\n\n/**\n * A result whose effect must wait until the backend holds it: a click that\n * may unload the page runs only once the resume carrying this result has\n * reached the backend, or the page would leave before the answer could.\n */\nexport type HostToolDeferredResult = {\n result: HostToolResult\n afterOutput: () => void\n /**\n * Called instead of `afterOutput` when the effect will never run: the\n * resume did not reach the backend, or the user stopped the agent. What\n * the call held for later is dropped there.\n */\n abandon?: () => void\n}\n\n/**\n * Set by a page click that may unload the page, read by the widget on the\n * next page (spec `page-tools.md`): the answer that clicked goes on there.\n */\nexport const PAGE_NAVIGATION_KEY = 'agentstudio:page-navigation'\n\n/**\n * Null-safe: a host `execute` may resolve anything, and whatever is not a\n * result must reach the backend as it is, to be refused there as \"not a tool\n * result\", not turn into a TypeError here.\n */\nconst isDeferred = (\n value: HostToolResult | HostToolDeferredResult,\n): value is HostToolDeferredResult =>\n typeof (value as HostToolDeferredResult | null)?.afterOutput === 'function'\n\n/** A host call as the stream announced it. */\nexport type HostToolCall = {\n toolCallId: string\n toolName: string\n input: unknown\n messageId: string\n readOnly: boolean\n provider?: 'app' | 'page'\n}\n\ntype HostToolOutput =\n | { tool: string; toolCallId: string; output: HostToolResult }\n | {\n tool: string\n toolCallId: string\n state: 'output-error'\n errorText: string\n }\n\n/** True for the `onToolCall` argument of a call the backend stamped as a host call. */\nexport const isHostToolCall = (toolCall: unknown): boolean =>\n (toolCall as { toolMetadata?: { source?: unknown } }).toolMetadata\n ?.source === HOST_TOOL_SOURCE\n\n/**\n * The definitions a request declares: the registered tools the agent allows,\n * without their `execute`. Nothing when the agent has host tools off.\n */\nexport const declaredHostTools = (\n registry: readonly RegisteredHostTool[] | undefined,\n capability: HostToolsCapability | undefined,\n): HostToolDefinition[] | undefined => {\n if (!capability || !registry?.length) {\n return undefined\n }\n const allowed = new Set(capability.allowed)\n const declared = registry\n .filter(\n (tool) =>\n allowed.has(tool.name) && !isReservedHostToolName(tool.name),\n )\n .map(\n ({\n execute: _execute,\n confirmation: _confirmation,\n policy: _policy,\n ...definition\n }) => definition,\n )\n return declared.length > 0 ? declared : undefined\n}\n\n/**\n * Runs host calls one at a time, in the order the stream announced them.\n *\n * `enqueue` returns at once: the SDK awaits `onToolCall` before it reads the\n * rest of the stream, and `addToolOutput` goes through the same job queue of\n * the `Chat`, so awaiting the host there would stall the stream and awaiting\n * the output would deadlock. One at a time because writes to a document depend\n * on their order, and a model can emit several calls in one step.\n *\n * `cancelAll` is for the stop, and for any message the user sends while a call\n * is pending: the request that announced the call has ended, so the chat looks\n * ready and the user can move on. It bumps the generation, so a result that\n * lands afterwards is dropped, and aborts the calls in flight. It adds no\n * output: an output after the stop would resume the turn through\n * `sendAutomaticallyWhen`. The backend closes those calls on the next message.\n *\n * `onPendingChange` reports the calls queued or running: while there are any\n * the chat is busy, whatever the status of its last request says.\n */\nexport function createHostToolRunner(deps: {\n registry: () => readonly RegisteredHostTool[] | undefined\n capability: () => HostToolsCapability | undefined\n addToolOutput: (output: HostToolOutput) => void\n /**\n * Asks the user. `confirmation` is the tool's own card (a page click\n * names what it clicks, a submit lists its fields); without one the card\n * asks about the call by its title.\n */\n confirm: (\n call: HostToolCall,\n confirmation?: HostToolConfirmation,\n ) => Promise<boolean>\n /** Resolves true once the resume that carries the last output reached the backend. */\n waitForResume: () => Promise<boolean>\n onPendingChange?: (pending: number) => void\n /** The call starting, or `undefined` when it ends: what the page control bar shows. */\n onActivity?: (call: HostToolCall | undefined) => void\n /**\n * The confirmations the user chose (spec `auto-confirmations.md`): in\n * automatic, a card that does not keep its question is not shown, and the\n * call runs as if the user had said yes. A card already waiting stays.\n */\n mode?: () => ConfirmationMode\n /** A card the automatic mode skipped: what the call's step reports of it. */\n onSkip?: (call: HostToolCall, card: HostToolConfirmation) => void\n}) {\n let generation = 0\n let pending = 0\n const setPending = (value: number) => {\n pending = value\n deps.onPendingChange?.(pending)\n }\n let tail: Promise<void> = Promise.resolve()\n const inFlight = new Map<string, AbortController>()\n /**\n * What answered calls still hold until their resume (a navigation of the\n * page): a stop lets it go at once, not when the wait for a resume that\n * will never come runs out.\n */\n const awaitingResume = new Set<() => void>()\n\n /** A result nobody will deliver: what it holds is let go. */\n const letGo = (result: HostToolResult | HostToolDeferredResult) => {\n if (isDeferred(result)) {\n result.abandon?.()\n }\n }\n\n const needsConfirmation = (\n tool: RegisteredHostTool,\n capability: HostToolsCapability,\n ): boolean =>\n capability.requireConfirmation.includes(tool.name) ||\n (capability.confirmDestructive &&\n tool.annotations?.destructiveHint === true)\n\n // Two closings and not one taking either: a host may resolve a string,\n // which is not a tool result and must reach the backend as one, to be\n // refused there, not be read as the error text of a write that landed.\n const answer = (call: HostToolCall, output: HostToolResult) =>\n deps.addToolOutput({\n tool: call.toolName,\n toolCallId: call.toolCallId,\n output,\n })\n const fail = (call: HostToolCall, errorText: string) =>\n deps.addToolOutput({\n tool: call.toolName,\n toolCallId: call.toolCallId,\n state: 'output-error',\n errorText,\n })\n\n async function run(call: HostToolCall, callGeneration: number) {\n const isCurrent = () => callGeneration === generation\n const capability = deps.capability()\n const tool = deps\n .registry()\n ?.find((candidate) => candidate.name === call.toolName)\n const timeoutMs = tool?.policy?.timeoutMs ?? capability?.timeoutMs\n if (!tool || timeoutMs === undefined) {\n fail(call, hostToolNoAnswerText(call.readOnly))\n return\n }\n let card: HostToolConfirmation | undefined\n try {\n const asked: unknown = tool.confirmation?.(call.input)\n // A page's tool may answer anything: a card only from a string\n // or from an object that has its question\n card =\n typeof asked === 'string'\n ? { question: asked }\n : typeof (asked as HostToolConfirmation | null)\n ?.question === 'string'\n ? (asked as HostToolConfirmation)\n : undefined\n } catch {\n // Thrown here, the call would never get an answer and the turn\n // would wait on it: a call nobody could judge does not run.\n fail(call, 'The host app could not prepare this call.')\n return\n }\n const byAgentRules =\n capability !== undefined && needsConfirmation(tool, capability)\n const asks =\n tool.policy && tool.confirmation\n ? card !== undefined\n : card !== undefined || byAgentRules\n // In automatic only what asks whatever the mode: a card that keeps its\n // question, and a host's own tool the agent asks about that says it\n // destroys something. What the tool checks after a yes still runs\n const kept =\n card?.keep === true ||\n (!tool.policy &&\n byAgentRules &&\n tool.annotations?.destructiveHint === true)\n if (asks && !kept && deps.mode?.() === 'automatic') {\n if (card) {\n deps.onSkip?.(call, card)\n }\n } else if (asks) {\n const confirmed = await deps.confirm(call, card)\n if (!isCurrent()) {\n return\n }\n if (!confirmed) {\n fail(call, card?.refusal ?? HOST_TOOL_REFUSED_TEXT)\n return\n }\n }\n\n const controller = new AbortController()\n inFlight.set(call.toolCallId, controller)\n deps.onActivity?.(call)\n const timer = setTimeout(\n () => controller.abort(new Error('timeout')),\n timeoutMs,\n )\n let running:\n Promise<HostToolResult | HostToolDeferredResult> | undefined\n try {\n const aborted = new Promise<never>((_, reject) => {\n controller.signal.addEventListener(\n 'abort',\n () => reject(controller.signal.reason),\n { once: true },\n )\n })\n running = Promise.resolve(\n tool.execute(call.input, {\n signal: controller.signal,\n callId: call.toolCallId,\n messageId: call.messageId,\n }),\n )\n const result = await Promise.race([running, aborted])\n if (!isCurrent()) {\n letGo(result)\n return\n }\n if (isDeferred(result)) {\n answer(\n call,\n result.result ?? (null as unknown as HostToolResult),\n )\n let settled = false\n const abandon = () => {\n if (!settled) {\n settled = true\n awaitingResume.delete(abandon)\n result.abandon?.()\n }\n }\n awaitingResume.add(abandon)\n // Not awaited: the queue moves on, and a stop in between\n // (generation bumped) cancels the effect.\n void deps.waitForResume().then((reached) => {\n if (settled) {\n return\n }\n if (reached && isCurrent()) {\n settled = true\n awaitingResume.delete(abandon)\n result.afterOutput()\n } else {\n abandon()\n }\n })\n } else {\n // `undefined` would vanish from the JSON of the resume and\n // leave the call open: `null` reaches the backend, which\n // refuses it as not a tool result.\n answer(call, result ?? (null as unknown as HostToolResult))\n }\n } catch (error) {\n // Given up before it answered (a stop, a timeout, another chat):\n // what it holds once it does has nobody to deliver it\n void running?.then(letGo, () => undefined)\n if (!isCurrent()) {\n return\n }\n // A timeout says nothing about a write: it may have landed.\n const timedOut = controller.signal.aborted\n fail(\n call,\n timedOut\n ? hostToolNoAnswerText(call.readOnly)\n : error instanceof Error && error.message\n ? error.message\n : 'The host app failed to run this call.',\n )\n } finally {\n clearTimeout(timer)\n inFlight.delete(call.toolCallId)\n deps.onActivity?.(undefined)\n }\n }\n\n return {\n enqueue(call: HostToolCall) {\n const callGeneration = generation\n setPending(pending + 1)\n tail = tail\n .then(() =>\n callGeneration === generation\n ? run(call, callGeneration)\n : undefined,\n )\n .catch(() => undefined)\n .then(() => {\n if (callGeneration === generation) {\n setPending(pending - 1)\n }\n })\n },\n cancelAll() {\n generation++\n setPending(0)\n for (const abandon of [...awaitingResume]) {\n abandon()\n }\n for (const controller of inFlight.values()) {\n controller.abort(new Error('cancelled'))\n }\n inFlight.clear()\n },\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$18 = \"vercel.ai.error\";\nconst symbol$18 = Symbol.for(marker$18);\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$18] = 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$18);\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$17 = \"AI_DecisionUnsupportedQuestionTypeError\";\nconst marker$17 = `vercel.ai.error.${name$17}`;\nconst symbol$17 = Symbol.for(marker$17);\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$17,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$17] = 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$17);\n\t}\n};\n//#endregion\n//#region src/errors/api-call-error.ts\nconst name$16 = \"AI_APICallError\";\nconst marker$16 = `vercel.ai.error.${name$16}`;\nconst symbol$16 = Symbol.for(marker$16);\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$16,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[symbol$16] = 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$16);\n\t}\n};\n//#endregion\n//#region src/errors/empty-response-body-error.ts\nconst name$15 = \"AI_EmptyResponseBodyError\";\nconst marker$15 = `vercel.ai.error.${name$15}`;\nconst symbol$15 = Symbol.for(marker$15);\nvar EmptyResponseBodyError = class extends AISDKError {\n\tconstructor({ message = \"Empty response body\" } = {}) {\n\t\tsuper({\n\t\t\tname: name$15,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$15] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$15);\n\t}\n};\n//#endregion\n//#region src/errors/decision-refusal-error.ts\nconst name$14 = \"AI_DecisionRefusalError\";\nconst marker$14 = `vercel.ai.error.${name$14}`;\nconst symbol$14 = Symbol.for(marker$14);\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$14,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$14] = 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$14);\n\t}\n};\n//#endregion\n//#region src/errors/extraction-refusal-error.ts\nconst name$13 = \"AI_ExtractionRefusalError\";\nconst marker$13 = `vercel.ai.error.${name$13}`;\nconst symbol$13 = Symbol.for(marker$13);\n/**\n* An extraction model declined to extract one or more fields.\n*/\nvar ExtractionRefusalError = class extends AISDKError {\n\tconstructor({ fieldIds, provider, modelId, message = `Extraction model \"${modelId}\" from provider \"${provider}\" refused ${fieldIds.length === 1 ? \"field\" : \"fields\"} ${fieldIds.map((id) => JSON.stringify(id)).join(\", \")}.` }) {\n\t\tsuper({\n\t\t\tname: name$13,\n\t\t\tmessage\n\t\t});\n\t\tthis[symbol$13] = true;\n\t\tthis.fieldIds = fieldIds;\n\t\tthis.provider = provider;\n\t\tthis.modelId = modelId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker$13);\n\t}\n};\n//#endregion\n//#region src/errors/extraction-unsupported-field-type-error.ts\nconst name$12 = \"AI_ExtractionUnsupportedFieldTypeError\";\nconst marker$12 = `vercel.ai.error.${name$12}`;\nconst symbol$12 = Symbol.for(marker$12);\n/**\n* An extraction model does not support the type of a requested field.\n*/\nvar ExtractionUnsupportedFieldTypeError = class extends AISDKError {\n\tconstructor({ fieldId, fieldType, provider, modelId, message = `Field \"${fieldId}\" has type \"${fieldType}\", which is not supported by provider \"${provider}\" and model \"${modelId}\".` }) {\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.fieldId = fieldId;\n\t\tthis.fieldType = fieldType;\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, ExtractionRefusalError as Experimental_ExtractionRefusalError, ExtractionUnsupportedFieldTypeError as Experimental_ExtractionUnsupportedFieldTypeError, 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 { config, toJSONSchema } from \"zod/v4/core\";\nimport en from \"zod/v4/locales/en.js\";\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\tconst bytes = new Uint8Array(latin1string.length);\n\tfor (let i = 0; i < latin1string.length; i++) bytes[i] = latin1string.charCodeAt(i);\n\treturn bytes;\n}\nfunction convertUint8ArrayToBase64(array) {\n\tif (typeof globalThis.Buffer?.from === \"function\") return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString(\"base64\");\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}\nconst typedArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;\nconst arrayBufferByteLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, \"byteLength\").get;\nfunction isUint8Array(value) {\n\treturn ArrayBuffer.isView(value) && typedArrayTag.call(value) === \"Uint8Array\";\n}\nfunction isArrayBuffer(value) {\n\tif (typeof value !== \"object\" || value === null || !(\"byteLength\" in value)) return false;\n\ttry {\n\t\tarrayBufferByteLength.call(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction convertToBase64(value) {\n\treturn isUint8Array(value) ? 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 (isUint8Array(data.data)) return new Uint8Array(data.data.buffer, data.data.byteOffset, data.data.byteLength);\n\tif (isArrayBuffer(data.data)) 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.81\";\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\tif (!Object.prototype.hasOwnProperty.call(topLevelSignatureTables, topLevelType)) return;\n\treturn detectMediaTypeBySignatures({\n\t\tdata,\n\t\tsignatures: topLevelSignatureTables[topLevelType]\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/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/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* This function performs string/literal-IP checks only. DNS validation must\n* be provided by the fetch transport or network egress controls.\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\") || hostname.endsWith(\".internal\")) 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}\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/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]);\n/**\n* Fetches one validated URL without following redirects.\n*\n* Uses the supplied fetch or the runtime's global fetch. URL validation does\n* not resolve DNS; inject a transport such as guarded-fetch on Node.js\n* when connection-time DNS validation is needed.\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\", requireDnsValidation = false }) {\n\tconst urlText = url.toString();\n\tif (!(trustedOrigin !== void 0 && isSameOrigin(urlText, trustedOrigin))) {\n\t\tvalidateDownloadUrl(urlText);\n\t\tif (requireDnsValidation && (customFetch == null || customFetch === globalThis.fetch) && !(isBrowserRuntime() && typeof document !== \"undefined\")) throw new DownloadError({\n\t\t\turl: urlText,\n\t\t\tmessage: \"This server runtime requires a custom fetch with connect-time DNS validation for untrusted URLs\"\n\t\t});\n\t}\n\treturn await (customFetch ?? globalThis.fetch)(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* Manually followed redirects from HTTPS to HTTP are rejected before requesting\n* the target.\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* URL validation does not resolve DNS. Use guarded-fetch on Node.js\n* for connection-time DNS validation, or enforce network egress restrictions.\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\tif (!(trustedOrigin !== void 0 && isSameOrigin(currentUrl, trustedOrigin))) validateDownloadUrl(currentUrl);\n\t\tconst fetch = customFetch ?? globalThis.fetch;\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 (new URL(currentUrl).protocol === \"https:\" && new URL(nextUrl).protocol === \"http:\") throw new DownloadError({\n\t\t\t\turl,\n\t\t\t\tmessage: \"Redirect from HTTPS to HTTP was blocked\"\n\t\t\t});\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, runtime fetch transport, redirect\n* limits, and cross-origin header stripping of {@link fetchWithValidatedRedirects}.\n* Inject guarded-fetch on Node.js for 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* @param onChunk - Optional. Receives each chunk instead of the chunks being\n* collected, so the body is not held in memory, and the returned array is empty.\n* The chunk may be a view on a larger buffer, copy what you keep.\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, onChunk }) {\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\tif (onChunk != null) {\n\t\t\t\tonChunk(value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchunks.push(value.byteLength < value.buffer.byteLength ? new Uint8Array(value) : 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(onChunk != null ? 0 : 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* @param options.fetch - Fetch transport, e.g. guarded-fetch for DNS validation on Node.js.\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\tfetch: options?.fetch\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/encode-path-segment.ts\n/**\n* Encodes a raw identifier as one URL path segment, including standalone dot\n* segments that URL parsers would otherwise normalize. Pass unencoded values;\n* for resource paths with intentional slashes, encode each segment separately.\n*/\nfunction encodePathSegment(value) {\n\tconst encodedValue = encodeURIComponent(value);\n\treturn encodedValue === \".\" ? \"%252E\" : encodedValue === \"..\" ? \"%252E%252E\" : encodedValue;\n}\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 && !isUint8Array(data) && !(data instanceof URL) && !isArrayBuffer(data) && !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\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\n/**\n* Reasoning levels in ascending order.\n*/\nconst REASONING_LEVELS = [\n\t\"minimal\",\n\t\"low\",\n\t\"medium\",\n\t\"high\",\n\t\"xhigh\",\n\t\"max\"\n];\nfunction isCustomReasoning(reasoning) {\n\treturn reasoning !== void 0 && reasoning !== \"provider-default\";\n}\n/**\n* Maps a top-level reasoning value to a provider-specific effort string.\n*\n* A `providerOptionsEffort` (the reasoning effort set in provider options) is\n* returned unchanged. Otherwise, `undefined` and `'provider-default'` return\n* `undefined`, and other reasoning values are mapped with the effort map.\n*\n* The effort map should only contain the values that the model supports. An\n* unsupported value maps to the next lower supported level, or the next higher\n* one if there is no lower level. `'none'` is never used as a fallback, so an\n* unsupported `'none'` maps to the lowest supported level.\n*\n* Pushes a compatibility warning if the effort that is sent differs from the\n* requested value, or an unsupported warning if the effort map is empty.\n*\n* @returns The provider options effort, the mapped effort string, or\n* `undefined` if no effort should be sent.\n*/\nfunction mapReasoningToProviderEffort({ reasoning, effortMap, providerOptionsEffort, warnings }) {\n\tif (providerOptionsEffort != null) return providerOptionsEffort;\n\tif (!isCustomReasoning(reasoning)) return;\n\tconst index = REASONING_LEVELS.indexOf(reasoning);\n\tconst level = [\n\t\treasoning,\n\t\t...REASONING_LEVELS.slice(0, Math.max(index, 0)).reverse(),\n\t\t...REASONING_LEVELS.slice(index + 1)\n\t].find((candidate) => effortMap[candidate] != null);\n\tif (level == 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\tconst mapped = effortMap[level];\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 value to an absolute token budget by multiplying\n* the model's max output tokens by a percentage for the level. Levels missing\n* from `budgetPercentages` use the default percentages. The result is clamped\n* between `minReasoningBudget` (default 1024) and `maxReasoningBudget`.\n*\n* Handle `'none'` before calling this function when the model can disable\n* reasoning. Otherwise, `'none'` maps to `minReasoningBudget` with a\n* compatibility warning.\n*\n* @returns The computed token budget.\n*/\nfunction mapReasoningToProviderBudget({ reasoning, maxOutputTokens, maxReasoningBudget, minReasoningBudget = 1024, budgetPercentages, warnings }) {\n\tif (reasoning === \"none\") {\n\t\twarnings.push({\n\t\t\ttype: \"compatibility\",\n\t\t\tfeature: \"reasoning\",\n\t\t\tdetails: `reasoning \"none\" is not supported by this model. mapped to the minimum reasoning budget of ${minReasoningBudget} tokens.`\n\t\t});\n\t\treturn minReasoningBudget;\n\t}\n\tconst percentage = budgetPercentages?.[reasoning] ?? DEFAULT_REASONING_BUDGET_PERCENTAGES[reasoning];\n\treturn Math.min(maxReasoningBudget, Math.max(minReasoningBudget, Math.round(maxOutputTokens * percentage)));\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\tif (!config().localeError) config(en());\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/resolve-provider-options.ts\n/**\n* Parses provider options that a model accepts under more than one\n* `providerOptions` namespace, e.g. a canonical key plus a provider-specific\n* or legacy alias.\n*\n* Each present namespace is validated against `schema` exactly like\n* `parseProviderOptions` does, so an invalid namespace throws.\n*\n* @returns the resolved options (`undefined` when no namespace is present)\n* and the namespaces that contributed to them, in resolution order.\n*/\nasync function resolveProviderOptions({ providerOptions, namespaces, resolution, schema }) {\n\tconst parsed = [];\n\tconst matched = [];\n\tfor (const namespace of new Set(namespaces)) {\n\t\tconst options = await parseProviderOptions({\n\t\t\tprovider: namespace,\n\t\t\tproviderOptions,\n\t\t\tschema\n\t\t});\n\t\tif (options == null) continue;\n\t\tif (resolution === \"first\") return {\n\t\t\toptions,\n\t\t\tnamespaces: [namespace]\n\t\t};\n\t\tparsed.push(options);\n\t\tmatched.push(namespace);\n\t}\n\treturn {\n\t\toptions: parsed.length === 0 ? void 0 : Object.assign({}, ...parsed),\n\t\tnamespaces: matched\n\t};\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/telemetry-redaction.ts\nconst telemetryRedaction = Symbol.for(\"vercel.ai.telemetry.redact\");\n/**\n* Attach a provider-owned telemetry view without changing the original value.\n* The annotation is not serialized or included in enumerable application data.\n* Keep the annotated object when forwarding tool arguments or provider metadata.\n*/\nfunction withTelemetryRedaction(value, redact) {\n\treturn Object.create(Object.getPrototypeOf(value), {\n\t\t...Object.getOwnPropertyDescriptors(value),\n\t\t[telemetryRedaction]: {\n\t\t\tvalue: redact,\n\t\t\tconfigurable: true\n\t\t}\n\t});\n}\n/** Apply the provider's telemetry view, leaving unannotated values unchanged. */\nfunction redactTelemetryValue(value) {\n\tif (value == null || typeof value !== \"object\") return value;\n\tconst redact = Object.getOwnPropertyDescriptor(value, telemetryRedaction)?.value;\n\tif (typeof redact !== \"function\") return value;\n\ttry {\n\t\treturn redact(value);\n\t} catch {\n\t\treturn;\n\t}\n}\n//#endregion\n//#region src/provider-defined-tool-factory.ts\nfunction createProviderDefinedToolFactory({ id, inputSchema, redactArgs }) {\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: redactArgs == null ? args : withTelemetryRedaction(args, redactArgs),\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, redactArgs }) {\n\treturn ({ execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({\n\t\ttype: \"provider\",\n\t\tisProviderExecuted: false,\n\t\tid,\n\t\targs: redactArgs == null ? args : withTelemetryRedaction(args, redactArgs),\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, redactArgs }) {\n\treturn ({ onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({\n\t\ttype: \"provider\",\n\t\tisProviderExecuted: true,\n\t\tid,\n\t\targs: redactArgs == null ? args : withTelemetryRedaction(args, redactArgs),\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/**\n* Resolves and transforms a value, preserving synchronous results. This allows\n* synchronous credentials to remain usable by workflow serialization while\n* asynchronous credentials are awaited by request handlers.\n*/\nfunction resolveWith(value, transform) {\n\tconst resolved = typeof value === \"function\" ? value() : value;\n\tif (resolved != null && (typeof resolved === \"object\" || typeof resolved === \"function\") && typeof resolved.then === \"function\") return Promise.resolve(resolved).then(transform);\n\treturn transform(resolved);\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/json-binary-field-scanner.ts\n/**\n* Streaming extraction of large base64 strings from a JSON response body.\n*\n* A JSON response that carries an image or a file is mostly one very long\n* base64 string. The regular pipeline (collect chunks, concatenate, decode to\n* text, `JSON.parse`, decode base64) holds about four copies of that string at\n* once. The scanner reads the body chunk by chunk instead: strings at the\n* configured paths are decoded to bytes while they stream in, and the text that\n* is handed to `JSON.parse` (the \"skeleton\") holds a short placeholder in their\n* place.\n*\n* - The skeleton is the original body except for the extracted strings, so\n* `secureJsonParse` still sees every key (a base64 string cannot contain a\n* quote, so it cannot hide one).\n* - A string is extracted only if it is canonical standard-alphabet base64\n* (length divisible by 4, `=` only as the final padding, zero trailing bits,\n* no escape sequences or whitespace). The bytes are then exactly what `atob`\n* gives for it. Everything else stays a string. What was decoded before a\n* string turned out not to qualify is encoded back, which gives the original\n* characters.\n*/\n/** Strings that decode to fewer bytes stay strings. */\nconst DEFAULT_BINARY_FIELD_MIN_BYTES = 65536;\nconst QUOTE = 34;\nconst BACKSLASH = 92;\nconst EQUALS = 61;\nconst COMMA = 44;\nconst COLON = 58;\nconst LEFT_BRACE = 123;\nconst RIGHT_BRACE = 125;\nconst LEFT_BRACKET = 91;\nconst RIGHT_BRACKET = 93;\nconst OUTSIDE = 0;\nconst KEY = 1;\nconst SKIP = 2;\nconst BLOB = 3;\n/**\n* Compiles paths such as `images[*]` or `content[*].data.data`: plain object\n* keys (letters, digits, `_` and `-`) joined by `.`, and `[*]` for every\n* element of an array. Keys are compared with the raw bytes of the key in the\n* body, so a key written with an escape sequence never matches.\n*/\nfunction compileBinaryFieldPaths(paths) {\n\tconst root = /* @__PURE__ */ new Map();\n\tfor (const path of paths) {\n\t\tif (!/^(?:[\\w-]+|\\[\\*])(?:\\.[\\w-]+|\\[\\*])*$/.test(path)) throw new InvalidArgumentError({\n\t\t\targument: \"experimental_binaryFields\",\n\t\t\tmessage: `Invalid binary field path \"${path}\"`\n\t\t});\n\t\tlet node = root;\n\t\tfor (const segment of path.match(/\\[\\*]|[\\w-]+/g)) {\n\t\t\tconst edges = segment === \"[*]\" ? [null] : new TextEncoder().encode(`${segment}\"`);\n\t\t\tfor (const edge of edges) {\n\t\t\t\tlet next = node.get(edge);\n\t\t\t\tif (next === void 0) node.set(edge, next = /* @__PURE__ */ new Map());\n\t\t\t\tnode = next;\n\t\t\t}\n\t\t}\n\t\tnode.set(true, node);\n\t}\n\treturn root;\n}\nfunction join(parts, length) {\n\tconst bytes = new Uint8Array(length);\n\tlet at = 0;\n\tfor (const part of parts) {\n\t\tbytes.set(part, at);\n\t\tat += part.length;\n\t}\n\treturn bytes;\n}\nfunction createJsonBinaryFieldScanner(paths, minBytes = DEFAULT_BINARY_FIELD_MIN_BYTES) {\n\tconst sextet = (/* @__PURE__ */ new Uint8Array(256)).fill(64);\n\tfor (let index = 0; index < 64; index++) sextet[\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charCodeAt(index)] = index;\n\tconst encoder = new TextEncoder();\n\tconst pieces = [];\n\tlet piece = /* @__PURE__ */ new Uint8Array(65536);\n\tlet pieceLength = 0;\n\tlet size = 0;\n\tconst binaries = /* @__PURE__ */ new Map();\n\tconst frames = [];\n\tlet skipped = 0;\n\tlet mode = OUTSIDE;\n\tlet escaped = false;\n\tlet last = 0;\n\tlet key;\n\tlet segments = [];\n\tlet segment = /* @__PURE__ */ new Uint8Array(0);\n\tlet at = 0;\n\tlet total = 0;\n\tlet bits = 0;\n\tlet chars = 0;\n\tlet padding = 0;\n\tconst add = (bytes) => {\n\t\tfor (let offset = 0; offset < bytes.length;) {\n\t\t\tconst length = Math.min(piece.length - pieceLength, bytes.length - offset);\n\t\t\tpiece.set(bytes.subarray(offset, offset + length), pieceLength);\n\t\t\tpieceLength += length;\n\t\t\toffset += length;\n\t\t\tsize += length;\n\t\t\tif (pieceLength === piece.length) {\n\t\t\t\tpieces.push(piece);\n\t\t\t\tpiece = /* @__PURE__ */ new Uint8Array(65536);\n\t\t\t\tpieceLength = 0;\n\t\t\t}\n\t\t}\n\t};\n\tconst emit = (chunk, start, end) => add(chunk.subarray(start, end));\n\tconst reset = () => {\n\t\tsegments = [];\n\t\tsegment = /* @__PURE__ */ new Uint8Array(0);\n\t\tat = 0;\n\t\ttotal = 0;\n\t\tbits = 0;\n\t\tchars = 0;\n\t\tpadding = 0;\n\t};\n\tconst grow = () => {\n\t\tif (at > 0) segments.push(segment.subarray(0, at));\n\t\tsegment = new Uint8Array(Math.min(Math.max(total, 4096), 4 << 20));\n\t\tat = 0;\n\t};\n\tconst rest = () => bits << (4 - chars) * 6;\n\tconst restore = () => {\n\t\tfor (const part of [...segments, segment.subarray(0, at)]) add(encoder.encode(convertUint8ArrayToBase64(part)));\n\t\tconst group = rest();\n\t\tadd(encoder.encode(convertUint8ArrayToBase64(Uint8Array.of(group >> 16, group >> 8, group)).slice(0, chars) + \"=\".repeat(padding)));\n\t\treset();\n\t};\n\tconst closeBlob = () => {\n\t\tmode = OUTSIDE;\n\t\tconst tail = chars && chars - 1;\n\t\tif (padding === (4 - chars) % 4 && !(bits & (1 << (4 - chars) * 2) - 1) && total + tail >= minBytes) {\n\t\t\tconst group = rest();\n\t\t\tconst bytes = join([...segments, segment.subarray(0, at)], total + tail);\n\t\t\tfor (let index = 0; index < tail; index++) bytes[total + index] = group >> 16 - 8 * index;\n\t\t\tconst placeholder = `[binary data: ${bytes.length} bytes; ref ${crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(2)).join(\"-\")}]`;\n\t\t\tbinaries.set(placeholder, bytes);\n\t\t\tadd(encoder.encode(placeholder));\n\t\t\treset();\n\t\t} else restore();\n\t};\n\tconst push = (chunk) => {\n\t\tlet from = 0;\n\t\tconst { length } = chunk;\n\t\tfor (let index = 0; index < length; index++) {\n\t\t\tlet byte = chunk[index];\n\t\t\tif (mode === BLOB) {\n\t\t\t\tif (padding === 0) {\n\t\t\t\t\tlet pending = bits;\n\t\t\t\t\tlet count = chars;\n\t\t\t\t\tfor (let value; index < length && (value = sextet[chunk[index]]) < 64; index++) {\n\t\t\t\t\t\tpending = pending << 6 | value;\n\t\t\t\t\t\tif (++count === 4) {\n\t\t\t\t\t\t\tif (at + 3 > segment.length) grow();\n\t\t\t\t\t\t\tsegment[at++] = pending >> 16;\n\t\t\t\t\t\t\tsegment[at++] = pending >> 8;\n\t\t\t\t\t\t\tsegment[at++] = pending;\n\t\t\t\t\t\t\ttotal += 3;\n\t\t\t\t\t\t\tpending = 0;\n\t\t\t\t\t\t\tcount = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbits = pending;\n\t\t\t\t\tchars = count;\n\t\t\t\t}\n\t\t\t\tif (index >= length) break;\n\t\t\t\tbyte = chunk[index];\n\t\t\t\tif (byte === QUOTE) {\n\t\t\t\t\tcloseBlob();\n\t\t\t\t\tfrom = index;\n\t\t\t\t} else if (byte === EQUALS && chars > 1 && padding < 4 - chars) padding++;\n\t\t\t\telse {\n\t\t\t\t\trestore();\n\t\t\t\t\tmode = SKIP;\n\t\t\t\t\tfrom = index--;\n\t\t\t\t}\n\t\t\t} else if (mode !== OUTSIDE) {\n\t\t\t\tif (mode === KEY) key = key?.get(byte);\n\t\t\t\tif (escaped) escaped = false;\n\t\t\t\telse if (byte === BACKSLASH) escaped = true;\n\t\t\t\telse if (byte === QUOTE) {\n\t\t\t\t\tif (mode === KEY) frames.at(-1).next = key;\n\t\t\t\t\tmode = OUTSIDE;\n\t\t\t\t}\n\t\t\t} else if (byte === QUOTE) {\n\t\t\t\tconst frame = frames.at(-1);\n\t\t\t\tif (skipped > 0) mode = SKIP;\n\t\t\t\telse if (frame?.keys && (last === LEFT_BRACE || last === COMMA)) {\n\t\t\t\t\tmode = KEY;\n\t\t\t\t\tkey = frame.keys;\n\t\t\t\t} else if ((frame ? frame.next : paths)?.get(true)) {\n\t\t\t\t\tmode = BLOB;\n\t\t\t\t\temit(chunk, from, index + 1);\n\t\t\t\t} else mode = SKIP;\n\t\t\t} else if (byte === LEFT_BRACE || byte === LEFT_BRACKET) {\n\t\t\t\tlast = byte;\n\t\t\t\tconst frame = frames.at(-1);\n\t\t\t\tconst node = skipped > 0 ? void 0 : frame ? frame.next : paths;\n\t\t\t\tconst items = node?.get(null);\n\t\t\t\tif (byte === LEFT_BRACE && node) frames.push({ keys: node });\n\t\t\t\telse if (byte === LEFT_BRACKET && items) frames.push({\n\t\t\t\t\tkeys: null,\n\t\t\t\t\tnext: items\n\t\t\t\t});\n\t\t\t\telse skipped++;\n\t\t\t} else if (byte === RIGHT_BRACE || byte === RIGHT_BRACKET) {\n\t\t\t\tif (skipped > 0) skipped--;\n\t\t\t\telse frames.pop();\n\t\t\t} else if (byte === COMMA || byte === COLON) last = byte;\n\t\t}\n\t\tif (mode !== BLOB) emit(chunk, from, length);\n\t};\n\tconst finish = () => {\n\t\tif (mode === BLOB) restore();\n\t\treturn {\n\t\t\ttext: new TextDecoder().decode(join([...pieces, piece.subarray(0, pieceLength)], size)),\n\t\t\tbinaries\n\t\t};\n\t};\n\treturn {\n\t\tpush,\n\t\tfinish\n\t};\n}\n/**\n* Replaces the placeholders in a parsed value with the bytes they stand for.\n* Objects and arrays are copied, the parsed value is not modified. A\n* placeholder holds a random number, so a string that equals one is ours.\n*/\nfunction replaceBinaryFieldPlaceholders(value, binaries) {\n\tif (typeof value === \"string\") return binaries.get(value) ?? value;\n\tif (Array.isArray(value)) return value.map((item) => replaceBinaryFieldPlaceholders(item, binaries));\n\tif (value != null && typeof value === \"object\") return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, replaceBinaryFieldPlaceholders(item, binaries)]));\n\treturn value;\n}\n/**\n* Makes `JSON.stringify` give the placeholder for each of the arrays, instead\n* of `{\"0\":…,\"1\":…}` with an entry for every byte: 24 MiB of bytes would\n* become a string of more than 300 MB. That is what a validator, or the code\n* that reports its issues, does with a value it puts into an error message.\n* The property is not enumerable, so the arrays look the same otherwise.\n* Returns the function that removes it again.\n*/\nfunction maskBinariesInJson(binaries) {\n\tfor (const [placeholder, bytes] of binaries) Object.defineProperty(bytes, \"toJSON\", {\n\t\tvalue: () => placeholder,\n\t\tconfigurable: true\n\t});\n\treturn () => {\n\t\tfor (const bytes of binaries.values()) Reflect.deleteProperty(bytes, \"toJSON\");\n\t};\n}\n/**\n* Wraps a schema so that it validates the extracted bytes in place of their\n* placeholders. The value parsed from the skeleton, and the value of the\n* validation error of the response, keep the placeholders: reporting an error\n* never prints the bytes.\n*\n* The errors of the schema itself may hold the bytes: a Standard Schema\n* validator wraps the value it was given into an error, and the issues it\n* reports may carry the offending input. So that their messages do not grow\n* with the image, the arrays stringify as their placeholders, and keep doing\n* so as long as an error can refer to them. When the validation succeeds the\n* arrays are plain again, for whoever receives them.\n*/\nfunction withBinaryFields(schema, binaries) {\n\tif (binaries.size === 0) return schema;\n\tconst actualSchema = asSchema(schema);\n\treturn jsonSchema({}, { validate: async (value) => {\n\t\tconst replaced = replaceBinaryFieldPlaceholders(value, binaries);\n\t\tconst unmask = maskBinariesInJson(binaries);\n\t\tconst result = actualSchema.validate ? await actualSchema.validate(replaced) : {\n\t\t\tsuccess: true,\n\t\t\tvalue: replaced\n\t\t};\n\t\tif (result.success) unmask();\n\t\treturn result;\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, { experimental_binaryFields } = {}) => {\n\tconst binaryFieldPaths = experimental_binaryFields?.length ? compileBinaryFieldPaths(experimental_binaryFields) : void 0;\n\treturn async ({ response, url, requestBodyValues }) => {\n\t\tlet responseBody;\n\t\tlet schema = responseSchema;\n\t\tif (binaryFieldPaths == null) responseBody = await readResponseBodyAsText({\n\t\t\tresponse,\n\t\t\turl\n\t\t});\n\t\telse {\n\t\t\tconst scanner = createJsonBinaryFieldScanner(binaryFieldPaths);\n\t\t\tawait readResponseWithSizeLimit({\n\t\t\t\tresponse,\n\t\t\t\turl,\n\t\t\t\tonChunk: scanner.push\n\t\t\t});\n\t\t\tconst scanned = scanner.finish();\n\t\t\tresponseBody = scanned.text;\n\t\t\tschema = withBinaryFields(responseSchema, scanned.binaries);\n\t\t}\n\t\tconst parsedResult = await safeParseJSON({\n\t\t\ttext: responseBody,\n\t\t\tschema\n\t\t});\n\t\tconst responseHeaders = extractResponseHeaders(response);\n\t\tif (!parsedResult.success) throw new APICallError({\n\t\t\tmessage: \"Invalid JSON response\",\n\t\t\tcause: parsedResult.error,\n\t\t\tstatusCode: response.status,\n\t\t\tresponseHeaders,\n\t\t\tresponseBody,\n\t\t\turl,\n\t\t\trequestBodyValues\n\t\t});\n\t\treturn {\n\t\t\tresponseHeaders,\n\t\t\tvalue: parsedResult.value,\n\t\t\trawValue: parsedResult.rawValue\n\t\t};\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/speech-stream-envelope.ts\n/**\n* Experimental speech-stream WebSocket envelope (v1): the standard\n* serialization of `Experimental_StreamingSpeechModelV4.doStream` over a WebSocket. Clients (e.g.\n* the `@ai-sdk/gateway` provider) encode with this module and servers (e.g.\n* AI Gateway) decode with it, so the two sides cannot drift.\n*\n* Envelope rules:\n*\n* 1. The client sends exactly one `speech-stream.start` TEXT frame first.\n* 2. Input text rides `speech-stream.text-delta` TEXT frames, in order. A\n* frame may carry its text part's `voice` and `providerOptions`. A long\n* part may span several frames: `voice` is repeated on each, and\n* `providerOptions` appear on the first only, so they must describe an\n* event at the start of the part (e.g. a turn break), not a setting. An\n* empty `delta` is valid and carries only part metadata; it does not end\n* the input.\n* 3. The client signals the end of the input text with the\n* `speech-stream.text-done` TEXT frame; a plain close without it is an\n* abort.\n* 4. Every server→client TEXT frame is one JSON-serialized\n* `SpeechModelV4StreamPart` (flattened, no wrapper). `audio` payloads are\n* base64 strings. `Date` values (`response-metadata.timestamp`) serialize\n* to ISO 8601 strings and are revived by `parseSpeechStreamPart`. `Error`\n* payloads in `error` parts serialize as `{ name, message }`; servers may\n* instead send `{ type, message }`, where `type` names an error class the\n* client can map to a typed error (e.g. `invalid_request_error`).\n* 5. The server closes with code 1000 after the `finish` part. Over this\n* envelope an `error` part is terminal: the server sends it on failure and\n* then closes non-1000. A close without a prior `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 keep text-delta frames under 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 layers on top. Both\n* parsers use `secureJsonParse`, so frames carrying `__proto__` /\n* `constructor.prototype` keys are rejected rather than parsed.\n*/\n/** Type of the first client TEXT frame. */\nconst SPEECH_STREAM_START_FRAME_TYPE = \"speech-stream.start\";\n/** Type of the client TEXT frame that carries one input text delta. */\nconst SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE = \"speech-stream.text-delta\";\n/** Type of the client TEXT frame that signals the end of the input text. */\nconst SPEECH_STREAM_TEXT_DONE_FRAME_TYPE = \"speech-stream.text-done\";\nconst optionalStartFrameFields = {\n\tinstructions: \"string\",\n\tlanguage: \"string\",\n\tspeed: \"number\",\n\tvoice: \"string\",\n\tincludeRawChunks: \"boolean\"\n};\n/**\n* Server-side: parse a client TEXT frame. Validates envelope shape only and\n* rejects prototype-pollution payloads. Never throws.\n*/\nfunction parseSpeechStreamClientFrame(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 (!isRecord(value)) return {\n\t\ttype: \"invalid\",\n\t\tmessage: \"frame must be a JSON object\"\n\t};\n\tif (typeof value.type !== \"string\") return {\n\t\ttype: \"invalid\",\n\t\tmessage: \"frame type must be a string\"\n\t};\n\tswitch (value.type) {\n\t\tcase SPEECH_STREAM_START_FRAME_TYPE: {\n\t\t\tfor (const [field, type] of Object.entries(optionalStartFrameFields)) if (value[field] !== void 0 && typeof value[field] !== type) return {\n\t\t\t\ttype: \"invalid\",\n\t\t\t\tmessage: `${field} must be a ${type} when present`\n\t\t\t};\n\t\t\tif (value.outputFormat !== void 0 && !isAudioFormat(value.outputFormat)) return {\n\t\t\t\ttype: \"invalid\",\n\t\t\t\tmessage: \"outputFormat must be an audio format object ({ type, rate? }) when present\"\n\t\t\t};\n\t\t\tif (value.providerOptions !== void 0 && !isProviderOptions(value.providerOptions)) return {\n\t\t\t\ttype: \"invalid\",\n\t\t\t\tmessage: \"providerOptions must be an object of provider objects when present\"\n\t\t\t};\n\t\t\tconst frame = { type: SPEECH_STREAM_START_FRAME_TYPE };\n\t\t\tfor (const field of Object.keys(optionalStartFrameFields)) if (value[field] !== void 0) frame[field] = value[field];\n\t\t\tif (value.outputFormat !== void 0) {\n\t\t\t\tconst { type, rate } = value.outputFormat;\n\t\t\t\tframe.outputFormat = {\n\t\t\t\t\ttype,\n\t\t\t\t\t...rate !== void 0 && { rate }\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (value.providerOptions !== void 0) frame.providerOptions = value.providerOptions;\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 SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE:\n\t\t\tif (typeof value.delta !== \"string\") return {\n\t\t\t\ttype: \"invalid\",\n\t\t\t\tmessage: \"text-delta frame must have a string delta\"\n\t\t\t};\n\t\t\tif (value.voice !== void 0 && typeof value.voice !== \"string\") return {\n\t\t\t\ttype: \"invalid\",\n\t\t\t\tmessage: \"text-delta voice must be a string when present\"\n\t\t\t};\n\t\t\tif (value.providerOptions !== void 0 && !isProviderOptions(value.providerOptions)) return {\n\t\t\t\ttype: \"invalid\",\n\t\t\t\tmessage: \"text-delta providerOptions must be an object of provider objects when present\"\n\t\t\t};\n\t\t\treturn {\n\t\t\t\ttype: \"text-delta\",\n\t\t\t\tdelta: value.delta,\n\t\t\t\t...value.voice !== void 0 && { voice: value.voice },\n\t\t\t\t...value.providerOptions !== void 0 && { providerOptions: value.providerOptions }\n\t\t\t};\n\t\tcase SPEECH_STREAM_TEXT_DONE_FRAME_TYPE: return { type: \"text-done\" };\n\t\tdefault: return { type: \"unknown\" };\n\t}\n}\n/**\n* Server-side: serialize a speech stream part as one TEXT frame. Binary audio\n* is base64-encoded and `Error` payloads serialize as `{ name, message }`.\n* Returns `undefined` for payloads that are not JSON-serializable; callers\n* drop the frame.\n*/\nfunction serializeSpeechStreamPart(part) {\n\ttry {\n\t\tif (part.type === \"audio\" && part.audio instanceof Uint8Array) return JSON.stringify({\n\t\t\t...part,\n\t\t\taudio: convertUint8ArrayToBase64(part.audio)\n\t\t});\n\t\tif (part.type === \"error\" && isError$1(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$1(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 speech stream part. Returns\n* `undefined` for malformed or unsafe JSON, unknown part types, and known\n* part types whose fields are missing or mistyped. Revives\n* `response-metadata.timestamp` to a `Date`.\n*/\nfunction parseSpeechStreamPart(text) {\n\tlet value;\n\ttry {\n\t\tvalue = secureJsonParse(text);\n\t} catch {\n\t\treturn;\n\t}\n\tif (!isRecord(value)) return;\n\tconst part = value;\n\tswitch (part.type) {\n\t\tcase \"stream-start\": {\n\t\t\tif (!Array.isArray(part.warnings)) return;\n\t\t\tconst warnings = part.warnings.filter((warning) => !isUnknownWarningType(warning));\n\t\t\treturn warnings.every(isWarning$1) ? {\n\t\t\t\t...part,\n\t\t\t\twarnings\n\t\t\t} : void 0;\n\t\t}\n\t\tcase \"audio\": return isString$1(part.audio) && isAudioFormat(part.audioFormat) && isOptional$1(part.id, isString$1) && isOptional$1(part.providerMetadata, isRecord) ? part : void 0;\n\t\tcase \"finish\": return isOptional$1(part.usage, isUsage) && isOptional$1(part.providerMetadata, isRecord) ? part : void 0;\n\t\tcase \"response-metadata\": {\n\t\t\tif (!(isOptional$1(part.modelId, isString$1) && isOptional$1(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$1(value) {\n\treturn typeof value === \"string\";\n}\nfunction isOptional$1(value, check) {\n\treturn value === void 0 || check(value);\n}\nconst knownWarningTypes = /* @__PURE__ */ new Set([\n\t\"compatibility\",\n\t\"deprecated\",\n\t\"other\",\n\t\"unsupported\"\n]);\nfunction isUnknownWarningType(value) {\n\treturn isRecord(value) && isString$1(value.type) && !knownWarningTypes.has(value.type);\n}\nfunction isWarning$1(value) {\n\tif (!isRecord(value)) return false;\n\tswitch (value.type) {\n\t\tcase \"compatibility\":\n\t\tcase \"unsupported\": return isString$1(value.feature) && isOptional$1(value.details, isString$1);\n\t\tcase \"deprecated\": return isString$1(value.setting) && isString$1(value.message);\n\t\tcase \"other\": return isString$1(value.message);\n\t\tdefault: return false;\n\t}\n}\nfunction isProviderOptions(value) {\n\treturn isRecord(value) && Object.values(value).every(isRecord);\n}\nfunction isAudioFormat(value) {\n\treturn isRecord(value) && isString$1(value.type) && value.type.length > 0 && isOptional$1(value.rate, (rate) => typeof rate === \"number\" && Number.isFinite(rate) && rate > 0);\n}\nfunction isUsage(value) {\n\treturn isRecord(value) && [\n\t\t\"inputCharacters\",\n\t\t\"inputTokens\",\n\t\t\"outputTokens\"\n\t].every((key) => isOptional$1(value[key], (count) => typeof count === \"number\"));\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\n//#region src/stringify-with-bigint-and-cycles.ts\n/**\n* Serializes a value as JSON, representing BigInt values as decimal strings and\n* ancestor cycles as \"[Circular]\". Reused objects, toJSON methods, and other JSON\n* serialization behavior are preserved. Getters and toJSON methods may throw.\n*/\nfunction stringifyWithBigIntAndCycles(value) {\n\tconst ancestors = [];\n\treturn JSON.stringify(value, function(_key, value) {\n\t\tif (typeof value === \"bigint\") return value.toString();\n\t\tif (typeof value !== \"object\" || value === null) return value;\n\t\twhile (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();\n\t\tif (ancestors.includes(value)) return \"[Circular]\";\n\t\tancestors.push(value);\n\t\treturn value;\n\t});\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, SPEECH_STREAM_START_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_START_FRAME_TYPE, SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE, SPEECH_STREAM_TEXT_DONE_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_TEXT_DONE_FRAME_TYPE, 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, encodePathSegment, executeTool, getToolCaller as experimental_getToolCaller, parseSpeechStreamClientFrame as experimental_parseSpeechStreamClientFrame, parseSpeechStreamPart as experimental_parseSpeechStreamPart, parseTranscriptionStreamClientFrame as experimental_parseTranscriptionStreamClientFrame, parseTranscriptionStreamPart as experimental_parseTranscriptionStreamPart, serializeSpeechStreamPart as experimental_serializeSpeechStreamPart, serializeTranscriptionStreamPart as experimental_serializeTranscriptionStreamPart, toolCaller as experimental_toolCaller, extractLines, extractResponseHeaders, fetchUntrustedUrl, fetchWithValidatedEndpoint, fetchWithValidatedRedirects, filterNullable, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, injectJsonInstructionIntoMessages, isAbortError, isArrayBuffer, isBrowserRuntime, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, isProviderStreamError, isRecord, isSameOrigin, isUint8Array, isUrlSupported, isValidHostnamePart, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeBatchRequestCounts, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postMultipartStreamToApi, postToApi, readResponseWithSizeLimit, readWebSocketMessageText, redactTelemetryValue, removeUndefinedEntries, resolve, resolveFullMediaType, resolveProviderOptions, resolveProviderReference, resolveWith, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, secureJsonParse, serializeModelOptions, stringifyWithBigIntAndCycles, stripFileExtension, toWebSocketUrl, tool, validateBaseURL, validateDownloadUrl, validateTypes, waitForWebSocketBufferDrain, withTelemetryRedaction, withUserAgentSuffix, withoutTrailingSlash, zodSchema };\n\n//# sourceMappingURL=index.js.map","import * as core from \"../core/index.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport * as util from \"../core/util.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodMiniType = /*@__PURE__*/ core.$constructor(\"ZodMiniType\", (inst, def) => {\n if (!inst._zod)\n throw new Error(\"Uninitialized schema in ZodMiniType.\");\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n}, {\n // `with` is an alias for `check`: the same function object, not a wrapper.\n get with() {\n return this.check;\n },\n set with(value) {\n util.own(this, \"with\", value);\n },\n parse(data, params) {\n return parse.parse(this, data, params, { callee: this.parse });\n },\n parseAsync(data, params) {\n return parse.parseAsync(this, data, params, { callee: this.parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n check(...checks) {\n const def = this.def;\n return this.clone({\n ...def,\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }, { parent: true });\n },\n clone(_def, params) {\n return core.clone(this, _def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n});\nexport const ZodMiniString = /*@__PURE__*/ core.$constructor(\"ZodMiniString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function string(params) {\n return core._string(ZodMiniString, params);\n}\nexport const ZodMiniStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n ZodMiniString.init(inst, def);\n});\nexport const ZodMiniEmail = /*@__PURE__*/ core.$constructor(\"ZodMiniEmail\", (inst, def) => {\n core.$ZodEmail.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function email(params) {\n return core._email(ZodMiniEmail, params);\n}\nexport const ZodMiniGUID = /*@__PURE__*/ core.$constructor(\"ZodMiniGUID\", (inst, def) => {\n core.$ZodGUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function guid(params) {\n return core._guid(ZodMiniGUID, params);\n}\nexport const ZodMiniUUID = /*@__PURE__*/ core.$constructor(\"ZodMiniUUID\", (inst, def) => {\n core.$ZodUUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function uuid(params) {\n return core._uuid(ZodMiniUUID, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function uuidv4(params) {\n return core._uuidv4(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv6\n// @__NO_SIDE_EFFECTS__\nexport function uuidv6(params) {\n return core._uuidv6(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv7\n// @__NO_SIDE_EFFECTS__\nexport function uuidv7(params) {\n return core._uuidv7(ZodMiniUUID, params);\n}\nexport const ZodMiniURL = /*@__PURE__*/ core.$constructor(\"ZodMiniURL\", (inst, def) => {\n core.$ZodURL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function url(params) {\n return core._url(ZodMiniURL, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function httpUrl(params) {\n return core._url(ZodMiniURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEmoji = /*@__PURE__*/ core.$constructor(\"ZodMiniEmoji\", (inst, def) => {\n core.$ZodEmoji.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function emoji(params) {\n return core._emoji(ZodMiniEmoji, params);\n}\nexport const ZodMiniNanoID = /*@__PURE__*/ core.$constructor(\"ZodMiniNanoID\", (inst, def) => {\n core.$ZodNanoID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nanoid(params) {\n return core._nanoid(ZodMiniNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodMiniCUID = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID\", (inst, def) => {\n core.$ZodCUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function cuid(params) {\n return core._cuid(ZodMiniCUID, params);\n}\nexport const ZodMiniCUID2 = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID2\", (inst, def) => {\n core.$ZodCUID2.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cuid2(params) {\n return core._cuid2(ZodMiniCUID2, params);\n}\nexport const ZodMiniULID = /*@__PURE__*/ core.$constructor(\"ZodMiniULID\", (inst, def) => {\n core.$ZodULID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ulid(params) {\n return core._ulid(ZodMiniULID, params);\n}\nexport const ZodMiniXID = /*@__PURE__*/ core.$constructor(\"ZodMiniXID\", (inst, def) => {\n core.$ZodXID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function xid(params) {\n return core._xid(ZodMiniXID, params);\n}\nexport const ZodMiniKSUID = /*@__PURE__*/ core.$constructor(\"ZodMiniKSUID\", (inst, def) => {\n core.$ZodKSUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ksuid(params) {\n return core._ksuid(ZodMiniKSUID, params);\n}\nexport const ZodMiniIPv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv4\", (inst, def) => {\n core.$ZodIPv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv4(params) {\n return core._ipv4(ZodMiniIPv4, params);\n}\nexport const ZodMiniIPv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv6\", (inst, def) => {\n core.$ZodIPv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv6(params) {\n return core._ipv6(ZodMiniIPv6, params);\n}\nexport const ZodMiniCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv4(params) {\n return core._cidrv4(ZodMiniCIDRv4, params);\n}\nexport const ZodMiniCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv6(params) {\n return core._cidrv6(ZodMiniCIDRv6, params);\n}\nexport const ZodMiniMAC = /*@__PURE__*/ core.$constructor(\"ZodMiniMAC\", (inst, def) => {\n core.$ZodMAC.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function mac(params) {\n return core._mac(ZodMiniMAC, params);\n}\nexport const ZodMiniBase64 = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64\", (inst, def) => {\n core.$ZodBase64.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64(params) {\n return core._base64(ZodMiniBase64, params);\n}\nexport const ZodMiniBase64URL = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64URL\", (inst, def) => {\n core.$ZodBase64URL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64url(params) {\n return core._base64url(ZodMiniBase64URL, params);\n}\nexport const ZodMiniE164 = /*@__PURE__*/ core.$constructor(\"ZodMiniE164\", (inst, def) => {\n core.$ZodE164.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function e164(params) {\n return core._e164(ZodMiniE164, params);\n}\nexport const ZodMiniCreditCard = /*@__PURE__*/ core.$constructor(\"ZodMiniCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function creditCard(params) {\n return core._creditCard(ZodMiniCreditCard, params);\n}\nexport const ZodMiniIBAN = /*@__PURE__*/ core.$constructor(\"ZodMiniIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function iban(params) {\n return core._iban(ZodMiniIBAN, params);\n}\nexport const ZodMiniJWT = /*@__PURE__*/ core.$constructor(\"ZodMiniJWT\", (inst, def) => {\n core.$ZodJWT.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function jwt(params) {\n return core._jwt(ZodMiniJWT, params);\n}\nexport const ZodMiniCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniCustomStringFormat\", (inst, def) => {\n core.$ZodCustomStringFormat.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodMiniCustomStringFormat, format, fnOrRegex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hostname(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hex(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hex\", regexes.hex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function currencyCode(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n // check for unrecognized format\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodMiniCustomStringFormat, format, regex, params);\n}\nexport const ZodMiniNumber = /*@__PURE__*/ core.$constructor(\"ZodMiniNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function number(params) {\n return core._number(ZodMiniNumber, params);\n}\nexport const ZodMiniNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodMiniNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodMiniNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodMiniNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodMiniNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodMiniNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodMiniNumberFormat, params);\n}\nexport const ZodMiniBoolean = /*@__PURE__*/ core.$constructor(\"ZodMiniBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function boolean(params) {\n return core._boolean(ZodMiniBoolean, params);\n}\nexport const ZodMiniBigInt = /*@__PURE__*/ core.$constructor(\"ZodMiniBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function bigint(params) {\n return core._bigint(ZodMiniBigInt, params);\n}\nexport const ZodMiniBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodMiniBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodMiniBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodMiniBigIntFormat, params);\n}\nexport const ZodMiniSymbol = /*@__PURE__*/ core.$constructor(\"ZodMiniSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function symbol(params) {\n return core._symbol(ZodMiniSymbol, params);\n}\nexport const ZodMiniUndefined = /*@__PURE__*/ core.$constructor(\"ZodMiniUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _undefined(params) {\n return core._undefined(ZodMiniUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodMiniNull = /*@__PURE__*/ core.$constructor(\"ZodMiniNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _null(params) {\n return core._null(ZodMiniNull, params);\n}\nexport { _null as null };\nexport const ZodMiniAny = /*@__PURE__*/ core.$constructor(\"ZodMiniAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function any() {\n return core._any(ZodMiniAny);\n}\nexport const ZodMiniUnknown = /*@__PURE__*/ core.$constructor(\"ZodMiniUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function unknown() {\n return core._unknown(ZodMiniUnknown);\n}\nexport const ZodMiniNever = /*@__PURE__*/ core.$constructor(\"ZodMiniNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function never(params) {\n return core._never(ZodMiniNever, params);\n}\nexport const ZodMiniVoid = /*@__PURE__*/ core.$constructor(\"ZodMiniVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _void(params) {\n return core._void(ZodMiniVoid, params);\n}\nexport { _void as void };\nexport const ZodMiniDate = /*@__PURE__*/ core.$constructor(\"ZodMiniDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function date(params) {\n return core._date(ZodMiniDate, params);\n}\nexport const ZodMiniArray = /*@__PURE__*/ core.$constructor(\"ZodMiniArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function array(element, params) {\n return new ZodMiniArray({\n type: \"array\",\n element: element,\n ...util.normalizeParams(params),\n });\n}\n// .keyof\n// @__NO_SIDE_EFFECTS__\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodMiniObject = /*@__PURE__*/ core.$constructor(\"ZodMiniObject\", (inst, def) => {\n core.$ZodObject.init(inst, def);\n ZodMiniType.init(inst, def);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n});\n// @__NO_SIDE_EFFECTS__\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodMiniObject(def);\n}\n// strictObject\n// @__NO_SIDE_EFFECTS__\nexport function strictObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\n// @__NO_SIDE_EFFECTS__\nexport function looseObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\n// object methods\n// @__NO_SIDE_EFFECTS__\nexport function extend(schema, shape) {\n return util.extend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function safeExtend(schema, shape) {\n return util.safeExtend(schema, shape);\n}\n/**\n * @deprecated Use [`z.extend(A, B.shape)`](https://zod.dev/api?id=extend) instead.\n */\n// @__NO_SIDE_EFFECTS__\nexport function merge(a, b) {\n return util.merge(a, b);\n}\n// @__NO_SIDE_EFFECTS__\nexport function pick(schema, mask) {\n return util.pick(schema, mask);\n}\n// .omit\n// @__NO_SIDE_EFFECTS__\nexport function omit(schema, mask) {\n return util.omit(schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function partial(schema, mask) {\n const def = schema._zod.def;\n if (def.type !== \"tuple\")\n return util.partial(ZodMiniOptional, schema, mask);\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return util.clone(schema, {\n ...def,\n items: def.items.map((item) => new ZodMiniOptional({ type: \"optional\", innerType: item })),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function exactPartial(schema, mask) {\n return util.partial(ZodMiniExactOptional, schema, mask, \"exactPartial\");\n}\n// @__NO_SIDE_EFFECTS__\nexport function required(schema, mask) {\n return util.required(ZodMiniNonOptional, schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function catchall(inst, catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return inst.clone(util.mergeDefs(inst._zod.def, { catchall: catchall }));\n}\nexport const ZodMiniUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function union(options, params) {\n return new ZodMiniUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniXor = /*@__PURE__*/ core.$constructor(\"ZodMiniXor\", (inst, def) => {\n ZodMiniUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodMiniXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniDiscriminatedUnion\", (inst, def) => {\n core.$ZodDiscriminatedUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function discriminatedUnion(discriminator, options, params) {\n return new ZodMiniDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniIntersection = /*@__PURE__*/ core.$constructor(\"ZodMiniIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function intersection(left, right) {\n return new ZodMiniIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodMiniTuple = /*@__PURE__*/ core.$constructor(\"ZodMiniTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodMiniTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniRecord = /*@__PURE__*/ core.$constructor(\"ZodMiniRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function partialRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniMap = /*@__PURE__*/ core.$constructor(\"ZodMiniMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function map(keyType, valueType, params) {\n return new ZodMiniMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSet = /*@__PURE__*/ core.$constructor(\"ZodMiniSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function set(valueType, params) {\n return new ZodMiniSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEnum = /*@__PURE__*/ core.$constructor(\"ZodMiniEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodMiniType.init(inst, def);\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n});\n// @__NO_SIDE_EFFECTS__\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function literal(value, params) {\n return new ZodMiniLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniFile = /*@__PURE__*/ core.$constructor(\"ZodMiniFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function file(params) {\n return core._file(ZodMiniFile, params);\n}\nexport const ZodMiniTransform = /*@__PURE__*/ core.$constructor(\"ZodMiniTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function transform(fn) {\n return new ZodMiniTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodMiniOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function optional(innerType) {\n return new ZodMiniOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniExactOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function exactOptional(innerType) {\n return new ZodMiniExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniNullable = /*@__PURE__*/ core.$constructor(\"ZodMiniNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nullable(innerType) {\n return new ZodMiniNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\n// @__NO_SIDE_EFFECTS__\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodMiniDefault = /*@__PURE__*/ core.$constructor(\"ZodMiniDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _default(innerType, defaultValue) {\n return new ZodMiniDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniPrefault = /*@__PURE__*/ core.$constructor(\"ZodMiniPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function prefault(innerType, defaultValue) {\n return new ZodMiniPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniNonOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nonoptional(innerType, params) {\n return new ZodMiniNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSuccess = /*@__PURE__*/ core.$constructor(\"ZodMiniSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function success(innerType) {\n return new ZodMiniSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCatch = /*@__PURE__*/ core.$constructor(\"ZodMiniCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _catch(innerType, catchValue) {\n return new ZodMiniCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodMiniNaN = /*@__PURE__*/ core.$constructor(\"ZodMiniNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nan(params) {\n return core._nan(ZodMiniNaN, params);\n}\nexport const ZodMiniPipe = /*@__PURE__*/ core.$constructor(\"ZodMiniPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function pipe(in_, out) {\n return new ZodMiniPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n });\n}\nexport const ZodMiniCodec = /*@__PURE__*/ core.$constructor(\"ZodMiniCodec\", (inst, def) => {\n ZodMiniPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function codec(in_, out, params) {\n return new ZodMiniCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodMiniCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodMiniReadonly = /*@__PURE__*/ core.$constructor(\"ZodMiniReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function readonly(innerType) {\n return new ZodMiniReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodMiniTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function templateLiteral(parts, params) {\n return new ZodMiniTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLazy = /*@__PURE__*/ core.$constructor(\"ZodMiniLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// export function lazy<T extends object>(getter: () => T): T {\n// return util.createTransparentProxy<T>(getter);\n// }\n// @__NO_SIDE_EFFECTS__\nfunction _lazy(getter) {\n return new ZodMiniLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport { _lazy as lazy };\nexport const ZodMiniPromise = /*@__PURE__*/ core.$constructor(\"ZodMiniPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function promise(innerType) {\n return new ZodMiniPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCustom = /*@__PURE__*/ core.$constructor(\"ZodMiniCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// custom checks\n// @__NO_SIDE_EFFECTS__\nexport function check(fn, params) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// ZodCustom custom schema\n// @__NO_SIDE_EFFECTS__\nexport function custom(fn, _params) {\n return core._custom(ZodMiniCustom, fn ?? (() => true), _params);\n}\n// refine\n// @__NO_SIDE_EFFECTS__\nexport function refine(fn, _params = {}) {\n return core._refine(ZodMiniCustom, fn, _params);\n}\n// superRefine\n// @__NO_SIDE_EFFECTS__\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\n// instanceof\nclass Class {\n constructor(..._args) { }\n}\n// @__NO_SIDE_EFFECTS__\nfunction _instanceof(cls, params = {}) {\n const inst = custom((data) => data instanceof cls, params);\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodMiniCodec,\n Boolean: ZodMiniBoolean,\n String: ZodMiniString,\n}, ...args);\n// @__NO_SIDE_EFFECTS__\nexport function json() {\n const jsonSchema = _lazy(() => {\n return union([string(), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\nexport const ZodMiniFunction = /*@__PURE__*/ core.$constructor(\"ZodMiniFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _function(params) {\n return new ZodMiniFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\n","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, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createIdGenerator, createIdGenerator as createIdGenerator$1, delay, detectMediaType, dynamicTool, executeTool, experimental_getToolCaller, experimental_toolCaller, fetchUntrustedUrl, filterNullable, generateId, generateId as generateId$1, getErrorMessage, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, getWebSocketConstructor, isAbortError, isArrayBuffer, isBuffer, isExecutableTool, isFullMediaType, isNonNullable, isProviderReference, isProviderStreamError, isUint8Array, isUrlSupported, jsonSchema, jsonSchema as jsonSchema$1, lazySchema, normalizeHeaders, parseJsonEventStream, parseJsonEventStream as parseJsonEventStream$1, readResponseWithSizeLimit, readWebSocketMessageText, redactTelemetryValue, 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, Experimental_ExtractionRefusalError, Experimental_ExtractionRefusalError as Experimental_ExtractionRefusalError$1, Experimental_ExtractionUnsupportedFieldTypeError, Experimental_ExtractionUnsupportedFieldTypeError as Experimental_ExtractionUnsupportedFieldTypeError$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 { NEVER, array, boolean, custom, discriminatedUnion, enum as enum$1, extend, int, literal, looseObject, maximum, minLength, never, nonnegative, number, object, optional, pipe, positive, record, refine, safeParse, startsWith, string, transform, union, unknown } from \"zod/v4/mini\";\nimport { array as array$1, boolean as boolean$1, custom as custom$1, discriminatedUnion as discriminatedUnion$1, instanceof as instanceof$1, lazy, literal as literal$1, null as null$1, number as number$1, object as object$1, record as record$1, string as string$1, union as union$1, unknown as unknown$1 } from \"zod/v4\";\n//#region src/telemetry/get-request-origin.ts\n/** Remove credentials, paths, queries, and fragments before emitting telemetry. */\nfunction getRequestOrigin(url) {\n\tif (url == null) return void 0;\n\ttry {\n\t\tconst endpoint = new URL(url);\n\t\treturn endpoint.protocol === \"http:\" || endpoint.protocol === \"https:\" ? endpoint.origin : void 0;\n\t} catch {\n\t\treturn;\n\t}\n}\n/** Preserve request metadata while keeping unknown or sensitive URL fields out of results. */\nfunction sanitizeRequestMetadata(request) {\n\tif (request == null || !(\"url\" in request)) return request;\n\tconst { url, ...rest } = request;\n\tconst origin = getRequestOrigin(url);\n\treturn {\n\t\t...rest,\n\t\t...origin != null ? { url: origin } : {}\n\t};\n}\n//#endregion\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\t...options.cause !== void 0 && { cause: options.cause }\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 === \"none\" ? \"Model response contained a tool call even though tool choice was none.\" : 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\tif (prop === \"doGenerate\") return async ({ timestampGranularities, ...options }) => {\n\t\t\tconst result = await target.doGenerate.call(model, options);\n\t\t\tif (!timestampGranularities?.length) return result;\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\twarnings: [...result.warnings, {\n\t\t\t\t\ttype: \"unsupported\",\n\t\t\t\t\tfeature: \"timestampGranularities\",\n\t\t\t\t\tdetails: `Shared timestamp granularities are not supported by ${model.specificationVersion} transcription models.`\n\t\t\t\t}]\n\t\t\t};\n\t\t};\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 resolveExtractionModel(model) {\n\tconst version = model.specificationVersion;\n\tif (version !== \"v4\") throw new UnsupportedModelVersionError({\n\t\tversion,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn model;\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 cloneValue(messages, /* @__PURE__ */ new Map());\n}\nfunction cloneValue(value, seen) {\n\tif (value == null || typeof value !== \"object\") return value;\n\tif (seen.has(value)) return seen.get(value);\n\tif (value instanceof URL) {\n\t\tconst copy = new URL(value.href);\n\t\tseen.set(value, copy);\n\t\treturn copy;\n\t}\n\tif (Array.isArray(value)) {\n\t\tconst copy = new Array(value.length);\n\t\tseen.set(value, copy);\n\t\tvalue.forEach((item, index) => {\n\t\t\tcopy[index] = cloneValue(item, seen);\n\t\t});\n\t\treturn copy;\n\t}\n\tif (isUint8Array(value)) {\n\t\tconst copy = new Uint8Array(value);\n\t\tseen.set(value, copy);\n\t\treturn copy;\n\t}\n\tif (isArrayBuffer(value)) {\n\t\tconst copy = new Uint8Array(value).slice().buffer;\n\t\tseen.set(value, copy);\n\t\treturn copy;\n\t}\n\tif (value instanceof Date || Object.prototype.toString.call(value) === \"[object Date]\") try {\n\t\tconst copy = new Date(Date.prototype.getTime.call(value));\n\t\tseen.set(value, copy);\n\t\treturn copy;\n\t} catch {}\n\tconst copy = {};\n\tseen.set(value, copy);\n\tfor (const [key, val] of Object.entries(value)) Object.defineProperty(copy, key, {\n\t\tvalue: cloneValue(val, seen),\n\t\twritable: true,\n\t\tenumerable: true,\n\t\tconfigurable: true\n\t});\n\treturn copy;\n}\n//#endregion\n//#region src/version.ts\nconst VERSION = \"7.0.173\";\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* @param fetch - An optional fetch transport.\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, fetch }) => {\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\tfetch\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$3 = download, abortSignal) => (requestedDownloads) => Promise.all(requestedDownloads.map(async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : await download$3({\n\t...requestedDownload,\n\tabortSignal: abortSignal ?? requestedDownload.abortSignal\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/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\treturn convertUint8ArrayToBase64(convertDataContentToUint8Array(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 (isUint8Array(content)) {\n\t\tif (content instanceof Uint8Array) return content;\n\t\tconst { buffer, byteOffset, byteLength } = content;\n\t\treturn new Uint8Array(buffer, byteOffset, byteLength);\n\t}\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 (isArrayBuffer(content)) return new Uint8Array(content);\n\tthrow new InvalidDataContentError({ content });\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 (isUint8Array(content) || isArrayBuffer(content)) return {\n\t\tdata: {\n\t\t\ttype: \"data\",\n\t\t\tdata: convertDataContentToUint8Array(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 (isUint8Array(content) || isArrayBuffer(content)) return convertInlineDataToFilePartData(content);\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, abortSignal);\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\": if (toolCallIds.size > 0) throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n\t}\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, abortSignal) {\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) {\n\t\t\t\tconst filePart = getDownloadableFilePart(contentPart);\n\t\t\t\tif (filePart != null) downloadableFiles.push(filePart);\n\t\t\t}\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) {\n\t\t\t\tconst filePart = getDownloadableFilePart(contentPart);\n\t\t\t\tif (filePart != null) downloadableFiles.push(filePart);\n\t\t\t}\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\tabortSignal,\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* Resolves the tool result content parts that point at a remote file to the\n* tagged file shape, including the deprecated `file-url` and `image-url`\n* types, so that they are downloaded and inlined exactly like their `file`\n* replacement. Returns `undefined` for content that is already inline or\n* provider-referenced.\n*/\nfunction getDownloadableFilePart(contentPart) {\n\tswitch (contentPart.type) {\n\t\tcase \"file\": return contentPart;\n\t\tcase \"file-url\": return {\n\t\t\ttype: \"file\",\n\t\t\tdata: {\n\t\t\t\ttype: \"url\",\n\t\t\t\turl: new URL(contentPart.url)\n\t\t\t},\n\t\t\tmediaType: contentPart.mediaType ?? getMediaTypeFromUrl(contentPart.url),\n\t\t\tproviderOptions: contentPart.providerOptions\n\t\t};\n\t\tcase \"image-url\": return {\n\t\t\ttype: \"file\",\n\t\t\tdata: {\n\t\t\t\ttype: \"url\",\n\t\t\t\turl: new URL(contentPart.url)\n\t\t\t},\n\t\t\tmediaType: \"image\",\n\t\t\tproviderOptions: contentPart.providerOptions\n\t\t};\n\t\tdefault: return;\n\t}\n}\n/**\n* Resolves file data and media type for a remote tool result content part: the downloaded\n* bytes when the asset was fetched, otherwise the URL reference. `originalUrl`\n* is preserved when the URL string does not round-trip through `URL`.\n*/\nfunction resolveDownloadedFile({ url, originalUrl, downloadedAssets, mediaType }) {\n\tconst convertedPart = convertPartToLanguageModelPart({\n\t\ttype: \"file\",\n\t\tdata: {\n\t\t\ttype: \"url\",\n\t\t\turl,\n\t\t\t...url.toString() !== originalUrl ? { originalUrl } : {}\n\t\t},\n\t\tmediaType\n\t}, downloadedAssets);\n\treturn {\n\t\tdata: convertedPart.data,\n\t\tmediaType: convertedPart.mediaType\n\t};\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\t...resolveDownloadedFile({\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\toriginalUrl: item.url,\n\t\t\t\t\t\t\tdownloadedAssets,\n\t\t\t\t\t\t\tmediaType\n\t\t\t\t\t\t}),\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\t...resolveDownloadedFile({\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\toriginalUrl: item.url,\n\t\t\t\t\t\t\tdownloadedAssets,\n\t\t\t\t\t\t\tmediaType: \"image\"\n\t\t\t\t\t\t}),\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 (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/prompt/standardize-prompt.ts\n/**\n* Converts a prompt input into a standardized prompt with model 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\tmessages = prompt == null ? messages : typeof prompt === \"string\" ? [{\n\t\trole: \"user\",\n\t\tcontent: prompt\n\t}] : prompt;\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\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\tconst toolCallOrder = Object.create(null);\n\tlet nextToolCallIndex = 0;\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\") {\n\t\t\ttoolCallsByToolCallId[part.toolCallId] = part;\n\t\t\ttoolCallOrder[part.toolCallId] = nextToolCallIndex++;\n\t\t}\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 collectedToolCallIds = /* @__PURE__ */ new Set();\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\tif (collectedToolCallIds.has(toolCall.toolCallId)) continue;\n\t\tcollectedToolCallIds.add(toolCall.toolCallId);\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\tapprovedToolApprovals.sort((a, b) => toolCallOrder[a.toolCall.toolCallId] - toolCallOrder[b.toolCall.toolCallId]);\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\tthis.base64Data = typeof data === \"string\" ? data : void 0;\n\t\tthis.uint8ArrayData = typeof data === \"string\" ? void 0 : convertDataContentToUint8Array(data);\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, download: download$2, 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 = download$2 == null ? (await download({\n\t\turl: data.url,\n\t\tabortSignal\n\t})).data : await downloadGeneratedFile({\n\t\turl: data.url,\n\t\tdownload: download$2,\n\t\tabortSignal\n\t});\n\tcache?.set(data, downloadedData);\n\treturn downloadedData;\n}\nasync function downloadGeneratedFile({ url, download, abortSignal }) {\n\tconst [result] = await download([{\n\t\turl,\n\t\tisUrlSupportedByModel: false,\n\t\tabortSignal\n\t}]);\n\tif (result == null) throw new DownloadError$1({\n\t\turl: url.toString(),\n\t\tmessage: `Generated file URL ${url} must be downloaded, but the download function returned null`\n\t});\n\treturn result.data;\n}\n//#endregion\n//#region src/generate-text/convert-language-model-content.ts\nasync function convertLanguageModelContent({ content, toolCalls, toolOutputs, toolApprovalRequests, toolApprovalResponses, tools, download, 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\tdownload,\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 (callers != null) resolved[toolName] = callers;\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/array-output-stream.ts\nconst arrayStreamParserFactories = /* @__PURE__ */ new WeakMap();\nfunction createArrayStreamParser(output) {\n\treturn arrayStreamParserFactories.get(output)?.();\n}\n/**\n* Scan only new text and parse/validate each delimited element once. Keep the\n* last element pending until another starts or the enclosing object closes,\n* matching the partial JSON parser's treatment of an incomplete response.\n* Nonstandard envelopes and malformed JSON use the existing partial parser.\n*/\nfunction createArrayOutputStreamParser(schema, skipInvalidElements) {\n\tlet phase = 0;\n\tlet prefix = \"\";\n\tlet elementText = \"\";\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tlet afterComma = false;\n\tlet pending = [];\n\tconst elements = [];\n\tlet publishedCount;\n\tasync function finishElement() {\n\t\tconst parsed = await safeParseJSON({ text: elementText });\n\t\tif (!parsed.success) return false;\n\t\tconst validated = await safeValidateTypes({\n\t\t\tvalue: parsed.value,\n\t\t\tschema\n\t\t});\n\t\tif (validated.success) pending = [validated.value];\n\t\telse if (!skipInvalidElements) return false;\n\t\telementText = \"\";\n\t\treturn true;\n\t}\n\tfunction publishPending() {\n\t\telements.push(...pending);\n\t\tpending = [];\n\t}\n\treturn async (textDelta) => {\n\t\tfor (const char of textDelta) {\n\t\t\tif (phase === 0) {\n\t\t\t\tprefix += char;\n\t\t\t\tif (char === \"[\") {\n\t\t\t\t\tif (!/^\\s*\\{\\s*\"elements\"\\s*:\\s*\\[$/.test(prefix)) return \"fallback\";\n\t\t\t\t\tphase = 1;\n\t\t\t\t} else if (prefix.length > 256) return \"fallback\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (phase === 2 || phase === 3) {\n\t\t\t\tif (/\\s/.test(char)) continue;\n\t\t\t\tif (phase === 2 && char === \"}\") {\n\t\t\t\t\tpublishPending();\n\t\t\t\t\tphase = 3;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn \"fallback\";\n\t\t\t}\n\t\t\tif (!inString && depth === 0 && (char === \",\" || char === \"]\")) {\n\t\t\t\tif (elementText.length > 0) {\n\t\t\t\t\tif (!await finishElement()) return \"fallback\";\n\t\t\t\t} else if (char === \",\" || afterComma) return \"fallback\";\n\t\t\t\tafterComma = char === \",\";\n\t\t\t\tif (char === \"]\") phase = 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (elementText.length === 0) {\n\t\t\t\tif (/\\s/.test(char)) continue;\n\t\t\t\tpublishPending();\n\t\t\t\tafterComma = false;\n\t\t\t}\n\t\t\telementText += char;\n\t\t\tif (inString) {\n\t\t\t\tif (escaped) escaped = false;\n\t\t\t\telse if (char === \"\\\\\") escaped = true;\n\t\t\t\telse if (char === \"\\\"\") inString = false;\n\t\t\t} else if (char === \"\\\"\") inString = true;\n\t\t\telse if (char === \"{\" || char === \"[\") depth++;\n\t\t\telse if (char === \"}\" || char === \"]\") depth--;\n\t\t}\n\t\tif (phase === 0 || publishedCount === elements.length) return;\n\t\tconst previousCount = publishedCount ?? 0;\n\t\tconst delta = (publishedCount == null ? \"[\" : \"\") + (previousCount > 0 && elements.length > previousCount ? \",\" : \"\") + elements.slice(previousCount).map((value) => JSON.stringify(value)).join(\",\") + (phase === 3 ? \"]\" : \"\");\n\t\tpublishedCount = elements.length;\n\t\treturn {\n\t\t\tpartial: elements.slice(),\n\t\t\ttextDelta: delta\n\t\t};\n\t};\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: processValueStart(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$2,\n\tchoice: () => choice,\n\tjson: () => json,\n\tobject: () => object$2,\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});\nfunction object$2({ 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\t...context,\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});\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\t...context,\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});\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}\nfunction array$2({ 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\tconst output = {\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\t...context,\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});\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\t...context,\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});\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\t...context,\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});\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\t...context,\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});\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\tconst parsePartialOutput = output.parsePartialOutput;\n\tarrayStreamParserFactories.set(output, () => output.parsePartialOutput === parsePartialOutput ? createArrayOutputStreamParser(elementSchema, true) : void 0);\n\treturn output;\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 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\t...context,\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});\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\t...context,\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});\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\t...context,\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});\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 globalThis.process?.release?.name === \"node\";\n}\n//#endregion\n//#region src/telemetry/redact-telemetry-credentials.ts\n/**\n* Apply provider-owned credential redaction on telemetry-only copies. Only visit SDK\n* metadata containers, never arbitrary prompts, tool outputs, or user context.\n*/\nfunction redactTelemetryCredentials(value) {\n\treturn replaceProperties(value, {\n\t\targs: redactTelemetryValue,\n\t\ttools: redactTools,\n\t\tstepTools: redactTools,\n\t\trequest: redactMetadata,\n\t\tresponse: redactMetadata,\n\t\tsteps: (steps) => mapArray(steps, redactTelemetryCredentials),\n\t\tfinalStep: redactTelemetryCredentials,\n\t\terror: redactTelemetryCredentials,\n\t\tcause: redactTelemetryCredentials,\n\t\terrors: (errors) => mapArray(errors, redactTelemetryCredentials),\n\t\tlastError: redactTelemetryCredentials,\n\t\trequestBodyValues: redactBody\n\t});\n}\nfunction redactMetadata(value) {\n\treturn Array.isArray(value) ? mapArray(value, redactMetadata) : replaceProperties(value, { body: redactBody });\n}\nfunction redactBody(value) {\n\treturn replaceProperties(redactTelemetryValue(value), { tools: redactTools });\n}\nfunction redactTools(value) {\n\tif (Array.isArray(value)) return mapArray(value, redactTelemetryCredentials);\n\tif (!isRecord$2(value)) return value;\n\treturn replaceProperties(value, Object.fromEntries(Object.keys(value).map((key) => [key, redactTelemetryCredentials])));\n}\nfunction isRecord$2(value) {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction mapArray(value, redact) {\n\tif (!Array.isArray(value)) return value;\n\tconst copy = value.map(redact);\n\treturn copy.some((entry, index) => entry !== value[index]) ? copy : value;\n}\n/** Preserve result getters, streams, and property descriptors without mutation. */\nfunction replaceProperties(value, redactors) {\n\tif (!isRecord$2(value)) return value;\n\tlet descriptors;\n\tfor (const [key, redact] of Object.entries(redactors)) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (descriptor == null || !(\"value\" in descriptor)) continue;\n\t\tconst redacted = redact(descriptor.value);\n\t\tif (redacted !== descriptor.value) {\n\t\t\tdescriptors ??= Object.getOwnPropertyDescriptors(value);\n\t\t\tdescriptors[key] = {\n\t\t\t\t...descriptor,\n\t\t\t\tvalue: redacted\n\t\t\t};\n\t\t}\n\t}\n\treturn descriptors == null ? value : Object.create(Object.getPrototypeOf(value), descriptors);\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, recordResult = true) {\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 recordResult ? executePromise.then(redactTelemetryCredentials, (error) => {\n\t\t\tthrow redactTelemetryCredentials(error);\n\t\t}) : executePromise.then(() => void 0, () => {\n\t\t\tthrow new Error(\"AI SDK operation failed\");\n\t\t});\n\t};\n\ttry {\n\t\tawait tracingChannel.tracePromise(tracedExecute, message);\n\t\treturn executionResult;\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, recordResult = true }) {\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 = recordResult ? redactTelemetryCredentials(error) : /* @__PURE__ */ new Error(\"AI SDK operation failed\");\n\t\t\tsafePublish(() => tracingChannel.error.publish(context));\n\t\t}\n\t\tif (recordResult && result !== void 0) context.result = redactTelemetryCredentials(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/filter-telemetry-event.ts\n/**\n* Filters SDK-owned content fields on a copy. Only descend into SDK event\n* containers; user context has its own inclusion policy.\n*/\nfunction filterTelemetryEvent(event, telemetry) {\n\tconst hideInputs = telemetry.recordInputs === false;\n\tconst hideOutputs = telemetry.recordOutputs === false;\n\tif (!hideInputs && !hideOutputs || event == null || typeof event !== \"object\") return event;\n\tconst filtered = Object.assign(Object.create(Object.getPrototypeOf(event)), event);\n\tconst replace = (fields) => {\n\t\tfor (const [key, value] of Object.entries(fields)) if (Object.hasOwn(event, key)) filtered[key] = value;\n\t};\n\tconst isSpeech = filtered.operationId === \"ai.generateSpeech\";\n\tif (hideInputs) {\n\t\treplace({\n\t\t\tinstructions: void 0,\n\t\t\tsystem: void 0,\n\t\t\tprompt: void 0,\n\t\t\tmessages: [],\n\t\t\tpromptMessages: [],\n\t\t\texperimental_steeringMessages: [],\n\t\t\ttools: void 0,\n\t\t\tstepTools: void 0,\n\t\t\tschema: void 0,\n\t\t\tschemaName: void 0,\n\t\t\tschemaDescription: void 0,\n\t\t\t...typeof filtered.output === \"object\" ? { output: void 0 } : {},\n\t\t\tproviderOptions: {},\n\t\t\tvalue: \"\",\n\t\t\tvalues: [],\n\t\t\tquery: \"\",\n\t\t\tdocuments: [],\n\t\t\tstate: Array.isArray(filtered.state) ? [] : typeof filtered.state === \"string\" ? \"\" : {},\n\t\t\tquestions: {},\n\t\t\t...isSpeech ? { text: \"\" } : {}\n\t\t});\n\t\tif (filtered.toolCall != null) filtered.toolCall = {\n\t\t\t...filtered.toolCall,\n\t\t\tinput: void 0\n\t\t};\n\t\tif (filtered.toolOutput != null) filtered.toolOutput = {\n\t\t\t...filtered.toolOutput,\n\t\t\tinput: void 0\n\t\t};\n\t\tif (Array.isArray(filtered.ranking)) filtered.ranking = filtered.ranking.map((entry) => \"document\" in entry ? {\n\t\t\t...entry,\n\t\t\tdocument: typeof entry.document === \"string\" ? \"\" : {}\n\t\t} : entry);\n\t}\n\tif (hideOutputs) {\n\t\treplace({\n\t\t\tcontent: [],\n\t\t\t...!isSpeech ? { text: \"\" } : {},\n\t\t\treasoning: Array.isArray(filtered.reasoning) ? [] : void 0,\n\t\t\treasoningText: void 0,\n\t\t\tfiles: [],\n\t\t\tsources: [],\n\t\t\ttoolCalls: [],\n\t\t\tstaticToolCalls: [],\n\t\t\tdynamicToolCalls: [],\n\t\t\ttoolResults: [],\n\t\t\tstaticToolResults: [],\n\t\t\tdynamicToolResults: [],\n\t\t\tresponseMessages: [],\n\t\t\tobject: void 0,\n\t\t\tobjectText: \"\",\n\t\t\tembedding: [],\n\t\t\tembeddings: [],\n\t\t\tranking: [],\n\t\t\tanswers: {},\n\t\t\tsegments: [],\n\t\t\twords: []\n\t\t});\n\t\tif (filtered.toolOutput != null) filtered.toolOutput = {\n\t\t\t...filtered.toolOutput,\n\t\t\toutput: void 0,\n\t\t\terror: void 0\n\t\t};\n\t}\n\treplace({\n\t\tproviderMetadata: void 0,\n\t\terror: filtered.error == null ? filtered.error : /* @__PURE__ */ new Error(\"AI SDK operation failed\")\n\t});\n\tfor (const key of [\"toolCall\", \"toolOutput\"]) {\n\t\tconst toolEvent = filtered[key];\n\t\tif (toolEvent != null && typeof toolEvent === \"object\") filtered[key] = {\n\t\t\t...toolEvent,\n\t\t\tproviderMetadata: void 0,\n\t\t\t...\"error\" in toolEvent ? { error: toolEvent.error == null ? toolEvent.error : /* @__PURE__ */ new Error(\"AI SDK operation failed\") } : {}\n\t\t};\n\t}\n\tfor (const key of [\"request\", \"response\"]) {\n\t\tconst filterMetadata = (metadata) => {\n\t\t\tif (metadata == null || typeof metadata !== \"object\") return metadata;\n\t\t\tconst filteredMetadata = { ...metadata };\n\t\t\tdelete filteredMetadata.body;\n\t\t\tif (key === \"request\" ? hideInputs : hideOutputs) {\n\t\t\t\tif (\"messages\" in metadata) filteredMetadata.messages = [];\n\t\t\t\tif (\"instructions\" in metadata) filteredMetadata.instructions = void 0;\n\t\t\t}\n\t\t\treturn filteredMetadata;\n\t\t};\n\t\tconst metadata = filtered[key];\n\t\tif (metadata != null) filtered[key] = Array.isArray(metadata) ? metadata.map(filterMetadata) : filterMetadata(metadata);\n\t}\n\tif (Array.isArray(filtered.steps)) filtered.steps = filtered.steps.map((step) => filterTelemetryEvent(step, telemetry));\n\tif (Object.hasOwn(event, \"finalStep\")) filtered.finalStep = filterTelemetryEvent(filtered.finalStep, telemetry);\n\treturn filtered;\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\taiVersion: VERSION\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 redactTelemetryCredentials(filterTelemetryEvent(augmentedEvent, telemetry));\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 recordResult = telemetry?.recordInputs !== false && telemetry?.recordOutputs !== false;\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, recordResult),\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\trecordResult\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\tonStepError: mergeTelemetryCallback(\"onStepError\"),\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 = async () => {\n\t\t\t\t\tconst originals = /* @__PURE__ */ new Map();\n\t\t\t\t\tconst redact = (original) => {\n\t\t\t\t\t\tconst redacted = redactTelemetryCredentials(original);\n\t\t\t\t\t\tif (redacted !== original) originals.set(redacted, original);\n\t\t\t\t\t\treturn redacted;\n\t\t\t\t\t};\n\t\t\t\t\tconst restore = (value) => originals.has(value) ? originals.get(value) : value;\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn restore(await executeWrapper({\n\t\t\t\t\t\t\t...augmentedEvent,\n\t\t\t\t\t\t\texecute: async () => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\treturn redact(await innerExecute());\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tthrow redact(error);\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} catch (error) {\n\t\t\t\t\t\tthrow restore(error);\n\t\t\t\t\t}\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, recordResult);\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, steeringMessages }) {\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\tif (steeringMessages != null && steeringMessages.length > 0) this.experimental_steeringMessages = steeringMessages;\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\tsteeringMessages: step.experimental_steeringMessages\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\tconst restrictStepStartEvent = (event) => ({\n\t\t...event,\n\t\truntimeContext: filterIncludedContext({\n\t\t\tcontext: event.runtimeContext,\n\t\t\tincludeContext: includeRuntimeContext\n\t\t}),\n\t\tsteps: event.steps.map((step) => restrictStepResult({\n\t\t\tstep,\n\t\t\tincludeRuntimeContext,\n\t\t\tincludeToolsContext\n\t\t})),\n\t\ttoolsContext: filterToolsContext({\n\t\t\ttoolsContext: event.toolsContext,\n\t\t\tincludeToolsContext\n\t\t})\n\t});\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?.(restrictStepStartEvent(event)),\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\tonStepError: (event) => telemetryDispatcher.onStepError?.(restrictStepStartEvent(event)),\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/steering.ts\nconst generateSteeringId = createIdGenerator$1({\n\tprefix: \"steer\",\n\tsize: 24\n});\nconst steeringRunStarter = Symbol.for(\"vercel.ai.steering.start\");\nvar DefaultSteering = class {\n\tconstructor() {\n\t\tthis.state = \"idle\";\n\t\tthis.pending = [];\n\t\tthis.queued = [];\n\t\tthis.taken = [];\n\t\tthis.outcomes = /* @__PURE__ */ new Map();\n\t}\n\tsteer(message, options) {\n\t\treturn this.add({\n\t\t\tmessage,\n\t\t\tid: options?.id,\n\t\t\ttarget: this.pending\n\t\t});\n\t}\n\tqueue(message, options) {\n\t\treturn this.add({\n\t\t\tmessage,\n\t\t\tid: options?.id,\n\t\t\ttarget: this.queued\n\t\t});\n\t}\n\tadd({ message, id = generateSteeringId(), target }) {\n\t\tconst existingOutcome = this.outcomes.get(id);\n\t\tif (existingOutcome != null) return existingOutcome;\n\t\tconst userMessage = typeof message === \"string\" ? {\n\t\t\trole: \"user\",\n\t\t\tcontent: message\n\t\t} : message;\n\t\tconst outcome = this.state === \"ended\" ? Promise.resolve({\n\t\t\ttype: \"not-delivered\",\n\t\t\tid,\n\t\t\tmessage: userMessage,\n\t\t\treason: \"finished\"\n\t\t}) : new Promise((resolve) => {\n\t\t\ttarget.push({\n\t\t\t\tid,\n\t\t\t\tmessage: userMessage,\n\t\t\t\tresolve\n\t\t\t});\n\t\t});\n\t\tthis.outcomes.set(id, outcome);\n\t\treturn outcome;\n\t}\n\t[steeringRunStarter]() {\n\t\tif (this.state !== \"idle\") throw new InvalidArgumentError({\n\t\t\tparameter: \"experimental_steering\",\n\t\t\tvalue: this,\n\t\t\tmessage: \"The steering object was already used by a generation. Create a new one with experimental_createSteering() for each call.\"\n\t\t});\n\t\tthis.state = \"running\";\n\t\treturn {\n\t\t\thasPendingMessages: () => this.state === \"running\" && this.pending.length > 0,\n\t\t\tpromoteQueuedMessage: () => {\n\t\t\t\tconst next = this.state === \"running\" ? this.queued.shift() : void 0;\n\t\t\t\tif (next == null) return false;\n\t\t\t\tthis.pending.push(next);\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\ttakeMessages: () => {\n\t\t\t\tif (this.state !== \"running\") return [];\n\t\t\t\tthis.taken = [...this.taken, ...this.pending];\n\t\t\t\tthis.pending = [];\n\t\t\t\treturn this.taken.map(({ message }) => message);\n\t\t\t},\n\t\t\tresolveTakenMessages: ({ stepNumber, sentMessages }) => {\n\t\t\t\tconst taken = this.taken;\n\t\t\t\tthis.taken = [];\n\t\t\t\tconst delivered = [];\n\t\t\t\tfor (const { id, message, resolve } of taken) if (isSent({\n\t\t\t\t\tmessage,\n\t\t\t\t\tsentMessages\n\t\t\t\t})) {\n\t\t\t\t\tdelivered.push({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tmessage\n\t\t\t\t\t});\n\t\t\t\t\tresolve({\n\t\t\t\t\t\ttype: \"delivered\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tstepNumber\n\t\t\t\t\t});\n\t\t\t\t} else resolve({\n\t\t\t\t\ttype: \"not-delivered\",\n\t\t\t\t\tid,\n\t\t\t\t\tmessage,\n\t\t\t\t\treason: \"removed-by-prepare-step\"\n\t\t\t\t});\n\t\t\t\treturn delivered;\n\t\t\t},\n\t\t\tend: (reason) => {\n\t\t\t\tif (this.state !== \"running\") return;\n\t\t\t\tconst notDelivered = [\n\t\t\t\t\t...this.taken,\n\t\t\t\t\t...this.pending,\n\t\t\t\t\t...this.queued\n\t\t\t\t];\n\t\t\t\tthis.taken = [];\n\t\t\t\tthis.pending = [];\n\t\t\t\tthis.queued = [];\n\t\t\t\tthis.state = \"ended\";\n\t\t\t\tfor (const { id, message, resolve } of notDelivered) resolve({\n\t\t\t\t\ttype: \"not-delivered\",\n\t\t\t\t\tid,\n\t\t\t\t\tmessage,\n\t\t\t\t\treason\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\t}\n};\nfunction isSent({ message, sentMessages }) {\n\tconst content = JSON.stringify(message.content);\n\treturn sentMessages.some((sentMessage) => sentMessage === message || sentMessage.role === \"user\" && JSON.stringify(sentMessage.content) === content);\n}\n/**\n* Creates a steering object that sends user messages to a running generation.\n*\n* @example\n* ```ts\n* const steering = experimental_createSteering();\n*\n* const result = streamText({\n* model,\n* tools,\n* stopWhen: isStepCount(20),\n* experimental_steering: steering,\n* });\n*\n* const outcome = await steering.steer('Use Paris, Texas instead.');\n* ```\n*/\nfunction createSteering() {\n\treturn new DefaultSteering();\n}\n/**\n* Starts a run for a steering object that was passed to a generation.\n*/\nfunction startSteeringRun(steering) {\n\tif (steering == null) return;\n\tconst start = steering[steeringRunStarter];\n\tif (typeof start !== \"function\") throw new InvalidArgumentError({\n\t\tparameter: \"experimental_steering\",\n\t\tvalue: steering,\n\t\tmessage: \"The steering object must be created with experimental_createSteering().\"\n\t});\n\treturn start.call(steering);\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 && part.providerMetadata == null) 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 collectedApproval of approvedToolApprovals) {\n\t\tconst tool = getOwn(tools, collectedApproval.toolCall.toolName);\n\t\tconst { toolMetadata: _toolMetadata, dynamic: _dynamic, ...toolCallFromHistory } = collectedApproval.toolCall;\n\t\tconst approval = {\n\t\t\t...collectedApproval,\n\t\t\ttoolCall: {\n\t\t\t\t...toolCallFromHistory,\n\t\t\t\t...tool?.metadata != null ? { toolMetadata: tool.metadata } : {},\n\t\t\t\t...tool?.type === \"dynamic\" ? { dynamic: true } : {},\n\t\t\t\ttitle: tool?.title\n\t\t\t}\n\t\t};\n\t\tconst { approvalRequest, toolCall } = approval;\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\tlet validationError;\n\t\t\ttry {\n\t\t\t\tconst approvedInput = structuredClone(toolCall.input);\n\t\t\t\tconst hasInputSchemaInput = Object.prototype.hasOwnProperty.call(approvalRequest, \"inputSchemaInput\");\n\t\t\t\tconst validation = await safeValidateTypes({\n\t\t\t\t\tvalue: structuredClone(hasInputSchemaInput ? approvalRequest.inputSchemaInput : toolCall.input),\n\t\t\t\t\tschema: asSchema$1(tool.inputSchema)\n\t\t\t\t});\n\t\t\t\tif (!validation.success) validationError = validation.error;\n\t\t\t\telse {\n\t\t\t\t\tconst revalidatedToolCall = await refineParsedToolCallInput({\n\t\t\t\t\t\ttoolCall: {\n\t\t\t\t\t\t\t...toolCall,\n\t\t\t\t\t\t\tinput: validation.value\n\t\t\t\t\t\t},\n\t\t\t\t\t\trefineToolInput\n\t\t\t\t\t});\n\t\t\t\t\tif (!isDeepEqualData(structuredClone(revalidatedToolCall.input), approvedInput)) validationError = /* @__PURE__ */ new Error(\"Approved tool input does not match the validated schema output.\");\n\t\t\t\t}\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/tool-call-concurrency.ts\n/**\n* Validates the maximum number of tool calls that may execute concurrently.\n*/\nfunction prepareToolCallConcurrency(toolCallConcurrency) {\n\tif (toolCallConcurrency == null) return;\n\tif (!Number.isInteger(toolCallConcurrency)) throw new InvalidArgumentError({\n\t\tparameter: \"toolCallConcurrency\",\n\t\tvalue: toolCallConcurrency,\n\t\tmessage: \"toolCallConcurrency must be an integer\"\n\t});\n\tif (toolCallConcurrency < 1) throw new InvalidArgumentError({\n\t\tparameter: \"toolCallConcurrency\",\n\t\tvalue: toolCallConcurrency,\n\t\tmessage: \"toolCallConcurrency must be >= 1\"\n\t});\n\treturn toolCallConcurrency;\n}\n/**\n* Maps items with an optional concurrency limit while preserving result order.\n*\n* Workers claim items in input order. When the signal is aborted or an\n* execution rejects, no additional queued items are started.\n*/\nasync function mapWithConcurrency({ items, concurrency, abortSignal, execute }) {\n\tif (concurrency == null || concurrency >= items.length) return Promise.all(items.map(execute));\n\tconst results = new Array(items.length);\n\tlet nextIndex = 0;\n\tlet stopped = false;\n\tconst worker = async () => {\n\t\twhile (!stopped) {\n\t\t\tabortSignal?.throwIfAborted();\n\t\t\tconst index = nextIndex++;\n\t\t\tif (index >= items.length) return;\n\t\t\ttry {\n\t\t\t\tresults[index] = await execute(items[index], index);\n\t\t\t} catch (error) {\n\t\t\t\tstopped = true;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t};\n\tawait Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));\n\treturn results;\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* @param toolCallConcurrency - Maximum number of tool calls that may execute concurrently within a step. Set to 1 for sequential execution. Default: unlimited.\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 experimental_steering - A steering object that adds user messages to the generation at the next step boundary.\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 onStepError - Callback that is called when a step that started fails before it produces a step result, i.e. when the provider call throws or rejects, or when the call is aborted or times out.\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(options) {\n\tconst steeringRun = startSteeringRun(options.experimental_steering);\n\ttry {\n\t\treturn await generateTextInternal(options, steeringRun);\n\t} catch (error) {\n\t\tsteeringRun?.end(options.abortSignal?.aborted ? \"aborted\" : \"error\");\n\t\tthrow error;\n\t}\n}\nasync function generateTextInternal({ 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, toolCallConcurrency, 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, onStepError, onStepFinish, onFinish, onEnd = onFinish, ...settings }, steeringRun) {\n\tinclude = {\n\t\trequestBody: include?.requestBody ?? false,\n\t\trequestMessages: include?.requestMessages ?? false,\n\t\tresponseBody: include?.responseBody ?? false\n\t};\n\tconst resolvedToolCallConcurrency = prepareToolCallConcurrency(toolCallConcurrency);\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\tlet openStep;\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\ttoolCallConcurrency: resolvedToolCallConcurrency\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\tlet steeringEndReason = \"finished\";\n\t\t\tconst shouldStartNextStep = async () => {\n\t\t\t\tif (steps[steps.length - 1].finishReason === \"interrupted\") return false;\n\t\t\t\tif (clientToolOutputs.length + deniedToolApprovalResponses.length !== clientToolCalls.length) {\n\t\t\t\t\tsteeringEndReason = \"waiting-for-tool-results\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (clientToolCalls.length === 0 && pendingDeferredToolCalls.size === 0) {\n\t\t\t\t\tconst isTruncated = steps[steps.length - 1].finishReason === \"length\" || steps[steps.length - 1].finishReason === \"content-filter\";\n\t\t\t\t\tif (!steeringRun?.hasPendingMessages() && (isTruncated || !steeringRun?.promoteQueuedMessage())) return false;\n\t\t\t\t\tif (steps[steps.length - 1].finishReason === \"error\") {\n\t\t\t\t\t\tsteeringEndReason = \"error\";\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (await isStopConditionMet({\n\t\t\t\t\tstopConditions,\n\t\t\t\t\tsteps\n\t\t\t\t})) {\n\t\t\t\t\tsteeringEndReason = \"stop-condition\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t};\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\tconst steeringMessages = steeringRun?.takeMessages() ?? [];\n\t\t\t\tif (steeringMessages.length > 0) messagesForNextStep = [...messagesForNextStep, ...steeringMessages];\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\t...steeringMessages.length > 0 ? { experimental_steeringMessages: steeringMessages } : {},\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, 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 stepExecutionTools = stepToolChoice.type === \"none\" ? void 0 : executionTools;\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 deliveredSteeringMessages = (steeringRun?.resolveTakenMessages({\n\t\t\t\t\t\t\t\tstepNumber,\n\t\t\t\t\t\t\t\tsentMessages: stepMessages\n\t\t\t\t\t\t\t}) ?? []).map(({ message }) => message);\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\tconst stepStartEvent = {\n\t\t\t\t\t\t\t\tcallId,\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\tstepNumber,\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,\n\t\t\t\t\t\t\t\ttoolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n\t\t\t\t\t\t\t\tactiveTools: prepareStepResult?.activeTools ?? activeTools,\n\t\t\t\t\t\t\t\ttoolOrder: stepToolOrder,\n\t\t\t\t\t\t\t\tsteps: [...steps],\n\t\t\t\t\t\t\t\tproviderOptions: stepProviderOptions,\n\t\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\t\truntimeContext,\n\t\t\t\t\t\t\t\tpromptMessages,\n\t\t\t\t\t\t\t\tstepTools,\n\t\t\t\t\t\t\t\tstepToolChoice,\n\t\t\t\t\t\t\t\ttoolsContext\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: stepStartEvent,\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\topenStep = stepStartEvent;\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 () => {\n\t\t\t\t\t\t\t\t\t\tconst result = await stepModel.doGenerate({\n\t\t\t\t\t\t\t\t\t\t\t...stepCallSettings,\n\t\t\t\t\t\t\t\t\t\t\ttools: stepTools,\n\t\t\t\t\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\t\t\t\t\tresponseFormat: await output?.responseFormat,\n\t\t\t\t\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\t\t\t\t\tproviderOptions: stepProviderOptions,\n\t\t\t\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\t\t\t\theaders: headersWithUserAgent\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\t\t\t\t\t...result.request && { request: sanitizeRequestMetadata(result.request) }\n\t\t\t\t\t\t\t\t\t\t};\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\treturn {\n\t\t\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\t\t\tid: result.response?.id ?? generateId(),\n\t\t\t\t\t\t\t\t\t\ttimestamp: result.response?.timestamp ?? /* @__PURE__ */ new Date(),\n\t\t\t\t\t\t\t\t\t\tmodelId: result.response?.modelId ?? stepModel.modelId,\n\t\t\t\t\t\t\t\t\t\theaders: result.response?.headers,\n\t\t\t\t\t\t\t\t\t\tbody: result.response?.body\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});\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: stepToolChoice.type === \"none\" ? void 0 : repairToolCall,\n\t\t\t\t\t\t\t\trefineToolInput: stepToolChoice.type === \"none\" ? void 0 : refineToolInput,\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\tdownload,\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.request?.url != null ? { request: { url: getRequestOrigin(currentModelResponse.request.url) } } : {},\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 === \"auto\" ? void 0 : stepToolChoice;\n\t\t\t\t\t\t\tif (enforcedToolChoice != null && (enforcedToolChoice.type === \"none\" ? stepToolCalls.length > 0 : currentModelResponse.finishReason.unified !== \"interrupted\" && !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\ttoolCallConcurrency: resolvedToolCallConcurrency\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\tdownload,\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\tsteeringMessages: deliveredSteeringMessages\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\topenStep = void 0;\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 (await shouldStartNextStep());\n\t\t\tsteeringRun?.end(steeringEndReason);\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) {\n\t\t\t\tconst outputSpecification = output ?? text();\n\t\t\t\tconst textForOutput = (await outputSpecification.responseFormat)?.type === \"json\" ? currentModelResponse.structuredOutputText ?? lastStep.text : lastStep.text;\n\t\t\t\tresolvedOutput = await outputSpecification.parseCompleteOutput({ text: textForOutput }, {\n\t\t\t\t\tresponse: lastStep.response,\n\t\t\t\t\tusage: lastStep.usage,\n\t\t\t\t\tfinishReason: lastStep.finishReason\n\t\t\t\t});\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\tconst wrappedError = wrapGatewayError(error);\n\t\t\tsteeringRun?.end(mergedAbortSignal?.aborted ? \"aborted\" : \"error\");\n\t\t\tif (openStep != null) await notify({\n\t\t\t\tevent: {\n\t\t\t\t\t...openStep,\n\t\t\t\t\terror: wrappedError\n\t\t\t\t},\n\t\t\t\tcallbacks: [onStepError, telemetryDispatcher.onStepError]\n\t\t\t});\n\t\t\tawait telemetryDispatcher.onError?.({\n\t\t\t\tcallId,\n\t\t\t\terror\n\t\t\t});\n\t\t\tthrow wrappedError;\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, toolCallConcurrency }) {\n\treturn (await mapWithConcurrency({\n\t\titems: toolCalls,\n\t\tconcurrency: toolCallConcurrency,\n\t\tabortSignal,\n\t\texecute: async (toolCall) => await executeToolCall({\n\t\t\ttoolCall,\n\t\t\ttools,\n\t\t\tcallId,\n\t\t\tmessages,\n\t\t\tabortSignal,\n\t\t\ttimeout,\n\t\t\texperimental_sandbox: sandbox,\n\t\t\ttoolsContext,\n\t\t\tonToolExecutionStart,\n\t\t\tonToolExecutionEnd,\n\t\t\texecuteToolInTelemetryContext,\n\t\t\trunInTracingChannelSpan\n\t\t})\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-model-tool-error-text.ts\n/**\n* Returns the error text that the model receives for a failed tool call (see\n* `createToolModelOutput` with `errorMode: 'text'`), or `undefined` when the\n* error cannot be serialized. In that case the model did not receive an error\n* text either, because creating the tool result fails the same way.\n*/\nfunction getModelToolErrorText(error) {\n\ttry {\n\t\treturn getErrorMessage$1(error);\n\t} catch {\n\t\treturn;\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/util/zod.ts\nconst z$1 = {\n\tNEVER,\n\tarray,\n\tboolean,\n\tcustom,\n\tdiscriminatedUnion,\n\tenum: enum$1,\n\textend,\n\tint,\n\tliteral,\n\tlooseObject,\n\tmaximum,\n\tminLength,\n\tnever,\n\tnonnegative,\n\tnumber,\n\tobject,\n\toptional,\n\tpipe,\n\tpositive,\n\trecord,\n\trefine,\n\tsafeParse,\n\tstartsWith,\n\tstring,\n\ttransform,\n\tunion,\n\tunknown\n};\n//#endregion\n//#region src/util/classic-zod.ts\nconst z = {\n\tarray: array$1,\n\tboolean: boolean$1,\n\tcustom: custom$1,\n\tdiscriminatedUnion: discriminatedUnion$1,\n\tinstanceof: instanceof$1,\n\tlazy,\n\tliteral: literal$1,\n\tnull: null$1,\n\tnumber: number$1,\n\tobject: object$1,\n\trecord: record$1,\n\tstring: string$1,\n\tunion: union$1,\n\tunknown: unknown$1\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$1 = z.record(z.string(), z.record(z.string(), jsonValueSchema.optional()));\n//#endregion\n//#region src/types/citation.ts\nconst citationSchema = z$1.object({\n\tsource: z$1.discriminatedUnion(\"sourceType\", [z$1.object({\n\t\ttype: z$1.literal(\"source\"),\n\t\tsourceType: z$1.literal(\"url\"),\n\t\tid: z$1.string(),\n\t\turl: z$1.string(),\n\t\ttitle: z$1.optional(z$1.string()),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}), z$1.object({\n\t\ttype: z$1.literal(\"source\"),\n\t\tsourceType: z$1.literal(\"document\"),\n\t\tid: z$1.string(),\n\t\tmediaType: z$1.string(),\n\t\ttitle: z$1.string(),\n\t\tfilename: z$1.optional(z$1.string()),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t})]),\n\tstartIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),\n\tendIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),\n\tcitedText: z$1.optional(z$1.string())\n});\n//#endregion\n//#region src/ui-message-stream/ui-message-chunks.ts\nconst toolMetadataSchema$1 = z$1.record(z$1.string(), z$1.optional(jsonValueSchema));\nconst uiMessageChunkSchema = lazySchema(() => zodSchema$1(z$1.union([\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"text-start\"),\n\t\tid: z$1.string(),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"text-delta\"),\n\t\tid: z$1.string(),\n\t\tdelta: z$1.string(),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"text-end\"),\n\t\tid: z$1.string(),\n\t\tcitations: z$1.optional(z$1.array(citationSchema)),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"error\"),\n\t\terrorText: z$1.string()\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"tool-input-start\"),\n\t\ttoolCallId: z$1.string(),\n\t\ttoolName: z$1.string(),\n\t\tinputEncoding: z$1.optional(z$1.enum([\"json\", \"text\"])),\n\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1),\n\t\ttoolMetadata: z$1.optional(toolMetadataSchema$1),\n\t\tdynamic: z$1.optional(z$1.boolean()),\n\t\ttitle: z$1.optional(z$1.string())\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"tool-input-delta\"),\n\t\ttoolCallId: z$1.string(),\n\t\tinputTextDelta: z$1.string()\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"tool-input-available\"),\n\t\ttoolCallId: z$1.string(),\n\t\ttoolName: z$1.string(),\n\t\tinput: z$1.unknown(),\n\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1),\n\t\ttoolMetadata: z$1.optional(toolMetadataSchema$1),\n\t\tdynamic: z$1.optional(z$1.boolean()),\n\t\ttitle: z$1.optional(z$1.string())\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"tool-input-error\"),\n\t\ttoolCallId: z$1.string(),\n\t\ttoolName: z$1.string(),\n\t\tinput: z$1.unknown(),\n\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1),\n\t\ttoolMetadata: z$1.optional(toolMetadataSchema$1),\n\t\tdynamic: z$1.optional(z$1.boolean()),\n\t\terrorText: z$1.string(),\n\t\ttitle: z$1.optional(z$1.string())\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"tool-approval-request\"),\n\t\tapprovalId: z$1.string(),\n\t\ttoolCallId: z$1.string(),\n\t\tapprovalDescriptor: z$1.optional(z$1.unknown()),\n\t\tinputSchemaInput: z$1.optional(z$1.unknown()),\n\t\treason: z$1.optional(z$1.string()),\n\t\tisAutomatic: z$1.optional(z$1.boolean()),\n\t\tsignature: z$1.optional(z$1.string())\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"tool-approval-response\"),\n\t\tapprovalId: z$1.string(),\n\t\tapproved: z$1.boolean(),\n\t\treason: z$1.optional(z$1.string()),\n\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"tool-output-available\"),\n\t\ttoolCallId: z$1.string(),\n\t\toutput: z$1.unknown(),\n\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1),\n\t\ttoolMetadata: z$1.optional(toolMetadataSchema$1),\n\t\tdynamic: z$1.optional(z$1.boolean()),\n\t\tpreliminary: z$1.optional(z$1.boolean())\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"tool-output-error\"),\n\t\ttoolCallId: z$1.string(),\n\t\terrorText: z$1.string(),\n\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1),\n\t\ttoolMetadata: z$1.optional(toolMetadataSchema$1),\n\t\tdynamic: z$1.optional(z$1.boolean())\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"tool-output-denied\"),\n\t\ttoolCallId: z$1.string()\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"reasoning-start\"),\n\t\tid: z$1.string(),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"reasoning-delta\"),\n\t\tid: z$1.string(),\n\t\tdelta: z$1.string(),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"reasoning-end\"),\n\t\tid: z$1.string(),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"custom\"),\n\t\tkind: z$1.pipe(z$1.string(), z$1.transform((value) => value)),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"source-url\"),\n\t\tsourceId: z$1.string(),\n\t\turl: z$1.string(),\n\t\ttitle: z$1.optional(z$1.string()),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"source-document\"),\n\t\tsourceId: z$1.string(),\n\t\tmediaType: z$1.string(),\n\t\ttitle: z$1.string(),\n\t\tfilename: z$1.optional(z$1.string()),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"file\"),\n\t\turl: z$1.string(),\n\t\tmediaType: z$1.string(),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"reasoning-file\"),\n\t\turl: z$1.string(),\n\t\tmediaType: z$1.string(),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"steering-message\"),\n\t\tid: z$1.string(),\n\t\tparts: z$1.array(z$1.union([z$1.looseObject({\n\t\t\ttype: z$1.literal(\"text\"),\n\t\t\ttext: z$1.string(),\n\t\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t\t}), z$1.looseObject({\n\t\t\ttype: z$1.literal(\"file\"),\n\t\t\tmediaType: z$1.string(),\n\t\t\turl: z$1.string(),\n\t\t\tfilename: z$1.optional(z$1.string()),\n\t\t\tproviderReference: z$1.optional(z$1.record(z$1.string(), z$1.string())),\n\t\t\tproviderMetadata: z$1.optional(providerMetadataSchema$1)\n\t\t})]))\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.custom((value) => typeof value === \"string\" && value.startsWith(\"data-\"), { message: \"Type must start with \\\"data-\\\"\" }),\n\t\tid: z$1.optional(z$1.string()),\n\t\tdata: z$1.unknown(),\n\t\ttransient: z$1.optional(z$1.boolean())\n\t}),\n\tz$1.looseObject({ type: z$1.literal(\"start-step\") }),\n\tz$1.looseObject({ type: z$1.literal(\"finish-step\") }),\n\tz$1.looseObject({ type: z$1.literal(\"reset-step\") }),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"start\"),\n\t\tmessageId: z$1.optional(z$1.string()),\n\t\tmessageMetadata: z$1.optional(z$1.unknown())\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"finish\"),\n\t\tfinishReason: z$1.optional(z$1.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\"interrupted\",\n\t\t\t\"other\"\n\t\t])),\n\t\tmessageMetadata: z$1.optional(z$1.unknown())\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"abort\"),\n\t\treason: z$1.optional(z$1.string())\n\t}),\n\tz$1.looseObject({\n\t\ttype: z$1.literal(\"message-metadata\"),\n\t\tmessageMetadata: z$1.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\tinputEncoding: part.inputEncoding,\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\tlet isFirstMessageStart = true;\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.type = `tool-${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\tif (anyOptions.inputEncoding != null) anyPart.inputEncoding = anyOptions.inputEncoding;\n\t\t\t\t\telse delete anyPart.inputEncoding;\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\t...anyOptions.inputEncoding != null ? { inputEncoding: anyOptions.inputEncoding } : {},\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\tif (anyOptions.inputEncoding != null) anyPart.inputEncoding = anyOptions.inputEncoding;\n\t\t\t\t\telse delete anyPart.inputEncoding;\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\t...anyOptions.inputEncoding != null ? { inputEncoding: anyOptions.inputEncoding } : {},\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\tif (chunk.citations != null) textPart.citations = chunk.citations;\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\tinputEncoding: chunk.inputEncoding,\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\tinputEncoding: chunk.inputEncoding,\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\tinputEncoding: chunk.inputEncoding,\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 partialArgs = partialToolCall.inputEncoding === \"text\" ? partialToolCall.text : (await parsePartialJson(partialToolCall.text)).value;\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\tinputEncoding: partialToolCall.inputEncoding,\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\tinputEncoding: partialToolCall.inputEncoding,\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 \"steering-message\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"steering-message\",\n\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\tparts: chunk.parts\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\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\tconst shouldReset = resetStateOnFirstMessageStart && isFirstMessageStart || resetStateOnMessageIdChange && chunk.messageId != null && chunk.messageId !== state.message.id;\n\t\t\t\t\tisFirstMessageStart = false;\n\t\t\t\t\tif (shouldReset) Object.assign(state, createStreamingUIMessageState({\n\t\t\t\t\t\tlastMessage: void 0,\n\t\t\t\t\t\tmessageId: chunk.messageId ?? state.message.id\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 (shouldReset || chunk.messageId != null || chunk.messageMetadata != null) write({ updateStatus: false });\n\t\t\t\t\tbreak;\n\t\t\t\t}\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\tconst dataPartSchema = dataPartSchemas?.[chunk.type.slice(5)];\n\t\t\t\t\tif (dataPartSchema != 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: dataPartSchema,\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: onErrorOption, redactToolErrors = onErrorOption != null, messageMetadata, responseMessageId } = {}) {\n\tconst onError = onErrorOption ?? (() => \"An error occurred.\");\n\tconst getToolErrorText = (error) => redactToolErrors ? onError(error) : getModelToolErrorText(error) ?? onError(error);\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.citations != null ? { citations: part.citations } : {},\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.inputEncoding != null ? { inputEncoding: part.inputEncoding } : {},\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: part.providerExecuted ? onError(part.error) : getToolErrorText(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) : getToolErrorText(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 \"steering-message\": return {\n\t\t\ttype: \"steering-message\",\n\t\t\tid: part.id,\n\t\t\tparts: convertUserMessageToUIParts(part.message)\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 \"ping\":\n\t\tcase \"raw\": return;\n\t\tdefault: throw new Error(`Unknown chunk type: ${partType}`);\n\t}\n}\nfunction convertUserMessageToUIParts(message) {\n\tif (typeof message.content === \"string\") return [{\n\t\ttype: \"text\",\n\t\ttext: message.content\n\t}];\n\treturn message.content.map((part) => {\n\t\tconst providerMetadata = part.providerOptions != null ? { providerMetadata: part.providerOptions } : {};\n\t\tif (part.type === \"text\") return {\n\t\t\ttype: \"text\",\n\t\t\ttext: part.text,\n\t\t\t...providerMetadata\n\t\t};\n\t\tconst { data, mediaType: dataUrlMediaType } = convertToLanguageModelV4FilePart(part.type === \"image\" ? part.image : part.data);\n\t\tconst mediaType = dataUrlMediaType ?? part.mediaType ?? \"image\";\n\t\tconst filename = part.type === \"file\" ? part.filename : void 0;\n\t\tconst file = {\n\t\t\ttype: \"file\",\n\t\t\tmediaType,\n\t\t\t...filename != null ? { filename } : {},\n\t\t\t...providerMetadata\n\t\t};\n\t\tswitch (data.type) {\n\t\t\tcase \"url\": return {\n\t\t\t\t...file,\n\t\t\t\turl: data.url.toString()\n\t\t\t};\n\t\t\tcase \"data\": return {\n\t\t\t\t...file,\n\t\t\t\turl: `data:${mediaType};base64,${convertDataContentToBase64String(data.data)}`\n\t\t\t};\n\t\t\tcase \"text\": return {\n\t\t\t\t...file,\n\t\t\t\turl: `data:${mediaType};base64,${convertUint8ArrayToBase64(new TextEncoder().encode(data.text))}`\n\t\t\t};\n\t\t\tcase \"reference\": return {\n\t\t\t\t...file,\n\t\t\t\turl: \"\",\n\t\t\t\tproviderReference: data.reference\n\t\t\t};\n\t\t}\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, redactToolErrors, messageMetadata, originalMessages, generateMessageId, onStepEnd, onStepFinish, onEnd, onFinish }) {\n\tlet outcome = { status: \"unknown\" };\n\tlet hasFatalFailure = false;\n\tconst invalidToolCallIds = /* @__PURE__ */ new Set();\n\tlet mismatchedToolCallIdInCurrentStep;\n\tlet mismatchedToolCallIdInEarlierStep;\n\tlet hasWarnedAboutToolErrorMismatch = 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\tif (part.type === \"tool-call\" && part.invalid) invalidToolCallIds.add(part.toolCallId);\n\t\t\t\tconst isInvalidToolCallError = part.type === \"tool-error\" && !part.providerExecuted && invalidToolCallIds.delete(part.toolCallId);\n\t\t\t\tconst messageMetadataValue = messageMetadata?.({ part });\n\t\t\t\tconst uiMessageChunk = isInvalidToolCallError ? void 0 : 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\tredactToolErrors,\n\t\t\t\t\tmessageMetadata: messageMetadataValue,\n\t\t\t\t\tresponseMessageId\n\t\t\t\t});\n\t\t\t\tif (part.type === \"start-step\") {\n\t\t\t\t\tmismatchedToolCallIdInEarlierStep ??= mismatchedToolCallIdInCurrentStep;\n\t\t\t\t\tmismatchedToolCallIdInCurrentStep = void 0;\n\t\t\t\t} else if ((part.type === \"tool-error\" || part.type === \"tool-call\") && !part.providerExecuted && (uiMessageChunk?.type === \"tool-output-error\" || uiMessageChunk?.type === \"tool-input-error\")) {\n\t\t\t\t\tconst { errorText } = uiMessageChunk;\n\t\t\t\t\tconst modelErrorText = getModelToolErrorText(part.error);\n\t\t\t\t\tif (modelErrorText != null && errorText !== modelErrorText) mismatchedToolCallIdInCurrentStep ??= part.toolCallId;\n\t\t\t\t} else if (uiMessageChunk?.type === \"reasoning-start\" && mismatchedToolCallIdInEarlierStep != null && !hasWarnedAboutToolErrorMismatch) {\n\t\t\t\t\thasWarnedAboutToolErrorMismatch = true;\n\t\t\t\t\tlogWarnings({ warnings: [{\n\t\t\t\t\t\ttype: \"other\",\n\t\t\t\t\t\tmessage: `The error text sent to the UI for tool call \"${mismatchedToolCallIdInEarlierStep}\" differs from the error text the model received, and reasoning from a later step was sent to the UI. Converting these UI messages back to model messages changes the tool result. Models that bind reasoning to the preceding messages (for example Anthropic models with preserved thinking) reject that history. See https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-tool-usage#tool-error-text-and-message-history`\n\t\t\t\t\t}] });\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: onError ?? (() => \"An error occurred.\"),\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, toolCallConcurrency }) {\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 mapWithConcurrency({\n\t\t\t\t\titems: toolCallsToExecute,\n\t\t\t\t\tconcurrency: toolCallConcurrency,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\texecute: async (toolCall) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await executeToolCall({\n\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t\texperimental_sandbox: sandbox,\n\t\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\t\tonToolExecutionStart,\n\t\t\t\t\t\t\t\tonToolExecutionEnd,\n\t\t\t\t\t\t\t\texecuteToolInTelemetryContext,\n\t\t\t\t\t\t\t\trunInTracingChannelSpan,\n\t\t\t\t\t\t\t\tonPreliminaryToolResult: (result) => {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(result);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (result != null) {\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"tool-execution-end\",\n\t\t\t\t\t\t\t\t\ttoolCallId: result.output.toolCallId,\n\t\t\t\t\t\t\t\t\ttoolExecutionMs: result.toolExecutionMs\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue(result.output);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror\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}\n\t} }));\n}\n//#endregion\n//#region src/generate-text/is-output-chunk.ts\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\tping: false,\n\traw: false\n};\nfunction isOutputChunk$1(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//#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/generate-text/stream-text-single-consumer-result.ts\n/** Expose only the stream and completion metadata for a single consumer. */\nfunction createSingleConsumerStreamTextResult(result) {\n\treturn {\n\t\tget textStream() {\n\t\t\treturn result.textStream;\n\t\t},\n\t\tget stream() {\n\t\t\treturn result.stream;\n\t\t},\n\t\tget fullStream() {\n\t\t\treturn result.fullStream;\n\t\t},\n\t\tget partialOutputStream() {\n\t\t\treturn result.partialOutputStream;\n\t\t},\n\t\tget elementStream() {\n\t\t\treturn result.elementStream;\n\t\t},\n\t\tget totalUsage() {\n\t\t\treturn result.totalUsage;\n\t\t},\n\t\tget usage() {\n\t\t\treturn result.usage;\n\t\t},\n\t\tget finishReason() {\n\t\t\treturn result.finishReason;\n\t\t},\n\t\tget rawFinishReason() {\n\t\t\treturn result.rawFinishReason;\n\t\t},\n\t\tconsumeStream: result.consumeStream.bind(result),\n\t\ttoUIMessageStream: result.toUIMessageStream.bind(result),\n\t\ttoUIMessageStreamResponse: result.toUIMessageStreamResponse.bind(result),\n\t\ttoTextStreamResponse: result.toTextStreamResponse.bind(result),\n\t\tpipeUIMessageStreamToResponse: result.pipeUIMessageStreamToResponse.bind(result),\n\t\tpipeTextStreamToResponse: result.pipeTextStreamToResponse.bind(result)\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 and generated file URLs.\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, collectContent = true } = {}, 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 () => {\n\t\t\tconst result = await resolvedModel.doStream({\n\t\t\t\t...callSettings,\n\t\t\t\ttools: stepTools,\n\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\tresponseFormat: await output?.responseFormat,\n\t\t\t\tprompt: promptMessages,\n\t\t\t\tproviderOptions,\n\t\t\t\tabortSignal,\n\t\t\t\theaders,\n\t\t\t\tincludeRawChunks\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\t...result.request && { request: sanitizeRequestMetadata(result.request) }\n\t\t\t};\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\tdownload,\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\trequest,\n\t\t\tonLanguageModelCallEnd,\n\t\t\tcollectContent\n\t\t}))),\n\t\tresponse,\n\t\trequest\n\t};\n}\nfunction createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({ tools, instructions, messages, repairToolCall, refineToolInput, download, abortSignal, callId, provider, modelId, toolChoice, generateId, now, callStartTimestampMs, request, onLanguageModelCallEnd, collectContent }) {\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\tconst withholdToolParts = toolChoice.type === \"none\";\n\treturn new TransformStream({ async transform(chunk, controller) {\n\t\tif (isOutputChunk(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\tif (withholdToolParts && (chunk.type === \"tool-input-start\" || chunk.type === \"tool-input-delta\" || chunk.type === \"tool-input-end\")) return;\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\tenabled: collectContent,\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\tenabled: collectContent,\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\tenabled: collectContent,\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\tenabled: collectContent,\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\tenabled: collectContent,\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\tenabled: collectContent,\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\tdownload,\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\tif (collectContent) modelCallContent.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\tif (collectContent) rawModelCallContent.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...request?.url != null ? { request: { url: getRequestOrigin(request.url) } } : {},\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 === \"auto\" ? void 0 : toolChoice;\n\t\t\t\tconst toolChoiceViolationError = enforcedToolChoice != null && (enforcedToolChoice.type === \"none\" ? toolCallsByToolCallId.size > 0 : chunk.finishReason.unified !== \"interrupted\" && ![...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\tif (collectContent) rawModelCallContent.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: withholdToolParts ? void 0 : repairToolCall,\n\t\t\t\t\t\trefineToolInput: withholdToolParts ? void 0 : refineToolInput,\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\tif (collectContent) modelCallContent.push(toolCall);\n\t\t\t\t\tif (withholdToolParts) break;\n\t\t\t\t\tcontroller.enqueue(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\tif (collectContent) rawModelCallContent.push(chunk);\n\t\t\t\tif (withholdToolParts) break;\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\tif (collectContent) modelCallContent.push(toolApprovalRequest);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool-result\": {\n\t\t\t\tif (collectContent) rawModelCallContent.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\tif (!withholdToolParts) controller.enqueue(toolResultPart);\n\t\t\t\tif (collectContent) modelCallContent.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\tif (collectContent) modelCallContent.push(chunk);\n\t\t\t\t\tif (collectContent) rawModelCallContent.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(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({ enabled, content, rawContent, partIndexes, rawPartIndexes, id, type, textDelta, providerMetadata }) {\n\tif (!enabled) return;\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});\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* @param toolCallConcurrency - Maximum number of tool calls that may execute concurrently within a step. Set to 1 for sequential execution. Default: unlimited.\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 experimental_steering - A steering object that adds user messages to the generation at the next step boundary.\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 onStepError - Callback that is called when a step that started fails before it produces a step result, i.e. when the provider call throws or rejects, or when the model stream ends without output. A provider `error` chunk still ends the step with `onStepEnd`, and an abort or timeout ends it with `onAbort`.\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(options) {\n\treturn startStreamText(options);\n}\n/**\n* Stream text with a single consumer, without replay or final-content getters.\n* Accepts the same options as streamText and uses the same execution engine.\n*/\nfunction streamTextLowMemory(options) {\n\tconst telemetry = options.telemetry ?? options.experimental_telemetry;\n\tconst integrations = telemetry?.integrations != null ? asArray(telemetry.integrations) : getGlobalTelemetryIntegrations();\n\tconst collectContent = options.tools != null && Object.keys(options.tools).length > 0 || options.toolChoice != null || options.output != null || options.prepareStep != null || options.stopWhen != null || options.onEnd != null || options.onFinish != null || options.onStepEnd != null || options.onStepFinish != null || options.onAbort != null || options.onLanguageModelCallEnd != null || options.experimental_onLanguageModelCallEnd != null || telemetry?.isEnabled !== false && integrations.length > 0;\n\treturn createSingleConsumerStreamTextResult(startStreamText({\n\t\t...options,\n\t\t_internal: {\n\t\t\t...options._internal,\n\t\t\tretention: {\n\t\t\t\treplay: false,\n\t\t\t\tcollectContent\n\t\t\t}\n\t\t}\n\t}));\n}\nfunction startStreamText(options) {\n\tconst steeringRun = startSteeringRun(options.experimental_steering);\n\ttry {\n\t\treturn streamTextInternal(options, steeringRun);\n\t} catch (error) {\n\t\tsteeringRun?.end(\"error\");\n\t\tthrow error;\n\t}\n}\nfunction streamTextInternal({ 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, toolCallConcurrency, experimental_repairToolCall, repairToolCall = experimental_repairToolCall, experimental_refineToolInput: refineToolInput, experimental_transform: transform, experimental_download: download, includeRawChunks, onChunk, onError: onErrorArg, onFinish, onEnd = onFinish, onAbort, onStepEnd, onStepError, 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, retention = {\n\treplay: true,\n\tcollectContent: true\n} } = {}, ...settings }, steeringRun) {\n\tconst resolvedToolCallConcurrency = prepareToolCallConcurrency(toolCallConcurrency);\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\tretention,\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\tsteeringRun,\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\ttoolCallConcurrency: resolvedToolCallConcurrency,\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\tonStepError,\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, collectOutput = true) {\n\tlet firstTextChunkId = void 0;\n\tlet text = \"\";\n\tlet textChunk = \"\";\n\tlet textProviderMetadata = void 0;\n\tlet arrayStreamParser = createArrayStreamParser(output);\n\tlet lastArrayPartial;\n\tlet lastPublishedValue = void 0;\n\tlet hasPublishedValue = false;\n\tfunction resetOutputState() {\n\t\tarrayStreamParser = createArrayStreamParser(output);\n\t\tlastArrayPartial = void 0;\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 (!collectOutput) {\n\t\t\tcontroller.enqueue(isStreamRetryBoundaryPart(chunk) ? chunk : {\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\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\tif (arrayStreamParser != null) {\n\t\t\tconst result = await arrayStreamParser(chunk.text);\n\t\t\tif (result !== \"fallback\") {\n\t\t\t\tif (result != null) {\n\t\t\t\t\tlastArrayPartial = result.partial;\n\t\t\t\t\tpublishTextChunk({\n\t\t\t\t\t\tcontroller,\n\t\t\t\t\t\tpartialOutput: lastArrayPartial\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tarrayStreamParser = void 0;\n\t\t\tif (lastArrayPartial != null) {\n\t\t\t\tlastPublishedValue = JSON.stringify(lastArrayPartial);\n\t\t\t\thasPublishedValue = true;\n\t\t\t}\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({ retention, model, telemetry, headers, settings, maxRetries: maxRetriesArg, streamRetries: streamRetriesArg, abortSignal, stepTimeoutMs, stepAbortController, firstChunkTimeoutMs, firstChunkAbortController, chunkTimeoutMs, chunkAbortController, instructions, system, prompt, messages, allowSystemInMessages, experimental_sandbox: sandbox, steeringRun, tools, toolChoice, transforms, activeTools, toolOrder, toolCallConcurrency, repairToolCall, refineToolInput, stopConditions, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, providerOptions, prepareStep, now, generateId, generateCallId, timeout, onChunk, onError, canRetryStreamViaOnError, onEnd, onAbort, onStepFinish, onStepError, 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.streamClaimed = false;\n\t\tthis.retention = retention;\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\tlet recordedSteps = [];\n\t\tconst initialResponseMessages = [];\n\t\tlet stepMessagesForNextStep;\n\t\tlet currentStepMessages = [];\n\t\tlet currentStepSteeringMessages = [];\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\tlet openStep;\n\t\tconst notifyStepError = async (error) => {\n\t\t\tif (openStep == null || abortSignal?.aborted) return;\n\t\t\tconst { event } = openStep;\n\t\t\topenStep = void 0;\n\t\t\tawait notify({\n\t\t\t\tevent: {\n\t\t\t\t\t...event,\n\t\t\t\t\terror\n\t\t\t\t},\n\t\t\t\tcallbacks: [onStepError, telemetryDispatcher.onStepError]\n\t\t\t});\n\t\t};\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 {\n\t\t\t\t\t\tif (openStep != null) openStep.error = error;\n\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\tevent: { error },\n\t\t\t\t\t\t\tcallbacks: async (event) => {\n\t\t\t\t\t\t\t\tawait onError(event);\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\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\") {\n\t\t\t\t\tif (retention.collectContent) recordedContent.push(part);\n\t\t\t\t}\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\tif (retention.collectContent) recordedContent.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\tif (retention.collectContent) activeText.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\tif (part.citations != null) activeText.citations = part.citations;\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\tif (retention.collectContent) recordedContent.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\tif (retention.collectContent) activeReasoning.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\") {\n\t\t\t\t\tif (retention.collectContent) recordedContent.push({\n\t\t\t\t\t\ttype: part.type,\n\t\t\t\t\t\tfile: part.file,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (part.type === \"tool-result\" && !part.preliminary) {\n\t\t\t\t\tif (retention.collectContent) recordedContent.push(part);\n\t\t\t\t}\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\tsteeringMessages: currentStepSteeringMessages\n\t\t\t\t\t});\n\t\t\t\t\topenStep = void 0;\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\tsteeringRun?.end(recordedSteps.length === 0 || recordedNoOutputError != null ? \"error\" : \"finished\");\n\t\t\t\ttry {\n\t\t\t\t\tconst noOutputError = new NoOutputGeneratedError({ message: \"No output generated. Check the stream for errors.\" });\n\t\t\t\t\tawait notifyStepError(openStep?.error ?? noOutputError);\n\t\t\t\t\tif (recordedSteps.length === 0 || recordedNoOutputError != null) {\n\t\t\t\t\t\tconst error = abortSignal?.aborted ? abortSignal.reason : recordedNoOutputError ?? noOutputError;\n\t\t\t\t\t\tif (recordedNoOutputError != null && !abortSignal?.aborted) await telemetryDispatcher.onError?.({\n\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\terror: recordedNoOutputError\n\t\t\t\t\t\t});\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(retention.replay ? 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 (retention.replay ? self.getOutputPromise() : self.parseOutput(finalStep)).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} finally {\n\t\t\t\t\tif (!retention.replay) {\n\t\t\t\t\t\trecordedSteps = [];\n\t\t\t\t\t\trecordedContent = [];\n\t\t\t\t\t\trecordedRequestMessages = [];\n\t\t\t\t\t\tcurrentStepMessages = [];\n\t\t\t\t\t\tstepMessagesForNextStep = void 0;\n\t\t\t\t\t\tactiveTextContent = createIdMap();\n\t\t\t\t\t\tactiveReasoningContent = createIdMap();\n\t\t\t\t\t}\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\tsteeringRun?.end(\"aborted\");\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\tsteeringRun?.end(\"error\");\n\t\t\t\t\t\tawait notifyStepError(wrapGatewayError(error));\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\tsteeringRun?.end(\"aborted\");\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(), retention.replay || output != null)).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 mapWithConcurrency({\n\t\t\t\t\t\titems: localApprovedToolApprovals,\n\t\t\t\t\t\tconcurrency: toolCallConcurrency,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\texecute: async (toolApproval) => {\n\t\t\t\t\t\t\tconst result = await executeToolCall({\n\t\t\t\t\t\t\t\ttoolCall: toolApproval.toolCall,\n\t\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\t\tcallId,\n\t\t\t\t\t\t\t\tmessages: initialMessages,\n\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t\texperimental_sandbox: sandbox,\n\t\t\t\t\t\t\t\ttoolsContext,\n\t\t\t\t\t\t\t\tonToolExecutionStart: filterNullable(onToolExecutionStart, telemetryDispatcher.onToolExecutionStart),\n\t\t\t\t\t\t\t\tonToolExecutionEnd: filterNullable(onToolExecutionEnd, telemetryDispatcher.onToolExecutionEnd),\n\t\t\t\t\t\t\t\texecuteToolInTelemetryContext: telemetryDispatcher.executeTool,\n\t\t\t\t\t\t\t\trunInTracingChannelSpan: runInTracingChannelSpanInStreamText,\n\t\t\t\t\t\t\t\tonPreliminaryToolResult: (result) => {\n\t\t\t\t\t\t\t\t\ttoolExecutionStepStreamController?.enqueue(result);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (result != null) {\n\t\t\t\t\t\t\t\ttoolExecutionStepStreamController?.enqueue(result.output);\n\t\t\t\t\t\t\t\ttoolOutputs.push(result.output);\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\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 steeringMessages = steeringRun?.takeMessages() ?? [];\n\t\t\t\t\tconst stepInputMessages = [...stepMessagesForNextStep ?? [...initialMessages, ...initialResponseMessages], ...steeringMessages];\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\t...steeringMessages.length > 0 ? { experimental_steeringMessages: steeringMessages } : {},\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, 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 stepExecutionTools = stepToolChoice.type === \"none\" ? void 0 : executionTools;\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 deliveredSteeringMessages = steeringRun?.resolveTakenMessages({\n\t\t\t\t\t\tstepNumber: currentStep,\n\t\t\t\t\t\tsentMessages: stepMessages\n\t\t\t\t\t}) ?? [];\n\t\t\t\t\tcurrentStepSteeringMessages = deliveredSteeringMessages.map(({ message }) => message);\n\t\t\t\t\tif (deliveredSteeringMessages.length > 0) self.addStream(new ReadableStream({ start(controller) {\n\t\t\t\t\t\tfor (const { id, message } of deliveredSteeringMessages) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"steering-message\",\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\tstepNumber: currentStep\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} }));\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\tconst stepStartEvent = {\n\t\t\t\t\t\t\t\tcallId,\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\tstepNumber: recordedSteps.length,\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,\n\t\t\t\t\t\t\t\ttoolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n\t\t\t\t\t\t\t\tactiveTools: prepareStepResult?.activeTools ?? activeTools,\n\t\t\t\t\t\t\t\ttoolOrder: stepToolOrder,\n\t\t\t\t\t\t\t\tsteps: [...recordedSteps],\n\t\t\t\t\t\t\t\tproviderOptions: stepProviderOptions,\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\toutput,\n\t\t\t\t\t\t\t\tpromptMessages,\n\t\t\t\t\t\t\t\tstepTools,\n\t\t\t\t\t\t\t\tstepToolChoice\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: stepStartEvent,\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\topenStep = { event: stepStartEvent };\n\t\t\t\t\t\t},\n\t\t\t\t\t\t_internal: {\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\tcollectContent: retention.collectContent\n\t\t\t\t\t\t},\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$1(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\" && value.type !== \"ping\" && (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\ttoolCallConcurrency\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$1(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 \"ping\":\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\tlet steeringEndReason = \"finished\";\n\t\t\t\t\t\t\tconst shouldStartNextStep = async () => {\n\t\t\t\t\t\t\t\tif (stepFinishReason === \"interrupted\") return false;\n\t\t\t\t\t\t\t\tif (clientToolCalls.length !== clientToolOutputs.length + deniedToolApprovalResponses.length) {\n\t\t\t\t\t\t\t\t\tsteeringEndReason = \"waiting-for-tool-results\";\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (clientToolCalls.length === 0 && pendingDeferredToolCalls.size === 0) {\n\t\t\t\t\t\t\t\t\tconst isTruncated = stepFinishReason === \"length\" || stepFinishReason === \"content-filter\";\n\t\t\t\t\t\t\t\t\tif (!steeringRun?.hasPendingMessages() && (isTruncated || !steeringRun?.promoteQueuedMessage())) return false;\n\t\t\t\t\t\t\t\t\tif (stepFinishReason === \"error\") {\n\t\t\t\t\t\t\t\t\t\tsteeringEndReason = \"error\";\n\t\t\t\t\t\t\t\t\t\treturn false;\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\tif (await isStopConditionMet({\n\t\t\t\t\t\t\t\t\tstopConditions,\n\t\t\t\t\t\t\t\t\tsteps: recordedSteps\n\t\t\t\t\t\t\t\t})) {\n\t\t\t\t\t\t\t\t\tsteeringEndReason = \"stop-condition\";\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (await shouldStartNextStep()) 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\tsteeringRun?.end(\"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\tsteeringRun?.end(steeringEndReason);\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\tsteeringRun?.end(abortSignal?.aborted ? \"aborted\" : \"error\");\n\t\t\tawait notifyStepError(wrapGatewayError(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\tif (this.retention.replay) this.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\tif (this.retention.replay) this.consumeStream();\n\t\treturn this._totalUsage.promise;\n\t}\n\tget finishReason() {\n\t\tif (this.retention.replay) this.consumeStream();\n\t\treturn this._finishReason.promise;\n\t}\n\tget rawFinishReason() {\n\t\tif (this.retention.replay) this.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\tif (!this.retention.replay) {\n\t\t\tif (this.streamClaimed) throw new AISDKError$1({\n\t\t\t\tname: \"AI_StreamAlreadyConsumedError\",\n\t\t\t\tmessage: \"This result supports one stream consumer. Choose one stream projection or response helper.\"\n\t\t\t});\n\t\t\tthis.streamClaimed = true;\n\t\t\tconst reader = this.baseStream.getReader();\n\t\t\tconst rejectResults = (error) => this.rejectResultPromises(error);\n\t\t\treturn new ReadableStream({\n\t\t\t\tasync pull(controller) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\t\tif (done) {\n\t\t\t\t\t\t\treader.releaseLock();\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t} else controller.enqueue(value);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\trejectResults(error);\n\t\t\t\t\t\treader.releaseLock();\n\t\t\t\t\t\tcontroller.error(error);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tasync cancel(reason) {\n\t\t\t\t\trejectResults(reason ?? new DOMException(\"The stream was cancelled.\", \"AbortError\"));\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait reader.cancel(reason);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\treader.releaseLock();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, { highWaterMark: 0 });\n\t\t}\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 this.asIterableStream(toTextStream({ stream: this.stream }));\n\t}\n\tasIterableStream(stream) {\n\t\treturn this.retention.replay ? createAsyncIterableStream(stream) : asAsyncIterableStream(stream);\n\t}\n\tget stream() {\n\t\treturn this.asIterableStream(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\tconst stream = this.stream;\n\t\ttry {\n\t\t\tawait consumeStream({\n\t\t\t\tstream,\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\tif (!this.retention.replay && this.outputSpecification == null) throw new UnsupportedFunctionalityError$1({ functionality: \"partialOutputStream without an explicit output specification with experimental_streamTextLowMemory\" });\n\t\treturn this.asIterableStream(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 this.asIterableStream(this.teeStream().pipeThrough(transform));\n\t}\n\tgetOutputPromise() {\n\t\tif (this.outputPromise == null) this.outputPromise = this.finalStep.then((step) => this.parseOutput(step));\n\t\treturn this.outputPromise;\n\t}\n\tparseOutput(step) {\n\t\treturn (this.outputSpecification ?? text()).parseCompleteOutput({ text: step.text }, {\n\t\t\tresponse: step.response,\n\t\t\tusage: step.usage,\n\t\t\tfinishReason: step.finishReason\n\t\t});\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, redactToolErrors } = {}) {\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\tredactToolErrors\n\t\t}));\n\t}\n\tpipeUIMessageStreamToResponse(response, { originalMessages, generateMessageId, onStepEnd, onStepFinish, onEnd, onFinish, messageMetadata, sendReasoning, sendSources, sendFinish, sendStart, onError, redactToolErrors, ...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\tredactToolErrors\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, redactToolErrors, ...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\tredactToolErrors\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/util/is-caused-by-abort.ts\n/**\n* Checks if the error is an abort or timeout error, or is caused by one.\n* Providers can wrap the abort or timeout error, e.g. as the cause of an\n* API call error.\n*/\nfunction isCausedByAbort(error) {\n\tlet current = error;\n\tfor (let depth = 0; current != null && depth < 5; depth++) {\n\t\tif (isAbortError(current)) return true;\n\t\tcurrent = current.cause;\n\t}\n\treturn false;\n}\n//#endregion\n//#region src/agent/default-stop-condition.ts\n/**\n* Logs the warning for the default stopWhen condition.\n*/\nfunction logDefaultStopConditionWarning({ stepCount, provider, modelId }) {\n\tlogWarnings({\n\t\tprovider,\n\t\tmodel: modelId,\n\t\twarnings: [{\n\t\t\ttype: \"other\",\n\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}]\n\t});\n}\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\tlogDefaultStopConditionWarning({\n\t\t\tstepCount,\n\t\t\tprovider,\n\t\t\tmodelId\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, onError: _settingsOnError, onAbort: _settingsOnAbort, 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, experimental_steering: steering, 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\texperimental_steering: steering,\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\ttry {\n\t\t\treturn await generate({\n\t\t\t\t...preparedCall,\n\t\t\t\t...callbackArgs,\n\t\t\t\theaders: this.agentHeaders(preparedCall)\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (!isCausedByAbort(error) && !abortSignal?.aborted) await notify({\n\t\t\t\tevent: { error },\n\t\t\t\tcallbacks: this.settings.onError\n\t\t\t});\n\t\t\tthrow error;\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_steering: steering, 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_steering: steering,\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\tonError: this.settings.onError,\n\t\t\tonAbort: this.settings.onAbort\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) || isFileUIPart(part)) return convertUserContentUIPart(part);\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\telse if (part.type === \"steering-message\") {\n\t\t\t\t\tawait processBlock();\n\t\t\t\t\tmodelMessages.push({\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: part.parts.map(convertUserContentUIPart)\n\t\t\t\t\t});\n\t\t\t\t}\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}\nfunction convertUserContentUIPart(part) {\n\tif (part.type === \"text\") return {\n\t\ttype: \"text\",\n\t\ttext: part.text,\n\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t};\n\treturn {\n\t\ttype: \"file\",\n\t\tmediaType: part.mediaType,\n\t\tfilename: part.filename,\n\t\tdata: part.providerReference != null ? {\n\t\t\ttype: \"reference\",\n\t\t\treference: part.providerReference\n\t\t} : {\n\t\t\ttype: \"url\",\n\t\t\turl: new URL(part.url)\n\t\t},\n\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t};\n}\n//#endregion\n//#region src/ui/validate-ui-messages.ts\n/**\n* Returns the path to the first value that can never be part of a JSON value\n* (a non-finite number, bigint, symbol, or function), if there is one.\n*/\nfunction findInvalidJsonValuePath(value, path = [], visited = /* @__PURE__ */ new WeakSet()) {\n\tswitch (typeof value) {\n\t\tcase \"number\": return Number.isFinite(value) ? void 0 : [...path];\n\t\tcase \"bigint\":\n\t\tcase \"symbol\":\n\t\tcase \"function\": return [...path];\n\t\tcase \"object\": {\n\t\t\tif (value === null || visited.has(value)) return;\n\t\t\tvisited.add(value);\n\t\t\tconst keys = Array.isArray(value) ? value.keys() : Object.keys(value);\n\t\t\tfor (const key of keys) {\n\t\t\t\tif (key === \"__proto__\") continue;\n\t\t\t\tpath.push(key);\n\t\t\t\tconst invalidPath = findInvalidJsonValuePath(value[key], path, visited);\n\t\t\t\tif (invalidPath != null) return invalidPath;\n\t\t\t\tpath.pop();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tdefault: return;\n\t}\n}\n/**\n* Rejects values that contain an invalid JSON value with a single issue before\n* `schema` validates them.\n*\n* The JSON value schema is a recursive union. It reports the issues of every\n* alternative at every nesting level around an invalid value, so the size of a\n* validation error would grow much faster than the (untrusted) input.\n*\n* @param jsonValuePath - Path from the validated value to the JSON value.\n*/\nfunction withJsonValueCheck(schema, jsonValuePath = []) {\n\treturn z$1.pipe(z$1.unknown().check((context) => {\n\t\tlet jsonValue = context.value;\n\t\tfor (const key of jsonValuePath) jsonValue = jsonValue != null && typeof jsonValue === \"object\" ? jsonValue[key] : void 0;\n\t\tconst invalidPath = findInvalidJsonValuePath(jsonValue);\n\t\tif (invalidPath != null) context.issues.push({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"Invalid JSON value. Expected null, a string, a finite number, a boolean, an array, or an object.\",\n\t\t\tinput: context.value,\n\t\t\tpath: [...jsonValuePath, ...invalidPath]\n\t\t});\n\t}), schema);\n}\nconst toolMetadataSchema = withJsonValueCheck(z$1.record(z$1.string(), z$1.optional(jsonValueSchema)));\nconst providerMetadataSchema = withJsonValueCheck(providerMetadataSchema$1);\nconst providerReferenceSchema$1 = z$1.record(z$1.string(), z$1.string());\nconst uiCitationSchema = withJsonValueCheck(citationSchema, [\"source\", \"providerMetadata\"]);\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}\n/**\n* Creates an array schema that validates its elements in order and stops at\n* the first invalid element.\n*\n* UI messages are untrusted input. `z.array` validates every element and\n* reports the issues of all invalid elements, so the memory and time needed to\n* reject an input would grow with the number of invalid elements in it.\n*/\nfunction arrayUntilFirstInvalidElement(selectElementSchema) {\n\treturn z$1.pipe(z$1.array(z$1.unknown()), z$1.transform((elements, context) => {\n\t\tconst validatedElements = [];\n\t\tfor (const [index, element] of elements.entries()) {\n\t\t\tconst result = z$1.safeParse(selectElementSchema(element), element);\n\t\t\tif (!result.success) {\n\t\t\t\tfor (const issue of result.error.issues) context.issues.push({\n\t\t\t\t\t...issue,\n\t\t\t\t\tpath: [index, ...issue.path]\n\t\t\t\t});\n\t\t\t\treturn z$1.NEVER;\n\t\t\t}\n\t\t\tvalidatedElements.push(result.data);\n\t\t}\n\t\treturn validatedElements;\n\t}));\n}\nconst uiMessagesSchema = lazySchema(() => {\n\tconst approvalRequestedSchema = z$1.object({\n\t\tid: z$1.string(),\n\t\tapproved: z$1.optional(z$1.never()),\n\t\tdescriptor: z$1.optional(z$1.unknown()),\n\t\trequestReason: z$1.optional(z$1.string()),\n\t\treason: z$1.optional(z$1.never()),\n\t\tisAutomatic: z$1.optional(z$1.boolean()),\n\t\tsignature: z$1.optional(z$1.string()),\n\t\tinputSchemaInput: z$1.optional(z$1.unknown())\n\t});\n\tconst approvalRespondedSchema = z$1.extend(approvalRequestedSchema, {\n\t\tapproved: z$1.boolean(),\n\t\treason: z$1.optional(z$1.string())\n\t});\n\tconst approvalGrantedSchema = z$1.extend(approvalRespondedSchema, { approved: z$1.literal(true) });\n\tconst approvalDeniedSchema = z$1.extend(approvalRespondedSchema, { approved: z$1.literal(false) });\n\tconst steeringMessagePartSchema = z$1.discriminatedUnion(\"type\", [z$1.object({\n\t\ttype: z$1.literal(\"text\"),\n\t\ttext: z$1.string(),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema)\n\t}), z$1.object({\n\t\ttype: z$1.literal(\"file\"),\n\t\tmediaType: z$1.string(),\n\t\tfilename: z$1.optional(z$1.string()),\n\t\turl: z$1.string(),\n\t\tproviderReference: z$1.optional(providerReferenceSchema$1),\n\t\tproviderMetadata: z$1.optional(providerMetadataSchema)\n\t})]);\n\tconst invalidPartTypeMessage = \"Invalid UI message part type. Expected a known part type (for example \\\"text\\\" or \\\"dynamic-tool\\\") or a type starting with \\\"data-\\\" or \\\"tool-\\\".\";\n\tconst staticPartSchema = z$1.discriminatedUnion(\"type\", [\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"text\"),\n\t\t\ttext: z$1.string(),\n\t\t\tcitations: z$1.optional(arrayUntilFirstInvalidElement(() => uiCitationSchema)),\n\t\t\tstate: z$1.optional(z$1.enum([\"streaming\", \"done\"])),\n\t\t\tproviderMetadata: z$1.optional(providerMetadataSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"reasoning\"),\n\t\t\tid: z$1.optional(z$1.string()),\n\t\t\ttext: z$1.string(),\n\t\t\tstate: z$1.optional(z$1.enum([\"streaming\", \"done\"])),\n\t\t\tproviderMetadata: z$1.optional(providerMetadataSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"custom\"),\n\t\t\tkind: z$1.string(),\n\t\t\tproviderMetadata: z$1.optional(providerMetadataSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"source-url\"),\n\t\t\tsourceId: z$1.string(),\n\t\t\turl: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\tproviderMetadata: z$1.optional(providerMetadataSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"source-document\"),\n\t\t\tsourceId: z$1.string(),\n\t\t\tmediaType: z$1.string(),\n\t\t\ttitle: z$1.string(),\n\t\t\tfilename: z$1.optional(z$1.string()),\n\t\t\tproviderMetadata: z$1.optional(providerMetadataSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"file\"),\n\t\t\tmediaType: z$1.string(),\n\t\t\tfilename: z$1.optional(z$1.string()),\n\t\t\turl: z$1.string(),\n\t\t\tproviderReference: z$1.optional(providerReferenceSchema$1),\n\t\t\tproviderMetadata: z$1.optional(providerMetadataSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"reasoning-file\"),\n\t\t\tmediaType: z$1.string(),\n\t\t\turl: z$1.string(),\n\t\t\tproviderMetadata: z$1.optional(providerMetadataSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"steering-message\"),\n\t\t\tid: z$1.string(),\n\t\t\tparts: arrayUntilFirstInvalidElement(() => steeringMessagePartSchema)\n\t\t}),\n\t\tz$1.object({ type: z$1.literal(\"step-start\") })\n\t], { error: (issue) => issue.code === \"invalid_union\" ? invalidPartTypeMessage : void 0 });\n\tconst dataPartSchema = z$1.object({\n\t\ttype: z$1.string().check(z$1.startsWith(\"data-\")),\n\t\tid: z$1.optional(z$1.string()),\n\t\tdata: z$1.unknown()\n\t});\n\tconst dynamicToolPartSchema = z$1.discriminatedUnion(\"state\", [\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"dynamic-tool\"),\n\t\t\tdynamic: z$1.optional(z$1.literal(false)),\n\t\t\ttoolName: z$1.string(),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"input-streaming\"),\n\t\t\tinput: z$1.optional(z$1.unknown()),\n\t\t\trawInput: z$1.optional(z$1.string()),\n\t\t\tinputEncoding: z$1.optional(z$1.enum([\"json\", \"text\"])),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tapproval: z$1.optional(z$1.never())\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"dynamic-tool\"),\n\t\t\tdynamic: z$1.optional(z$1.literal(false)),\n\t\t\ttoolName: z$1.string(),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"input-available\"),\n\t\t\tinput: z$1.unknown(),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tapproval: z$1.optional(z$1.never())\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"dynamic-tool\"),\n\t\t\tdynamic: z$1.optional(z$1.literal(false)),\n\t\t\ttoolName: z$1.string(),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"approval-requested\"),\n\t\t\tinput: z$1.unknown(),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tapproval: approvalRequestedSchema\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"dynamic-tool\"),\n\t\t\tdynamic: z$1.optional(z$1.literal(false)),\n\t\t\ttoolName: z$1.string(),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"approval-responded\"),\n\t\t\tinput: z$1.unknown(),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tapproval: approvalRespondedSchema\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"dynamic-tool\"),\n\t\t\tdynamic: z$1.optional(z$1.literal(false)),\n\t\t\ttoolName: z$1.string(),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"output-available\"),\n\t\t\tinput: z$1.unknown(),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\toutput: z$1.unknown(),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tresultProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tpreliminary: z$1.optional(z$1.boolean()),\n\t\t\tapproval: z$1.optional(approvalGrantedSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"dynamic-tool\"),\n\t\t\tdynamic: z$1.optional(z$1.literal(false)),\n\t\t\ttoolName: z$1.string(),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"output-error\"),\n\t\t\tinput: z$1.optional(z$1.unknown()),\n\t\t\trawInput: z$1.optional(z$1.unknown()),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.string(),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tresultProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tapproval: z$1.optional(approvalGrantedSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.literal(\"dynamic-tool\"),\n\t\t\tdynamic: z$1.optional(z$1.literal(false)),\n\t\t\ttoolName: z$1.string(),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"output-denied\"),\n\t\t\tinput: z$1.unknown(),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tapproval: approvalDeniedSchema\n\t\t})\n\t]);\n\tconst toolPartSchema = z$1.discriminatedUnion(\"state\", [\n\t\tz$1.object({\n\t\t\ttype: z$1.string().check(z$1.startsWith(\"tool-\")),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"input-streaming\"),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tinput: z$1.optional(z$1.unknown()),\n\t\t\trawInput: z$1.optional(z$1.string()),\n\t\t\tinputEncoding: z$1.optional(z$1.enum([\"json\", \"text\"])),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tapproval: z$1.optional(z$1.never())\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.string().check(z$1.startsWith(\"tool-\")),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"input-available\"),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\tinput: z$1.unknown(),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tapproval: z$1.optional(z$1.never())\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.string().check(z$1.startsWith(\"tool-\")),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"approval-requested\"),\n\t\t\tinput: z$1.unknown(),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tapproval: approvalRequestedSchema\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.string().check(z$1.startsWith(\"tool-\")),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"approval-responded\"),\n\t\t\tinput: z$1.unknown(),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tapproval: approvalRespondedSchema\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.string().check(z$1.startsWith(\"tool-\")),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"output-available\"),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\tinput: z$1.unknown(),\n\t\t\toutput: z$1.unknown(),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tresultProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tpreliminary: z$1.optional(z$1.boolean()),\n\t\t\tapproval: z$1.optional(approvalGrantedSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.string().check(z$1.startsWith(\"tool-\")),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"output-error\"),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\tinput: z$1.optional(z$1.unknown()),\n\t\t\trawInput: z$1.optional(z$1.unknown()),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.string(),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tresultProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tapproval: z$1.optional(approvalGrantedSchema)\n\t\t}),\n\t\tz$1.object({\n\t\t\ttype: z$1.string().check(z$1.startsWith(\"tool-\")),\n\t\t\ttoolCallId: z$1.string(),\n\t\t\ttitle: z$1.optional(z$1.string()),\n\t\t\ttoolMetadata: z$1.optional(toolMetadataSchema),\n\t\t\tstate: z$1.literal(\"output-denied\"),\n\t\t\tproviderExecuted: z$1.optional(z$1.boolean()),\n\t\t\tinput: z$1.unknown(),\n\t\t\toutput: z$1.optional(z$1.never()),\n\t\t\terrorText: z$1.optional(z$1.never()),\n\t\t\tcallProviderMetadata: z$1.optional(providerMetadataSchema),\n\t\t\tapproval: approvalDeniedSchema\n\t\t})\n\t]);\n\tconst messageSchema = z$1.object({\n\t\tid: z$1.string(),\n\t\trole: z$1.enum([\n\t\t\t\"system\",\n\t\t\t\"user\",\n\t\t\t\"assistant\"\n\t\t]),\n\t\tmetadata: z$1.optional(z$1.unknown()),\n\t\tparts: arrayUntilFirstInvalidElement((part) => {\n\t\t\tconst type = part?.type;\n\t\t\tif (typeof type === \"string\") {\n\t\t\t\tif (type.startsWith(\"data-\")) return dataPartSchema;\n\t\t\t\tif (type.startsWith(\"tool-\")) return toolPartSchema;\n\t\t\t\tif (type === \"dynamic-tool\") return dynamicToolPartSchema;\n\t\t\t}\n\t\t\treturn staticPartSchema;\n\t\t})\n\t}).check((context) => {\n\t\tconst message = context.value;\n\t\tif (message.role !== \"assistant\" && message.parts.length === 0) context.issues.push({\n\t\t\tcontinue: true,\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});\n\treturn zodSchema$1(arrayUntilFirstInvalidElement(() => messageSchema).check(z$1.minLength(1, \"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 experimental_steering - A steering object that adds user messages to the run at the next step boundary. Only supported by `ToolLoopAgent`. 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_steering: steering, experimental_transform, onStepEnd, onStepFinish, onUIMessageStepEnd, ...uiMessageStreamOptions }) {\n\tif (steering != null && !(agent instanceof ToolLoopAgent)) throw new InvalidArgumentError({\n\t\tparameter: \"experimental_steering\",\n\t\tvalue: steering,\n\t\tmessage: \"Steering is only supported by ToolLoopAgent.\"\n\t});\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_steering: steering,\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 experimental_steering - A steering object that adds user messages to the run at the next step boundary. Only supported by `ToolLoopAgent`. 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 experimental_steering - A steering object that adds user messages to the run at the next step boundary. Only supported by `ToolLoopAgent`. 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/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.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, download }) {\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: download ?? (async (requests) => {\n\t\t\tif (requests.length > 0) throw new DownloadError$1({\n\t\t\t\turl: requests[0].url.toString(),\n\t\t\t\tmessage: \"URL file state requires experimental_download. For untrusted URLs, use createDownload({ fetch }) with a transport that validates DNS at connection time.\"\n\t\t\t});\n\t\t\treturn [];\n\t\t}),\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}\n/**\n* Checks the JSON constraints that types cannot express: finite numbers, no\n* cycles, and no array holes. These would otherwise be silently changed by\n* `JSON.stringify` or make it throw.\n*/\nfunction isSerializableJSON(value, ancestors = /* @__PURE__ */ new Set()) {\n\tif (typeof value === \"number\") return Number.isFinite(value);\n\tif (value == null || typeof value !== \"object\") return true;\n\tif (ancestors.has(value)) return false;\n\tancestors.add(value);\n\tconst valid = Array.isArray(value) ? Array.from(value.keys()).every((index) => index in value && isSerializableJSON(value[index], ancestors)) : Object.values(value).every((item) => isSerializableJSON(item, ancestors));\n\tancestors.delete(value);\n\treturn valid;\n}\nfunction invalidInput(parameter, value, message) {\n\tthrow new InvalidArgumentError({\n\t\tparameter,\n\t\tvalue,\n\t\tmessage\n\t});\n}\nfunction validateDecisionState(state) {\n\tif (Array.isArray(state) && Array.from(state.keys()).some((index) => !(index in state))) invalidInput(\"state\", state, \"state parts must not contain array holes\");\n\tif (!isSerializableJSON(Array.isArray(state) ? state.flatMap((part) => part.type === \"json\" ? [part.value] : []) : state)) invalidInput(\"state\", state, \"JSON content must not contain non-finite numbers, cycles, or array holes\");\n}\nfunction validateDecisionInput({ state, questions }) {\n\tvalidateDecisionState(state);\n\tif (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 (!isSerializableJSON(question.instructions) || \"criteria\" in question && !isSerializableJSON(question.criteria)) invalidInput(parameter, question, \"instructions and criteria must not contain non-finite numbers, cycles, or array holes\");\n\t\tswitch (question.type) {\n\t\t\tcase \"choice\":\n\t\t\t\tif (Object.keys(question.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 (question.criteria.length === 0) invalidInput(parameter, question, \"score criteria must contain at least one ordered level\");\n\t\t\t\tbreak;\n\t\t\tcase \"boolean\": {\n\t\t\t\tconst criteria = question.criteria;\n\t\t\t\tif (question.instructions == null && (criteria == null || !Object.values(criteria).some((value) => value != null))) invalidInput(parameter, question, \"boolean questions require instructions or at least one non-null criterion\");\n\t\t\t\tif (criteria != null && 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\t}\n\t\t}\n\t}\n}\nfunction invalidAnswer$1(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$1(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$1(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$1(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$1(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$1(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$1(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 + 2 * probabilityError)) invalidAnswer$1(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$1(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$1(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 \"box\": {\n\t\t\t\tconst box = answer.box;\n\t\t\t\tif (!isRecord$1(box) || !hasExactKeys(box, [\n\t\t\t\t\t\"top\",\n\t\t\t\t\t\"bottom\",\n\t\t\t\t\t\"left\",\n\t\t\t\t\t\"right\"\n\t\t\t\t]) || !isProbability(box.left) || !isProbability(box.right) || !isProbability(box.top) || !isProbability(box.bottom) || !(box.left < box.right) || !(box.top < box.bottom)) invalidAnswer$1(answers, `Question \"${id}\" must return box edges in [0, 1] with left < right and top < bottom.`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"boolean\": if (!isProbability(answer.probability)) invalidAnswer$1(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, maxOutputTokens, reasoning, maxRetries, abortSignal, experimental_download: download, headers, providerOptions = {}, telemetry, runtimeContext = {}, onStart, onEnd, _internal: { generateCallId = originalGenerateCallId$4 } = {} }) {\n\tconst model = resolveDecisionModel(modelArg);\n\tprepareLanguageModelCallOptions({ maxOutputTokens });\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\tmaxOutputTokens,\n\t\treasoning,\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({\n\t\t\t\t\tstate,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\tdownload\n\t\t\t\t});\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\tmaxOutputTokens,\n\t\t\t\t\t\treasoning,\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/extract/validate-extraction.ts\nconst durationUnits = [\n\t\"seconds\",\n\t\"minutes\",\n\t\"hours\",\n\t\"days\",\n\t\"weeks\",\n\t\"months\",\n\t\"years\"\n];\nconst listItems = [\n\t\"text\",\n\t\"number\",\n\t\"date\"\n];\nconst time = /^([01]\\d|2[0-3]):[0-5]\\d(:[0-5]\\d)?$/;\nconst datetime = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d(:[0-5]\\d(\\.\\d{1,9})?)?(Z|[+-]([01]\\d|2[0-3]):[0-5]\\d)?$/;\nfunction isDate(value) {\n\tif (typeof value !== \"string\" || !/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return false;\n\tconst date = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);\n\treturn !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;\n}\nfunction isNumber(value, { integer, decimals }) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && (!integer || Number.isInteger(value)) && (decimals === void 0 || Number(value.toFixed(decimals)) === value);\n}\nfunction isDenseArray(value) {\n\tif (!Array.isArray(value) || Object.keys(value).length !== value.length) return false;\n\tfor (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;\n\treturn true;\n}\nfunction isValue(field, value) {\n\tswitch (field.type) {\n\t\tcase \"text\": return typeof value === \"string\";\n\t\tcase \"number\": return isNumber(value, field);\n\t\tcase \"duration\": return isNumber(value, field) && value >= 0;\n\t\tcase \"date\": return isDate(value);\n\t\tcase \"time\": return typeof value === \"string\" && time.test(value);\n\t\tcase \"datetime\": return typeof value === \"string\" && datetime.test(value) && isDate(value.slice(0, 10));\n\t}\n}\nfunction isSource(source, state) {\n\tif (!isRecord$1(source) || typeof source.part !== \"number\" || !Number.isInteger(source.part) || source.part < 0 || source.part >= state.length) return false;\n\tconst part = state[source.part];\n\tswitch (source.type) {\n\t\tcase \"text\": return part.type === \"text\" && typeof source.start === \"number\" && typeof source.end === \"number\" && Number.isInteger(source.start) && Number.isInteger(source.end) && source.start >= 0 && source.start < source.end && source.end <= part.text.length;\n\t\tcase \"file\": return part.type === \"file\";\n\t\tdefault: return false;\n\t}\n}\nfunction validateExtractionInput({ state, fields, referenceDate }) {\n\tvalidateDecisionState(state);\n\tif (referenceDate !== void 0 && !isDate(referenceDate)) invalidInput(\"referenceDate\", referenceDate, \"must be a YYYY-MM-DD calendar date\");\n\tif (Object.keys(fields).length === 0) invalidInput(\"fields\", fields, \"must be a nonempty field map\");\n\tfor (const [id, field] of Object.entries(fields)) {\n\t\tconst parameter = `fields.${id}`;\n\t\tif (!isSerializableJSON(field.instructions)) invalidInput(parameter, field, \"instructions must not contain non-finite numbers, cycles, or array holes\");\n\t\tif (\"decimals\" in field && field.decimals !== void 0 && !(Number.isInteger(field.decimals) && field.decimals >= 0 && field.decimals <= 6)) invalidInput(parameter, field, \"decimals must be an integer from 0 to 6\");\n\t\tif (field.type === \"duration\" && field.unit !== void 0 && !durationUnits.includes(field.unit)) invalidInput(parameter, field, `duration unit must be one of ${durationUnits.join(\", \")}`);\n\t\tif (field.type === \"list\" && !listItems.includes(field.items)) invalidInput(parameter, field, `list items must be one of ${listItems.join(\", \")}`);\n\t}\n}\nfunction invalidAnswer(answers, message) {\n\tthrow new InvalidResponseDataError$1({\n\t\tdata: answers,\n\t\tmessage\n\t});\n}\nfunction validateExtractionAnswers({ fields, state, answers }) {\n\tif (!isRecord$1(answers) || !hasExactKeys(answers, Object.keys(fields))) invalidAnswer(answers, \"Extraction must return exactly one answer for every field.\");\n\tfor (const [id, field] of Object.entries(fields)) {\n\t\tconst answer = answers[id];\n\t\tif (isRecord$1(answer) && answer.type === \"refusal\") continue;\n\t\tif (!isRecord$1(answer) || answer.type !== field.type) invalidAnswer(answers, `Field \"${id}\" returned an answer with the wrong type.`);\n\t\tif (answer.pNull !== void 0 && !isProbability(answer.pNull) || answer.confidence !== void 0 && !isProbability(answer.confidence)) invalidAnswer(answers, `Field \"${id}\" must return pNull and confidence as finite probabilities in [0, 1].`);\n\t\tif (field.type === \"list\") {\n\t\t\tconst item = field.items === \"number\" ? {\n\t\t\t\ttype: \"number\",\n\t\t\t\tinteger: field.integer,\n\t\t\t\tdecimals: field.decimals\n\t\t\t} : { type: field.items };\n\t\t\tconst value = answer.value;\n\t\t\tif (value !== null && !(isDenseArray(value) && value.every((entry) => isValue(item, entry)))) invalidAnswer(answers, `Field \"${id}\" must return null or a list of ${field.items} values.`);\n\t\t\tconst items = answer.items;\n\t\t\tif (items !== void 0 && !(isDenseArray(items) && Array.isArray(value) && items.length === value.length && items.every((entry) => isRecord$1(entry) && (entry.confidence === void 0 || isProbability(entry.confidence)) && (entry.source === void 0 || isSource(entry.source, state))))) invalidAnswer(answers, `Field \"${id}\" must return one item entry per list value, with confidences in [0, 1] and sources inside the state.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (answer.value !== null && !isValue(field, answer.value)) invalidAnswer(answers, `Field \"${id}\" must return null or a valid ${field.type} value.`);\n\t\tif (answer.guess !== void 0 && !isValue(field, answer.guess)) invalidAnswer(answers, `Field \"${id}\" must return a valid ${field.type} guess.`);\n\t\tif (answer.source !== void 0 && !isSource(answer.source, state)) invalidAnswer(answers, `Field \"${id}\" returned a source outside the state.`);\n\t}\n}\n//#endregion\n//#region src/extract/extract.ts\n/** Extract typed field values from one shared state. Experimental. */\nasync function extract({ model: modelArg, state, fields, referenceDate, maxOutputTokens, reasoning, maxRetries, abortSignal, experimental_download: download, headers, providerOptions = {} }) {\n\tconst model = resolveExtractionModel(modelArg);\n\tprepareLanguageModelCallOptions({ maxOutputTokens });\n\tvalidateExtractionInput({\n\t\tstate,\n\t\tfields,\n\t\treferenceDate\n\t});\n\tfor (const [fieldId, field] of Object.entries(fields)) if (!model.supportedFieldTypes.includes(field.type)) throw new Experimental_ExtractionUnsupportedFieldTypeError$1({\n\t\tfieldId,\n\t\tfieldType: field.type,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries,\n\t\tabortSignal\n\t});\n\tconst preparedState = await prepareDecisionState({\n\t\tstate,\n\t\tabortSignal,\n\t\tdownload\n\t});\n\tconst result = await retry(async () => {\n\t\tabortSignal?.throwIfAborted();\n\t\treturn await model.doExtract({\n\t\t\tstate: preparedState,\n\t\t\tfields,\n\t\t\treferenceDate,\n\t\t\tmaxOutputTokens,\n\t\t\treasoning,\n\t\t\tabortSignal,\n\t\t\theaders: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n\t\t\tproviderOptions\n\t\t});\n\t});\n\tabortSignal?.throwIfAborted();\n\tvalidateExtractionAnswers({\n\t\tfields,\n\t\tstate: preparedState,\n\t\tanswers: result.answers\n\t});\n\tconst refusedFieldIds = Object.keys(fields).filter((id) => result.answers[id]?.type === \"refusal\");\n\tif (refusedFieldIds.length > 0) throw new Experimental_ExtractionRefusalError$1({\n\t\tfieldIds: refusedFieldIds,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\tlogWarnings({\n\t\twarnings: result.warnings,\n\t\tprovider: model.provider,\n\t\tmodel: model.modelId\n\t});\n\tconst inputTokens = result.usage?.inputTokens;\n\tconst outputTokens = result.usage?.outputTokens;\n\treturn {\n\t\tanswers: result.answers,\n\t\tusage: {\n\t\t\tinputTokens,\n\t\t\toutputTokens,\n\t\t\ttotalTokens: inputTokens != null && outputTokens != null ? inputTokens + outputTokens : void 0\n\t\t},\n\t\twarnings: result.warnings,\n\t\tproviderMetadata: result.providerMetadata,\n\t\tresponse: {\n\t\t\t...result.response,\n\t\t\ttimestamp: result.response?.timestamp ?? /* @__PURE__ */ new Date(),\n\t\t\tmodelId: result.response?.modelId ?? model.modelId\n\t\t}\n\t};\n}\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\tcreateArrayStreamParser: () => createArrayOutputStreamParser(schema, false),\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 === \"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 (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 (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\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 = sanitizeRequestMetadata(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(generateResult.structuredOutputText ?? 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* @param options.fetch - Fetch transport, e.g. guarded-fetch for DNS validation on Node.js.\n* @returns A download function that can be passed to `transcribe()`,\n* `experimental_generateVideo()`, or as `experimental_download` to\n* `generateText()` and `streamText()`.\n*/\nfunction createDownload(options) {\n\tconst download$1 = ({ url, abortSignal }) => download({\n\t\turl,\n\t\tmaxBytes: options?.maxBytes,\n\t\tabortSignal,\n\t\tfetch: options?.fetch\n\t});\n\treturn ((requests) => Array.isArray(requests) ? Promise.all(requests.map((request) => request.isUrlSupportedByModel ? null : download$1(request))) : download$1(requests));\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: rawRequest } = await retry(() => model.doStream(callOptions));\n\t\t\tconst request = sanitizeRequestMetadata(rawRequest);\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 arrayStreamParser = outputStrategy.createArrayStreamParser?.();\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\tif (arrayStreamParser != null) {\n\t\t\t\t\t\t\tconst result = await arrayStreamParser(chunk);\n\t\t\t\t\t\t\tif (result !== \"fallback\") {\n\t\t\t\t\t\t\t\tif (result != null) {\n\t\t\t\t\t\t\t\t\tlatestObject = result.partial;\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\t\tobject: latestObject\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\t\ttextDelta: result.textDelta\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\ttextDelta = \"\";\n\t\t\t\t\t\t\t\t\tisFirstDelta = false;\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\tarrayStreamParser = void 0;\n\t\t\t\t\t\t}\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/is-streaming-speech-model.ts\n/**\n* Whether a resolved speech model implements the experimental streaming\n* speech extension (`Experimental_StreamingSpeechModelV4`).\n*/\nfunction isStreamingSpeechModel(model) {\n\treturn typeof model.doStream === \"function\";\n}\n//#endregion\n//#region src/generate-speech/stream-speech.ts\n/**\n* Streams speech audio using a speech model.\n*\n* @param model - The speech model to use. It must support streaming speech.\n* @param text - The text to convert to speech: a complete string, or a stream of text deltas\n* (e.g. the text stream of `streamText`) or text parts that is synthesized as it arrives.\n* A text part can set its own `voice` on providers that support several voices per stream.\n* @param voice - The voice to use for speech generation.\n* @param outputFormat - The format of the output audio chunks, e.g. `{ type: 'audio/pcm', rate: 24000 }`.\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.\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, raw provider chunks are included in `fullStream`.\n* @param onError - Called for each provider error part; defaults to `console.error`.\n*\n* @returns A result object with the audio stream and the final usage and metadata.\n*/\nfunction streamSpeech({ model, text, voice, outputFormat, instructions, speed, language, providerOptions = {}, abortSignal, headers, includeRawChunks, onError = ({ error }) => {\n\tconsole.error(error);\n}, _internal: { currentDate = () => /* @__PURE__ */ new Date() } = {} }) {\n\tconst resolvedModel = resolveSpeechModel(model);\n\tif (!resolvedModel) throw new Error(\"Model could not be resolved\");\n\tif (!isStreamingSpeechModel(resolvedModel)) throw new UnsupportedFunctionalityError$1({\n\t\tfunctionality: \"streaming speech\",\n\t\tmessage: `The ${resolvedModel.provider} model \"${resolvedModel.modelId}\" does not support streaming speech.` + (typeof model === \"string\" ? \" String model IDs resolve through the global provider (AI Gateway by default). If that provider does not support streaming speech, pass a provider model instance instead (e.g. elevenLabs.speech('eleven_flash_v2_5')) or upgrade @ai-sdk/gateway to a version with streaming speech support.\" : \"\")\n\t});\n\tconst textStream = toTextStream$1(text);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`);\n\tconst usagePromise = new DelayedPromise();\n\tconst warningsPromise = new DelayedPromise();\n\tconst responsesPromise = new DelayedPromise();\n\tconst providerMetadataPromise = new DelayedPromise();\n\tconst rejectPendingPromises = (error) => {\n\t\tfor (const promise of [\n\t\t\tusagePromise,\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 = (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 hasAudio = false;\n\tlet finished = false;\n\tlet lastError;\n\tconst incompleteStreamError = () => hasAudio ? lastError ?? new StreamProviderError({ message: \"The speech stream ended before it finished.\" }) : new NoSpeechGeneratedError({\n\t\tresponses: [currentResponseMetadata()],\n\t\tcause: lastError\n\t});\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\tbody: value.body ?? response?.body\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"audio\": {\n\t\t\t\t\tconst audio = typeof value.audio === \"string\" ? convertBase64ToUint8Array(value.audio) : value.audio;\n\t\t\t\t\tif (audio.length === 0 && value.providerMetadata == null) break;\n\t\t\t\t\thasAudio ||= audio.length > 0;\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"audio\",\n\t\t\t\t\t\t...value.id != null && { id: value.id },\n\t\t\t\t\t\taudio,\n\t\t\t\t\t\taudioFormat: value.audioFormat,\n\t\t\t\t\t\t...value.providerMetadata != null && { providerMetadata: value.providerMetadata }\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"raw\":\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":\n\t\t\t\t\tlastError = value.error;\n\t\t\t\t\tPromise.resolve().then(() => onError({ error: value.error })).catch(() => {});\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 (!hasAudio) throw new NoSpeechGeneratedError({\n\t\t\t\t\t\tresponses: [currentResponseMetadata()],\n\t\t\t\t\t\tcause: lastError\n\t\t\t\t\t});\n\t\t\t\t\tfinished = true;\n\t\t\t\t\tusagePromise.resolve(value.usage ?? {});\n\t\t\t\t\tresponsesPromise.resolve([currentResponseMetadata()]);\n\t\t\t\t\tproviderMetadataPromise.resolve(value.providerMetadata ?? {});\n\t\t\t}\n\t\t},\n\t\tflush() {\n\t\t\tif (!finished) throw incompleteStreamError();\n\t\t},\n\t\tcancel(reason) {\n\t\t\tconst cancelReason = reason ?? /* @__PURE__ */ new Error(\"Speech stream was cancelled.\");\n\t\t\trejectPendingPromises(cancelReason);\n\t\t\tpipeAbortController.abort(cancelReason);\n\t\t}\n\t});\n\tif (abortSignal != null) {\n\t\tconst onAbort = () => {\n\t\t\tconst reason = abortSignal.reason;\n\t\t\trejectPendingPromises(reason);\n\t\t\tpipeAbortController.abort(reason);\n\t\t\ttransform.writable.abort(reason).catch(() => {});\n\t\t};\n\t\tif (abortSignal.aborted) onAbort();\n\t\telse abortSignal.addEventListener(\"abort\", onAbort, { once: true });\n\t}\n\t(async () => {\n\t\tconst result = await resolvedModel.doStream({\n\t\t\ttext: textStream,\n\t\t\tvoice,\n\t\t\toutputFormat,\n\t\t\tinstructions,\n\t\t\tspeed,\n\t\t\tlanguage,\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\tbody: result.response?.body\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(\"Speech stream was cancelled or errored.\");\n\t\trejectPendingPromises(reason);\n\t\ttextStream.cancel(reason).catch(() => {});\n\t\ttransform.writable.abort(reason).catch(() => {});\n\t});\n\tlet streamOwner = \"unclaimed\";\n\tfunction consumeStream() {\n\t\tif (streamOwner !== \"unclaimed\") 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 claimStream(owner) {\n\t\tif (streamOwner !== \"unclaimed\") throw new Error(streamOwner === \"result-promises\" ? `${owner === \"full-stream\" ? \"fullStream\" : \"audioStream\"} cannot be accessed after a result promise.` : \"Only one of audioStream or fullStream can be accessed, and only once.\");\n\t\tstreamOwner = owner;\n\t\treturn transform.readable;\n\t}\n\treturn {\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 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 asAsyncIterableStream(claimStream(\"full-stream\"));\n\t\t},\n\t\tget audioStream() {\n\t\t\treturn asAsyncIterableStream(createAudioByteStream(claimStream(\"audio-stream\")));\n\t\t}\n\t};\n}\n/**\n* Projects speech parts to audio bytes with a pull-based stream rather than a\n* second `pipeThrough`, so an early consumer cancel cancels the part stream\n* directly instead of surfacing an unhandled rejection from a chained pipe.\n*/\nfunction createAudioByteStream(parts) {\n\tlet reader;\n\treturn new ReadableStream({\n\t\tasync pull(controller) {\n\t\t\treader ??= parts.getReader();\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (value.type === \"audio\" && value.audio.length > 0) {\n\t\t\t\t\tcontroller.enqueue(value.audio);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tasync cancel(reason) {\n\t\t\tif (reader != null) await reader.cancel(reason).catch(() => {});\n\t\t\telse await parts.cancel(reason).catch(() => {});\n\t\t}\n\t});\n}\nfunction toTextStream$1(text) {\n\tif (typeof text === \"string\") return new ReadableStream({ start(controller) {\n\t\tcontroller.enqueue({\n\t\t\ttype: \"text\",\n\t\t\ttext\n\t\t});\n\t\tcontroller.close();\n\t} });\n\treturn toSourceStream(text).pipeThrough(new TransformStream({ transform(value, controller) {\n\t\tcontroller.enqueue(toTextPart(value));\n\t} }));\n}\nfunction toSourceStream(text) {\n\tif (text instanceof ReadableStream) return text;\n\tif (typeof text?.[Symbol.asyncIterator] === \"function\") return convertAsyncIteratorToReadableStream(text[Symbol.asyncIterator]());\n\tconst iterable = text;\n\treturn convertAsyncIteratorToReadableStream((async function* () {\n\t\tyield* iterable;\n\t})());\n}\nfunction toTextPart(value) {\n\tif (typeof value === \"string\") return {\n\t\ttype: \"text\",\n\t\ttext: value\n\t};\n\treturn {\n\t\ttype: \"text\",\n\t\ttext: value.text,\n\t\t...value.voice != null && { voice: value.voice },\n\t\t...value.providerOptions != null && { providerOptions: value.providerOptions }\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\tconst keepParts = message.content.map((part) => {\n\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\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\tconst partToolName = part.type === \"tool-call\" || part.type === \"tool-result\" ? part.toolName : approvalIdToToolName.get(part.approvalId);\n\t\t\t\treturn toolCall.tools != null && partToolName != null && !toolCall.tools.includes(partToolName);\n\t\t\t});\n\t\t\tif (message.role === \"assistant\") for (let reasoningIndex = 0; reasoningIndex < message.content.length; reasoningIndex++) {\n\t\t\t\tconst part = message.content[reasoningIndex];\n\t\t\t\tif (part.type !== \"reasoning\" && part.type !== \"reasoning-file\") continue;\n\t\t\t\tlet reasoningEndIndex = reasoningIndex + 1;\n\t\t\t\twhile (reasoningEndIndex < message.content.length) {\n\t\t\t\t\tconst nextPart = message.content[reasoningEndIndex];\n\t\t\t\t\tif (nextPart.type !== \"reasoning\" && nextPart.type !== \"reasoning-file\") break;\n\t\t\t\t\treasoningEndIndex++;\n\t\t\t\t}\n\t\t\t\tlet followingPartIndex = reasoningEndIndex;\n\t\t\t\tlet hasFollowingPart = false;\n\t\t\t\tlet hasKeptFollowingPart = false;\n\t\t\t\twhile (followingPartIndex < message.content.length) {\n\t\t\t\t\tconst followingPart = message.content[followingPartIndex];\n\t\t\t\t\tif (followingPart.type === \"reasoning\" || followingPart.type === \"reasoning-file\") break;\n\t\t\t\t\thasFollowingPart = true;\n\t\t\t\t\thasKeptFollowingPart ||= keepParts[followingPartIndex];\n\t\t\t\t\tfollowingPartIndex++;\n\t\t\t\t}\n\t\t\t\tif (hasFollowingPart && !hasKeptFollowingPart) for (let index = reasoningIndex; index < reasoningEndIndex; index++) keepParts[index] = false;\n\t\t\t\treasoningIndex = followingPartIndex - 1;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...message,\n\t\t\t\tcontent: message.content.filter((_, index) => keepParts[index])\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}\" which is not a prefix of buffer \"${buffer}\"`);\n\t\treturn match;\n\t};\n\telse {\n\t\tconst chunkingRegex = typeof chunking === \"string\" ? CHUNKING_REGEXPS[chunking] : chunking;\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 === \"ping\") {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\treturn;\n\t\t\t}\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\tlet uploadedVideos = 0;\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 \"uploaded\":\n\t\t\t\tuploadedVideos++;\n\t\t\t\tbreak;\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 && uploadedVideos === 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\tconst result = {\n\t\tvideo: videos[0],\n\t\tvideos,\n\t\tuploadedVideos,\n\t\twarnings,\n\t\tresponses,\n\t\tproviderMetadata\n\t};\n\tif (videos.length === 0) Object.defineProperty(result, \"video\", {\n\t\tenumerable: false,\n\t\tget() {\n\t\t\tthrow new NoVideoGeneratedError({\n\t\t\t\tmessage: \"Videos were delivered to the upload destination. Use uploadedVideos instead of video.\",\n\t\t\t\tresponses\n\t\t\t});\n\t\t}\n\t});\n\treturn result;\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, structuredOutputText, ...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\t...structuredOutputText != null && { structuredOutputText: transform(structuredOutputText) }\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\tfunction extractReasoning(input) {\n\t\tconst text = startWithReasoning ? openingTag + input : input;\n\t\tconst regexp = new RegExp(`${escapedOpeningTag}(.*?)${escapedClosingTag}`, \"gs\");\n\t\tconst matches = Array.from(text.matchAll(regexp));\n\t\tif (!matches.length) return {\n\t\t\ttext: input,\n\t\t\treasoning: void 0\n\t\t};\n\t\tconst reasoning = matches.map((match) => match[1]).join(separator);\n\t\tlet textWithoutReasoning = text;\n\t\tfor (let i = matches.length - 1; i >= 0; i--) {\n\t\t\tconst match = matches[i];\n\t\t\tconst beforeMatch = textWithoutReasoning.slice(0, match.index);\n\t\t\tconst afterMatch = textWithoutReasoning.slice(match.index + match[0].length);\n\t\t\ttextWithoutReasoning = beforeMatch + (beforeMatch.length > 0 && afterMatch.length > 0 ? separator : \"\") + afterMatch;\n\t\t}\n\t\treturn {\n\t\t\ttext: textWithoutReasoning,\n\t\t\treasoning\n\t\t};\n\t}\n\treturn {\n\t\tspecificationVersion: \"v4\",\n\t\twrapGenerate: async ({ doGenerate }) => {\n\t\t\tconst { content, structuredOutputText, ...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, reasoning } = extractReasoning(part.text);\n\t\t\t\tif (reasoning === void 0) {\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\ttype: \"reasoning\",\n\t\t\t\t\ttext: reasoning\n\t\t\t\t});\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext\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\t...structuredOutputText != null && { structuredOutputText: extractReasoning(structuredOutputText).text }\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 || (part.citations?.length ?? 0) > 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\t...part.citations != null ? { citations: part.citations } : {}\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/prompt/content-part.ts\nconst fileInlineDataSchema = z.union([\n\tz.string(),\n\tz.custom(isUint8Array, { message: \"Must be a Uint8Array\" }),\n\tz.custom(isArrayBuffer, { message: \"Must be an ArrayBuffer\" }),\n\tz.custom(isBuffer, { message: \"Must be a Buffer\" })\n]);\nconst providerReferenceSchema = 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$1.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\n\t]),\n\tmediaType: z.string().optional(),\n\tproviderOptions: providerMetadataSchema$1.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\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\n\t]),\n\tfilename: z.string().optional(),\n\tmediaType: z.string(),\n\tproviderOptions: providerMetadataSchema$1.optional()\n});\n/**\n* @internal\n*/\nconst reasoningPartSchema = z.object({\n\ttype: z.literal(\"reasoning\"),\n\ttext: z.string(),\n\tproviderOptions: providerMetadataSchema$1.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$1.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$1.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$1.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$1.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"json\"),\n\t\tvalue: jsonValueSchema,\n\t\tproviderOptions: providerMetadataSchema$1.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"execution-denied\"),\n\t\treason: z.string().optional(),\n\t\tproviderOptions: providerMetadataSchema$1.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"error-text\"),\n\t\tvalue: z.string(),\n\t\tproviderOptions: providerMetadataSchema$1.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"error-json\"),\n\t\tvalue: jsonValueSchema,\n\t\tproviderOptions: providerMetadataSchema$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"custom\"),\n\t\t\t\tproviderOptions: providerMetadataSchema$1.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$1.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$1.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$1.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$1.optional()\n});\nconst toolModelMessageSchema = z.object({\n\trole: z.literal(\"tool\"),\n\tcontent: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),\n\tproviderOptions: providerMetadataSchema$1.optional()\n});\nconst modelMessageSchema = z.union([\n\tsystemModelMessageSchema,\n\tuserModelMessageSchema,\n\tassistantModelMessageSchema,\n\ttoolModelMessageSchema\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.reportedTransportErrors = /* @__PURE__ */ new WeakSet();\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$1.object({\n\ttoken: z$1.string().check(z$1.refine((value) => value.trim().length > 0)),\n\turl: z$1.string().check(z$1.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$1.optional(z$1.number().check(z$1.positive()).check(z$1.maximum(Number.MAX_SAFE_INTEGER))),\n\ttools: z$1.optional(z$1.array(z$1.object({\n\t\ttype: z$1.literal(\"function\"),\n\t\tname: z$1.string().check(z$1.minLength(1)),\n\t\tdescription: z$1.optional(z$1.string()),\n\t\tparameters: z$1.record(z$1.string(), z$1.unknown())\n\t})))\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 || api.provider != null) && this.options.maxPlaybackBufferSeconds != null) throw new Error(\"maxPlaybackBufferSeconds is supported only for continuous PCM sessions\");\n\t\tconst connection = api.provider != null ? \"provider\" : api.session != null ? \"webrtc\" : api.token != null ? \"client-secret-websocket\" : \"server-websocket\";\n\t\tif (!(model.capabilities?.connections ?? [\"client-secret-websocket\"]).includes(connection) || api.provider == null && 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.provider != null) {\n\t\t\tif (model.createTransport == null) throw new Error(\"Realtime model does not support a provider transport\");\n\t\t\treturn;\n\t\t}\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 && api.provider == 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 = attempt.reportedTransportErrors;\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.providerTransport ?? 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 (api.provider != null && attempt.closing) {\n\t\t\t\t\t\tif (error != null && !finalizationConfirmed && !reportedTransportErrors.has(error)) {\n\t\t\t\t\t\t\treportedTransportErrors.add(error);\n\t\t\t\t\t\t\tthis.reportError(error, attempt);\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 (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.provider != null) {\n\t\t\t\tconst transport = model.createTransport(callbacks);\n\t\t\t\tif (!current()) {\n\t\t\t\t\ttransport.dispose();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.providerTransport = transport;\n\t\t\t\tawait transport.connect({\n\t\t\t\t\tapi: api.provider,\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\tabortSignal: attempt.abort.signal\n\t\t\t\t});\n\t\t\t} else if (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.providerTransport ?? this.rtc ?? this.pcm ?? this.transport;\n\t\tthis.drainAttempt(attempt, transport?.finish());\n\t\tif (error instanceof Error) {\n\t\t\tif (attempt.reportedTransportErrors.has(error)) return;\n\t\t\tattempt.reportedTransportErrors.add(error);\n\t\t}\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\tconst providerTransport = this.providerTransport;\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.providerTransport = 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\tproviderTransport?.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 provider cleanup or supported session-close finalization. */\n\tclose(options) {\n\t\tconst attempt = this.attempt;\n\t\tif (attempt?.closePromise != null) return attempt.closePromise;\n\t\tconst providerTransport = this.providerTransport;\n\t\tif (providerTransport != null && attempt?.active) {\n\t\t\tconst promise = attempt.beginClose();\n\t\t\tattempt.clearTimer(\"startup\");\n\t\t\tthis.applyState({\n\t\t\t\t...this.state,\n\t\t\t\tstatus: \"closing\"\n\t\t\t});\n\t\t\tif (this.attempt !== attempt || !attempt.active) return promise;\n\t\t\tthis.stopAudioCapture();\n\t\t\tif (this.attempt !== attempt || !attempt.active) return promise;\n\t\t\tattempt.timer(\"close\", this.options.closeTimeoutMs ?? 15e3, () => {\n\t\t\t\tif (this.attempt === attempt && attempt.active) this.fail(/* @__PURE__ */ new Error(\"Realtime provider session cleanup timed out\"));\n\t\t\t});\n\t\t\tproviderTransport.close().then(() => this.finishAttempt(attempt), (error) => this.closeFailed(attempt, error));\n\t\t\treturn promise;\n\t\t}\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.providerTransport ?? this.rtc ?? this.pcm ?? this.transport;\n\t\tif (transport == null) throw new Error(\"Realtime connection is not open\");\n\t\tif (transport === this.providerTransport) {\n\t\t\tconst attempt = this.attempt;\n\t\t\tconst sent = transport.sendEvent(event, guard);\n\t\t\tsent.catch((error) => {\n\t\t\t\tif (attempt?.active && this.attempt === attempt) this.reportError(error, attempt);\n\t\t\t});\n\t\t\treturn sent;\n\t\t}\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.providerTransport != null || 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 && this.options.api.provider == 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.providerTransport != null) return this.providerTransport.startCapture(this.suppliedStream);\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 providerTransport = this.providerTransport;\n\t\tconst attempt = this.attempt;\n\t\tif (providerTransport != null) providerTransport.stopCapture().catch((error) => {\n\t\t\tif (attempt?.active && this.attempt === attempt) this.reportError(error, attempt);\n\t\t});\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.providerTransport ?? this.rtc ?? this.pcm ?? this.audio)?.stopPlayback();\n\t}\n\tasync resumePlayback() {\n\t\tawait (this.providerTransport ?? 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 = {}, timestampGranularities, 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\ttimestampGranularities\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\tif (resolvedModel.doGenerateFromUrl != null && downloadFn === defaultDownload && (audio.protocol === \"https:\" || audio.protocol === \"http:\")) audioData = audio;\n\t\t\telse {\n\t\t\t\tconst downloadResult = await downloadFn({\n\t\t\t\t\turl: audio,\n\t\t\t\t\tabortSignal\n\t\t\t\t});\n\t\t\t\taudioData = downloadResult.data;\n\t\t\t\tdownloadedMediaType = downloadResult.mediaType;\n\t\t\t}\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\tlet mediaType = audioData instanceof URL ? void 0 : getAudioMediaType(downloadedMediaType) ?? detectMediaType({\n\t\tdata: audioData,\n\t\ttopLevelType: \"audio\"\n\t}) ?? \"audio/wav\";\n\tlet byteLength = audioData instanceof URL ? void 0 : audioData.byteLength;\n\tconst startEvent = createStartEvent({\n\t\tbyteLength,\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(async () => {\n\t\t\t\t\tconst callOptions = {\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\t...timestampGranularities != null ? { timestampGranularities } : {}\n\t\t\t\t\t};\n\t\t\t\t\tif (audioData instanceof URL) {\n\t\t\t\t\t\tconst nativeResult = await resolvedModel.doGenerateFromUrl?.({\n\t\t\t\t\t\t\t...callOptions,\n\t\t\t\t\t\t\taudio: audioData\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (nativeResult != null) return nativeResult;\n\t\t\t\t\t\tconst downloaded = await downloadFn({\n\t\t\t\t\t\t\turl: audioData,\n\t\t\t\t\t\t\tabortSignal\n\t\t\t\t\t\t});\n\t\t\t\t\t\taudioData = downloaded.data;\n\t\t\t\t\t\tmediaType = getAudioMediaType(downloaded.mediaType) ?? detectMediaType({\n\t\t\t\t\t\t\tdata: audioData,\n\t\t\t\t\t\t\ttopLevelType: \"audio\"\n\t\t\t\t\t\t}) ?? \"audio/wav\";\n\t\t\t\t\t\tbyteLength = audioData.byteLength;\n\t\t\t\t\t}\n\t\t\t\t\treturn resolvedModel.doGenerate({\n\t\t\t\t\t\t...callOptions,\n\t\t\t\t\t\taudio: audioData,\n\t\t\t\t\t\tmediaType: mediaType ?? \"audio/wav\"\n\t\t\t\t\t});\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,\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\twords: result.words,\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\twords: result.words,\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}\n/**\n* Normalizes a downloaded `Content-Type` header value and returns it only\n* when it is a full `audio/<subtype>` media type. Generic or mislabeled types\n* (e.g. `application/octet-stream`, `binary/octet-stream`, `text/plain`)\n* return `undefined` so that the media type is detected from the audio bytes\n* instead.\n*/\nfunction getAudioMediaType(contentType) {\n\tconst mediaType = contentType?.split(\";\")[0].trim().toLowerCase();\n\treturn mediaType != null && getTopLevelMediaType(mediaType) === \"audio\" && isFullMediaType(mediaType) ? mediaType : void 0;\n}\nvar DefaultTranscriptionResult = class {\n\tconstructor(options) {\n\t\tthis.text = options.text;\n\t\tthis.segments = options.segments;\n\t\tthis.words = options.words;\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({ resumeStreamIsReplay = true, ...options } = {}) {\n\t\tsuper(options);\n\t\tthis.resumeStreamIsReplay = resumeStreamIsReplay;\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\tget id() {\n\t\treturn this._id ??= this.generateId();\n\t}\n\tconstructor({ generateId = generateId$1, id, transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen, experimental_queue = false }) {\n\t\tthis.queuedMessagesFallback = [];\n\t\tthis.queuedMessageOptions = /* @__PURE__ */ new Map();\n\t\tthis.isQueuePaused = false;\n\t\tthis.pendingAutomaticDecisions = [];\n\t\tthis.pendingMessagePreparations = /* @__PURE__ */ new Set();\n\t\tthis.interruptedMessageIds = /* @__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.experimental_removeQueuedMessage = (id) => {\n\t\t\tthis.queuedMessageOptions.delete(id);\n\t\t\tthis.setQueuedMessages(this.experimental_queuedMessages.filter((message) => message.id !== id));\n\t\t};\n\t\tthis.experimental_sendQueuedMessageNow = async (id) => {\n\t\t\tconst message = this.experimental_queuedMessages.find((message) => message.id === id);\n\t\t\tif (message == null) return;\n\t\t\tthis.setQueuedMessages([message, ...this.experimental_queuedMessages.filter((queued) => queued.id !== id)]);\n\t\t\tconst stopGeneration = this.stopGeneration + 1;\n\t\t\tawait this.stop();\n\t\t\tif (stopGeneration !== this.stopGeneration) return;\n\t\t\tawait this.resumeQueue({\n\t\t\t\tskipWaitForUser: true,\n\t\t\t\toptions: this.queuedMessageOptions.get(id)\n\t\t\t});\n\t\t};\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 (this.queueEnabled && message.messageId == null && (this.isRequestInProgress() || this.isWaitingForUser() || this.experimental_queuedMessages.length > 0)) {\n\t\t\t\tconst queuedMessage = {\n\t\t\t\t\t...uiMessage,\n\t\t\t\t\tid: uiMessage.id ?? this.generateId(),\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\tif (options != null) this.queuedMessageOptions.set(queuedMessage.id, options);\n\t\t\t\tthis.setQueuedMessages([...this.experimental_queuedMessages, queuedMessage]);\n\t\t\t\tawait this.resumeQueue({\n\t\t\t\t\tskipWaitForUser: this.isQueuePaused,\n\t\t\t\t\toptions\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (message.messageId != null) {\n\t\t\t\tawait this.clearQueueForHistoryChange();\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\tthis.isQueuePaused = false;\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\tawait this.clearQueueForHistoryChange();\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[\"~resumeStreamIfDisconnected\"] = async ({ shouldResume = () => true } = {}) => {\n\t\t\tconst activeResponse = this.activeResponse;\n\t\t\tif (this.resumableStreamState == null && activeResponse != null) {\n\t\t\t\tawait activeResponse.completionPromise;\n\t\t\t\tif (this.resumableStreamState !== activeResponse.state) return;\n\t\t\t}\n\t\t\tif (this.resumableStreamState != null && shouldResume()) await this.resumeStream();\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 stopGeneration = this.stopGeneration;\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(messages[messageIndex].id);\n\t\t\t\tif (shouldSend) {\n\t\t\t\t\tthis.runAutomaticRequest(() => {\n\t\t\t\t\t\tconst messageId = messageIndex === -1 ? this.lastMessage?.id : messages[messageIndex].id;\n\t\t\t\t\t\treturn this.makeRequestForToolApproval({\n\t\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\t\tmessageIndex,\n\t\t\t\t\t\t\t...options\n\t\t\t\t\t\t});\n\t\t\t\t\t}, shouldSend);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.settleQueue({ stopGeneration });\n\t\t});\n\t\tthis.addToolOutput = async ({ state, toolCallId, output, errorText, options }) => this.jobExecutor.run(async () => {\n\t\t\tconst stopGeneration = this.stopGeneration;\n\t\t\tconst messages = this.state.messages;\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\tconst messageIndex = messages.findIndex((message) => message.parts.some((part) => isToolUIPart(part) && part.toolCallId === toolCallId));\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}\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(messages[messageIndex].id);\n\t\t\t\tif (shouldSend) {\n\t\t\t\t\tthis.runAutomaticRequest(() => this.makeRequest({\n\t\t\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\t\t\tmessageId: messages[messageIndex].id,\n\t\t\t\t\t\t...options\n\t\t\t\t\t}), shouldSend);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.settleQueue({ stopGeneration });\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\tthis.deferredApprovalSend = void 0;\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\tthis.isQueuePaused = true;\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\tthis.queueEnabled = experimental_queue;\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\t/**\n\t* Experimental. Messages that wait to be sent when `experimental_queue` is\n\t* enabled, in the order they will be sent.\n\t*/\n\tget experimental_queuedMessages() {\n\t\treturn this.state.experimental_queuedMessages ?? this.queuedMessagesFallback;\n\t}\n\tsetQueuedMessages(experimental_queuedMessages) {\n\t\tif (\"experimental_queuedMessages\" in this.state) this.state.experimental_queuedMessages = experimental_queuedMessages;\n\t\telse this.queuedMessagesFallback = experimental_queuedMessages;\n\t}\n\tasync resumeQueue({ skipWaitForUser, options }) {\n\t\tthis.isQueuePaused = false;\n\t\tif (this.hasUnsentApprovalResponse()) {\n\t\t\tif (!this.isRequestInProgress()) {\n\t\t\t\tawait this.sendMessage(void 0, options);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.deferredApprovalSend = { options };\n\t\t}\n\t\tawait this.settleQueue({ skipWaitForUser });\n\t}\n\tasync clearQueueForHistoryChange() {\n\t\tif (!this.queueEnabled) return;\n\t\tthis.queuedMessageOptions.clear();\n\t\tthis.setQueuedMessages([]);\n\t\tthis.deferredApprovalSend = void 0;\n\t\tif (this.isRequestInProgress()) await this.stop();\n\t}\n\tisRequestInProgress() {\n\t\treturn this.pendingAutomaticDecisions.includes(this.stopGeneration) || this.activeResponse != null || this.status === \"submitted\" || this.status === \"streaming\";\n\t}\n\tisWaitingForUser() {\n\t\tconst lastMessage = this.lastMessage;\n\t\treturn lastMessage?.role === \"assistant\" && lastMessage.parts.some((part) => isToolUIPart(part) && (part.state === \"approval-requested\" || part.state === \"approval-responded\" || !part.providerExecuted && (part.state === \"input-streaming\" || part.state === \"input-available\")));\n\t}\n\thasUnsentApprovalResponse() {\n\t\tconst lastMessage = this.lastMessage;\n\t\treturn lastMessage?.role === \"assistant\" && lastMessage.parts.some((part) => isToolUIPart(part) && part.state === \"approval-responded\") && !lastMessage.parts.some((part) => isToolUIPart(part) && (part.state === \"approval-requested\" || !part.providerExecuted && (part.state === \"input-streaming\" || part.state === \"input-available\")));\n\t}\n\tasync settleQueue({ stopGeneration = this.stopGeneration, skipWaitForUser = false } = {}) {\n\t\tif (this.isQueuePaused || this.isRequestInProgress() || this.activeStopCount > 0 || stopGeneration !== this.stopGeneration) return;\n\t\tconst deferredApprovalSend = this.deferredApprovalSend;\n\t\tthis.deferredApprovalSend = void 0;\n\t\tif (deferredApprovalSend != null && this.hasUnsentApprovalResponse()) {\n\t\t\tawait this.sendMessage(void 0, deferredApprovalSend.options);\n\t\t\treturn;\n\t\t}\n\t\tconst [message, ...rest] = this.experimental_queuedMessages;\n\t\tif (message == null || !skipWaitForUser && this.isWaitingForUser()) return;\n\t\tconst options = this.queuedMessageOptions.get(message.id);\n\t\tthis.queuedMessageOptions.delete(message.id);\n\t\tthis.setQueuedMessages(rest);\n\t\tthis.state.pushMessage(message);\n\t\tawait this.makeRequest({\n\t\t\ttrigger: \"submit-message\",\n\t\t\t...options\n\t\t});\n\t}\n\tset messages(messages) {\n\t\tthis.state.messages = messages;\n\t}\n\tasync shouldSendAutomatically(messageId = this.lastMessage?.id) {\n\t\tconst isInterrupted = (id) => id != null && this.interruptedMessageIds.has(id);\n\t\tif (!this.sendAutomaticallyWhen || isInterrupted(messageId) || isInterrupted(this.lastMessage?.id)) return false;\n\t\tconst stopGeneration = this.stopGeneration;\n\t\tthis.pendingAutomaticDecisions.push(stopGeneration);\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this.sendAutomaticallyWhen({ messages: this.state.messages });\n\t\t} finally {\n\t\t\tthis.pendingAutomaticDecisions.splice(this.pendingAutomaticDecisions.indexOf(stopGeneration), 1);\n\t\t}\n\t\treturn result && !isInterrupted(messageId) && !isInterrupted(this.lastMessage?.id);\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 false;\n\t\tif (startedWhileStopping || stopGeneration !== this.stopGeneration || this.activeStopCount > 0) return false;\n\t\tawait request();\n\t\treturn true;\n\t}\n\tasync makeRequestForToolApproval({ messageId, messageIndex, ...options }) {\n\t\tthis.deferredApprovalSend = void 0;\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 originalResponseMessageId = responseMessage?.id;\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\tconst existingMessageIndex = this.state.messages.findLastIndex((message) => message.id === response.state.message.id);\n\t\t\t\t\t\tif (existingMessageIndex !== -1) this.state.replaceMessage(existingMessageIndex, response.state.message);\n\t\t\t\t\t\telse if (usesEarlierAssistantMessage) {\n\t\t\t\t\t\t\tconst originalMessageIndex = this.state.messages.findLastIndex((message) => message.id === originalResponseMessageId);\n\t\t\t\t\t\t\tif (originalMessageIndex !== -1) this.state.replaceMessage(originalMessageIndex, response.state.message);\n\t\t\t\t\t\t\telse this.state.pushMessage(response.state.message);\n\t\t\t\t\t\t} else 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) {\n\t\t\t\t\tconst { message, finishReason } = activeResponse.state;\n\t\t\t\t\tif (finishReason === \"interrupted\") this.interruptedMessageIds.add(message.id);\n\t\t\t\t\telse if (!isAbort && !isError) this.interruptedMessageIds.delete(message.id);\n\t\t\t\t\tthis.onFinish?.({\n\t\t\t\t\t\tmessage: activeResponse.state.message,\n\t\t\t\t\t\tmessages: this.state.messages,\n\t\t\t\t\t\tisAbort,\n\t\t\t\t\t\tisDisconnect,\n\t\t\t\t\t\tisError,\n\t\t\t\t\t\tfinishReason: activeResponse.state.finishReason\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tif (isAbort || isError || activeResponse?.state.finishReason === \"interrupted\") this.isQueuePaused = true;\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 && activeResponse?.state.finishReason !== \"interrupted\") {\n\t\t\tconst stopGeneration = this.stopGeneration;\n\t\t\tif (!await this.runAutomaticRequest(() => this.makeRequest({\n\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\tmessageId: this.lastMessage?.id,\n\t\t\t\tmetadata,\n\t\t\t\theaders,\n\t\t\t\tbody\n\t\t\t}))) await this.settleQueue({ stopGeneration });\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, Experimental_ExtractionRefusalError, Experimental_ExtractionUnsupportedFieldTypeError, 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, createSteering as experimental_createSteering, decide as experimental_decide, decodeRealtimeAudio as experimental_decodeRealtimeAudio, encodeRealtimeAudio as experimental_encodeRealtimeAudio, experimental_evaluate, extract as experimental_extract, filterActiveTools as experimental_filterActiveTools, 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, streamSpeech as experimental_streamSpeech, streamTextLowMemory as experimental_streamTextLowMemory, 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, normalizeHeaders, 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\tconst currentAbortController = new AbortController();\n\t\tabortController = currentAbortController;\n\t\ttry {\n\t\t\tawait clearObject();\n\t\t\tif (currentAbortController.signal.aborted) return;\n\t\t\tawait mutateLoading(() => true);\n\t\t\tif (currentAbortController.signal.aborted) {\n\t\t\t\tif (abortController === null) await mutateLoading(() => false);\n\t\t\t\treturn;\n\t\t\t}\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...normalizeHeaders(headers)\n\t\t\t\t},\n\t\t\t\tcredentials: credentials ?? \"same-origin\",\n\t\t\t\tsignal: currentAbortController.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\tif (abortController === currentAbortController) {\n\t\t\t\t\t\tabortController = null;\n\t\t\t\t\t\tawait mutateLoading(() => false);\n\t\t\t\t\t}\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.queuedMessagesRef = ref([]);\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\tget experimental_queuedMessages() {\n\t\treturn this.queuedMessagesRef.value;\n\t}\n\tset experimental_queuedMessages(experimental_queuedMessages) {\n\t\tthis.queuedMessagesRef.value = experimental_queuedMessages;\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, queuedMessagesRef, throttleWaitMs }) {\n\t\tthis.publishedMessages = [];\n\t\tthis.publishedMessageSources = [];\n\t\tthis.dirtyMessageIndices = /* @__PURE__ */ new Set();\n\t\tthis.statusValue = \"ready\";\n\t\tthis.queuedMessagesValue = [];\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.queuedMessagesRef = queuedMessagesRef;\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\tget experimental_queuedMessages() {\n\t\treturn this.queuedMessagesValue;\n\t}\n\tset experimental_queuedMessages(experimental_queuedMessages) {\n\t\tthis.queuedMessagesValue = experimental_queuedMessages;\n\t\tif (this.isActive) this.queuedMessagesRef.value = experimental_queuedMessages;\n\t}\n\tpublishInitialState() {\n\t\tthis.publishMessages();\n\t\tthis.statusRef.value = this.statusValue;\n\t\tthis.errorRef.value = this.errorValue;\n\t\tthis.queuedMessagesRef.value = this.queuedMessagesValue;\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 experimental_queuedMessages = 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\tqueuedMessagesRef: experimental_queuedMessages,\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\texperimental_queuedMessages,\n\t\texperimental_removeQueuedMessage: (id) => chatInstance.value.experimental_removeQueuedMessage(id),\n\t\texperimental_sendQueuedMessageNow: (id) => chatInstance.value.experimental_sendQueuedMessageNow(id)\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 {\n computed,\n nextTick,\n onScopeDispose,\n reactive,\n ref,\n shallowRef,\n watch,\n watchEffect,\n} from 'vue'\nimport { useI18n } from 'vue-i18n'\nimport { useDocumentVisibility, usePreferredDark } from '@vueuse/core'\nimport { generateId } from 'ai'\nimport { useChat } from '@ai-sdk/vue'\nimport { defineStore } from 'pinia'\nimport {\n useSafeLocalStorage,\n useSafeSessionStorage,\n} from '../useSafeLocalStorage'\nimport {\n CHAT_LIST_WITHOUT_PROJECT,\n isHostToolPart,\n isReservedHostToolName,\n isUserAnsweredTool,\n PAGE_TOOL_FEATURES,\n PageAccessLevel,\n pageAccessAllows,\n TOOL_TERMINAL_STATES,\n} from 'models'\nimport type {\n Chat as ChatRecord,\n AgentConfirmationsCapability,\n AgentFileUpload,\n AgentInterface,\n AgentModel,\n AgentVoiceCapability,\n AgentGatewayOptions,\n ChatMessageActions,\n MessageFeedback,\n RevisedAnswer,\n UIChatMessage,\n UIChatMessageMetadata,\n AgentTools,\n HostToolResult,\n HostToolsCapability,\n PageAccessCapability,\n PagePointer,\n FilePointer,\n MediaSource,\n SelectionActionsCapability,\n} from 'models'\nimport {\n PAGE_NAVIGATION_KEY,\n createHostToolRunner,\n declaredHostTools,\n isHostToolCall,\n type ConfirmationMode,\n type HostToolCall,\n type HostToolConfirmation,\n type RegisteredHostTool,\n} from './hostTools'\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 {\n CONVERSATIONS_PAGE_SIZE,\n createChatbotApiClient,\n type ChatbotFile,\n} from './api'\nimport type { PendingAttachment } from './types'\n\n// The store exposes `chat` (a reactive view of `useChat`) 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/**\n * How long a call's page action that may unload the page waits after its\n * result left for the provider: the socket sends it, then the page may go.\n */\nconst VOICE_RESULT_SEND_MS = 300\n\n/** How long the turn has to stay quiet before `isWorking` goes off. */\nexport const WORKING_SETTLE_MS = 400\n\n/** A tool call of the answer waits for the user's approval card. */\nconst awaitsApproval = (message: UIChatMessage | undefined): boolean =>\n message?.role === 'assistant' &&\n message.parts.some(\n (part) => (part as { state?: string }).state === 'approval-requested',\n )\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. And a persisted question already on screen under its own id\n // accounts for itself: left in, the \"sì\" written two turns ago took the\n // \"sì\" just said for its own, which vanished the same way and made the\n // reload report its turn as written before it was.\n const onScreen = new Set(shown.map((message) => message.id))\n const server = persisted\n .filter(\n (message) => message.role === 'user' && !onScreen.has(message.id),\n )\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/**\n * How long a chat opened mid-turn waits for the turn to be written, and how\n * often it reads the chat meanwhile. Longer than the minute and a half after\n * which the server stops reporting the turn of a replica that is gone.\n */\nconst FOLLOW_TURN_TIMEOUT_MS = 120_000\nconst FOLLOW_TURN_RETRY_MS = 1_000\n\n/** How often the turns running in the background are read again. */\nexport const RUNNING_TURNS_POLL_MS = 5_000\n\n/** The chats asked about at once, as many as the server reads. */\nconst RUNNING_TURNS_MAX_IDS = 100\n\n/**\n * How long a chat left before its request reached the server (`submitted`)\n * waits to be reported running once: until then its absence is not the end\n * of its turn, and after it the turn never started.\n */\nconst BACKGROUND_START_GRACE_MS = 30_000\n\n/**\n * How long a queued message waits for the turn before it to be written, and\n * how often it asks meanwhile: the write follows the end of the stream.\n */\nconst QUEUE_WRITE_WAIT_MS = 5_000\nconst QUEUE_WRITE_RETRY_MS = 250\n/** One ask that takes longer counts as \"still running\", so the wait keeps its bound. */\nconst QUEUE_WRITE_ASK_MS = 1_000\n\n/** Between the queued messages, sent together as one. */\nconst QUEUE_SEPARATOR = '\\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/** A tool of the answer waits for the user to answer it: a form, a choice. */\nconst awaitsToolAnswer = (message: UIChatMessage | undefined): boolean =>\n message?.role === 'assistant' &&\n message.parts.some(\n (part) =>\n isUserAnsweredTool(partToolName(part)) &&\n !(part as { providerExecuted?: boolean }).providerExecuted &&\n !TOOL_TERMINAL_STATES.has((part as { state?: string }).state ?? ''),\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 // A host call is answered by the app that embeds the chat\n // (spec `host-tools.md`), and resumes the turn the same way.\n (isUserAnsweredTool(partToolName(part)) ||\n isHostToolPart(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\n/** What a message sent with a selection carries: on the page, or in a file of the chat. */\nexport type SelectionPointer =\n { pagePointer: PagePointer } | { filePointer: FilePointer }\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 /** Host tools as the agent allows them, from the public agent: absent is off. */\n const agentHostTools = ref<HostToolsCapability | undefined>()\n /** Tools the host registered (`registerTool` on the custom element). Shallow: they carry functions. */\n const hostToolRegistry = shallowRef<RegisteredHostTool[] | undefined>()\n /** Host calls queued or running: the turn is not over while there are any. */\n const hostToolsPending = ref(0)\n /** Page calls of a voice call queued or running: the page control bar stays up for them. */\n const voicePageCallsPending = ref(0)\n /** Page access as the agent allows it (spec `page-tools.md`): absent is off. */\n const agentPageAccess = ref<PageAccessCapability | undefined>()\n /** Whether the user may choose automatic confirmations (spec `auto-confirmations.md`): absent is no. */\n const agentConfirmations = ref<\n AgentConfirmationsCapability | undefined\n >()\n /** The selection bar's groups (spec `selection-actions.md`, \"Cosa è comune\"): absent is no bar. */\n const agentSelectionActions = ref<\n SelectionActionsCapability | undefined\n >()\n /** The page tools of the widget: never declared as host tools, run by the same queue. */\n const pageToolRegistry = shallowRef<RegisteredHostTool[] | undefined>()\n /** The tools of the forms annotated on the page, read again each time they are needed. */\n const pageFormsProvider = shallowRef<\n (() => RegisteredHostTool[]) | undefined\n >()\n /** The page action running, what the page control bar shows; undefined when none. */\n const pageAction = ref<{ title: string } | undefined>()\n /**\n * What the user pointed at on the page for the next message (spec\n * `page-point-and-choose.md`, P): the chip above the input, sent on\n * the message's metadata.\n */\n const pagePointer = ref<PagePointer | undefined>()\n /** Starts pointing at the page: the widget's, absent where the chat cannot read a page. */\n const pagePointerStart = shallowRef<(() => void) | undefined>()\n /** The user is choosing an element of the page now. */\n const pagePointing = ref(false)\n /**\n * The titles of this page's steps by call, naming what each acts on\n * (spec `page-tools-improvements.md`, M8). Not saved with the chat:\n * after a reload the steps show their tool's own title.\n */\n const hostStepTitles = ref<Record<string, string>>({})\n /**\n * What the steps the automatic confirmations ran without a card\n * changed, by call: the table their card would have shown. Not saved\n * with the chat either (spec `auto-confirmations.md`).\n */\n const hostStepChanges = ref<\n Record<string, Pick<HostToolConfirmation, 'details' | 'unchanged'>>\n >({})\n /** True from the first page action of a response until the response ends. */\n const pageControlActive = ref(false)\n /** Requests started: a deferred click waits for the next one to stream. */\n const requestCount = ref(0)\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 // === Page access switched off by the user (spec `page-tools.md`) ===\n // For this agent in this tab: sessionStorage is the tab's and the\n // site's origin's, the scope the user decided for.\n const pageAccessOff = useSafeSessionStorage<boolean>(\n computed(() => `${agentIdRef.value}-pageAccessOff`),\n false,\n )\n /** The page tools the requests declare and the queue runs: none once the user switched them off. */\n const activePageTools = computed(() =>\n pageAccessOff.value ? [] : (pageToolRegistry.value ?? []),\n )\n /** The annotated forms of the page now: none once the user switched page access off. */\n const pageForms = () =>\n pageAccessOff.value ? [] : (pageFormsProvider.value?.() ?? [])\n /** The agent may use this page: the menu then offers to switch it off, or on again. */\n const pageAccessAvailable = computed(() =>\n Boolean(agentPageAccess.value && pageToolRegistry.value?.length),\n )\n\n // === Confirmations chosen by the user (spec `auto-confirmations.md`) ===\n // In this browser, for this agent and this user, until they go back\n // to manual: whoever chose them finds them again.\n const confirmationChoice = useSafeLocalStorage<ConfirmationMode>(\n computed(\n () =>\n `${agentIdRef.value}-${userId.value ?? 'anonymous'}-confirmations`,\n ),\n 'manual',\n )\n /** The user may choose automatic confirmations: the menu then offers them. */\n const confirmationsAvailable = computed(\n () => agentConfirmations.value?.allowAutomatic === true,\n )\n /** What holds now: automatic only while the agent allows it, whatever was chosen. */\n const confirmationMode = computed<ConfirmationMode>(() =>\n confirmationsAvailable.value &&\n confirmationChoice.value === 'automatic'\n ? 'automatic'\n : 'manual',\n )\n /** The user's choice from the menu or the label above the input. */\n function setConfirmationMode(mode: ConfirmationMode) {\n confirmationChoice.value = mode\n }\n /** The user may point at the page: the agent offers it, the widget can, and the page tools are on. */\n const pagePointerAvailable = computed(\n () =>\n !!pagePointerStart.value &&\n agentPageAccess.value?.pointer === true &&\n activePageTools.value.length > 0,\n )\n // Switched off, the page sends nothing more: not what was pointed at\n watch(pagePointerAvailable, (available) => {\n if (!available) {\n pagePointer.value = undefined\n }\n })\n\n // === Page access notice (spec `page-tools.md`) ===\n // Closed for this agent in this browser, up to the level it spoke of:\n // a level raised later is news, and the notice comes back; a lower\n // one is part of what the user already read.\n const pageNoticeClosedAt = useSafeLocalStorage<string | null>(\n computed(() => `${agentIdRef.value}-pageNotice`),\n null,\n )\n /** The level the notice above the input speaks of; undefined when it is not shown. */\n const pageNoticeLevel = computed(() => {\n const level = agentPageAccess.value?.level\n return level &&\n level !== PageAccessLevel.Off &&\n activePageTools.value.length &&\n !pageAccessAllows(\n (pageNoticeClosedAt.value ?? undefined) as\n PageAccessLevel | undefined,\n level,\n )\n ? level\n : undefined\n })\n function closePageNotice() {\n pageNoticeClosedAt.value = agentPageAccess.value?.level ?? null\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 // A colleague's chat is never written, so never restarted either:\n // a new chat of the reader would carry their words out of it\n if (isEntityNotFoundError(error) && !isReadOnlyChat.value) {\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 chatError.value = undefined\n\n // The chat of the new id exists from the next tick, when\n // `useChat` recreates it: resend there, not to the one that\n // just failed with the old id.\n void nextTick(() => {\n chat.value.clearError()\n if (lastUserText) {\n chat.value.sendMessage({ text: lastUserText })\n }\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 /**\n * True once a request started after this call is streaming: the\n * backend merges the outputs it carries before it streams anything,\n * so the first chunk is the proof it holds them. False after 30 s.\n */\n const waitForResume = () => {\n const startedBefore = requestCount.value\n return new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => {\n stop()\n resolve(false)\n }, 30_000)\n const stop = watch(\n () => [requestCount.value, chat.value.status] as const,\n ([count, status]) => {\n if (count > startedBefore && status === 'streaming') {\n clearTimeout(timer)\n stop()\n resolve(true)\n }\n },\n )\n })\n }\n\n /**\n * The host call waiting for the user's consent: what the confirmation\n * card shows. Kept here only, never in a message or a request.\n */\n const hostConfirmation = shallowRef<\n | {\n toolCallId: string\n question?: string\n details?: HostToolConfirmation['details']\n unchanged?: HostToolConfirmation['unchanged']\n answer: (approved: boolean) => void\n }\n | undefined\n >()\n const askHostConfirmation = (\n call: HostToolCall,\n confirmation?: HostToolConfirmation,\n ) =>\n new Promise<boolean>((resolve) => {\n hostConfirmation.value?.answer(false)\n hostConfirmation.value = {\n toolCallId: call.toolCallId,\n question: confirmation?.question,\n details: confirmation?.details,\n unchanged: confirmation?.unchanged,\n answer: (approved) => {\n hostConfirmation.value = undefined\n resolve(approved)\n },\n }\n })\n /** The user's answer on the confirmation card. */\n function respondHostConfirmation(approved: boolean) {\n hostConfirmation.value?.answer(approved)\n }\n /**\n * A card the automatic confirmations skipped: its changes stay on the\n * call's step, the record of what the agent did without asking.\n */\n const reportSkippedCard = (\n call: HostToolCall,\n card: HostToolConfirmation,\n ) => {\n if (!card.details?.some((detail) => detail.before !== undefined)) {\n return\n }\n hostStepChanges.value = {\n ...hostStepChanges.value,\n [call.toolCallId]: {\n details: card.details,\n unchanged: card.unchanged,\n },\n }\n }\n\n /**\n * What a request declares of the page tools (spec `page-tools.md`),\n * nothing when they are off. A call declares none of the forms: the\n * provider takes its tools before the call, and a form's name is the\n * page's.\n */\n const declarePageTools = ({ forms }: { forms: boolean }) =>\n agentPageAccess.value && activePageTools.value.length\n ? {\n version: 1 as const,\n // What this bundle runs: the backend offers nothing past it\n features: [...PAGE_TOOL_FEATURES],\n // What the model reads of each form: never its `execute`.\n forms: forms\n ? pageForms().map(\n ({\n name,\n description,\n inputSchema,\n annotations,\n }) => ({\n name,\n description,\n inputSchema,\n annotations,\n }),\n )\n : [],\n }\n : undefined\n\n /** What the page control bar and the steps show of the call starting, or of none. */\n const showPageActivity = (call: HostToolCall | undefined) => {\n if (call?.provider !== 'page') {\n pageAction.value = undefined\n return\n }\n const tool = [...activePageTools.value, ...pageForms()].find(\n (candidate) => candidate.name === call.toolName,\n )\n // What the step acts on, by name; a failure keeps the\n // tool's own title\n let described: string | undefined\n try {\n described = tool?.describe?.(call.input)\n } catch {\n described = undefined\n }\n if (described) {\n hostStepTitles.value = {\n ...hostStepTitles.value,\n [call.toolCallId]: described,\n }\n }\n if (call.readOnly) {\n pageAction.value = undefined\n return\n }\n pageAction.value = {\n title: described ?? tool?.annotations?.title ?? call.toolName,\n }\n pageControlActive.value = true\n }\n\n const hostToolRunner = createHostToolRunner({\n registry: () => [\n // Never a page's tool under a reserved name: the backend\n // offers only the widget's own under it, and the page's\n // would run in its place without the widget's confirmation.\n ...(hostToolRegistry.value ?? []).filter(\n (tool) => !isReservedHostToolName(tool.name),\n ),\n ...activePageTools.value,\n ...pageForms(),\n ],\n capability: () => agentHostTools.value,\n addToolOutput: (output) =>\n void chat.value.addToolOutput(\n output as Parameters<typeof chat.value.addToolOutput>[0],\n ),\n confirm: askHostConfirmation,\n waitForResume,\n onPendingChange: (pending) => {\n hostToolsPending.value = pending\n },\n onActivity: showPageActivity,\n mode: () => confirmationMode.value,\n onSkip: reportSkippedCard,\n })\n\n /**\n * The page calls of a voice call waiting for their result, by the id\n * the widget gave them: the provider awaits each one's promise, and\n * the runner settles it (spec `voice-page-control.md`).\n */\n const voicePageCalls = new Map<string, (result: string) => void>()\n let voicePageCallCount = 0\n\n /**\n * Answers the provider with the result as the backend reads a page\n * tool's: serialized whole, so a failure stays a failure (the\n * provider passes on the text, not its own error flag).\n */\n const settleVoicePageCall = (\n toolCallId: string,\n result: HostToolResult,\n ) => {\n const settle = voicePageCalls.get(toolCallId)\n voicePageCalls.delete(toolCallId)\n settle?.(JSON.stringify(result))\n }\n\n /**\n * The card of a call's page action, once the card is free: one\n * question at a time, and the chat's is never answered no on the\n * user's behalf. A call stopped while it waited asks nothing.\n */\n const askVoicePageConfirmation = async (\n call: HostToolCall,\n confirmation?: HostToolConfirmation,\n ) => {\n while (hostConfirmation.value) {\n await new Promise<void>((resolve) => {\n const stop = watch(hostConfirmation, (current) => {\n if (!current) {\n stop()\n resolve()\n }\n })\n })\n }\n if (!voicePageCalls.has(call.toolCallId)) {\n return false\n }\n return askHostConfirmation(call, confirmation)\n }\n\n /**\n * Runs the page calls of a voice call: the same tools, confirmation\n * card and presence as a typed turn's, with the provider in place of\n * the resume. Its own queue, so a call's actions never wait behind\n * the chat's, nor are cancelled by a message typed meanwhile.\n */\n const voicePageToolRunner = createHostToolRunner({\n registry: () => activePageTools.value,\n capability: () => agentHostTools.value,\n addToolOutput: (output) =>\n settleVoicePageCall(\n output.toolCallId,\n 'output' in output\n ? output.output\n : {\n content: [\n { type: 'text', text: output.errorText },\n ],\n isError: true,\n },\n ),\n confirm: askVoicePageConfirmation,\n // No resume to wait for: the provider sends the result on the\n // call's socket. A beat for that send before an action that may\n // unload the page.\n waitForResume: () =>\n new Promise((resolve) =>\n setTimeout(() => resolve(true), VOICE_RESULT_SEND_MS),\n ),\n onPendingChange: (pending) => {\n voicePageCallsPending.value = pending\n },\n onActivity: showPageActivity,\n // The call runs with the confirmations it opened with, as its\n // spoken turns do on the server. Nothing kept for the steps: the\n // call's ids are the widget's own, and the steps the transcript\n // brings back carry the model's\n mode: () => voiceCallConfirmationMode,\n })\n /** The confirmations of the call open now, taken when it opened. */\n let voiceCallConfirmationMode: ConfirmationMode = 'manual'\n\n /**\n * The page tools of a call opened from this widget: their declaration\n * for the session request, and the handlers the voice provider calls\n * with each call's arguments. Nothing when the page tools are off.\n * Called once per call, when it opens: it also takes the call's\n * confirmations.\n */\n function voicePageTools():\n | {\n declaration: NonNullable<ReturnType<typeof declarePageTools>>\n clientTools: Record<\n string,\n (parameters: unknown) => Promise<string>\n >\n }\n | undefined {\n voiceCallConfirmationMode = confirmationMode.value\n const declaration = declarePageTools({ forms: false })\n if (!declaration) {\n return undefined\n }\n return {\n declaration,\n clientTools: Object.fromEntries(\n activePageTools.value.map((tool) => [\n tool.name,\n (parameters: unknown) =>\n new Promise<string>((resolve) => {\n voicePageCallCount += 1\n // The provider hands the handler no call id\n const toolCallId = `page-call-${voicePageCallCount}`\n voicePageCalls.set(toolCallId, resolve)\n voicePageToolRunner.enqueue({\n toolCallId,\n toolName: tool.name,\n input: parameters ?? {},\n messageId: lastChatMessage()?.id ?? '',\n readOnly:\n tool.annotations?.readOnlyHint === true,\n provider: 'page',\n })\n }),\n ]),\n ),\n }\n }\n\n /**\n * Ends the page calls of a voice call: on the Stop of the control\n * bar, and when the call ends. The provider still waits on each one,\n * so each gets an answer: a failure the model reads as such.\n */\n function cancelVoicePageCalls() {\n voicePageToolRunner.cancelAll()\n // Its card goes too; the chat's own stays.\n if (\n hostConfirmation.value &&\n voicePageCalls.has(hostConfirmation.value.toolCallId)\n ) {\n hostConfirmation.value.answer(false)\n }\n for (const toolCallId of [...voicePageCalls.keys()]) {\n settleVoicePageCall(toolCallId, {\n content: [{ type: 'text', text: 'Stopped by the user.' }],\n isError: true,\n })\n }\n }\n\n /**\n * The page control bar's stop (spec `page-tools.md`). Unlike\n * `stopGeneration` it keeps the conversation as it is: the actions\n * already done on the page stay done, and the answer that did them\n * must stay in view.\n */\n async function stopHostActions() {\n cancelHostCalls()\n cancelVoicePageCalls()\n pageAction.value = undefined\n pageControlActive.value = false\n lastSubmittedInput.value = ''\n await chat.value.stop()\n }\n\n /**\n * Cancels the host calls queued and running, and the consent they wait\n * for: the card goes, and its call ends without an output. The card\n * of a call's page action stays: the call goes on (see\n * `cancelVoicePageCalls`).\n */\n function cancelHostCalls() {\n hostToolRunner.cancelAll()\n if (\n hostConfirmation.value &&\n !voicePageCalls.has(hostConfirmation.value.toolCallId)\n ) {\n hostConfirmation.value.answer(false)\n }\n }\n\n /** The user's switch from the widget menu: off, it stops what runs first. */\n async function setPageAccessOff(off: boolean) {\n pageAccessOff.value = off\n if (off) {\n await stopHostActions()\n }\n }\n\n // A call of the conversation left behind has nowhere to land. Sync,\n // and registered before the watcher that detaches the chat: a result\n // landing in between would resume the turn on the chat being left.\n watch(localChatId, () => cancelHostCalls(), { flush: 'sync' })\n\n /** A resume is running: its errors are not the user's, see `followTurn`. */\n let isResumingTurn = false\n /** The turn `followTurn` is following, until it ends or is stopped. */\n let followedTurn: { chatId: string } | undefined\n /** The chat of `followedTurn`, for what the screen shows of it. */\n const followedChatId = ref<string | undefined>()\n /**\n * The name of the turn on screen, from its stream: its Stop sends it,\n * since a turn sent from another page may have replaced it as the\n * chat's running one.\n */\n let turnStreamId: string | undefined\n\n // === Turns left running (spec resumable-chat-streams, F2) ===\n /** The chats whose turn runs, as the server last said. */\n const serverRunningChatIds = ref<string[]>([])\n /** Chats left while their turn ran: their end shows a notice. */\n const backgroundTurns = ref<string[]>([])\n /** Turns that ended in the background, one notice each until opened or closed. */\n const answeredInBackground = ref<string[]>([])\n /**\n * The question of each chat left running: the name of its row while\n * the list does not have it yet (the list leaves out a chat until its\n * first turn is written) and of its notice while it has no title.\n */\n const backgroundQuestions = ref<Record<string, string>>({})\n /** When each chat was left, for the grace of a turn not started yet. */\n const backgroundLeftAt = new Map<string, number>()\n /** Chats whose turn the server has reported running at least once. */\n const seenRunning = new Set<string>()\n\n function noteBackgroundTurn(\n chatId: string,\n question: string,\n started: boolean,\n ) {\n if (!backgroundTurns.value.includes(chatId)) {\n backgroundTurns.value = [...backgroundTurns.value, chatId]\n }\n backgroundLeftAt.set(chatId, Date.now())\n // A turn streaming has its record already; one still `submitted`\n // may not, and is over only once the server has reported it.\n if (started) {\n seenRunning.add(chatId)\n } else {\n seenRunning.delete(chatId)\n }\n if (question) {\n backgroundQuestions.value = {\n ...backgroundQuestions.value,\n [chatId]: question,\n }\n }\n if (!runningTurnsTimer) {\n scheduleRunningTurns()\n }\n }\n\n function forgetBackgroundQuestion(chatId: string) {\n backgroundQuestions.value = Object.fromEntries(\n Object.entries(backgroundQuestions.value).filter(\n ([id]) => id !== chatId,\n ),\n )\n }\n\n /** Back on the chat: its turn, if still running, is followed here. */\n function forgetBackgroundTurn(chatId: string) {\n backgroundLeftAt.delete(chatId)\n backgroundTurns.value = backgroundTurns.value.filter(\n (id) => id !== chatId,\n )\n answeredInBackground.value = answeredInBackground.value.filter(\n (id) => id !== chatId,\n )\n forgetBackgroundQuestion(chatId)\n }\n\n // `useChat` recreates the chat, empty, whenever what this getter reads\n // synchronously changes: the chatId, the endpoint, the agent type.\n // The recreation runs on the next tick, not at the change: code that\n // rotates the chatId waits for it before acting on the new chat.\n const chatHelpers = useChat<UIChatMessage>(() => ({\n id: localChatId.value,\n transport: new DefaultChatTransport({\n api: apiClient.value.getChatEndpoint(\n agentIdRef.value,\n isReasoningAgent.value ? 'reasoning' : 'chat',\n ),\n // Read when the chat resumes, not here: see `followTurn`.\n prepareReconnectToStreamRequest: ({ id }) => ({\n api: apiClient.value.getChatStreamEndpoint(\n agentIdRef.value,\n id,\n ),\n }),\n prepareSendMessagesRequest: ({ messages: msgs, id }) => ({\n body: {\n id,\n messages: [msgs[msgs.length - 1]],\n model: model.value,\n prompt: agentModel.value?.prompt,\n maxOutputTokens: agentModel.value?.maxOutputTokens,\n temperature: agentModel.value?.temperature,\n presencePenalty: agentModel.value?.presencePenalty,\n frequencyPenalty: 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: agentInterface.value?.smoothStream,\n deviceContext: buildDeviceContext(),\n externalContext: externalContext.value,\n disabledTools: agentTools.value?.disabled,\n fallbackModels: fallbackModels.value,\n gatewayOptions: gatewayOptions.value,\n hostTools: declaredHostTools(\n hostToolRegistry.value,\n agentHostTools.value,\n ),\n pageTools: declarePageTools({ forms: true }),\n ...(newChatProjectOf(id) && {\n projectId: newChatProjectOf(id),\n }),\n ...(confirmationMode.value === 'automatic' && {\n confirmations: 'automatic' as const,\n }),\n },\n }),\n credentials: 'include',\n // Resolved per-request: reading `headers.value` here\n // would make `useChat` recreate the chat (wiping its\n // 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 // Never in a colleague's chat, which the reader only reads.\n sendAutomaticallyWhen: (options) =>\n !isReadOnlyChat.value &&\n (lastAssistantMessageIsCompleteWithAnsweredClientTools(\n options,\n ) ||\n lastAssistantMessageIsCompleteWithApprovalResponses(\n options,\n )),\n onError: (error) => {\n // A resume that fails is not the user's error: the\n // reload that follows it shows what the chat stores.\n if (isResumingTurn) {\n logger.warn(error)\n return\n }\n handleChatError(error)\n },\n // A host call goes to the queue and returns at once: the\n // SDK awaits this callback before reading the rest of the\n // stream (see createHostToolRunner).\n onToolCall: ({ toolCall }) => {\n // A resume replays the turn into a message of its own,\n // which answering would send back over the stored one:\n // the stored answer runs its open page reads afterwards\n // (see `continueAfterLoad`). A colleague's turn followed\n // live runs nothing in the reader's page.\n if (\n !isHostToolCall(toolCall) ||\n isResumingTurn ||\n isReadOnlyChat.value\n ) {\n return\n }\n const call = toolCall as unknown as {\n toolCallId: string\n toolName: string\n input: unknown\n toolMetadata?: {\n readOnly?: unknown\n provider?: unknown\n }\n }\n hostToolRunner.enqueue({\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n input: call.input,\n messageId: lastChatMessage()?.id ?? '',\n readOnly: call.toolMetadata?.readOnly === true,\n provider:\n call.toolMetadata?.provider === 'page' ? 'page' : 'app',\n })\n },\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-turnStream') {\n turnStreamId = (part.data as { streamId: string }).streamId\n return\n }\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 * The chat as the store, its components and its tests read it\n * (`chat.value.messages`, `chat.value.status`, `store.chat.messages =`),\n * the way they read the deprecated `Chat` instance it replaces:\n * `reactive` unwraps the helpers' refs, and an assignment to `messages`\n * reaches the chat through them.\n */\n const chat = computed(() => reactive(chatHelpers))\n /** What the `Chat` instance gave as `lastMessage`, which `useChat` does not expose. */\n const lastChatMessage = (): UIChatMessage | undefined =>\n chat.value.messages[chat.value.messages.length - 1]\n\n // Leaving a chat (another conversation, a new chat, a rotated\n // session) detaches the browser from its turn, which goes on\n // server-side and is resumed when the chat is opened again: a stream\n // left reading would keep calling `onError` and `onData` on the chat\n // on screen. Sync, so it reaches the chat being left before `useChat`\n // replaces it on the next tick. A turn left running is noted, for the\n // notice its end shows wherever the user is then.\n watch(\n localChatId,\n (chatId, leftChatId) => {\n if (\n leftChatId &&\n !isReasoningAgent.value &&\n (isTurnInFlight() || followedTurn?.chatId === leftChatId)\n ) {\n const questions = chat.value.messages.filter(\n (message) => message.role === 'user',\n )\n const question = questions[questions.length - 1]\n noteBackgroundTurn(\n leftChatId,\n question ? (getTextPart(question) ?? '') : '',\n chat.value.status === 'streaming' ||\n followedTurn?.chatId === leftChatId,\n )\n }\n forgetBackgroundTurn(chatId)\n turnStreamId = undefined\n // The chat opened is not working: the quiet moment that keeps\n // the signal from blinking belongs to the chat left.\n clearTimeout(workingTimer)\n isWorking.value = false\n void chat.value.stop()\n },\n { flush: 'sync' },\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 // From a chatId change to the next tick the chat is still the\n // previous one (`useChat` recreates it then): show the new chat as\n // the empty one it is about to be, not the old conversation.\n const chatMessages =\n chat.value.id === localChatId.value ? chat.value.messages : []\n\n if (isReasoningAgent.value) {\n return resolveInFlight(chatMessages)\n }\n if (\n !hideWelcomeMessage.value &&\n chatMessages[0]?.role !== 'assistant'\n ) {\n return [welcomeMessage.value, ...resolveInFlight(chatMessages)]\n }\n return resolveInFlight(chatMessages)\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 // === Shared projects (docs/specs/chat-projects.md) ===\n /** The host shows the projects: the list by date leaves their chats out. */\n const projectsEnabled = ref(false)\n /**\n * Whose chat it is and in which project, tied to the chat's id: what\n * is known of one chat never applies to the next (a Back to a chat\n * never written, a colleague's opened from the list). A chat without\n * an author is one never written, which the user is starting.\n */\n const chatOwnership = ref<{\n chatId: string\n authorId?: string\n projectId?: string\n }>()\n /** What the list or the server says of a chat: its author, its project. */\n function describeChat(\n chatId: string,\n details: { authorId?: string; projectId?: string | null },\n ) {\n chatOwnership.value = {\n chatId,\n authorId: details.authorId,\n projectId: details.projectId ?? undefined,\n }\n }\n const ownershipOf = (chatId: string) =>\n chatOwnership.value?.chatId === chatId\n ? chatOwnership.value\n : undefined\n /** The author of the chat on screen, once listed or read. */\n const chatAuthorId = computed(\n () => ownershipOf(localChatId.value)?.authorId,\n )\n /** The project of the chat on screen, or the one a new chat opens in. */\n const chatProjectId = computed(\n () => ownershipOf(localChatId.value)?.projectId,\n )\n /** A colleague's conversation in a shared project: read, never written. */\n const isReadOnlyChat = computed(\n () =>\n chatAuthorId.value !== undefined &&\n userId.value !== undefined &&\n chatAuthorId.value !== userId.value,\n )\n /** The project a chat never written opens in, told with its messages. */\n const newChatProjectOf = (chatId: string) => {\n const ownership = ownershipOf(chatId)\n return ownership && ownership.authorId === undefined\n ? ownership.projectId\n : undefined\n }\n /** What the list asks the server for: outside the projects, when shown. */\n const conversationListFilter = () =>\n projectsEnabled.value\n ? { projectId: CHAT_LIST_WITHOUT_PROJECT }\n : undefined\n\n // === Conversations ===\n const conversations = ref<ChatRecord[]>([])\n const isLoadingConversations = ref(false)\n // The list loads a page at a time: the last page loaded, whether a\n // full one says more may follow, the next one in flight, and whose\n // list the loaded pages are (a sign-in changes the user)\n const conversationsPage = ref(1)\n const hasMoreConversations = ref(false)\n const isLoadingMoreConversations = ref(false)\n let conversationsOwner: string | undefined\n const chatFiles = ref<ChatbotFile[]>([])\n const isLoadingChatFiles = ref(false)\n\n // === Navigation ===\n const activeView = ref<ChatbotView>('chat')\n // Bumped to send the focus to the message field from outside the\n // chat view (the host's ⇧Esc): the chat view watches it\n const inputFocusRequest = ref(0)\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 /** Whether a Stop puts the rolled back text in the field: not for a selection bar's action. */\n const lastSubmittedToInput = ref(true)\n /** What the user pointed at with the message a Stop may roll back: it goes back with the text. */\n const lastSubmittedPointer = shallowRef<PagePointer | undefined>()\n const messageCountBeforeSubmit = ref(0)\n\n // === Queue: what the user writes while a turn runs (spec\n // resumable-chat-streams, F2) ===\n /** Per chat, in the tab: a reload keeps what was queued. */\n const queues = useSafeSessionStorage<Record<string, string[]>>(\n computed(() => `${agentIdRef.value}-queue`),\n {},\n )\n /** Queued in the chat on screen: sent together when its turn ends. */\n const queuedMessages = computed(\n () => queues.value[localChatId.value] ?? [],\n )\n /** A reasoning agent opens a new chat at every message: nothing waits. */\n const canQueue = computed(() => !isReasoningAgent.value)\n function setQueue(chatId: string, queued: string[]) {\n const others = Object.fromEntries(\n Object.entries(queues.value).filter(([id]) => id !== chatId),\n )\n queues.value =\n queued.length > 0 ? { ...others, [chatId]: queued } : others\n }\n /** Takes the chat's queue out, as the one message it is sent as. */\n function takeQueue(chatId: string): string {\n const text = (queues.value[chatId] ?? []).join(QUEUE_SEPARATOR)\n setQueue(chatId, [])\n return text\n }\n /** Puts text back in the input, after what the user is writing. */\n function restoreInput(text: string) {\n if (text) {\n input.value = input.value\n ? `${input.value}${QUEUE_SEPARATOR}${text}`\n : text\n }\n }\n function removeQueuedMessage(index: number) {\n setQueue(\n localChatId.value,\n queuedMessages.value.filter((_, i) => i !== index),\n )\n }\n /** Back to the input, to be changed and sent or queued again. */\n function editQueuedMessage(index: number) {\n const text = queuedMessages.value[index]\n removeQueuedMessage(index)\n restoreInput(text ?? '')\n }\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 const listed = await apiClient.value.getConversations(\n id,\n userId.value,\n conversationListFilter(),\n )\n // A chat left during its first turn is not listed until the\n // turn is written: its row stands in meanwhile, named by its\n // question, so the list can mark it.\n const listedIds = new Set(listed.map((c) => c.id))\n const leftRunning = backgroundTurns.value\n .filter(\n (chatId) =>\n !listedIds.has(chatId) &&\n backgroundQuestions.value[chatId],\n )\n .map(\n (chatId) =>\n ({\n id: chatId,\n agentId: id,\n title: backgroundQuestions.value[chatId],\n summary: null,\n messages: [],\n lastMessageAt: new Date(),\n }) as unknown as ChatRecord,\n )\n // The pages loaded beyond the first stay, for the same user\n // and agent: a reload after a turn would otherwise take the\n // list back to the newest page\n const owner = `${id}:${userId.value ?? ''}`\n if (owner !== conversationsOwner) {\n conversationsPage.value = 1\n }\n const leftRunningIds = new Set(leftRunning.map((c) => c.id))\n const older =\n conversationsPage.value > 1\n ? conversations.value.filter(\n (c) =>\n !listedIds.has(c.id) &&\n !leftRunningIds.has(c.id),\n )\n : []\n conversations.value = [...leftRunning, ...listed, ...older]\n conversationsOwner = owner\n if (conversationsPage.value === 1) {\n hasMoreConversations.value =\n listed.length >= CONVERSATIONS_PAGE_SIZE\n }\n } catch {\n conversations.value = []\n conversationsPage.value = 1\n conversationsOwner = undefined\n hasMoreConversations.value = false\n return\n } finally {\n isLoadingConversations.value = false\n }\n // The turns left running first: the server reads at most so many.\n void refreshRunningTurns([\n ...new Set([\n ...watchedTurns(),\n ...conversations.value.map(\n (conversation) => conversation.id,\n ),\n ]),\n ])\n }\n\n /** The next page of the list, appended (the end of the sidebar) */\n async function loadMoreConversations() {\n if (\n !hasMoreConversations.value ||\n isLoadingMoreConversations.value ||\n isReasoningAgent.value\n ) {\n return\n }\n isLoadingMoreConversations.value = true\n const owner = conversationsOwner\n try {\n const page = conversationsPage.value + 1\n const listed = await apiClient.value.getConversations(\n agentIdRef.value,\n userId.value,\n { ...conversationListFilter(), page },\n )\n // Another user's list arrived meanwhile: this page is not its\n if (owner !== conversationsOwner) {\n return\n }\n // A chat started meanwhile moved every row one down: the\n // first of this page can be the last of the previous one\n const known = new Set(conversations.value.map((c) => c.id))\n conversations.value = [\n ...conversations.value,\n ...listed.filter((c) => !known.has(c.id)),\n ]\n conversationsPage.value = page\n hasMoreConversations.value =\n listed.length >= CONVERSATIONS_PAGE_SIZE\n } catch {\n // The next scroll to the end asks again\n } finally {\n isLoadingMoreConversations.value = false\n }\n }\n\n /**\n * The user's chats whose title matches, from the server, so a chat\n * beyond the loaded pages is found too. Not kept in the list.\n */\n async function searchConversations(\n search: string,\n ): Promise<ChatRecord[]> {\n if (isReasoningAgent.value) {\n return []\n }\n return apiClient.value.getConversations(\n agentIdRef.value,\n userId.value,\n { search },\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 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 if (chatId !== localChatId.value) {\n return\n }\n // Whose it is and where: a colleague's is read only\n if (data) {\n describeChat(chatId, {\n authorId: data.userId,\n projectId: data.projectId,\n })\n }\n // The chat may have advanced while the request was in flight\n // (the user submitted a message): never clobber local\n // messages with a stale response. A wiped list mid-stream\n // also suppresses the synthetic welcome message, because the\n // streamed reply gets re-pushed at index 0.\n if (\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 void continueAfterLoad(\n id,\n chatId,\n data.turnInProgress === true,\n )\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 * What a chat just opened still has running: its turn, followed to\n * the end, then the page reads its answer left open, which run on\n * the stored answer rather than on the replay, and last what the user\n * queued in the chat.\n */\n async function continueAfterLoad(\n id: string,\n chatId: string,\n turnInProgress: boolean,\n ) {\n if (turnInProgress) {\n await followTurn(chatId)\n // Left meanwhile, or already sent on: the messages on screen\n // are no longer this chat's answer.\n if (chatId !== localChatId.value || isTurnInFlight()) {\n return\n }\n }\n await resumeAfterPageNavigation(id, chatId)\n if (chatId === localChatId.value) {\n await flushQueue()\n }\n }\n\n /**\n * Follows the turn still running in a chat just opened (spec\n * resumable-chat-streams): its answer streams in from the start, the\n * status is `streaming` meanwhile (so nothing else is sent), and when\n * the stream ends the chat is read again until the turn is written.\n * The stream also ends with nothing in it: the turn finished between\n * the read and the resume, or the replica running it is gone, which\n * the server stops reporting within a minute and a half.\n */\n async function followTurn(chatId: string) {\n const turn = { chatId }\n followedTurn = turn\n followedChatId.value = chatId\n const isFollowing = () =>\n followedTurn === turn && chatId === localChatId.value\n const deadline = Date.now() + FOLLOW_TURN_TIMEOUT_MS\n try {\n while (\n isFollowing() &&\n !isTurnInFlight() &&\n Date.now() < deadline\n ) {\n isResumingTurn = true\n try {\n await chat.value.resumeStream()\n } finally {\n isResumingTurn = false\n }\n if (!isFollowing()) {\n return\n }\n chat.value.clearError()\n const data = await apiClient.value\n .getChat(agentIdRef.value, chatId)\n .catch(() => null)\n if (!data || !isFollowing() || isTurnInFlight()) {\n return\n }\n if (!data.turnInProgress) {\n chat.value.messages = data.messages as UIChatMessage[]\n return\n }\n await new Promise((resolve) =>\n setTimeout(resolve, FOLLOW_TURN_RETRY_MS),\n )\n }\n } finally {\n if (followedTurn === turn) {\n followedTurn = undefined\n followedChatId.value = undefined\n }\n }\n }\n\n /**\n * After a navigation the agent started (spec `page-tools.md`), the\n * answer that clicked goes on on the backend and usually asks to read\n * the new page, but its stream stayed with the old one: that call\n * waits here. Runs the pending READ-ONLY page calls of the last answer\n * on this page, never a write, and only within a minute of the click.\n * The backend may still be finishing that answer, so the stored chat\n * is read again for a while.\n */\n async function resumeAfterPageNavigation(id: string, chatId: string) {\n let clickedAt: number\n try {\n clickedAt = Number(sessionStorage.getItem(PAGE_NAVIGATION_KEY))\n sessionStorage.removeItem(PAGE_NAVIGATION_KEY)\n } catch {\n return\n }\n // Switched off by the user: the answer waits for the next message.\n if (\n !clickedAt ||\n Date.now() - clickedAt > 60_000 ||\n pageAccessOff.value\n ) {\n return\n }\n for (let attempt = 0; attempt < 12; attempt++) {\n const last = chat.value.messages[chat.value.messages.length - 1]\n if (last?.role === 'assistant') {\n const open = last.parts.filter(\n (part) =>\n isHostToolPart(part) &&\n (part as { state?: string }).state ===\n 'input-available',\n ) as unknown as Array<{\n toolCallId: string\n toolName: string\n input: unknown\n toolMetadata?: { provider?: string; readOnly?: boolean }\n }>\n const reads = open.filter(\n (part) =>\n part.toolMetadata?.provider === 'page' &&\n part.toolMetadata.readOnly === true,\n )\n if (open.length > 0) {\n // A write left open is never replayed: the next\n // message closes it as an unknown outcome. Checked\n // again here: the user may have switched page access\n // off while the history was being read.\n if (\n reads.length === open.length &&\n !pageAccessOff.value\n ) {\n for (const part of reads) {\n hostToolRunner.enqueue({\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n messageId: last.id,\n readOnly: true,\n provider: 'page',\n })\n }\n }\n return\n }\n if (last.parts[last.parts.length - 1]?.type === 'text') {\n return\n }\n }\n await new Promise((resolve) => setTimeout(resolve, 1500))\n if (\n chatId !== localChatId.value ||\n chat.value.status !== 'ready'\n ) {\n return\n }\n try {\n const data = await apiClient.value.getChat(id, chatId)\n if (data && chatId === localChatId.value) {\n chat.value.messages = data.messages as UIChatMessage[]\n }\n } catch {\n return\n }\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 /**\n * The answer on screen is not over: its request runs, it is followed\n * from another page, or the embedding page runs its calls (the chat\n * reads `ready` then, and the input shows the work and its stop).\n */\n const isTurnBusy = (): boolean =>\n isTurnInFlight() ||\n followedTurn?.chatId === localChatId.value ||\n hostToolsPending.value > 0\n\n /**\n * The answer waits on the user: an approval, the consent to a host\n * call, a form or another tool only the user answers.\n */\n const awaitsUser = (): boolean => {\n const last = lastChatMessage()\n return (\n hostConfirmation.value !== undefined ||\n awaitsApproval(last) ||\n awaitsToolAnswer(last)\n )\n }\n\n /** The chats whose queue is waiting for its turn to be written. */\n const flushingChats = new Set<string>()\n /**\n * Sends what the user queued in the chat on screen once its turn is\n * over and written: the server builds the history from the stored\n * chat and the request carries only the new message, so a message\n * sent before the write would reach the agent without the answer it\n * follows. The write follows the end of the stream: waited for a few\n * seconds at most. An answer that waits on the user (a chat opened\n * again on its form) gets the queue back in the input instead.\n */\n async function flushQueue() {\n const chatId = localChatId.value\n if (\n flushingChats.has(chatId) ||\n queuedMessages.value.length === 0 ||\n isTurnBusy() ||\n chatError.value\n ) {\n return\n }\n if (awaitsUser()) {\n restoreInput(takeQueue(chatId))\n return\n }\n flushingChats.add(chatId)\n try {\n const deadline = Date.now() + QUEUE_WRITE_WAIT_MS\n while (Date.now() < deadline) {\n const running = await Promise.race([\n apiClient.value\n .getRunningTurns(agentIdRef.value, [chatId])\n .catch((): string[] => []),\n new Promise<string[]>((resolve) =>\n setTimeout(\n () => resolve([chatId]),\n QUEUE_WRITE_ASK_MS,\n ),\n ),\n ])\n if (!running.includes(chatId)) {\n break\n }\n await new Promise((resolve) =>\n setTimeout(resolve, QUEUE_WRITE_RETRY_MS),\n )\n }\n // Left meanwhile, or the turn went on by itself (a host\n // result, an answered tool): the queue waits for its end.\n if (chatId !== localChatId.value || isTurnBusy()) {\n return\n }\n const text = takeQueue(chatId)\n if (text) {\n submitTurn(text)\n }\n } finally {\n flushingChats.delete(chatId)\n }\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 // An attachment still uploading or failed would leave the message\n // without a word: the composer keeps the send off until it is\n // uploaded, retried or taken back, and so does this\n if (\n isReadOnlyChat.value ||\n pendingAttachments.value.some((a) => a.state !== 'done')\n ) {\n return\n }\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 const pointer = pagePointerAvailable.value\n ? pagePointer.value\n : undefined\n\n // While a turn runs the message waits for it, and goes with the\n // others queued when the turn ends. Text only: attaching and\n // pointing stay off during a turn.\n if (!isReasoningAgent.value && isTurnBusy()) {\n if (text && fileParts.length === 0 && !pointer) {\n setQueue(localChatId.value, [...queuedMessages.value, text])\n input.value = ''\n }\n return\n }\n\n if (isReasoningAgent.value && messages.value.length > 0) {\n await startNewChat()\n }\n\n submitTurn(text, fileParts, pointer && { pagePointer: pointer })\n input.value = ''\n pagePointer.value = undefined\n clearPendingAttachments()\n }\n\n /**\n * Sends an action of the selection bar (spec `selection-actions.md`,\n * \"Cosa è comune\"): its instruction, or what the user wrote in its\n * field, with the selection as metadata. A turn like a typed message:\n * a Stop takes it off the chat, since the server keeps no stopped\n * turn, but puts nothing in the field, which the bar does not use.\n * Refused while a turn runs, where the bar does not show.\n */\n function sendSelection(\n text: string,\n pointer: SelectionPointer,\n ): boolean {\n const trimmed = text.trim()\n if (\n !trimmed ||\n isConversationBlocked.value ||\n isReadOnlyChat.value ||\n isTurnBusy() ||\n chat.value.status !== 'ready'\n ) {\n return false\n }\n submitTurn(trimmed, [], pointer, { toInput: false })\n return true\n }\n\n /**\n * Sends the user's message, ready to be rolled back by a Stop. The\n * rolled back text goes back in the field unless `toInput` is false,\n * and with it a page pointer as the field's label, never a file\n * pointer.\n */\n function submitTurn(\n text: string,\n fileParts: FileUIPart[] = [],\n pointer?: SelectionPointer,\n { toInput = true }: { toInput?: boolean } = {},\n ) {\n // Every way of writing ends here: a colleague's chat takes none\n // (a suggested reply, a form, a restore asked from a card)\n if (isReadOnlyChat.value) {\n return\n }\n // A host call still pending belongs to the turn the user is\n // leaving: its result must not land on the next one.\n cancelHostCalls()\n\n // Snapshot state before sending so we can rollback on stop\n lastSubmittedInput.value = text\n lastSubmittedToInput.value = toInput\n lastSubmittedPointer.value =\n toInput && pointer && 'pagePointer' in pointer\n ? pointer.pagePointer\n : undefined\n messageCountBeforeSubmit.value = chat.value.messages.length\n\n // The chat's sendMessage can't resolve the correct overload\n // when using a custom message generic: the cast is intentional.\n const sendMessage = chat.value.sendMessage as unknown as (msg: {\n text: string\n files?: FileUIPart[]\n metadata?: UIChatMessageMetadata\n }) => void\n sendMessage({\n text,\n files: fileParts.length > 0 ? fileParts : undefined,\n ...(pointer && { metadata: pointer }),\n })\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 || isReadOnlyChat.value) {\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 cancelHostCalls()\n send({ text: trimmed })\n }\n\n /**\n * The user's Stop. The turn is stopped server-side too, where it would\n * otherwise go on and be written (spec resumable-chat-streams), so the\n * rollback below matches what a reload shows. A turn that had already\n * ended is stored whole: the chat is read again instead.\n */\n async function stopGeneration() {\n // An answer that already called the host stays: the app or the\n // page may have acted on it, and the rollback would hide what\n // they did (spec `page-tools.md`, Ferma).\n const answerCalledHost = chat.value.messages\n .slice(messageCountBeforeSubmit.value)\n .some((message) => message.parts.some(isHostToolPart))\n // Read before the stop: the stop turns the chat `ready`, and the\n // watcher that clears the rollback state on `ready` can run before\n // the stop resolves, which put the messages back with an empty\n // input.\n const submittedText = lastSubmittedInput.value\n const submittedToInput = lastSubmittedToInput.value\n const submittedPointer = lastSubmittedPointer.value\n const shouldRollback = submittedText.length > 0 && !answerCalledHost\n const chatId = localChatId.value\n const countBeforeSubmit = messageCountBeforeSubmit.value\n // A turn followed from another page has nothing to roll back\n // here: once stopped, the chat as stored has no trace of it.\n const wasFollowing = followedTurn?.chatId === chatId\n // This page's own turn, which a turn sent from another page may\n // have replaced as the chat's running one.\n const streamId = turnStreamId\n // What the user queued is not sent after a Stop: it goes back to\n // the input, after the question a rollback puts there and before\n // what the user is still writing. Taken before the stop, which\n // turns the chat `ready` and would send it.\n const queuedText = takeQueue(chatId)\n const restoreInputAfterStop = (question = '') => {\n input.value = [question, queuedText, input.value]\n .filter(Boolean)\n .join(QUEUE_SEPARATOR)\n }\n // Moved on while the server was asked (another chat on screen, or\n // the next message already sent): what is on screen now is not\n // this turn's to roll back, and the queue waits in its chat.\n const movedOn = () => {\n if (\n chatId === localChatId.value &&\n !isTurnInFlight() &&\n messageCountBeforeSubmit.value === countBeforeSubmit\n ) {\n return false\n }\n if (queuedText) {\n setQueue(chatId, [\n queuedText,\n ...(queues.value[chatId] ?? []),\n ])\n }\n return true\n }\n followedTurn = undefined\n followedChatId.value = undefined\n // Before the stop: a host result landing after it must not resume\n // the turn the user just stopped.\n cancelHostCalls()\n await chat.value.stop()\n // Not stopped server-side: a reasoning chat, never stored, and an\n // answer that called the host from this page, which stays and\n // must stay on a reload too (a followed turn runs no host call).\n // A Stop the server did not get is rolled back as before.\n const stopped =\n isReasoningAgent.value ||\n (answerCalledHost && !wasFollowing) ||\n (await apiClient.value\n .stopChatTurn(agentIdRef.value, chatId, streamId)\n .catch(() => true))\n if (movedOn()) {\n return\n }\n if (wasFollowing || !stopped) {\n await refreshMessages()\n // The same, while the chat was read again.\n if (movedOn()) {\n return\n }\n if (\n wasFollowing ||\n chat.value.messages.length > messageCountBeforeSubmit.value\n ) {\n lastSubmittedInput.value = ''\n restoreInputAfterStop()\n return\n }\n // Nothing stored either: the turn never reached the server.\n }\n if (shouldRollback) {\n restoreInputAfterStop(submittedToInput ? submittedText : '')\n // The chip comes back with its question, unless the user\n // pointed at something else meanwhile\n pagePointer.value ??= submittedPointer\n chat.value.messages = chat.value.messages.slice(\n 0,\n messageCountBeforeSubmit.value,\n )\n lastSubmittedInput.value = ''\n return\n }\n restoreInputAfterStop()\n }\n\n // A history replaced under a waiting question (a reload from the\n // server that no longer carries the call): nobody can answer it, and\n // the queue would wait on it for ever. A call's page action is never\n // in the history under the widget's id: its question waits for the\n // user, whatever the reloads of the call bring.\n watch(\n () => chat.value.messages,\n (current) => {\n const waiting = hostConfirmation.value?.toolCallId\n if (\n waiting &&\n !voicePageCalls.has(waiting) &&\n !current.some((message) =>\n message.parts.some(\n (part) =>\n (part as { toolCallId?: string }).toolCallId ===\n waiting,\n ),\n )\n ) {\n cancelHostCalls()\n }\n },\n )\n\n // A request starting: what a deferred page click waits for. Its turn\n // names itself in its stream: until then a Stop names no turn, never\n // the one before it.\n watch(\n () => chat.value.status,\n (status) => {\n if (status === 'submitted') {\n requestCount.value++\n turnStreamId = undefined\n }\n },\n )\n\n // The page control bar stays up for the whole response: between two\n // actions the chat is ready for a moment, before the resume starts.\n // A call's actions keep it up too: the chat does not move during them.\n let pageControlTimer: ReturnType<typeof setTimeout> | undefined\n watch(\n () =>\n [\n chat.value.status,\n hostToolsPending.value,\n voicePageCallsPending.value,\n ] as const,\n ([status, pending, voicePending]) => {\n clearTimeout(pageControlTimer)\n if (status === 'ready' && pending === 0 && voicePending === 0) {\n pageControlTimer = setTimeout(() => {\n pageControlActive.value = false\n }, 1500)\n }\n },\n )\n\n // === Working state (spec `widget-copilot.md`, D4) ===\n // On at once, off only after a quiet moment: between the result of a\n // call and the resume it starts the chat is ready for an instant, and\n // the signal would blink at every step. A confirmation card turns it\n // off, because the turn waits on the user then: the card of a host\n // call, or the approval of a tool the backend runs.\n const isWorking = ref(false)\n let workingTimer: ReturnType<typeof setTimeout> | undefined\n watch(\n () =>\n !hostConfirmation.value &&\n !awaitsApproval(lastChatMessage()) &&\n (isTurnInFlight() || hostToolsPending.value > 0),\n (busy) => {\n clearTimeout(workingTimer)\n if (busy) {\n isWorking.value = true\n return\n }\n workingTimer = setTimeout(() => {\n isWorking.value = false\n }, WORKING_SETTLE_MS)\n },\n { immediate: true },\n )\n\n // === Turns running in the background (spec resumable-chat-streams, F2) ===\n /**\n * The chats the list marks as answering: the chat on screen from its\n * own state (working here, or followed), the others as the server\n * last said.\n */\n const runningChatIds = computed(() => {\n const others = serverRunningChatIds.value.filter(\n (id) => id !== localChatId.value,\n )\n return isWorking.value || followedChatId.value === localChatId.value\n ? [...others, localChatId.value]\n : others\n })\n\n /** The turns worth asking about: running elsewhere, or left running. */\n const watchedTurns = () => [\n ...new Set([\n ...serverRunningChatIds.value,\n ...backgroundTurns.value,\n ]),\n ]\n\n const documentVisibility = useDocumentVisibility()\n let runningTurnsTimer: ReturnType<typeof setTimeout> | undefined\n /** Ordering of the concurrent reads, as for `refreshMessages`. */\n let runningTurnsSequence = 0\n let runningTurnsApplied = 0\n\n /** Asks again in a while, while there is a turn to watch and anyone to see it. */\n function scheduleRunningTurns() {\n clearTimeout(runningTurnsTimer)\n runningTurnsTimer = undefined\n if (\n watchedTurns().length === 0 ||\n documentVisibility.value !== 'visible'\n ) {\n return\n }\n runningTurnsTimer = setTimeout(() => {\n runningTurnsTimer = undefined\n void refreshRunningTurns(watchedTurns())\n }, RUNNING_TURNS_POLL_MS)\n }\n\n /**\n * The message the user would likely send after the answer\n * `messageId`, the chat's last one, when the agent offers it\n * (`interface.nextMessageSuggestion`). Undefined for none: a failure\n * is not worth a word to the user, the field just stays as it is.\n */\n async function suggestNextMessage(\n messageId: string,\n ): Promise<string | undefined> {\n const chatId = localChatId.value\n if (\n !agentInterface.value?.nextMessageSuggestion ||\n isReasoningAgent.value ||\n !chatId\n ) {\n return undefined\n }\n try {\n const message = await apiClient.value.suggestNextMessage(\n agentIdRef.value,\n chatId,\n messageId,\n )\n return message ?? undefined\n } catch {\n return undefined\n }\n }\n\n /**\n * Reads which of the chats have a turn running and settles the ones\n * that ended: the list loses their mark, a turn left in the background\n * leaves a notice (unless its chat is on screen again), and the list\n * is read again once, for the titles and the order the written turns\n * changed.\n */\n async function refreshRunningTurns(chatIds: string[]) {\n // Beyond the server's limit an id is not asked, so never taken as\n // over: the callers put the turns left running first.\n const askedIds = chatIds.slice(0, RUNNING_TURNS_MAX_IDS)\n if (isReasoningAgent.value || askedIds.length === 0) {\n scheduleRunningTurns()\n return\n }\n const mine = (runningTurnsSequence += 1)\n let running: string[]\n try {\n running = await apiClient.value.getRunningTurns(\n agentIdRef.value,\n askedIds,\n )\n } catch {\n scheduleRunningTurns()\n return\n }\n if (mine <= runningTurnsApplied) {\n return\n }\n runningTurnsApplied = mine\n for (const id of running) {\n seenRunning.add(id)\n }\n const asked = new Set(askedIds)\n const absent = watchedTurns().filter(\n (id) => asked.has(id) && !running.includes(id),\n )\n // A turn left before its request reached the server is not over\n // while it has never been reported: it stays watched for a\n // while, then is dropped without a notice (it never started).\n const unstarted = (id: string) =>\n backgroundTurns.value.includes(id) && !seenRunning.has(id)\n const expired = absent.filter(\n (id) =>\n unstarted(id) &&\n Date.now() - (backgroundLeftAt.get(id) ?? 0) >\n BACKGROUND_START_GRACE_MS,\n )\n const ended = absent.filter((id) => !unstarted(id))\n serverRunningChatIds.value = [\n ...serverRunningChatIds.value.filter((id) => !asked.has(id)),\n ...running,\n ]\n const endedInBackground = ended.filter((id) =>\n backgroundTurns.value.includes(id),\n )\n if (endedInBackground.length > 0 || expired.length > 0) {\n backgroundTurns.value = backgroundTurns.value.filter(\n (id) =>\n !endedInBackground.includes(id) &&\n !expired.includes(id),\n )\n answeredInBackground.value = [\n ...answeredInBackground.value,\n ...endedInBackground.filter(\n (id) =>\n id !== localChatId.value &&\n !answeredInBackground.value.includes(id),\n ),\n ]\n }\n if (ended.length > 0) {\n void loadConversations(agentIdRef.value)\n }\n scheduleRunningTurns()\n }\n\n watch(documentVisibility, (visibility) => {\n if (visibility === 'visible') {\n void refreshRunningTurns(watchedTurns())\n return\n }\n clearTimeout(runningTurnsTimer)\n runningTurnsTimer = undefined\n })\n onScopeDispose(() => clearTimeout(runningTurnsTimer))\n\n /** The answers that ended in the background, named by the chat's title, else its question. */\n const backgroundAnswers = computed(() =>\n answeredInBackground.value.map((chatId) => ({\n chatId,\n title:\n conversations.value.find((c) => c.id === chatId)?.title ||\n backgroundQuestions.value[chatId] ||\n undefined,\n })),\n )\n /** The notice's \"Open\": the chat whose answer ended in the background. */\n function openBackgroundAnswer(chatId: string) {\n forgetBackgroundTurn(chatId)\n localChatId.value = chatId\n navigate('chat')\n }\n function dismissBackgroundAnswer(chatId: string) {\n answeredInBackground.value = answeredInBackground.value.filter(\n (id) => id !== chatId,\n )\n forgetBackgroundQuestion(chatId)\n }\n\n // The turn on screen ended: what the user queued goes now, unless the\n // turn failed or waits on the user, when it goes back to the input.\n // A status that changes with the chat (another conversation opened)\n // is not an end: the chat opened sends its queue once loaded.\n watch(\n () => [chat.value.status, chat.value.id] as const,\n ([status, id], [previous, previousId]) => {\n if (id !== previousId) {\n return\n }\n // A resume that fails is not the end of the turn it follows.\n if (status === 'error') {\n if (followedTurn?.chatId !== localChatId.value) {\n restoreInput(takeQueue(localChatId.value))\n }\n return\n }\n if (\n status === 'ready' &&\n (previous === 'streaming' || previous === 'submitted')\n ) {\n if (awaitsUser()) {\n restoreInput(takeQueue(localChatId.value))\n return\n }\n void flushQueue()\n }\n },\n )\n // The host calls of the answer done, with nothing that resumes it:\n // the turn is over.\n watch(hostToolsPending, (pending) => {\n if (pending === 0 && chat.value.status === 'ready') {\n void flushQueue()\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 /**\n * @param options.projectId - the shared project the chat opens in,\n * which its first message tells the server\n */\n async function startNewChat(options?: { projectId?: string }) {\n const projectId =\n typeof options?.projectId === 'string'\n ? options.projectId\n : undefined\n lastSubmittedInput.value = ''\n hostStepTitles.value = {}\n hostStepChanges.value = {}\n // Not a Stop: the turn of the chat left behind goes on and is\n // written, the browser only detaches from it (see the watcher on\n // the chatId), and its host calls are cancelled by theirs.\n localChatId.value = generateId()\n describeChat(localChatId.value, { projectId })\n // `useChat` recreates the chat for the new id on the next tick:\n // wait for it, so this function and its callers (a reasoning\n // agent's submit, the identity switch) act on the new chat.\n await nextTick()\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 (isReadOnlyChat.value) {\n return\n }\n if (chat.value.status !== 'ready') {\n lastSubmittedInput.value = ''\n await stopGeneration()\n }\n cancelHostCalls()\n await chat.value.regenerate(options)\n }\n\n function addToolOutput(params: {\n tool: string\n toolCallId: string\n output: unknown\n }) {\n if (isReadOnlyChat.value) {\n return\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 if (isReadOnlyChat.value) {\n return\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 (isReadOnlyChat.value) {\n return\n }\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 attachment = newPendingAttachment(file)\n pendingAttachments.value = [...pendingAttachments.value, attachment]\n await uploadPendingAttachment(attachment)\n }\n\n /**\n * The user edited an image of the composer (spec\n * `chat-image-editor.md`): the edited copy takes its place in the\n * list and uploads, and the replaced upload is deleted from `temp/`\n * at once, since it holds what the user may have covered. One still\n * uploading is deleted when it lands, in `uploadPendingAttachment`.\n */\n async function replacePendingAttachment(\n attachment: PendingAttachment,\n file: File,\n ) {\n const replaced = pendingAttachments.value.find(\n (a) => a.id === attachment.id,\n )\n if (!replaced) {\n return\n }\n URL.revokeObjectURL(replaced.localUrl)\n const next = newPendingAttachment(file)\n pendingAttachments.value = pendingAttachments.value.map((a) =>\n a.id === replaced.id ? next : a,\n )\n await Promise.all([\n discardPendingAttachment(replaced),\n uploadPendingAttachment(next),\n ])\n }\n\n /**\n * Uploads again an attachment whose upload failed: the same file, so\n * an image edited in the composer keeps its edits.\n */\n async function retryPendingAttachment(attachment: PendingAttachment) {\n const failed = pendingAttachments.value.find(\n (a) => a.id === attachment.id && a.state === 'error',\n )\n if (!failed) {\n return\n }\n pendingAttachments.value = pendingAttachments.value.map((a) =>\n a.id === failed.id\n ? { ...a, state: 'uploading', error: undefined }\n : a,\n )\n await uploadPendingAttachment(failed)\n }\n\n function newPendingAttachment(file: File): PendingAttachment {\n return {\n id: generateId(),\n file,\n localUrl: URL.createObjectURL(file),\n state: 'uploading',\n }\n }\n\n async function uploadPendingAttachment({\n id,\n file,\n }: PendingAttachment) {\n try {\n const mediaSource = await apiClient.value.uploadMedia(\n agentIdRef.value,\n localChatId.value,\n file,\n )\n // Taken back or replaced by its edited copy while it\n // uploaded: nothing will send it\n if (!pendingAttachments.value.some((a) => a.id === id)) {\n await discardUpload(mediaSource)\n return\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 /**\n * An attachment the user took back before sending, already out of\n * `pendingAttachments` (the composer removes it): its upload is\n * deleted from `temp/` instead of left a day to the storage rule, since\n * the user may have taken it back for what it shows. One still\n * uploading is deleted when it lands, in `uploadPendingAttachment`.\n */\n async function discardPendingAttachment(attachment: PendingAttachment) {\n if (attachment.mediaSource) {\n await discardUpload(attachment.mediaSource)\n }\n }\n\n async function discardUpload(source: MediaSource) {\n try {\n await apiClient.value.discardMedia(source)\n } catch {\n // Nothing for the user to do: the storage rule `temp-ttl-1d`\n // still deletes it within a day\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 function focusInput() {\n navigate('chat')\n inputFocusRequest.value++\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): `null`.\n */\n function readChatAsNewUser(chatId: string) {\n const probe = () =>\n apiClient.value.getChat(agentIdRef.value, chatId)\n return probe().catch(() => probe().catch(() => null))\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 readable = isReasoningAgent.value\n ? null\n : await readChatAsNewUser(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 (readable) {\n // Same conversation, new owner (anonymous → linked account):\n // keep the messages, refresh the user-scoped list. Its author\n // is read again: the linked account's now, or a colleague's\n // in a shared project, which stays read only.\n describeChat(verifiedChatId, {\n authorId: readable.userId,\n projectId: readable.projectId,\n })\n loadConversations(agentIdRef.value)\n return\n }\n conversations.value = []\n messageFeedbacks.value = []\n chatFiles.value = []\n serverRunningChatIds.value = []\n backgroundTurns.value = []\n answeredInBackground.value = []\n backgroundQuestions.value = {}\n // Rotating the chatId recreates the chat (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 suggestNextMessage,\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 agentHostTools,\n hostToolRegistry,\n hostToolsPending,\n agentPageAccess,\n pageToolRegistry,\n pageFormsProvider,\n pageAction,\n hostStepTitles,\n hostStepChanges,\n pageControlActive,\n isWorking,\n stopHostActions,\n voicePageTools,\n cancelVoicePageCalls,\n pageNoticeLevel,\n closePageNotice,\n hostConfirmation,\n respondHostConfirmation,\n pageAccessAvailable,\n pageAccessOff,\n setPageAccessOff,\n agentConfirmations,\n agentSelectionActions,\n sendSelection,\n confirmationsAvailable,\n confirmationMode,\n setConfirmationMode,\n pagePointer,\n pagePointerStart,\n pagePointing,\n pagePointerAvailable,\n systemTheme,\n hideWelcomeMessage,\n isDark,\n // Chat state\n chat,\n messages,\n conversations,\n isLoadingConversations,\n hasMoreConversations,\n isLoadingMoreConversations,\n chatFiles,\n isLoadingChatFiles,\n input,\n pendingAttachments,\n isAttachmentLimitReached,\n fileLimitError,\n localChatId,\n isConversationBlocked,\n inputMessagePlaceholder,\n chatError,\n // Background turns and the queue (spec resumable-chat-streams, F2)\n runningChatIds,\n backgroundAnswers,\n openBackgroundAnswer,\n dismissBackgroundAnswer,\n canQueue,\n queuedMessages,\n removeQueuedMessage,\n editQueuedMessage,\n // Navigation\n activeView,\n inputFocusRequest,\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 loadMoreConversations,\n projectsEnabled,\n chatAuthorId,\n chatProjectId,\n isReadOnlyChat,\n describeChat,\n searchConversations,\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 discardPendingAttachment,\n replacePendingAttachment,\n retryPendingAttachment,\n clearFileLimitError,\n clearPendingAttachments,\n onUpvote,\n onDownvote,\n onFeedback,\n onFeedbackSubmit,\n onLeadSubmit,\n navigate,\n focusInput,\n renameChatTitle,\n deleteChat,\n }\n })()\n}\n"],"ignoreList":[2,3,4,5,6,7,8,9,10,11,12,13],"mappings":";;;;;;;;;;;AAgBA,SAAgBmH,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;EACrB,UAAU,OAAO,SAAS;EAC1B,WAAW,SAAS;EACpB,UAAU,SAAS,YAAY,KAAA;EAC/B,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB,gBAAgB,OAAO;EACvB,kBAAkB,OAAO;EACzB,gBAAgB,UAAU;EAC1B,qBAAqB,UAAU;EAC/B,cAAe,UACV;EACL,UAAUA,GAAQ;EAClB,gBAAgBD,GAAY;EAC5B,yBAAyBA,GAAY;EACrC,oBAAoBA,GAAY;EAChC,eAAeA,GAAY;EAC3B,UAAUA,GAAY;EACtB,UAAU,OAAO,WAAW,8BAA8B,CAAC,CAAC;EAC5D,eAAe,OAAO,WAAW,kCAAkC,CAAC,CAC/D;EACL,eAAe,OAAO,QAAQ;CAClC;AACJ;AAoBA,eAAsBE,GAClB,GAC+B;CAC/B,IAAI,CAAC,UAAU,eAAe,CAAC,UAAU,aACrC,OAAO;CAGX,IAAI;EAIA,KAAI,MAHqB,UAAU,YAAY,MAAM,EACj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EA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GAEA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GAEA;GACA;GAEA;GACA;GACA;GACA;GACA;GAEA;GACA;GACA;GAEA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACJ;CACJ,CAAC,CAAC,CAAC;AACP"}
|