murmur-rag 1.1.0 → 1.3.0

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.
Files changed (45) hide show
  1. package/README.md +28 -19
  2. package/dist/cdn/{anthropic-dc7h9prc.js → anthropic-tw416spz.js} +2 -2
  3. package/dist/cdn/chunk-xyp6nm65.js +1 -0
  4. package/dist/cdn/{embed-fd96s8qk.js → embed-3am76qfd.js} +9 -9
  5. package/dist/cdn/embed-50pfy67v.js +83 -0
  6. package/dist/cdn/{embed-z32y952f.js → embed-cx1r66ch.js} +6 -6
  7. package/dist/cdn/{embed-ssqsb38w.js → embed-g0p6yc29.js} +2 -2
  8. package/dist/cdn/{embed-krrjjyf5.js → embed-q81wdr1z.js} +4 -4
  9. package/dist/cdn/embed-rjpq8psf.js +10 -0
  10. package/dist/cdn/{embed-acjpjh6t.js → embed-yz75savs.js} +3 -3
  11. package/dist/cdn/{google-yywkqdph.js → google-556tp13p.js} +8 -8
  12. package/dist/cdn/index-8r44b2wt.js +1 -0
  13. package/dist/cdn/index-a5j4aat5.js +1 -0
  14. package/dist/cdn/index-ft8r539a.js +1 -0
  15. package/dist/cdn/index-pjxy71n5.js +1 -0
  16. package/dist/cdn/{index-gyd02jvt.js → index-qpy1k923.js} +2 -2
  17. package/dist/cdn/mistral-25w1nsx5.js +3 -0
  18. package/dist/cdn/{murmur-j1ky5vmr.js → murmur-1a55et82.js} +3 -3
  19. package/dist/cdn/murmur.js +7 -7
  20. package/dist/cdn/openai-bjrbem49.js +18 -0
  21. package/dist/cdn/{openai-compatible-zhaj1r43.js → openai-compatible-sg25g0vj.js} +6 -6
  22. package/dist/cdn/retriever-06ybegpd.js +1 -0
  23. package/dist/cdn/{transformers.web-3kmbvcbt.js → transformers.web-49m0ht4a.js} +9 -9
  24. package/dist/lib/chunks/{index-92w507gk.js → index-4ftk20yq.js} +164 -50
  25. package/dist/lib/embed.js +10 -4
  26. package/dist/lib/llm/index.js +23 -0
  27. package/dist/lib/local/index.js +38 -2
  28. package/dist/lib/widget/index.js +2 -2
  29. package/dist/types/llm/index.d.ts +8 -0
  30. package/dist/types/local/index.d.ts +12 -0
  31. package/dist/types/widget/element.d.ts +4 -0
  32. package/dist/types/widget/i18n.d.ts +1 -0
  33. package/dist/types/widget/session.d.ts +56 -8
  34. package/dist/types/widget/styles.d.ts +1 -1
  35. package/package.json +1 -1
  36. package/dist/cdn/chunk-hpx6rpea.js +0 -1
  37. package/dist/cdn/embed-6gef7ym5.js +0 -10
  38. package/dist/cdn/embed-jdraznwg.js +0 -83
  39. package/dist/cdn/index-bq0x71h1.js +0 -1
  40. package/dist/cdn/index-jt6n0d28.js +0 -1
  41. package/dist/cdn/index-nesgnf2n.js +0 -1
  42. package/dist/cdn/index-wgzgvzaf.js +0 -1
  43. package/dist/cdn/mistral-0mg4kk7s.js +0 -3
  44. package/dist/cdn/openai-g1685z9v.js +0 -18
  45. package/dist/cdn/retriever-dqxzjaqk.js +0 -1
@@ -1,14 +1,14 @@
1
- import{oe,Ie}from"./embed-6gef7ym5.js";import{et}from"./embed-acjpjh6t.js";import{m,b,P,me,u,e,r,c,v,Ae,o,t,U,l,y,i,n,G,k,T,d,Oe,ue,fe,ae,N,X,M,we,Yt,te,le,xe,ke,Z,q,Te,z,K,He,Me,tn,de,C,R,L,Ze,he,W,Se,it,ge,Q,a,s,j,J,h,g,ve,S,_,O,H,I,D,p,_e,E,Y}from"./embed-jdraznwg.js";var zn="4.0.107",fn=()=>t({code:r().nullable(),message:e(),status:e(),details:o(v()).nullish()}),Jn=a(()=>s(t({error:fn()}))),Xe=I({errorSchema:Jn,errorToMessage:(f)=>f.error.message}),Yn=()=>l([t({text:e()}),t({inlineData:t({mimeType:e(),data:e()})}),t({fileData:t({fileUri:e(),mimeType:e()})})]),Xn=a(()=>s(t({outputDimensionality:r().optional(),taskType:i(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),content:o(o(Yn()).min(1).nullable()).optional()}))),Qn=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.specificationVersion="v4",this.maxEmbeddingsPerCall=100,this.supportsParallelCalls=!0,this[tn]=({providerOptions:A,values:F,startIndex:B,endIndex:re})=>{let ee=A?.google?.content;if(!Array.isArray(ee))return A;return zt({multimodalContent:ee,values:F}),{...A,google:{...A?.google,content:ee.slice(B,re)}}},this.modelId=w,this.config=x}async doEmbed({values:w,dimensions:x,headers:A,abortSignal:F,providerOptions:B}){let re=await h({provider:"google",providerOptions:B,schema:Xn});if(w.length>this.maxEmbeddingsPerCall)throw new me({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:w});let ee=d(this.config.headers?await _(this.config.headers):void 0,A),V=re?.content;if(zt({multimodalContent:V,values:w}),w.length===1){let Le=V?.[0],Ce=w[0]?[{text:w[0]}]:[],Ee=Le!=null?[...Ce,...Le]:[{text:w[0]}],{responseHeaders:je,value:Ne,rawValue:ye}=await g({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:ee,body:{model:`models/${this.modelId}`,content:{parts:Ee},outputDimensionality:re?.outputDimensionality??x,taskType:re?.taskType},failedResponseHandler:Xe,successfulResponseHandler:p(eo),abortSignal:F,fetch:this.config.fetch});return{warnings:[],embeddings:[Ne.embedding.values],usage:void 0,response:{headers:je,body:ye}}}let{responseHeaders:pe,value:ce,rawValue:Re}=await g({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:ee,body:{requests:w.map((Le,Ce)=>{let Ee=V?.[Ce],je=Le?[{text:Le}]:[];return{model:`models/${this.modelId}`,content:{role:"user",parts:Ee!=null?[...je,...Ee]:[{text:Le}]},outputDimensionality:re?.outputDimensionality??x,taskType:re?.taskType}})},failedResponseHandler:Xe,successfulResponseHandler:p(Zn),abortSignal:F,fetch:this.config.fetch});return{warnings:[],embeddings:ce.embeddings.map((Le)=>Le.values),usage:void 0,response:{headers:pe,body:Re}}}},Zn=a(()=>s(t({embeddings:o(t({values:o(r())}))}))),eo=a(()=>s(t({embedding:t({values:o(r())})})));function zt({multimodalContent:f,values:w}){if(f!=null&&f.length!==w.length)throw Error(`The number of multimodal content entries (${f.length}) must match the number of values (${w.length}).`)}function Tt(f){return f.includes("/")?f:`models/${f}`}function to({stream:f,getContinuationToken:w,continueStream:x}){let A=f.getReader(),F;return new ReadableStream({async pull(B){while(!0){let{done:re,value:ee}=await A.read();if(!re){if(ee.success){let pe=w(ee.value);if(pe!=null)F=pe}B.enqueue(ee);return}if(F==null){B.close();return}let V=F;F=void 0;try{A=(await x(V)).getReader(),B.enqueue({type:"continuation-start"});return}catch(pe){B.enqueue({success:!1,error:pe,rawValue:void 0}),B.close();return}}},async cancel(B){await A.cancel(B)}})}function Jt(f){if(f==null)return te();let w=f.promptTokenCount??0,x=f.candidatesTokenCount??0,A=f.toolUsePromptTokenCount??0,F=f.cachedContentTokenCount??0,B=f.thoughtsTokenCount??0,re=w+A;return{inputTokens:{total:re,noCache:re-F,cacheRead:F,cacheWrite:void 0},outputTokens:{total:x+B,text:x,reasoning:B},raw:f}}function jt(f,w){if(f==null||w==null)return w??f;return{...f,...w,promptTokenCount:vt(f.promptTokenCount,w.promptTokenCount),candidatesTokenCount:vt(f.candidatesTokenCount,w.candidatesTokenCount),toolUsePromptTokenCount:vt(f.toolUsePromptTokenCount,w.toolUsePromptTokenCount),totalTokenCount:vt(f.totalTokenCount,w.totalTokenCount),cachedContentTokenCount:vt(f.cachedContentTokenCount,w.cachedContentTokenCount),thoughtsTokenCount:vt(f.thoughtsTokenCount,w.thoughtsTokenCount),promptTokensDetails:kt(f.promptTokensDetails,w.promptTokensDetails),cacheTokensDetails:kt(f.cacheTokensDetails,w.cacheTokensDetails),candidatesTokensDetails:kt(f.candidatesTokensDetails,w.candidatesTokensDetails),toolUsePromptTokensDetails:kt(f.toolUsePromptTokensDetails,w.toolUsePromptTokensDetails)}}function vt(f,w){return f==null&&w==null?w??f:(f??0)+(w??0)}function kt(f,w){if(f==null||w==null)return w??f;let x=new Map;for(let{modality:A,tokenCount:F}of[...f,...w])x.set(A,(x.get(A)??0)+F);return Array.from(x,([A,F])=>({modality:A,tokenCount:F}))}var yn=t({language:e().describe("The programming language of the code."),code:e().describe("The code to be executed.")}),vn=t({outcome:e().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:e().describe("The output from the code execution.")}),no=S({id:"google.code_execution",inputSchema:yn,outputSchema:vn}),oo="skip_thought_signature_validator",io=/^data:([^;,]+);base64,(.+)$/s;function so(f){let w=io.exec(f);if(w==null)return;return{mediaType:w[1],data:w[2]}}function ao(f){let w=so(f);if(w==null)return;return{inlineData:{mimeType:w.mediaType,data:w.data}}}function Gt(f){if(Array.isArray(f))return f.some(Gt);if(typeof f!=="object"||f===null)return!1;return Object.entries(f).some(([w,x])=>w==="$ref"||Gt(x))}function Xt(f){return Gt(f)?JSON.stringify(f):f}function ro(f,w,x,A,F=!0,B={}){let re=[],ee=[];for(let V of x)switch(V.type){case"text":ee.push(V.text);break;case"file":if(V.data.type==="data")re.push({inlineData:{mimeType:O({part:V}),data:M(V.data.data)}});else if(V.data.type==="url"){let pe=V.data.url.toString(),ce=ao(pe),Re=V.data.url.protocol==="gs:"&&V.data.originalUrl!=null?V.data.originalUrl:pe;if(ce!=null)re.push(ce);else if(K(V.mediaType)&&Ze({url:Re,mediaType:V.mediaType,supportedUrls:B}))re.push({fileData:{mimeType:V.mediaType,fileUri:Re}});else ee.push(JSON.stringify(V))}else ee.push(JSON.stringify(V));break;default:ee.push(JSON.stringify(V))}f.push({functionResponse:{...F&&A!=null?{id:A}:{},name:w,response:{name:w,content:ee.length>0?ee.join(`
2
- `):"Tool executed successfully."},...re.length>0?{parts:re}:{}}})}function lo(f,w,x,A,F=!0){for(let B of x)switch(B.type){case"text":f.push({functionResponse:{...F&&A!=null?{id:A}:{},name:w,response:{name:w,content:B.text}}});break;case"file":if(B.data.type==="data"){let re=z(B.mediaType);f.push({inlineData:{mimeType:O({part:B}),data:M(B.data.data)}},{text:`Tool executed successfully and returned this ${re==="image"?"image":"file"} as a response`})}else f.push({text:JSON.stringify(B)});break;default:f.push({text:JSON.stringify(B)})}}function uo(f,w){let x=[],A=[],F=!0,B=w?.isGemmaModel??!1,re=w?.isGemini3Model??!1,ee=w?.onWarning,V=w?.providerOptionsNames??["google"],pe=!V.includes("google"),ce=w?.supportsFunctionResponseParts??!0,Re=w?.includeFunctionCallIds??!0,Le=w?.supportedFunctionResponseUrls??{},Ce=!1,Ee=[],je=(ye)=>(Ee.push(ye),Ce=!0,oo),Ne=(ye)=>{for(let ie of V){let be=ye.providerOptions?.[ie];if(be!=null)return be}if(pe)return ye.providerOptions?.google;return ye.providerOptions?.googleVertex??ye.providerOptions?.vertex};for(let{role:ye,content:ie}of f)switch(ye){case"system":if(!F)throw new u({functionality:"system messages are only supported at the beginning of the conversation"});x.push({text:ie});break;case"user":{F=!1;let be=[];for(let ne of ie)switch(ne.type){case"text":be.push({text:ne.text});break;case"file":switch(ne.data.type){case"url":be.push({fileData:{mimeType:O({part:ne}),fileUri:ne.data.url.protocol==="gs:"&&ne.data.originalUrl!=null?ne.data.originalUrl:ne.data.url.toString()}});break;case"reference":if(pe)throw new u({functionality:"file parts with provider references"});be.push({fileData:{mimeType:O({part:ne}),fileUri:H({reference:ne.data.reference,provider:"google"})}});break;case"text":be.push({inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:M(new TextEncoder().encode(ne.data.text))}});break;case"data":be.push({inlineData:{mimeType:O({part:ne}),data:M(ne.data.data)}})}}A.push({role:"user",parts:be});break}case"assistant":{F=!1;let be=!1;A.push({role:"model",parts:ie.map((ne)=>{let se=Ne(ne),Ue=se?.thoughtSignature!=null?String(se.thoughtSignature):void 0;switch(ne.type){case"text":return ne.text.length===0?void 0:{text:ne.text,thoughtSignature:Ue};case"reasoning":return ne.text.length===0?void 0:{text:ne.text,thought:!0,thoughtSignature:Ue};case"reasoning-file":switch(ne.data.type){case"url":throw new u({functionality:"File data URLs in assistant messages are not supported"});case"data":return{inlineData:{mimeType:ne.mediaType,data:M(ne.data.data)},thought:!0,thoughtSignature:Ue}}break;case"file":switch(ne.data.type){case"url":throw new u({functionality:"File data URLs in assistant messages are not supported"});case"reference":if(pe)throw new u({functionality:"file parts with provider references"});return{fileData:{mimeType:ne.mediaType,fileUri:H({reference:ne.data.reference,provider:"google"})},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"text":return{inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:M(new TextEncoder().encode(ne.data.text))},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"data":return{inlineData:{mimeType:ne.mediaType,data:M(ne.data.data)},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue}}break;case"tool-call":{if(ne.providerExecuted===!0&&ne.toolName==="code_execution")return{executableCode:yn.parse(typeof ne.input==="string"?Q(ne.input):ne.input)};let De=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,qe=se?.serverToolType!=null?String(se.serverToolType):void 0,We=De!=null&&qe!=null,nt=Ue??(re&&!(!We&&Ue==null&&be)?je(ne.toolName):void 0);if(!We&&Ue!=null)be=!0;if(We)return{toolCall:{toolType:qe,args:typeof ne.input==="string"?Q(ne.input):ne.input,id:De},thoughtSignature:nt};return{functionCall:{...Re&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,args:ne.input},thoughtSignature:nt}}case"tool-result":{if(ne.toolName==="code_execution"&&ne.output.type==="json")return{codeExecutionResult:vn.parse(ne.output.value)};let De=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,qe=se?.serverToolType!=null?String(se.serverToolType):void 0;if(De&&qe)return{toolResponse:{toolType:qe,response:ne.output.type==="json"?ne.output.value:{},id:De},thoughtSignature:Ue};return}}}).filter((ne)=>ne!==void 0)});break}case"tool":{F=!1;let be=[];for(let ne of ie){if(ne.type==="tool-approval-response")continue;let se=Ne(ne),Ue=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,De=se?.serverToolType!=null?String(se.serverToolType):void 0;if(Ue&&De){let We=se?.thoughtSignature!=null?String(se.thoughtSignature):void 0;if(A.length>0){let nt=A[A.length-1];if(nt.role==="model"){nt.parts.push({toolResponse:{toolType:De,response:ne.output.type==="json"?ne.output.value:{},id:Ue},thoughtSignature:We});continue}}}let qe=ne.output;if(qe.type==="content")if(ce)ro(be,ne.toolName,qe.value,ne.toolCallId,Re,Le);else lo(be,ne.toolName,qe.value,ne.toolCallId,Re);else{let We=qe.type==="error-text"||qe.type==="error-json"||qe.type==="execution-denied";be.push({functionResponse:{...Re&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,response:{name:ne.toolName,...We?{error:qe.type==="execution-denied"?qe.reason??"Tool call execution denied.":Xt(qe.value)}:{content:Xt(qe.value)}}}})}}A.push({role:"user",parts:be});break}}if(B&&x.length>0&&A.length>0&&A[0].role==="user"){let ye=x.map((ie)=>ie.text).join(`
1
+ import{oe,Ie}from"./embed-rjpq8psf.js";import{rt}from"./embed-yz75savs.js";import{m,b,P,me,u,e,r,c,v,Ae,o,t,U,l,y,i,n,G,k,T,d,Oe,ue,fe,ae,j,X,M,we,tn,te,le,xe,ke,Z,F,Te,z,K,Ke,Me,on,de,C,R,L,Qe,he,W,Se,ut,ge,Q,a,s,q,J,h,g,ve,S,_,O,H,I,D,p,_e,E,Y}from"./embed-50pfy67v.js";var zn="4.0.107",fn=()=>t({code:r().nullable(),message:e(),status:e(),details:o(v()).nullish()}),Jn=a(()=>s(t({error:fn()}))),Xe=I({errorSchema:Jn,errorToMessage:(f)=>f.error.message}),Yn=()=>l([t({text:e()}),t({inlineData:t({mimeType:e(),data:e()})}),t({fileData:t({fileUri:e(),mimeType:e()})})]),Xn=a(()=>s(t({outputDimensionality:r().optional(),taskType:i(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),content:o(o(Yn()).min(1).nullable()).optional()}))),Qn=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.specificationVersion="v4",this.maxEmbeddingsPerCall=100,this.supportsParallelCalls=!0,this[on]=({providerOptions:A,values:N,startIndex:B,endIndex:re})=>{let ee=A?.google?.content;if(!Array.isArray(ee))return A;return zt({multimodalContent:ee,values:N}),{...A,google:{...A?.google,content:ee.slice(B,re)}}},this.modelId=w,this.config=x}async doEmbed({values:w,dimensions:x,headers:A,abortSignal:N,providerOptions:B}){let re=await h({provider:"google",providerOptions:B,schema:Xn});if(w.length>this.maxEmbeddingsPerCall)throw new me({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:w});let ee=d(this.config.headers?await _(this.config.headers):void 0,A),V=re?.content;if(zt({multimodalContent:V,values:w}),w.length===1){let Le=V?.[0],Ce=w[0]?[{text:w[0]}]:[],Ee=Le!=null?[...Ce,...Le]:[{text:w[0]}],{responseHeaders:je,value:Ne,rawValue:ye}=await g({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:ee,body:{model:`models/${this.modelId}`,content:{parts:Ee},outputDimensionality:re?.outputDimensionality??x,taskType:re?.taskType},failedResponseHandler:Xe,successfulResponseHandler:p(eo),abortSignal:N,fetch:this.config.fetch});return{warnings:[],embeddings:[Ne.embedding.values],usage:void 0,response:{headers:je,body:ye}}}let{responseHeaders:pe,value:ce,rawValue:Re}=await g({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:ee,body:{requests:w.map((Le,Ce)=>{let Ee=V?.[Ce],je=Le?[{text:Le}]:[];return{model:`models/${this.modelId}`,content:{role:"user",parts:Ee!=null?[...je,...Ee]:[{text:Le}]},outputDimensionality:re?.outputDimensionality??x,taskType:re?.taskType}})},failedResponseHandler:Xe,successfulResponseHandler:p(Zn),abortSignal:N,fetch:this.config.fetch});return{warnings:[],embeddings:ce.embeddings.map((Le)=>Le.values),usage:void 0,response:{headers:pe,body:Re}}}},Zn=a(()=>s(t({embeddings:o(t({values:o(r())}))}))),eo=a(()=>s(t({embedding:t({values:o(r())})})));function zt({multimodalContent:f,values:w}){if(f!=null&&f.length!==w.length)throw Error(`The number of multimodal content entries (${f.length}) must match the number of values (${w.length}).`)}function Tt(f){return f.includes("/")?f:`models/${f}`}function to({stream:f,getContinuationToken:w,continueStream:x}){let A=f.getReader(),N;return new ReadableStream({async pull(B){while(!0){let{done:re,value:ee}=await A.read();if(!re){if(ee.success){let pe=w(ee.value);if(pe!=null)N=pe}B.enqueue(ee);return}if(N==null){B.close();return}let V=N;N=void 0;try{A=(await x(V)).getReader(),B.enqueue({type:"continuation-start"});return}catch(pe){B.enqueue({success:!1,error:pe,rawValue:void 0}),B.close();return}}},async cancel(B){await A.cancel(B)}})}function Jt(f){if(f==null)return te();let w=f.promptTokenCount??0,x=f.candidatesTokenCount??0,A=f.toolUsePromptTokenCount??0,N=f.cachedContentTokenCount??0,B=f.thoughtsTokenCount??0,re=w+A;return{inputTokens:{total:re,noCache:re-N,cacheRead:N,cacheWrite:void 0},outputTokens:{total:x+B,text:x,reasoning:B},raw:f}}function jt(f,w){if(f==null||w==null)return w??f;return{...f,...w,promptTokenCount:vt(f.promptTokenCount,w.promptTokenCount),candidatesTokenCount:vt(f.candidatesTokenCount,w.candidatesTokenCount),toolUsePromptTokenCount:vt(f.toolUsePromptTokenCount,w.toolUsePromptTokenCount),totalTokenCount:vt(f.totalTokenCount,w.totalTokenCount),cachedContentTokenCount:vt(f.cachedContentTokenCount,w.cachedContentTokenCount),thoughtsTokenCount:vt(f.thoughtsTokenCount,w.thoughtsTokenCount),promptTokensDetails:kt(f.promptTokensDetails,w.promptTokensDetails),cacheTokensDetails:kt(f.cacheTokensDetails,w.cacheTokensDetails),candidatesTokensDetails:kt(f.candidatesTokensDetails,w.candidatesTokensDetails),toolUsePromptTokensDetails:kt(f.toolUsePromptTokensDetails,w.toolUsePromptTokensDetails)}}function vt(f,w){return f==null&&w==null?w??f:(f??0)+(w??0)}function kt(f,w){if(f==null||w==null)return w??f;let x=new Map;for(let{modality:A,tokenCount:N}of[...f,...w])x.set(A,(x.get(A)??0)+N);return Array.from(x,([A,N])=>({modality:A,tokenCount:N}))}var yn=t({language:e().describe("The programming language of the code."),code:e().describe("The code to be executed.")}),vn=t({outcome:e().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:e().describe("The output from the code execution.")}),no=S({id:"google.code_execution",inputSchema:yn,outputSchema:vn}),oo="skip_thought_signature_validator",io=/^data:([^;,]+);base64,(.+)$/s;function so(f){let w=io.exec(f);if(w==null)return;return{mediaType:w[1],data:w[2]}}function ao(f){let w=so(f);if(w==null)return;return{inlineData:{mimeType:w.mediaType,data:w.data}}}function Gt(f){if(Array.isArray(f))return f.some(Gt);if(typeof f!=="object"||f===null)return!1;return Object.entries(f).some(([w,x])=>w==="$ref"||Gt(x))}function Yt(f){return Gt(f)?JSON.stringify(f):f}function ro(f,w,x,A,N=!0,B={}){let re=[],ee=[];for(let V of x)switch(V.type){case"text":ee.push(V.text);break;case"file":if(V.data.type==="data")re.push({inlineData:{mimeType:O({part:V}),data:M(V.data.data)}});else if(V.data.type==="url"){let pe=V.data.url.toString(),ce=ao(pe),Re=V.data.url.protocol==="gs:"&&V.data.originalUrl!=null?V.data.originalUrl:pe;if(ce!=null)re.push(ce);else if(K(V.mediaType)&&Qe({url:Re,mediaType:V.mediaType,supportedUrls:B}))re.push({fileData:{mimeType:V.mediaType,fileUri:Re}});else ee.push(JSON.stringify(V))}else ee.push(JSON.stringify(V));break;default:ee.push(JSON.stringify(V))}f.push({functionResponse:{...N&&A!=null?{id:A}:{},name:w,response:{name:w,content:ee.length>0?ee.join(`
2
+ `):"Tool executed successfully."},...re.length>0?{parts:re}:{}}})}function lo(f,w,x,A,N=!0){for(let B of x)switch(B.type){case"text":f.push({functionResponse:{...N&&A!=null?{id:A}:{},name:w,response:{name:w,content:B.text}}});break;case"file":if(B.data.type==="data"){let re=z(B.mediaType);f.push({inlineData:{mimeType:O({part:B}),data:M(B.data.data)}},{text:`Tool executed successfully and returned this ${re==="image"?"image":"file"} as a response`})}else f.push({text:JSON.stringify(B)});break;default:f.push({text:JSON.stringify(B)})}}function uo(f,w){let x=[],A=[],N=!0,B=w?.isGemmaModel??!1,re=w?.isGemini3Model??!1,ee=w?.onWarning,V=w?.providerOptionsNames??["google"],pe=!V.includes("google"),ce=w?.supportsFunctionResponseParts??!0,Re=w?.includeFunctionCallIds??!0,Le=w?.supportedFunctionResponseUrls??{},Ce=!1,Ee=[],je=(ye)=>(Ee.push(ye),Ce=!0,oo),Ne=(ye)=>{for(let ie of V){let be=ye.providerOptions?.[ie];if(be!=null)return be}if(pe)return ye.providerOptions?.google;return ye.providerOptions?.googleVertex??ye.providerOptions?.vertex};for(let{role:ye,content:ie}of f)switch(ye){case"system":if(!N)throw new u({functionality:"system messages are only supported at the beginning of the conversation"});x.push({text:ie});break;case"user":{N=!1;let be=[];for(let ne of ie)switch(ne.type){case"text":be.push({text:ne.text});break;case"file":switch(ne.data.type){case"url":be.push({fileData:{mimeType:O({part:ne}),fileUri:ne.data.url.protocol==="gs:"&&ne.data.originalUrl!=null?ne.data.originalUrl:ne.data.url.toString()}});break;case"reference":if(pe)throw new u({functionality:"file parts with provider references"});be.push({fileData:{mimeType:O({part:ne}),fileUri:H({reference:ne.data.reference,provider:"google"})}});break;case"text":be.push({inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:M(new TextEncoder().encode(ne.data.text))}});break;case"data":be.push({inlineData:{mimeType:O({part:ne}),data:M(ne.data.data)}})}}A.push({role:"user",parts:be});break}case"assistant":{N=!1;let be=!1;A.push({role:"model",parts:ie.map((ne)=>{let se=Ne(ne),Ue=se?.thoughtSignature!=null?String(se.thoughtSignature):void 0;switch(ne.type){case"text":return ne.text.length===0?void 0:{text:ne.text,thoughtSignature:Ue};case"reasoning":return ne.text.length===0?void 0:{text:ne.text,thought:!0,thoughtSignature:Ue};case"reasoning-file":switch(ne.data.type){case"url":throw new u({functionality:"File data URLs in assistant messages are not supported"});case"data":return{inlineData:{mimeType:ne.mediaType,data:M(ne.data.data)},thought:!0,thoughtSignature:Ue}}break;case"file":switch(ne.data.type){case"url":throw new u({functionality:"File data URLs in assistant messages are not supported"});case"reference":if(pe)throw new u({functionality:"file parts with provider references"});return{fileData:{mimeType:ne.mediaType,fileUri:H({reference:ne.data.reference,provider:"google"})},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"text":return{inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:M(new TextEncoder().encode(ne.data.text))},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"data":return{inlineData:{mimeType:ne.mediaType,data:M(ne.data.data)},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue}}break;case"tool-call":{if(ne.providerExecuted===!0&&ne.toolName==="code_execution")return{executableCode:yn.parse(typeof ne.input==="string"?Q(ne.input):ne.input)};let De=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,qe=se?.serverToolType!=null?String(se.serverToolType):void 0,Ve=De!=null&&qe!=null,tt=Ue??(re&&!(!Ve&&Ue==null&&be)?je(ne.toolName):void 0);if(!Ve&&Ue!=null)be=!0;if(Ve)return{toolCall:{toolType:qe,args:typeof ne.input==="string"?Q(ne.input):ne.input,id:De},thoughtSignature:tt};return{functionCall:{...Re&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,args:ne.input},thoughtSignature:tt}}case"tool-result":{if(ne.toolName==="code_execution"&&ne.output.type==="json")return{codeExecutionResult:vn.parse(ne.output.value)};let De=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,qe=se?.serverToolType!=null?String(se.serverToolType):void 0;if(De&&qe)return{toolResponse:{toolType:qe,response:ne.output.type==="json"?ne.output.value:{},id:De},thoughtSignature:Ue};return}}}).filter((ne)=>ne!==void 0)});break}case"tool":{N=!1;let be=[];for(let ne of ie){if(ne.type==="tool-approval-response")continue;let se=Ne(ne),Ue=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,De=se?.serverToolType!=null?String(se.serverToolType):void 0;if(Ue&&De){let Ve=se?.thoughtSignature!=null?String(se.thoughtSignature):void 0;if(A.length>0){let tt=A[A.length-1];if(tt.role==="model"){tt.parts.push({toolResponse:{toolType:De,response:ne.output.type==="json"?ne.output.value:{},id:Ue},thoughtSignature:Ve});continue}}}let qe=ne.output;if(qe.type==="content")if(ce)ro(be,ne.toolName,qe.value,ne.toolCallId,Re,Le);else lo(be,ne.toolName,qe.value,ne.toolCallId,Re);else{let Ve=qe.type==="error-text"||qe.type==="error-json"||qe.type==="execution-denied";be.push({functionResponse:{...Re&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,response:{name:ne.toolName,...Ve?{error:qe.type==="execution-denied"?qe.reason??"Tool call execution denied.":Yt(qe.value)}:{content:Yt(qe.value)}}}})}}A.push({role:"user",parts:be});break}}if(B&&x.length>0&&A.length>0&&A[0].role==="user"){let ye=x.map((ie)=>ie.text).join(`
3
3
 
4
4
  `);A[0].parts.unshift({text:ye+`
5
5
 
6
- `})}if(Ce&&ee!=null){let ye=Array.from(new Set(Ee));ee({type:"other",message:`Replayed ${Ee.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${ye.map((ie)=>`\`${ie}\``).join(", ")}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`})}return{systemInstruction:x.length>0&&!B?{parts:x}:void 0,contents:A}}async function co(f,{abortSignal:w,maxBytes:x,supportedUrls:A={}}){let F=[];for(let B of f){if(B.role==="assistant"){let re=[];for(let ee of B.content)re.push(ee.type==="tool-result"?{...ee,output:await Qt(ee.output,{abortSignal:w,maxBytes:x,supportedUrls:A})}:ee);F.push({...B,content:re});continue}if(B.role==="tool"){let re=[];for(let ee of B.content){if(ee.type!=="tool-result"){re.push(ee);continue}re.push({...ee,output:await Qt(ee.output,{abortSignal:w,maxBytes:x,supportedUrls:A})})}F.push({...B,content:re});continue}F.push(B)}return F}async function Qt(f,{abortSignal:w,maxBytes:x,supportedUrls:A}){if(f.type!=="content")return f;let F=[];for(let B of f.value){if(B.type!=="file"||B.data.type!=="url"){F.push(B);continue}if(Ze({url:B.data.url.toString(),mediaType:B.mediaType,supportedUrls:A})){F.push(B);continue}let re=await Me(B.data.url.toString(),{abortSignal:w,maxBytes:x}),ee=new Uint8Array(await re.arrayBuffer()),V=Te({data:ee,topLevelType:"image"});F.push({...B,data:{type:"data",data:ee},mediaType:V??(re.type&&!K(B.mediaType)?re.type:B.mediaType)})}return{...f,value:F}}function bn(f){let{const:w,properties:x,items:A,additionalProperties:F,anyOf:B,oneOf:re,...ee}=f;return{...ee,...w!==void 0?{enum:[w]}:{},...x!=null?{properties:Zt(x)}:{},...A!=null?{items:Array.isArray(A)?A.map(bt):bt(A)}:{},...F!=null?{additionalProperties:typeof F==="boolean"?F:bt(F)}:{},...B!=null?{anyOf:B.map(bt)}:{},...re!=null?{oneOf:re.map(bt)}:{},...ee.$defs!=null?{$defs:Zt(ee.$defs)}:{}}}function Zt(f){return Object.fromEntries(Object.entries(f).map(([w,x])=>[w,bt(x)]))}function bt(f){return typeof f==="boolean"?f:bn(f)}var Et=a(()=>s(t({responseModalities:o(i(["TEXT","IMAGE","AUDIO"])).optional(),thinkingConfig:t({thinkingBudget:r().optional(),includeThoughts:c().optional(),thinkingLevel:i(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:e().optional(),structuredOutputs:c().optional(),safetySettings:o(t({category:i(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:i(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:i(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:c().optional(),labels:y(e(),e()).optional(),mediaResolution:i(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:t({aspectRatio:i(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).optional(),imageSize:i(["1K","2K","4K","512"]).optional(),personGeneration:i(["PERSON_GENERATION_UNSPECIFIED","ALLOW_ALL","ALLOW_ADULT","ALLOW_NONE"]).optional(),prominentPeople:i(["PROMINENT_PEOPLE_UNSPECIFIED","ALLOW_PROMINENT_PEOPLE","BLOCK_PROMINENT_PEOPLE"]).optional(),imageOutputOptions:t({mimeType:i(["image/jpeg","image/png"]).optional(),compressionQuality:r().optional()}).optional()}).optional(),retrievalConfig:t({latLng:t({latitude:r(),longitude:r()}).optional()}).optional(),streamFunctionCallArguments:c().optional(),serviceTier:i(["standard","flex","priority"]).optional(),continuationToken:e().optional(),sharedRequestType:i(["priority","flex","standard"]).optional(),requestType:i(["shared"]).optional()}))),po=/(^|[/.])gemini-1(?:[.-]|$)/i,go=/(^|[/.])gemini-2(?:[.-]|$)/i,ho=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,mo=/(^|[/.])gemini-/i;function fo(f){return po.test(f)||/(^|[/.])gemini-pro(?:-vision)?$/i.test(f)||/(^|[/.])gemini-robotics-er-1\.5(?:[.-]|$)/i.test(f)}function At(f){let w=mo.test(f),x=go.test(f),A=fo(f),F=w&&!(A||x);return{supportsGemini2Tools:w&&!A||f.toLowerCase().includes("nano-banana"),supportsFileSearch:ho.test(f)||F,usesGemini3Features:F}}function yo({tools:f,toolChoice:w,modelId:x,isVertexProvider:A=!1}){f=f?.length?f:void 0;let F=[],{supportsGemini2Tools:B,supportsFileSearch:re,usesGemini3Features:ee}=At(x);if(f==null)return{tools:void 0,toolConfig:void 0,toolWarnings:F};let V=f.some((Ce)=>Ce.type==="function"),pe=f.some((Ce)=>Ce.type==="provider");if(V&&pe&&!ee)F.push({type:"unsupported",feature:"combination of function and provider-defined tools"});if(pe){let Ce=[];if(f.filter((Ee)=>Ee.type==="provider").forEach((Ee)=>{switch(Ee.id){case"google.google_search":if(B)Ce.push({googleSearch:{...Ee.args}});else F.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":if(B)Ce.push({enterpriseWebSearch:{}});else F.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":if(B)Ce.push({urlContext:{}});else F.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(B)Ce.push({codeExecution:{}});else F.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The code execution tool is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":if(re)Ce.push({fileSearch:{...Ee.args}});else F.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":if(B)Ce.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:Ee.args.ragCorpus},similarity_top_k:Ee.args.topK}}});else F.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":if(B)Ce.push({googleMaps:{}});else F.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:F.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`})}}),V&&ee&&Ce.length>0){let Ee=[];for(let Ne of f)if(Ne.type==="function")Ee.push(en(Ne));let je={functionCallingConfig:{mode:"VALIDATED"},...!A&&{includeServerSideToolInvocations:!0}};if(w!=null)switch(w.type){case"auto":break;case"none":je.functionCallingConfig={mode:"NONE"};break;case"required":je.functionCallingConfig={mode:"ANY"};break;case"tool":je.functionCallingConfig={mode:"ANY",allowedFunctionNames:[w.toolName]}}return{tools:[...Ce,{functionDeclarations:Ee}],toolConfig:je,toolWarnings:F}}return{tools:Ce.length>0?Ce:void 0,toolConfig:void 0,toolWarnings:F}}let ce=[],Re=!1;for(let Ce of f)switch(Ce.type){case"function":if(ce.push(en(Ce)),Ce.strict===!0)Re=!0;break;default:F.push({type:"unsupported",feature:`function tool ${Ce.name}`})}if(w==null)return{tools:[{functionDeclarations:ce}],toolConfig:Re?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:F};let Le=w.type;switch(Le){case"auto":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:Re?"VALIDATED":"AUTO"}},toolWarnings:F};case"none":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:F};case"required":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:F};case"tool":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[w.toolName]}},toolWarnings:F};default:throw new u({functionality:`tool choice type: ${Le}`})}}function en(f){return{name:f.name,description:f.description??"",parametersJsonSchema:f.inputSchema}}var vo=class{constructor(){this.accumulatedArgs={},this.jsonText="",this.pathStack=[],this.stringOpen=!1}processPartialArgs(f){let w="";for(let x of f){let A=x.jsonPath.endsWith("[]"),F=(A?x.jsonPath.slice(0,-2):x.jsonPath).replace(/^\$\./,"");if(!F||F==="$")continue;let B=bo(F),re=_o(this.accumulatedArgs,B);if(x.stringValue!=null&&re!==void 0){let V=JSON.stringify(x.stringValue).slice(1,-1);Ut(this.accumulatedArgs,B,re+x.stringValue),w+=V;continue}let ee=Co(x);if(ee==null){if(re!==void 0||x.willContinue===!0)continue;Ut(this.accumulatedArgs,B,A?[]:{}),w+=this.emitContainer(B,A);continue}Ut(this.accumulatedArgs,B,ee.value),w+=this.emitNavigationTo(B,x,ee.json)}return this.jsonText+=w,{currentJSON:this.accumulatedArgs,textDelta:w}}finalize(){let f=JSON.stringify(this.accumulatedArgs);return{finalJSON:f,closingDelta:f.slice(this.jsonText.length)}}ensureRoot(){if(this.pathStack.length===0)return this.pathStack.push({segment:"",isArray:!1,childCount:0}),"{";return""}emitNavigationTo(f,w,x){let A="";if(this.stringOpen)A+='"',this.stringOpen=!1;A+=this.ensureRoot();let F=f.slice(0,-1),B=f[f.length-1],re=this.findCommonStackDepth(F);return A+=this.closeDownTo(re),A+=this.openDownTo(F,B),A+=this.emitLeaf(B,w,x),A}emitContainer(f,w){let x="";if(this.stringOpen)x+='"',this.stringOpen=!1;x+=this.ensureRoot();let A=this.findCommonStackDepth(f);return x+=this.closeDownTo(A),x+=this.openDownTo(f,w?0:""),x}findCommonStackDepth(f){let w=Math.min(this.pathStack.length-1,f.length),x=0;for(let A=0;A<w;A++)if(this.pathStack[A+1].segment===f[A])x++;else break;return x+1}closeDownTo(f){let w="";while(this.pathStack.length>f){let x=this.pathStack.pop();w+=x.isArray?"]":"}"}return w}openDownTo(f,w){let x="",A=this.pathStack.length-1;for(let F=A;F<f.length;F++){let B=f[F],re=this.pathStack[this.pathStack.length-1];if(re.childCount>0)x+=",";if(re.childCount++,typeof B==="string")x+=`${JSON.stringify(B)}:`;let ee=typeof(F+1<f.length?f[F+1]:w)==="number";x+=ee?"[":"{",this.pathStack.push({segment:B,isArray:ee,childCount:0})}return x}emitLeaf(f,w,x){let A="",F=this.pathStack[this.pathStack.length-1];if(F.childCount>0)A+=",";if(F.childCount++,typeof f==="string")A+=`${JSON.stringify(f)}:`;if(w.stringValue!=null&&w.willContinue)A+=x.slice(0,-1),this.stringOpen=!0;else A+=x;return A}};function bo(f){let w=[];for(let x of f.split(".")){let A=x.indexOf("[");if(A===-1)w.push(x);else{if(A>0)w.push(x.slice(0,A));for(let F of x.matchAll(/\[(\d+)\]/g))w.push(parseInt(F[1],10))}}return w}var To=Object.prototype.hasOwnProperty;function Tn(f,w){return To.call(f,w)}function nn(f,w,x){Object.defineProperty(f,w,{value:x,enumerable:!0,configurable:!0,writable:!0})}function _o(f,w){let x=f;for(let A of w){if(x==null||typeof x!=="object")return;let F=x;if(!Tn(F,A))return;x=F[A]}return x}function Ut(f,w,x){let A=f;for(let F=0;F<w.length-1;F++){let B=w[F],re=w[F+1];if(!Tn(A,B)||A[B]==null)nn(A,B,typeof re==="number"?[]:{});A=A[B]}nn(A,w[w.length-1],x)}function Co(f){let w=f.stringValue??f.numberValue??f.boolValue;if(w!=null)return{value:w,json:JSON.stringify(w)};if("nullValue"in f)return{value:null,json:"null"}}function on({finishReason:f,hasToolCalls:w}){switch(f){case"STOP":return w?"tool-calls":"stop";case"MAX_TOKENS":case"CONTINUATION":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";default:return"other"}}var wo=["HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT"],So=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,Io={"image/png":[/^gs:\/\/.*$/],"image/jpeg":[/^gs:\/\/.*$/],"image/webp":[/^gs:\/\/.*$/],"application/pdf":[/^gs:\/\/.*$/],"text/plain":[/^gs:\/\/.*$/]},Ct=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}constructor(w,x){this.specificationVersion="v4",this.modelId=w,this.config=x,this.generateId=x.generateId??C}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?.()??{}}static async prepareRequest({modelId:w,config:x,options:{prompt:A,maxOutputTokens:F,temperature:B,topP:re,topK:ee,frequencyPenalty:V,presencePenalty:pe,stopSequences:ce,responseFormat:Re,seed:Le,tools:Ce,toolChoice:Ee,reasoning:je,providerOptions:Ne,abortSignal:ye},isStreaming:ie=!1}){let be=[],ne=x.provider.includes("vertex")?["googleVertex","vertex"]:["google"],se;for(let at of ne)if(se=await h({provider:at,providerOptions:Ne,schema:Et}),se!=null)break;if(se==null&&!ne.includes("google"))se=await h({provider:"google",providerOptions:Ne,schema:Et});let Ue=x.provider.startsWith("google.vertex.");if(Ce?.some((at)=>at.type==="provider"&&at.id==="google.vertex_rag_store")&&!Ue)be.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${x.provider}).`});if(se?.streamFunctionCallArguments&&!Ue)be.push({type:"other",message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${x.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});if(se?.serviceTier&&Ue)be.push({type:"other",message:"'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo"});if((se?.sharedRequestType||se?.requestType)&&!Ue)be.push({type:"other",message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${x.provider}).`});let De=Ue&&(se?.sharedRequestType||se?.requestType)?{...se.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":se.sharedRequestType},...se.requestType&&{"X-Vertex-AI-LLM-Request-Type":se.requestType}}:void 0,qe=Ue?void 0:se?.serviceTier,We=se?.imageConfig;if(We!=null&&!Ue){let{personGeneration:at,prominentPeople:st,imageOutputOptions:wt,...St}=We,Ye=Object.entries({personGeneration:at,prominentPeople:st,imageOutputOptions:wt}).filter(([,Ge])=>Ge!=null).map(([Ge])=>`'imageConfig.${Ge}'`);if(Ye.length>0)be.push({type:"other",message:`${Ye.join(", ")} ${Ye.length===1?"is a Vertex AI option and is":"are Vertex AI options and are"} ignored with the current Google provider (${x.provider}).`}),We=St}let nt=w.toLowerCase().startsWith("gemma-"),Ke=!Ue&&So.test(w);if(Ke&&V!=null)be.push({type:"unsupported",feature:"frequencyPenalty"});if(Ke&&pe!=null)be.push({type:"unsupported",feature:"presencePenalty"});let{usesGemini3Features:Qe}=At(w),pt=Qe&&x.downloadToolResultFiles?.supportsGoogleCloudStorageUrls?Io:void 0,{contents:ze,systemInstruction:ot}=uo(x.downloadToolResultFiles?await co(A,{abortSignal:ye,maxBytes:x.downloadToolResultFiles.maxBytes,supportedUrls:pt}):A,{isGemmaModel:nt,isGemini3Model:Qe,onWarning:(at)=>be.push(at),providerOptionsNames:ne,supportsFunctionResponseParts:Qe,includeFunctionCallIds:!Ue,supportedFunctionResponseUrls:pt}),{tools:Ve,toolConfig:rt,toolWarnings:lt}=yo({tools:Ce,toolChoice:Ee,modelId:w,isVertexProvider:Ue}),dt=le({tools:Ce,providerToolNames:{"google.code_execution":"code_execution"}}),Fe=se?.thinkingConfig?.thinkingBudget!=null||se?.thinkingConfig?.thinkingLevel!=null?void 0:Ro({reasoning:je,modelId:w,warnings:be}),tt=se?.thinkingConfig||Fe?{...Fe,...se?.thinkingConfig}:void 0,Je=ie&&Ue?se?.streamFunctionCallArguments??!1:void 0,Be=se?.threshold,Pe=se?.safetySettings??(Be!=null?wo.map((at)=>({category:at,threshold:Be})):void 0),ut=rt||Je||se?.retrievalConfig?{...rt,...Je&&{functionCallingConfig:{...rt?.functionCallingConfig,streamFunctionCallArguments:!0}},...se?.retrievalConfig&&{retrievalConfig:se.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:F,temperature:B,topK:ee,topP:re,frequencyPenalty:Ke?void 0:V,presencePenalty:Ke?void 0:pe,stopSequences:ce,seed:Le,responseMimeType:Re?.type==="json"?"application/json":void 0,responseJsonSchema:Re?.type==="json"&&Re.schema!=null&&(se?.structuredOutputs??!0)?bn(Re.schema):void 0,...se?.audioTimestamp&&{audioTimestamp:se.audioTimestamp},responseModalities:se?.responseModalities,thinkingConfig:tt,...se?.mediaResolution&&{mediaResolution:se.mediaResolution},...We&&{imageConfig:We}},contents:ze,systemInstruction:nt?void 0:ot,safetySettings:Pe,tools:Ve,toolConfig:ut,cachedContent:se?.cachedContent,labels:se?.labels,serviceTier:qe,...se?.continuationToken!=null&&{continuationToken:se.continuationToken}},warnings:[...be,...lt],providerOptionsNames:ne,extraHeaders:De,toolNameMapping:dt}}async getArgs(w,{isStreaming:x=!1}={}){let{responseFormat:A,tools:F,toolChoice:B}=w,re;if(A?.type==="json"&&A.schema!=null&&F?.some((ee)=>ee.type==="function")&&/(^|\/)gemini-/i.test(this.modelId)&&(!At(this.modelId).usesGemini3Features||B?.type==="required"||B?.type==="tool")){let ee="json";for(let V=1;F.some((pe)=>pe.name===ee);V++)ee=`json_${V}`;re={type:"function",name:ee,description:A.description??"Respond with a JSON object.",inputSchema:A.schema}}return{...await f.prepareRequest({modelId:this.modelId,config:this.config,options:re==null?w:{...w,responseFormat:void 0,tools:[...F??[],re],toolChoice:B?.type==="tool"?B:B?.type==="none"?{type:"tool",toolName:re.name}:{type:"required"}},isStreaming:x}),jsonResponseToolName:re?.name}}static convertGenerateContentResponse({config:w,response:x,warnings:A,providerOptionsNames:F,toolNameMapping:B,jsonResponseToolName:re,initialPromptTokenCount:ee,groundingMetadataPerRequest:V}){let pe=(se)=>Object.fromEntries(F.map((Ue)=>[Ue,se])),ce=x.candidates?.[0],Re=x.promptFeedback?.blockReason,Le=an(Re)?Re:void 0,Ce=ce?.finishReason==null&&Le!=null,Ee=ce?.finishReason??Le,je=[],Ne=ce?.content?.parts??[],ye=x.usageMetadata,ie,be;for(let se of Ne)if("executableCode"in se&&se.executableCode?.code){let Ue=w.generateId();ie=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:B?.toCustomToolName("code_execution")??"code_execution",input:JSON.stringify(se.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in se&&se.codeExecutionResult)je.push({type:"tool-result",toolCallId:ie,toolName:B?.toCustomToolName("code_execution")??"code_execution",result:{outcome:se.codeExecutionResult.outcome,output:se.codeExecutionResult.output??""}});else if("text"in se&&se.text!=null){if(re!=null&&se.thought!==!0)continue;let Ue=se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature}):void 0;if(se.text.length===0){if(Ue!=null&&je.length>0){let De=je[je.length-1];De.providerMetadata=Ue}}else je.push({type:se.thought===!0?"reasoning":"text",text:se.text,providerMetadata:Ue})}else if("functionCall"in se&&se.functionCall.name!=null){if(se.functionCall.name===re){je.push({type:"text",text:typeof se.functionCall.args==="string"?se.functionCall.args:JSON.stringify(se.functionCall.args??{}),...se.thoughtSignature?{providerMetadata:pe({thoughtSignature:se.thoughtSignature})}:{}});continue}je.push({type:"tool-call",toolCallId:se.functionCall.id||w.generateId(),toolName:se.functionCall.name,input:JSON.stringify(se.functionCall.args??{}),providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature}):void 0})}else if("inlineData"in se){let Ue=se.thought===!0,De=!!se.thoughtSignature;je.push({type:Ue?"reasoning-file":"file",data:{type:"data",data:se.inlineData.data},mediaType:se.inlineData.mimeType,providerMetadata:De?pe({thoughtSignature:se.thoughtSignature}):void 0})}else if("toolCall"in se&&se.toolCall){let Ue=se.toolCall.id||w.generateId();be=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:`server:${se.toolCall.toolType}`,input:JSON.stringify(se.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature,serverToolCallId:Ue,serverToolType:se.toolCall.toolType}):pe({serverToolCallId:Ue,serverToolType:se.toolCall.toolType})})}else if("toolResponse"in se&&se.toolResponse){let Ue=be||se.toolResponse.id||w.generateId();je.push({type:"tool-result",toolCallId:Ue,toolName:`server:${se.toolResponse.toolType}`,result:se.toolResponse.response??{},providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature,serverToolCallId:Ue,serverToolType:se.toolResponse.toolType}):pe({serverToolCallId:Ue,serverToolType:se.toolResponse.toolType})}),be=void 0}let ne=sn({groundingMetadata:ce?.groundingMetadata,generateId:w.generateId})??[];for(let se of ne)je.push(se);return{content:je,finishReason:{unified:Ce?"content-filter":on({finishReason:Ee,hasToolCalls:je.some((se)=>se.type==="tool-call"&&!se.providerExecuted)}),raw:Ee},usage:Jt(ye),warnings:A,providerMetadata:pe({promptFeedback:x.promptFeedback??null,groundingMetadata:ce?.groundingMetadata??null,...V!=null?{groundingMetadataPerRequest:V}:{},urlContextMetadata:ce?.urlContextMetadata??null,safetyRatings:ce?.safetyRatings??null,usageMetadata:ye??null,finishMessage:ce?.finishMessage??null,serviceTier:ye?.serviceTier??null,...ce?.continuationToken!=null?{continuationToken:ce.continuationToken}:{},...ee!=null?{initialPromptTokenCount:ee}:{}}),response:{id:x.responseId??void 0}}}async doGenerate(w){let{args:x,warnings:A,providerOptionsNames:F,extraHeaders:B,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(w),V=d(this.config.headers?await _(this.config.headers):void 0,w.headers,B),pe=(ne)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:generateContent`,headers:V,body:ne,failedResponseHandler:Xe,successfulResponseHandler:p(In),abortSignal:w.abortSignal,fetch:this.config.fetch}),{responseHeaders:ce,value:Re,rawValue:Le}=await pe(x),Ce=[],Ee=[],je,Ne=Re.usageMetadata?.promptTokenCount,ye=!1;while(!0){let ne=Re.candidates?.[0];Ee.push(ne?.groundingMetadata??null);let se=ne?.finishReason==="CONTINUATION"?ne.continuationToken:void 0;if(je=jt(je,Re.usageMetadata??void 0),se==null)break;Ce.push(...f.convertGenerateContentResponse({config:this.config,response:Re,warnings:A,providerOptionsNames:F,toolNameMapping:re,jsonResponseToolName:ee}).content),ye=!0,{responseHeaders:ce,value:Re,rawValue:Le}=await pe({...x,continuationToken:se})}let ie=f.convertGenerateContentResponse({config:this.config,response:{...Re,usageMetadata:je},warnings:A,providerOptionsNames:F,toolNameMapping:re,jsonResponseToolName:ee,initialPromptTokenCount:ye?Ne:void 0,groundingMetadataPerRequest:ye?Ee:void 0}),be={...ie,content:[...Ce,...ie.content]};return{...be,request:{body:x},response:{...be.response,headers:ce,body:Le}}}async doStream(w){let{args:x,warnings:A,providerOptionsNames:F,extraHeaders:B,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(w,{isStreaming:!0}),V=(Be)=>Object.fromEntries(F.map((Pe)=>[Pe,Be])),pe=d(this.config.headers?await _(this.config.headers):void 0,w.headers,B),ce=(Be)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:streamGenerateContent?alt=sse`,headers:pe,body:Be,failedResponseHandler:Xe,successfulResponseHandler:D(Lo),abortSignal:w.abortSignal,fetch:this.config.fetch}),{responseHeaders:Re,value:Le}=await ce(x),Ce=[],Ee=null,je=to({stream:Le,getContinuationToken:(Be)=>{let Pe=Be.candidates?.[0];if(Pe?.groundingMetadata!=null)Ee=Pe.groundingMetadata;return Pe?.finishReason==="CONTINUATION"?Pe.continuationToken??void 0:void 0},continueStream:async(Be)=>{let{value:Pe}=await ce({...x,continuationToken:Be});return Ce.push(Ee),Ee=null,Pe}}),Ne={unified:"interrupted",raw:void 0},ye=void 0,ie=void 0,be=void 0,ne=null,se=null,Ue=null,De=null,qe=null,We=null,nt,Ke=this.config.generateId,Qe=!1,pt=!1,ze=null,ot=null,Ve=0,rt=new Set,lt,dt,Fe=[],tt=(Be)=>{let Pe=Fe.pop();if(Pe==null)return;let{finalJSON:ut,closingDelta:at}=Pe.accumulator.finalize();if(at.length>0)Be.enqueue({type:"tool-input-delta",id:Pe.toolCallId,delta:at,providerMetadata:Pe.providerMetadata});Be.enqueue({type:"tool-input-end",id:Pe.toolCallId,providerMetadata:Pe.providerMetadata}),Be.enqueue({type:"tool-call",toolCallId:Pe.toolCallId,toolName:Pe.toolName,input:ut,providerMetadata:Pe.providerMetadata}),Qe=!0},Je={stream:je.pipeThrough(new TransformStream({start(Be){Be.enqueue({type:"stream-start",warnings:A})},transform(Be,Pe){if("type"in Be){Ne={unified:"interrupted",raw:void 0};return}if(w.includeRawChunks)Pe.enqueue({type:"raw",rawValue:Be.rawValue});if(!Be.success){if(Ne.unified==="interrupted")Ne={unified:"error",raw:void 0};Pe.enqueue({type:"error",error:Be.error});return}let ut=Be.value;if(ut.error!=null){Ne={unified:"error",raw:void 0};let Ye=ut.error;Pe.enqueue({type:"error",error:xe({message:Ye.message,type:Ye.status,code:Ye.code??void 0,statusCode:Ye.code??void 0,isRetryable:Ye.code!=null&&(Ye.code===408||Ye.code===409||Ye.code===429||Ye.code>=500),data:Ye})});return}if(!pt&&ut.responseId!=null)pt=!0,Pe.enqueue({type:"response-metadata",id:ut.responseId});let at=ut.usageMetadata;if(at!=null)ye=at;if(ut.promptFeedback!=null&&nt==null){if(ne=ut.promptFeedback,an(ut.promptFeedback.blockReason))nt=ut.promptFeedback.blockReason,Ne={unified:"content-filter",raw:nt}}let st=ut.candidates?.[0];if(st!=null){if(st.groundingMetadata!=null)se=st.groundingMetadata;if(st.urlContextMetadata!=null)Ue=st.urlContextMetadata;if(st.safetyRatings!=null)De=st.safetyRatings;if(st.finishMessage!=null)qe=st.finishMessage;if(st.continuationToken!=null)We=st.continuationToken}if(nt!=null||st==null)return;let wt=st.content,St=sn({groundingMetadata:st.groundingMetadata,generateId:Ke});if(St!=null){for(let Ye of St)if(Ye.sourceType==="url"&&!rt.has(Ye.url))rt.add(Ye.url),Pe.enqueue(Ye)}if(wt!=null){let Ye=wt.parts??[];for(let Ge of Ye)if("executableCode"in Ge&&Ge.executableCode?.code){let $e=Ke();lt=$e,Pe.enqueue({type:"tool-call",toolCallId:$e,toolName:re.toCustomToolName("code_execution"),input:JSON.stringify(Ge.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in Ge&&Ge.codeExecutionResult){let $e=lt;if($e)Pe.enqueue({type:"tool-result",toolCallId:$e,toolName:re.toCustomToolName("code_execution"),result:{outcome:Ge.codeExecutionResult.outcome,output:Ge.codeExecutionResult.output??""}})}else if("text"in Ge&&Ge.text!=null){let $e=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0;if(Ge.text.length===0){if($e!=null&&ze!==null)Pe.enqueue({type:"text-delta",id:ze,delta:"",providerMetadata:$e})}else if(Ge.thought===!0){if(ze!==null)Pe.enqueue({type:"text-end",id:ze}),ze=null;if(ot===null)ot=String(Ve++),Pe.enqueue({type:"reasoning-start",id:ot,providerMetadata:$e});Pe.enqueue({type:"reasoning-delta",id:ot,delta:Ge.text,providerMetadata:$e})}else{if(ot!==null)Pe.enqueue({type:"reasoning-end",id:ot}),ot=null;if(ze===null)ze=String(Ve++),Pe.enqueue({type:"text-start",id:ze,providerMetadata:$e});Pe.enqueue({type:"text-delta",id:ze,delta:Ge.text,providerMetadata:$e})}}else if("inlineData"in Ge){if(ze!==null)Pe.enqueue({type:"text-end",id:ze}),ze=null;if(ot!==null)Pe.enqueue({type:"reasoning-end",id:ot}),ot=null;let $e=Ge.thought===!0,yt=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0;Pe.enqueue({type:$e?"reasoning-file":"file",mediaType:Ge.inlineData.mimeType,data:{type:"data",data:Ge.inlineData.data},providerMetadata:yt})}else if("toolCall"in Ge&&Ge.toolCall){let $e=Ge.toolCall.id||Ke();dt=$e;let yt=V({...Ge.thoughtSignature?{thoughtSignature:Ge.thoughtSignature}:{},serverToolCallId:$e,serverToolType:Ge.toolCall.toolType});Pe.enqueue({type:"tool-call",toolCallId:$e,toolName:`server:${Ge.toolCall.toolType}`,input:JSON.stringify(Ge.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:yt})}else if("toolResponse"in Ge&&Ge.toolResponse){let $e=dt||Ge.toolResponse.id||Ke(),yt=V({...Ge.thoughtSignature?{thoughtSignature:Ge.thoughtSignature}:{},serverToolCallId:$e,serverToolType:Ge.toolResponse.toolType});Pe.enqueue({type:"tool-result",toolCallId:$e,toolName:`server:${Ge.toolResponse.toolType}`,result:Ge.toolResponse.response??{},providerMetadata:yt}),dt=void 0}for(let Ge of Ye){if(!("functionCall"in Ge))continue;let $e=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0,yt=Ge.functionCall.partialArgs!=null||Ge.functionCall.name!=null&&Ge.functionCall.willContinue===!0,Hn=Ge.functionCall.name==null&&Ge.functionCall.args==null&&Ge.functionCall.partialArgs==null&&Ge.functionCall.willContinue==null,Vn=Ge.functionCall.name!=null&&Ge.functionCall.args!=null&&Ge.functionCall.partialArgs==null,Wn=Ge.functionCall.name!=null&&Ge.functionCall.args==null&&Ge.functionCall.partialArgs==null&&Ge.functionCall.willContinue!==!0;if(yt){if(Ge.functionCall.name!=null){let ct=Ge.functionCall.id||Ke(),gt=new vo;if(Fe.push({toolCallId:ct,toolName:Ge.functionCall.name,accumulator:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-start",id:ct,toolName:Ge.functionCall.name,providerMetadata:$e}),Ge.functionCall.partialArgs!=null){let ft=Ge.functionCall.partialArgs,{textDelta:It}=gt.processPartialArgs(ft);if(It.length>0)Pe.enqueue({type:"tool-input-delta",id:ct,delta:It,providerMetadata:$e});if(Ge.functionCall.willContinue!==!0&&ft.every((Kn)=>Kn.willContinue!==!0))tt(Pe)}}else if(Ge.functionCall.partialArgs!=null&&Fe.length>0){let ct=Fe[Fe.length-1],gt=Ge.functionCall.partialArgs,{textDelta:ft}=ct.accumulator.processPartialArgs(gt);if(ft.length>0)Pe.enqueue({type:"tool-input-delta",id:ct.toolCallId,delta:ft,providerMetadata:$e});if(Ge.functionCall.willContinue!==!0&&gt.every((It)=>It.willContinue!==!0))tt(Pe)}}else if(Hn&&Fe.length>0)tt(Pe);else if(Vn){let ct=Ge.functionCall.id||Ke(),gt=Ge.functionCall.name,ft=typeof Ge.functionCall.args==="string"?Ge.functionCall.args:JSON.stringify(Ge.functionCall.args??{});Pe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-delta",id:ct,delta:ft,providerMetadata:$e}),Pe.enqueue({type:"tool-input-end",id:ct,providerMetadata:$e}),Pe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:ft,providerMetadata:$e}),Qe=!0}else if(Wn){let ct=Ge.functionCall.id||Ke(),gt=Ge.functionCall.name;Pe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-end",id:ct,providerMetadata:$e}),Pe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:"{}",providerMetadata:$e}),Qe=!0}}}if(st.finishReason==="CONTINUATION"){if(ie==null)be=ye?.promptTokenCount;ie=jt(ie,ye),ye=void 0}if(st.finishReason!=null)Ne={unified:on({finishReason:st.finishReason,hasToolCalls:Qe}),raw:st.finishReason}},flush(Be){if(ye=jt(ie,ye),ze!==null)Be.enqueue({type:"text-end",id:ze});if(ot!==null)Be.enqueue({type:"reasoning-end",id:ot});Be.enqueue({type:"finish",finishReason:Ne,usage:Jt(ye),providerMetadata:V({promptFeedback:ne,groundingMetadata:se,...Ce.length>0?{groundingMetadataPerRequest:[...Ce,Ee]}:{},urlContextMetadata:Ue,safetyRatings:De,usageMetadata:ye??null,finishMessage:qe,serviceTier:ye?.serviceTier??null,...We!=null&&(Ne.raw==="MAX_TOKENS"||Ne.raw==="CONTINUATION")?{continuationToken:We}:{},...be!=null?{initialPromptTokenCount:be}:{}})})}})),response:{headers:Re},request:{body:x}};return{...Je,stream:ee==null?Je.stream:Je.stream.pipeThrough(Yt(ee))}}};function ko(){return 65536}function xo(f){let w=f.toLowerCase();if(w.includes("2.5-pro")||w.includes("gemini-3-pro-image"))return 32768;return 24576}function Ro({reasoning:f,modelId:w,warnings:x}){if(!W(f))return;if(At(w).usesGemini3Features&&!w.includes("gemini-3-pro-image"))return Oo({reasoning:f,modelId:w,warnings:x});return Eo({reasoning:f,modelId:w,warnings:x})}function Oo({reasoning:f,modelId:w,warnings:x}){let A=Mo(w);if(f==="none")return{thinkingLevel:A};let F=Se({reasoning:f,effortMap:{minimal:A,low:"low",medium:"medium",high:"high",xhigh:"high",max:"high"},warnings:x});if(F==null)return;return{thinkingLevel:F}}function Mo(f){let w=/(?:^|[/.])(gemini-[^/]*)$/i.exec(f)?.[1].toLowerCase();if(w==="gemini-flash-latest")return"low";let x=/^gemini-(\d+)(?:\.\d+)?-pro(?:$|-)/.exec(w??"");if(Number(x?.[1])>=3)return"low";let A=/^gemini-(\d+)\.(\d+)-flash(?:$|-(?!lite(?:-|$)))/.exec(w??"");if(A==null)return"minimal";let F=Number(A[1]),B=Number(A[2]);return F>3||F===3&&B>=7?"low":"minimal"}function Eo({reasoning:f,modelId:w,warnings:x}){if(f==="none")return{thinkingBudget:0};let A=it({reasoning:f,maxOutputTokens:ko(),maxReasoningBudget:xo(w),minReasoningBudget:0,warnings:x});if(A==null)return;return{thinkingBudget:A}}function sn({groundingMetadata:f,generateId:w}){if(!f?.groundingChunks)return;let x=[];for(let A of f.groundingChunks)if(A.web!=null)x.push({type:"source",sourceType:"url",id:w(),url:A.web.uri,title:A.web.title??void 0});else if(A.image!=null)x.push({type:"source",sourceType:"url",id:w(),url:A.image.sourceUri,title:A.image.title??void 0});else if(A.retrievedContext!=null){let F=A.retrievedContext.uri,B=A.retrievedContext.fileSearchStore;if(F&&(F.startsWith("http://")||F.startsWith("https://")))x.push({type:"source",sourceType:"url",id:w(),url:F,title:A.retrievedContext.title??void 0});else if(F){let re=A.retrievedContext.title??"Unknown Document",ee="application/octet-stream",V=void 0;if(F.endsWith(".pdf"))ee="application/pdf",V=F.split("/").pop();else if(F.endsWith(".txt"))ee="text/plain",V=F.split("/").pop();else if(F.endsWith(".docx"))ee="application/vnd.openxmlformats-officedocument.wordprocessingml.document",V=F.split("/").pop();else if(F.endsWith(".doc"))ee="application/msword",V=F.split("/").pop();else if(F.match(/\.(md|markdown)$/))ee="text/markdown",V=F.split("/").pop();else V=F.split("/").pop();x.push({type:"source",sourceType:"document",id:w(),mediaType:ee,title:re,filename:V})}else if(B){let re=A.retrievedContext.title??"Unknown Document";x.push({type:"source",sourceType:"document",id:w(),mediaType:"application/octet-stream",title:re,filename:B.split("/").pop()})}}else if(A.maps!=null){if(A.maps.uri)x.push({type:"source",sourceType:"url",id:w(),url:A.maps.uri,title:A.maps.title??void 0})}return x.length>0?x:void 0}var _n=()=>t({webSearchQueries:o(e()).nullish(),imageSearchQueries:o(e()).nullish(),retrievalQueries:o(e()).nullish(),searchEntryPoint:t({renderedContent:e()}).nullish(),groundingChunks:o(t({web:t({uri:e(),title:e().nullish()}).nullish(),image:t({sourceUri:e(),imageUri:e(),title:e().nullish(),domain:e().nullish()}).nullish(),retrievedContext:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),fileSearchStore:e().nullish(),customMetadata:o(t({key:e(),stringValue:e().nullish(),numericValue:r().nullish(),stringListValue:t({values:o(e()).nullish()}).nullish()})).nullish()}).nullish(),maps:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),placeId:e().nullish()}).nullish()})).nullish(),groundingSupports:o(t({segment:t({startIndex:r().nullish(),endIndex:r().nullish(),text:e().nullish()}).nullish(),segment_text:e().nullish(),groundingChunkIndices:o(r()).nullish(),supportChunkIndices:o(r()).nullish(),confidenceScores:o(r()).nullish(),confidenceScore:o(r()).nullish()})).nullish(),retrievalMetadata:l([t({webDynamicRetrievalScore:r()}),t({})]).nullish()}),Ao=()=>t({jsonPath:e(),stringValue:e().nullish(),numberValue:r().nullish(),boolValue:c().nullish(),nullValue:v().nullish(),willContinue:c().nullish()}),Cn=()=>t({parts:o(l([t({functionCall:t({id:e().nullish(),name:e().nullish(),args:v().nullish(),partialArgs:o(Ao()).nullish(),willContinue:c().nullish()}),thoughtSignature:e().nullish()}),t({inlineData:t({mimeType:e(),data:e()}),thought:c().nullish(),thoughtSignature:e().nullish()}),t({toolCall:t({toolType:e(),args:v().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({toolResponse:t({toolType:e(),response:v().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({executableCode:t({language:e(),code:e()}).nullish(),codeExecutionResult:t({outcome:e(),output:e().nullish()}).nullish(),text:e().nullish(),thought:c().nullish(),thoughtSignature:e().nullish()})])).nullish()}),Lt=()=>t({category:e().nullish(),probability:e().nullish(),probabilityScore:r().nullish(),severity:e().nullish(),severityScore:r().nullish(),blocked:c().nullish()}),xt=()=>o(t({modality:e(),tokenCount:r()}).loose()).nullish(),wn=()=>t({cachedContentTokenCount:r().nullish(),thoughtsTokenCount:r().nullish(),promptTokenCount:r().nullish(),candidatesTokenCount:r().nullish(),toolUsePromptTokenCount:r().nullish(),totalTokenCount:r().nullish(),trafficType:e().nullish(),serviceTier:e().nullish(),promptTokensDetails:xt(),cacheTokensDetails:xt(),candidatesTokensDetails:xt(),toolUsePromptTokensDetails:xt()}).loose(),Sn=()=>t({urlMetadata:o(t({retrievedUrl:e(),urlRetrievalStatus:e()})).nullish()}),In=a(()=>s(t({responseId:e().nullish(),candidates:o(t({content:Cn().nullish().or(t({}).strict()),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(Lt()).nullish(),groundingMetadata:_n().nullish(),urlContextMetadata:Sn().nullish()})).nullish(),usageMetadata:wn().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(Lt()).nullish()}).nullish()}))),Lo=a(()=>s(t({error:fn().nullish(),responseId:e().nullish(),candidates:o(t({content:Cn().nullish(),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(Lt()).nullish(),groundingMetadata:_n().nullish(),urlContextMetadata:Sn().nullish()})).nullish(),usageMetadata:wn().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(Lt()).nullish()}).nullish()})));function an(f){return f!=null&&f!==""&&f!=="BLOCK_REASON_UNSPECIFIED"&&f!=="BLOCKED_REASON_UNSPECIFIED"}var jo=()=>U({searchTypes:t({webSearch:t({}).optional(),imageSearch:t({}).optional()}).optional(),timeRangeFilter:t({startTime:e(),endTime:e()}).optional()}),Uo=S({id:"google.google_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),kn=a(()=>s(t({googleSearch:jo().optional()}))),No=2147483648,Go=20000000,Do=new Set(["text","reasoning","source","tool-call","tool-result"]);function Po(f){for(let w of f){let x=w.type;if(x!=="text"&&x!=="image")throw new u({functionality:`batch request type: ${x}`,message:`The Google Batch API does not support batch requests with type "${x}".`})}}var Bt=()=>t({code:l([r(),e()]).nullish(),message:e().nullish(),status:e().nullish()}),qo=()=>t({requestCount:l([e(),r()]).nullish(),successfulRequestCount:l([e(),r()]).nullish(),failedRequestCount:l([e(),r()]).nullish(),pendingRequestCount:l([e(),r()]).nullish()}),rn=()=>t({responsesFile:e().nullish(),inlinedResponses:t({inlinedResponses:o(t({metadata:t({key:e()}),response:v().nullish(),error:Bt().nullish()}))}).nullish()}),xn=()=>t({name:e(),metadata:t({state:e().nullish(),createTime:e().nullish(),batchStats:qo().nullish(),output:rn().nullish()}).nullish(),done:c().nullish(),error:Bt().nullish(),response:rn().nullish()}),Nt=a(()=>s(xn())),$o=a(()=>s(t({operations:o(xn()).nullish(),nextPageToken:e().nullish()}))),Fo=a(()=>s(t({}))),Bo=a(()=>s(t({file:t({name:e(),expirationTime:e().nullish()})}))),Ho=a(()=>s(t({key:e(),response:v().nullish(),error:Bt().nullish()}))),Vo=a(()=>s(t({candidates:o(v()).nullish(),promptFeedback:t({blockReason:e().nullish()}).nullish()}))),Wo=class{constructor(f){this.specificationVersion="v4",this.provider=f.provider,this.batchConfig=f.config,this.supportedUrls=f.supportedUrls,this.batchGenerateId=f.config.generateId??C,this.maxLineBytes=f.maxLineBytes}async doStartBatch(f){Po(f.requests);let w=Yo(f.requests),x=[],A=`ai-sdk-batch-${this.batchGenerateId()}`,F=[],B={batch:{displayName:A,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{requests:{requests:F}}}},re=new TextEncoder,ee=re.encode(JSON.stringify(B)).byteLength,V;for(let je of f.requests){let Ne=je.type==="text"?await Ct.prepareRequest({modelId:je.modelId,config:this.batchConfig,options:je.options}):await this.prepareImageRequest(je),ye={request:Ne.args,metadata:{key:je.id}};if(V==null){let ie=re.encode(JSON.stringify(ye)).byteLength,be=ee+ie+(F.length>0?1:0);if(be<Go)F.push(ye),ee=be;else{V=[];for(let ne of F)V.push(JSON.stringify({key:ne.metadata.key,request:ne.request}),`
7
- `);F.length=0,V.push(JSON.stringify({key:je.id,request:Ne.args}),`
6
+ `})}if(Ce&&ee!=null){let ye=Array.from(new Set(Ee));ee({type:"other",message:`Replayed ${Ee.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${ye.map((ie)=>`\`${ie}\``).join(", ")}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`})}return{systemInstruction:x.length>0&&!B?{parts:x}:void 0,contents:A}}async function co(f,{abortSignal:w,maxBytes:x,supportedUrls:A={}}){let N=[];for(let B of f){if(B.role==="assistant"){let re=[];for(let ee of B.content)re.push(ee.type==="tool-result"?{...ee,output:await Xt(ee.output,{abortSignal:w,maxBytes:x,supportedUrls:A})}:ee);N.push({...B,content:re});continue}if(B.role==="tool"){let re=[];for(let ee of B.content){if(ee.type!=="tool-result"){re.push(ee);continue}re.push({...ee,output:await Xt(ee.output,{abortSignal:w,maxBytes:x,supportedUrls:A})})}N.push({...B,content:re});continue}N.push(B)}return N}async function Xt(f,{abortSignal:w,maxBytes:x,supportedUrls:A}){if(f.type!=="content")return f;let N=[];for(let B of f.value){if(B.type!=="file"||B.data.type!=="url"){N.push(B);continue}if(Qe({url:B.data.url.toString(),mediaType:B.mediaType,supportedUrls:A})){N.push(B);continue}let re=await Me(B.data.url.toString(),{abortSignal:w,maxBytes:x}),ee=new Uint8Array(await re.arrayBuffer()),V=Te({data:ee,topLevelType:"image"});N.push({...B,data:{type:"data",data:ee},mediaType:V??(re.type&&!K(B.mediaType)?re.type:B.mediaType)})}return{...f,value:N}}function bn(f){let{const:w,properties:x,items:A,additionalProperties:N,anyOf:B,oneOf:re,...ee}=f;return{...ee,...w!==void 0?{enum:[w]}:{},...x!=null?{properties:Qt(x)}:{},...A!=null?{items:Array.isArray(A)?A.map(bt):bt(A)}:{},...N!=null?{additionalProperties:typeof N==="boolean"?N:bt(N)}:{},...B!=null?{anyOf:B.map(bt)}:{},...re!=null?{oneOf:re.map(bt)}:{},...ee.$defs!=null?{$defs:Qt(ee.$defs)}:{}}}function Qt(f){return Object.fromEntries(Object.entries(f).map(([w,x])=>[w,bt(x)]))}function bt(f){return typeof f==="boolean"?f:bn(f)}var Et=a(()=>s(t({responseModalities:o(i(["TEXT","IMAGE","AUDIO"])).optional(),thinkingConfig:t({thinkingBudget:r().optional(),includeThoughts:c().optional(),thinkingLevel:i(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:e().optional(),structuredOutputs:c().optional(),safetySettings:o(t({category:i(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:i(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:i(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:c().optional(),labels:y(e(),e()).optional(),mediaResolution:i(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:t({aspectRatio:i(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).optional(),imageSize:i(["1K","2K","4K","512"]).optional(),personGeneration:i(["PERSON_GENERATION_UNSPECIFIED","ALLOW_ALL","ALLOW_ADULT","ALLOW_NONE"]).optional(),prominentPeople:i(["PROMINENT_PEOPLE_UNSPECIFIED","ALLOW_PROMINENT_PEOPLE","BLOCK_PROMINENT_PEOPLE"]).optional(),imageOutputOptions:t({mimeType:i(["image/jpeg","image/png"]).optional(),compressionQuality:r().optional()}).optional()}).optional(),retrievalConfig:t({latLng:t({latitude:r(),longitude:r()}).optional()}).optional(),streamFunctionCallArguments:c().optional(),serviceTier:i(["standard","flex","priority"]).optional(),continuationToken:e().optional(),sharedRequestType:i(["priority","flex","standard"]).optional(),requestType:i(["shared"]).optional()}))),po=/(^|[/.])gemini-1(?:[.-]|$)/i,go=/(^|[/.])gemini-2(?:[.-]|$)/i,ho=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,mo=/(^|[/.])gemini-/i;function fo(f){return po.test(f)||/(^|[/.])gemini-pro(?:-vision)?$/i.test(f)||/(^|[/.])gemini-robotics-er-1\.5(?:[.-]|$)/i.test(f)}function At(f){let w=mo.test(f),x=go.test(f),A=fo(f),N=w&&!(A||x);return{supportsGemini2Tools:w&&!A||f.toLowerCase().includes("nano-banana"),supportsFileSearch:ho.test(f)||N,usesGemini3Features:N}}function yo({tools:f,toolChoice:w,modelId:x,isVertexProvider:A=!1}){f=f?.length?f:void 0;let N=[],{supportsGemini2Tools:B,supportsFileSearch:re,usesGemini3Features:ee}=At(x);if(f==null)return{tools:void 0,toolConfig:void 0,toolWarnings:N};let V=f.some((Ce)=>Ce.type==="function"),pe=f.some((Ce)=>Ce.type==="provider");if(V&&pe&&!ee)N.push({type:"unsupported",feature:"combination of function and provider-defined tools"});if(pe){let Ce=[];if(f.filter((Ee)=>Ee.type==="provider").forEach((Ee)=>{switch(Ee.id){case"google.google_search":if(B)Ce.push({googleSearch:{...Ee.args}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":if(B)Ce.push({enterpriseWebSearch:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":if(B)Ce.push({urlContext:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(B)Ce.push({codeExecution:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The code execution tool is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":if(re)Ce.push({fileSearch:{...Ee.args}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":if(B)Ce.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:Ee.args.ragCorpus},similarity_top_k:Ee.args.topK}}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":if(B)Ce.push({googleMaps:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`})}}),V&&ee&&Ce.length>0){let Ee=[];for(let Ne of f)if(Ne.type==="function")Ee.push(Zt(Ne));let je={functionCallingConfig:{mode:"VALIDATED"},...!A&&{includeServerSideToolInvocations:!0}};if(w!=null)switch(w.type){case"auto":break;case"none":je.functionCallingConfig={mode:"NONE"};break;case"required":je.functionCallingConfig={mode:"ANY"};break;case"tool":je.functionCallingConfig={mode:"ANY",allowedFunctionNames:[w.toolName]}}return{tools:[...Ce,{functionDeclarations:Ee}],toolConfig:je,toolWarnings:N}}return{tools:Ce.length>0?Ce:void 0,toolConfig:void 0,toolWarnings:N}}let ce=[],Re=!1;for(let Ce of f)switch(Ce.type){case"function":if(ce.push(Zt(Ce)),Ce.strict===!0)Re=!0;break;default:N.push({type:"unsupported",feature:`function tool ${Ce.name}`})}if(w==null)return{tools:[{functionDeclarations:ce}],toolConfig:Re?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:N};let Le=w.type;switch(Le){case"auto":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:Re?"VALIDATED":"AUTO"}},toolWarnings:N};case"none":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:N};case"required":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:N};case"tool":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[w.toolName]}},toolWarnings:N};default:throw new u({functionality:`tool choice type: ${Le}`})}}function Zt(f){return{name:f.name,description:f.description??"",parametersJsonSchema:f.inputSchema}}var vo=class{constructor(){this.accumulatedArgs={},this.jsonText="",this.pathStack=[],this.stringOpen=!1}processPartialArgs(f){let w="";for(let x of f){let A=x.jsonPath.endsWith("[]"),N=(A?x.jsonPath.slice(0,-2):x.jsonPath).replace(/^\$\./,"");if(!N||N==="$")continue;let B=bo(N),re=_o(this.accumulatedArgs,B);if(x.stringValue!=null&&re!==void 0){let V=JSON.stringify(x.stringValue).slice(1,-1);Ut(this.accumulatedArgs,B,re+x.stringValue),w+=V;continue}let ee=Co(x);if(ee==null){if(re!==void 0||x.willContinue===!0)continue;Ut(this.accumulatedArgs,B,A?[]:{}),w+=this.emitContainer(B,A);continue}Ut(this.accumulatedArgs,B,ee.value),w+=this.emitNavigationTo(B,x,ee.json)}return this.jsonText+=w,{currentJSON:this.accumulatedArgs,textDelta:w}}finalize(){let f=JSON.stringify(this.accumulatedArgs);return{finalJSON:f,closingDelta:f.slice(this.jsonText.length)}}ensureRoot(){if(this.pathStack.length===0)return this.pathStack.push({segment:"",isArray:!1,childCount:0}),"{";return""}emitNavigationTo(f,w,x){let A="";if(this.stringOpen)A+='"',this.stringOpen=!1;A+=this.ensureRoot();let N=f.slice(0,-1),B=f[f.length-1],re=this.findCommonStackDepth(N);return A+=this.closeDownTo(re),A+=this.openDownTo(N,B),A+=this.emitLeaf(B,w,x),A}emitContainer(f,w){let x="";if(this.stringOpen)x+='"',this.stringOpen=!1;x+=this.ensureRoot();let A=this.findCommonStackDepth(f);return x+=this.closeDownTo(A),x+=this.openDownTo(f,w?0:""),x}findCommonStackDepth(f){let w=Math.min(this.pathStack.length-1,f.length),x=0;for(let A=0;A<w;A++)if(this.pathStack[A+1].segment===f[A])x++;else break;return x+1}closeDownTo(f){let w="";while(this.pathStack.length>f){let x=this.pathStack.pop();w+=x.isArray?"]":"}"}return w}openDownTo(f,w){let x="",A=this.pathStack.length-1;for(let N=A;N<f.length;N++){let B=f[N],re=this.pathStack[this.pathStack.length-1];if(re.childCount>0)x+=",";if(re.childCount++,typeof B==="string")x+=`${JSON.stringify(B)}:`;let ee=typeof(N+1<f.length?f[N+1]:w)==="number";x+=ee?"[":"{",this.pathStack.push({segment:B,isArray:ee,childCount:0})}return x}emitLeaf(f,w,x){let A="",N=this.pathStack[this.pathStack.length-1];if(N.childCount>0)A+=",";if(N.childCount++,typeof f==="string")A+=`${JSON.stringify(f)}:`;if(w.stringValue!=null&&w.willContinue)A+=x.slice(0,-1),this.stringOpen=!0;else A+=x;return A}};function bo(f){let w=[];for(let x of f.split(".")){let A=x.indexOf("[");if(A===-1)w.push(x);else{if(A>0)w.push(x.slice(0,A));for(let N of x.matchAll(/\[(\d+)\]/g))w.push(parseInt(N[1],10))}}return w}var To=Object.prototype.hasOwnProperty;function Tn(f,w){return To.call(f,w)}function en(f,w,x){Object.defineProperty(f,w,{value:x,enumerable:!0,configurable:!0,writable:!0})}function _o(f,w){let x=f;for(let A of w){if(x==null||typeof x!=="object")return;let N=x;if(!Tn(N,A))return;x=N[A]}return x}function Ut(f,w,x){let A=f;for(let N=0;N<w.length-1;N++){let B=w[N],re=w[N+1];if(!Tn(A,B)||A[B]==null)en(A,B,typeof re==="number"?[]:{});A=A[B]}en(A,w[w.length-1],x)}function Co(f){let w=f.stringValue??f.numberValue??f.boolValue;if(w!=null)return{value:w,json:JSON.stringify(w)};if("nullValue"in f)return{value:null,json:"null"}}function nn({finishReason:f,hasToolCalls:w}){switch(f){case"STOP":return w?"tool-calls":"stop";case"MAX_TOKENS":case"CONTINUATION":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";default:return"other"}}var wo=["HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT"],So=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,Io={"image/png":[/^gs:\/\/.*$/],"image/jpeg":[/^gs:\/\/.*$/],"image/webp":[/^gs:\/\/.*$/],"application/pdf":[/^gs:\/\/.*$/],"text/plain":[/^gs:\/\/.*$/]},Ct=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}constructor(w,x){this.specificationVersion="v4",this.modelId=w,this.config=x,this.generateId=x.generateId??C}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?.()??{}}static async prepareRequest({modelId:w,config:x,options:{prompt:A,maxOutputTokens:N,temperature:B,topP:re,topK:ee,frequencyPenalty:V,presencePenalty:pe,stopSequences:ce,responseFormat:Re,seed:Le,tools:Ce,toolChoice:Ee,reasoning:je,providerOptions:Ne,abortSignal:ye},isStreaming:ie=!1}){let be=[],ne=x.provider.includes("vertex")?["googleVertex","vertex"]:["google"],se;for(let it of ne)if(se=await h({provider:it,providerOptions:Ne,schema:Et}),se!=null)break;if(se==null&&!ne.includes("google"))se=await h({provider:"google",providerOptions:Ne,schema:Et});let Ue=x.provider.startsWith("google.vertex.");if(Ce?.some((it)=>it.type==="provider"&&it.id==="google.vertex_rag_store")&&!Ue)be.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${x.provider}).`});if(se?.streamFunctionCallArguments&&!Ue)be.push({type:"other",message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${x.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});if(se?.serviceTier&&Ue)be.push({type:"other",message:"'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo"});if((se?.sharedRequestType||se?.requestType)&&!Ue)be.push({type:"other",message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${x.provider}).`});let De=Ue&&(se?.sharedRequestType||se?.requestType)?{...se.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":se.sharedRequestType},...se.requestType&&{"X-Vertex-AI-LLM-Request-Type":se.requestType}}:void 0,qe=Ue?void 0:se?.serviceTier,Ve=se?.imageConfig;if(Ve!=null&&!Ue){let{personGeneration:it,prominentPeople:ot,imageOutputOptions:wt,...St}=Ve,Ye=Object.entries({personGeneration:it,prominentPeople:ot,imageOutputOptions:wt}).filter(([,Ge])=>Ge!=null).map(([Ge])=>`'imageConfig.${Ge}'`);if(Ye.length>0)be.push({type:"other",message:`${Ye.join(", ")} ${Ye.length===1?"is a Vertex AI option and is":"are Vertex AI options and are"} ignored with the current Google provider (${x.provider}).`}),Ve=St}let tt=w.toLowerCase().startsWith("gemma-"),We=!Ue&&So.test(w);if(We&&V!=null)be.push({type:"unsupported",feature:"frequencyPenalty"});if(We&&pe!=null)be.push({type:"unsupported",feature:"presencePenalty"});let{usesGemini3Features:Ze}=At(w),pt=Ze&&x.downloadToolResultFiles?.supportsGoogleCloudStorageUrls?Io:void 0,{contents:ze,systemInstruction:nt}=uo(x.downloadToolResultFiles?await co(A,{abortSignal:ye,maxBytes:x.downloadToolResultFiles.maxBytes,supportedUrls:pt}):A,{isGemmaModel:tt,isGemini3Model:Ze,onWarning:(it)=>be.push(it),providerOptionsNames:ne,supportsFunctionResponseParts:Ze,includeFunctionCallIds:!Ue,supportedFunctionResponseUrls:pt}),{tools:He,toolConfig:st,toolWarnings:at}=yo({tools:Ce,toolChoice:Ee,modelId:w,isVertexProvider:Ue}),dt=le({tools:Ce,providerToolNames:{"google.code_execution":"code_execution"}}),Fe=se?.thinkingConfig?.thinkingBudget!=null||se?.thinkingConfig?.thinkingLevel!=null?void 0:Ro({reasoning:je,modelId:w,warnings:be}),et=se?.thinkingConfig||Fe?{...Fe,...se?.thinkingConfig}:void 0,Je=ie&&Ue?se?.streamFunctionCallArguments??!1:void 0,Be=se?.threshold,Pe=se?.safetySettings??(Be!=null?wo.map((it)=>({category:it,threshold:Be})):void 0),lt=st||Je||se?.retrievalConfig?{...st,...Je&&{functionCallingConfig:{...st?.functionCallingConfig,streamFunctionCallArguments:!0}},...se?.retrievalConfig&&{retrievalConfig:se.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:N,temperature:B,topK:ee,topP:re,frequencyPenalty:We?void 0:V,presencePenalty:We?void 0:pe,stopSequences:ce,seed:Le,responseMimeType:Re?.type==="json"?"application/json":void 0,responseJsonSchema:Re?.type==="json"&&Re.schema!=null&&(se?.structuredOutputs??!0)?bn(Re.schema):void 0,...se?.audioTimestamp&&{audioTimestamp:se.audioTimestamp},responseModalities:se?.responseModalities,thinkingConfig:et,...se?.mediaResolution&&{mediaResolution:se.mediaResolution},...Ve&&{imageConfig:Ve}},contents:ze,systemInstruction:tt?void 0:nt,safetySettings:Pe,tools:He,toolConfig:lt,cachedContent:se?.cachedContent,labels:se?.labels,serviceTier:qe,...se?.continuationToken!=null&&{continuationToken:se.continuationToken}},warnings:[...be,...at],providerOptionsNames:ne,extraHeaders:De,toolNameMapping:dt}}async getArgs(w,{isStreaming:x=!1}={}){let{responseFormat:A,tools:N,toolChoice:B}=w,re;if(A?.type==="json"&&A.schema!=null&&N?.some((ee)=>ee.type==="function")&&/(^|\/)gemini-/i.test(this.modelId)&&(!At(this.modelId).usesGemini3Features||B?.type==="required"||B?.type==="tool")){let ee="json";for(let V=1;N.some((pe)=>pe.name===ee);V++)ee=`json_${V}`;re={type:"function",name:ee,description:A.description??"Respond with a JSON object.",inputSchema:A.schema}}return{...await f.prepareRequest({modelId:this.modelId,config:this.config,options:re==null?w:{...w,responseFormat:void 0,tools:[...N??[],re],toolChoice:B?.type==="tool"?B:B?.type==="none"?{type:"tool",toolName:re.name}:{type:"required"}},isStreaming:x}),jsonResponseToolName:re?.name}}static convertGenerateContentResponse({config:w,response:x,warnings:A,providerOptionsNames:N,toolNameMapping:B,jsonResponseToolName:re,initialPromptTokenCount:ee,groundingMetadataPerRequest:V}){let pe=(se)=>Object.fromEntries(N.map((Ue)=>[Ue,se])),ce=x.candidates?.[0],Re=x.promptFeedback?.blockReason,Le=an(Re)?Re:void 0,Ce=ce?.finishReason==null&&Le!=null,Ee=ce?.finishReason??Le,je=[],Ne=ce?.content?.parts??[],ye=x.usageMetadata,ie,be;for(let se of Ne)if("executableCode"in se&&se.executableCode?.code){let Ue=w.generateId();ie=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:B?.toCustomToolName("code_execution")??"code_execution",input:JSON.stringify(se.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in se&&se.codeExecutionResult)je.push({type:"tool-result",toolCallId:ie,toolName:B?.toCustomToolName("code_execution")??"code_execution",result:{outcome:se.codeExecutionResult.outcome,output:se.codeExecutionResult.output??""}});else if("text"in se&&se.text!=null){if(re!=null&&se.thought!==!0)continue;let Ue=se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature}):void 0;if(se.text.length===0){if(Ue!=null&&je.length>0){let De=je[je.length-1];De.providerMetadata=Ue}}else je.push({type:se.thought===!0?"reasoning":"text",text:se.text,providerMetadata:Ue})}else if("functionCall"in se&&se.functionCall.name!=null){if(se.functionCall.name===re){je.push({type:"text",text:typeof se.functionCall.args==="string"?se.functionCall.args:JSON.stringify(se.functionCall.args??{}),...se.thoughtSignature?{providerMetadata:pe({thoughtSignature:se.thoughtSignature})}:{}});continue}je.push({type:"tool-call",toolCallId:se.functionCall.id||w.generateId(),toolName:se.functionCall.name,input:JSON.stringify(se.functionCall.args??{}),providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature}):void 0})}else if("inlineData"in se){let Ue=se.thought===!0,De=!!se.thoughtSignature;je.push({type:Ue?"reasoning-file":"file",data:{type:"data",data:se.inlineData.data},mediaType:se.inlineData.mimeType,providerMetadata:De?pe({thoughtSignature:se.thoughtSignature}):void 0})}else if("toolCall"in se&&se.toolCall){let Ue=se.toolCall.id||w.generateId();be=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:`server:${se.toolCall.toolType}`,input:JSON.stringify(se.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature,serverToolCallId:Ue,serverToolType:se.toolCall.toolType}):pe({serverToolCallId:Ue,serverToolType:se.toolCall.toolType})})}else if("toolResponse"in se&&se.toolResponse){let Ue=be||se.toolResponse.id||w.generateId();je.push({type:"tool-result",toolCallId:Ue,toolName:`server:${se.toolResponse.toolType}`,result:se.toolResponse.response??{},providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature,serverToolCallId:Ue,serverToolType:se.toolResponse.toolType}):pe({serverToolCallId:Ue,serverToolType:se.toolResponse.toolType})}),be=void 0}let ne=sn({groundingMetadata:ce?.groundingMetadata,generateId:w.generateId})??[];for(let se of ne)je.push(se);return{content:je,finishReason:{unified:Ce?"content-filter":nn({finishReason:Ee,hasToolCalls:je.some((se)=>se.type==="tool-call"&&!se.providerExecuted)}),raw:Ee},usage:Jt(ye),warnings:A,providerMetadata:pe({promptFeedback:x.promptFeedback??null,groundingMetadata:ce?.groundingMetadata??null,...V!=null?{groundingMetadataPerRequest:V}:{},urlContextMetadata:ce?.urlContextMetadata??null,safetyRatings:ce?.safetyRatings??null,usageMetadata:ye??null,finishMessage:ce?.finishMessage??null,serviceTier:ye?.serviceTier??null,...ce?.continuationToken!=null?{continuationToken:ce.continuationToken}:{},...ee!=null?{initialPromptTokenCount:ee}:{}}),response:{id:x.responseId??void 0}}}async doGenerate(w){let{args:x,warnings:A,providerOptionsNames:N,extraHeaders:B,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(w),V=d(this.config.headers?await _(this.config.headers):void 0,w.headers,B),pe=(ne)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:generateContent`,headers:V,body:ne,failedResponseHandler:Xe,successfulResponseHandler:p(In),abortSignal:w.abortSignal,fetch:this.config.fetch}),{responseHeaders:ce,value:Re,rawValue:Le}=await pe(x),Ce=[],Ee=[],je,Ne=Re.usageMetadata?.promptTokenCount,ye=!1;while(!0){let ne=Re.candidates?.[0];Ee.push(ne?.groundingMetadata??null);let se=ne?.finishReason==="CONTINUATION"?ne.continuationToken:void 0;if(je=jt(je,Re.usageMetadata??void 0),se==null)break;Ce.push(...f.convertGenerateContentResponse({config:this.config,response:Re,warnings:A,providerOptionsNames:N,toolNameMapping:re,jsonResponseToolName:ee}).content),ye=!0,{responseHeaders:ce,value:Re,rawValue:Le}=await pe({...x,continuationToken:se})}let ie=f.convertGenerateContentResponse({config:this.config,response:{...Re,usageMetadata:je},warnings:A,providerOptionsNames:N,toolNameMapping:re,jsonResponseToolName:ee,initialPromptTokenCount:ye?Ne:void 0,groundingMetadataPerRequest:ye?Ee:void 0}),be={...ie,content:[...Ce,...ie.content]};return{...be,request:{body:x},response:{...be.response,headers:ce,body:Le}}}async doStream(w){let{args:x,warnings:A,providerOptionsNames:N,extraHeaders:B,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(w,{isStreaming:!0}),V=(Be)=>Object.fromEntries(N.map((Pe)=>[Pe,Be])),pe=d(this.config.headers?await _(this.config.headers):void 0,w.headers,B),ce=(Be)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:streamGenerateContent?alt=sse`,headers:pe,body:Be,failedResponseHandler:Xe,successfulResponseHandler:D(Lo),abortSignal:w.abortSignal,fetch:this.config.fetch}),{responseHeaders:Re,value:Le}=await ce(x),Ce=[],Ee=null,je=to({stream:Le,getContinuationToken:(Be)=>{let Pe=Be.candidates?.[0];if(Pe?.groundingMetadata!=null)Ee=Pe.groundingMetadata;return Pe?.finishReason==="CONTINUATION"?Pe.continuationToken??void 0:void 0},continueStream:async(Be)=>{let{value:Pe}=await ce({...x,continuationToken:Be});return Ce.push(Ee),Ee=null,Pe}}),Ne={unified:"interrupted",raw:void 0},ye=void 0,ie=void 0,be=void 0,ne=null,se=null,Ue=null,De=null,qe=null,Ve=null,tt,We=this.config.generateId,Ze=!1,pt=!1,ze=null,nt=null,He=0,st=new Set,at,dt,Fe=[],et=(Be)=>{let Pe=Fe.pop();if(Pe==null)return;let{finalJSON:lt,closingDelta:it}=Pe.accumulator.finalize();if(it.length>0)Be.enqueue({type:"tool-input-delta",id:Pe.toolCallId,delta:it,providerMetadata:Pe.providerMetadata});Be.enqueue({type:"tool-input-end",id:Pe.toolCallId,providerMetadata:Pe.providerMetadata}),Be.enqueue({type:"tool-call",toolCallId:Pe.toolCallId,toolName:Pe.toolName,input:lt,providerMetadata:Pe.providerMetadata}),Ze=!0},Je={stream:je.pipeThrough(new TransformStream({start(Be){Be.enqueue({type:"stream-start",warnings:A})},transform(Be,Pe){if("type"in Be){Ne={unified:"interrupted",raw:void 0};return}if(w.includeRawChunks)Pe.enqueue({type:"raw",rawValue:Be.rawValue});if(!Be.success){if(Ne.unified==="interrupted")Ne={unified:"error",raw:void 0};Pe.enqueue({type:"error",error:Be.error});return}let lt=Be.value;if(lt.error!=null){Ne={unified:"error",raw:void 0};let Ye=lt.error;Pe.enqueue({type:"error",error:xe({message:Ye.message,type:Ye.status,code:Ye.code??void 0,statusCode:Ye.code??void 0,isRetryable:Ye.code!=null&&(Ye.code===408||Ye.code===409||Ye.code===429||Ye.code>=500),data:Ye})});return}if(!pt&&lt.responseId!=null)pt=!0,Pe.enqueue({type:"response-metadata",id:lt.responseId});let it=lt.usageMetadata;if(it!=null)ye=it;if(lt.promptFeedback!=null&&tt==null){if(ne=lt.promptFeedback,an(lt.promptFeedback.blockReason))tt=lt.promptFeedback.blockReason,Ne={unified:"content-filter",raw:tt}}let ot=lt.candidates?.[0];if(ot!=null){if(ot.groundingMetadata!=null)se=ot.groundingMetadata;if(ot.urlContextMetadata!=null)Ue=ot.urlContextMetadata;if(ot.safetyRatings!=null)De=ot.safetyRatings;if(ot.finishMessage!=null)qe=ot.finishMessage;if(ot.continuationToken!=null)Ve=ot.continuationToken}if(tt!=null||ot==null)return;let wt=ot.content,St=sn({groundingMetadata:ot.groundingMetadata,generateId:We});if(St!=null){for(let Ye of St)if(Ye.sourceType==="url"&&!st.has(Ye.url))st.add(Ye.url),Pe.enqueue(Ye)}if(wt!=null){let Ye=wt.parts??[];for(let Ge of Ye)if("executableCode"in Ge&&Ge.executableCode?.code){let $e=We();at=$e,Pe.enqueue({type:"tool-call",toolCallId:$e,toolName:re.toCustomToolName("code_execution"),input:JSON.stringify(Ge.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in Ge&&Ge.codeExecutionResult){let $e=at;if($e)Pe.enqueue({type:"tool-result",toolCallId:$e,toolName:re.toCustomToolName("code_execution"),result:{outcome:Ge.codeExecutionResult.outcome,output:Ge.codeExecutionResult.output??""}})}else if("text"in Ge&&Ge.text!=null){let $e=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0;if(Ge.text.length===0){if($e!=null&&ze!==null)Pe.enqueue({type:"text-delta",id:ze,delta:"",providerMetadata:$e})}else if(Ge.thought===!0){if(ze!==null)Pe.enqueue({type:"text-end",id:ze}),ze=null;if(nt===null)nt=String(He++),Pe.enqueue({type:"reasoning-start",id:nt,providerMetadata:$e});Pe.enqueue({type:"reasoning-delta",id:nt,delta:Ge.text,providerMetadata:$e})}else{if(nt!==null)Pe.enqueue({type:"reasoning-end",id:nt}),nt=null;if(ze===null)ze=String(He++),Pe.enqueue({type:"text-start",id:ze,providerMetadata:$e});Pe.enqueue({type:"text-delta",id:ze,delta:Ge.text,providerMetadata:$e})}}else if("inlineData"in Ge){if(ze!==null)Pe.enqueue({type:"text-end",id:ze}),ze=null;if(nt!==null)Pe.enqueue({type:"reasoning-end",id:nt}),nt=null;let $e=Ge.thought===!0,yt=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0;Pe.enqueue({type:$e?"reasoning-file":"file",mediaType:Ge.inlineData.mimeType,data:{type:"data",data:Ge.inlineData.data},providerMetadata:yt})}else if("toolCall"in Ge&&Ge.toolCall){let $e=Ge.toolCall.id||We();dt=$e;let yt=V({...Ge.thoughtSignature?{thoughtSignature:Ge.thoughtSignature}:{},serverToolCallId:$e,serverToolType:Ge.toolCall.toolType});Pe.enqueue({type:"tool-call",toolCallId:$e,toolName:`server:${Ge.toolCall.toolType}`,input:JSON.stringify(Ge.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:yt})}else if("toolResponse"in Ge&&Ge.toolResponse){let $e=dt||Ge.toolResponse.id||We(),yt=V({...Ge.thoughtSignature?{thoughtSignature:Ge.thoughtSignature}:{},serverToolCallId:$e,serverToolType:Ge.toolResponse.toolType});Pe.enqueue({type:"tool-result",toolCallId:$e,toolName:`server:${Ge.toolResponse.toolType}`,result:Ge.toolResponse.response??{},providerMetadata:yt}),dt=void 0}for(let Ge of Ye){if(!("functionCall"in Ge))continue;let $e=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0,yt=Ge.functionCall.partialArgs!=null||Ge.functionCall.name!=null&&Ge.functionCall.willContinue===!0,Hn=Ge.functionCall.name==null&&Ge.functionCall.args==null&&Ge.functionCall.partialArgs==null&&Ge.functionCall.willContinue==null,Vn=Ge.functionCall.name!=null&&Ge.functionCall.args!=null&&Ge.functionCall.partialArgs==null,Wn=Ge.functionCall.name!=null&&Ge.functionCall.args==null&&Ge.functionCall.partialArgs==null&&Ge.functionCall.willContinue!==!0;if(yt){if(Ge.functionCall.name!=null){let ct=Ge.functionCall.id||We(),gt=new vo;if(Fe.push({toolCallId:ct,toolName:Ge.functionCall.name,accumulator:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-start",id:ct,toolName:Ge.functionCall.name,providerMetadata:$e}),Ge.functionCall.partialArgs!=null){let ft=Ge.functionCall.partialArgs,{textDelta:It}=gt.processPartialArgs(ft);if(It.length>0)Pe.enqueue({type:"tool-input-delta",id:ct,delta:It,providerMetadata:$e});if(Ge.functionCall.willContinue!==!0&&ft.every((Kn)=>Kn.willContinue!==!0))et(Pe)}}else if(Ge.functionCall.partialArgs!=null&&Fe.length>0){let ct=Fe[Fe.length-1],gt=Ge.functionCall.partialArgs,{textDelta:ft}=ct.accumulator.processPartialArgs(gt);if(ft.length>0)Pe.enqueue({type:"tool-input-delta",id:ct.toolCallId,delta:ft,providerMetadata:$e});if(Ge.functionCall.willContinue!==!0&&gt.every((It)=>It.willContinue!==!0))et(Pe)}}else if(Hn&&Fe.length>0)et(Pe);else if(Vn){let ct=Ge.functionCall.id||We(),gt=Ge.functionCall.name,ft=typeof Ge.functionCall.args==="string"?Ge.functionCall.args:JSON.stringify(Ge.functionCall.args??{});Pe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-delta",id:ct,delta:ft,providerMetadata:$e}),Pe.enqueue({type:"tool-input-end",id:ct,providerMetadata:$e}),Pe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:ft,providerMetadata:$e}),Ze=!0}else if(Wn){let ct=Ge.functionCall.id||We(),gt=Ge.functionCall.name;Pe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-end",id:ct,providerMetadata:$e}),Pe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:"{}",providerMetadata:$e}),Ze=!0}}}if(ot.finishReason==="CONTINUATION"){if(ie==null)be=ye?.promptTokenCount;ie=jt(ie,ye),ye=void 0}if(ot.finishReason!=null)Ne={unified:nn({finishReason:ot.finishReason,hasToolCalls:Ze}),raw:ot.finishReason}},flush(Be){if(ye=jt(ie,ye),ze!==null)Be.enqueue({type:"text-end",id:ze});if(nt!==null)Be.enqueue({type:"reasoning-end",id:nt});Be.enqueue({type:"finish",finishReason:Ne,usage:Jt(ye),providerMetadata:V({promptFeedback:ne,groundingMetadata:se,...Ce.length>0?{groundingMetadataPerRequest:[...Ce,Ee]}:{},urlContextMetadata:Ue,safetyRatings:De,usageMetadata:ye??null,finishMessage:qe,serviceTier:ye?.serviceTier??null,...Ve!=null&&(Ne.raw==="MAX_TOKENS"||Ne.raw==="CONTINUATION")?{continuationToken:Ve}:{},...be!=null?{initialPromptTokenCount:be}:{}})})}})),response:{headers:Re},request:{body:x}};return{...Je,stream:ee==null?Je.stream:Je.stream.pipeThrough(tn(ee))}}};function ko(){return 65536}function xo(f){let w=f.toLowerCase();if(w.includes("2.5-pro")||w.includes("gemini-3-pro-image"))return 32768;return 24576}function Ro({reasoning:f,modelId:w,warnings:x}){if(!W(f))return;if(At(w).usesGemini3Features&&!w.includes("gemini-3-pro-image"))return Oo({reasoning:f,modelId:w,warnings:x});return Eo({reasoning:f,modelId:w,warnings:x})}function Oo({reasoning:f,modelId:w,warnings:x}){let A=Mo(w);if(f==="none")return{thinkingLevel:A};let N=Se({reasoning:f,effortMap:{minimal:A,low:"low",medium:"medium",high:"high",xhigh:"high",max:"high"},warnings:x});if(N==null)return;return{thinkingLevel:N}}function Mo(f){let w=/(?:^|[/.])(gemini-[^/]*)$/i.exec(f)?.[1].toLowerCase();if(w==="gemini-flash-latest")return"low";let x=/^gemini-(\d+)(?:\.\d+)?-pro(?:$|-)/.exec(w??"");if(Number(x?.[1])>=3)return"low";let A=/^gemini-(\d+)\.(\d+)-flash(?:$|-(?!lite(?:-|$)))/.exec(w??"");if(A==null)return"minimal";let N=Number(A[1]),B=Number(A[2]);return N>3||N===3&&B>=7?"low":"minimal"}function Eo({reasoning:f,modelId:w,warnings:x}){if(f==="none")return{thinkingBudget:0};let A=ut({reasoning:f,maxOutputTokens:ko(),maxReasoningBudget:xo(w),minReasoningBudget:0,warnings:x});if(A==null)return;return{thinkingBudget:A}}function sn({groundingMetadata:f,generateId:w}){if(!f?.groundingChunks)return;let x=[];for(let A of f.groundingChunks)if(A.web!=null)x.push({type:"source",sourceType:"url",id:w(),url:A.web.uri,title:A.web.title??void 0});else if(A.image!=null)x.push({type:"source",sourceType:"url",id:w(),url:A.image.sourceUri,title:A.image.title??void 0});else if(A.retrievedContext!=null){let N=A.retrievedContext.uri,B=A.retrievedContext.fileSearchStore;if(N&&(N.startsWith("http://")||N.startsWith("https://")))x.push({type:"source",sourceType:"url",id:w(),url:N,title:A.retrievedContext.title??void 0});else if(N){let re=A.retrievedContext.title??"Unknown Document",ee="application/octet-stream",V=void 0;if(N.endsWith(".pdf"))ee="application/pdf",V=N.split("/").pop();else if(N.endsWith(".txt"))ee="text/plain",V=N.split("/").pop();else if(N.endsWith(".docx"))ee="application/vnd.openxmlformats-officedocument.wordprocessingml.document",V=N.split("/").pop();else if(N.endsWith(".doc"))ee="application/msword",V=N.split("/").pop();else if(N.match(/\.(md|markdown)$/))ee="text/markdown",V=N.split("/").pop();else V=N.split("/").pop();x.push({type:"source",sourceType:"document",id:w(),mediaType:ee,title:re,filename:V})}else if(B){let re=A.retrievedContext.title??"Unknown Document";x.push({type:"source",sourceType:"document",id:w(),mediaType:"application/octet-stream",title:re,filename:B.split("/").pop()})}}else if(A.maps!=null){if(A.maps.uri)x.push({type:"source",sourceType:"url",id:w(),url:A.maps.uri,title:A.maps.title??void 0})}return x.length>0?x:void 0}var _n=()=>t({webSearchQueries:o(e()).nullish(),imageSearchQueries:o(e()).nullish(),retrievalQueries:o(e()).nullish(),searchEntryPoint:t({renderedContent:e()}).nullish(),groundingChunks:o(t({web:t({uri:e(),title:e().nullish()}).nullish(),image:t({sourceUri:e(),imageUri:e(),title:e().nullish(),domain:e().nullish()}).nullish(),retrievedContext:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),fileSearchStore:e().nullish(),customMetadata:o(t({key:e(),stringValue:e().nullish(),numericValue:r().nullish(),stringListValue:t({values:o(e()).nullish()}).nullish()})).nullish()}).nullish(),maps:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),placeId:e().nullish()}).nullish()})).nullish(),groundingSupports:o(t({segment:t({startIndex:r().nullish(),endIndex:r().nullish(),text:e().nullish()}).nullish(),segment_text:e().nullish(),groundingChunkIndices:o(r()).nullish(),supportChunkIndices:o(r()).nullish(),confidenceScores:o(r()).nullish(),confidenceScore:o(r()).nullish()})).nullish(),retrievalMetadata:l([t({webDynamicRetrievalScore:r()}),t({})]).nullish()}),Ao=()=>t({jsonPath:e(),stringValue:e().nullish(),numberValue:r().nullish(),boolValue:c().nullish(),nullValue:v().nullish(),willContinue:c().nullish()}),Cn=()=>t({parts:o(l([t({functionCall:t({id:e().nullish(),name:e().nullish(),args:v().nullish(),partialArgs:o(Ao()).nullish(),willContinue:c().nullish()}),thoughtSignature:e().nullish()}),t({inlineData:t({mimeType:e(),data:e()}),thought:c().nullish(),thoughtSignature:e().nullish()}),t({toolCall:t({toolType:e(),args:v().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({toolResponse:t({toolType:e(),response:v().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({executableCode:t({language:e(),code:e()}).nullish(),codeExecutionResult:t({outcome:e(),output:e().nullish()}).nullish(),text:e().nullish(),thought:c().nullish(),thoughtSignature:e().nullish()})])).nullish()}),Lt=()=>t({category:e().nullish(),probability:e().nullish(),probabilityScore:r().nullish(),severity:e().nullish(),severityScore:r().nullish(),blocked:c().nullish()}),xt=()=>o(t({modality:e(),tokenCount:r()}).loose()).nullish(),wn=()=>t({cachedContentTokenCount:r().nullish(),thoughtsTokenCount:r().nullish(),promptTokenCount:r().nullish(),candidatesTokenCount:r().nullish(),toolUsePromptTokenCount:r().nullish(),totalTokenCount:r().nullish(),trafficType:e().nullish(),serviceTier:e().nullish(),promptTokensDetails:xt(),cacheTokensDetails:xt(),candidatesTokensDetails:xt(),toolUsePromptTokensDetails:xt()}).loose(),Sn=()=>t({urlMetadata:o(t({retrievedUrl:e(),urlRetrievalStatus:e()})).nullish()}),In=a(()=>s(t({responseId:e().nullish(),candidates:o(t({content:Cn().nullish().or(t({}).strict()),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(Lt()).nullish(),groundingMetadata:_n().nullish(),urlContextMetadata:Sn().nullish()})).nullish(),usageMetadata:wn().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(Lt()).nullish()}).nullish()}))),Lo=a(()=>s(t({error:fn().nullish(),responseId:e().nullish(),candidates:o(t({content:Cn().nullish(),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(Lt()).nullish(),groundingMetadata:_n().nullish(),urlContextMetadata:Sn().nullish()})).nullish(),usageMetadata:wn().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(Lt()).nullish()}).nullish()})));function an(f){return f!=null&&f!==""&&f!=="BLOCK_REASON_UNSPECIFIED"&&f!=="BLOCKED_REASON_UNSPECIFIED"}var jo=()=>U({searchTypes:t({webSearch:t({}).optional(),imageSearch:t({}).optional()}).optional(),timeRangeFilter:t({startTime:e(),endTime:e()}).optional()}),Uo=S({id:"google.google_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),kn=a(()=>s(t({googleSearch:jo().optional()}))),No=2147483648,Go=20000000,Do=new Set(["text","reasoning","source","tool-call","tool-result"]);function Po(f){for(let w of f){let x=w.type;if(x!=="text"&&x!=="image")throw new u({functionality:`batch request type: ${x}`,message:`The Google Batch API does not support batch requests with type "${x}".`})}}var Bt=()=>t({code:l([r(),e()]).nullish(),message:e().nullish(),status:e().nullish()}),qo=()=>t({requestCount:l([e(),r()]).nullish(),successfulRequestCount:l([e(),r()]).nullish(),failedRequestCount:l([e(),r()]).nullish(),pendingRequestCount:l([e(),r()]).nullish()}),rn=()=>t({responsesFile:e().nullish(),inlinedResponses:t({inlinedResponses:o(t({metadata:t({key:e()}),response:v().nullish(),error:Bt().nullish()}))}).nullish()}),xn=()=>t({name:e(),metadata:t({state:e().nullish(),createTime:e().nullish(),batchStats:qo().nullish(),output:rn().nullish()}).nullish(),done:c().nullish(),error:Bt().nullish(),response:rn().nullish()}),Nt=a(()=>s(xn())),$o=a(()=>s(t({operations:o(xn()).nullish(),nextPageToken:e().nullish()}))),Fo=a(()=>s(t({}))),Bo=a(()=>s(t({file:t({name:e(),expirationTime:e().nullish()})}))),Ho=a(()=>s(t({key:e(),response:v().nullish(),error:Bt().nullish()}))),Vo=a(()=>s(t({candidates:o(v()).nullish(),promptFeedback:t({blockReason:e().nullish()}).nullish()}))),Wo=class{constructor(f){this.specificationVersion="v4",this.provider=f.provider,this.batchConfig=f.config,this.supportedUrls=f.supportedUrls,this.batchGenerateId=f.config.generateId??C,this.maxLineBytes=f.maxLineBytes}async doStartBatch(f){Po(f.requests);let w=Yo(f.requests),x=[],A=`ai-sdk-batch-${this.batchGenerateId()}`,N=[],B={batch:{displayName:A,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{requests:{requests:N}}}},re=new TextEncoder,ee=re.encode(JSON.stringify(B)).byteLength,V;for(let je of f.requests){let Ne=je.type==="text"?await Ct.prepareRequest({modelId:je.modelId,config:this.batchConfig,options:je.options}):await this.prepareImageRequest(je),ye={request:Ne.args,metadata:{key:je.id}};if(V==null){let ie=re.encode(JSON.stringify(ye)).byteLength,be=ee+ie+(N.length>0?1:0);if(be<Go)N.push(ye),ee=be;else{V=[];for(let ne of N)V.push(JSON.stringify({key:ne.metadata.key,request:ne.request}),`
7
+ `);N.length=0,V.push(JSON.stringify({key:je.id,request:Ne.args}),`
8
8
  `)}}else V.push(JSON.stringify({key:je.id,request:Ne.args}),`
9
- `);for(let ie of Ne.warnings)x.push({requestId:je.id,warning:ie})}let pe=await this.getHeaders(f.headers),ce=`${this.batchConfig.baseURL}/${Tt(w)}:batchGenerateContent`;if(V==null){let{value:je}=await g({url:ce,headers:pe,body:B,failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch});return{batchId:je.name,..._t(je),warnings:x}}let Re=new Blob(V,{type:"application/jsonl"});if(V.length=0,Re.size>No)throw new b({argument:"requests",message:"Google batch input files must not exceed 2 GB."});let{value:Le}=await g({url:`${this.getBaseOrigin()}/upload/v1beta/files`,headers:d(pe,{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(Re.size),"X-Goog-Upload-Header-Content-Type":"application/jsonl"}),body:{file:{display_name:`${A}-input`}},failedResponseHandler:Xe,successfulResponseHandler:Jo,abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{value:Ce}=await ve({url:Le,headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize","Content-Type":"application/jsonl"},body:{content:Re,values:{byteLength:Re.size,mediaType:"application/jsonl"}},failedResponseHandler:Xe,successfulResponseHandler:p(Bo),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{value:Ee}=await g({url:ce,headers:pe,body:{batch:{displayName:A,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{fileName:Ce.file.name}}},failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch});return{batchId:Ee.name,..._t(Ee),providerMetadata:{google:{inputFileId:Ce.file.name,...Ce.file.expirationTime!=null?{inputFileExpiresAt:Ce.file.expirationTime}:{}}},warnings:x}}async doGetBatchStatus(f){return _t(await this.retrieveBatch(f))}async doCancelBatch(f){return await g({url:`${this.batchConfig.baseURL}/${f.batchId}:cancel`,headers:await this.getHeaders(f.headers),body:{},failedResponseHandler:Xe,successfulResponseHandler:p(Fo),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{}}async doListBatches(f){let w=new URL(`${this.batchConfig.baseURL}/batches`);if(f.limit!=null)w.searchParams.set("pageSize",String(f.limit));if(f.cursor!=null)w.searchParams.set("pageToken",f.cursor);let{value:x}=await R({url:w.toString(),headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:p($o),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return{batches:(x.operations??[]).map((A)=>({batchId:A.name,..._t(A)})),...x.nextPageToken!=null?{nextCursor:x.nextPageToken}:{}}}async doGetBatchResults(f){let w=await this.retrieveBatch(f),x=_t(w);if(x.status==="pending")throw new b({argument:"batchId",message:`Google batch "${f.batchId}" is not complete.`});let A=w.metadata?.output?.inlinedResponses?.inlinedResponses??w.response?.inlinedResponses?.inlinedResponses;if(A!=null)return ae(this.iterateBatchResults(A.map((ee)=>({key:ee.metadata.key,response:ee.response,error:ee.error}))));let F=w.metadata?.output?.responsesFile??w.response?.responsesFile;if(F==null){if(x.status==="completed")throw new P({data:w,message:`Google batch "${f.batchId}" completed without batch output.`});return new ReadableStream({start(ee){ee.close()}})}let B=F.split("/").map((ee)=>encodeURIComponent(ee)).join("/"),{value:re}=await R({url:`${this.getBaseOrigin()}/download/v1beta/${B}:download?alt=media`,headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:_e(Ho,{maxLineBytes:this.maxLineBytes}),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return ae(this.iterateBatchResults(re))}async retrieveBatch(f){let{value:w}=await R({url:`${this.batchConfig.baseURL}/${f.batchId}`,headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return w}async*iterateBatchResults(f){for await(let w of f){if(w.error!=null){let ee=Rn(w.error,"Google batch request failed."),V=w.error.status==="CANCELLED"||String(w.error.code)==="1"?"cancelled":"failed";yield{type:"text",id:w.key,status:V,error:ee};continue}if(w.response==null){yield{type:"text",id:w.key,status:"failed",error:{message:"Google returned a batch result without a response or error.",code:"invalid_batch_result"}};continue}let x=await j({value:w.response,schema:Vo});if(x.success&&(x.value.candidates==null||x.value.candidates.length===0)){let ee=x.value.promptFeedback??void 0,V=ee?.blockReason??void 0;yield{type:"text",id:w.key,status:"failed",error:{message:V==null?"Google returned a batch response without any candidates.":`Google blocked the batch request (${V}).`,code:V==null?"invalid_response":"prompt_blocked",...V!=null?{type:V}:{}},...ee!=null?{providerMetadata:{google:{promptFeedback:{blockReason:ee.blockReason??null}}}}:{}};continue}let A=await j({value:w.response,schema:In});if(!A.success){yield{type:"text",id:w.key,status:"failed",error:{message:"Google returned an invalid GenerateContent batch result.",code:"invalid_response"}};continue}let F=Ct.convertGenerateContentResponse({config:this.batchConfig,response:A.value,warnings:[],providerOptionsNames:["google"]}),B=Xo(F);if(B!=null){yield{type:"image",id:w.key,status:"succeeded",result:B};continue}let re=F.content.find((ee)=>!Do.has(ee.type));if(re!=null){yield{type:"text",id:w.key,status:"failed",error:{message:`Google returned a "${re.type}" content block, but that content is not supported in AI SDK text batches.`,code:"unsupported_content"}};continue}yield{type:"text",id:w.key,status:"succeeded",result:F}}}async prepareImageRequest(f){let{prompt:w,n:x,size:A,aspectRatio:F,seed:B,files:re,mask:ee,providerOptions:V}=f.options,pe=[];if(ee!=null)throw new u({functionality:"mask-based image editing in Google batches"});if(x>1)throw new u({functionality:"multiple images per Google batch request"});if(A!=null)pe.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let ce=[];if(w!=null)ce.push({type:"text",text:w});for(let ye of re??[])ce.push(ye.type==="url"?{type:"file",data:{type:"url",url:new URL(ye.url)},mediaType:"image/*"}:{type:"file",data:{type:"data",data:ye.data},mediaType:ye.mediaType});let Re=await h({provider:"google",providerOptions:V,schema:kn}),{responseModalities:Le,imageConfig:Ce,...Ee}=await h({provider:"google",providerOptions:V,schema:Et})??{},je=await h({provider:"google",providerOptions:{google:{...Ee,responseModalities:["IMAGE"],imageConfig:F!=null||Ce!=null?{...Ce,...F!=null?{aspectRatio:F}:{}}:void 0}},schema:Et}),Ne=await Ct.prepareRequest({modelId:f.modelId,config:this.batchConfig,options:{prompt:[{role:"user",content:ce}],seed:B,providerOptions:{google:je??{responseModalities:["IMAGE"]}},tools:Re?.googleSearch!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Re.googleSearch}]:void 0}});return{...Ne,warnings:[...pe,...Ne.warnings]}}async getHeaders(f){return d(this.batchConfig.headers?await _(this.batchConfig.headers):void 0,f)}getBaseOrigin(){return this.batchConfig.baseURL.replace(/\/v1beta$/,"")}};function _t(f){let w=f.metadata?.state??void 0,x=zo(f.metadata?.batchStats),A=f.metadata?.createTime??void 0,F=f.error!=null?Rn(f.error,"Google batch failed."):void 0;return{status:Ko({rawStatus:w,done:f.done??void 0,hasError:F!=null}),...w!=null?{rawStatus:w}:{},...x!=null?{requestCounts:x}:{},...F!=null?{error:F}:{},...A!=null?{createdAt:A}:{}}}function Ko({rawStatus:f,done:w,hasError:x}){if(x)return"failed";if(f==null)return w?"completed":"pending";switch(f.replace(/^(?:BATCH|JOB)_STATE_/,"")){case"SUCCEEDED":return"completed";case"FAILED":case"CANCELLED":case"EXPIRED":return"failed";default:return"pending"}}function zo(f){let w=Rt(f?.requestCount),x=Rt(f?.successfulRequestCount??0),A=Rt(f?.failedRequestCount??0),F=Rt(f?.pendingRequestCount??0);return ge({total:w,pending:F,completed:x,failed:A})}function Rt(f){let w=typeof f==="string"&&/^\d+$/.test(f)?Number(f):f;return typeof w==="number"&&Number.isSafeInteger(w)&&w>=0?w:void 0}function Rn(f,w){return{message:f.message??w,...f.status!=null?{type:f.status}:{},...f.code!=null?{code:String(f.code)}:{}}}var Jo=async({response:f})=>{let w=f.headers.get("x-goog-upload-url");if(w==null)throw new P({data:f.headers,message:"Google did not return a resumable upload URL."});return{value:w}};function Yo(f){let w=f[0]?.modelId;if(w==null)throw new b({argument:"requests",message:"Google batches require at least one request."});for(let x of f)if(x.modelId!==w)throw new b({argument:"requests",message:"Google batches require every request to use the same model because the model is part of the batch endpoint."});return w}function Xo(f){let w=f.content.flatMap((A)=>A.type==="file"&&A.mediaType.startsWith("image/")&&A.data.type==="data"?[M(A.data.data)]:[]);if(w.length===0)return;let x=f.providerMetadata?.google??{};return{images:w,warnings:f.warnings,providerMetadata:{google:{...x,images:w.map(()=>({}))}},response:{timestamp:new Date,modelId:f.response?.modelId??"",headers:f.response?.headers},usage:{inputTokens:f.usage.inputTokens.total,outputTokens:f.usage.outputTokens.total,totalTokens:(f.usage.inputTokens.total??0)+(f.usage.outputTokens.total??0)}}}var Qo=S({id:"google.enterprise_web_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))});a(()=>s(U({fileSearchStoreNames:o(e()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:r().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:e().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()})));var Zo=S({id:"google.file_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),ei={googleSearch:Uo,enterpriseWebSearch:Qo,googleMaps:S({id:"google.google_maps",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),urlContext:S({id:"google.url_context",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),fileSearch:Zo,codeExecution:no,vertexRagStore:S({id:"google.vertex_rag_store",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))})},ti=new Set(["gemini-2.5-flash-image","gemini-3-pro-image-preview","gemini-3.1-flash-image-preview","gemini-nano-banana-2.1"]),ni=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,{},w.config)}get maxImagesPerCall(){if(this.settings.maxImagesPerCall!=null)return this.settings.maxImagesPerCall;return 1}get supportsFileInputs(){return ti.has(this.modelId)?!0:void 0}get supportsMaskInputs(){return this.supportsFileInputs===!0?!1:void 0}get provider(){return this.config.provider}constructor(w,x,A){this.modelId=w,this.settings=x,this.config=A,this.specificationVersion="v4"}async doGenerate(w){if(!this.modelId.startsWith("gemini-"))throw Error("Google image models other than Gemini are no longer supported. Use a model ID that starts with `gemini-`.");let{prompt:x,size:A,aspectRatio:F,seed:B,providerOptions:re,headers:ee,abortSignal:V,files:pe,mask:ce}=w,Re=[];if(ce!=null)throw Error("Gemini image models do not support mask-based image editing.");if(A!=null)Re.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let Le=[];if(x!=null)Le.push({type:"text",text:x});if(pe!=null&&pe.length>0)for(let De of pe)if(De.type==="url")Le.push({type:"file",data:{type:"url",url:new URL(De.url)},mediaType:"image/*"});else Le.push({type:"file",data:{type:"data",data:typeof De.data==="string"?De.data:new Uint8Array(De.data)},mediaType:De.mediaType});let Ce=[{role:"user",content:Le}],Ee=await h({provider:"google",providerOptions:re,schema:kn}),{googleSearch:je,responseModalities:Ne,imageConfig:ye,...ie}=re?.google??{},be=await new Ct(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??C}).doGenerate({prompt:Ce,seed:B,providerOptions:{google:{...ie,responseModalities:["IMAGE"],imageConfig:F!=null||ye!=null?{...ye,...F!=null?{aspectRatio:F}:{}}:void 0}},tools:Ee?.googleSearch!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Ee.googleSearch}]:void 0,headers:ee,abortSignal:V}),ne=this.config._internal?.currentDate?.()??new Date,se=[];for(let De of be.content)if(De.type==="file"&&De.mediaType.startsWith("image/")&&De.data.type==="data")se.push(M(De.data.data));let Ue=be.providerMetadata?.google??{};return{images:se,...be.finishReason.unified==="content-filter"?{isRetryable:!1}:{},warnings:Re,providerMetadata:{google:{...Ue,finishReason:be.finishReason.raw??null,images:se.map(()=>({}))}},response:{timestamp:ne,modelId:this.modelId,headers:be.response?.headers},usage:be.usage?{inputTokens:be.usage.inputTokens.total,outputTokens:be.usage.outputTokens.total,totalTokens:(be.usage.inputTokens.total??0)+(be.usage.outputTokens.total??0)}:void 0}}},oi=class{get provider(){return this.config.provider}constructor(f){this.config=f,this.specificationVersion="v4"}async uploadFile(f){let w=await h({provider:"google",providerOptions:f.providerOptions,schema:ai}),x=d(this.config.headers(),f.headers),A=this.config.fetch??globalThis.fetch,F=[];if(f.filename!=null)F.push({type:"unsupported",feature:"filename"});let B=we(f.data),re=f.mediaType,ee=w?.displayName,V=await A(`${this.config.baseURL.replace(/\/v1beta$/,"")}/upload/v1beta/files`,{method:"POST",headers:{...x,"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(B.length),"X-Goog-Upload-Header-Content-Type":re,"Content-Type":"application/json"},body:JSON.stringify({file:{...ee!=null?{display_name:ee}:{}}}),signal:f.abortSignal});if(!V.ok){let je=await V.text();throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to initiate resumable upload: ${V.status} ${je}`})}let pe=V.headers.get("x-goog-upload-url");if(!pe)throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:"No upload URL returned from initiation request"});let ce=await A(pe,{method:"POST",headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"},body:ii(B),signal:f.abortSignal});if(!ce.ok){let je=await ce.text();throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to upload file data: ${ce.status} ${je}`})}let Re=(await ce.json()).file,Le=w?.pollIntervalMs??2000,Ce=w?.pollTimeoutMs??300000,Ee=Date.now();while(Re.state==="PROCESSING"){if(Date.now()-Ee>Ce)throw new m({name:"GOOGLE_FILES_UPLOAD_TIMEOUT",message:`File processing timed out after ${Ce}ms`});await Oe(Le,{abortSignal:f.abortSignal});let je=/^files\/([^/]+)$/.exec(Re.name),Ne=je!=null?`files/${de(je[1])}`:de(Re.name),{value:ye}=await R({url:`${this.config.baseURL}/${Ne}`,validateUrl:!1,headers:d(x),successfulResponseHandler:p(si),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch});Re=ye}if(Re.state==="FAILED")throw new m({name:"GOOGLE_FILES_UPLOAD_FAILED",message:`File processing failed for ${Re.name}`});return{warnings:F,providerReference:{google:Re.uri},mediaType:Re.mimeType??f.mediaType,providerMetadata:{google:{name:Re.name,displayName:Re.displayName,mimeType:Re.mimeType,sizeBytes:Re.sizeBytes,state:Re.state,uri:Re.uri,...Re.createTime!=null?{createTime:Re.createTime}:{},...Re.updateTime!=null?{updateTime:Re.updateTime}:{},...Re.expirationTime!=null?{expirationTime:Re.expirationTime}:{},...Re.sha256Hash!=null?{sha256Hash:Re.sha256Hash}:{}}}}}};function ii(f){if(f.buffer instanceof ArrayBuffer)return f;return new Uint8Array(f)}var si=a(()=>s(t({name:e(),displayName:e().nullish(),mimeType:e(),sizeBytes:e().nullish(),createTime:e().nullish(),updateTime:e().nullish(),expirationTime:e().nullish(),sha256Hash:e().nullish(),uri:e(),state:e()}))),ai=a(()=>s(U({displayName:e().nullish(),pollIntervalMs:r().positive().nullish(),pollTimeoutMs:r().positive().nullish()}))),ri=a(()=>s(U({pollIntervalMs:r().positive().nullish(),pollTimeoutMs:r().positive().nullish(),personGeneration:i(["dont_allow","allow_adult","allow_all"]).nullish(),negativePrompt:e().nullish(),referenceImages:o(t({bytesBase64Encoded:e().nullish(),gcsUri:e().nullish()})).nullish()})));function li(f){return f.frameImages?.find((w)=>w.frameType==="first_frame")?.image}function ui(f){return li(f)??f.image}function ci(f){return f.frameImages?.find((w)=>w.frameType==="last_frame")?.image}function di(f){if(f.frameImages!=null&&f.frameImages.length>0)return;return f.inputReferences!=null&&f.inputReferences.length>0?f.inputReferences:void 0}function Dt(f,w){if(f.type==="url"){if(f.url.startsWith("gs://"))return{gcsUri:f.url,mimeType:"image/png"};w.push({type:"unsupported",feature:"URL-based image input",details:"Google Generative AI video models require base64-encoded images or GCS URIs. URL will be ignored."});return}return{bytesBase64Encoded:typeof f.data==="string"?f.data:X(f.data),mimeType:f.mediaType||"image/png"}}function pi(f){if(f.bytesBase64Encoded)return{image:{bytesBase64Encoded:f.bytesBase64Encoded,mimeType:"image/png"},referenceType:"asset"};if(f.gcsUri)return{image:{gcsUri:f.gcsUri,mimeType:"image/png"},referenceType:"asset"};return f}function gi(f,w){let x=Dt(f,w);return x!=null?{image:x,referenceType:"asset"}:void 0}var hi=class{get provider(){return this.config.provider}get maxVideosPerCall(){return 4}constructor(f,w){this.modelId=f,this.config=w,this.specificationVersion="v4"}async buildRequest(f){let w=[],x=await h({provider:"google",providerOptions:f.providerOptions,schema:ri}),A=[{}],F=A[0];if(f.prompt!=null)F.prompt=f.prompt;let B=ui(f);if(B!=null){let pe=Dt(B,w);if(pe!=null)F.image=pe}let re=ci(f);if(re!=null){let pe=Dt(re,w);if(pe!=null)F.lastFrame=pe}let ee=di(f);if(ee!=null)F.referenceImages=ee.flatMap((pe)=>{let ce=gi(pe,w);return ce!=null?[ce]:[]});else if(x?.referenceImages!=null)F.referenceImages=x.referenceImages.map((pe)=>pi(pe));let V={sampleCount:f.n};if(f.aspectRatio)V.aspectRatio=f.aspectRatio;if(f.resolution)V.resolution={"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"}[f.resolution]||f.resolution;if(f.duration)V.durationSeconds=f.duration;if(f.seed)V.seed=f.seed;if(x!=null){let pe=x;if(pe.personGeneration!==void 0&&pe.personGeneration!==null)V.personGeneration=pe.personGeneration;if(pe.negativePrompt!==void 0&&pe.negativePrompt!==null)V.negativePrompt=pe.negativePrompt;for(let[ce,Re]of Object.entries(pe))if(!["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","referenceImages"].includes(ce))V[ce]=Re}return{instances:A,parameters:V,warnings:w,googleOptions:x}}async buildCompletedResult(f,w,x,A){let F=f.response;if(!F?.generateVideoResponse?.generatedSamples||F.generateVideoResponse.generatedSamples.length===0)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:`No videos in response. Response: ${JSON.stringify(f)}`});let B=[],re=[],ee=(await _(this.config.headers))?.["x-goog-api-key"];for(let V of F.generateVideoResponse.generatedSamples)if(V.video?.uri){let pe=ee&&He(V.video.uri,this.config.baseURL)?`${V.video.uri}${V.video.uri.includes("?")?"&":"?"}key=${ee}`:V.video.uri;B.push({type:"url",url:pe,mediaType:"video/mp4"}),re.push({uri:V.video.uri})}if(B.length===0)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{status:"completed",videos:B,warnings:x,response:{timestamp:A,modelId:this.modelId,headers:w},providerMetadata:{google:{videos:re}}}}async doStart(f){let w=this.config._internal?.currentDate?.()??new Date,{instances:x,parameters:A,warnings:F}=await this.buildRequest(f),{value:B,responseHeaders:re}=await g({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:d(await _(this.config.headers),f.headers),body:{instances:x,parameters:A},successfulResponseHandler:p(ln),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch}),ee=B.name;if(!ee)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No operation name returned from API"});return{operation:{operationName:ee},warnings:F,response:{timestamp:w,modelId:this.modelId,headers:re}}}async doStatus(f){let w=this.config._internal?.currentDate?.()??new Date,{operationName:x}=f.operation,{value:A,responseHeaders:F}=await R({url:`${this.config.baseURL}/${x}`,validateUrl:!1,headers:d(await _(this.config.headers),f.headers),successfulResponseHandler:p(ln),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch});if(!A.done)return{status:"pending",response:{timestamp:w,modelId:this.modelId,headers:F}};if(A.error)return{status:"error",error:`Video generation failed: ${A.error.message}`,response:{timestamp:w,modelId:this.modelId,headers:F}};return this.buildCompletedResult(A,F,[],w)}},ln=a(()=>s(t({name:e().nullish(),done:c().nullish(),error:t({code:r().nullish(),message:e(),status:e().nullish()}).nullish(),response:t({generateVideoResponse:t({generatedSamples:o(t({video:t({uri:e().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}))),mi=a(()=>s(t({candidates:o(t({content:t({parts:o(t({inlineData:t({mimeType:e().nullish(),data:e().nullish()}).nullish()})).nullish()}).nullish()})).nullish(),usageMetadata:y(e(),G()).nullish()})));function fi({text:f,voice:w,providerOptions:x}){let A=x?.google,F=A!=null&&typeof A==="object"?A:void 0,B=F&&"turns"in F?F.turns:void 0,re=[];if(Array.isArray(B)&&B.length>0){for(let pe of B){if(pe==null||typeof pe!=="object"||!("text"in pe)||typeof pe.text!=="string")break;re.push(pe.text)}if(re.length===B.length)f=re.join("")}let ee=F&&"multiSpeakerVoiceConfig"in F?F.multiSpeakerVoiceConfig:void 0,V=ee!=null&&typeof ee==="object"&&"speakerVoiceConfigs"in ee&&Array.isArray(ee.speakerVoiceConfigs)?ee.speakerVoiceConfigs:[];return{text:f,usesCustomVoice:w?.startsWith("voice_")===!0||w?.startsWith("voicekey_")===!0||V.some((pe)=>pe!=null&&typeof pe==="object"&&("voiceConfig"in pe)&&pe.voiceConfig!=null&&typeof pe.voiceConfig==="object"&&("voice"in pe.voiceConfig))}}var yi=()=>t({voiceName:e()}),vi=()=>t({prebuiltVoiceConfig:yi(),voice:Ae().optional()}),un=()=>t({speaker:e().min(1).optional(),style:e().optional()}),cn=a(()=>s(t({speechMetadata:un().optional(),turns:o(t({text:e(),speechMetadata:un().optional()})).min(1).optional(),multiSpeakerVoiceConfig:t({speakerVoiceConfigs:o(t({speaker:e(),voiceConfig:vi()}))}).optional()}))),bi="Kore",Ti=24000,_i=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.modelId=w,this.config=x,this.specificationVersion="v4"}async getArgs({text:w,voice:x=bi,outputFormat:A,instructions:F,speed:B,language:re,providerOptions:ee}){let V=[],pe=this.config.provider.includes("vertex")?["googleVertex","vertex"]:["google"],ce;for(let be of pe)if(ce=await h({provider:be,providerOptions:ee,schema:cn}),ce!=null)break;if(ce==null&&!pe.includes("google"))ce=await h({provider:"google",providerOptions:ee,schema:cn});let Re=!this.modelId.startsWith("gemini-2.5-")&&!this.modelId.startsWith("gemini-3.1-"),Le=fi({text:w,voice:x,providerOptions:{google:ce}});if(Le.usesCustomVoice)throw new b({argument:"voice",message:"Custom voices are not supported. Use a prebuilt voice instead."});let Ce=ce?.multiSpeakerVoiceConfig,Ee=Ce?{multiSpeakerVoiceConfig:Ce}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:x}}},je=w;if(F!=null&&!Re)if(Ce)V.push({type:"unsupported",feature:"instructions",details:"Google Gemini TTS ignores `instructions` when `multiSpeakerVoiceConfig` is set, because prepending them would break multi-speaker transcript parsing."});else je=`${F}: ${w}`;let Ne=[{text:je}];if(Re){if(ce?.turns&&ce.speechMetadata)throw new b({argument:"providerOptions",message:"Set speechMetadata on each turn when using turns."});if(ce?.turns&&w!=="")V.push({type:"unsupported",feature:"text",details:"Google TTS turns replace the top-level text."});Ne=(ce?.turns??[{text:w,speechMetadata:ce?.speechMetadata}]).map((be)=>{let ne=be.speechMetadata?.style??F,se=be.speechMetadata?.speaker;if(Ce&&!Ce.speakerVoiceConfigs.some((Ue)=>Ue.speaker===se))throw new b({argument:"speechMetadata.speaker",message:"Every multi-speaker turn must specify a speechMetadata.speaker matching a configured speaker."});return{text:be.text,...ne!=null||se!=null?{speechMetadata:{style:ne,speaker:se}}:{}}})}else if(ce?.turns||ce?.speechMetadata)throw new b({argument:"providerOptions",message:"Structured speech metadata and turns require Gemini 3.8 TTS."});if(Le.text.length===0)throw new b({argument:"text",message:"Speech input must contain a non-empty transcript."});if(B!=null)V.push({type:"unsupported",feature:"speed",details:"Google Gemini TTS models do not support the `speed` option. It was ignored."});if(re!=null)V.push({type:"unsupported",feature:"language",details:"Google Gemini TTS models do not support the `language` option. Language is detected automatically from the input text."});let ye=Re?{wav:"AUDIO_WAV","audio/wav":"AUDIO_WAV",pcm:"AUDIO_L16","audio/l16":"AUDIO_L16",mulaw:"AUDIO_MULAW","audio/mulaw":"AUDIO_MULAW",alaw:"AUDIO_ALAW","audio/alaw":"AUDIO_ALAW"}:{wav:"AUDIO_WAV",pcm:"AUDIO_L16"},ie="wav";if(A!=null&&Object.prototype.hasOwnProperty.call(ye,A))ie=A;else if(A!=null)V.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${A}. Using wav instead.`});return{requestBody:{contents:[{role:"user",parts:Ne}],generationConfig:{responseModalities:["AUDIO"],speechConfig:Ee,...Re&&A!=null?{responseFormat:{audio:{mimeType:ye[ie]}}}:{}}},warnings:V,outputFormat:ye[ie],usesStructuredSpeech:Re}}async doGenerate(w){let x=this.config._internal?.currentDate?.()??new Date,{requestBody:A,warnings:F,outputFormat:B,usesStructuredSpeech:re}=await this.getArgs(w),{value:ee,responseHeaders:V,rawValue:pe}=await g({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:d(this.config.headers?await _(this.config.headers):void 0,w.headers),body:A,failedResponseHandler:Xe,successfulResponseHandler:p(mi),abortSignal:w.abortSignal,fetch:this.config.fetch}),ce,Re;for(let Ne of ee.candidates??[]){for(let ye of Ne.content?.parts??[])if(ye.inlineData?.data){ce=ye.inlineData.data,Re=ye.inlineData.mimeType??void 0;break}if(ce!=null)break}let Le=Ci(Re)??Ti,Ce=ce!=null?N(ce):new Uint8Array(0),Ee=/^audio\/(?:l16|pcm)(?:;|$)/i.test(Re??"")||Re==null&&!re,je=B==="AUDIO_WAV"&&Ee&&Ce.length>0?wi(Ce,Le):Ce;if(B==="AUDIO_L16"&&Ce.length>0&&!re)F.push({type:"unsupported",feature:"outputFormat",details:`Returning raw PCM audio (signed 16-bit little-endian, mono, ${Le} Hz). These bytes have no container header and are not directly playable; see providerMetadata.google for the sample rate and mime type.`});return{audio:je,warnings:F,...ee.usageMetadata!=null&&{usage:ee.usageMetadata},request:{body:JSON.stringify(A)},response:{timestamp:x,modelId:this.modelId,headers:V,body:pe},providerMetadata:{google:{sampleRate:Le,mimeType:Re??null}}}}};function Ci(f){if(f==null)return;let w=/rate=(\d+)/.exec(f);return w?Number.parseInt(w[1],10):void 0}function wi(f,w){let B=w*2,re=f.length,ee=new ArrayBuffer(44+re),V=new DataView(ee);Ot(V,0,"RIFF"),V.setUint32(4,36+re,!0),Ot(V,8,"WAVE"),Ot(V,12,"fmt "),V.setUint32(16,16,!0),V.setUint16(20,1,!0),V.setUint16(22,1,!0),V.setUint32(24,w,!0),V.setUint32(28,B,!0),V.setUint16(32,2,!0),V.setUint16(34,16,!0),Ot(V,36,"data"),V.setUint32(40,re,!0);let pe=new Uint8Array(ee);return pe.set(f,44),pe}function Ot(f,w,x){for(let A=0;A<x.length;A++)f.setUint8(w+A,x.charCodeAt(A))}function Ht(f){if(f==null)return te();let w=f.total_input_tokens??0,x=f.total_output_tokens??0,A=f.total_thought_tokens??0,F=f.total_cached_tokens??0;return{inputTokens:{total:f.total_input_tokens??void 0,noCache:f.total_input_tokens==null?void 0:w-F,cacheRead:f.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:f.total_output_tokens==null&&f.total_thought_tokens==null?void 0:x+A,text:f.total_output_tokens??void 0,reasoning:f.total_thought_tokens??void 0},raw:f}}function On(f){let w=f?.output_tokens_by_modality;if(w==null)return;let x={};for(let A of w)if(A?.modality!=null&&A.tokens!=null)x[A.modality]=A.tokens;return Object.keys(x).length>0?x:void 0}var Si={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function Mn(f){let w=f.toLowerCase();for(let[x,A]of Object.entries(Si))if(w.endsWith(`.${x}`))return A;return"application/octet-stream"}function En(f){let w=f.split("/"),x=w[w.length-1];return x&&x.length>0?x:void 0}function Ii({annotation:f,generateId:w}){switch(f.type){case"url_citation":{let x=f;if(x.url==null||x.url.length===0)return;return{type:"source",sourceType:"url",id:w(),url:x.url,...x.title!=null?{title:x.title}:{}}}case"file_citation":{let x=f,A=x.url??x.document_uri??x.file_name;if(A==null||A.length===0)return;if(A.startsWith("http://")||A.startsWith("https://"))return{type:"source",sourceType:"url",id:w(),url:A,...x.file_name!=null?{title:x.file_name}:{}};let F=x.file_name??En(A),B=Mn(A);return{type:"source",sourceType:"document",id:w(),mediaType:B,title:x.file_name??F??A,...F!=null?{filename:F}:{}}}case"place_citation":{let x=f;if(x.url==null||x.url.length===0)return;return{type:"source",sourceType:"url",id:w(),url:x.url,...x.name!=null?{title:x.name}:{}}}default:return}}function An({block:f,generateId:w}){let x=[];switch(f.type){case"url_context_result":{let A=f.result??[];for(let F of A){if(F?.url==null||F.url.length===0)continue;if(F.status!=null&&F.status!=="success")continue;x.push({type:"source",sourceType:"url",id:w(),url:F.url})}break}case"google_search_result":{let A=f.result??[];for(let F of A){let B=F?.url;if(B==null||B.length===0)continue;x.push({type:"source",sourceType:"url",id:w(),url:B,...F.title!=null?{title:F.title}:{}})}break}case"google_maps_result":{let A=f.result??[];for(let F of A)for(let B of F.places??[]){if(B.url==null||B.url.length===0)continue;x.push({type:"source",sourceType:"url",id:w(),url:B.url,...B.name!=null?{title:B.name}:{}})}break}case"file_search_result":{let A=f.result??[];for(let F of A){if(F==null||typeof F!=="object")continue;let B=F,re=B.url??B.document_uri??B.file_name;if(re==null||re.length===0)continue;if(re.startsWith("http://")||re.startsWith("https://")){x.push({type:"source",sourceType:"url",id:w(),url:re,...B.title!=null?{title:B.title}:{}});continue}let ee=B.file_name??En(re),V=Mn(re);x.push({type:"source",sourceType:"document",id:w(),mediaType:V,title:B.title??B.file_name??ee??re,...ee!=null?{filename:ee}:{}})}break}}return x}function Pt({annotations:f,generateId:w}){if(f==null)return[];let x=new Set,A=[];for(let F of f){let B=Ii({annotation:F,generateId:w});if(B==null)continue;let re=B.sourceType==="url"?`url:${B.url}`:`doc:${B.filename??B.title}`;if(x.has(re))continue;x.add(re),A.push(B)}return A}function Vt({status:f,hasFunctionCall:w}){switch(f){case"completed":return w?"tool-calls":"stop";case"requires_action":return"tool-calls";case"failed":return"error";case"incomplete":return"length";case"cancelled":return"other";default:return"other"}}var ki=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),xi=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function Ri(f){return f.replace(/_call$/,"")}function Oi(f){return f.replace(/_result$/,"")}function dn({warnings:f,generateId:w,includeRawChunks:x,serviceTier:A}){let F,B,re=A,ee,V=!1,pe=!1,ce=new Map,Re=new Set;function Le(Ce){return Ce.sourceType==="url"?`url:${Ce.url}`:`doc:${Ce.filename??Ce.title}`}return new TransformStream({start(Ce){Ce.enqueue({type:"stream-start",warnings:f})},transform(Ce,Ee){if(x)Ee.enqueue({type:"raw",rawValue:Ce.rawValue});if(!Ce.success){ee="failed",Ee.enqueue({type:"error",error:Ce.error});return}let je=Ce.value,Ne=je.event_type;switch(Ne){case"interaction.created":{let ye=je.interaction;F=ye?.id!=null&&ye.id.length>0?ye.id:void 0;let ie=ye?.created,be;if(typeof ie==="string"){let ne=new Date(ie);if(!Number.isNaN(ne.getTime()))be=ne}Ee.enqueue({type:"response-metadata",...F!=null?{id:F}:{},modelId:ye?.model,...be?{timestamp:be}:{}});break}case"step.start":{let ye=je,{step:ie,index:be}=ye,ne=`${F??"interaction"}:${be}`,se=ie?.type;if(se==="model_output"){let Ue=ie?.content?.[0];if(Ue?.type==="text"){ce.set(be,{kind:"text",id:ne,emittedSourceKeys:new Set}),Ee.enqueue({type:"text-start",id:ne});let De=Pt({annotations:Ue.annotations,generateId:w});for(let qe of De){let We=Le(qe);if(Re.has(We))continue;Re.add(We),Ee.enqueue(qe)}}else if(Ue?.type==="image")ce.set(be,{kind:"image",id:ne,...Ue.data!=null?{data:Ue.data}:{},...Ue.mime_type!=null?{mimeType:Ue.mime_type}:{},...Ue.uri!=null?{uri:Ue.uri}:{}});else ce.set(be,{kind:"pending_model_output",id:ne})}else if(se==="thought"){let Ue=ie?.signature;if(ce.set(be,{kind:"reasoning",id:ne,...Ue!=null?{signature:Ue}:{}}),Ee.enqueue({type:"reasoning-start",id:ne}),Array.isArray(ie?.summary)){for(let De of ie.summary)if(De?.type==="text"&&typeof De.text==="string")Ee.enqueue({type:"reasoning-delta",id:ne,delta:De.text})}}else if(se==="processing_call"||se==="processing_result"){let Ue={};if(ie?.signature!=null)Ue.signature=ie.signature;if(F!=null)Ue.interactionId=F;if(se==="processing_call")Ue.processingId=ie?.id||ne;else Ue.processingCallId=ie?.call_id||ne;ce.set(be,{kind:"custom",id:ne,customKind:`google.${se}`,google:Ue})}else if(se==="function_call"){let Ue=ie?.id||ne,De=ie?.name??"unknown";V=!0;let qe={kind:"function_call",id:ne,toolCallId:Ue,toolName:De,argumentsAccum:"",...ie?.signature!=null?{signature:ie.signature}:{}};ce.set(be,qe),Ee.enqueue({type:"tool-input-start",id:Ue,toolName:De})}else if(se!=null&&ki.has(se)){let Ue=se==="mcp_server_tool_call"?ie?.name??"mcp_server_tool":Ri(se),De={kind:"builtin_tool_call",id:ne,blockType:se,toolCallId:ie?.id||ne,toolName:Ue,arguments:ie?.arguments??{},callEmitted:!1};ce.set(be,De)}else if(se!=null&&xi.has(se)){let Ue=se==="mcp_server_tool_result"?ie?.name??"mcp_server_tool":Oi(se),De={kind:"builtin_tool_result",id:ne,blockType:se,callId:ie?.call_id||ne,toolName:Ue,result:ie?.result??null,...ie?.is_error!=null?{isError:ie.is_error}:{},resultEmitted:!1};ce.set(be,De)}else ce.set(be,{kind:"unknown",id:ne});break}case"step.delta":{let ye=je,ie=ce.get(ye.index);if(ie==null)break;let be=ye.delta?.type;if(ie.kind==="pending_model_output"){if(be==="text"||be==="text_annotation"||be==="text_annotation_delta"){let se={kind:"text",id:ie.id,emittedSourceKeys:new Set};ce.set(ye.index,se),ie=se,Ee.enqueue({type:"text-start",id:se.id})}}if(be==="image"&&(ie.kind==="pending_model_output"||ie.kind==="text"||ie.kind==="image")){let se=ye.delta,Ue={};if(F!=null)Ue.interactionId=F;let De=Object.keys(Ue).length>0?{google:Ue}:void 0;if(se?.data!=null&&se.data.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"image/png",data:{type:"data",data:se.data},...De?{providerMetadata:De}:{}});else if(se?.uri!=null&&se.uri.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"image/png",data:{type:"url",url:new URL(se.uri)},...De?{providerMetadata:De}:{}});if(ie.kind==="image")ie.data=void 0,ie.uri=void 0;break}if(be==="video"&&(ie.kind==="pending_model_output"||ie.kind==="text")){let se=ye.delta,Ue={};if(F!=null)Ue.interactionId=F;let De=Object.keys(Ue).length>0?{google:Ue}:void 0;if(se?.data!=null&&se.data.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"video/mp4",data:{type:"data",data:se.data},...De?{providerMetadata:De}:{}});else if(se?.uri!=null&&se.uri.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"video/mp4",data:{type:"url",url:new URL(se.uri)},...De?{providerMetadata:De}:{}});break}let ne=ye.delta;if(ie.kind==="custom"&&(ne?.type==="processing_call"||ne?.type==="processing_result")){if(ne.signature!=null)ie.google.signature=ne.signature;if(ne.type==="processing_call"&&ne.id!=null&&ne.id.length>0)ie.google.processingId=ne.id;if(ne.type==="processing_result"&&ne.call_id!=null&&ne.call_id.length>0)ie.google.processingCallId=ne.call_id}else if(ie.kind==="text"&&ne?.type==="text"){let se=ne.text??"";if(se.length>0)Ee.enqueue({type:"text-delta",id:ie.id,delta:se})}else if(ie.kind==="text"&&(ne?.type==="text_annotation"||ne?.type==="text_annotation_delta")){let se=Pt({annotations:ne.annotations,generateId:w});for(let Ue of se){let De=Le(Ue);if(Re.has(De))continue;Re.add(De),ie.emittedSourceKeys.add(De),Ee.enqueue(Ue)}}else if(ie.kind==="image"&&ne?.type==="image"){if(ne.data!=null)ie.data=ne.data;if(ne.mime_type!=null)ie.mimeType=ne.mime_type;if(ne.uri!=null)ie.uri=ne.uri}else if(ie.kind==="reasoning"){if(ne?.type==="thought_summary"){let se=ne.content;if(se?.type==="text"&&typeof se.text==="string")Ee.enqueue({type:"reasoning-delta",id:ie.id,delta:se.text})}else if(ne?.type==="thought_signature"){let se=ne.signature;if(se!=null)ie.signature=se}}else if(ie.kind==="function_call"&&ne?.type==="arguments_delta"){let se=typeof ne.arguments==="string"?ne.arguments:"";if(se.length>0)ie.argumentsAccum+=se,Ee.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:se});if(ne.id!=null&&ne.id.length>0)ie.toolCallId=ne.id;if(ne.signature!=null)ie.signature=ne.signature;V=!0}else if(ie.kind==="builtin_tool_call"&&ne?.type===ie.blockType){if(ne.id!=null&&ne.id.length>0)ie.toolCallId=ne.id;if(ne.arguments!=null&&typeof ne.arguments==="object")ie.arguments=ne.arguments;if(ne.name!=null&&ie.blockType==="mcp_server_tool_call")ie.toolName=ne.name}else if(ie.kind==="builtin_tool_result"&&ne?.type===ie.blockType){if(ne.call_id!=null&&ne.call_id.length>0)ie.callId=ne.call_id;if(ne.result!==void 0)ie.result=ne.result;if(ne.is_error!=null)ie.isError=ne.is_error;if(ne.name!=null&&ie.blockType==="mcp_server_tool_result")ie.toolName=ne.name}break}case"step.stop":{let ye=je,ie=ce.get(ye.index);if(ie==null)break;if(ie.kind==="text"){let be=F!=null?{google:{interactionId:F}}:void 0;Ee.enqueue({type:"text-end",id:ie.id,...be?{providerMetadata:be}:{}})}else if(ie.kind==="reasoning"){let be={};if(ie.signature!=null)be.signature=ie.signature;if(F!=null)be.interactionId=F;let ne=Object.keys(be).length>0?{google:be}:void 0;Ee.enqueue({type:"reasoning-end",id:ie.id,...ne?{providerMetadata:ne}:{}})}else if(ie.kind==="image"){let be={};if(F!=null)be.interactionId=F;let ne=Object.keys(be).length>0?{google:be}:void 0;if(ie.data!=null&&ie.data.length>0)Ee.enqueue({type:"file",mediaType:ie.mimeType??"image/png",data:{type:"data",data:ie.data},...ne?{providerMetadata:ne}:{}});else if(ie.uri!=null&&ie.uri.length>0)Ee.enqueue({type:"file",mediaType:ie.mimeType??"image/png",data:{type:"url",url:new URL(ie.uri)},...ne?{providerMetadata:ne}:{}})}else if(ie.kind==="function_call"){let be=ie.argumentsAccum.length>0?ie.argumentsAccum:"{}";Ee.enqueue({type:"tool-input-end",id:ie.toolCallId});let ne={};if(ie.signature!=null)ne.signature=ie.signature;if(F!=null)ne.interactionId=F;let se=Object.keys(ne).length>0?{google:ne}:void 0;Ee.enqueue({type:"tool-call",toolCallId:ie.toolCallId,toolName:ie.toolName,input:be,...se?{providerMetadata:se}:{}})}else if(ie.kind==="custom")Ee.enqueue({type:"custom",kind:ie.customKind,providerMetadata:{google:ie.google}});else if(ie.kind==="builtin_tool_call"&&!ie.callEmitted)Ee.enqueue({type:"tool-call",toolCallId:ie.toolCallId,toolName:ie.toolName,input:JSON.stringify(ie.arguments??{}),providerExecuted:!0}),ie.callEmitted=!0;else if(ie.kind==="builtin_tool_result"&&!ie.resultEmitted){Ee.enqueue({type:"tool-result",toolCallId:ie.callId,toolName:ie.toolName,result:ie.result??null}),ie.resultEmitted=!0;let be=An({block:{type:ie.blockType,call_id:ie.callId,result:ie.result},generateId:w});for(let ne of be){let se=Le(ne);if(Re.has(se))continue;Re.add(se),Ee.enqueue(ne)}}ce.delete(ye.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{let ye=je;if(ye.status!=null)ee=ye.status;else if(Ne==="interaction.requires_action")ee="requires_action";else ee="in_progress";break}case"interaction.completed":{pe=!0;let ye=je.interaction;if(ye?.id!=null&&ye.id.length>0)F=ye.id;if(ye?.status!=null)ee=ye.status;if(ye?.usage!=null)B=ye.usage;if(ye?.service_tier!=null)re=ye.service_tier;break}case"error":{let ye=je;ee="failed",Ee.enqueue({type:"error",error:xe({message:ye.error?.message??"Unknown interaction error",type:ye.event_type,code:ye.error?.code??void 0,data:ye})});break}}},flush(Ce){let Ee=!pe&&(ee==null||ee==="in_progress"),je={unified:Ee?"interrupted":Vt({status:ee,hasFunctionCall:V}),raw:Ee?void 0:ee},Ne=On(B),ye={google:{...F!=null?{interactionId:F}:{},...re!=null?{serviceTier:re}:{},...Ne!=null?{outputTokensByModality:Ne}:{}}};Ce.enqueue({type:"finish",finishReason:je,usage:Ht(B),providerMetadata:ye})}})}function Mi({prompt:f,previousInteractionId:w,store:x,mediaResolution:A}){let F=[],B=w!=null&&x===!1,re=w!=null&&x!==!1;if(B)F.push({type:"other",message:"google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted."});let ee=re?Ai({prompt:f,previousInteractionId:w}):f,V=[],pe=[];for(let ce of ee)switch(ce.role){case"system":V.push(ce.content);break;case"user":{let Re=[];for(let Ce of ce.content)if(Ce.type==="text")Re.push({type:"text",text:Ce.text});else if(Ce.type==="file"){let Ee=pn({part:Ce,warnings:F,mediaResolution:A});if(Ee!=null)Re.push(Ee)}let Le=Ni(Re);if(Le.length>0)pe.push({type:"user_input",content:Le});break}case"assistant":{let Re=[],Le=()=>{if(Re.length>0)pe.push({type:"model_output",content:Re}),Re=[]};for(let Ce of ce.content)if(Ce.type==="text")Re.push({type:"text",text:Ce.text});else if(Ce.type==="reasoning"){Le();let Ee=Ce.providerOptions?.google?.signature;pe.push({type:"thought",...Ee!=null?{signature:Ee}:{},summary:Ce.text.length>0?[{type:"text",text:Ce.text}]:void 0})}else if(Ce.type==="file"){let Ee=pn({part:Ce,warnings:F,mediaResolution:A});if(Ee!=null)Re.push(Ee)}else if(Ce.type==="custom"){Le();let Ee=Ce.providerOptions?.google,je=typeof Ee?.signature==="string"?Ee.signature:void 0;if(Ce.kind==="google.processing_call"&&typeof Ee?.processingId==="string")pe.push({type:"processing_call",id:Ee.processingId,...je!=null?{signature:je}:{}});else if(Ce.kind==="google.processing_result"&&typeof Ee?.processingCallId==="string")pe.push({type:"processing_result",call_id:Ee.processingCallId,...je!=null?{signature:je}:{}});else F.push({type:"other",message:`google.interactions: unsupported or invalid custom assistant content part "${Ce.kind}"; part dropped.`})}else if(Ce.type==="tool-call"){Le();let Ee=Ce.providerOptions?.google?.signature,je=typeof Ce.input==="string"?Li(Ce.input):Ce.input??{};pe.push({type:"function_call",id:Ce.toolCallId,name:Ce.toolName,arguments:je,...Ee!=null?{signature:Ee}:{}})}else F.push({type:"other",message:`google.interactions: unsupported assistant content part type "${Ce.type}"; part dropped.`});Le();break}case"tool":{let Re=[];for(let Le of ce.content){if(Le.type!=="tool-result"){F.push({type:"other",message:`google.interactions: unsupported tool message part type "${Le.type}"; part dropped.`});continue}let Ce=ji({toolCallId:Le.toolCallId,toolName:Le.toolName,output:Le.output,signature:Le.providerOptions?.google?.signature,warnings:F});Re.push(Ce)}if(Re.length>0)pe.push({type:"user_input",content:Re});break}}return{input:pe,systemInstruction:V.length>0?V.join(`
9
+ `);for(let ie of Ne.warnings)x.push({requestId:je.id,warning:ie})}let pe=await this.getHeaders(f.headers),ce=`${this.batchConfig.baseURL}/${Tt(w)}:batchGenerateContent`;if(V==null){let{value:je}=await g({url:ce,headers:pe,body:B,failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch});return{batchId:je.name,..._t(je),warnings:x}}let Re=new Blob(V,{type:"application/jsonl"});if(V.length=0,Re.size>No)throw new b({argument:"requests",message:"Google batch input files must not exceed 2 GB."});let{value:Le}=await g({url:`${this.getBaseOrigin()}/upload/v1beta/files`,headers:d(pe,{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(Re.size),"X-Goog-Upload-Header-Content-Type":"application/jsonl"}),body:{file:{display_name:`${A}-input`}},failedResponseHandler:Xe,successfulResponseHandler:Jo,abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{value:Ce}=await ve({url:Le,headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize","Content-Type":"application/jsonl"},body:{content:Re,values:{byteLength:Re.size,mediaType:"application/jsonl"}},failedResponseHandler:Xe,successfulResponseHandler:p(Bo),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{value:Ee}=await g({url:ce,headers:pe,body:{batch:{displayName:A,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{fileName:Ce.file.name}}},failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch});return{batchId:Ee.name,..._t(Ee),providerMetadata:{google:{inputFileId:Ce.file.name,...Ce.file.expirationTime!=null?{inputFileExpiresAt:Ce.file.expirationTime}:{}}},warnings:x}}async doGetBatchStatus(f){return _t(await this.retrieveBatch(f))}async doCancelBatch(f){return await g({url:`${this.batchConfig.baseURL}/${f.batchId}:cancel`,headers:await this.getHeaders(f.headers),body:{},failedResponseHandler:Xe,successfulResponseHandler:p(Fo),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{}}async doListBatches(f){let w=new URL(`${this.batchConfig.baseURL}/batches`);if(f.limit!=null)w.searchParams.set("pageSize",String(f.limit));if(f.cursor!=null)w.searchParams.set("pageToken",f.cursor);let{value:x}=await R({url:w.toString(),headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:p($o),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return{batches:(x.operations??[]).map((A)=>({batchId:A.name,..._t(A)})),...x.nextPageToken!=null?{nextCursor:x.nextPageToken}:{}}}async doGetBatchResults(f){let w=await this.retrieveBatch(f),x=_t(w);if(x.status==="pending")throw new b({argument:"batchId",message:`Google batch "${f.batchId}" is not complete.`});let A=w.metadata?.output?.inlinedResponses?.inlinedResponses??w.response?.inlinedResponses?.inlinedResponses;if(A!=null)return ae(this.iterateBatchResults(A.map((ee)=>({key:ee.metadata.key,response:ee.response,error:ee.error}))));let N=w.metadata?.output?.responsesFile??w.response?.responsesFile;if(N==null){if(x.status==="completed")throw new P({data:w,message:`Google batch "${f.batchId}" completed without batch output.`});return new ReadableStream({start(ee){ee.close()}})}let B=N.split("/").map((ee)=>encodeURIComponent(ee)).join("/"),{value:re}=await R({url:`${this.getBaseOrigin()}/download/v1beta/${B}:download?alt=media`,headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:_e(Ho,{maxLineBytes:this.maxLineBytes}),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return ae(this.iterateBatchResults(re))}async retrieveBatch(f){let{value:w}=await R({url:`${this.batchConfig.baseURL}/${f.batchId}`,headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return w}async*iterateBatchResults(f){for await(let w of f){if(w.error!=null){let ee=Rn(w.error,"Google batch request failed."),V=w.error.status==="CANCELLED"||String(w.error.code)==="1"?"cancelled":"failed";yield{type:"text",id:w.key,status:V,error:ee};continue}if(w.response==null){yield{type:"text",id:w.key,status:"failed",error:{message:"Google returned a batch result without a response or error.",code:"invalid_batch_result"}};continue}let x=await q({value:w.response,schema:Vo});if(x.success&&(x.value.candidates==null||x.value.candidates.length===0)){let ee=x.value.promptFeedback??void 0,V=ee?.blockReason??void 0;yield{type:"text",id:w.key,status:"failed",error:{message:V==null?"Google returned a batch response without any candidates.":`Google blocked the batch request (${V}).`,code:V==null?"invalid_response":"prompt_blocked",...V!=null?{type:V}:{}},...ee!=null?{providerMetadata:{google:{promptFeedback:{blockReason:ee.blockReason??null}}}}:{}};continue}let A=await q({value:w.response,schema:In});if(!A.success){yield{type:"text",id:w.key,status:"failed",error:{message:"Google returned an invalid GenerateContent batch result.",code:"invalid_response"}};continue}let N=Ct.convertGenerateContentResponse({config:this.batchConfig,response:A.value,warnings:[],providerOptionsNames:["google"]}),B=Xo(N);if(B!=null){yield{type:"image",id:w.key,status:"succeeded",result:B};continue}let re=N.content.find((ee)=>!Do.has(ee.type));if(re!=null){yield{type:"text",id:w.key,status:"failed",error:{message:`Google returned a "${re.type}" content block, but that content is not supported in AI SDK text batches.`,code:"unsupported_content"}};continue}yield{type:"text",id:w.key,status:"succeeded",result:N}}}async prepareImageRequest(f){let{prompt:w,n:x,size:A,aspectRatio:N,seed:B,files:re,mask:ee,providerOptions:V}=f.options,pe=[];if(ee!=null)throw new u({functionality:"mask-based image editing in Google batches"});if(x>1)throw new u({functionality:"multiple images per Google batch request"});if(A!=null)pe.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let ce=[];if(w!=null)ce.push({type:"text",text:w});for(let ye of re??[])ce.push(ye.type==="url"?{type:"file",data:{type:"url",url:new URL(ye.url)},mediaType:"image/*"}:{type:"file",data:{type:"data",data:ye.data},mediaType:ye.mediaType});let Re=await h({provider:"google",providerOptions:V,schema:kn}),{responseModalities:Le,imageConfig:Ce,...Ee}=await h({provider:"google",providerOptions:V,schema:Et})??{},je=await h({provider:"google",providerOptions:{google:{...Ee,responseModalities:["IMAGE"],imageConfig:N!=null||Ce!=null?{...Ce,...N!=null?{aspectRatio:N}:{}}:void 0}},schema:Et}),Ne=await Ct.prepareRequest({modelId:f.modelId,config:this.batchConfig,options:{prompt:[{role:"user",content:ce}],seed:B,providerOptions:{google:je??{responseModalities:["IMAGE"]}},tools:Re?.googleSearch!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Re.googleSearch}]:void 0}});return{...Ne,warnings:[...pe,...Ne.warnings]}}async getHeaders(f){return d(this.batchConfig.headers?await _(this.batchConfig.headers):void 0,f)}getBaseOrigin(){return this.batchConfig.baseURL.replace(/\/v1beta$/,"")}};function _t(f){let w=f.metadata?.state??void 0,x=zo(f.metadata?.batchStats),A=f.metadata?.createTime??void 0,N=f.error!=null?Rn(f.error,"Google batch failed."):void 0;return{status:Ko({rawStatus:w,done:f.done??void 0,hasError:N!=null}),...w!=null?{rawStatus:w}:{},...x!=null?{requestCounts:x}:{},...N!=null?{error:N}:{},...A!=null?{createdAt:A}:{}}}function Ko({rawStatus:f,done:w,hasError:x}){if(x)return"failed";if(f==null)return w?"completed":"pending";switch(f.replace(/^(?:BATCH|JOB)_STATE_/,"")){case"SUCCEEDED":return"completed";case"FAILED":case"CANCELLED":case"EXPIRED":return"failed";default:return"pending"}}function zo(f){let w=Rt(f?.requestCount),x=Rt(f?.successfulRequestCount??0),A=Rt(f?.failedRequestCount??0),N=Rt(f?.pendingRequestCount??0);return ge({total:w,pending:N,completed:x,failed:A})}function Rt(f){let w=typeof f==="string"&&/^\d+$/.test(f)?Number(f):f;return typeof w==="number"&&Number.isSafeInteger(w)&&w>=0?w:void 0}function Rn(f,w){return{message:f.message??w,...f.status!=null?{type:f.status}:{},...f.code!=null?{code:String(f.code)}:{}}}var Jo=async({response:f})=>{let w=f.headers.get("x-goog-upload-url");if(w==null)throw new P({data:f.headers,message:"Google did not return a resumable upload URL."});return{value:w}};function Yo(f){let w=f[0]?.modelId;if(w==null)throw new b({argument:"requests",message:"Google batches require at least one request."});for(let x of f)if(x.modelId!==w)throw new b({argument:"requests",message:"Google batches require every request to use the same model because the model is part of the batch endpoint."});return w}function Xo(f){let w=f.content.flatMap((A)=>A.type==="file"&&A.mediaType.startsWith("image/")&&A.data.type==="data"?[M(A.data.data)]:[]);if(w.length===0)return;let x=f.providerMetadata?.google??{};return{images:w,warnings:f.warnings,providerMetadata:{google:{...x,images:w.map(()=>({}))}},response:{timestamp:new Date,modelId:f.response?.modelId??"",headers:f.response?.headers},usage:{inputTokens:f.usage.inputTokens.total,outputTokens:f.usage.outputTokens.total,totalTokens:(f.usage.inputTokens.total??0)+(f.usage.outputTokens.total??0)}}}var Qo=S({id:"google.enterprise_web_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))});a(()=>s(U({fileSearchStoreNames:o(e()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:r().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:e().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()})));var Zo=S({id:"google.file_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),ei={googleSearch:Uo,enterpriseWebSearch:Qo,googleMaps:S({id:"google.google_maps",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),urlContext:S({id:"google.url_context",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),fileSearch:Zo,codeExecution:no,vertexRagStore:S({id:"google.vertex_rag_store",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))})},ti=new Set(["gemini-2.5-flash-image","gemini-3-pro-image-preview","gemini-3.1-flash-image-preview","gemini-nano-banana-2.1"]),ni=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,{},w.config)}get maxImagesPerCall(){if(this.settings.maxImagesPerCall!=null)return this.settings.maxImagesPerCall;return 1}get supportsFileInputs(){return ti.has(this.modelId)?!0:void 0}get supportsMaskInputs(){return this.supportsFileInputs===!0?!1:void 0}get provider(){return this.config.provider}constructor(w,x,A){this.modelId=w,this.settings=x,this.config=A,this.specificationVersion="v4"}async doGenerate(w){if(!this.modelId.startsWith("gemini-"))throw Error("Google image models other than Gemini are no longer supported. Use a model ID that starts with `gemini-`.");let{prompt:x,size:A,aspectRatio:N,seed:B,providerOptions:re,headers:ee,abortSignal:V,files:pe,mask:ce}=w,Re=[];if(ce!=null)throw Error("Gemini image models do not support mask-based image editing.");if(A!=null)Re.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let Le=[];if(x!=null)Le.push({type:"text",text:x});if(pe!=null&&pe.length>0)for(let De of pe)if(De.type==="url")Le.push({type:"file",data:{type:"url",url:new URL(De.url)},mediaType:"image/*"});else Le.push({type:"file",data:{type:"data",data:typeof De.data==="string"?De.data:new Uint8Array(De.data)},mediaType:De.mediaType});let Ce=[{role:"user",content:Le}],Ee=await h({provider:"google",providerOptions:re,schema:kn}),{googleSearch:je,responseModalities:Ne,imageConfig:ye,...ie}=re?.google??{},be=await new Ct(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??C}).doGenerate({prompt:Ce,seed:B,providerOptions:{google:{...ie,responseModalities:["IMAGE"],imageConfig:N!=null||ye!=null?{...ye,...N!=null?{aspectRatio:N}:{}}:void 0}},tools:Ee?.googleSearch!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Ee.googleSearch}]:void 0,headers:ee,abortSignal:V}),ne=this.config._internal?.currentDate?.()??new Date,se=[];for(let De of be.content)if(De.type==="file"&&De.mediaType.startsWith("image/")&&De.data.type==="data")se.push(M(De.data.data));let Ue=be.providerMetadata?.google??{};return{images:se,...be.finishReason.unified==="content-filter"?{isRetryable:!1}:{},warnings:Re,providerMetadata:{google:{...Ue,finishReason:be.finishReason.raw??null,images:se.map(()=>({}))}},response:{timestamp:ne,modelId:this.modelId,headers:be.response?.headers},usage:be.usage?{inputTokens:be.usage.inputTokens.total,outputTokens:be.usage.outputTokens.total,totalTokens:(be.usage.inputTokens.total??0)+(be.usage.outputTokens.total??0)}:void 0}}},oi=class{get provider(){return this.config.provider}constructor(f){this.config=f,this.specificationVersion="v4"}async uploadFile(f){let w=await h({provider:"google",providerOptions:f.providerOptions,schema:ai}),x=d(this.config.headers(),f.headers),A=this.config.fetch??globalThis.fetch,N=[];if(f.filename!=null)N.push({type:"unsupported",feature:"filename"});let B=we(f.data),re=f.mediaType,ee=w?.displayName,V=await A(`${this.config.baseURL.replace(/\/v1beta$/,"")}/upload/v1beta/files`,{method:"POST",headers:{...x,"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(B.length),"X-Goog-Upload-Header-Content-Type":re,"Content-Type":"application/json"},body:JSON.stringify({file:{...ee!=null?{display_name:ee}:{}}}),signal:f.abortSignal});if(!V.ok){let je=await V.text();throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to initiate resumable upload: ${V.status} ${je}`})}let pe=V.headers.get("x-goog-upload-url");if(!pe)throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:"No upload URL returned from initiation request"});let ce=await A(pe,{method:"POST",headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"},body:ii(B),signal:f.abortSignal});if(!ce.ok){let je=await ce.text();throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to upload file data: ${ce.status} ${je}`})}let Re=(await ce.json()).file,Le=w?.pollIntervalMs??2000,Ce=w?.pollTimeoutMs??300000,Ee=Date.now();while(Re.state==="PROCESSING"){if(Date.now()-Ee>Ce)throw new m({name:"GOOGLE_FILES_UPLOAD_TIMEOUT",message:`File processing timed out after ${Ce}ms`});await Oe(Le,{abortSignal:f.abortSignal});let je=/^files\/([^/]+)$/.exec(Re.name),Ne=je!=null?`files/${de(je[1])}`:de(Re.name),{value:ye}=await R({url:`${this.config.baseURL}/${Ne}`,validateUrl:!1,headers:d(x),successfulResponseHandler:p(si),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch});Re=ye}if(Re.state==="FAILED")throw new m({name:"GOOGLE_FILES_UPLOAD_FAILED",message:`File processing failed for ${Re.name}`});return{warnings:N,providerReference:{google:Re.uri},mediaType:Re.mimeType??f.mediaType,providerMetadata:{google:{name:Re.name,displayName:Re.displayName,mimeType:Re.mimeType,sizeBytes:Re.sizeBytes,state:Re.state,uri:Re.uri,...Re.createTime!=null?{createTime:Re.createTime}:{},...Re.updateTime!=null?{updateTime:Re.updateTime}:{},...Re.expirationTime!=null?{expirationTime:Re.expirationTime}:{},...Re.sha256Hash!=null?{sha256Hash:Re.sha256Hash}:{}}}}}};function ii(f){if(f.buffer instanceof ArrayBuffer)return f;return new Uint8Array(f)}var si=a(()=>s(t({name:e(),displayName:e().nullish(),mimeType:e(),sizeBytes:e().nullish(),createTime:e().nullish(),updateTime:e().nullish(),expirationTime:e().nullish(),sha256Hash:e().nullish(),uri:e(),state:e()}))),ai=a(()=>s(U({displayName:e().nullish(),pollIntervalMs:r().positive().nullish(),pollTimeoutMs:r().positive().nullish()}))),ri=a(()=>s(U({pollIntervalMs:r().positive().nullish(),pollTimeoutMs:r().positive().nullish(),personGeneration:i(["dont_allow","allow_adult","allow_all"]).nullish(),negativePrompt:e().nullish(),referenceImages:o(t({bytesBase64Encoded:e().nullish(),gcsUri:e().nullish()})).nullish()})));function li(f){return f.frameImages?.find((w)=>w.frameType==="first_frame")?.image}function ui(f){return li(f)??f.image}function ci(f){return f.frameImages?.find((w)=>w.frameType==="last_frame")?.image}function di(f){if(f.frameImages!=null&&f.frameImages.length>0)return;return f.inputReferences!=null&&f.inputReferences.length>0?f.inputReferences:void 0}function Dt(f,w){if(f.type==="url"){if(f.url.startsWith("gs://"))return{gcsUri:f.url,mimeType:"image/png"};w.push({type:"unsupported",feature:"URL-based image input",details:"Google Generative AI video models require base64-encoded images or GCS URIs. URL will be ignored."});return}return{bytesBase64Encoded:typeof f.data==="string"?f.data:X(f.data),mimeType:f.mediaType||"image/png"}}function pi(f){if(f.bytesBase64Encoded)return{image:{bytesBase64Encoded:f.bytesBase64Encoded,mimeType:"image/png"},referenceType:"asset"};if(f.gcsUri)return{image:{gcsUri:f.gcsUri,mimeType:"image/png"},referenceType:"asset"};return f}function gi(f,w){let x=Dt(f,w);return x!=null?{image:x,referenceType:"asset"}:void 0}var hi=class{get provider(){return this.config.provider}get maxVideosPerCall(){return 4}constructor(f,w){this.modelId=f,this.config=w,this.specificationVersion="v4"}async buildRequest(f){let w=[],x=await h({provider:"google",providerOptions:f.providerOptions,schema:ri}),A=[{}],N=A[0];if(f.prompt!=null)N.prompt=f.prompt;let B=ui(f);if(B!=null){let pe=Dt(B,w);if(pe!=null)N.image=pe}let re=ci(f);if(re!=null){let pe=Dt(re,w);if(pe!=null)N.lastFrame=pe}let ee=di(f);if(ee!=null)N.referenceImages=ee.flatMap((pe)=>{let ce=gi(pe,w);return ce!=null?[ce]:[]});else if(x?.referenceImages!=null)N.referenceImages=x.referenceImages.map((pe)=>pi(pe));let V={sampleCount:f.n};if(f.aspectRatio)V.aspectRatio=f.aspectRatio;if(f.resolution)V.resolution={"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"}[f.resolution]||f.resolution;if(f.duration)V.durationSeconds=f.duration;if(f.seed)V.seed=f.seed;if(x!=null){let pe=x;if(pe.personGeneration!==void 0&&pe.personGeneration!==null)V.personGeneration=pe.personGeneration;if(pe.negativePrompt!==void 0&&pe.negativePrompt!==null)V.negativePrompt=pe.negativePrompt;for(let[ce,Re]of Object.entries(pe))if(!["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","referenceImages"].includes(ce))V[ce]=Re}return{instances:A,parameters:V,warnings:w,googleOptions:x}}async buildCompletedResult(f,w,x,A){let N=f.response;if(!N?.generateVideoResponse?.generatedSamples||N.generateVideoResponse.generatedSamples.length===0)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:`No videos in response. Response: ${JSON.stringify(f)}`});let B=[],re=[],ee=(await _(this.config.headers))?.["x-goog-api-key"];for(let V of N.generateVideoResponse.generatedSamples)if(V.video?.uri){let pe=ee&&Ke(V.video.uri,this.config.baseURL)?`${V.video.uri}${V.video.uri.includes("?")?"&":"?"}key=${ee}`:V.video.uri;B.push({type:"url",url:pe,mediaType:"video/mp4"}),re.push({uri:V.video.uri})}if(B.length===0)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{status:"completed",videos:B,warnings:x,response:{timestamp:A,modelId:this.modelId,headers:w},providerMetadata:{google:{videos:re}}}}async doStart(f){let w=this.config._internal?.currentDate?.()??new Date,{instances:x,parameters:A,warnings:N}=await this.buildRequest(f),{value:B,responseHeaders:re}=await g({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:d(await _(this.config.headers),f.headers),body:{instances:x,parameters:A},successfulResponseHandler:p(ln),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch}),ee=B.name;if(!ee)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No operation name returned from API"});return{operation:{operationName:ee},warnings:N,response:{timestamp:w,modelId:this.modelId,headers:re}}}async doStatus(f){let w=this.config._internal?.currentDate?.()??new Date,{operationName:x}=f.operation,{value:A,responseHeaders:N}=await R({url:`${this.config.baseURL}/${x}`,validateUrl:!1,headers:d(await _(this.config.headers),f.headers),successfulResponseHandler:p(ln),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch});if(!A.done)return{status:"pending",response:{timestamp:w,modelId:this.modelId,headers:N}};if(A.error)return{status:"error",error:`Video generation failed: ${A.error.message}`,response:{timestamp:w,modelId:this.modelId,headers:N}};return this.buildCompletedResult(A,N,[],w)}},ln=a(()=>s(t({name:e().nullish(),done:c().nullish(),error:t({code:r().nullish(),message:e(),status:e().nullish()}).nullish(),response:t({generateVideoResponse:t({generatedSamples:o(t({video:t({uri:e().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}))),mi=a(()=>s(t({candidates:o(t({content:t({parts:o(t({inlineData:t({mimeType:e().nullish(),data:e().nullish()}).nullish()})).nullish()}).nullish()})).nullish(),usageMetadata:y(e(),G()).nullish()})));function fi({text:f,voice:w,providerOptions:x}){let A=x?.google,N=A!=null&&typeof A==="object"?A:void 0,B=N&&"turns"in N?N.turns:void 0,re=[];if(Array.isArray(B)&&B.length>0){for(let pe of B){if(pe==null||typeof pe!=="object"||!("text"in pe)||typeof pe.text!=="string")break;re.push(pe.text)}if(re.length===B.length)f=re.join("")}let ee=N&&"multiSpeakerVoiceConfig"in N?N.multiSpeakerVoiceConfig:void 0,V=ee!=null&&typeof ee==="object"&&"speakerVoiceConfigs"in ee&&Array.isArray(ee.speakerVoiceConfigs)?ee.speakerVoiceConfigs:[];return{text:f,usesCustomVoice:w?.startsWith("voice_")===!0||w?.startsWith("voicekey_")===!0||V.some((pe)=>pe!=null&&typeof pe==="object"&&("voiceConfig"in pe)&&pe.voiceConfig!=null&&typeof pe.voiceConfig==="object"&&("voice"in pe.voiceConfig))}}var yi=()=>t({voiceName:e()}),vi=()=>t({prebuiltVoiceConfig:yi(),voice:Ae().optional()}),un=()=>t({speaker:e().min(1).optional(),style:e().optional()}),cn=a(()=>s(t({speechMetadata:un().optional(),turns:o(t({text:e(),speechMetadata:un().optional()})).min(1).optional(),multiSpeakerVoiceConfig:t({speakerVoiceConfigs:o(t({speaker:e(),voiceConfig:vi()}))}).optional()}))),bi="Kore",Ti=24000,_i=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.modelId=w,this.config=x,this.specificationVersion="v4"}async getArgs({text:w,voice:x=bi,outputFormat:A,instructions:N,speed:B,language:re,providerOptions:ee}){let V=[],pe=this.config.provider.includes("vertex")?["googleVertex","vertex"]:["google"],ce;for(let be of pe)if(ce=await h({provider:be,providerOptions:ee,schema:cn}),ce!=null)break;if(ce==null&&!pe.includes("google"))ce=await h({provider:"google",providerOptions:ee,schema:cn});let Re=!this.modelId.startsWith("gemini-2.5-")&&!this.modelId.startsWith("gemini-3.1-"),Le=fi({text:w,voice:x,providerOptions:{google:ce}});if(Le.usesCustomVoice)throw new b({argument:"voice",message:"Custom voices are not supported. Use a prebuilt voice instead."});let Ce=ce?.multiSpeakerVoiceConfig,Ee=Ce?{multiSpeakerVoiceConfig:Ce}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:x}}},je=w;if(N!=null&&!Re)if(Ce)V.push({type:"unsupported",feature:"instructions",details:"Google Gemini TTS ignores `instructions` when `multiSpeakerVoiceConfig` is set, because prepending them would break multi-speaker transcript parsing."});else je=`${N}: ${w}`;let Ne=[{text:je}];if(Re){if(ce?.turns&&ce.speechMetadata)throw new b({argument:"providerOptions",message:"Set speechMetadata on each turn when using turns."});if(ce?.turns&&w!=="")V.push({type:"unsupported",feature:"text",details:"Google TTS turns replace the top-level text."});Ne=(ce?.turns??[{text:w,speechMetadata:ce?.speechMetadata}]).map((be)=>{let ne=be.speechMetadata?.style??N,se=be.speechMetadata?.speaker;if(Ce&&!Ce.speakerVoiceConfigs.some((Ue)=>Ue.speaker===se))throw new b({argument:"speechMetadata.speaker",message:"Every multi-speaker turn must specify a speechMetadata.speaker matching a configured speaker."});return{text:be.text,...ne!=null||se!=null?{speechMetadata:{style:ne,speaker:se}}:{}}})}else if(ce?.turns||ce?.speechMetadata)throw new b({argument:"providerOptions",message:"Structured speech metadata and turns require Gemini 3.8 TTS."});if(Le.text.length===0)throw new b({argument:"text",message:"Speech input must contain a non-empty transcript."});if(B!=null)V.push({type:"unsupported",feature:"speed",details:"Google Gemini TTS models do not support the `speed` option. It was ignored."});if(re!=null)V.push({type:"unsupported",feature:"language",details:"Google Gemini TTS models do not support the `language` option. Language is detected automatically from the input text."});let ye=Re?{wav:"AUDIO_WAV","audio/wav":"AUDIO_WAV",pcm:"AUDIO_L16","audio/l16":"AUDIO_L16",mulaw:"AUDIO_MULAW","audio/mulaw":"AUDIO_MULAW",alaw:"AUDIO_ALAW","audio/alaw":"AUDIO_ALAW"}:{wav:"AUDIO_WAV",pcm:"AUDIO_L16"},ie="wav";if(A!=null&&Object.prototype.hasOwnProperty.call(ye,A))ie=A;else if(A!=null)V.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${A}. Using wav instead.`});return{requestBody:{contents:[{role:"user",parts:Ne}],generationConfig:{responseModalities:["AUDIO"],speechConfig:Ee,...Re&&A!=null?{responseFormat:{audio:{mimeType:ye[ie]}}}:{}}},warnings:V,outputFormat:ye[ie],usesStructuredSpeech:Re}}async doGenerate(w){let x=this.config._internal?.currentDate?.()??new Date,{requestBody:A,warnings:N,outputFormat:B,usesStructuredSpeech:re}=await this.getArgs(w),{value:ee,responseHeaders:V,rawValue:pe}=await g({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:d(this.config.headers?await _(this.config.headers):void 0,w.headers),body:A,failedResponseHandler:Xe,successfulResponseHandler:p(mi),abortSignal:w.abortSignal,fetch:this.config.fetch}),ce,Re;for(let Ne of ee.candidates??[]){for(let ye of Ne.content?.parts??[])if(ye.inlineData?.data){ce=ye.inlineData.data,Re=ye.inlineData.mimeType??void 0;break}if(ce!=null)break}let Le=Ci(Re)??Ti,Ce=ce!=null?j(ce):new Uint8Array(0),Ee=/^audio\/(?:l16|pcm)(?:;|$)/i.test(Re??"")||Re==null&&!re,je=B==="AUDIO_WAV"&&Ee&&Ce.length>0?wi(Ce,Le):Ce;if(B==="AUDIO_L16"&&Ce.length>0&&!re)N.push({type:"unsupported",feature:"outputFormat",details:`Returning raw PCM audio (signed 16-bit little-endian, mono, ${Le} Hz). These bytes have no container header and are not directly playable; see providerMetadata.google for the sample rate and mime type.`});return{audio:je,warnings:N,...ee.usageMetadata!=null&&{usage:ee.usageMetadata},request:{body:JSON.stringify(A)},response:{timestamp:x,modelId:this.modelId,headers:V,body:pe},providerMetadata:{google:{sampleRate:Le,mimeType:Re??null}}}}};function Ci(f){if(f==null)return;let w=/rate=(\d+)/.exec(f);return w?Number.parseInt(w[1],10):void 0}function wi(f,w){let B=w*2,re=f.length,ee=new ArrayBuffer(44+re),V=new DataView(ee);Ot(V,0,"RIFF"),V.setUint32(4,36+re,!0),Ot(V,8,"WAVE"),Ot(V,12,"fmt "),V.setUint32(16,16,!0),V.setUint16(20,1,!0),V.setUint16(22,1,!0),V.setUint32(24,w,!0),V.setUint32(28,B,!0),V.setUint16(32,2,!0),V.setUint16(34,16,!0),Ot(V,36,"data"),V.setUint32(40,re,!0);let pe=new Uint8Array(ee);return pe.set(f,44),pe}function Ot(f,w,x){for(let A=0;A<x.length;A++)f.setUint8(w+A,x.charCodeAt(A))}function Ht(f){if(f==null)return te();let w=f.total_input_tokens??0,x=f.total_output_tokens??0,A=f.total_thought_tokens??0,N=f.total_cached_tokens??0;return{inputTokens:{total:f.total_input_tokens??void 0,noCache:f.total_input_tokens==null?void 0:w-N,cacheRead:f.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:f.total_output_tokens==null&&f.total_thought_tokens==null?void 0:x+A,text:f.total_output_tokens??void 0,reasoning:f.total_thought_tokens??void 0},raw:f}}function On(f){let w=f?.output_tokens_by_modality;if(w==null)return;let x={};for(let A of w)if(A?.modality!=null&&A.tokens!=null)x[A.modality]=A.tokens;return Object.keys(x).length>0?x:void 0}var Si={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function Mn(f){let w=f.toLowerCase();for(let[x,A]of Object.entries(Si))if(w.endsWith(`.${x}`))return A;return"application/octet-stream"}function En(f){let w=f.split("/"),x=w[w.length-1];return x&&x.length>0?x:void 0}function Ii({annotation:f,generateId:w}){switch(f.type){case"url_citation":{let x=f;if(x.url==null||x.url.length===0)return;return{type:"source",sourceType:"url",id:w(),url:x.url,...x.title!=null?{title:x.title}:{}}}case"file_citation":{let x=f,A=x.url??x.document_uri??x.file_name;if(A==null||A.length===0)return;if(A.startsWith("http://")||A.startsWith("https://"))return{type:"source",sourceType:"url",id:w(),url:A,...x.file_name!=null?{title:x.file_name}:{}};let N=x.file_name??En(A),B=Mn(A);return{type:"source",sourceType:"document",id:w(),mediaType:B,title:x.file_name??N??A,...N!=null?{filename:N}:{}}}case"place_citation":{let x=f;if(x.url==null||x.url.length===0)return;return{type:"source",sourceType:"url",id:w(),url:x.url,...x.name!=null?{title:x.name}:{}}}default:return}}function An({block:f,generateId:w}){let x=[];switch(f.type){case"url_context_result":{let A=f.result??[];for(let N of A){if(N?.url==null||N.url.length===0)continue;if(N.status!=null&&N.status!=="success")continue;x.push({type:"source",sourceType:"url",id:w(),url:N.url})}break}case"google_search_result":{let A=f.result??[];for(let N of A){let B=N?.url;if(B==null||B.length===0)continue;x.push({type:"source",sourceType:"url",id:w(),url:B,...N.title!=null?{title:N.title}:{}})}break}case"google_maps_result":{let A=f.result??[];for(let N of A)for(let B of N.places??[]){if(B.url==null||B.url.length===0)continue;x.push({type:"source",sourceType:"url",id:w(),url:B.url,...B.name!=null?{title:B.name}:{}})}break}case"file_search_result":{let A=f.result??[];for(let N of A){if(N==null||typeof N!=="object")continue;let B=N,re=B.url??B.document_uri??B.file_name;if(re==null||re.length===0)continue;if(re.startsWith("http://")||re.startsWith("https://")){x.push({type:"source",sourceType:"url",id:w(),url:re,...B.title!=null?{title:B.title}:{}});continue}let ee=B.file_name??En(re),V=Mn(re);x.push({type:"source",sourceType:"document",id:w(),mediaType:V,title:B.title??B.file_name??ee??re,...ee!=null?{filename:ee}:{}})}break}}return x}function Pt({annotations:f,generateId:w}){if(f==null)return[];let x=new Set,A=[];for(let N of f){let B=Ii({annotation:N,generateId:w});if(B==null)continue;let re=B.sourceType==="url"?`url:${B.url}`:`doc:${B.filename??B.title}`;if(x.has(re))continue;x.add(re),A.push(B)}return A}function Vt({status:f,hasFunctionCall:w}){switch(f){case"completed":return w?"tool-calls":"stop";case"requires_action":return"tool-calls";case"failed":return"error";case"incomplete":return"length";case"cancelled":return"other";default:return"other"}}var ki=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),xi=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function Ri(f){return f.replace(/_call$/,"")}function Oi(f){return f.replace(/_result$/,"")}function dn({warnings:f,generateId:w,includeRawChunks:x,serviceTier:A}){let N,B,re=A,ee,V=!1,pe=!1,ce=new Map,Re=new Set;function Le(Ce){return Ce.sourceType==="url"?`url:${Ce.url}`:`doc:${Ce.filename??Ce.title}`}return new TransformStream({start(Ce){Ce.enqueue({type:"stream-start",warnings:f})},transform(Ce,Ee){if(x)Ee.enqueue({type:"raw",rawValue:Ce.rawValue});if(!Ce.success){ee="failed",Ee.enqueue({type:"error",error:Ce.error});return}let je=Ce.value,Ne=je.event_type;switch(Ne){case"interaction.created":{let ye=je.interaction;N=ye?.id!=null&&ye.id.length>0?ye.id:void 0;let ie=ye?.created,be;if(typeof ie==="string"){let ne=new Date(ie);if(!Number.isNaN(ne.getTime()))be=ne}Ee.enqueue({type:"response-metadata",...N!=null?{id:N}:{},modelId:ye?.model,...be?{timestamp:be}:{}});break}case"step.start":{let ye=je,{step:ie,index:be}=ye,ne=`${N??"interaction"}:${be}`,se=ie?.type;if(se==="model_output"){let Ue=ie?.content?.[0];if(Ue?.type==="text"){ce.set(be,{kind:"text",id:ne,emittedSourceKeys:new Set}),Ee.enqueue({type:"text-start",id:ne});let De=Pt({annotations:Ue.annotations,generateId:w});for(let qe of De){let Ve=Le(qe);if(Re.has(Ve))continue;Re.add(Ve),Ee.enqueue(qe)}}else if(Ue?.type==="image")ce.set(be,{kind:"image",id:ne,...Ue.data!=null?{data:Ue.data}:{},...Ue.mime_type!=null?{mimeType:Ue.mime_type}:{},...Ue.uri!=null?{uri:Ue.uri}:{}});else ce.set(be,{kind:"pending_model_output",id:ne})}else if(se==="thought"){let Ue=ie?.signature;if(ce.set(be,{kind:"reasoning",id:ne,...Ue!=null?{signature:Ue}:{}}),Ee.enqueue({type:"reasoning-start",id:ne}),Array.isArray(ie?.summary)){for(let De of ie.summary)if(De?.type==="text"&&typeof De.text==="string")Ee.enqueue({type:"reasoning-delta",id:ne,delta:De.text})}}else if(se==="processing_call"||se==="processing_result"){let Ue={};if(ie?.signature!=null)Ue.signature=ie.signature;if(N!=null)Ue.interactionId=N;if(se==="processing_call")Ue.processingId=ie?.id||ne;else Ue.processingCallId=ie?.call_id||ne;ce.set(be,{kind:"custom",id:ne,customKind:`google.${se}`,google:Ue})}else if(se==="function_call"){let Ue=ie?.id||ne,De=ie?.name??"unknown";V=!0;let qe={kind:"function_call",id:ne,toolCallId:Ue,toolName:De,argumentsAccum:"",...ie?.signature!=null?{signature:ie.signature}:{}};ce.set(be,qe),Ee.enqueue({type:"tool-input-start",id:Ue,toolName:De})}else if(se!=null&&ki.has(se)){let Ue=se==="mcp_server_tool_call"?ie?.name??"mcp_server_tool":Ri(se),De={kind:"builtin_tool_call",id:ne,blockType:se,toolCallId:ie?.id||ne,toolName:Ue,arguments:ie?.arguments??{},callEmitted:!1};ce.set(be,De)}else if(se!=null&&xi.has(se)){let Ue=se==="mcp_server_tool_result"?ie?.name??"mcp_server_tool":Oi(se),De={kind:"builtin_tool_result",id:ne,blockType:se,callId:ie?.call_id||ne,toolName:Ue,result:ie?.result??null,...ie?.is_error!=null?{isError:ie.is_error}:{},resultEmitted:!1};ce.set(be,De)}else ce.set(be,{kind:"unknown",id:ne});break}case"step.delta":{let ye=je,ie=ce.get(ye.index);if(ie==null)break;let be=ye.delta?.type;if(ie.kind==="pending_model_output"){if(be==="text"||be==="text_annotation"||be==="text_annotation_delta"){let se={kind:"text",id:ie.id,emittedSourceKeys:new Set};ce.set(ye.index,se),ie=se,Ee.enqueue({type:"text-start",id:se.id})}}if(be==="image"&&(ie.kind==="pending_model_output"||ie.kind==="text"||ie.kind==="image")){let se=ye.delta,Ue={};if(N!=null)Ue.interactionId=N;let De=Object.keys(Ue).length>0?{google:Ue}:void 0;if(se?.data!=null&&se.data.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"image/png",data:{type:"data",data:se.data},...De?{providerMetadata:De}:{}});else if(se?.uri!=null&&se.uri.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"image/png",data:{type:"url",url:new URL(se.uri)},...De?{providerMetadata:De}:{}});if(ie.kind==="image")ie.data=void 0,ie.uri=void 0;break}if(be==="video"&&(ie.kind==="pending_model_output"||ie.kind==="text")){let se=ye.delta,Ue={};if(N!=null)Ue.interactionId=N;let De=Object.keys(Ue).length>0?{google:Ue}:void 0;if(se?.data!=null&&se.data.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"video/mp4",data:{type:"data",data:se.data},...De?{providerMetadata:De}:{}});else if(se?.uri!=null&&se.uri.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"video/mp4",data:{type:"url",url:new URL(se.uri)},...De?{providerMetadata:De}:{}});break}let ne=ye.delta;if(ie.kind==="custom"&&(ne?.type==="processing_call"||ne?.type==="processing_result")){if(ne.signature!=null)ie.google.signature=ne.signature;if(ne.type==="processing_call"&&ne.id!=null&&ne.id.length>0)ie.google.processingId=ne.id;if(ne.type==="processing_result"&&ne.call_id!=null&&ne.call_id.length>0)ie.google.processingCallId=ne.call_id}else if(ie.kind==="text"&&ne?.type==="text"){let se=ne.text??"";if(se.length>0)Ee.enqueue({type:"text-delta",id:ie.id,delta:se})}else if(ie.kind==="text"&&(ne?.type==="text_annotation"||ne?.type==="text_annotation_delta")){let se=Pt({annotations:ne.annotations,generateId:w});for(let Ue of se){let De=Le(Ue);if(Re.has(De))continue;Re.add(De),ie.emittedSourceKeys.add(De),Ee.enqueue(Ue)}}else if(ie.kind==="image"&&ne?.type==="image"){if(ne.data!=null)ie.data=ne.data;if(ne.mime_type!=null)ie.mimeType=ne.mime_type;if(ne.uri!=null)ie.uri=ne.uri}else if(ie.kind==="reasoning"){if(ne?.type==="thought_summary"){let se=ne.content;if(se?.type==="text"&&typeof se.text==="string")Ee.enqueue({type:"reasoning-delta",id:ie.id,delta:se.text})}else if(ne?.type==="thought_signature"){let se=ne.signature;if(se!=null)ie.signature=se}}else if(ie.kind==="function_call"&&ne?.type==="arguments_delta"){let se=typeof ne.arguments==="string"?ne.arguments:"";if(se.length>0)ie.argumentsAccum+=se,Ee.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:se});if(ne.id!=null&&ne.id.length>0)ie.toolCallId=ne.id;if(ne.signature!=null)ie.signature=ne.signature;V=!0}else if(ie.kind==="builtin_tool_call"&&ne?.type===ie.blockType){if(ne.id!=null&&ne.id.length>0)ie.toolCallId=ne.id;if(ne.arguments!=null&&typeof ne.arguments==="object")ie.arguments=ne.arguments;if(ne.name!=null&&ie.blockType==="mcp_server_tool_call")ie.toolName=ne.name}else if(ie.kind==="builtin_tool_result"&&ne?.type===ie.blockType){if(ne.call_id!=null&&ne.call_id.length>0)ie.callId=ne.call_id;if(ne.result!==void 0)ie.result=ne.result;if(ne.is_error!=null)ie.isError=ne.is_error;if(ne.name!=null&&ie.blockType==="mcp_server_tool_result")ie.toolName=ne.name}break}case"step.stop":{let ye=je,ie=ce.get(ye.index);if(ie==null)break;if(ie.kind==="text"){let be=N!=null?{google:{interactionId:N}}:void 0;Ee.enqueue({type:"text-end",id:ie.id,...be?{providerMetadata:be}:{}})}else if(ie.kind==="reasoning"){let be={};if(ie.signature!=null)be.signature=ie.signature;if(N!=null)be.interactionId=N;let ne=Object.keys(be).length>0?{google:be}:void 0;Ee.enqueue({type:"reasoning-end",id:ie.id,...ne?{providerMetadata:ne}:{}})}else if(ie.kind==="image"){let be={};if(N!=null)be.interactionId=N;let ne=Object.keys(be).length>0?{google:be}:void 0;if(ie.data!=null&&ie.data.length>0)Ee.enqueue({type:"file",mediaType:ie.mimeType??"image/png",data:{type:"data",data:ie.data},...ne?{providerMetadata:ne}:{}});else if(ie.uri!=null&&ie.uri.length>0)Ee.enqueue({type:"file",mediaType:ie.mimeType??"image/png",data:{type:"url",url:new URL(ie.uri)},...ne?{providerMetadata:ne}:{}})}else if(ie.kind==="function_call"){let be=ie.argumentsAccum.length>0?ie.argumentsAccum:"{}";Ee.enqueue({type:"tool-input-end",id:ie.toolCallId});let ne={};if(ie.signature!=null)ne.signature=ie.signature;if(N!=null)ne.interactionId=N;let se=Object.keys(ne).length>0?{google:ne}:void 0;Ee.enqueue({type:"tool-call",toolCallId:ie.toolCallId,toolName:ie.toolName,input:be,...se?{providerMetadata:se}:{}})}else if(ie.kind==="custom")Ee.enqueue({type:"custom",kind:ie.customKind,providerMetadata:{google:ie.google}});else if(ie.kind==="builtin_tool_call"&&!ie.callEmitted)Ee.enqueue({type:"tool-call",toolCallId:ie.toolCallId,toolName:ie.toolName,input:JSON.stringify(ie.arguments??{}),providerExecuted:!0}),ie.callEmitted=!0;else if(ie.kind==="builtin_tool_result"&&!ie.resultEmitted){Ee.enqueue({type:"tool-result",toolCallId:ie.callId,toolName:ie.toolName,result:ie.result??null}),ie.resultEmitted=!0;let be=An({block:{type:ie.blockType,call_id:ie.callId,result:ie.result},generateId:w});for(let ne of be){let se=Le(ne);if(Re.has(se))continue;Re.add(se),Ee.enqueue(ne)}}ce.delete(ye.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{let ye=je;if(ye.status!=null)ee=ye.status;else if(Ne==="interaction.requires_action")ee="requires_action";else ee="in_progress";break}case"interaction.completed":{pe=!0;let ye=je.interaction;if(ye?.id!=null&&ye.id.length>0)N=ye.id;if(ye?.status!=null)ee=ye.status;if(ye?.usage!=null)B=ye.usage;if(ye?.service_tier!=null)re=ye.service_tier;break}case"error":{let ye=je;ee="failed",Ee.enqueue({type:"error",error:xe({message:ye.error?.message??"Unknown interaction error",type:ye.event_type,code:ye.error?.code??void 0,data:ye})});break}}},flush(Ce){let Ee=!pe&&(ee==null||ee==="in_progress"),je={unified:Ee?"interrupted":Vt({status:ee,hasFunctionCall:V}),raw:Ee?void 0:ee},Ne=On(B),ye={google:{...N!=null?{interactionId:N}:{},...re!=null?{serviceTier:re}:{},...Ne!=null?{outputTokensByModality:Ne}:{}}};Ce.enqueue({type:"finish",finishReason:je,usage:Ht(B),providerMetadata:ye})}})}function Mi({prompt:f,previousInteractionId:w,store:x,mediaResolution:A}){let N=[],B=w!=null&&x===!1,re=w!=null&&x!==!1;if(B)N.push({type:"other",message:"google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted."});let ee=re?Ai({prompt:f,previousInteractionId:w}):f,V=[],pe=[];for(let ce of ee)switch(ce.role){case"system":V.push(ce.content);break;case"user":{let Re=[];for(let Ce of ce.content)if(Ce.type==="text")Re.push({type:"text",text:Ce.text});else if(Ce.type==="file"){let Ee=pn({part:Ce,warnings:N,mediaResolution:A});if(Ee!=null)Re.push(Ee)}let Le=Ni(Re);if(Le.length>0)pe.push({type:"user_input",content:Le});break}case"assistant":{let Re=[],Le=()=>{if(Re.length>0)pe.push({type:"model_output",content:Re}),Re=[]};for(let Ce of ce.content)if(Ce.type==="text")Re.push({type:"text",text:Ce.text});else if(Ce.type==="reasoning"){Le();let Ee=Ce.providerOptions?.google?.signature;pe.push({type:"thought",...Ee!=null?{signature:Ee}:{},summary:Ce.text.length>0?[{type:"text",text:Ce.text}]:void 0})}else if(Ce.type==="file"){let Ee=pn({part:Ce,warnings:N,mediaResolution:A});if(Ee!=null)Re.push(Ee)}else if(Ce.type==="custom"){Le();let Ee=Ce.providerOptions?.google,je=typeof Ee?.signature==="string"?Ee.signature:void 0;if(Ce.kind==="google.processing_call"&&typeof Ee?.processingId==="string")pe.push({type:"processing_call",id:Ee.processingId,...je!=null?{signature:je}:{}});else if(Ce.kind==="google.processing_result"&&typeof Ee?.processingCallId==="string")pe.push({type:"processing_result",call_id:Ee.processingCallId,...je!=null?{signature:je}:{}});else N.push({type:"other",message:`google.interactions: unsupported or invalid custom assistant content part "${Ce.kind}"; part dropped.`})}else if(Ce.type==="tool-call"){Le();let Ee=Ce.providerOptions?.google?.signature,je=typeof Ce.input==="string"?Li(Ce.input):Ce.input??{};pe.push({type:"function_call",id:Ce.toolCallId,name:Ce.toolName,arguments:je,...Ee!=null?{signature:Ee}:{}})}else N.push({type:"other",message:`google.interactions: unsupported assistant content part type "${Ce.type}"; part dropped.`});Le();break}case"tool":{let Re=[];for(let Le of ce.content){if(Le.type!=="tool-result"){N.push({type:"other",message:`google.interactions: unsupported tool message part type "${Le.type}"; part dropped.`});continue}let Ce=ji({toolCallId:Le.toolCallId,toolName:Le.toolName,output:Le.output,signature:Le.providerOptions?.google?.signature,warnings:N});Re.push(Ce)}if(Re.length>0)pe.push({type:"user_input",content:Re});break}}return{input:pe,systemInstruction:V.length>0?V.join(`
10
10
 
11
- `):void 0,warnings:F}}function pn({part:f,warnings:w,mediaResolution:x}){if(f.data.type==="text")return{type:"text",text:f.data.text};let A=z(f.mediaType),F;switch(A){case"image":F="image";break;case"audio":F="audio";break;case"video":F="video";break;case"application":case"text":F="document";break;default:F=void 0}if(F==null){w.push({type:"other",message:`google.interactions: unsupported file media type "${f.mediaType}"; part dropped.`});return}let B=x!=null&&(F==="image"||F==="video")?{resolution:x}:{},re=F==="video"?Ei({part:f,warnings:w}):{};switch(f.data.type){case"data":{let ee=O({part:f});return{type:F,data:M(f.data.data),mime_type:ee,...B,...re}}case"url":return{type:F,uri:f.data.url.toString(),...K(f.mediaType)?{mime_type:f.mediaType}:{},...B,...re};case"reference":{let ee=H({reference:f.data.reference,provider:"google"});return{type:F,uri:ee,...K(f.mediaType)?{mime_type:f.mediaType}:{},...B,...re}}}}function Ei({part:f,warnings:w}){let x=f.providerOptions?.google?.processing;if(x==null)return{};if(x==="agentic"||x==="static")return{processing:x};if(typeof x==="object"&&!Array.isArray(x)&&x.type==="static"){let A=x;return{processing:{type:"static",...typeof A.startOffset==="number"?{start_offset:`${A.startOffset}s`}:{},...typeof A.endOffset==="number"?{end_offset:`${A.endOffset}s`}:{},...typeof A.fps==="number"?{fps:A.fps}:{}}}}return w.push({type:"other",message:'google.interactions: invalid providerOptions.google.processing on video file part; expected "agentic", "static", or a static processing configuration. Option dropped.'}),{}}function Ai({prompt:f,previousInteractionId:w}){let x=[],A=new Set;for(let F of f){if(F.role==="assistant"){if(F.content.some((B)=>B.providerOptions?.google?.interactionId===w)){for(let B of F.content)if(B.type==="tool-call")A.add(B.toolCallId);continue}x.push(F);continue}if(F.role==="tool"){let B=F.content.filter((re)=>{if(re.type!=="tool-result")return!0;return!A.has(re.toolCallId)});if(B.length===0)continue;x.push({...F,content:B});continue}x.push(F)}return x}function Li(f){try{let w=Q(f);if(w!=null&&typeof w==="object"&&!Array.isArray(w))return w;return{value:w}}catch{return{value:f}}}function ji({toolCallId:f,toolName:w,output:x,signature:A,warnings:F}){let B={type:"function_result",call_id:f,name:w,...A!=null?{signature:A}:{}};switch(x.type){case"text":return{...B,result:x.value};case"json":return{...B,result:JSON.stringify(x.value)};case"error-text":return{...B,is_error:!0,result:x.value};case"error-json":return{...B,is_error:!0,result:JSON.stringify(x.value)};case"execution-denied":return{...B,is_error:!0,result:x.reason??"Tool execution denied by user."};case"content":{let re=[];for(let ee of x.value)if(ee.type==="text")re.push({type:"text",text:ee.text});else if(ee.type==="file"){if(z(ee.mediaType)!=="image"){F.push({type:"other",message:`google.interactions: tool-result file with mediaType "${ee.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let V=Ui({part:ee,warnings:F});if(V!=null)re.push(V)}else F.push({type:"other",message:`google.interactions: tool-result content part type "${ee.type}" is not supported; part dropped.`});return{...B,result:re}}}}function Ui({part:f,warnings:w}){switch(f.data.type){case"data":{let x=K(f.mediaType)?f.mediaType:O({part:{type:"file",mediaType:f.mediaType,data:f.data}});return{type:"image",data:M(f.data.data),mime_type:x}}case"url":return{type:"image",uri:f.data.url.toString(),...K(f.mediaType)?{mime_type:f.mediaType}:{}};case"reference":return{type:"image",uri:H({reference:f.data.reference,provider:"google"}),...K(f.mediaType)?{mime_type:f.mediaType}:{}};case"text":w.push({type:"other",message:'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'});return}}function Ni(f){if(f.length<2)return f;let w=[];for(let x of f){let A=w[w.length-1];if(x.type==="text"&&A!=null&&A.type==="text"&&A.annotations==null&&x.annotations==null){let F={type:"text",text:`${A.text}
11
+ `):void 0,warnings:N}}function pn({part:f,warnings:w,mediaResolution:x}){if(f.data.type==="text")return{type:"text",text:f.data.text};let A=z(f.mediaType),N;switch(A){case"image":N="image";break;case"audio":N="audio";break;case"video":N="video";break;case"application":case"text":N="document";break;default:N=void 0}if(N==null){w.push({type:"other",message:`google.interactions: unsupported file media type "${f.mediaType}"; part dropped.`});return}let B=x!=null&&(N==="image"||N==="video")?{resolution:x}:{},re=N==="video"?Ei({part:f,warnings:w}):{};switch(f.data.type){case"data":{let ee=O({part:f});return{type:N,data:M(f.data.data),mime_type:ee,...B,...re}}case"url":return{type:N,uri:f.data.url.toString(),...K(f.mediaType)?{mime_type:f.mediaType}:{},...B,...re};case"reference":{let ee=H({reference:f.data.reference,provider:"google"});return{type:N,uri:ee,...K(f.mediaType)?{mime_type:f.mediaType}:{},...B,...re}}}}function Ei({part:f,warnings:w}){let x=f.providerOptions?.google?.processing;if(x==null)return{};if(x==="agentic"||x==="static")return{processing:x};if(typeof x==="object"&&!Array.isArray(x)&&x.type==="static"){let A=x;return{processing:{type:"static",...typeof A.startOffset==="number"?{start_offset:`${A.startOffset}s`}:{},...typeof A.endOffset==="number"?{end_offset:`${A.endOffset}s`}:{},...typeof A.fps==="number"?{fps:A.fps}:{}}}}return w.push({type:"other",message:'google.interactions: invalid providerOptions.google.processing on video file part; expected "agentic", "static", or a static processing configuration. Option dropped.'}),{}}function Ai({prompt:f,previousInteractionId:w}){let x=[],A=new Set;for(let N of f){if(N.role==="assistant"){if(N.content.some((B)=>B.providerOptions?.google?.interactionId===w)){for(let B of N.content)if(B.type==="tool-call")A.add(B.toolCallId);continue}x.push(N);continue}if(N.role==="tool"){let B=N.content.filter((re)=>{if(re.type!=="tool-result")return!0;return!A.has(re.toolCallId)});if(B.length===0)continue;x.push({...N,content:B});continue}x.push(N)}return x}function Li(f){try{let w=Q(f);if(w!=null&&typeof w==="object"&&!Array.isArray(w))return w;return{value:w}}catch{return{value:f}}}function ji({toolCallId:f,toolName:w,output:x,signature:A,warnings:N}){let B={type:"function_result",call_id:f,name:w,...A!=null?{signature:A}:{}};switch(x.type){case"text":return{...B,result:x.value};case"json":return{...B,result:JSON.stringify(x.value)};case"error-text":return{...B,is_error:!0,result:x.value};case"error-json":return{...B,is_error:!0,result:JSON.stringify(x.value)};case"execution-denied":return{...B,is_error:!0,result:x.reason??"Tool execution denied by user."};case"content":{let re=[];for(let ee of x.value)if(ee.type==="text")re.push({type:"text",text:ee.text});else if(ee.type==="file"){if(z(ee.mediaType)!=="image"){N.push({type:"other",message:`google.interactions: tool-result file with mediaType "${ee.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let V=Ui({part:ee,warnings:N});if(V!=null)re.push(V)}else N.push({type:"other",message:`google.interactions: tool-result content part type "${ee.type}" is not supported; part dropped.`});return{...B,result:re}}}}function Ui({part:f,warnings:w}){switch(f.data.type){case"data":{let x=K(f.mediaType)?f.mediaType:O({part:{type:"file",mediaType:f.mediaType,data:f.data}});return{type:"image",data:M(f.data.data),mime_type:x}}case"url":return{type:"image",uri:f.data.url.toString(),...K(f.mediaType)?{mime_type:f.mediaType}:{}};case"reference":return{type:"image",uri:H({reference:f.data.reference,provider:"google"}),...K(f.mediaType)?{mime_type:f.mediaType}:{}};case"text":w.push({type:"other",message:'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'});return}}function Ni(f){if(f.length<2)return f;let w=[];for(let x of f){let A=w[w.length-1];if(x.type==="text"&&A!=null&&A.type==="text"&&A.annotations==null&&x.annotations==null){let N={type:"text",text:`${A.text}
12
12
 
13
- ${x.text}`};w[w.length-1]=F;continue}w.push(x)}return w}var Mt=()=>t({modality:e().nullish(),tokens:r().nullish()}).loose(),Ln=()=>t({total_input_tokens:r().nullish(),total_output_tokens:r().nullish(),total_thought_tokens:r().nullish(),total_cached_tokens:r().nullish(),total_tool_use_tokens:r().nullish(),total_tokens:r().nullish(),input_tokens_by_modality:o(Mt()).nullish(),output_tokens_by_modality:o(Mt()).nullish(),cached_tokens_by_modality:o(Mt()).nullish(),tool_use_tokens_by_modality:o(Mt()).nullish(),grounding_tool_count:o(t({type:e().nullish(),count:r().nullish()}).loose()).nullish()}).loose(),jn=()=>i(["in_progress","requires_action","completed","failed","cancelled","incomplete"]),Un=()=>{let f=t({type:n("url_citation"),url:e().nullish(),title:e().nullish(),start_index:r().nullish(),end_index:r().nullish()}).loose(),w=t({type:n("file_citation"),file_name:e().nullish(),document_uri:e().nullish(),url:e().nullish(),page_number:r().nullish(),media_id:e().nullish(),start_index:r().nullish(),end_index:r().nullish(),custom_metadata:y(e(),v()).nullish()}).loose(),x=t({type:n("place_citation"),name:e().nullish(),url:e().nullish(),place_id:e().nullish(),start_index:r().nullish(),end_index:r().nullish()}).loose();return l([f,w,x,t({type:e()}).loose()])},Nn=()=>t({type:e(),text:e().nullish(),data:e().nullish(),mime_type:e().nullish()}).loose(),gn=()=>{let f=t({type:n("text"),text:e(),annotations:o(Un()).nullish()}).loose(),w=t({type:n("image"),data:e().nullish(),mime_type:e().nullish(),resolution:i(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),x=t({type:n("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose();return l([f,w,x,t({type:e()}).loose()])},Gn=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],Dn=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],Pn=()=>{let f=t({type:n("user_input"),content:o(gn()).nullish()}).loose(),w=t({type:n("model_output"),content:o(gn()).nullish()}).loose(),x=t({type:n("function_call"),id:e(),name:e(),arguments:y(e(),v()).nullish(),signature:e().nullish()}).loose(),A=t({type:n("thought"),signature:e().nullish(),summary:o(Nn()).nullish()}).loose(),F=t({type:n("processing_call"),id:e(),signature:e().nullish()}).loose(),B=t({type:n("processing_result"),call_id:e(),signature:e().nullish()}).loose(),re=t({type:i(Gn),id:e(),arguments:y(e(),v()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),ee=t({type:i(Dn),call_id:e(),result:v().nullish(),is_error:c().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose();return l([f,w,x,A,F,B,re,ee,t({type:e()}).loose()])},qt=a(()=>s(t({id:e().nullish(),created:e().nullish(),updated:e().nullish(),status:jn(),model:e().nullish(),agent:e().nullish(),steps:o(Pn()).nullish(),usage:Ln().nullish(),service_tier:e().nullish(),previous_interaction_id:e().nullish(),response_modalities:o(e()).nullish()}).loose())),qn=a(()=>s((()=>{let f=jn(),w=Un(),x=Nn(),A=t({event_type:n("interaction.created"),event_id:e().nullish(),interaction:t({id:e().nullish(),created:e().nullish(),model:e().nullish(),agent:e().nullish(),status:f.nullish()}).loose()}).loose(),F=t({event_type:n("step.start"),event_id:e().nullish(),index:r(),step:Pn()}).loose(),B=t({type:n("text"),text:e()}).loose(),re=t({type:n("thought_summary"),content:x.nullish()}).loose(),ee=t({type:n("thought_signature"),signature:e().nullish()}).loose(),V=t({type:n("arguments_delta"),arguments:e().nullish(),id:e().nullish(),signature:e().nullish()}).loose(),pe=t({type:i(["text_annotation_delta","text_annotation"]),annotations:o(w).nullish()}).loose(),ce=t({type:n("image"),data:e().nullish(),mime_type:e().nullish(),resolution:i(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),Re=t({type:n("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose(),Le=t({type:i(Gn),id:e().nullish(),arguments:y(e(),v()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),Ce=t({type:i(Dn),call_id:e().nullish(),result:v().nullish(),is_error:c().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose(),Ee=t({type:e()}).loose(),je=l([B,ce,Re,re,ee,V,pe,Le,Ce,Ee]),Ne=t({event_type:n("step.delta"),event_id:e().nullish(),index:r(),delta:je}).loose(),ye=t({event_type:n("step.stop"),event_id:e().nullish(),index:r()}).loose(),ie=t({event_type:n("interaction.status_update"),event_id:e().nullish(),interaction_id:e().nullish(),status:f.nullish()}).loose(),be=t({event_type:n("interaction.in_progress"),event_id:e().nullish(),interaction_id:e().nullish(),status:f.nullish()}).loose(),ne=t({event_type:n("interaction.requires_action"),event_id:e().nullish(),interaction_id:e().nullish(),status:f.nullish()}).loose(),se=t({event_type:n("interaction.completed"),event_id:e().nullish(),interaction:t({id:e().nullish(),status:f.nullish(),usage:Ln().nullish(),service_tier:e().nullish()}).loose()}).loose(),Ue=t({event_type:n("error"),event_id:e().nullish(),error:t({code:e().nullish(),message:e().nullish()}).loose().nullish()}).loose(),De=t({event_type:e()}).loose();return l([A,F,Ne,ye,ie,be,ne,se,Ue,De])})())),Gi=a(()=>s(t({previousInteractionId:e().nullish(),store:c().nullish(),agent:e().nullish(),agentConfig:l([t({type:n("dynamic")}).loose(),t({type:n("deep-research"),thinkingSummaries:i(["auto","none"]).nullish(),visualization:i(["off","auto"]).nullish(),collaborativePlanning:c().nullish()})]).nullish(),thinkingLevel:i(["minimal","low","medium","high"]).nullish(),thinkingSummaries:i(["auto","none"]).nullish(),responseFormat:o(l([t({type:n("text"),mimeType:e().nullish(),schema:v().nullish()}).loose(),t({type:n("image"),mimeType:e().nullish(),aspectRatio:i(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:i(["1K","2K","4K","512"]).nullish()}).loose(),t({type:n("audio"),mimeType:e().nullish()}).loose(),t({type:n("video"),aspectRatio:i(["16:9","9:16"]).nullish(),resolution:i(["360p","720p","1080p","4k"]).nullish(),duration:e().nullish(),delivery:i(["inline","uri"]).nullish(),gcsUri:e().nullish()}).loose()])).nullish(),imageConfig:t({aspectRatio:i(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:i(["1K","2K","4K","512"]).nullish()}).nullish(),mediaResolution:i(["low","medium","high","ultra_high"]).nullish(),responseModalities:o(i(["text","image","audio","video","document"])).nullish(),serviceTier:i(["flex","standard","priority"]).nullish(),systemInstruction:e().nullish(),signature:e().nullish(),interactionId:e().nullish(),pollingTimeoutMs:r().int().positive().nullish(),background:c().nullish(),environment:l([e(),t({type:n("remote"),sources:o(l([t({type:n("gcs"),source:e(),target:e().nullish()}),t({type:n("repository"),source:e(),target:e().nullish()}),t({type:n("inline"),content:e(),target:e()})])).nullish(),network:l([n("disabled"),t({allowlist:o(t({domain:e(),transform:o(y(e(),e())).nullish()}))})]).nullish()})]).nullish()})));function mt({signature:f,interactionId:w,processingId:x,processingCallId:A}){let F={};if(f!=null)F.signature=f;if(w!=null)F.interactionId=w;if(x!=null)F.processingId=x;if(A!=null)F.processingCallId=A;return Object.keys(F).length>0?{providerMetadata:{google:F}}:{}}var Di=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),Pi=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function qi(f){return f.replace(/_call$/,"")}function $i(f){return f.replace(/_result$/,"")}function $n({steps:f,generateId:w,interactionId:x}){let A=[],F=!1;if(f==null)return{content:A,hasFunctionCall:F};for(let B of f){if(B==null||typeof B!=="object")continue;let re=B.type;if(typeof re!=="string")continue;switch(re){case"user_input":break;case"model_output":{let ee=B.content??[];for(let V of ee){if(V==null||typeof V!=="object")continue;let pe=V.type;if(pe==="text"){let ce=V.text??"",Re=V.annotations;A.push({type:"text",text:ce,...mt({interactionId:x})});let Le=Pt({annotations:Re,generateId:w});for(let Ce of Le)A.push(Ce)}else if(pe==="image"){let ce=V;if(ce.data!=null&&ce.data.length>0)A.push({type:"file",mediaType:ce.mime_type??"image/png",data:{type:"data",data:ce.data},...mt({interactionId:x})});else if(ce.uri!=null&&ce.uri.length>0)A.push({type:"file",mediaType:ce.mime_type??"image/png",data:{type:"url",url:new URL(ce.uri)},...mt({interactionId:x})})}else if(pe==="video"){let ce=V;if(ce.data!=null&&ce.data.length>0)A.push({type:"file",mediaType:ce.mime_type??"video/mp4",data:{type:"data",data:ce.data},...mt({interactionId:x})});else if(ce.uri!=null&&ce.uri.length>0)A.push({type:"file",mediaType:ce.mime_type??"video/mp4",data:{type:"url",url:new URL(ce.uri)},...mt({interactionId:x})})}}break}case"thought":{let ee=B,V=(Array.isArray(ee.summary)?ee.summary:[]).filter((pe)=>pe?.type==="text"&&typeof pe.text==="string").map((pe)=>pe.text).join(`
14
- `);A.push({type:"reasoning",text:V,...mt({signature:ee.signature,interactionId:x})});break}case"processing_call":{let ee=B,V=ee.id||w();A.push({type:"custom",kind:"google.processing_call",...mt({signature:ee.signature,interactionId:x,processingId:V})});break}case"processing_result":{let ee=B,V=ee.call_id||w();A.push({type:"custom",kind:"google.processing_result",...mt({signature:ee.signature,interactionId:x,processingCallId:V})});break}case"function_call":{F=!0;let ee=B;A.push({type:"tool-call",toolCallId:ee.id,toolName:ee.name,input:JSON.stringify(ee.arguments??{}),...mt({signature:ee.signature,interactionId:x})});break}default:if(Di.has(re)){let ee=B,V=re==="mcp_server_tool_call"?ee.name??"mcp_server_tool":qi(re),pe=JSON.stringify(ee.arguments??{});A.push({type:"tool-call",toolCallId:ee.id||w(),toolName:V,input:pe,providerExecuted:!0})}else if(Pi.has(re)){let ee=B,V=re==="mcp_server_tool_result"?ee.name??"mcp_server_tool":$i(re);A.push({type:"tool-result",toolCallId:ee.call_id||w(),toolName:V,result:ee.result??null});let pe=An({block:B,generateId:w});for(let ce of pe)A.push(ce)}}}return{content:A,hasFunctionCall:F}}var Fi=()=>globalThis.fetch;async function Fn({baseURL:f,interactionId:w,headers:x,fetch:A=Fi()}){if(w==null||w.length===0)return;let F=`${f}/interactions/${encodeURIComponent(w)}/cancel`;try{let B=await A(F,{method:"POST",headers:q(d({"Content-Type":"application/json"},x),ke()),body:"{}"});try{await B.text()}catch{}}catch{}}var Bi=new Set(["completed","failed","cancelled","incomplete"]);function $t(f){return f!=null&&Bi.has(f)}var Hi=1000,Vi=1e4,Wi=1800000;async function Ki({baseURL:f,interactionId:w,headers:x,fetch:A,abortSignal:F,initialDelayMs:B=Hi,maxDelayMs:re=Vi,timeoutMs:ee=Wi}){if(w==null||w.length===0)throw Error("google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.");let V=Date.now(),pe=B,ce=`${f}/interactions/${encodeURIComponent(w)}`,Re=()=>Fn({baseURL:f,interactionId:w,headers:x,fetch:A});try{while(!0){if(F?.aborted)throw await Re(),new DOMException("Polling was aborted","AbortError");if(Date.now()-V>ee)throw Error(`google.interactions: timed out polling interaction ${w} after ${ee}ms.`);await Oe(pe,{abortSignal:F});let{value:Le,rawValue:Ce,responseHeaders:Ee}=await R({url:ce,validateUrl:!1,headers:x,failedResponseHandler:Xe,successfulResponseHandler:p(qt),abortSignal:F,fetch:A});if($t(Le.status))return{response:Le,rawResponse:Ce,responseHeaders:Ee};pe=Math.min(pe*2,re)}}catch(Le){if(Z(Le))await Re();throw Le}}function zi({tools:f,toolChoice:w}){let x=[],A=f?.length?f:void 0;if(A==null)return{tools:void 0,toolChoice:void 0,toolWarnings:x};let F=[];for(let ee of A){if(ee.type==="function"){F.push({type:"function",name:ee.name,description:ee.description??"",parameters:ee.inputSchema});continue}if(ee.type==="provider"){let V=ee.args??{};switch(ee.id){case"google.google_search":{let pe=V.searchTypes,ce;if(pe!=null&&typeof pe==="object"){let Re=[];if(pe.webSearch!=null)Re.push("web_search");if(pe.imageSearch!=null)Re.push("image_search");if(Re.length>0)ce=Re}F.push({type:"google_search",...ce!=null?{search_types:ce}:{}});break}case"google.code_execution":F.push({type:"code_execution"});break;case"google.url_context":F.push({type:"url_context"});break;case"google.file_search":F.push({type:"file_search",...V.fileSearchStoreNames!=null?{file_search_store_names:V.fileSearchStoreNames}:{},...V.topK!=null?{top_k:V.topK}:{},...V.metadataFilter!=null?{metadata_filter:V.metadataFilter}:{}});break;case"google.google_maps":F.push({type:"google_maps",...V.latitude!=null?{latitude:V.latitude}:{},...V.longitude!=null?{longitude:V.longitude}:{},...V.enableWidget!=null?{enable_widget:V.enableWidget}:{}});break;case"google.computer_use":F.push({type:"computer_use",environment:V.environment??"browser",...V.excludedPredefinedFunctions!=null?{excludedPredefinedFunctions:V.excludedPredefinedFunctions}:{}});break;case"google.mcp_server":F.push({type:"mcp_server",...V.name!=null?{name:V.name}:{},...V.url!=null?{url:V.url}:{},...V.headers!=null?{headers:V.headers}:{},...V.allowedTools!=null?{allowed_tools:V.allowedTools}:{}});break;case"google.retrieval":{let pe=V.vertexAiSearchConfig??void 0;F.push({type:"retrieval",...V.retrievalTypes!=null?{retrieval_types:V.retrievalTypes}:{retrieval_types:["vertex_ai_search"]},...pe!=null?{vertex_ai_search_config:pe}:{}});break}default:x.push({type:"unsupported",feature:`provider-defined tool ${ee.id}`,details:`provider-defined tool ${ee.id} is not supported by google.interactions; tool dropped.`})}continue}x.push({type:"unsupported",feature:`tool of type ${ee.type}`,details:"Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."})}let B=F.some((ee)=>ee.type==="function"),re;if(w!=null&&B)switch(w.type){case"auto":re="auto";break;case"required":re="any";break;case"none":re="none";break;case"tool":re={allowed_tools:{mode:"validated",tools:[w.toolName]}}}return{tools:F.length>0?F:void 0,toolChoice:re,toolWarnings:x}}var Ji=3,Yi=500;function Xi({baseURL:f,interactionId:w,headers:x,fetch:A,abortSignal:F,maxRetries:B=Ji,retryDelayMs:re=Yi}){if(w.length===0)throw Error("google.interactions: cannot stream a background interaction without an id.");let ee={...x,accept:"text/event-stream"},V,pe=!1,ce=0,Re=!1,Le,Ce=new AbortController,Ee=()=>Ce.abort();if(F!=null)if(F.aborted)Ce.abort();else F.addEventListener("abort",Ee,{once:!0});let je=Ce.signal;function Ne(){let ie=`${f}/interactions/${encodeURIComponent(w)}`,be=new URLSearchParams({stream:"true"});if(V!=null)be.set("last_event_id",V);return`${ie}?${be.toString()}`}async function ye(){let{value:ie}=await R({url:Ne(),validateUrl:!1,headers:ee,failedResponseHandler:Xe,successfulResponseHandler:D(qn),abortSignal:je,fetch:A});return ie.getReader()}return new ReadableStream({async start(ie){try{while(!pe&&!je.aborted){if(Le==null)try{Le=await ye(),Re=!1}catch(be){if(Z(be)||je.aborted){ie.error(be);return}if(ce++,ce>=B){ie.error(be);return}await Oe(re*ce,{abortSignal:je});continue}try{let{done:be,value:ne}=await Le.read();if(be){if(Le=void 0,pe)break;if(!Re){if(ce++,ce>=B){ie.error(Error("google.interactions: SSE stream closed without producing any events."));return}await Oe(re*ce,{abortSignal:je})}else ce=0;continue}if(Re=!0,ne.success){let se=ne.value;if(typeof se.event_id==="string"&&se.event_id.length>0)V=se.event_id;if(se.event_type==="interaction.completed"||se.event_type==="error")pe=!0}ie.enqueue(ne)}catch(be){if(Z(be)||je.aborted){ie.error(be);return}if(Le=void 0,ce++,ce>=B){ie.error(be);return}await Oe(re*ce,{abortSignal:je})}}ie.close()}catch(be){ie.error(be)}finally{if(F!=null)F.removeEventListener("abort",Ee);if(Le?.cancel().catch(()=>{}),Le=void 0,je.aborted&&!pe)await Fn({baseURL:f,interactionId:w,headers:x,fetch:A})}},cancel(){Ce.abort(),Le?.cancel().catch(()=>{}),Le=void 0}})}function Qi({response:f,warnings:w,generateId:x,includeRawChunks:A,headerServiceTier:F}){return new ReadableStream({start(B){B.enqueue({type:"stream-start",warnings:w});let re=typeof f.id==="string"&&f.id.length>0?f.id:void 0,ee,V=f.created;if(typeof V==="string"){let Ne=new Date(V);if(!Number.isNaN(Ne.getTime()))ee=Ne}if(B.enqueue({type:"response-metadata",...re!=null?{id:re}:{},modelId:f.model??void 0,...ee?{timestamp:ee}:{}}),A)B.enqueue({type:"raw",rawValue:f});let{content:pe,hasFunctionCall:ce}=$n({steps:f.steps??null,generateId:x,interactionId:re}),Re=0,Le=()=>`${re??"agent"}:${Re++}`;for(let Ne of pe)switch(Ne.type){case"text":{let ye=Le(),ie=Ne.providerMetadata;if(B.enqueue({type:"text-start",id:ye}),Ne.text.length>0)B.enqueue({type:"text-delta",id:ye,delta:Ne.text});B.enqueue({type:"text-end",id:ye,...ie?{providerMetadata:ie}:{}});break}case"reasoning":{let ye=Le(),ie=Ne.providerMetadata;if(B.enqueue({type:"reasoning-start",id:ye}),Ne.text.length>0)B.enqueue({type:"reasoning-delta",id:ye,delta:Ne.text});B.enqueue({type:"reasoning-end",id:ye,...ie?{providerMetadata:ie}:{}});break}case"tool-call":{let ye=Ne.providerMetadata;B.enqueue({type:"tool-input-start",id:Ne.toolCallId,toolName:Ne.toolName,...Ne.providerExecuted?{providerExecuted:Ne.providerExecuted}:{}}),B.enqueue({type:"tool-input-delta",id:Ne.toolCallId,delta:Ne.input}),B.enqueue({type:"tool-input-end",id:Ne.toolCallId}),B.enqueue({type:"tool-call",toolCallId:Ne.toolCallId,toolName:Ne.toolName,input:Ne.input,...Ne.providerExecuted?{providerExecuted:Ne.providerExecuted}:{},...ye?{providerMetadata:ye}:{}});break}case"tool-result":B.enqueue({type:"tool-result",toolCallId:Ne.toolCallId,toolName:Ne.toolName,result:Ne.result});break;case"source":case"file":B.enqueue(Ne)}let Ce=f.service_tier??F,Ee={unified:Vt({status:f.status,hasFunctionCall:ce}),raw:f.status},je={google:{...re!=null?{interactionId:re}:{},...Ce!=null?{serviceTier:Ce}:{}}};B.enqueue({type:"finish",finishReason:Ee,usage:Ht(f.usage),providerMetadata:je}),B.close()}})}var Zi=class f{static[k](w){return{...E({modelId:w.modelId,config:w.config}),agent:w.agent}}static[T](w){return new f(w.agent!=null?{agent:w.agent}:w.modelId,w.config)}constructor(w,x){if(this.specificationVersion="v4",typeof w==="string")this.modelId=w,this.agent=void 0;else if("managedAgent"in w)this.modelId=w.managedAgent,this.agent=w.managedAgent;else this.modelId=w.agent,this.agent=w.agent;this.config=x}get provider(){return this.config.provider}get supportedUrls(){if(this.config.supportedUrls)return this.config.supportedUrls();return{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(w){let x=[],A=await h({provider:"google",providerOptions:w.providerOptions,schema:Gi}),F=this.agent!=null;if(!F){if(w.frequencyPenalty!=null)x.push({type:"unsupported",feature:"frequencyPenalty"});if(w.presencePenalty!=null)x.push({type:"unsupported",feature:"presencePenalty"})}let B=w.tools!=null&&w.tools.length>0,re,ee;if(B){let ye=zi({tools:w.tools,toolChoice:w.toolChoice});re=ye.tools,ee=ye.toolChoice,x.push(...ye.toolWarnings)}let V=[];if(w.responseFormat?.type==="json")if(F)x.push({type:"other",message:"google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."});else{let ye={type:"text",mime_type:"application/json",...w.responseFormat.schema!=null?{schema:w.responseFormat.schema}:{}};V.push(ye)}if(A?.responseFormat!=null){for(let ye of A.responseFormat)if(ye.type==="text")V.push(ht({type:"text",mime_type:ye.mimeType??void 0,schema:ye.schema??void 0}));else if(ye.type==="image")V.push(ht({type:"image",mime_type:ye.mimeType??void 0,aspect_ratio:ye.aspectRatio??void 0,image_size:ye.imageSize??void 0}));else if(ye.type==="audio")V.push(ht({type:"audio",mime_type:ye.mimeType??void 0}));else if(ye.type==="video")V.push(ht({type:"video",aspect_ratio:ye.aspectRatio??void 0,resolution:ye.resolution??void 0,duration:ye.duration??void 0,delivery:ye.delivery??void 0,gcs_uri:ye.gcsUri??void 0}))}let{input:pe,systemInstruction:ce,warnings:Re}=Mi({prompt:w.prompt,previousInteractionId:A?.previousInteractionId??void 0,store:A?.store??void 0,mediaResolution:A?.mediaResolution??void 0});x.push(...Re);let Le=ce,Ce=A?.systemInstruction??void 0;if(Le!=null&&Ce!=null)x.push({type:"other",message:"google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."});else if(Le==null&&Ce!=null)Le=Ce;let Ee;if(F){let ye=[];if(w.temperature!=null)ye.push("temperature");if(w.topP!=null)ye.push("topP");if(w.topK!=null)ye.push("topK");if(w.frequencyPenalty!=null)ye.push("frequencyPenalty");if(w.presencePenalty!=null)ye.push("presencePenalty");if(w.seed!=null)ye.push("seed");if(w.stopSequences!=null&&w.stopSequences.length>0)ye.push("stopSequences");if(w.maxOutputTokens!=null)ye.push("maxOutputTokens");if(A?.thinkingLevel!=null)ye.push("thinkingLevel");if(A?.thinkingSummaries!=null)ye.push("thinkingSummaries");if(A?.imageConfig!=null)ye.push("imageConfig");if(ye.length>0)x.push({type:"other",message:`google.interactions: ${ye.join(", ")} ${ye.length===1?"is":"are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`});Ee=void 0}else if(Ee=ht({temperature:w.temperature??void 0,top_p:w.topP??void 0,top_k:w.topK??void 0,seed:w.seed??void 0,stop_sequences:w.stopSequences!=null&&w.stopSequences.length>0?w.stopSequences:void 0,max_output_tokens:w.maxOutputTokens??void 0,thinking_level:A?.thinkingLevel??void 0,thinking_summaries:A?.thinkingSummaries??void 0,tool_choice:ee}),A?.imageConfig!=null){let ye=V.some((ie)=>ie.type==="image");if(x.push({type:"other",message:ye?"google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.":'google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.'}),!ye)V.push({type:"image",mime_type:"image/png",...A.imageConfig.aspectRatio!=null?{aspect_ratio:A.imageConfig.aspectRatio}:{},...A.imageConfig.imageSize!=null?{image_size:A.imageConfig.imageSize}:{}})}let je;if(F&&A?.agentConfig!=null){let ye=A.agentConfig;if(ye.type==="deep-research")je=ht({type:"deep-research",thinking_summaries:ye.thinkingSummaries??void 0,visualization:ye.visualization??void 0,collaborative_planning:ye.collaborativePlanning??void 0});else if(ye.type==="dynamic")je={type:"dynamic"}}let Ne;if(A?.environment!=null)if(!F)x.push({type:"other",message:"google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."});else if(typeof A.environment==="string")Ne=A.environment;else{let ye=A.environment,ie=ye.sources?.map((ne)=>{if(ne.type==="inline")return{type:"inline",content:ne.content,target:ne.target};return ht({type:ne.type,source:ne.source,target:ne.target??void 0})}),be;if(ye.network==="disabled")be="disabled";else if(ye.network!=null)be={allowlist:ye.network.allowlist.map((ne)=>ht({domain:ne.domain,transform:ne.transform??void 0}))};Ne=ht({type:"remote",sources:ie!=null&&ie.length>0?ie:void 0,network:be})}return{args:ht({...F?{agent:this.agent}:{model:this.modelId},input:pe,system_instruction:Le,tools:re,response_format:V.length>0?V:void 0,response_modalities:A?.responseModalities!=null?A.responseModalities:void 0,previous_interaction_id:A?.previousInteractionId??void 0,service_tier:A?.serviceTier??void 0,store:A?.store??void 0,generation_config:Ee!=null&&Object.keys(Ee).length>0?Ee:void 0,agent_config:je,environment:Ne,background:A?.background??void 0}),warnings:x,isAgent:F,isBackground:A?.background===!0,pollingTimeoutMs:A?.pollingTimeoutMs??void 0}}async doGenerate(w){let{args:x,warnings:A,isAgent:F,isBackground:B,pollingTimeoutMs:re}=await this.getArgs(w),ee=`${this.config.baseURL}/interactions`,V=d(this.config.headers?await _(this.config.headers):void 0,w.headers),{responseHeaders:pe,value:ce,rawValue:Re}=await g({url:ee,headers:V,body:x,failedResponseHandler:Xe,successfulResponseHandler:p(qt),abortSignal:w.abortSignal,fetch:this.config.fetch});if((F||B)&&!$t(ce.status)){let ne=await Ki({baseURL:this.config.baseURL,interactionId:ce.id,headers:V,fetch:this.config.fetch,abortSignal:w.abortSignal,timeoutMs:re});ce=ne.response,Re=ne.rawResponse,pe=ne.responseHeaders??pe}let Le=typeof ce.id==="string"&&ce.id.length>0?ce.id:void 0,{content:Ce,hasFunctionCall:Ee}=$n({steps:ce.steps??null,generateId:this.config.generateId??C,interactionId:Le}),je={unified:Vt({status:ce.status,hasFunctionCall:Ee}),raw:ce.status},Ne=ce.service_tier??pe?.["x-gemini-service-tier"]??void 0,ye=On(ce.usage),ie={google:{...Le!=null?{interactionId:Le}:{},...Ne!=null?{serviceTier:Ne}:{},...ye!=null?{outputTokensByModality:ye}:{}}},be;if(typeof ce.created==="string"){let ne=new Date(ce.created);if(!Number.isNaN(ne.getTime()))be=ne}return{content:Ce,finishReason:je,usage:Ht(ce.usage),warnings:A,providerMetadata:ie,request:{body:x},response:{headers:pe,body:Re,...Le!=null?{id:Le}:{},...be?{timestamp:be}:{},modelId:ce.model??void 0}}}async doStream(w){let{args:x,warnings:A,isBackground:F,pollingTimeoutMs:B}=await this.getArgs(w),re=`${this.config.baseURL}/interactions`,ee=d(this.config.headers?await _(this.config.headers):void 0,w.headers);if(F)return this.doStreamBackground({args:x,warnings:A,url:re,mergedHeaders:ee,options:w,pollingTimeoutMs:B});let V={...x,stream:!0},{responseHeaders:pe,value:ce}=await g({url:re,headers:ee,body:V,failedResponseHandler:Xe,successfulResponseHandler:D(qn),abortSignal:w.abortSignal,fetch:this.config.fetch}),Re=pe?.["x-gemini-service-tier"],Le=dn({warnings:A,generateId:this.config.generateId??C,includeRawChunks:w.includeRawChunks,serviceTier:Re});return{stream:ce.pipeThrough(Le),request:{body:V},response:{headers:pe}}}async doStreamBackground({args:w,warnings:x,url:A,mergedHeaders:F,options:B,pollingTimeoutMs:re}){let{responseHeaders:ee,value:V}=await g({url:A,headers:F,body:w,failedResponseHandler:Xe,successfulResponseHandler:p(qt),abortSignal:B.abortSignal,fetch:this.config.fetch}),pe=V.id;if(pe==null||pe.length===0)throw Error("google.interactions: background POST response did not include an interaction id; cannot stream the result.");let ce=ee?.["x-gemini-service-tier"];if($t(V.status))return{stream:Qi({response:V,warnings:x,generateId:this.config.generateId??C,includeRawChunks:B.includeRawChunks,headerServiceTier:ce}),request:{body:w},response:{headers:ee}};let Re=Xi({baseURL:this.config.baseURL,interactionId:pe,headers:F,fetch:this.config.fetch,abortSignal:B.abortSignal}),Le=dn({warnings:x,generateId:this.config.generateId??C,includeRawChunks:B.includeRawChunks,serviceTier:ce});return{stream:Re.pipeThrough(Le),request:{body:w},response:{headers:ee}}}};function ht(f){let w={};for(let[x,A]of Object.entries(f)){if(A===void 0)continue;w[x]=A}return w}function Bn(f){let w=new URL(f),x=w.pathname.split("/"),A=x.at(-1);if(A==="v1beta"||A==="v1alpha")x.pop(),w.pathname=x.join("/")||"/";return w}function Wt(f,w){let x=Bn(f);return x.protocol=x.protocol==="https:"?"wss:":"ws:",x.pathname=`${x.pathname.replace(/\/$/,"")}/ws/${w}`,x}var es=class{constructor(){this.turnCounter=0,this.inputTranscriptionCounter=0,this.inputTranscriptionBuffer="",this.inputTranscriptionBoundary="none",this.preserveInputTranscriptionAcrossTurnComplete=!1,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,this.turnClosed=!1,this.inputAudioRate=16000}get responseId(){return`google-resp-${this.turnCounter}`}get itemId(){return`google-item-${this.turnCounter}`}beginTurnIfClosed(){if(!this.turnClosed)return;this.turnCounter++,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,this.turnClosed=!1,this.preserveInputTranscriptionAcrossTurnComplete=!1}accumulateInputTranscription({text:f,finished:w}){if(!f){if(w===!0)this.finishInputTranscription();return}let x=w!=null;if(this.inputTranscriptionBuffer!==""&&(this.inputTranscriptionBoundary==="interrupted"||this.inputTranscriptionBoundary==="turn-complete"&&!x))this.finishInputTranscription();this.inputTranscriptionBoundary="none",this.inputTranscriptionBuffer+=f;let A={itemId:`google-input-${this.inputTranscriptionCounter}`,transcript:this.inputTranscriptionBuffer};if(w===!0)this.finishInputTranscription();return A}finishInputTranscription(){if(this.inputTranscriptionBuffer==="")return;this.inputTranscriptionCounter++,this.inputTranscriptionBuffer=""}parseServerEvent(f){let w=f;if(w.setupComplete!=null)return{type:"session-created",raw:f};if(w.toolCall!=null)return this.beginTurnIfClosed(),(w.toolCall.functionCalls??[]).flatMap((x)=>{let A=JSON.stringify(x.args??{});return[{type:"function-call-arguments-delta",responseId:this.responseId,itemId:this.itemId,callId:x.id,delta:A,raw:f},{type:"function-call-arguments-done",responseId:this.responseId,itemId:this.itemId,callId:x.id,name:x.name,arguments:A,raw:f}]});if(w.toolCallCancellation!=null)return{type:"custom",rawType:"toolCallCancellation",raw:f};if(w.goAway!=null)return{type:"custom",rawType:"goAway",raw:f};if(w.sessionResumptionUpdate!=null)return{type:"custom",rawType:"sessionResumptionUpdate",raw:f};if(w.serverContent!=null)return this.parseServerContent(w.serverContent,f);if(w.inputTranscription!=null){let x=this.accumulateInputTranscription(w.inputTranscription);if(x!=null)return{type:"input-transcription-completed",...x,raw:f}}return{type:"custom",rawType:String(Object.keys(w)[0]),raw:f}}parseServerContent(f,w){let x=[];if(f.interrupted)this.inputTranscriptionBoundary="interrupted",this.preserveInputTranscriptionAcrossTurnComplete=!0,this.turnClosed=!0,x.push({type:"speech-started",raw:w});if(f.modelTurn?.parts){this.beginTurnIfClosed();for(let A of f.modelTurn.parts){if(A.inlineData?.data)this.hasAudio=!0,x.push({type:"audio-delta",responseId:this.responseId,itemId:this.itemId,delta:A.inlineData.data,raw:w});if(A.text)this.hasText=!0,x.push({type:"text-delta",responseId:this.responseId,itemId:this.itemId,delta:A.text,raw:w})}}if(f.outputTranscription?.text)this.hasTranscript=!0,x.push({type:"audio-transcript-delta",responseId:this.responseId,itemId:this.itemId,delta:f.outputTranscription.text,raw:w});if(f.inputTranscription!=null){let A=this.accumulateInputTranscription(f.inputTranscription);if(A!=null)x.push({type:"input-transcription-completed",...A,raw:w})}if(f.generationComplete)x.push({type:"custom",rawType:"generationComplete",raw:w});if(f.interactionStatus!=null)x.push({type:"custom",rawType:"interactionStatus",raw:w});if(f.waitingForInput)x.push({type:"custom",rawType:"waitingForInput",raw:w});if(f.turnComplete){if(this.hasAudio)x.push({type:"audio-done",responseId:this.responseId,itemId:this.itemId,raw:w});if(this.hasText)x.push({type:"text-done",responseId:this.responseId,itemId:this.itemId,raw:w});if(this.hasTranscript)x.push({type:"audio-transcript-done",responseId:this.responseId,itemId:this.itemId,raw:w});if(x.push({type:"response-done",responseId:this.responseId,status:"completed",raw:w}),this.turnClosed=!0,this.preserveInputTranscriptionAcrossTurnComplete)this.preserveInputTranscriptionAcrossTurnComplete=!1;else if(this.inputTranscriptionBoundary!=="interrupted")this.inputTranscriptionBoundary="turn-complete"}if(x.length===0)return{type:"custom",rawType:"serverContent",raw:w};return x.length===1?x[0]:x}serializeClientEvent(f,w){switch(f.type){case"session-update":if(f.config.inputAudioFormat?.rate!=null)this.inputAudioRate=f.config.inputAudioFormat.rate;return{setup:Ft(f.config,w)};case"input-audio-append":return{realtimeInput:{audio:{data:f.audio,mimeType:`audio/pcm;rate=${this.inputAudioRate}`}}};case"input-audio-commit":return{realtimeInput:{audioStreamEnd:!0}};case"input-audio-clear":case"response-create":case"response-cancel":case"conversation-item-truncate":return null;case"conversation-item-create":{let x=f.item;switch(x.type){case"text-message":return{realtimeInput:{text:x.text}};case"function-call-output":return ns(x);case"audio-message":return null}break}}return null}};function ts(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)?f:{output:f}}async function ns(f){let w=await J({text:f.output}),x=w.success?ts(w.value):{output:f.output};return{toolResponse:{functionResponses:[{id:f.callId,name:f.name,response:x}]}}}function os(f){let w=f.split("/").at(-1)?.toLowerCase()??"";return/^gemini-\d+\.\d+-live\b.*thinking/.test(w)}function Ft(f,w){let x={model:Tt(w)},{google:A,...F}=f?.providerOptions??{},B=L(A)?A:void 0,re={};if(f?.outputModalities!=null)re.responseModalities=f.outputModalities.map((Re)=>Re.toUpperCase());else re.responseModalities=["AUDIO"];if(f?.voice!=null)re.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:f.voice}}};if(x.generationConfig=re,f?.instructions!=null)x.systemInstruction={parts:[{text:f.instructions}]};if(f?.tools!=null&&f.tools.length>0)x.tools=[{functionDeclarations:f.tools.map((Re)=>({name:Re.name,description:Re.description,parametersJsonSchema:Re.parameters,...B?.defaultToolBehavior!=null?{behavior:B.defaultToolBehavior}:{}}))}];if(f?.inputAudioTranscription!=null)x.inputAudioTranscription={};if(f?.outputAudioTranscription!=null)x.outputAudioTranscription={};let ee=F.generationConfig,V=B?.thinkingConfig??(L(ee)&&L(ee.thinkingConfig)?ee.thinkingConfig:void 0),pe=os(w)&&V?.thinkingLevel==null&&V?.thinkingBudget==null?{...V,thinkingLevel:"low"}:B?.thinkingConfig,ce=()=>{if(pe==null)return;let Re=L(x.generationConfig)?x.generationConfig:re;x.generationConfig={...Re,thinkingConfig:pe}};if(f?.providerOptions==null)return ce(),x;if(Object.assign(x,F),B?.translationConfig!=null)x.generationConfig={...L(x.generationConfig)?x.generationConfig:re,translationConfig:B.translationConfig};return ce(),x}var is="google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained";function ss(f){let w=Bn(f);return w.pathname=`${w.pathname.replace(/\/$/,"")}/v1alpha/auth_tokens`,w.toString()}function as(f){return Wt(f,is).toString()}var rs=class{constructor(f,w){this.specificationVersion="v4",this.mapper=new es,this.modelId=f,this.provider=w.provider,this.config=w}async doCreateClientSecret(f){let w=this.config.fetch??fetch,x=this.config.headers()["x-goog-api-key"];if(!x)throw Error("Google Generative AI API key is required for realtime token creation.");let A=Date.now(),F=(f.expiresAfterSeconds??60)*1000,B=new Date(A+F).toISOString(),re=new Date(A+F+1800000).toISOString(),ee=Ft(f.sessionConfig,this.modelId),V=await w(`${ss(this.config.baseURL)}?key=${encodeURIComponent(x)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uses:0,expireTime:re,newSessionExpireTime:B,bidiGenerateContentSetup:ee})});if(!V.ok){let ce=await V.text();throw Error(`Google realtime auth token request failed: ${V.status} ${ce}`)}let pe=await V.json();return{token:pe.name,url:as(this.config.baseURL),expiresAt:pe.expireTime?Math.floor(new Date(pe.expireTime).getTime()/1000):void 0}}getWebSocketConfig(f){return{url:`${f.url}?access_token=${encodeURIComponent(f.token)}`}}parseServerEvent(f){return this.mapper.parseServerEvent(f)}serializeClientEvent(f){return this.mapper.serializeClientEvent(f,this.modelId)}buildSessionConfig(f){return Ft(f,this.modelId)}};var ls=a(()=>s(t({languageCodes:o(e()).optional(),customVocabulary:o(e()).optional(),wordTimestamp:c().optional(),diarization:c().optional(),mode:i(["SMART","VERBATIM"]).optional()}))),us="google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",cs=3000;function ds(f,w){let x=Wt(f,us);return x.searchParams.set("key",w),x}function hn(f){return f.includes("-live")}var ps=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.modelId=w,this.config=x,this.specificationVersion="v4"}async parseOptions(w){return h({provider:"google",providerOptions:w,schema:ls})}async doGenerate(w){if(hn(this.modelId))throw new b({argument:"modelId",message:`Model '${this.modelId}' only supports streaming transcription. Use experimental_streamTranscribe, or a unary model such as 'gemini-3.5-transcribe'.`});let x=this.config._internal?.currentDate?.()??new Date,A=[],F=ms(await this.parseOptions(w.providerOptions)),B={model:this.modelId,input:[{type:"audio",data:M(w.audio),mime_type:w.mediaType}],...F!=null?{generation_config:{transcription_config:F}}:{}},{value:re,responseHeaders:ee,rawValue:V}=await g({url:`${this.config.baseURL}/interactions`,headers:d(this.config.headers?await _(this.config.headers):void 0,w.headers),body:B,failedResponseHandler:Xe,successfulResponseHandler:p(vs),abortSignal:w.abortSignal,fetch:this.config.fetch}),pe="",ce=[];for(let Re of re.steps??[])for(let Le of Re.content??[]){if(Le.type!=="text"||Le.text==null)continue;pe+=Le.text;for(let Ce of Le.annotations??[]){if(Ce.type!=="word_info")continue;let Ee=mn(Ce.start_offset),je=mn(Ce.end_offset);if(Ce.text==null||Ee==null||je==null)continue;ce.push({text:Ce.text,startSecond:Ee,endSecond:je})}}return{text:pe,segments:ce,language:void 0,durationInSeconds:void 0,warnings:A,...re.usage!=null&&{usage:re.usage},response:{timestamp:x,modelId:this.modelId,headers:ee,body:V},...re.usage!=null?{providerMetadata:{google:{usage:re.usage}}}:{}}}async doStream(w){if(!hn(this.modelId))throw new b({argument:"modelId",message:`Model '${this.modelId}' does not support streaming transcription. Use a live model such as 'gemini-3.5-transcribe-live'.`});let x=this.config._internal?.currentDate?.()??new Date,A=[],F=await this.parseOptions(w.providerOptions);fs(w.inputAudioFormat);let B=d(this.config.headers?await _(this.config.headers):void 0,w.headers),re;for(let[pe,ce]of Object.entries(B))if(pe.toLowerCase()==="x-goog-api-key"&&ce!=null)re=ce;if(re==null)throw Error("Google Generative AI API key is required for streaming transcription.");let ee=Object.fromEntries(Object.entries(B).filter(([pe])=>pe.toLowerCase()!=="x-goog-api-key")),V={model:Tt(this.modelId),inputAudioTranscription:hs(F)??{}};return{request:{body:V},response:{timestamp:x,modelId:this.modelId},stream:gs({webSocket:this.config.webSocket,url:ds(this.config.baseURL,re),headers:ee,setup:V,inputAudioRate:w.inputAudioFormat.rate??16000,finishGraceMs:this.config._internal?.finishGraceMs??cs,warnings:A,audio:w.audio,abortSignal:w.abortSignal,includeRawChunks:w.includeRawChunks})}}};function gs({webSocket:f,url:w,headers:x,setup:A,inputAudioRate:F,finishGraceMs:B,warnings:re,audio:ee,abortSignal:V,includeRawChunks:pe}){let ce=!1,Re=()=>{};return new ReadableStream({start:(Le)=>{let Ce,Ee,je,Ne=new Promise((Ve)=>{je=Ve}),ye=0,ie="",be="",ne="",se,Ue=!1,De,qe,We=()=>`google-segment-${ye}`,nt=()=>{if(qe!=null)clearTimeout(qe),qe=void 0},Ke=()=>{if(ce||!Ue)return;nt(),qe=setTimeout(()=>{qe=void 0,ze()},B)};Re=(Ve)=>{if(nt(),Ce!=null)Ce.cancel().catch(()=>{});else ee.cancel().catch(()=>{});Ee?.close(Ve)};let Qe=(Ve)=>{if(ce)return;ce=!0,Re(),Le.error(Ve)},pt=()=>{if(ie===""){if(ne==="")return;ie=ne}ne="",Le.enqueue({type:"transcript-final",id:We(),text:ie}),be+=be===""?ie:` ${ie}`,ie="",ye++},ze=()=>{if(ce)return;pt(),ce=!0,Le.enqueue({type:"finish",text:be,segments:[],language:se,durationInSeconds:void 0,usage:De,...De!=null?{providerMetadata:{google:{usageMetadata:De}}}:{}}),Le.close(),Re(1000)},ot=async(Ve)=>{Ce=ee.getReader();try{while(!0){let{done:rt,value:lt}=await Ce.read();if(rt||ce)break;Ve.send(JSON.stringify({realtimeInput:{audio:{data:M(lt),mimeType:`audio/pcm;rate=${F}`}}})),await ue(Ve)}}finally{Ce.releaseLock(),Ce=void 0}if(!ce)Ve.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),Ue=!0,Ke()};Ee=fe({url:w,headers:x,webSocket:f,abortSignal:V,onAbort:Qe,onProcessingError:Qe,onOpen:(Ve)=>{Le.enqueue({type:"stream-start",warnings:re}),Ve.send(JSON.stringify({setup:A})),Ne.then(()=>ce?void 0:ot(Ve)).catch(Qe)},onMessageText:async(Ve)=>{if(ce)return;let rt=await J({text:Ve});if(!rt.success)return;let lt=rt.value;if(pe)Le.enqueue({type:"raw",rawValue:lt});if(lt.setupComplete!=null)je();if(lt.usageMetadata!=null)De=lt.usageMetadata;if(lt.error!=null){Qe(Error(lt.error.message??"Google Live API error"));return}let dt=lt.serverContent,Fe=dt?.interimInputTranscription;if(Fe?.text)Ke(),ne=Fe.text,Le.enqueue({type:"transcript-partial",id:We(),text:Fe.text});let tt=dt?.inputTranscription??lt.inputTranscription;if(tt!=null){if(tt.languageCode!=null)se=tt.languageCode;if(tt.text)Ke(),ne="",ie+=tt.text,Le.enqueue({type:"transcript-delta",id:We(),delta:tt.text});if(tt.finished===!0)pt()}if(dt?.turnComplete)pt();let Je=dt?.interactionStatus;if(Ue&&(Je==="IDLE"||Je==="REQUIRES_ACTION"||dt?.turnComplete===!0&&Je==null))ze()},onSocketError:()=>{Qe(Error("Google Live transcription error"))},onClose:({code:Ve,reason:rt})=>{if(ce)return;if(Ue){ze();return}Qe(Error(`Google Live transcription WebSocket closed unexpectedly before finishing (code ${Ve??"unknown"}${rt?`, reason: ${rt}`:""}).`))}})},cancel:()=>{if(ce)return;ce=!0,Re()}})}function hs(f){if(f==null)return;let w={};if(f.languageCodes!=null)w.languageCodes=f.languageCodes;if(f.customVocabulary!=null)w.customVocabulary=f.customVocabulary;if(f.wordTimestamp!=null)w.wordTimestamp=f.wordTimestamp;if(f.diarization!=null)w.diarization=f.diarization;if(f.mode!=null)w.mode=f.mode;return Object.keys(w).length>0?w:void 0}function ms(f){if(f==null)return;let w={};if(f.languageCodes!=null)w.language_codes=f.languageCodes;if(f.customVocabulary!=null)w.custom_vocabulary=f.customVocabulary;if(f.mode!=null||f.diarization===!0||f.wordTimestamp===!0)w.mode={type:(f.mode??"VERBATIM").toLowerCase(),...f.diarization===!0?{diarization_mode:"speaker"}:{},...f.wordTimestamp===!0?{timestamp_granularities:["word"]}:{}};return Object.keys(w).length>0?w:void 0}function mn(f){if(f==null)return;let w=Number.parseFloat(f);return Number.isFinite(w)?w:void 0}function fs(f){if(f.type!=="audio/pcm"||f.rate!=null&&f.rate!==16000)throw new b({argument:"inputAudioFormat",message:"The Gemini Live transcription API only supports 16kHz 16-bit PCM input audio."})}var ys=()=>t({type:e().nullish(),text:e().nullish(),speaker:e().nullish(),start_offset:e().nullish(),end_offset:e().nullish()}),vs=a(()=>s(t({status:e().nullish(),steps:o(t({type:e().nullish(),content:o(t({type:e().nullish(),text:e().nullish(),annotations:o(ys()).nullish()})).nullish()})).nullish(),usage:y(e(),G()).nullish()}))),bs=a(()=>s(t({echoTargetLanguage:c().optional()}))),Ts="google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",_s=1000,Cs=24000,ws=128;function Ss(f,w){let x=Wt(f,Ts);return x.searchParams.set("key",w),x}var Is=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.specificationVersion="v4",this.modelId=w,this.config=x}async doStream(w){if(w.targetLanguage==null)throw new b({argument:"targetLanguage",message:`targetLanguage is required for translation model '${this.modelId}'.`});let x=this.config._internal?.currentDate?.()??new Date,A=await h({provider:"google",providerOptions:w.providerOptions,schema:bs}),F=[];if(Ms(w.inputAudioFormat),w.sourceLanguage!=null)F.push({type:"unsupported",feature:"sourceLanguage",details:"The Gemini Live translation API auto-detects the source language and does not accept a source language."});if(w.outputAudioFormat!=null)F.push({type:"unsupported",feature:"outputAudioFormat",details:"The Gemini Live API always outputs 24kHz 16-bit PCM audio and does not accept an output audio format."});let B=d(this.config.headers(),w.headers),re;for(let[pe,ce]of Object.entries(B))if(pe.toLowerCase()==="x-goog-api-key"&&ce!=null)re=ce;if(re==null)throw Error("Google Generative AI API key is required for streaming translation.");let ee=Object.fromEntries(Object.entries(B).filter(([pe])=>pe.toLowerCase()!=="x-goog-api-key")),V=Os({modelId:this.modelId,targetLanguage:w.targetLanguage,providerOptions:A});return{request:{body:V},response:{timestamp:x,modelId:this.modelId},stream:ks({webSocket:this.config.webSocket,url:Ss(this.config.baseURL,re),headers:ee,setup:V,inputAudioRate:w.inputAudioFormat.rate??16000,finishGraceMs:this.config._internal?.finishGraceMs??_s,warnings:F,audio:w.audio,abortSignal:w.abortSignal,includeRawChunks:w.includeRawChunks})}}};function ks({webSocket:f,url:w,headers:x,setup:A,inputAudioRate:F,finishGraceMs:B,warnings:re,audio:ee,abortSignal:V,includeRawChunks:pe}){let ce=!1,Re=()=>{};return new ReadableStream({start:(Le)=>{let Ce,Ee,je,Ne=new Promise((Fe)=>{je=Fe}),ye=0,ie="",be="",ne="",se="",Ue=!1,De,qe=!1,We=!1,nt=0,Ke,Qe=()=>`google-item-${ye}`,pt=()=>{if(Ke!=null)clearTimeout(Ke),Ke=void 0},ze=()=>{if(ce||Ke!=null)return;Ke=setTimeout(()=>{Ke=void 0,rt()},B)},ot=()=>{qe=!0,nt=0,pt()};Re=(Fe)=>{if(pt(),Ce!=null)Ce.cancel().catch(()=>{});else ee.cancel().catch(()=>{});Ee?.close(Fe)};let Ve=(Fe)=>{if(ce)return;ce=!0,Re(),Le.error(Fe)},rt=()=>{if(ce)return;if(be!==""||se!=="")lt();ce=!0,Le.enqueue({type:"finish",sourceText:ie,outputText:ne,usage:De}),Le.close(),Re(1000)},lt=()=>{if(be!=="")Le.enqueue({type:"source-transcript-final",id:Qe(),text:be}),ie+=be,be="";if(se!=="")Le.enqueue({type:"output-text-final",id:Qe(),text:se}),ne+=se,se="";ye++},dt=async(Fe)=>{Ce=ee.getReader();try{while(!0){let{done:tt,value:Je}=await Ce.read();if(tt||ce)break;Fe.send(JSON.stringify({realtimeInput:{audio:{data:M(Je),mimeType:`audio/pcm;rate=${F}`}}})),await ue(Fe)}}finally{Ce.releaseLock(),Ce=void 0}if(!ce){if(Fe.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),Ue=!0,We&&!qe)ze()}};Ee=fe({url:w,headers:x,webSocket:f,abortSignal:V,onAbort:Ve,onProcessingError:Ve,onOpen:(Fe)=>{Le.enqueue({type:"stream-start",warnings:re}),Fe.send(JSON.stringify({setup:A})),Ne.then(()=>ce?void 0:dt(Fe)).catch(Ve)},onMessageText:async(Fe)=>{if(ce)return;let tt=await J({text:Fe});if(!tt.success)return;let Je=tt.value;if(pe)Le.enqueue({type:"raw",rawValue:Je});if(Je.setupComplete!=null)je();if(Je.usageMetadata!=null)De=xs(De,Je.usageMetadata);if(Je.error!=null){Ve(Error(Je.error.message??"Google Live API error"));return}let Be=Je.serverContent?.inputTranscription?.text??Je.inputTranscription?.text;if(Be)ot(),be+=Be,Le.enqueue({type:"source-transcript-delta",id:Qe(),delta:Be});let Pe=Je.serverContent;if(Pe==null)return;for(let ut of Pe.modelTurn?.parts??[])if(ut.inlineData?.data){Le.enqueue({type:"audio",id:Qe(),audio:ut.inlineData.data});let at=Rs(ut.inlineData.data);if(Ue&&at!=null){if(nt+=at,nt>=B){rt();return}}else ot()}if(Pe.outputTranscription?.text)ot(),se+=Pe.outputTranscription.text,Le.enqueue({type:"output-text-delta",id:Qe(),delta:Pe.outputTranscription.text});if(Pe.turnComplete){if(lt(),qe=!1,We=!0,Ue)ze()}},onSocketError:()=>{Ve(Error("Google Live translation error"))},onClose:({code:Fe,reason:tt})=>{if(ce)return;if(Ke!=null){rt();return}Ve(Error(`Google Live translation WebSocket closed unexpectedly before finishing (code ${Fe??"unknown"}${tt?`, reason: ${tt}`:""}).`))}})},cancel:()=>{if(ce)return;ce=!0,Re()}})}function xs(f,w){let x=f?.inputAudioTokens,A=f?.outputAudioTokens;for(let F of w.promptTokensDetails??[])if(F.modality==="AUDIO"&&F.tokenCount!=null)x=(x??0)+F.tokenCount;for(let F of w.responseTokensDetails??[])if(F.modality==="AUDIO"&&F.tokenCount!=null)A=(A??0)+F.tokenCount;if(x==null&&A==null)return f;return{...f,...x!=null?{inputAudioTokens:x}:{},...A!=null?{outputAudioTokens:A}:{}}}function Rs(f){let w;try{w=N(f)}catch{return}if(w.byteLength<2)return;let x=new DataView(w.buffer,w.byteOffset,w.byteLength),A=Math.floor(w.byteLength/2);for(let F=0;F<A;F++)if(Math.abs(x.getInt16(F*2,!0))>ws)return;return A/Cs*1000}function Os({modelId:f,targetLanguage:w,providerOptions:x}){return{model:Tt(f),generationConfig:{responseModalities:["AUDIO"],translationConfig:{targetLanguageCode:w,...x?.echoTargetLanguage!=null?{echoTargetLanguage:x.echoTargetLanguage}:{}}},inputAudioTranscription:{},outputAudioTranscription:{}}}function Ms(f){if(f.type!=="audio/pcm"||f.rate!=null&&f.rate!==16000)throw new b({argument:"inputAudioFormat",message:"The Gemini Live translation API only supports 16kHz 16-bit PCM input audio."})}var Es="https://generativelanguage.googleapis.com/v1beta",As=/^https:\/\/generativelanguage\.googleapis\.com\/v1beta\/files\/.*$/,Ls=["text/html","text/css","text/plain","text/xml","text/csv","text/rtf","text/javascript","application/json","application/pdf","image/bmp","image/jpeg","image/png","image/webp","video/mp4","video/mpeg","video/quicktime","video/avi","video/x-flv","video/mpg","video/webm","video/wmv","video/3gpp"],js=/^https:\/\/.*$/;function Us(f){return/(^|\/)gemini-/.test(f)&&!/(^|\/)gemini-2\.0/.test(f)}function Kt(f={}){let w=Y(f.baseURL)??Es,x=f.name??"google.generative-ai",A=()=>q({"x-goog-api-key":he({apiKey:f.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...f.headers},`ai-sdk-google/${zn}`),F=(be,ne=be==null||Us(be))=>({"*":[As,new RegExp(`^${w}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")],...ne?Object.fromEntries(Ls.map((se)=>[se,[js]])):{}}),B={provider:x,baseURL:w,headers:A,generateId:f.generateId??C,fetch:f.fetch},re=(be)=>new Ct(be,{...B,supportedUrls:()=>F(be)}),ee=()=>new Wo({provider:`${x.replace(/\.generative-ai$/,"")}.batch`,maxLineBytes:f.batchResultDownloads?.maxLineBytes,config:B,supportedUrls:F(void 0,!1)}),V=(be)=>new Qn(be,{provider:x,baseURL:w,headers:A,fetch:f.fetch}),pe=(be,ne={})=>new ni(be,ne,{provider:x,baseURL:w,headers:A,fetch:f.fetch}),ce=()=>new oi({provider:x,baseURL:w,headers:A,fetch:f.fetch}),Re=(be)=>new hi(be,{provider:x,baseURL:w,headers:A,fetch:f.fetch,generateId:f.generateId??C}),Le=(be)=>new rs(be,{provider:`${x}.realtime`,baseURL:w,headers:A,fetch:f.fetch}),Ce=(be)=>new Is(be,{provider:`${x}.speech-translation`,baseURL:w,headers:A,webSocket:f.webSocket}),Ee=(be)=>new _i(be,{provider:`${x}.speech`,baseURL:w,headers:A,fetch:f.fetch}),je=(be)=>new ps(be,{provider:`${x}.transcription`,baseURL:w,headers:A,fetch:f.fetch,webSocket:f.webSocket}),Ne=Object.assign((be)=>Le(be),{getToken:async(be)=>{let ne=await Le(be.model).doCreateClientSecret({sessionConfig:be.sessionConfig,expiresAfterSeconds:be.expiresAfterSeconds});return{token:ne.token,url:ne.url,expiresAt:ne.expiresAt}}}),ye=(be)=>new Zi(be,{provider:`${x}.interactions`,baseURL:w,headers:A,generateId:f.generateId??C,fetch:f.fetch}),ie=function(be){if(new.target)throw Error("The Google Generative AI model function cannot be called with the new keyword.");return re(be)};return ie.specificationVersion="v4",ie.languageModel=re,ie.chat=re,ie.generativeAI=re,ie.decisionModel=(be)=>new et({model:re(be),provider:`${x.replace(/\.generative-ai$/,"")}.decision`}),ie.evaluationModel=ie.decisionModel,ie.experimental_batch=ee,ie.embedding=V,ie.embeddingModel=V,ie.textEmbedding=V,ie.textEmbeddingModel=V,ie.image=pe,ie.imageModel=pe,ie.video=Re,ie.videoModel=Re,ie.experimental_realtime=Ne,ie.files=ce,ie.speech=Ee,ie.speechModel=Ee,ie.transcription=je,ie.transcriptionModel=je,ie.translation=Ce,ie.speechTranslationModel=Ce,ie.interactions=ye,ie.tools=ei,ie}var Fs=Kt();var Ns=Ie(Kt);function Qs(){oe("google",Ns)}export{Qs as register};
13
+ ${x.text}`};w[w.length-1]=N;continue}w.push(x)}return w}var Mt=()=>t({modality:e().nullish(),tokens:r().nullish()}).loose(),Ln=()=>t({total_input_tokens:r().nullish(),total_output_tokens:r().nullish(),total_thought_tokens:r().nullish(),total_cached_tokens:r().nullish(),total_tool_use_tokens:r().nullish(),total_tokens:r().nullish(),input_tokens_by_modality:o(Mt()).nullish(),output_tokens_by_modality:o(Mt()).nullish(),cached_tokens_by_modality:o(Mt()).nullish(),tool_use_tokens_by_modality:o(Mt()).nullish(),grounding_tool_count:o(t({type:e().nullish(),count:r().nullish()}).loose()).nullish()}).loose(),jn=()=>i(["in_progress","requires_action","completed","failed","cancelled","incomplete"]),Un=()=>{let f=t({type:n("url_citation"),url:e().nullish(),title:e().nullish(),start_index:r().nullish(),end_index:r().nullish()}).loose(),w=t({type:n("file_citation"),file_name:e().nullish(),document_uri:e().nullish(),url:e().nullish(),page_number:r().nullish(),media_id:e().nullish(),start_index:r().nullish(),end_index:r().nullish(),custom_metadata:y(e(),v()).nullish()}).loose(),x=t({type:n("place_citation"),name:e().nullish(),url:e().nullish(),place_id:e().nullish(),start_index:r().nullish(),end_index:r().nullish()}).loose();return l([f,w,x,t({type:e()}).loose()])},Nn=()=>t({type:e(),text:e().nullish(),data:e().nullish(),mime_type:e().nullish()}).loose(),gn=()=>{let f=t({type:n("text"),text:e(),annotations:o(Un()).nullish()}).loose(),w=t({type:n("image"),data:e().nullish(),mime_type:e().nullish(),resolution:i(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),x=t({type:n("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose();return l([f,w,x,t({type:e()}).loose()])},Gn=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],Dn=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],Pn=()=>{let f=t({type:n("user_input"),content:o(gn()).nullish()}).loose(),w=t({type:n("model_output"),content:o(gn()).nullish()}).loose(),x=t({type:n("function_call"),id:e(),name:e(),arguments:y(e(),v()).nullish(),signature:e().nullish()}).loose(),A=t({type:n("thought"),signature:e().nullish(),summary:o(Nn()).nullish()}).loose(),N=t({type:n("processing_call"),id:e(),signature:e().nullish()}).loose(),B=t({type:n("processing_result"),call_id:e(),signature:e().nullish()}).loose(),re=t({type:i(Gn),id:e(),arguments:y(e(),v()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),ee=t({type:i(Dn),call_id:e(),result:v().nullish(),is_error:c().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose();return l([f,w,x,A,N,B,re,ee,t({type:e()}).loose()])},qt=a(()=>s(t({id:e().nullish(),created:e().nullish(),updated:e().nullish(),status:jn(),model:e().nullish(),agent:e().nullish(),steps:o(Pn()).nullish(),usage:Ln().nullish(),service_tier:e().nullish(),previous_interaction_id:e().nullish(),response_modalities:o(e()).nullish()}).loose())),qn=a(()=>s((()=>{let f=jn(),w=Un(),x=Nn(),A=t({event_type:n("interaction.created"),event_id:e().nullish(),interaction:t({id:e().nullish(),created:e().nullish(),model:e().nullish(),agent:e().nullish(),status:f.nullish()}).loose()}).loose(),N=t({event_type:n("step.start"),event_id:e().nullish(),index:r(),step:Pn()}).loose(),B=t({type:n("text"),text:e()}).loose(),re=t({type:n("thought_summary"),content:x.nullish()}).loose(),ee=t({type:n("thought_signature"),signature:e().nullish()}).loose(),V=t({type:n("arguments_delta"),arguments:e().nullish(),id:e().nullish(),signature:e().nullish()}).loose(),pe=t({type:i(["text_annotation_delta","text_annotation"]),annotations:o(w).nullish()}).loose(),ce=t({type:n("image"),data:e().nullish(),mime_type:e().nullish(),resolution:i(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),Re=t({type:n("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose(),Le=t({type:i(Gn),id:e().nullish(),arguments:y(e(),v()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),Ce=t({type:i(Dn),call_id:e().nullish(),result:v().nullish(),is_error:c().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose(),Ee=t({type:e()}).loose(),je=l([B,ce,Re,re,ee,V,pe,Le,Ce,Ee]),Ne=t({event_type:n("step.delta"),event_id:e().nullish(),index:r(),delta:je}).loose(),ye=t({event_type:n("step.stop"),event_id:e().nullish(),index:r()}).loose(),ie=t({event_type:n("interaction.status_update"),event_id:e().nullish(),interaction_id:e().nullish(),status:f.nullish()}).loose(),be=t({event_type:n("interaction.in_progress"),event_id:e().nullish(),interaction_id:e().nullish(),status:f.nullish()}).loose(),ne=t({event_type:n("interaction.requires_action"),event_id:e().nullish(),interaction_id:e().nullish(),status:f.nullish()}).loose(),se=t({event_type:n("interaction.completed"),event_id:e().nullish(),interaction:t({id:e().nullish(),status:f.nullish(),usage:Ln().nullish(),service_tier:e().nullish()}).loose()}).loose(),Ue=t({event_type:n("error"),event_id:e().nullish(),error:t({code:e().nullish(),message:e().nullish()}).loose().nullish()}).loose(),De=t({event_type:e()}).loose();return l([A,N,Ne,ye,ie,be,ne,se,Ue,De])})())),Gi=a(()=>s(t({previousInteractionId:e().nullish(),store:c().nullish(),agent:e().nullish(),agentConfig:l([t({type:n("dynamic")}).loose(),t({type:n("deep-research"),thinkingSummaries:i(["auto","none"]).nullish(),visualization:i(["off","auto"]).nullish(),collaborativePlanning:c().nullish()})]).nullish(),thinkingLevel:i(["minimal","low","medium","high"]).nullish(),thinkingSummaries:i(["auto","none"]).nullish(),responseFormat:o(l([t({type:n("text"),mimeType:e().nullish(),schema:v().nullish()}).loose(),t({type:n("image"),mimeType:e().nullish(),aspectRatio:i(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:i(["1K","2K","4K","512"]).nullish()}).loose(),t({type:n("audio"),mimeType:e().nullish()}).loose(),t({type:n("video"),aspectRatio:i(["16:9","9:16"]).nullish(),resolution:i(["360p","720p","1080p","4k"]).nullish(),duration:e().nullish(),delivery:i(["inline","uri"]).nullish(),gcsUri:e().nullish()}).loose()])).nullish(),imageConfig:t({aspectRatio:i(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:i(["1K","2K","4K","512"]).nullish()}).nullish(),mediaResolution:i(["low","medium","high","ultra_high"]).nullish(),responseModalities:o(i(["text","image","audio","video","document"])).nullish(),serviceTier:i(["flex","standard","priority"]).nullish(),systemInstruction:e().nullish(),signature:e().nullish(),interactionId:e().nullish(),pollingTimeoutMs:r().int().positive().nullish(),background:c().nullish(),environment:l([e(),t({type:n("remote"),sources:o(l([t({type:n("gcs"),source:e(),target:e().nullish()}),t({type:n("repository"),source:e(),target:e().nullish()}),t({type:n("inline"),content:e(),target:e()})])).nullish(),network:l([n("disabled"),t({allowlist:o(t({domain:e(),transform:o(y(e(),e())).nullish()}))})]).nullish()})]).nullish()})));function mt({signature:f,interactionId:w,processingId:x,processingCallId:A}){let N={};if(f!=null)N.signature=f;if(w!=null)N.interactionId=w;if(x!=null)N.processingId=x;if(A!=null)N.processingCallId=A;return Object.keys(N).length>0?{providerMetadata:{google:N}}:{}}var Di=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),Pi=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function qi(f){return f.replace(/_call$/,"")}function $i(f){return f.replace(/_result$/,"")}function $n({steps:f,generateId:w,interactionId:x}){let A=[],N=!1;if(f==null)return{content:A,hasFunctionCall:N};for(let B of f){if(B==null||typeof B!=="object")continue;let re=B.type;if(typeof re!=="string")continue;switch(re){case"user_input":break;case"model_output":{let ee=B.content??[];for(let V of ee){if(V==null||typeof V!=="object")continue;let pe=V.type;if(pe==="text"){let ce=V.text??"",Re=V.annotations;A.push({type:"text",text:ce,...mt({interactionId:x})});let Le=Pt({annotations:Re,generateId:w});for(let Ce of Le)A.push(Ce)}else if(pe==="image"){let ce=V;if(ce.data!=null&&ce.data.length>0)A.push({type:"file",mediaType:ce.mime_type??"image/png",data:{type:"data",data:ce.data},...mt({interactionId:x})});else if(ce.uri!=null&&ce.uri.length>0)A.push({type:"file",mediaType:ce.mime_type??"image/png",data:{type:"url",url:new URL(ce.uri)},...mt({interactionId:x})})}else if(pe==="video"){let ce=V;if(ce.data!=null&&ce.data.length>0)A.push({type:"file",mediaType:ce.mime_type??"video/mp4",data:{type:"data",data:ce.data},...mt({interactionId:x})});else if(ce.uri!=null&&ce.uri.length>0)A.push({type:"file",mediaType:ce.mime_type??"video/mp4",data:{type:"url",url:new URL(ce.uri)},...mt({interactionId:x})})}}break}case"thought":{let ee=B,V=(Array.isArray(ee.summary)?ee.summary:[]).filter((pe)=>pe?.type==="text"&&typeof pe.text==="string").map((pe)=>pe.text).join(`
14
+ `);A.push({type:"reasoning",text:V,...mt({signature:ee.signature,interactionId:x})});break}case"processing_call":{let ee=B,V=ee.id||w();A.push({type:"custom",kind:"google.processing_call",...mt({signature:ee.signature,interactionId:x,processingId:V})});break}case"processing_result":{let ee=B,V=ee.call_id||w();A.push({type:"custom",kind:"google.processing_result",...mt({signature:ee.signature,interactionId:x,processingCallId:V})});break}case"function_call":{N=!0;let ee=B;A.push({type:"tool-call",toolCallId:ee.id,toolName:ee.name,input:JSON.stringify(ee.arguments??{}),...mt({signature:ee.signature,interactionId:x})});break}default:if(Di.has(re)){let ee=B,V=re==="mcp_server_tool_call"?ee.name??"mcp_server_tool":qi(re),pe=JSON.stringify(ee.arguments??{});A.push({type:"tool-call",toolCallId:ee.id||w(),toolName:V,input:pe,providerExecuted:!0})}else if(Pi.has(re)){let ee=B,V=re==="mcp_server_tool_result"?ee.name??"mcp_server_tool":$i(re);A.push({type:"tool-result",toolCallId:ee.call_id||w(),toolName:V,result:ee.result??null});let pe=An({block:B,generateId:w});for(let ce of pe)A.push(ce)}}}return{content:A,hasFunctionCall:N}}var Fi=()=>globalThis.fetch;async function Fn({baseURL:f,interactionId:w,headers:x,fetch:A=Fi()}){if(w==null||w.length===0)return;let N=`${f}/interactions/${encodeURIComponent(w)}/cancel`;try{let B=await A(N,{method:"POST",headers:F(d({"Content-Type":"application/json"},x),ke()),body:"{}"});try{await B.text()}catch{}}catch{}}var Bi=new Set(["completed","failed","cancelled","incomplete"]);function $t(f){return f!=null&&Bi.has(f)}var Hi=1000,Vi=1e4,Wi=1800000;async function Ki({baseURL:f,interactionId:w,headers:x,fetch:A,abortSignal:N,initialDelayMs:B=Hi,maxDelayMs:re=Vi,timeoutMs:ee=Wi}){if(w==null||w.length===0)throw Error("google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.");let V=Date.now(),pe=B,ce=`${f}/interactions/${encodeURIComponent(w)}`,Re=()=>Fn({baseURL:f,interactionId:w,headers:x,fetch:A});try{while(!0){if(N?.aborted)throw await Re(),new DOMException("Polling was aborted","AbortError");if(Date.now()-V>ee)throw Error(`google.interactions: timed out polling interaction ${w} after ${ee}ms.`);await Oe(pe,{abortSignal:N});let{value:Le,rawValue:Ce,responseHeaders:Ee}=await R({url:ce,validateUrl:!1,headers:x,failedResponseHandler:Xe,successfulResponseHandler:p(qt),abortSignal:N,fetch:A});if($t(Le.status))return{response:Le,rawResponse:Ce,responseHeaders:Ee};pe=Math.min(pe*2,re)}}catch(Le){if(Z(Le))await Re();throw Le}}function zi({tools:f,toolChoice:w}){let x=[],A=f?.length?f:void 0;if(A==null)return{tools:void 0,toolChoice:void 0,toolWarnings:x};let N=[];for(let ee of A){if(ee.type==="function"){N.push({type:"function",name:ee.name,description:ee.description??"",parameters:ee.inputSchema});continue}if(ee.type==="provider"){let V=ee.args??{};switch(ee.id){case"google.google_search":{let pe=V.searchTypes,ce;if(pe!=null&&typeof pe==="object"){let Re=[];if(pe.webSearch!=null)Re.push("web_search");if(pe.imageSearch!=null)Re.push("image_search");if(Re.length>0)ce=Re}N.push({type:"google_search",...ce!=null?{search_types:ce}:{}});break}case"google.code_execution":N.push({type:"code_execution"});break;case"google.url_context":N.push({type:"url_context"});break;case"google.file_search":N.push({type:"file_search",...V.fileSearchStoreNames!=null?{file_search_store_names:V.fileSearchStoreNames}:{},...V.topK!=null?{top_k:V.topK}:{},...V.metadataFilter!=null?{metadata_filter:V.metadataFilter}:{}});break;case"google.google_maps":N.push({type:"google_maps",...V.latitude!=null?{latitude:V.latitude}:{},...V.longitude!=null?{longitude:V.longitude}:{},...V.enableWidget!=null?{enable_widget:V.enableWidget}:{}});break;case"google.computer_use":N.push({type:"computer_use",environment:V.environment??"browser",...V.excludedPredefinedFunctions!=null?{excludedPredefinedFunctions:V.excludedPredefinedFunctions}:{}});break;case"google.mcp_server":N.push({type:"mcp_server",...V.name!=null?{name:V.name}:{},...V.url!=null?{url:V.url}:{},...V.headers!=null?{headers:V.headers}:{},...V.allowedTools!=null?{allowed_tools:V.allowedTools}:{}});break;case"google.retrieval":{let pe=V.vertexAiSearchConfig??void 0;N.push({type:"retrieval",...V.retrievalTypes!=null?{retrieval_types:V.retrievalTypes}:{retrieval_types:["vertex_ai_search"]},...pe!=null?{vertex_ai_search_config:pe}:{}});break}default:x.push({type:"unsupported",feature:`provider-defined tool ${ee.id}`,details:`provider-defined tool ${ee.id} is not supported by google.interactions; tool dropped.`})}continue}x.push({type:"unsupported",feature:`tool of type ${ee.type}`,details:"Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."})}let B=N.some((ee)=>ee.type==="function"),re;if(w!=null&&B)switch(w.type){case"auto":re="auto";break;case"required":re="any";break;case"none":re="none";break;case"tool":re={allowed_tools:{mode:"validated",tools:[w.toolName]}}}return{tools:N.length>0?N:void 0,toolChoice:re,toolWarnings:x}}var Ji=3,Yi=500;function Xi({baseURL:f,interactionId:w,headers:x,fetch:A,abortSignal:N,maxRetries:B=Ji,retryDelayMs:re=Yi}){if(w.length===0)throw Error("google.interactions: cannot stream a background interaction without an id.");let ee={...x,accept:"text/event-stream"},V,pe=!1,ce=0,Re=!1,Le,Ce=new AbortController,Ee=()=>Ce.abort();if(N!=null)if(N.aborted)Ce.abort();else N.addEventListener("abort",Ee,{once:!0});let je=Ce.signal;function Ne(){let ie=`${f}/interactions/${encodeURIComponent(w)}`,be=new URLSearchParams({stream:"true"});if(V!=null)be.set("last_event_id",V);return`${ie}?${be.toString()}`}async function ye(){let{value:ie}=await R({url:Ne(),validateUrl:!1,headers:ee,failedResponseHandler:Xe,successfulResponseHandler:D(qn),abortSignal:je,fetch:A});return ie.getReader()}return new ReadableStream({async start(ie){try{while(!pe&&!je.aborted){if(Le==null)try{Le=await ye(),Re=!1}catch(be){if(Z(be)||je.aborted){ie.error(be);return}if(ce++,ce>=B){ie.error(be);return}await Oe(re*ce,{abortSignal:je});continue}try{let{done:be,value:ne}=await Le.read();if(be){if(Le=void 0,pe)break;if(!Re){if(ce++,ce>=B){ie.error(Error("google.interactions: SSE stream closed without producing any events."));return}await Oe(re*ce,{abortSignal:je})}else ce=0;continue}if(Re=!0,ne.success){let se=ne.value;if(typeof se.event_id==="string"&&se.event_id.length>0)V=se.event_id;if(se.event_type==="interaction.completed"||se.event_type==="error")pe=!0}ie.enqueue(ne)}catch(be){if(Z(be)||je.aborted){ie.error(be);return}if(Le=void 0,ce++,ce>=B){ie.error(be);return}await Oe(re*ce,{abortSignal:je})}}ie.close()}catch(be){ie.error(be)}finally{if(N!=null)N.removeEventListener("abort",Ee);if(Le?.cancel().catch(()=>{}),Le=void 0,je.aborted&&!pe)await Fn({baseURL:f,interactionId:w,headers:x,fetch:A})}},cancel(){Ce.abort(),Le?.cancel().catch(()=>{}),Le=void 0}})}function Qi({response:f,warnings:w,generateId:x,includeRawChunks:A,headerServiceTier:N}){return new ReadableStream({start(B){B.enqueue({type:"stream-start",warnings:w});let re=typeof f.id==="string"&&f.id.length>0?f.id:void 0,ee,V=f.created;if(typeof V==="string"){let Ne=new Date(V);if(!Number.isNaN(Ne.getTime()))ee=Ne}if(B.enqueue({type:"response-metadata",...re!=null?{id:re}:{},modelId:f.model??void 0,...ee?{timestamp:ee}:{}}),A)B.enqueue({type:"raw",rawValue:f});let{content:pe,hasFunctionCall:ce}=$n({steps:f.steps??null,generateId:x,interactionId:re}),Re=0,Le=()=>`${re??"agent"}:${Re++}`;for(let Ne of pe)switch(Ne.type){case"text":{let ye=Le(),ie=Ne.providerMetadata;if(B.enqueue({type:"text-start",id:ye}),Ne.text.length>0)B.enqueue({type:"text-delta",id:ye,delta:Ne.text});B.enqueue({type:"text-end",id:ye,...ie?{providerMetadata:ie}:{}});break}case"reasoning":{let ye=Le(),ie=Ne.providerMetadata;if(B.enqueue({type:"reasoning-start",id:ye}),Ne.text.length>0)B.enqueue({type:"reasoning-delta",id:ye,delta:Ne.text});B.enqueue({type:"reasoning-end",id:ye,...ie?{providerMetadata:ie}:{}});break}case"tool-call":{let ye=Ne.providerMetadata;B.enqueue({type:"tool-input-start",id:Ne.toolCallId,toolName:Ne.toolName,...Ne.providerExecuted?{providerExecuted:Ne.providerExecuted}:{}}),B.enqueue({type:"tool-input-delta",id:Ne.toolCallId,delta:Ne.input}),B.enqueue({type:"tool-input-end",id:Ne.toolCallId}),B.enqueue({type:"tool-call",toolCallId:Ne.toolCallId,toolName:Ne.toolName,input:Ne.input,...Ne.providerExecuted?{providerExecuted:Ne.providerExecuted}:{},...ye?{providerMetadata:ye}:{}});break}case"tool-result":B.enqueue({type:"tool-result",toolCallId:Ne.toolCallId,toolName:Ne.toolName,result:Ne.result});break;case"source":case"file":B.enqueue(Ne)}let Ce=f.service_tier??N,Ee={unified:Vt({status:f.status,hasFunctionCall:ce}),raw:f.status},je={google:{...re!=null?{interactionId:re}:{},...Ce!=null?{serviceTier:Ce}:{}}};B.enqueue({type:"finish",finishReason:Ee,usage:Ht(f.usage),providerMetadata:je}),B.close()}})}var Zi=class f{static[k](w){return{...E({modelId:w.modelId,config:w.config}),agent:w.agent}}static[T](w){return new f(w.agent!=null?{agent:w.agent}:w.modelId,w.config)}constructor(w,x){if(this.specificationVersion="v4",typeof w==="string")this.modelId=w,this.agent=void 0;else if("managedAgent"in w)this.modelId=w.managedAgent,this.agent=w.managedAgent;else this.modelId=w.agent,this.agent=w.agent;this.config=x}get provider(){return this.config.provider}get supportedUrls(){if(this.config.supportedUrls)return this.config.supportedUrls();return{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(w){let x=[],A=await h({provider:"google",providerOptions:w.providerOptions,schema:Gi}),N=this.agent!=null;if(!N){if(w.frequencyPenalty!=null)x.push({type:"unsupported",feature:"frequencyPenalty"});if(w.presencePenalty!=null)x.push({type:"unsupported",feature:"presencePenalty"})}let B=w.tools!=null&&w.tools.length>0,re,ee;if(B){let ye=zi({tools:w.tools,toolChoice:w.toolChoice});re=ye.tools,ee=ye.toolChoice,x.push(...ye.toolWarnings)}let V=[];if(w.responseFormat?.type==="json")if(N)x.push({type:"other",message:"google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."});else{let ye={type:"text",mime_type:"application/json",...w.responseFormat.schema!=null?{schema:w.responseFormat.schema}:{}};V.push(ye)}if(A?.responseFormat!=null){for(let ye of A.responseFormat)if(ye.type==="text")V.push(ht({type:"text",mime_type:ye.mimeType??void 0,schema:ye.schema??void 0}));else if(ye.type==="image")V.push(ht({type:"image",mime_type:ye.mimeType??void 0,aspect_ratio:ye.aspectRatio??void 0,image_size:ye.imageSize??void 0}));else if(ye.type==="audio")V.push(ht({type:"audio",mime_type:ye.mimeType??void 0}));else if(ye.type==="video")V.push(ht({type:"video",aspect_ratio:ye.aspectRatio??void 0,resolution:ye.resolution??void 0,duration:ye.duration??void 0,delivery:ye.delivery??void 0,gcs_uri:ye.gcsUri??void 0}))}let{input:pe,systemInstruction:ce,warnings:Re}=Mi({prompt:w.prompt,previousInteractionId:A?.previousInteractionId??void 0,store:A?.store??void 0,mediaResolution:A?.mediaResolution??void 0});x.push(...Re);let Le=ce,Ce=A?.systemInstruction??void 0;if(Le!=null&&Ce!=null)x.push({type:"other",message:"google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."});else if(Le==null&&Ce!=null)Le=Ce;let Ee;if(N){let ye=[];if(w.temperature!=null)ye.push("temperature");if(w.topP!=null)ye.push("topP");if(w.topK!=null)ye.push("topK");if(w.frequencyPenalty!=null)ye.push("frequencyPenalty");if(w.presencePenalty!=null)ye.push("presencePenalty");if(w.seed!=null)ye.push("seed");if(w.stopSequences!=null&&w.stopSequences.length>0)ye.push("stopSequences");if(w.maxOutputTokens!=null)ye.push("maxOutputTokens");if(A?.thinkingLevel!=null)ye.push("thinkingLevel");if(A?.thinkingSummaries!=null)ye.push("thinkingSummaries");if(A?.imageConfig!=null)ye.push("imageConfig");if(ye.length>0)x.push({type:"other",message:`google.interactions: ${ye.join(", ")} ${ye.length===1?"is":"are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`});Ee=void 0}else if(Ee=ht({temperature:w.temperature??void 0,top_p:w.topP??void 0,top_k:w.topK??void 0,seed:w.seed??void 0,stop_sequences:w.stopSequences!=null&&w.stopSequences.length>0?w.stopSequences:void 0,max_output_tokens:w.maxOutputTokens??void 0,thinking_level:A?.thinkingLevel??void 0,thinking_summaries:A?.thinkingSummaries??void 0,tool_choice:ee}),A?.imageConfig!=null){let ye=V.some((ie)=>ie.type==="image");if(x.push({type:"other",message:ye?"google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.":'google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.'}),!ye)V.push({type:"image",mime_type:"image/png",...A.imageConfig.aspectRatio!=null?{aspect_ratio:A.imageConfig.aspectRatio}:{},...A.imageConfig.imageSize!=null?{image_size:A.imageConfig.imageSize}:{}})}let je;if(N&&A?.agentConfig!=null){let ye=A.agentConfig;if(ye.type==="deep-research")je=ht({type:"deep-research",thinking_summaries:ye.thinkingSummaries??void 0,visualization:ye.visualization??void 0,collaborative_planning:ye.collaborativePlanning??void 0});else if(ye.type==="dynamic")je={type:"dynamic"}}let Ne;if(A?.environment!=null)if(!N)x.push({type:"other",message:"google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."});else if(typeof A.environment==="string")Ne=A.environment;else{let ye=A.environment,ie=ye.sources?.map((ne)=>{if(ne.type==="inline")return{type:"inline",content:ne.content,target:ne.target};return ht({type:ne.type,source:ne.source,target:ne.target??void 0})}),be;if(ye.network==="disabled")be="disabled";else if(ye.network!=null)be={allowlist:ye.network.allowlist.map((ne)=>ht({domain:ne.domain,transform:ne.transform??void 0}))};Ne=ht({type:"remote",sources:ie!=null&&ie.length>0?ie:void 0,network:be})}return{args:ht({...N?{agent:this.agent}:{model:this.modelId},input:pe,system_instruction:Le,tools:re,response_format:V.length>0?V:void 0,response_modalities:A?.responseModalities!=null?A.responseModalities:void 0,previous_interaction_id:A?.previousInteractionId??void 0,service_tier:A?.serviceTier??void 0,store:A?.store??void 0,generation_config:Ee!=null&&Object.keys(Ee).length>0?Ee:void 0,agent_config:je,environment:Ne,background:A?.background??void 0}),warnings:x,isAgent:N,isBackground:A?.background===!0,pollingTimeoutMs:A?.pollingTimeoutMs??void 0}}async doGenerate(w){let{args:x,warnings:A,isAgent:N,isBackground:B,pollingTimeoutMs:re}=await this.getArgs(w),ee=`${this.config.baseURL}/interactions`,V=d(this.config.headers?await _(this.config.headers):void 0,w.headers),{responseHeaders:pe,value:ce,rawValue:Re}=await g({url:ee,headers:V,body:x,failedResponseHandler:Xe,successfulResponseHandler:p(qt),abortSignal:w.abortSignal,fetch:this.config.fetch});if((N||B)&&!$t(ce.status)){let ne=await Ki({baseURL:this.config.baseURL,interactionId:ce.id,headers:V,fetch:this.config.fetch,abortSignal:w.abortSignal,timeoutMs:re});ce=ne.response,Re=ne.rawResponse,pe=ne.responseHeaders??pe}let Le=typeof ce.id==="string"&&ce.id.length>0?ce.id:void 0,{content:Ce,hasFunctionCall:Ee}=$n({steps:ce.steps??null,generateId:this.config.generateId??C,interactionId:Le}),je={unified:Vt({status:ce.status,hasFunctionCall:Ee}),raw:ce.status},Ne=ce.service_tier??pe?.["x-gemini-service-tier"]??void 0,ye=On(ce.usage),ie={google:{...Le!=null?{interactionId:Le}:{},...Ne!=null?{serviceTier:Ne}:{},...ye!=null?{outputTokensByModality:ye}:{}}},be;if(typeof ce.created==="string"){let ne=new Date(ce.created);if(!Number.isNaN(ne.getTime()))be=ne}return{content:Ce,finishReason:je,usage:Ht(ce.usage),warnings:A,providerMetadata:ie,request:{body:x},response:{headers:pe,body:Re,...Le!=null?{id:Le}:{},...be?{timestamp:be}:{},modelId:ce.model??void 0}}}async doStream(w){let{args:x,warnings:A,isBackground:N,pollingTimeoutMs:B}=await this.getArgs(w),re=`${this.config.baseURL}/interactions`,ee=d(this.config.headers?await _(this.config.headers):void 0,w.headers);if(N)return this.doStreamBackground({args:x,warnings:A,url:re,mergedHeaders:ee,options:w,pollingTimeoutMs:B});let V={...x,stream:!0},{responseHeaders:pe,value:ce}=await g({url:re,headers:ee,body:V,failedResponseHandler:Xe,successfulResponseHandler:D(qn),abortSignal:w.abortSignal,fetch:this.config.fetch}),Re=pe?.["x-gemini-service-tier"],Le=dn({warnings:A,generateId:this.config.generateId??C,includeRawChunks:w.includeRawChunks,serviceTier:Re});return{stream:ce.pipeThrough(Le),request:{body:V},response:{headers:pe}}}async doStreamBackground({args:w,warnings:x,url:A,mergedHeaders:N,options:B,pollingTimeoutMs:re}){let{responseHeaders:ee,value:V}=await g({url:A,headers:N,body:w,failedResponseHandler:Xe,successfulResponseHandler:p(qt),abortSignal:B.abortSignal,fetch:this.config.fetch}),pe=V.id;if(pe==null||pe.length===0)throw Error("google.interactions: background POST response did not include an interaction id; cannot stream the result.");let ce=ee?.["x-gemini-service-tier"];if($t(V.status))return{stream:Qi({response:V,warnings:x,generateId:this.config.generateId??C,includeRawChunks:B.includeRawChunks,headerServiceTier:ce}),request:{body:w},response:{headers:ee}};let Re=Xi({baseURL:this.config.baseURL,interactionId:pe,headers:N,fetch:this.config.fetch,abortSignal:B.abortSignal}),Le=dn({warnings:x,generateId:this.config.generateId??C,includeRawChunks:B.includeRawChunks,serviceTier:ce});return{stream:Re.pipeThrough(Le),request:{body:w},response:{headers:ee}}}};function ht(f){let w={};for(let[x,A]of Object.entries(f)){if(A===void 0)continue;w[x]=A}return w}function Bn(f){let w=new URL(f),x=w.pathname.split("/"),A=x.at(-1);if(A==="v1beta"||A==="v1alpha")x.pop(),w.pathname=x.join("/")||"/";return w}function Wt(f,w){let x=Bn(f);return x.protocol=x.protocol==="https:"?"wss:":"ws:",x.pathname=`${x.pathname.replace(/\/$/,"")}/ws/${w}`,x}var es=class{constructor(){this.turnCounter=0,this.inputTranscriptionCounter=0,this.inputTranscriptionBuffer="",this.inputTranscriptionBoundary="none",this.preserveInputTranscriptionAcrossTurnComplete=!1,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,this.turnClosed=!1,this.inputAudioRate=16000}get responseId(){return`google-resp-${this.turnCounter}`}get itemId(){return`google-item-${this.turnCounter}`}beginTurnIfClosed(){if(!this.turnClosed)return;this.turnCounter++,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,this.turnClosed=!1,this.preserveInputTranscriptionAcrossTurnComplete=!1}accumulateInputTranscription({text:f,finished:w}){if(!f){if(w===!0)this.finishInputTranscription();return}let x=w!=null;if(this.inputTranscriptionBuffer!==""&&(this.inputTranscriptionBoundary==="interrupted"||this.inputTranscriptionBoundary==="turn-complete"&&!x))this.finishInputTranscription();this.inputTranscriptionBoundary="none",this.inputTranscriptionBuffer+=f;let A={itemId:`google-input-${this.inputTranscriptionCounter}`,transcript:this.inputTranscriptionBuffer};if(w===!0)this.finishInputTranscription();return A}finishInputTranscription(){if(this.inputTranscriptionBuffer==="")return;this.inputTranscriptionCounter++,this.inputTranscriptionBuffer=""}parseServerEvent(f){let w=f;if(w.setupComplete!=null)return{type:"session-created",raw:f};if(w.toolCall!=null)return this.beginTurnIfClosed(),(w.toolCall.functionCalls??[]).flatMap((x)=>{let A=JSON.stringify(x.args??{});return[{type:"function-call-arguments-delta",responseId:this.responseId,itemId:this.itemId,callId:x.id,delta:A,raw:f},{type:"function-call-arguments-done",responseId:this.responseId,itemId:this.itemId,callId:x.id,name:x.name,arguments:A,raw:f}]});if(w.toolCallCancellation!=null)return{type:"custom",rawType:"toolCallCancellation",raw:f};if(w.goAway!=null)return{type:"custom",rawType:"goAway",raw:f};if(w.sessionResumptionUpdate!=null)return{type:"custom",rawType:"sessionResumptionUpdate",raw:f};if(w.serverContent!=null)return this.parseServerContent(w.serverContent,f);if(w.inputTranscription!=null){let x=this.accumulateInputTranscription(w.inputTranscription);if(x!=null)return{type:"input-transcription-completed",...x,raw:f}}return{type:"custom",rawType:String(Object.keys(w)[0]),raw:f}}parseServerContent(f,w){let x=[];if(f.interrupted)this.inputTranscriptionBoundary="interrupted",this.preserveInputTranscriptionAcrossTurnComplete=!0,this.turnClosed=!0,x.push({type:"speech-started",raw:w});if(f.modelTurn?.parts){this.beginTurnIfClosed();for(let A of f.modelTurn.parts){if(A.inlineData?.data)this.hasAudio=!0,x.push({type:"audio-delta",responseId:this.responseId,itemId:this.itemId,delta:A.inlineData.data,raw:w});if(A.text)this.hasText=!0,x.push({type:"text-delta",responseId:this.responseId,itemId:this.itemId,delta:A.text,raw:w})}}if(f.outputTranscription?.text)this.hasTranscript=!0,x.push({type:"audio-transcript-delta",responseId:this.responseId,itemId:this.itemId,delta:f.outputTranscription.text,raw:w});if(f.inputTranscription!=null){let A=this.accumulateInputTranscription(f.inputTranscription);if(A!=null)x.push({type:"input-transcription-completed",...A,raw:w})}if(f.generationComplete)x.push({type:"custom",rawType:"generationComplete",raw:w});if(f.interactionStatus!=null)x.push({type:"custom",rawType:"interactionStatus",raw:w});if(f.waitingForInput)x.push({type:"custom",rawType:"waitingForInput",raw:w});if(f.turnComplete){if(this.hasAudio)x.push({type:"audio-done",responseId:this.responseId,itemId:this.itemId,raw:w});if(this.hasText)x.push({type:"text-done",responseId:this.responseId,itemId:this.itemId,raw:w});if(this.hasTranscript)x.push({type:"audio-transcript-done",responseId:this.responseId,itemId:this.itemId,raw:w});if(x.push({type:"response-done",responseId:this.responseId,status:"completed",raw:w}),this.turnClosed=!0,this.preserveInputTranscriptionAcrossTurnComplete)this.preserveInputTranscriptionAcrossTurnComplete=!1;else if(this.inputTranscriptionBoundary!=="interrupted")this.inputTranscriptionBoundary="turn-complete"}if(x.length===0)return{type:"custom",rawType:"serverContent",raw:w};return x.length===1?x[0]:x}serializeClientEvent(f,w){switch(f.type){case"session-update":if(f.config.inputAudioFormat?.rate!=null)this.inputAudioRate=f.config.inputAudioFormat.rate;return{setup:Ft(f.config,w)};case"input-audio-append":return{realtimeInput:{audio:{data:f.audio,mimeType:`audio/pcm;rate=${this.inputAudioRate}`}}};case"input-audio-commit":return{realtimeInput:{audioStreamEnd:!0}};case"input-audio-clear":case"response-create":case"response-cancel":case"conversation-item-truncate":return null;case"conversation-item-create":{let x=f.item;switch(x.type){case"text-message":return{realtimeInput:{text:x.text}};case"function-call-output":return ns(x);case"audio-message":return null}break}}return null}};function ts(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)?f:{output:f}}async function ns(f){let w=await J({text:f.output}),x=w.success?ts(w.value):{output:f.output};return{toolResponse:{functionResponses:[{id:f.callId,name:f.name,response:x}]}}}function os(f){let w=f.split("/").at(-1)?.toLowerCase()??"";return/^gemini-\d+\.\d+-live\b.*thinking/.test(w)}function Ft(f,w){let x={model:Tt(w)},{google:A,...N}=f?.providerOptions??{},B=L(A)?A:void 0,re={};if(f?.outputModalities!=null)re.responseModalities=f.outputModalities.map((Re)=>Re.toUpperCase());else re.responseModalities=["AUDIO"];if(f?.voice!=null)re.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:f.voice}}};if(x.generationConfig=re,f?.instructions!=null)x.systemInstruction={parts:[{text:f.instructions}]};if(f?.tools!=null&&f.tools.length>0)x.tools=[{functionDeclarations:f.tools.map((Re)=>({name:Re.name,description:Re.description,parametersJsonSchema:Re.parameters,...B?.defaultToolBehavior!=null?{behavior:B.defaultToolBehavior}:{}}))}];if(f?.inputAudioTranscription!=null)x.inputAudioTranscription={};if(f?.outputAudioTranscription!=null)x.outputAudioTranscription={};let ee=N.generationConfig,V=B?.thinkingConfig??(L(ee)&&L(ee.thinkingConfig)?ee.thinkingConfig:void 0),pe=os(w)&&V?.thinkingLevel==null&&V?.thinkingBudget==null?{...V,thinkingLevel:"low"}:B?.thinkingConfig,ce=()=>{if(pe==null)return;let Re=L(x.generationConfig)?x.generationConfig:re;x.generationConfig={...Re,thinkingConfig:pe}};if(f?.providerOptions==null)return ce(),x;if(Object.assign(x,N),B?.translationConfig!=null)x.generationConfig={...L(x.generationConfig)?x.generationConfig:re,translationConfig:B.translationConfig};return ce(),x}var is="google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained";function ss(f){let w=Bn(f);return w.pathname=`${w.pathname.replace(/\/$/,"")}/v1alpha/auth_tokens`,w.toString()}function as(f){return Wt(f,is).toString()}var rs=class{constructor(f,w){this.specificationVersion="v4",this.mapper=new es,this.modelId=f,this.provider=w.provider,this.config=w}async doCreateClientSecret(f){let w=this.config.fetch??fetch,x=this.config.headers()["x-goog-api-key"];if(!x)throw Error("Google Generative AI API key is required for realtime token creation.");let A=Date.now(),N=(f.expiresAfterSeconds??60)*1000,B=new Date(A+N).toISOString(),re=new Date(A+N+1800000).toISOString(),ee=Ft(f.sessionConfig,this.modelId),V=await w(`${ss(this.config.baseURL)}?key=${encodeURIComponent(x)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uses:0,expireTime:re,newSessionExpireTime:B,bidiGenerateContentSetup:ee})});if(!V.ok){let ce=await V.text();throw Error(`Google realtime auth token request failed: ${V.status} ${ce}`)}let pe=await V.json();return{token:pe.name,url:as(this.config.baseURL),expiresAt:pe.expireTime?Math.floor(new Date(pe.expireTime).getTime()/1000):void 0}}getWebSocketConfig(f){return{url:`${f.url}?access_token=${encodeURIComponent(f.token)}`}}parseServerEvent(f){return this.mapper.parseServerEvent(f)}serializeClientEvent(f){return this.mapper.serializeClientEvent(f,this.modelId)}buildSessionConfig(f){return Ft(f,this.modelId)}};var ls=a(()=>s(t({languageCodes:o(e()).optional(),customVocabulary:o(e()).optional(),wordTimestamp:c().optional(),diarization:c().optional(),mode:i(["SMART","VERBATIM"]).optional()}))),us="google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",cs=3000;function ds(f,w){let x=Wt(f,us);return x.searchParams.set("key",w),x}function hn(f){return f.includes("-live")}var ps=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.modelId=w,this.config=x,this.specificationVersion="v4"}async parseOptions(w){return h({provider:"google",providerOptions:w,schema:ls})}async doGenerate(w){if(hn(this.modelId))throw new b({argument:"modelId",message:`Model '${this.modelId}' only supports streaming transcription. Use experimental_streamTranscribe, or a unary model such as 'gemini-3.5-transcribe'.`});let x=this.config._internal?.currentDate?.()??new Date,A=[],N=ms(await this.parseOptions(w.providerOptions)),B={model:this.modelId,input:[{type:"audio",data:M(w.audio),mime_type:w.mediaType}],...N!=null?{generation_config:{transcription_config:N}}:{}},{value:re,responseHeaders:ee,rawValue:V}=await g({url:`${this.config.baseURL}/interactions`,headers:d(this.config.headers?await _(this.config.headers):void 0,w.headers),body:B,failedResponseHandler:Xe,successfulResponseHandler:p(vs),abortSignal:w.abortSignal,fetch:this.config.fetch}),pe="",ce=[];for(let Re of re.steps??[])for(let Le of Re.content??[]){if(Le.type!=="text"||Le.text==null)continue;pe+=Le.text;for(let Ce of Le.annotations??[]){if(Ce.type!=="word_info")continue;let Ee=mn(Ce.start_offset),je=mn(Ce.end_offset);if(Ce.text==null||Ee==null||je==null)continue;ce.push({text:Ce.text,startSecond:Ee,endSecond:je})}}return{text:pe,segments:ce,language:void 0,durationInSeconds:void 0,warnings:A,...re.usage!=null&&{usage:re.usage},response:{timestamp:x,modelId:this.modelId,headers:ee,body:V},...re.usage!=null?{providerMetadata:{google:{usage:re.usage}}}:{}}}async doStream(w){if(!hn(this.modelId))throw new b({argument:"modelId",message:`Model '${this.modelId}' does not support streaming transcription. Use a live model such as 'gemini-3.5-transcribe-live'.`});let x=this.config._internal?.currentDate?.()??new Date,A=[],N=await this.parseOptions(w.providerOptions);fs(w.inputAudioFormat);let B=d(this.config.headers?await _(this.config.headers):void 0,w.headers),re;for(let[pe,ce]of Object.entries(B))if(pe.toLowerCase()==="x-goog-api-key"&&ce!=null)re=ce;if(re==null)throw Error("Google Generative AI API key is required for streaming transcription.");let ee=Object.fromEntries(Object.entries(B).filter(([pe])=>pe.toLowerCase()!=="x-goog-api-key")),V={model:Tt(this.modelId),inputAudioTranscription:hs(N)??{}};return{request:{body:V},response:{timestamp:x,modelId:this.modelId},stream:gs({webSocket:this.config.webSocket,url:ds(this.config.baseURL,re),headers:ee,setup:V,inputAudioRate:w.inputAudioFormat.rate??16000,finishGraceMs:this.config._internal?.finishGraceMs??cs,warnings:A,audio:w.audio,abortSignal:w.abortSignal,includeRawChunks:w.includeRawChunks})}}};function gs({webSocket:f,url:w,headers:x,setup:A,inputAudioRate:N,finishGraceMs:B,warnings:re,audio:ee,abortSignal:V,includeRawChunks:pe}){let ce=!1,Re=()=>{};return new ReadableStream({start:(Le)=>{let Ce,Ee,je,Ne=new Promise((He)=>{je=He}),ye=0,ie="",be="",ne="",se,Ue=!1,De,qe,Ve=()=>`google-segment-${ye}`,tt=()=>{if(qe!=null)clearTimeout(qe),qe=void 0},We=()=>{if(ce||!Ue)return;tt(),qe=setTimeout(()=>{qe=void 0,ze()},B)};Re=(He)=>{if(tt(),Ce!=null)Ce.cancel().catch(()=>{});else ee.cancel().catch(()=>{});Ee?.close(He)};let Ze=(He)=>{if(ce)return;ce=!0,Re(),Le.error(He)},pt=()=>{if(ie===""){if(ne==="")return;ie=ne}ne="",Le.enqueue({type:"transcript-final",id:Ve(),text:ie}),be+=be===""?ie:` ${ie}`,ie="",ye++},ze=()=>{if(ce)return;pt(),ce=!0,Le.enqueue({type:"finish",text:be,segments:[],language:se,durationInSeconds:void 0,usage:De,...De!=null?{providerMetadata:{google:{usageMetadata:De}}}:{}}),Le.close(),Re(1000)},nt=async(He)=>{Ce=ee.getReader();try{while(!0){let{done:st,value:at}=await Ce.read();if(st||ce)break;He.send(JSON.stringify({realtimeInput:{audio:{data:M(at),mimeType:`audio/pcm;rate=${N}`}}})),await ue(He)}}finally{Ce.releaseLock(),Ce=void 0}if(!ce)He.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),Ue=!0,We()};Ee=fe({url:w,headers:x,webSocket:f,abortSignal:V,onAbort:Ze,onProcessingError:Ze,onOpen:(He)=>{Le.enqueue({type:"stream-start",warnings:re}),He.send(JSON.stringify({setup:A})),Ne.then(()=>ce?void 0:nt(He)).catch(Ze)},onMessageText:async(He)=>{if(ce)return;let st=await J({text:He});if(!st.success)return;let at=st.value;if(pe)Le.enqueue({type:"raw",rawValue:at});if(at.setupComplete!=null)je();if(at.usageMetadata!=null)De=at.usageMetadata;if(at.error!=null){Ze(Error(at.error.message??"Google Live API error"));return}let dt=at.serverContent,Fe=dt?.interimInputTranscription;if(Fe?.text)We(),ne=Fe.text,Le.enqueue({type:"transcript-partial",id:Ve(),text:Fe.text});let et=dt?.inputTranscription??at.inputTranscription;if(et!=null){if(et.languageCode!=null)se=et.languageCode;if(et.text)We(),ne="",ie+=et.text,Le.enqueue({type:"transcript-delta",id:Ve(),delta:et.text});if(et.finished===!0)pt()}if(dt?.turnComplete)pt();let Je=dt?.interactionStatus;if(Ue&&(Je==="IDLE"||Je==="REQUIRES_ACTION"||dt?.turnComplete===!0&&Je==null))ze()},onSocketError:()=>{Ze(Error("Google Live transcription error"))},onClose:({code:He,reason:st})=>{if(ce)return;if(Ue){ze();return}Ze(Error(`Google Live transcription WebSocket closed unexpectedly before finishing (code ${He??"unknown"}${st?`, reason: ${st}`:""}).`))}})},cancel:()=>{if(ce)return;ce=!0,Re()}})}function hs(f){if(f==null)return;let w={};if(f.languageCodes!=null)w.languageCodes=f.languageCodes;if(f.customVocabulary!=null)w.customVocabulary=f.customVocabulary;if(f.wordTimestamp!=null)w.wordTimestamp=f.wordTimestamp;if(f.diarization!=null)w.diarization=f.diarization;if(f.mode!=null)w.mode=f.mode;return Object.keys(w).length>0?w:void 0}function ms(f){if(f==null)return;let w={};if(f.languageCodes!=null)w.language_codes=f.languageCodes;if(f.customVocabulary!=null)w.custom_vocabulary=f.customVocabulary;if(f.mode!=null||f.diarization===!0||f.wordTimestamp===!0)w.mode={type:(f.mode??"VERBATIM").toLowerCase(),...f.diarization===!0?{diarization_mode:"speaker"}:{},...f.wordTimestamp===!0?{timestamp_granularities:["word"]}:{}};return Object.keys(w).length>0?w:void 0}function mn(f){if(f==null)return;let w=Number.parseFloat(f);return Number.isFinite(w)?w:void 0}function fs(f){if(f.type!=="audio/pcm"||f.rate!=null&&f.rate!==16000)throw new b({argument:"inputAudioFormat",message:"The Gemini Live transcription API only supports 16kHz 16-bit PCM input audio."})}var ys=()=>t({type:e().nullish(),text:e().nullish(),speaker:e().nullish(),start_offset:e().nullish(),end_offset:e().nullish()}),vs=a(()=>s(t({status:e().nullish(),steps:o(t({type:e().nullish(),content:o(t({type:e().nullish(),text:e().nullish(),annotations:o(ys()).nullish()})).nullish()})).nullish(),usage:y(e(),G()).nullish()}))),bs=a(()=>s(t({echoTargetLanguage:c().optional()}))),Ts="google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",_s=1000,Cs=24000,ws=128;function Ss(f,w){let x=Wt(f,Ts);return x.searchParams.set("key",w),x}var Is=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.specificationVersion="v4",this.modelId=w,this.config=x}async doStream(w){if(w.targetLanguage==null)throw new b({argument:"targetLanguage",message:`targetLanguage is required for translation model '${this.modelId}'.`});let x=this.config._internal?.currentDate?.()??new Date,A=await h({provider:"google",providerOptions:w.providerOptions,schema:bs}),N=[];if(Ms(w.inputAudioFormat),w.sourceLanguage!=null)N.push({type:"unsupported",feature:"sourceLanguage",details:"The Gemini Live translation API auto-detects the source language and does not accept a source language."});if(w.outputAudioFormat!=null)N.push({type:"unsupported",feature:"outputAudioFormat",details:"The Gemini Live API always outputs 24kHz 16-bit PCM audio and does not accept an output audio format."});let B=d(this.config.headers(),w.headers),re;for(let[pe,ce]of Object.entries(B))if(pe.toLowerCase()==="x-goog-api-key"&&ce!=null)re=ce;if(re==null)throw Error("Google Generative AI API key is required for streaming translation.");let ee=Object.fromEntries(Object.entries(B).filter(([pe])=>pe.toLowerCase()!=="x-goog-api-key")),V=Os({modelId:this.modelId,targetLanguage:w.targetLanguage,providerOptions:A});return{request:{body:V},response:{timestamp:x,modelId:this.modelId},stream:ks({webSocket:this.config.webSocket,url:Ss(this.config.baseURL,re),headers:ee,setup:V,inputAudioRate:w.inputAudioFormat.rate??16000,finishGraceMs:this.config._internal?.finishGraceMs??_s,warnings:N,audio:w.audio,abortSignal:w.abortSignal,includeRawChunks:w.includeRawChunks})}}};function ks({webSocket:f,url:w,headers:x,setup:A,inputAudioRate:N,finishGraceMs:B,warnings:re,audio:ee,abortSignal:V,includeRawChunks:pe}){let ce=!1,Re=()=>{};return new ReadableStream({start:(Le)=>{let Ce,Ee,je,Ne=new Promise((Fe)=>{je=Fe}),ye=0,ie="",be="",ne="",se="",Ue=!1,De,qe=!1,Ve=!1,tt=0,We,Ze=()=>`google-item-${ye}`,pt=()=>{if(We!=null)clearTimeout(We),We=void 0},ze=()=>{if(ce||We!=null)return;We=setTimeout(()=>{We=void 0,st()},B)},nt=()=>{qe=!0,tt=0,pt()};Re=(Fe)=>{if(pt(),Ce!=null)Ce.cancel().catch(()=>{});else ee.cancel().catch(()=>{});Ee?.close(Fe)};let He=(Fe)=>{if(ce)return;ce=!0,Re(),Le.error(Fe)},st=()=>{if(ce)return;if(be!==""||se!=="")at();ce=!0,Le.enqueue({type:"finish",sourceText:ie,outputText:ne,usage:De}),Le.close(),Re(1000)},at=()=>{if(be!=="")Le.enqueue({type:"source-transcript-final",id:Ze(),text:be}),ie+=be,be="";if(se!=="")Le.enqueue({type:"output-text-final",id:Ze(),text:se}),ne+=se,se="";ye++},dt=async(Fe)=>{Ce=ee.getReader();try{while(!0){let{done:et,value:Je}=await Ce.read();if(et||ce)break;Fe.send(JSON.stringify({realtimeInput:{audio:{data:M(Je),mimeType:`audio/pcm;rate=${N}`}}})),await ue(Fe)}}finally{Ce.releaseLock(),Ce=void 0}if(!ce){if(Fe.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),Ue=!0,Ve&&!qe)ze()}};Ee=fe({url:w,headers:x,webSocket:f,abortSignal:V,onAbort:He,onProcessingError:He,onOpen:(Fe)=>{Le.enqueue({type:"stream-start",warnings:re}),Fe.send(JSON.stringify({setup:A})),Ne.then(()=>ce?void 0:dt(Fe)).catch(He)},onMessageText:async(Fe)=>{if(ce)return;let et=await J({text:Fe});if(!et.success)return;let Je=et.value;if(pe)Le.enqueue({type:"raw",rawValue:Je});if(Je.setupComplete!=null)je();if(Je.usageMetadata!=null)De=xs(De,Je.usageMetadata);if(Je.error!=null){He(Error(Je.error.message??"Google Live API error"));return}let Be=Je.serverContent?.inputTranscription?.text??Je.inputTranscription?.text;if(Be)nt(),be+=Be,Le.enqueue({type:"source-transcript-delta",id:Ze(),delta:Be});let Pe=Je.serverContent;if(Pe==null)return;for(let lt of Pe.modelTurn?.parts??[])if(lt.inlineData?.data){Le.enqueue({type:"audio",id:Ze(),audio:lt.inlineData.data});let it=Rs(lt.inlineData.data);if(Ue&&it!=null){if(tt+=it,tt>=B){st();return}}else nt()}if(Pe.outputTranscription?.text)nt(),se+=Pe.outputTranscription.text,Le.enqueue({type:"output-text-delta",id:Ze(),delta:Pe.outputTranscription.text});if(Pe.turnComplete){if(at(),qe=!1,Ve=!0,Ue)ze()}},onSocketError:()=>{He(Error("Google Live translation error"))},onClose:({code:Fe,reason:et})=>{if(ce)return;if(We!=null){st();return}He(Error(`Google Live translation WebSocket closed unexpectedly before finishing (code ${Fe??"unknown"}${et?`, reason: ${et}`:""}).`))}})},cancel:()=>{if(ce)return;ce=!0,Re()}})}function xs(f,w){let x=f?.inputAudioTokens,A=f?.outputAudioTokens;for(let N of w.promptTokensDetails??[])if(N.modality==="AUDIO"&&N.tokenCount!=null)x=(x??0)+N.tokenCount;for(let N of w.responseTokensDetails??[])if(N.modality==="AUDIO"&&N.tokenCount!=null)A=(A??0)+N.tokenCount;if(x==null&&A==null)return f;return{...f,...x!=null?{inputAudioTokens:x}:{},...A!=null?{outputAudioTokens:A}:{}}}function Rs(f){let w;try{w=j(f)}catch{return}if(w.byteLength<2)return;let x=new DataView(w.buffer,w.byteOffset,w.byteLength),A=Math.floor(w.byteLength/2);for(let N=0;N<A;N++)if(Math.abs(x.getInt16(N*2,!0))>ws)return;return A/Cs*1000}function Os({modelId:f,targetLanguage:w,providerOptions:x}){return{model:Tt(f),generationConfig:{responseModalities:["AUDIO"],translationConfig:{targetLanguageCode:w,...x?.echoTargetLanguage!=null?{echoTargetLanguage:x.echoTargetLanguage}:{}}},inputAudioTranscription:{},outputAudioTranscription:{}}}function Ms(f){if(f.type!=="audio/pcm"||f.rate!=null&&f.rate!==16000)throw new b({argument:"inputAudioFormat",message:"The Gemini Live translation API only supports 16kHz 16-bit PCM input audio."})}var Es="https://generativelanguage.googleapis.com/v1beta",As=/^https:\/\/generativelanguage\.googleapis\.com\/v1beta\/files\/.*$/,Ls=["text/html","text/css","text/plain","text/xml","text/csv","text/rtf","text/javascript","application/json","application/pdf","image/bmp","image/jpeg","image/png","image/webp","video/mp4","video/mpeg","video/quicktime","video/avi","video/x-flv","video/mpg","video/webm","video/wmv","video/3gpp"],js=/^https:\/\/.*$/;function Us(f){return/(^|\/)gemini-/.test(f)&&!/(^|\/)gemini-2\.0/.test(f)}function Kt(f={}){let w=Y(f.baseURL)??Es,x=f.name??"google.generative-ai",A=()=>F({"x-goog-api-key":he({apiKey:f.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...f.headers},`ai-sdk-google/${zn}`),N=(be,ne=be==null||Us(be))=>({"*":[As,new RegExp(`^${w}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")],...ne?Object.fromEntries(Ls.map((se)=>[se,[js]])):{}}),B={provider:x,baseURL:w,headers:A,generateId:f.generateId??C,fetch:f.fetch},re=(be)=>new Ct(be,{...B,supportedUrls:()=>N(be)}),ee=()=>new Wo({provider:`${x.replace(/\.generative-ai$/,"")}.batch`,maxLineBytes:f.batchResultDownloads?.maxLineBytes,config:B,supportedUrls:N(void 0,!1)}),V=(be)=>new Qn(be,{provider:x,baseURL:w,headers:A,fetch:f.fetch}),pe=(be,ne={})=>new ni(be,ne,{provider:x,baseURL:w,headers:A,fetch:f.fetch}),ce=()=>new oi({provider:x,baseURL:w,headers:A,fetch:f.fetch}),Re=(be)=>new hi(be,{provider:x,baseURL:w,headers:A,fetch:f.fetch,generateId:f.generateId??C}),Le=(be)=>new rs(be,{provider:`${x}.realtime`,baseURL:w,headers:A,fetch:f.fetch}),Ce=(be)=>new Is(be,{provider:`${x}.speech-translation`,baseURL:w,headers:A,webSocket:f.webSocket}),Ee=(be)=>new _i(be,{provider:`${x}.speech`,baseURL:w,headers:A,fetch:f.fetch}),je=(be)=>new ps(be,{provider:`${x}.transcription`,baseURL:w,headers:A,fetch:f.fetch,webSocket:f.webSocket}),Ne=Object.assign((be)=>Le(be),{getToken:async(be)=>{let ne=await Le(be.model).doCreateClientSecret({sessionConfig:be.sessionConfig,expiresAfterSeconds:be.expiresAfterSeconds});return{token:ne.token,url:ne.url,expiresAt:ne.expiresAt}}}),ye=(be)=>new Zi(be,{provider:`${x}.interactions`,baseURL:w,headers:A,generateId:f.generateId??C,fetch:f.fetch}),ie=function(be){if(new.target)throw Error("The Google Generative AI model function cannot be called with the new keyword.");return re(be)};return ie.specificationVersion="v4",ie.languageModel=re,ie.chat=re,ie.generativeAI=re,ie.decisionModel=(be)=>new rt({model:re(be),provider:`${x.replace(/\.generative-ai$/,"")}.decision`}),ie.evaluationModel=ie.decisionModel,ie.experimental_batch=ee,ie.embedding=V,ie.embeddingModel=V,ie.textEmbedding=V,ie.textEmbeddingModel=V,ie.image=pe,ie.imageModel=pe,ie.video=Re,ie.videoModel=Re,ie.experimental_realtime=Ne,ie.files=ce,ie.speech=Ee,ie.speechModel=Ee,ie.transcription=je,ie.transcriptionModel=je,ie.translation=Ce,ie.speechTranslationModel=Ce,ie.interactions=ye,ie.tools=ei,ie}var Fs=Kt();var Ns=Ie(Kt);function Qs(){oe("google",Ns)}export{Qs as register};