murmur-rag 0.1.2 → 1.1.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 (59) hide show
  1. package/README.md +23 -19
  2. package/dist/cdn/anthropic-dc7h9prc.js +2 -0
  3. package/dist/cdn/chunk-hpx6rpea.js +1 -0
  4. package/dist/cdn/{embed-hn0r8fmg.js → embed-6gef7ym5.js} +2 -2
  5. package/dist/cdn/{embed-59r4jck6.js → embed-acjpjh6t.js} +3 -3
  6. package/dist/cdn/embed-fd96s8qk.js +44 -0
  7. package/dist/cdn/embed-jdraznwg.js +83 -0
  8. package/dist/cdn/{embed-q6y6vgv1.js → embed-krrjjyf5.js} +4 -4
  9. package/dist/cdn/{embed-we24qtes.js → embed-ssqsb38w.js} +2 -2
  10. package/dist/cdn/embed-z32y952f.js +9 -0
  11. package/dist/cdn/google-yywkqdph.js +14 -0
  12. package/dist/cdn/index-bq0x71h1.js +1 -0
  13. package/dist/cdn/index-gyd02jvt.js +9 -0
  14. package/dist/cdn/index-jt6n0d28.js +1 -0
  15. package/dist/cdn/index-nesgnf2n.js +1 -0
  16. package/dist/cdn/index-wgzgvzaf.js +1 -0
  17. package/dist/cdn/mistral-0mg4kk7s.js +3 -0
  18. package/dist/cdn/murmur-j1ky5vmr.js +5 -0
  19. package/dist/cdn/murmur.js +24 -5
  20. package/dist/cdn/openai-compatible-zhaj1r43.js +11 -0
  21. package/dist/cdn/openai-g1685z9v.js +18 -0
  22. package/dist/cdn/retriever-dqxzjaqk.js +1 -0
  23. package/dist/cdn/transformers.web-3kmbvcbt.js +46 -0
  24. package/dist/cli.js +10 -5
  25. package/dist/lib/chunks/{index-fs6gmhz9.js → index-8h9c8ekq.js} +4 -2
  26. package/dist/lib/chunks/{index-0x7gav29.js → index-92w507gk.js} +304 -27
  27. package/dist/lib/chunks/{index-6re28wc1.js → index-b77xqap3.js} +13 -1
  28. package/dist/lib/chunks/{index-z8pn9sdj.js → index-p86sy3y4.js} +17 -4
  29. package/dist/lib/chunks/{murmur-wq1d15n7.js → murmur-t36hd4vt.js} +2 -2
  30. package/dist/lib/chunks/{retriever-1rw4z2n6.js → retriever-wxshtnm0.js} +1 -1
  31. package/dist/lib/embed.js +4 -2
  32. package/dist/lib/index.js +5 -3
  33. package/dist/lib/indexer/index.js +10 -5
  34. package/dist/lib/local/index.js +163 -0
  35. package/dist/lib/rag/index.js +13 -11
  36. package/dist/lib/widget/index.js +2 -2
  37. package/dist/types/local/index.d.ts +56 -0
  38. package/dist/types/rag/ground.d.ts +7 -0
  39. package/dist/types/rag/index.d.ts +1 -1
  40. package/dist/types/widget/element.d.ts +3 -0
  41. package/dist/types/widget/i18n.d.ts +14 -0
  42. package/dist/types/widget/session.d.ts +20 -1
  43. package/dist/types/widget/styles.d.ts +1 -1
  44. package/package.json +18 -3
  45. package/dist/cdn/anthropic-w7nkjk5e.js +0 -2
  46. package/dist/cdn/chunk-e0j28zmb.js +0 -1
  47. package/dist/cdn/embed-2xm309sb.js +0 -7
  48. package/dist/cdn/embed-n7jskdxd.js +0 -44
  49. package/dist/cdn/embed-sgjh2kg2.js +0 -83
  50. package/dist/cdn/google-qha5xyx4.js +0 -14
  51. package/dist/cdn/index-11c9cspb.js +0 -1
  52. package/dist/cdn/index-e5entetm.js +0 -1
  53. package/dist/cdn/index-kk9hgxdc.js +0 -1
  54. package/dist/cdn/index-zrmby2xc.js +0 -9
  55. package/dist/cdn/mistral-16bekg8b.js +0 -3
  56. package/dist/cdn/murmur-5vkc01ns.js +0 -5
  57. package/dist/cdn/openai-compatible-za7hc1fv.js +0 -11
  58. package/dist/cdn/openai-dhy4fp4c.js +0 -18
  59. package/dist/cdn/retriever-k9mmdcz5.js +0 -1
@@ -1,14 +0,0 @@
1
- import{oe,Ee}from"./embed-hn0r8fmg.js";import{Xe}from"./embed-59r4jck6.js";import{m,b,A,me,u,e,r,c,w,Re,o,t,B,l,y,a,n,F,S,I,d,Oe,ue,fe,ie,q,X,T,ve,Jt,te,le,xe,Se,W,L,Ie,z,K,Ge,Te,Yt,de,C,P,j,We,he,H,ke,it,ge,Q,i,s,N,J,h,g,we,k,_,O,V,E,D,p,_e,M,Y}from"./embed-sgjh2kg2.js";var zn="4.0.107",fn=()=>t({code:r().nullable(),message:e(),status:e(),details:o(w()).nullish()}),Jn=i(()=>s(t({error:fn()}))),Ze=E({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=i(()=>s(t({outputDimensionality:r().optional(),taskType:a(["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[S](v){return M({modelId:v.modelId,config:v.config})}static[I](v){return new f(v.modelId,v.config)}get provider(){return this.config.provider}constructor(v,x){this.specificationVersion="v4",this.maxEmbeddingsPerCall=100,this.supportsParallelCalls=!0,this[Yt]=({providerOptions:R,values:U,startIndex:G,endIndex:re})=>{let ee=R?.google?.content;if(!Array.isArray(ee))return R;return zt({multimodalContent:ee,values:U}),{...R,google:{...R?.google,content:ee.slice(G,re)}}},this.modelId=v,this.config=x}async doEmbed({values:v,dimensions:x,headers:R,abortSignal:U,providerOptions:G}){let re=await h({provider:"google",providerOptions:G,schema:Xn});if(v.length>this.maxEmbeddingsPerCall)throw new me({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:v});let ee=d(this.config.headers?await _(this.config.headers):void 0,R),Z=re?.content;if(zt({multimodalContent:Z,values:v}),v.length===1){let Le=Z?.[0],Ce=v[0]?[{text:v[0]}]:[],Ae=Le!=null?[...Ce,...Le]:[{text:v[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:Ae},outputDimensionality:re?.outputDimensionality??x,taskType:re?.taskType},failedResponseHandler:Ze,successfulResponseHandler:p(eo),abortSignal:U,fetch:this.config.fetch});return{warnings:[],embeddings:[Ne.embedding.values],usage:void 0,response:{headers:je,body:ye}}}let{responseHeaders:pe,value:ce,rawValue:Me}=await g({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:ee,body:{requests:v.map((Le,Ce)=>{let Ae=Z?.[Ce],je=Le?[{text:Le}]:[];return{model:`models/${this.modelId}`,content:{role:"user",parts:Ae!=null?[...je,...Ae]:[{text:Le}]},outputDimensionality:re?.outputDimensionality??x,taskType:re?.taskType}})},failedResponseHandler:Ze,successfulResponseHandler:p(Zn),abortSignal:U,fetch:this.config.fetch});return{warnings:[],embeddings:ce.embeddings.map((Le)=>Le.values),usage:void 0,response:{headers:pe,body:Me}}}},Zn=i(()=>s(t({embeddings:o(t({values:o(r())}))}))),eo=i(()=>s(t({embedding:t({values:o(r())})})));function zt({multimodalContent:f,values:v}){if(f!=null&&f.length!==v.length)throw Error(`The number of multimodal content entries (${f.length}) must match the number of values (${v.length}).`)}function Tt(f){return f.includes("/")?f:`models/${f}`}function to({stream:f,getContinuationToken:v,continueStream:x}){let R=f.getReader(),U;return new ReadableStream({async pull(G){while(!0){let{done:re,value:ee}=await R.read();if(!re){if(ee.success){let pe=v(ee.value);if(pe!=null)U=pe}G.enqueue(ee);return}if(U==null){G.close();return}let Z=U;U=void 0;try{R=(await x(Z)).getReader(),G.enqueue({type:"continuation-start"});return}catch(pe){G.enqueue({success:!1,error:pe,rawValue:void 0}),G.close();return}}},async cancel(G){await R.cancel(G)}})}function Xt(f){if(f==null)return te();let v=f.promptTokenCount??0,x=f.candidatesTokenCount??0,R=f.toolUsePromptTokenCount??0,U=f.cachedContentTokenCount??0,G=f.thoughtsTokenCount??0,re=v+R;return{inputTokens:{total:re,noCache:re-U,cacheRead:U,cacheWrite:void 0},outputTokens:{total:x+G,text:x,reasoning:G},raw:f}}function jt(f,v){if(f==null||v==null)return v??f;return{...f,...v,promptTokenCount:vt(f.promptTokenCount,v.promptTokenCount),candidatesTokenCount:vt(f.candidatesTokenCount,v.candidatesTokenCount),toolUsePromptTokenCount:vt(f.toolUsePromptTokenCount,v.toolUsePromptTokenCount),totalTokenCount:vt(f.totalTokenCount,v.totalTokenCount),cachedContentTokenCount:vt(f.cachedContentTokenCount,v.cachedContentTokenCount),thoughtsTokenCount:vt(f.thoughtsTokenCount,v.thoughtsTokenCount),promptTokensDetails:kt(f.promptTokensDetails,v.promptTokensDetails),cacheTokensDetails:kt(f.cacheTokensDetails,v.cacheTokensDetails),candidatesTokensDetails:kt(f.candidatesTokensDetails,v.candidatesTokensDetails),toolUsePromptTokensDetails:kt(f.toolUsePromptTokensDetails,v.toolUsePromptTokensDetails)}}function vt(f,v){return f==null&&v==null?v??f:(f??0)+(v??0)}function kt(f,v){if(f==null||v==null)return v??f;let x=new Map;for(let{modality:R,tokenCount:U}of[...f,...v])x.set(R,(x.get(R)??0)+U);return Array.from(x,([R,U])=>({modality:R,tokenCount:U}))}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=k({id:"google.code_execution",inputSchema:yn,outputSchema:vn}),oo="skip_thought_signature_validator",io=/^data:([^;,]+);base64,(.+)$/s;function so(f){let v=io.exec(f);if(v==null)return;return{mediaType:v[1],data:v[2]}}function ao(f){let v=so(f);if(v==null)return;return{inlineData:{mimeType:v.mediaType,data:v.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(([v,x])=>v==="$ref"||Gt(x))}function Qt(f){return Gt(f)?JSON.stringify(f):f}function ro(f,v,x,R,U=!0,G={}){let re=[],ee=[];for(let Z of x)switch(Z.type){case"text":ee.push(Z.text);break;case"file":if(Z.data.type==="data")re.push({inlineData:{mimeType:O({part:Z}),data:T(Z.data.data)}});else if(Z.data.type==="url"){let pe=Z.data.url.toString(),ce=ao(pe),Me=Z.data.url.protocol==="gs:"&&Z.data.originalUrl!=null?Z.data.originalUrl:pe;if(ce!=null)re.push(ce);else if(K(Z.mediaType)&&We({url:Me,mediaType:Z.mediaType,supportedUrls:G}))re.push({fileData:{mimeType:Z.mediaType,fileUri:Me}});else ee.push(JSON.stringify(Z))}else ee.push(JSON.stringify(Z));break;default:ee.push(JSON.stringify(Z))}f.push({functionResponse:{...U&&R!=null?{id:R}:{},name:v,response:{name:v,content:ee.length>0?ee.join(`
2
- `):"Tool executed successfully."},...re.length>0?{parts:re}:{}}})}function lo(f,v,x,R,U=!0){for(let G of x)switch(G.type){case"text":f.push({functionResponse:{...U&&R!=null?{id:R}:{},name:v,response:{name:v,content:G.text}}});break;case"file":if(G.data.type==="data"){let re=z(G.mediaType);f.push({inlineData:{mimeType:O({part:G}),data:T(G.data.data)}},{text:`Tool executed successfully and returned this ${re==="image"?"image":"file"} as a response`})}else f.push({text:JSON.stringify(G)});break;default:f.push({text:JSON.stringify(G)})}}function uo(f,v){let x=[],R=[],U=!0,G=v?.isGemmaModel??!1,re=v?.isGemini3Model??!1,ee=v?.onWarning,Z=v?.providerOptionsNames??["google"],pe=!Z.includes("google"),ce=v?.supportsFunctionResponseParts??!0,Me=v?.includeFunctionCallIds??!0,Le=v?.supportedFunctionResponseUrls??{},Ce=!1,Ae=[],je=(ye)=>(Ae.push(ye),Ce=!0,oo),Ne=(ye)=>{for(let se of Z){let be=ye.providerOptions?.[se];if(be!=null)return be}if(pe)return ye.providerOptions?.google;return ye.providerOptions?.googleVertex??ye.providerOptions?.vertex};for(let{role:ye,content:se}of f)switch(ye){case"system":if(!U)throw new u({functionality:"system messages are only supported at the beginning of the conversation"});x.push({text:se});break;case"user":{U=!1;let be=[];for(let ne of se)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:V({reference:ne.data.reference,provider:"google"})}});break;case"text":be.push({inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:T(new TextEncoder().encode(ne.data.text))}});break;case"data":be.push({inlineData:{mimeType:O({part:ne}),data:T(ne.data.data)}})}}R.push({role:"user",parts:be});break}case"assistant":{U=!1;let be=!1;R.push({role:"model",parts:se.map((ne)=>{let ae=Ne(ne),Ue=ae?.thoughtSignature!=null?String(ae.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:T(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:V({reference:ne.data.reference,provider:"google"})},...ae?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"text":return{inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:T(new TextEncoder().encode(ne.data.text))},...ae?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"data":return{inlineData:{mimeType:ne.mediaType,data:T(ne.data.data)},...ae?.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 Pe=ae?.serverToolCallId!=null?String(ae.serverToolCallId):void 0,$e=ae?.serverToolType!=null?String(ae.serverToolType):void 0,Ke=Pe!=null&&$e!=null,nt=Ue??(re&&!(!Ke&&Ue==null&&be)?je(ne.toolName):void 0);if(!Ke&&Ue!=null)be=!0;if(Ke)return{toolCall:{toolType:$e,args:typeof ne.input==="string"?Q(ne.input):ne.input,id:Pe},thoughtSignature:nt};return{functionCall:{...Me&&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 Pe=ae?.serverToolCallId!=null?String(ae.serverToolCallId):void 0,$e=ae?.serverToolType!=null?String(ae.serverToolType):void 0;if(Pe&&$e)return{toolResponse:{toolType:$e,response:ne.output.type==="json"?ne.output.value:{},id:Pe},thoughtSignature:Ue};return}}}).filter((ne)=>ne!==void 0)});break}case"tool":{U=!1;let be=[];for(let ne of se){if(ne.type==="tool-approval-response")continue;let ae=Ne(ne),Ue=ae?.serverToolCallId!=null?String(ae.serverToolCallId):void 0,Pe=ae?.serverToolType!=null?String(ae.serverToolType):void 0;if(Ue&&Pe){let Ke=ae?.thoughtSignature!=null?String(ae.thoughtSignature):void 0;if(R.length>0){let nt=R[R.length-1];if(nt.role==="model"){nt.parts.push({toolResponse:{toolType:Pe,response:ne.output.type==="json"?ne.output.value:{},id:Ue},thoughtSignature:Ke});continue}}}let $e=ne.output;if($e.type==="content")if(ce)ro(be,ne.toolName,$e.value,ne.toolCallId,Me,Le);else lo(be,ne.toolName,$e.value,ne.toolCallId,Me);else{let Ke=$e.type==="error-text"||$e.type==="error-json"||$e.type==="execution-denied";be.push({functionResponse:{...Me&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,response:{name:ne.toolName,...Ke?{error:$e.type==="execution-denied"?$e.reason??"Tool call execution denied.":Qt($e.value)}:{content:Qt($e.value)}}}})}}R.push({role:"user",parts:be});break}}if(G&&x.length>0&&R.length>0&&R[0].role==="user"){let ye=x.map((se)=>se.text).join(`
3
-
4
- `);R[0].parts.unshift({text:ye+`
5
-
6
- `})}if(Ce&&ee!=null){let ye=Array.from(new Set(Ae));ee({type:"other",message:`Replayed ${Ae.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${ye.map((se)=>`\`${se}\``).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&&!G?{parts:x}:void 0,contents:R}}async function co(f,{abortSignal:v,maxBytes:x,supportedUrls:R={}}){let U=[];for(let G of f){if(G.role==="assistant"){let re=[];for(let ee of G.content)re.push(ee.type==="tool-result"?{...ee,output:await Zt(ee.output,{abortSignal:v,maxBytes:x,supportedUrls:R})}:ee);U.push({...G,content:re});continue}if(G.role==="tool"){let re=[];for(let ee of G.content){if(ee.type!=="tool-result"){re.push(ee);continue}re.push({...ee,output:await Zt(ee.output,{abortSignal:v,maxBytes:x,supportedUrls:R})})}U.push({...G,content:re});continue}U.push(G)}return U}async function Zt(f,{abortSignal:v,maxBytes:x,supportedUrls:R}){if(f.type!=="content")return f;let U=[];for(let G of f.value){if(G.type!=="file"||G.data.type!=="url"){U.push(G);continue}if(We({url:G.data.url.toString(),mediaType:G.mediaType,supportedUrls:R})){U.push(G);continue}let re=await Te(G.data.url.toString(),{abortSignal:v,maxBytes:x}),ee=new Uint8Array(await re.arrayBuffer()),Z=Ie({data:ee,topLevelType:"image"});U.push({...G,data:{type:"data",data:ee},mediaType:Z??(re.type&&!K(G.mediaType)?re.type:G.mediaType)})}return{...f,value:U}}function bn(f){let{const:v,properties:x,items:R,additionalProperties:U,anyOf:G,oneOf:re,...ee}=f;return{...ee,...v!==void 0?{enum:[v]}:{},...x!=null?{properties:en(x)}:{},...R!=null?{items:Array.isArray(R)?R.map(bt):bt(R)}:{},...U!=null?{additionalProperties:typeof U==="boolean"?U:bt(U)}:{},...G!=null?{anyOf:G.map(bt)}:{},...re!=null?{oneOf:re.map(bt)}:{},...ee.$defs!=null?{$defs:en(ee.$defs)}:{}}}function en(f){return Object.fromEntries(Object.entries(f).map(([v,x])=>[v,bt(x)]))}function bt(f){return typeof f==="boolean"?f:bn(f)}var Et=i(()=>s(t({responseModalities:o(a(["TEXT","IMAGE","AUDIO"])).optional(),thinkingConfig:t({thinkingBudget:r().optional(),includeThoughts:c().optional(),thinkingLevel:a(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:e().optional(),structuredOutputs:c().optional(),safetySettings:o(t({category:a(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:a(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:a(["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:a(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:t({aspectRatio:a(["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:a(["1K","2K","4K","512"]).optional(),personGeneration:a(["PERSON_GENERATION_UNSPECIFIED","ALLOW_ALL","ALLOW_ADULT","ALLOW_NONE"]).optional(),prominentPeople:a(["PROMINENT_PEOPLE_UNSPECIFIED","ALLOW_PROMINENT_PEOPLE","BLOCK_PROMINENT_PEOPLE"]).optional(),imageOutputOptions:t({mimeType:a(["image/jpeg","image/png"]).optional(),compressionQuality:r().optional()}).optional()}).optional(),retrievalConfig:t({latLng:t({latitude:r(),longitude:r()}).optional()}).optional(),streamFunctionCallArguments:c().optional(),serviceTier:a(["standard","flex","priority"]).optional(),continuationToken:e().optional(),sharedRequestType:a(["priority","flex","standard"]).optional(),requestType:a(["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 v=mo.test(f),x=go.test(f),R=fo(f),U=v&&!(R||x);return{supportsGemini2Tools:v&&!R||f.toLowerCase().includes("nano-banana"),supportsFileSearch:ho.test(f)||U,usesGemini3Features:U}}function yo({tools:f,toolChoice:v,modelId:x,isVertexProvider:R=!1}){f=f?.length?f:void 0;let U=[],{supportsGemini2Tools:G,supportsFileSearch:re,usesGemini3Features:ee}=At(x);if(f==null)return{tools:void 0,toolConfig:void 0,toolWarnings:U};let Z=f.some((Ce)=>Ce.type==="function"),pe=f.some((Ce)=>Ce.type==="provider");if(Z&&pe&&!ee)U.push({type:"unsupported",feature:"combination of function and provider-defined tools"});if(pe){let Ce=[];if(f.filter((Ae)=>Ae.type==="provider").forEach((Ae)=>{switch(Ae.id){case"google.google_search":if(G)Ce.push({googleSearch:{...Ae.args}});else U.push({type:"unsupported",feature:`provider-defined tool ${Ae.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":if(G)Ce.push({enterpriseWebSearch:{}});else U.push({type:"unsupported",feature:`provider-defined tool ${Ae.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":if(G)Ce.push({urlContext:{}});else U.push({type:"unsupported",feature:`provider-defined tool ${Ae.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(G)Ce.push({codeExecution:{}});else U.push({type:"unsupported",feature:`provider-defined tool ${Ae.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:{...Ae.args}});else U.push({type:"unsupported",feature:`provider-defined tool ${Ae.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(G)Ce.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:Ae.args.ragCorpus},similarity_top_k:Ae.args.topK}}});else U.push({type:"unsupported",feature:`provider-defined tool ${Ae.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":if(G)Ce.push({googleMaps:{}});else U.push({type:"unsupported",feature:`provider-defined tool ${Ae.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:U.push({type:"unsupported",feature:`provider-defined tool ${Ae.id}`})}}),Z&&ee&&Ce.length>0){let Ae=[];for(let Ne of f)if(Ne.type==="function")Ae.push(tn(Ne));let je={functionCallingConfig:{mode:"VALIDATED"},...!R&&{includeServerSideToolInvocations:!0}};if(v!=null)switch(v.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:[v.toolName]}}return{tools:[...Ce,{functionDeclarations:Ae}],toolConfig:je,toolWarnings:U}}return{tools:Ce.length>0?Ce:void 0,toolConfig:void 0,toolWarnings:U}}let ce=[],Me=!1;for(let Ce of f)switch(Ce.type){case"function":if(ce.push(tn(Ce)),Ce.strict===!0)Me=!0;break;default:U.push({type:"unsupported",feature:`function tool ${Ce.name}`})}if(v==null)return{tools:[{functionDeclarations:ce}],toolConfig:Me?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:U};let Le=v.type;switch(Le){case"auto":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:Me?"VALIDATED":"AUTO"}},toolWarnings:U};case"none":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:U};case"required":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:U};case"tool":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[v.toolName]}},toolWarnings:U};default:throw new u({functionality:`tool choice type: ${Le}`})}}function tn(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 v="";for(let x of f){let R=x.jsonPath.endsWith("[]"),U=(R?x.jsonPath.slice(0,-2):x.jsonPath).replace(/^\$\./,"");if(!U||U==="$")continue;let G=bo(U),re=_o(this.accumulatedArgs,G);if(x.stringValue!=null&&re!==void 0){let Z=JSON.stringify(x.stringValue).slice(1,-1);Ut(this.accumulatedArgs,G,re+x.stringValue),v+=Z;continue}let ee=Co(x);if(ee==null){if(re!==void 0||x.willContinue===!0)continue;Ut(this.accumulatedArgs,G,R?[]:{}),v+=this.emitContainer(G,R);continue}Ut(this.accumulatedArgs,G,ee.value),v+=this.emitNavigationTo(G,x,ee.json)}return this.jsonText+=v,{currentJSON:this.accumulatedArgs,textDelta:v}}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,v,x){let R="";if(this.stringOpen)R+='"',this.stringOpen=!1;R+=this.ensureRoot();let U=f.slice(0,-1),G=f[f.length-1],re=this.findCommonStackDepth(U);return R+=this.closeDownTo(re),R+=this.openDownTo(U,G),R+=this.emitLeaf(G,v,x),R}emitContainer(f,v){let x="";if(this.stringOpen)x+='"',this.stringOpen=!1;x+=this.ensureRoot();let R=this.findCommonStackDepth(f);return x+=this.closeDownTo(R),x+=this.openDownTo(f,v?0:""),x}findCommonStackDepth(f){let v=Math.min(this.pathStack.length-1,f.length),x=0;for(let R=0;R<v;R++)if(this.pathStack[R+1].segment===f[R])x++;else break;return x+1}closeDownTo(f){let v="";while(this.pathStack.length>f){let x=this.pathStack.pop();v+=x.isArray?"]":"}"}return v}openDownTo(f,v){let x="",R=this.pathStack.length-1;for(let U=R;U<f.length;U++){let G=f[U],re=this.pathStack[this.pathStack.length-1];if(re.childCount>0)x+=",";if(re.childCount++,typeof G==="string")x+=`${JSON.stringify(G)}:`;let ee=typeof(U+1<f.length?f[U+1]:v)==="number";x+=ee?"[":"{",this.pathStack.push({segment:G,isArray:ee,childCount:0})}return x}emitLeaf(f,v,x){let R="",U=this.pathStack[this.pathStack.length-1];if(U.childCount>0)R+=",";if(U.childCount++,typeof f==="string")R+=`${JSON.stringify(f)}:`;if(v.stringValue!=null&&v.willContinue)R+=x.slice(0,-1),this.stringOpen=!0;else R+=x;return R}};function bo(f){let v=[];for(let x of f.split(".")){let R=x.indexOf("[");if(R===-1)v.push(x);else{if(R>0)v.push(x.slice(0,R));for(let U of x.matchAll(/\[(\d+)\]/g))v.push(parseInt(U[1],10))}}return v}var To=Object.prototype.hasOwnProperty;function Tn(f,v){return To.call(f,v)}function nn(f,v,x){Object.defineProperty(f,v,{value:x,enumerable:!0,configurable:!0,writable:!0})}function _o(f,v){let x=f;for(let R of v){if(x==null||typeof x!=="object")return;let U=x;if(!Tn(U,R))return;x=U[R]}return x}function Ut(f,v,x){let R=f;for(let U=0;U<v.length-1;U++){let G=v[U],re=v[U+1];if(!Tn(R,G)||R[G]==null)nn(R,G,typeof re==="number"?[]:{});R=R[G]}nn(R,v[v.length-1],x)}function Co(f){let v=f.stringValue??f.numberValue??f.boolValue;if(v!=null)return{value:v,json:JSON.stringify(v)};if("nullValue"in f)return{value:null,json:"null"}}function on({finishReason:f,hasToolCalls:v}){switch(f){case"STOP":return v?"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[S](v){return M({modelId:v.modelId,config:v.config})}static[I](v){return new f(v.modelId,v.config)}constructor(v,x){this.specificationVersion="v4",this.modelId=v,this.config=x,this.generateId=x.generateId??C}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?.()??{}}static async prepareRequest({modelId:v,config:x,options:{prompt:R,maxOutputTokens:U,temperature:G,topP:re,topK:ee,frequencyPenalty:Z,presencePenalty:pe,stopSequences:ce,responseFormat:Me,seed:Le,tools:Ce,toolChoice:Ae,reasoning:je,providerOptions:Ne,abortSignal:ye},isStreaming:se=!1}){let be=[],ne=x.provider.includes("vertex")?["googleVertex","vertex"]:["google"],ae;for(let at of ne)if(ae=await h({provider:at,providerOptions:Ne,schema:Et}),ae!=null)break;if(ae==null&&!ne.includes("google"))ae=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(ae?.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(ae?.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((ae?.sharedRequestType||ae?.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 Pe=Ue&&(ae?.sharedRequestType||ae?.requestType)?{...ae.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":ae.sharedRequestType},...ae.requestType&&{"X-Vertex-AI-LLM-Request-Type":ae.requestType}}:void 0,$e=Ue?void 0:ae?.serviceTier,Ke=ae?.imageConfig;if(Ke!=null&&!Ue){let{personGeneration:at,prominentPeople:st,imageOutputOptions:wt,...St}=Ke,Qe=Object.entries({personGeneration:at,prominentPeople:st,imageOutputOptions:wt}).filter(([,De])=>De!=null).map(([De])=>`'imageConfig.${De}'`);if(Qe.length>0)be.push({type:"other",message:`${Qe.join(", ")} ${Qe.length===1?"is a Vertex AI option and is":"are Vertex AI options and are"} ignored with the current Google provider (${x.provider}).`}),Ke=St}let nt=v.toLowerCase().startsWith("gemma-"),ze=!Ue&&So.test(v);if(ze&&Z!=null)be.push({type:"unsupported",feature:"frequencyPenalty"});if(ze&&pe!=null)be.push({type:"unsupported",feature:"presencePenalty"});let{usesGemini3Features:et}=At(v),pt=et&&x.downloadToolResultFiles?.supportsGoogleCloudStorageUrls?Io:void 0,{contents:Je,systemInstruction:ot}=uo(x.downloadToolResultFiles?await co(R,{abortSignal:ye,maxBytes:x.downloadToolResultFiles.maxBytes,supportedUrls:pt}):R,{isGemmaModel:nt,isGemini3Model:et,onWarning:(at)=>be.push(at),providerOptionsNames:ne,supportsFunctionResponseParts:et,includeFunctionCallIds:!Ue,supportedFunctionResponseUrls:pt}),{tools:Ve,toolConfig:rt,toolWarnings:lt}=yo({tools:Ce,toolChoice:Ae,modelId:v,isVertexProvider:Ue}),dt=le({tools:Ce,providerToolNames:{"google.code_execution":"code_execution"}}),Be=ae?.thinkingConfig?.thinkingBudget!=null||ae?.thinkingConfig?.thinkingLevel!=null?void 0:Ro({reasoning:je,modelId:v,warnings:be}),tt=ae?.thinkingConfig||Be?{...Be,...ae?.thinkingConfig}:void 0,Ye=se&&Ue?ae?.streamFunctionCallArguments??!1:void 0,He=ae?.threshold,qe=ae?.safetySettings??(He!=null?wo.map((at)=>({category:at,threshold:He})):void 0),ut=rt||Ye||ae?.retrievalConfig?{...rt,...Ye&&{functionCallingConfig:{...rt?.functionCallingConfig,streamFunctionCallArguments:!0}},...ae?.retrievalConfig&&{retrievalConfig:ae.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:U,temperature:G,topK:ee,topP:re,frequencyPenalty:ze?void 0:Z,presencePenalty:ze?void 0:pe,stopSequences:ce,seed:Le,responseMimeType:Me?.type==="json"?"application/json":void 0,responseJsonSchema:Me?.type==="json"&&Me.schema!=null&&(ae?.structuredOutputs??!0)?bn(Me.schema):void 0,...ae?.audioTimestamp&&{audioTimestamp:ae.audioTimestamp},responseModalities:ae?.responseModalities,thinkingConfig:tt,...ae?.mediaResolution&&{mediaResolution:ae.mediaResolution},...Ke&&{imageConfig:Ke}},contents:Je,systemInstruction:nt?void 0:ot,safetySettings:qe,tools:Ve,toolConfig:ut,cachedContent:ae?.cachedContent,labels:ae?.labels,serviceTier:$e,...ae?.continuationToken!=null&&{continuationToken:ae.continuationToken}},warnings:[...be,...lt],providerOptionsNames:ne,extraHeaders:Pe,toolNameMapping:dt}}async getArgs(v,{isStreaming:x=!1}={}){let{responseFormat:R,tools:U,toolChoice:G}=v,re;if(R?.type==="json"&&R.schema!=null&&U?.some((ee)=>ee.type==="function")&&/(^|\/)gemini-/i.test(this.modelId)&&(!At(this.modelId).usesGemini3Features||G?.type==="required"||G?.type==="tool")){let ee="json";for(let Z=1;U.some((pe)=>pe.name===ee);Z++)ee=`json_${Z}`;re={type:"function",name:ee,description:R.description??"Respond with a JSON object.",inputSchema:R.schema}}return{...await f.prepareRequest({modelId:this.modelId,config:this.config,options:re==null?v:{...v,responseFormat:void 0,tools:[...U??[],re],toolChoice:G?.type==="tool"?G:G?.type==="none"?{type:"tool",toolName:re.name}:{type:"required"}},isStreaming:x}),jsonResponseToolName:re?.name}}static convertGenerateContentResponse({config:v,response:x,warnings:R,providerOptionsNames:U,toolNameMapping:G,jsonResponseToolName:re,initialPromptTokenCount:ee,groundingMetadataPerRequest:Z}){let pe=(ae)=>Object.fromEntries(U.map((Ue)=>[Ue,ae])),ce=x.candidates?.[0],Me=x.promptFeedback?.blockReason,Le=an(Me)?Me:void 0,Ce=ce?.finishReason==null&&Le!=null,Ae=ce?.finishReason??Le,je=[],Ne=ce?.content?.parts??[],ye=x.usageMetadata,se,be;for(let ae of Ne)if("executableCode"in ae&&ae.executableCode?.code){let Ue=v.generateId();se=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:G?.toCustomToolName("code_execution")??"code_execution",input:JSON.stringify(ae.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in ae&&ae.codeExecutionResult)je.push({type:"tool-result",toolCallId:se,toolName:G?.toCustomToolName("code_execution")??"code_execution",result:{outcome:ae.codeExecutionResult.outcome,output:ae.codeExecutionResult.output??""}});else if("text"in ae&&ae.text!=null){if(re!=null&&ae.thought!==!0)continue;let Ue=ae.thoughtSignature?pe({thoughtSignature:ae.thoughtSignature}):void 0;if(ae.text.length===0){if(Ue!=null&&je.length>0){let Pe=je[je.length-1];Pe.providerMetadata=Ue}}else je.push({type:ae.thought===!0?"reasoning":"text",text:ae.text,providerMetadata:Ue})}else if("functionCall"in ae&&ae.functionCall.name!=null){if(ae.functionCall.name===re){je.push({type:"text",text:typeof ae.functionCall.args==="string"?ae.functionCall.args:JSON.stringify(ae.functionCall.args??{}),...ae.thoughtSignature?{providerMetadata:pe({thoughtSignature:ae.thoughtSignature})}:{}});continue}je.push({type:"tool-call",toolCallId:ae.functionCall.id||v.generateId(),toolName:ae.functionCall.name,input:JSON.stringify(ae.functionCall.args??{}),providerMetadata:ae.thoughtSignature?pe({thoughtSignature:ae.thoughtSignature}):void 0})}else if("inlineData"in ae){let Ue=ae.thought===!0,Pe=!!ae.thoughtSignature;je.push({type:Ue?"reasoning-file":"file",data:{type:"data",data:ae.inlineData.data},mediaType:ae.inlineData.mimeType,providerMetadata:Pe?pe({thoughtSignature:ae.thoughtSignature}):void 0})}else if("toolCall"in ae&&ae.toolCall){let Ue=ae.toolCall.id||v.generateId();be=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:`server:${ae.toolCall.toolType}`,input:JSON.stringify(ae.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:ae.thoughtSignature?pe({thoughtSignature:ae.thoughtSignature,serverToolCallId:Ue,serverToolType:ae.toolCall.toolType}):pe({serverToolCallId:Ue,serverToolType:ae.toolCall.toolType})})}else if("toolResponse"in ae&&ae.toolResponse){let Ue=be||ae.toolResponse.id||v.generateId();je.push({type:"tool-result",toolCallId:Ue,toolName:`server:${ae.toolResponse.toolType}`,result:ae.toolResponse.response??{},providerMetadata:ae.thoughtSignature?pe({thoughtSignature:ae.thoughtSignature,serverToolCallId:Ue,serverToolType:ae.toolResponse.toolType}):pe({serverToolCallId:Ue,serverToolType:ae.toolResponse.toolType})}),be=void 0}let ne=sn({groundingMetadata:ce?.groundingMetadata,generateId:v.generateId})??[];for(let ae of ne)je.push(ae);return{content:je,finishReason:{unified:Ce?"content-filter":on({finishReason:Ae,hasToolCalls:je.some((ae)=>ae.type==="tool-call"&&!ae.providerExecuted)}),raw:Ae},usage:Xt(ye),warnings:R,providerMetadata:pe({promptFeedback:x.promptFeedback??null,groundingMetadata:ce?.groundingMetadata??null,...Z!=null?{groundingMetadataPerRequest:Z}:{},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(v){let{args:x,warnings:R,providerOptionsNames:U,extraHeaders:G,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(v),Z=d(this.config.headers?await _(this.config.headers):void 0,v.headers,G),pe=(ne)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:generateContent`,headers:Z,body:ne,failedResponseHandler:Ze,successfulResponseHandler:p(In),abortSignal:v.abortSignal,fetch:this.config.fetch}),{responseHeaders:ce,value:Me,rawValue:Le}=await pe(x),Ce=[],Ae=[],je,Ne=Me.usageMetadata?.promptTokenCount,ye=!1;while(!0){let ne=Me.candidates?.[0];Ae.push(ne?.groundingMetadata??null);let ae=ne?.finishReason==="CONTINUATION"?ne.continuationToken:void 0;if(je=jt(je,Me.usageMetadata??void 0),ae==null)break;Ce.push(...f.convertGenerateContentResponse({config:this.config,response:Me,warnings:R,providerOptionsNames:U,toolNameMapping:re,jsonResponseToolName:ee}).content),ye=!0,{responseHeaders:ce,value:Me,rawValue:Le}=await pe({...x,continuationToken:ae})}let se=f.convertGenerateContentResponse({config:this.config,response:{...Me,usageMetadata:je},warnings:R,providerOptionsNames:U,toolNameMapping:re,jsonResponseToolName:ee,initialPromptTokenCount:ye?Ne:void 0,groundingMetadataPerRequest:ye?Ae:void 0}),be={...se,content:[...Ce,...se.content]};return{...be,request:{body:x},response:{...be.response,headers:ce,body:Le}}}async doStream(v){let{args:x,warnings:R,providerOptionsNames:U,extraHeaders:G,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(v,{isStreaming:!0}),Z=(He)=>Object.fromEntries(U.map((qe)=>[qe,He])),pe=d(this.config.headers?await _(this.config.headers):void 0,v.headers,G),ce=(He)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:streamGenerateContent?alt=sse`,headers:pe,body:He,failedResponseHandler:Ze,successfulResponseHandler:D(Lo),abortSignal:v.abortSignal,fetch:this.config.fetch}),{responseHeaders:Me,value:Le}=await ce(x),Ce=[],Ae=null,je=to({stream:Le,getContinuationToken:(He)=>{let qe=He.candidates?.[0];if(qe?.groundingMetadata!=null)Ae=qe.groundingMetadata;return qe?.finishReason==="CONTINUATION"?qe.continuationToken??void 0:void 0},continueStream:async(He)=>{let{value:qe}=await ce({...x,continuationToken:He});return Ce.push(Ae),Ae=null,qe}}),Ne={unified:"interrupted",raw:void 0},ye=void 0,se=void 0,be=void 0,ne=null,ae=null,Ue=null,Pe=null,$e=null,Ke=null,nt,ze=this.config.generateId,et=!1,pt=!1,Je=null,ot=null,Ve=0,rt=new Set,lt,dt,Be=[],tt=(He)=>{let qe=Be.pop();if(qe==null)return;let{finalJSON:ut,closingDelta:at}=qe.accumulator.finalize();if(at.length>0)He.enqueue({type:"tool-input-delta",id:qe.toolCallId,delta:at,providerMetadata:qe.providerMetadata});He.enqueue({type:"tool-input-end",id:qe.toolCallId,providerMetadata:qe.providerMetadata}),He.enqueue({type:"tool-call",toolCallId:qe.toolCallId,toolName:qe.toolName,input:ut,providerMetadata:qe.providerMetadata}),et=!0},Ye={stream:je.pipeThrough(new TransformStream({start(He){He.enqueue({type:"stream-start",warnings:R})},transform(He,qe){if("type"in He){Ne={unified:"interrupted",raw:void 0};return}if(v.includeRawChunks)qe.enqueue({type:"raw",rawValue:He.rawValue});if(!He.success){if(Ne.unified==="interrupted")Ne={unified:"error",raw:void 0};qe.enqueue({type:"error",error:He.error});return}let ut=He.value;if(ut.error!=null){Ne={unified:"error",raw:void 0};let Qe=ut.error;qe.enqueue({type:"error",error:xe({message:Qe.message,type:Qe.status,code:Qe.code??void 0,statusCode:Qe.code??void 0,isRetryable:Qe.code!=null&&(Qe.code===408||Qe.code===409||Qe.code===429||Qe.code>=500),data:Qe})});return}if(!pt&&ut.responseId!=null)pt=!0,qe.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)ae=st.groundingMetadata;if(st.urlContextMetadata!=null)Ue=st.urlContextMetadata;if(st.safetyRatings!=null)Pe=st.safetyRatings;if(st.finishMessage!=null)$e=st.finishMessage;if(st.continuationToken!=null)Ke=st.continuationToken}if(nt!=null||st==null)return;let wt=st.content,St=sn({groundingMetadata:st.groundingMetadata,generateId:ze});if(St!=null){for(let Qe of St)if(Qe.sourceType==="url"&&!rt.has(Qe.url))rt.add(Qe.url),qe.enqueue(Qe)}if(wt!=null){let Qe=wt.parts??[];for(let De of Qe)if("executableCode"in De&&De.executableCode?.code){let Fe=ze();lt=Fe,qe.enqueue({type:"tool-call",toolCallId:Fe,toolName:re.toCustomToolName("code_execution"),input:JSON.stringify(De.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in De&&De.codeExecutionResult){let Fe=lt;if(Fe)qe.enqueue({type:"tool-result",toolCallId:Fe,toolName:re.toCustomToolName("code_execution"),result:{outcome:De.codeExecutionResult.outcome,output:De.codeExecutionResult.output??""}})}else if("text"in De&&De.text!=null){let Fe=De.thoughtSignature?Z({thoughtSignature:De.thoughtSignature}):void 0;if(De.text.length===0){if(Fe!=null&&Je!==null)qe.enqueue({type:"text-delta",id:Je,delta:"",providerMetadata:Fe})}else if(De.thought===!0){if(Je!==null)qe.enqueue({type:"text-end",id:Je}),Je=null;if(ot===null)ot=String(Ve++),qe.enqueue({type:"reasoning-start",id:ot,providerMetadata:Fe});qe.enqueue({type:"reasoning-delta",id:ot,delta:De.text,providerMetadata:Fe})}else{if(ot!==null)qe.enqueue({type:"reasoning-end",id:ot}),ot=null;if(Je===null)Je=String(Ve++),qe.enqueue({type:"text-start",id:Je,providerMetadata:Fe});qe.enqueue({type:"text-delta",id:Je,delta:De.text,providerMetadata:Fe})}}else if("inlineData"in De){if(Je!==null)qe.enqueue({type:"text-end",id:Je}),Je=null;if(ot!==null)qe.enqueue({type:"reasoning-end",id:ot}),ot=null;let Fe=De.thought===!0,yt=De.thoughtSignature?Z({thoughtSignature:De.thoughtSignature}):void 0;qe.enqueue({type:Fe?"reasoning-file":"file",mediaType:De.inlineData.mimeType,data:{type:"data",data:De.inlineData.data},providerMetadata:yt})}else if("toolCall"in De&&De.toolCall){let Fe=De.toolCall.id||ze();dt=Fe;let yt=Z({...De.thoughtSignature?{thoughtSignature:De.thoughtSignature}:{},serverToolCallId:Fe,serverToolType:De.toolCall.toolType});qe.enqueue({type:"tool-call",toolCallId:Fe,toolName:`server:${De.toolCall.toolType}`,input:JSON.stringify(De.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:yt})}else if("toolResponse"in De&&De.toolResponse){let Fe=dt||De.toolResponse.id||ze(),yt=Z({...De.thoughtSignature?{thoughtSignature:De.thoughtSignature}:{},serverToolCallId:Fe,serverToolType:De.toolResponse.toolType});qe.enqueue({type:"tool-result",toolCallId:Fe,toolName:`server:${De.toolResponse.toolType}`,result:De.toolResponse.response??{},providerMetadata:yt}),dt=void 0}for(let De of Qe){if(!("functionCall"in De))continue;let Fe=De.thoughtSignature?Z({thoughtSignature:De.thoughtSignature}):void 0,yt=De.functionCall.partialArgs!=null||De.functionCall.name!=null&&De.functionCall.willContinue===!0,Hn=De.functionCall.name==null&&De.functionCall.args==null&&De.functionCall.partialArgs==null&&De.functionCall.willContinue==null,Vn=De.functionCall.name!=null&&De.functionCall.args!=null&&De.functionCall.partialArgs==null,Wn=De.functionCall.name!=null&&De.functionCall.args==null&&De.functionCall.partialArgs==null&&De.functionCall.willContinue!==!0;if(yt){if(De.functionCall.name!=null){let ct=De.functionCall.id||ze(),gt=new vo;if(Be.push({toolCallId:ct,toolName:De.functionCall.name,accumulator:gt,providerMetadata:Fe}),qe.enqueue({type:"tool-input-start",id:ct,toolName:De.functionCall.name,providerMetadata:Fe}),De.functionCall.partialArgs!=null){let ft=De.functionCall.partialArgs,{textDelta:It}=gt.processPartialArgs(ft);if(It.length>0)qe.enqueue({type:"tool-input-delta",id:ct,delta:It,providerMetadata:Fe});if(De.functionCall.willContinue!==!0&&ft.every((Kn)=>Kn.willContinue!==!0))tt(qe)}}else if(De.functionCall.partialArgs!=null&&Be.length>0){let ct=Be[Be.length-1],gt=De.functionCall.partialArgs,{textDelta:ft}=ct.accumulator.processPartialArgs(gt);if(ft.length>0)qe.enqueue({type:"tool-input-delta",id:ct.toolCallId,delta:ft,providerMetadata:Fe});if(De.functionCall.willContinue!==!0&&gt.every((It)=>It.willContinue!==!0))tt(qe)}}else if(Hn&&Be.length>0)tt(qe);else if(Vn){let ct=De.functionCall.id||ze(),gt=De.functionCall.name,ft=typeof De.functionCall.args==="string"?De.functionCall.args:JSON.stringify(De.functionCall.args??{});qe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:Fe}),qe.enqueue({type:"tool-input-delta",id:ct,delta:ft,providerMetadata:Fe}),qe.enqueue({type:"tool-input-end",id:ct,providerMetadata:Fe}),qe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:ft,providerMetadata:Fe}),et=!0}else if(Wn){let ct=De.functionCall.id||ze(),gt=De.functionCall.name;qe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:Fe}),qe.enqueue({type:"tool-input-end",id:ct,providerMetadata:Fe}),qe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:"{}",providerMetadata:Fe}),et=!0}}}if(st.finishReason==="CONTINUATION"){if(se==null)be=ye?.promptTokenCount;se=jt(se,ye),ye=void 0}if(st.finishReason!=null)Ne={unified:on({finishReason:st.finishReason,hasToolCalls:et}),raw:st.finishReason}},flush(He){if(ye=jt(se,ye),Je!==null)He.enqueue({type:"text-end",id:Je});if(ot!==null)He.enqueue({type:"reasoning-end",id:ot});He.enqueue({type:"finish",finishReason:Ne,usage:Xt(ye),providerMetadata:Z({promptFeedback:ne,groundingMetadata:ae,...Ce.length>0?{groundingMetadataPerRequest:[...Ce,Ae]}:{},urlContextMetadata:Ue,safetyRatings:Pe,usageMetadata:ye??null,finishMessage:$e,serviceTier:ye?.serviceTier??null,...Ke!=null&&(Ne.raw==="MAX_TOKENS"||Ne.raw==="CONTINUATION")?{continuationToken:Ke}:{},...be!=null?{initialPromptTokenCount:be}:{}})})}})),response:{headers:Me},request:{body:x}};return{...Ye,stream:ee==null?Ye.stream:Ye.stream.pipeThrough(Jt(ee))}}};function ko(){return 65536}function xo(f){let v=f.toLowerCase();if(v.includes("2.5-pro")||v.includes("gemini-3-pro-image"))return 32768;return 24576}function Ro({reasoning:f,modelId:v,warnings:x}){if(!H(f))return;if(At(v).usesGemini3Features&&!v.includes("gemini-3-pro-image"))return Oo({reasoning:f,modelId:v,warnings:x});return Eo({reasoning:f,modelId:v,warnings:x})}function Oo({reasoning:f,modelId:v,warnings:x}){let R=Mo(v);if(f==="none")return{thinkingLevel:R};let U=ke({reasoning:f,effortMap:{minimal:R,low:"low",medium:"medium",high:"high",xhigh:"high",max:"high"},warnings:x});if(U==null)return;return{thinkingLevel:U}}function Mo(f){let v=/(?:^|[/.])(gemini-[^/]*)$/i.exec(f)?.[1].toLowerCase();if(v==="gemini-flash-latest")return"low";let x=/^gemini-(\d+)(?:\.\d+)?-pro(?:$|-)/.exec(v??"");if(Number(x?.[1])>=3)return"low";let R=/^gemini-(\d+)\.(\d+)-flash(?:$|-(?!lite(?:-|$)))/.exec(v??"");if(R==null)return"minimal";let U=Number(R[1]),G=Number(R[2]);return U>3||U===3&&G>=7?"low":"minimal"}function Eo({reasoning:f,modelId:v,warnings:x}){if(f==="none")return{thinkingBudget:0};let R=it({reasoning:f,maxOutputTokens:ko(),maxReasoningBudget:xo(v),minReasoningBudget:0,warnings:x});if(R==null)return;return{thinkingBudget:R}}function sn({groundingMetadata:f,generateId:v}){if(!f?.groundingChunks)return;let x=[];for(let R of f.groundingChunks)if(R.web!=null)x.push({type:"source",sourceType:"url",id:v(),url:R.web.uri,title:R.web.title??void 0});else if(R.image!=null)x.push({type:"source",sourceType:"url",id:v(),url:R.image.sourceUri,title:R.image.title??void 0});else if(R.retrievedContext!=null){let U=R.retrievedContext.uri,G=R.retrievedContext.fileSearchStore;if(U&&(U.startsWith("http://")||U.startsWith("https://")))x.push({type:"source",sourceType:"url",id:v(),url:U,title:R.retrievedContext.title??void 0});else if(U){let re=R.retrievedContext.title??"Unknown Document",ee="application/octet-stream",Z=void 0;if(U.endsWith(".pdf"))ee="application/pdf",Z=U.split("/").pop();else if(U.endsWith(".txt"))ee="text/plain",Z=U.split("/").pop();else if(U.endsWith(".docx"))ee="application/vnd.openxmlformats-officedocument.wordprocessingml.document",Z=U.split("/").pop();else if(U.endsWith(".doc"))ee="application/msword",Z=U.split("/").pop();else if(U.match(/\.(md|markdown)$/))ee="text/markdown",Z=U.split("/").pop();else Z=U.split("/").pop();x.push({type:"source",sourceType:"document",id:v(),mediaType:ee,title:re,filename:Z})}else if(G){let re=R.retrievedContext.title??"Unknown Document";x.push({type:"source",sourceType:"document",id:v(),mediaType:"application/octet-stream",title:re,filename:G.split("/").pop()})}}else if(R.maps!=null){if(R.maps.uri)x.push({type:"source",sourceType:"url",id:v(),url:R.maps.uri,title:R.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:w().nullish(),willContinue:c().nullish()}),Cn=()=>t({parts:o(l([t({functionCall:t({id:e().nullish(),name:e().nullish(),args:w().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:w().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({toolResponse:t({toolType:e(),response:w().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=i(()=>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=i(()=>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=()=>B({searchTypes:t({webSearch:t({}).optional(),imageSearch:t({}).optional()}).optional(),timeRangeFilter:t({startTime:e(),endTime:e()}).optional()}),Uo=k({id:"google.google_search",inputSchema:i(()=>s(t({}))),outputSchema:i(()=>s(t({})))}),kn=i(()=>s(t({googleSearch:jo().optional()}))),No=2147483648,Go=20000000,Do=new Set(["text","reasoning","source","tool-call","tool-result"]);function Po(f){for(let v of f){let x=v.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:w().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=i(()=>s(xn())),$o=i(()=>s(t({operations:o(xn()).nullish(),nextPageToken:e().nullish()}))),Fo=i(()=>s(t({}))),Bo=i(()=>s(t({file:t({name:e(),expirationTime:e().nullish()})}))),Ho=i(()=>s(t({key:e(),response:w().nullish(),error:Bt().nullish()}))),Vo=i(()=>s(t({candidates:o(w()).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 v=Yo(f.requests),x=[],R=`ai-sdk-batch-${this.batchGenerateId()}`,U=[],G={batch:{displayName:R,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{requests:{requests:U}}}},re=new TextEncoder,ee=re.encode(JSON.stringify(G)).byteLength,Z;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(Z==null){let se=re.encode(JSON.stringify(ye)).byteLength,be=ee+se+(U.length>0?1:0);if(be<Go)U.push(ye),ee=be;else{Z=[];for(let ne of U)Z.push(JSON.stringify({key:ne.metadata.key,request:ne.request}),`
7
- `);U.length=0,Z.push(JSON.stringify({key:je.id,request:Ne.args}),`
8
- `)}}else Z.push(JSON.stringify({key:je.id,request:Ne.args}),`
9
- `);for(let se of Ne.warnings)x.push({requestId:je.id,warning:se})}let pe=await this.getHeaders(f.headers),ce=`${this.batchConfig.baseURL}/${Tt(v)}:batchGenerateContent`;if(Z==null){let{value:je}=await g({url:ce,headers:pe,body:G,failedResponseHandler:Ze,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch});return{batchId:je.name,..._t(je),warnings:x}}let Me=new Blob(Z,{type:"application/jsonl"});if(Z.length=0,Me.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(Me.size),"X-Goog-Upload-Header-Content-Type":"application/jsonl"}),body:{file:{display_name:`${R}-input`}},failedResponseHandler:Ze,successfulResponseHandler:Jo,abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{value:Ce}=await we({url:Le,headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize","Content-Type":"application/jsonl"},body:{content:Me,values:{byteLength:Me.size,mediaType:"application/jsonl"}},failedResponseHandler:Ze,successfulResponseHandler:p(Bo),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{value:Ae}=await g({url:ce,headers:pe,body:{batch:{displayName:R,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{fileName:Ce.file.name}}},failedResponseHandler:Ze,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch});return{batchId:Ae.name,..._t(Ae),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:Ze,successfulResponseHandler:p(Fo),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{}}async doListBatches(f){let v=new URL(`${this.batchConfig.baseURL}/batches`);if(f.limit!=null)v.searchParams.set("pageSize",String(f.limit));if(f.cursor!=null)v.searchParams.set("pageToken",f.cursor);let{value:x}=await P({url:v.toString(),headers:await this.getHeaders(f.headers),failedResponseHandler:Ze,successfulResponseHandler:p($o),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return{batches:(x.operations??[]).map((R)=>({batchId:R.name,..._t(R)})),...x.nextPageToken!=null?{nextCursor:x.nextPageToken}:{}}}async doGetBatchResults(f){let v=await this.retrieveBatch(f),x=_t(v);if(x.status==="pending")throw new b({argument:"batchId",message:`Google batch "${f.batchId}" is not complete.`});let R=v.metadata?.output?.inlinedResponses?.inlinedResponses??v.response?.inlinedResponses?.inlinedResponses;if(R!=null)return ie(this.iterateBatchResults(R.map((ee)=>({key:ee.metadata.key,response:ee.response,error:ee.error}))));let U=v.metadata?.output?.responsesFile??v.response?.responsesFile;if(U==null){if(x.status==="completed")throw new A({data:v,message:`Google batch "${f.batchId}" completed without batch output.`});return new ReadableStream({start(ee){ee.close()}})}let G=U.split("/").map((ee)=>encodeURIComponent(ee)).join("/"),{value:re}=await P({url:`${this.getBaseOrigin()}/download/v1beta/${G}:download?alt=media`,headers:await this.getHeaders(f.headers),failedResponseHandler:Ze,successfulResponseHandler:_e(Ho,{maxLineBytes:this.maxLineBytes}),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return ie(this.iterateBatchResults(re))}async retrieveBatch(f){let{value:v}=await P({url:`${this.batchConfig.baseURL}/${f.batchId}`,headers:await this.getHeaders(f.headers),failedResponseHandler:Ze,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return v}async*iterateBatchResults(f){for await(let v of f){if(v.error!=null){let ee=Rn(v.error,"Google batch request failed."),Z=v.error.status==="CANCELLED"||String(v.error.code)==="1"?"cancelled":"failed";yield{type:"text",id:v.key,status:Z,error:ee};continue}if(v.response==null){yield{type:"text",id:v.key,status:"failed",error:{message:"Google returned a batch result without a response or error.",code:"invalid_batch_result"}};continue}let x=await N({value:v.response,schema:Vo});if(x.success&&(x.value.candidates==null||x.value.candidates.length===0)){let ee=x.value.promptFeedback??void 0,Z=ee?.blockReason??void 0;yield{type:"text",id:v.key,status:"failed",error:{message:Z==null?"Google returned a batch response without any candidates.":`Google blocked the batch request (${Z}).`,code:Z==null?"invalid_response":"prompt_blocked",...Z!=null?{type:Z}:{}},...ee!=null?{providerMetadata:{google:{promptFeedback:{blockReason:ee.blockReason??null}}}}:{}};continue}let R=await N({value:v.response,schema:In});if(!R.success){yield{type:"text",id:v.key,status:"failed",error:{message:"Google returned an invalid GenerateContent batch result.",code:"invalid_response"}};continue}let U=Ct.convertGenerateContentResponse({config:this.batchConfig,response:R.value,warnings:[],providerOptionsNames:["google"]}),G=Xo(U);if(G!=null){yield{type:"image",id:v.key,status:"succeeded",result:G};continue}let re=U.content.find((ee)=>!Do.has(ee.type));if(re!=null){yield{type:"text",id:v.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:v.key,status:"succeeded",result:U}}}async prepareImageRequest(f){let{prompt:v,n:x,size:R,aspectRatio:U,seed:G,files:re,mask:ee,providerOptions:Z}=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(R!=null)pe.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let ce=[];if(v!=null)ce.push({type:"text",text:v});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 Me=await h({provider:"google",providerOptions:Z,schema:kn}),{responseModalities:Le,imageConfig:Ce,...Ae}=await h({provider:"google",providerOptions:Z,schema:Et})??{},je=await h({provider:"google",providerOptions:{google:{...Ae,responseModalities:["IMAGE"],imageConfig:U!=null||Ce!=null?{...Ce,...U!=null?{aspectRatio:U}:{}}:void 0}},schema:Et}),Ne=await Ct.prepareRequest({modelId:f.modelId,config:this.batchConfig,options:{prompt:[{role:"user",content:ce}],seed:G,providerOptions:{google:je??{responseModalities:["IMAGE"]}},tools:Me?.googleSearch!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Me.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 v=f.metadata?.state??void 0,x=zo(f.metadata?.batchStats),R=f.metadata?.createTime??void 0,U=f.error!=null?Rn(f.error,"Google batch failed."):void 0;return{status:Ko({rawStatus:v,done:f.done??void 0,hasError:U!=null}),...v!=null?{rawStatus:v}:{},...x!=null?{requestCounts:x}:{},...U!=null?{error:U}:{},...R!=null?{createdAt:R}:{}}}function Ko({rawStatus:f,done:v,hasError:x}){if(x)return"failed";if(f==null)return v?"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 v=Rt(f?.requestCount),x=Rt(f?.successfulRequestCount??0),R=Rt(f?.failedRequestCount??0),U=Rt(f?.pendingRequestCount??0);return ge({total:v,pending:U,completed:x,failed:R})}function Rt(f){let v=typeof f==="string"&&/^\d+$/.test(f)?Number(f):f;return typeof v==="number"&&Number.isSafeInteger(v)&&v>=0?v:void 0}function Rn(f,v){return{message:f.message??v,...f.status!=null?{type:f.status}:{},...f.code!=null?{code:String(f.code)}:{}}}var Jo=async({response:f})=>{let v=f.headers.get("x-goog-upload-url");if(v==null)throw new A({data:f.headers,message:"Google did not return a resumable upload URL."});return{value:v}};function Yo(f){let v=f[0]?.modelId;if(v==null)throw new b({argument:"requests",message:"Google batches require at least one request."});for(let x of f)if(x.modelId!==v)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 v}function Xo(f){let v=f.content.flatMap((R)=>R.type==="file"&&R.mediaType.startsWith("image/")&&R.data.type==="data"?[T(R.data.data)]:[]);if(v.length===0)return;let x=f.providerMetadata?.google??{};return{images:v,warnings:f.warnings,providerMetadata:{google:{...x,images:v.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=k({id:"google.enterprise_web_search",inputSchema:i(()=>s(t({}))),outputSchema:i(()=>s(t({})))});i(()=>s(B({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=k({id:"google.file_search",inputSchema:i(()=>s(t({}))),outputSchema:i(()=>s(t({})))}),ei={googleSearch:Uo,enterpriseWebSearch:Qo,googleMaps:k({id:"google.google_maps",inputSchema:i(()=>s(t({}))),outputSchema:i(()=>s(t({})))}),urlContext:k({id:"google.url_context",inputSchema:i(()=>s(t({}))),outputSchema:i(()=>s(t({})))}),fileSearch:Zo,codeExecution:no,vertexRagStore:k({id:"google.vertex_rag_store",inputSchema:i(()=>s(t({}))),outputSchema:i(()=>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[S](v){return M({modelId:v.modelId,config:v.config})}static[I](v){return new f(v.modelId,{},v.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(v,x,R){this.modelId=v,this.settings=x,this.config=R,this.specificationVersion="v4"}async doGenerate(v){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:R,aspectRatio:U,seed:G,providerOptions:re,headers:ee,abortSignal:Z,files:pe,mask:ce}=v,Me=[];if(ce!=null)throw Error("Gemini image models do not support mask-based image editing.");if(R!=null)Me.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 Pe of pe)if(Pe.type==="url")Le.push({type:"file",data:{type:"url",url:new URL(Pe.url)},mediaType:"image/*"});else Le.push({type:"file",data:{type:"data",data:typeof Pe.data==="string"?Pe.data:new Uint8Array(Pe.data)},mediaType:Pe.mediaType});let Ce=[{role:"user",content:Le}],Ae=await h({provider:"google",providerOptions:re,schema:kn}),{googleSearch:je,responseModalities:Ne,imageConfig:ye,...se}=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:G,providerOptions:{google:{...se,responseModalities:["IMAGE"],imageConfig:U!=null||ye!=null?{...ye,...U!=null?{aspectRatio:U}:{}}:void 0}},tools:Ae?.googleSearch!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Ae.googleSearch}]:void 0,headers:ee,abortSignal:Z}),ne=this.config._internal?.currentDate?.()??new Date,ae=[];for(let Pe of be.content)if(Pe.type==="file"&&Pe.mediaType.startsWith("image/")&&Pe.data.type==="data")ae.push(T(Pe.data.data));let Ue=be.providerMetadata?.google??{};return{images:ae,...be.finishReason.unified==="content-filter"?{isRetryable:!1}:{},warnings:Me,providerMetadata:{google:{...Ue,finishReason:be.finishReason.raw??null,images:ae.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 v=await h({provider:"google",providerOptions:f.providerOptions,schema:ai}),x=d(this.config.headers(),f.headers),R=this.config.fetch??globalThis.fetch,U=[];if(f.filename!=null)U.push({type:"unsupported",feature:"filename"});let G=ve(f.data),re=f.mediaType,ee=v?.displayName,Z=await R(`${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(G.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(!Z.ok){let je=await Z.text();throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to initiate resumable upload: ${Z.status} ${je}`})}let pe=Z.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 R(pe,{method:"POST",headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"},body:ii(G),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 Me=(await ce.json()).file,Le=v?.pollIntervalMs??2000,Ce=v?.pollTimeoutMs??300000,Ae=Date.now();while(Me.state==="PROCESSING"){if(Date.now()-Ae>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(Me.name),Ne=je!=null?`files/${de(je[1])}`:de(Me.name),{value:ye}=await P({url:`${this.config.baseURL}/${Ne}`,validateUrl:!1,headers:d(x),successfulResponseHandler:p(si),failedResponseHandler:Ze,abortSignal:f.abortSignal,fetch:this.config.fetch});Me=ye}if(Me.state==="FAILED")throw new m({name:"GOOGLE_FILES_UPLOAD_FAILED",message:`File processing failed for ${Me.name}`});return{warnings:U,providerReference:{google:Me.uri},mediaType:Me.mimeType??f.mediaType,providerMetadata:{google:{name:Me.name,displayName:Me.displayName,mimeType:Me.mimeType,sizeBytes:Me.sizeBytes,state:Me.state,uri:Me.uri,...Me.createTime!=null?{createTime:Me.createTime}:{},...Me.updateTime!=null?{updateTime:Me.updateTime}:{},...Me.expirationTime!=null?{expirationTime:Me.expirationTime}:{},...Me.sha256Hash!=null?{sha256Hash:Me.sha256Hash}:{}}}}}};function ii(f){if(f.buffer instanceof ArrayBuffer)return f;return new Uint8Array(f)}var si=i(()=>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=i(()=>s(B({displayName:e().nullish(),pollIntervalMs:r().positive().nullish(),pollTimeoutMs:r().positive().nullish()}))),ri=i(()=>s(B({pollIntervalMs:r().positive().nullish(),pollTimeoutMs:r().positive().nullish(),personGeneration:a(["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((v)=>v.frameType==="first_frame")?.image}function ui(f){return li(f)??f.image}function ci(f){return f.frameImages?.find((v)=>v.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,v){if(f.type==="url"){if(f.url.startsWith("gs://"))return{gcsUri:f.url,mimeType:"image/png"};v.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,v){let x=Dt(f,v);return x!=null?{image:x,referenceType:"asset"}:void 0}var hi=class{get provider(){return this.config.provider}get maxVideosPerCall(){return 4}constructor(f,v){this.modelId=f,this.config=v,this.specificationVersion="v4"}async buildRequest(f){let v=[],x=await h({provider:"google",providerOptions:f.providerOptions,schema:ri}),R=[{}],U=R[0];if(f.prompt!=null)U.prompt=f.prompt;let G=ui(f);if(G!=null){let pe=Dt(G,v);if(pe!=null)U.image=pe}let re=ci(f);if(re!=null){let pe=Dt(re,v);if(pe!=null)U.lastFrame=pe}let ee=di(f);if(ee!=null)U.referenceImages=ee.flatMap((pe)=>{let ce=gi(pe,v);return ce!=null?[ce]:[]});else if(x?.referenceImages!=null)U.referenceImages=x.referenceImages.map((pe)=>pi(pe));let Z={sampleCount:f.n};if(f.aspectRatio)Z.aspectRatio=f.aspectRatio;if(f.resolution)Z.resolution={"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"}[f.resolution]||f.resolution;if(f.duration)Z.durationSeconds=f.duration;if(f.seed)Z.seed=f.seed;if(x!=null){let pe=x;if(pe.personGeneration!==void 0&&pe.personGeneration!==null)Z.personGeneration=pe.personGeneration;if(pe.negativePrompt!==void 0&&pe.negativePrompt!==null)Z.negativePrompt=pe.negativePrompt;for(let[ce,Me]of Object.entries(pe))if(!["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","referenceImages"].includes(ce))Z[ce]=Me}return{instances:R,parameters:Z,warnings:v,googleOptions:x}}async buildCompletedResult(f,v,x,R){let U=f.response;if(!U?.generateVideoResponse?.generatedSamples||U.generateVideoResponse.generatedSamples.length===0)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:`No videos in response. Response: ${JSON.stringify(f)}`});let G=[],re=[],ee=(await _(this.config.headers))?.["x-goog-api-key"];for(let Z of U.generateVideoResponse.generatedSamples)if(Z.video?.uri){let pe=ee&&Ge(Z.video.uri,this.config.baseURL)?`${Z.video.uri}${Z.video.uri.includes("?")?"&":"?"}key=${ee}`:Z.video.uri;G.push({type:"url",url:pe,mediaType:"video/mp4"}),re.push({uri:Z.video.uri})}if(G.length===0)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{status:"completed",videos:G,warnings:x,response:{timestamp:R,modelId:this.modelId,headers:v},providerMetadata:{google:{videos:re}}}}async doStart(f){let v=this.config._internal?.currentDate?.()??new Date,{instances:x,parameters:R,warnings:U}=await this.buildRequest(f),{value:G,responseHeaders:re}=await g({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:d(await _(this.config.headers),f.headers),body:{instances:x,parameters:R},successfulResponseHandler:p(ln),failedResponseHandler:Ze,abortSignal:f.abortSignal,fetch:this.config.fetch}),ee=G.name;if(!ee)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No operation name returned from API"});return{operation:{operationName:ee},warnings:U,response:{timestamp:v,modelId:this.modelId,headers:re}}}async doStatus(f){let v=this.config._internal?.currentDate?.()??new Date,{operationName:x}=f.operation,{value:R,responseHeaders:U}=await P({url:`${this.config.baseURL}/${x}`,validateUrl:!1,headers:d(await _(this.config.headers),f.headers),successfulResponseHandler:p(ln),failedResponseHandler:Ze,abortSignal:f.abortSignal,fetch:this.config.fetch});if(!R.done)return{status:"pending",response:{timestamp:v,modelId:this.modelId,headers:U}};if(R.error)return{status:"error",error:`Video generation failed: ${R.error.message}`,response:{timestamp:v,modelId:this.modelId,headers:U}};return this.buildCompletedResult(R,U,[],v)}},ln=i(()=>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=i(()=>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(),F()).nullish()})));function fi({text:f,voice:v,providerOptions:x}){let R=x?.google,U=R!=null&&typeof R==="object"?R:void 0,G=U&&"turns"in U?U.turns:void 0,re=[];if(Array.isArray(G)&&G.length>0){for(let pe of G){if(pe==null||typeof pe!=="object"||!("text"in pe)||typeof pe.text!=="string")break;re.push(pe.text)}if(re.length===G.length)f=re.join("")}let ee=U&&"multiSpeakerVoiceConfig"in U?U.multiSpeakerVoiceConfig:void 0,Z=ee!=null&&typeof ee==="object"&&"speakerVoiceConfigs"in ee&&Array.isArray(ee.speakerVoiceConfigs)?ee.speakerVoiceConfigs:[];return{text:f,usesCustomVoice:v?.startsWith("voice_")===!0||v?.startsWith("voicekey_")===!0||Z.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:Re().optional()}),un=()=>t({speaker:e().min(1).optional(),style:e().optional()}),cn=i(()=>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[S](v){return M({modelId:v.modelId,config:v.config})}static[I](v){return new f(v.modelId,v.config)}get provider(){return this.config.provider}constructor(v,x){this.modelId=v,this.config=x,this.specificationVersion="v4"}async getArgs({text:v,voice:x=bi,outputFormat:R,instructions:U,speed:G,language:re,providerOptions:ee}){let Z=[],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 Me=!this.modelId.startsWith("gemini-2.5-")&&!this.modelId.startsWith("gemini-3.1-"),Le=fi({text:v,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,Ae=Ce?{multiSpeakerVoiceConfig:Ce}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:x}}},je=v;if(U!=null&&!Me)if(Ce)Z.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=`${U}: ${v}`;let Ne=[{text:je}];if(Me){if(ce?.turns&&ce.speechMetadata)throw new b({argument:"providerOptions",message:"Set speechMetadata on each turn when using turns."});if(ce?.turns&&v!=="")Z.push({type:"unsupported",feature:"text",details:"Google TTS turns replace the top-level text."});Ne=(ce?.turns??[{text:v,speechMetadata:ce?.speechMetadata}]).map((be)=>{let ne=be.speechMetadata?.style??U,ae=be.speechMetadata?.speaker;if(Ce&&!Ce.speakerVoiceConfigs.some((Ue)=>Ue.speaker===ae))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||ae!=null?{speechMetadata:{style:ne,speaker:ae}}:{}}})}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(G!=null)Z.push({type:"unsupported",feature:"speed",details:"Google Gemini TTS models do not support the `speed` option. It was ignored."});if(re!=null)Z.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=Me?{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"},se="wav";if(R!=null&&Object.prototype.hasOwnProperty.call(ye,R))se=R;else if(R!=null)Z.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${R}. Using wav instead.`});return{requestBody:{contents:[{role:"user",parts:Ne}],generationConfig:{responseModalities:["AUDIO"],speechConfig:Ae,...Me&&R!=null?{responseFormat:{audio:{mimeType:ye[se]}}}:{}}},warnings:Z,outputFormat:ye[se],usesStructuredSpeech:Me}}async doGenerate(v){let x=this.config._internal?.currentDate?.()??new Date,{requestBody:R,warnings:U,outputFormat:G,usesStructuredSpeech:re}=await this.getArgs(v),{value:ee,responseHeaders:Z,rawValue:pe}=await g({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:d(this.config.headers?await _(this.config.headers):void 0,v.headers),body:R,failedResponseHandler:Ze,successfulResponseHandler:p(mi),abortSignal:v.abortSignal,fetch:this.config.fetch}),ce,Me;for(let Ne of ee.candidates??[]){for(let ye of Ne.content?.parts??[])if(ye.inlineData?.data){ce=ye.inlineData.data,Me=ye.inlineData.mimeType??void 0;break}if(ce!=null)break}let Le=Ci(Me)??Ti,Ce=ce!=null?q(ce):new Uint8Array(0),Ae=/^audio\/(?:l16|pcm)(?:;|$)/i.test(Me??"")||Me==null&&!re,je=G==="AUDIO_WAV"&&Ae&&Ce.length>0?wi(Ce,Le):Ce;if(G==="AUDIO_L16"&&Ce.length>0&&!re)U.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:U,...ee.usageMetadata!=null&&{usage:ee.usageMetadata},request:{body:JSON.stringify(R)},response:{timestamp:x,modelId:this.modelId,headers:Z,body:pe},providerMetadata:{google:{sampleRate:Le,mimeType:Me??null}}}}};function Ci(f){if(f==null)return;let v=/rate=(\d+)/.exec(f);return v?Number.parseInt(v[1],10):void 0}function wi(f,v){let G=v*2,re=f.length,ee=new ArrayBuffer(44+re),Z=new DataView(ee);Ot(Z,0,"RIFF"),Z.setUint32(4,36+re,!0),Ot(Z,8,"WAVE"),Ot(Z,12,"fmt "),Z.setUint32(16,16,!0),Z.setUint16(20,1,!0),Z.setUint16(22,1,!0),Z.setUint32(24,v,!0),Z.setUint32(28,G,!0),Z.setUint16(32,2,!0),Z.setUint16(34,16,!0),Ot(Z,36,"data"),Z.setUint32(40,re,!0);let pe=new Uint8Array(ee);return pe.set(f,44),pe}function Ot(f,v,x){for(let R=0;R<x.length;R++)f.setUint8(v+R,x.charCodeAt(R))}function Ht(f){if(f==null)return te();let v=f.total_input_tokens??0,x=f.total_output_tokens??0,R=f.total_thought_tokens??0,U=f.total_cached_tokens??0;return{inputTokens:{total:f.total_input_tokens??void 0,noCache:f.total_input_tokens==null?void 0:v-U,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+R,text:f.total_output_tokens??void 0,reasoning:f.total_thought_tokens??void 0},raw:f}}function On(f){let v=f?.output_tokens_by_modality;if(v==null)return;let x={};for(let R of v)if(R?.modality!=null&&R.tokens!=null)x[R.modality]=R.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 v=f.toLowerCase();for(let[x,R]of Object.entries(Si))if(v.endsWith(`.${x}`))return R;return"application/octet-stream"}function En(f){let v=f.split("/"),x=v[v.length-1];return x&&x.length>0?x:void 0}function Ii({annotation:f,generateId:v}){switch(f.type){case"url_citation":{let x=f;if(x.url==null||x.url.length===0)return;return{type:"source",sourceType:"url",id:v(),url:x.url,...x.title!=null?{title:x.title}:{}}}case"file_citation":{let x=f,R=x.url??x.document_uri??x.file_name;if(R==null||R.length===0)return;if(R.startsWith("http://")||R.startsWith("https://"))return{type:"source",sourceType:"url",id:v(),url:R,...x.file_name!=null?{title:x.file_name}:{}};let U=x.file_name??En(R),G=Mn(R);return{type:"source",sourceType:"document",id:v(),mediaType:G,title:x.file_name??U??R,...U!=null?{filename:U}:{}}}case"place_citation":{let x=f;if(x.url==null||x.url.length===0)return;return{type:"source",sourceType:"url",id:v(),url:x.url,...x.name!=null?{title:x.name}:{}}}default:return}}function An({block:f,generateId:v}){let x=[];switch(f.type){case"url_context_result":{let R=f.result??[];for(let U of R){if(U?.url==null||U.url.length===0)continue;if(U.status!=null&&U.status!=="success")continue;x.push({type:"source",sourceType:"url",id:v(),url:U.url})}break}case"google_search_result":{let R=f.result??[];for(let U of R){let G=U?.url;if(G==null||G.length===0)continue;x.push({type:"source",sourceType:"url",id:v(),url:G,...U.title!=null?{title:U.title}:{}})}break}case"google_maps_result":{let R=f.result??[];for(let U of R)for(let G of U.places??[]){if(G.url==null||G.url.length===0)continue;x.push({type:"source",sourceType:"url",id:v(),url:G.url,...G.name!=null?{title:G.name}:{}})}break}case"file_search_result":{let R=f.result??[];for(let U of R){if(U==null||typeof U!=="object")continue;let G=U,re=G.url??G.document_uri??G.file_name;if(re==null||re.length===0)continue;if(re.startsWith("http://")||re.startsWith("https://")){x.push({type:"source",sourceType:"url",id:v(),url:re,...G.title!=null?{title:G.title}:{}});continue}let ee=G.file_name??En(re),Z=Mn(re);x.push({type:"source",sourceType:"document",id:v(),mediaType:Z,title:G.title??G.file_name??ee??re,...ee!=null?{filename:ee}:{}})}break}}return x}function Pt({annotations:f,generateId:v}){if(f==null)return[];let x=new Set,R=[];for(let U of f){let G=Ii({annotation:U,generateId:v});if(G==null)continue;let re=G.sourceType==="url"?`url:${G.url}`:`doc:${G.filename??G.title}`;if(x.has(re))continue;x.add(re),R.push(G)}return R}function Vt({status:f,hasFunctionCall:v}){switch(f){case"completed":return v?"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:v,includeRawChunks:x,serviceTier:R}){let U,G,re=R,ee,Z=!1,pe=!1,ce=new Map,Me=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,Ae){if(x)Ae.enqueue({type:"raw",rawValue:Ce.rawValue});if(!Ce.success){ee="failed",Ae.enqueue({type:"error",error:Ce.error});return}let je=Ce.value,Ne=je.event_type;switch(Ne){case"interaction.created":{let ye=je.interaction;U=ye?.id!=null&&ye.id.length>0?ye.id:void 0;let se=ye?.created,be;if(typeof se==="string"){let ne=new Date(se);if(!Number.isNaN(ne.getTime()))be=ne}Ae.enqueue({type:"response-metadata",...U!=null?{id:U}:{},modelId:ye?.model,...be?{timestamp:be}:{}});break}case"step.start":{let ye=je,{step:se,index:be}=ye,ne=`${U??"interaction"}:${be}`,ae=se?.type;if(ae==="model_output"){let Ue=se?.content?.[0];if(Ue?.type==="text"){ce.set(be,{kind:"text",id:ne,emittedSourceKeys:new Set}),Ae.enqueue({type:"text-start",id:ne});let Pe=Pt({annotations:Ue.annotations,generateId:v});for(let $e of Pe){let Ke=Le($e);if(Me.has(Ke))continue;Me.add(Ke),Ae.enqueue($e)}}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(ae==="thought"){let Ue=se?.signature;if(ce.set(be,{kind:"reasoning",id:ne,...Ue!=null?{signature:Ue}:{}}),Ae.enqueue({type:"reasoning-start",id:ne}),Array.isArray(se?.summary)){for(let Pe of se.summary)if(Pe?.type==="text"&&typeof Pe.text==="string")Ae.enqueue({type:"reasoning-delta",id:ne,delta:Pe.text})}}else if(ae==="processing_call"||ae==="processing_result"){let Ue={};if(se?.signature!=null)Ue.signature=se.signature;if(U!=null)Ue.interactionId=U;if(ae==="processing_call")Ue.processingId=se?.id||ne;else Ue.processingCallId=se?.call_id||ne;ce.set(be,{kind:"custom",id:ne,customKind:`google.${ae}`,google:Ue})}else if(ae==="function_call"){let Ue=se?.id||ne,Pe=se?.name??"unknown";Z=!0;let $e={kind:"function_call",id:ne,toolCallId:Ue,toolName:Pe,argumentsAccum:"",...se?.signature!=null?{signature:se.signature}:{}};ce.set(be,$e),Ae.enqueue({type:"tool-input-start",id:Ue,toolName:Pe})}else if(ae!=null&&ki.has(ae)){let Ue=ae==="mcp_server_tool_call"?se?.name??"mcp_server_tool":Ri(ae),Pe={kind:"builtin_tool_call",id:ne,blockType:ae,toolCallId:se?.id||ne,toolName:Ue,arguments:se?.arguments??{},callEmitted:!1};ce.set(be,Pe)}else if(ae!=null&&xi.has(ae)){let Ue=ae==="mcp_server_tool_result"?se?.name??"mcp_server_tool":Oi(ae),Pe={kind:"builtin_tool_result",id:ne,blockType:ae,callId:se?.call_id||ne,toolName:Ue,result:se?.result??null,...se?.is_error!=null?{isError:se.is_error}:{},resultEmitted:!1};ce.set(be,Pe)}else ce.set(be,{kind:"unknown",id:ne});break}case"step.delta":{let ye=je,se=ce.get(ye.index);if(se==null)break;let be=ye.delta?.type;if(se.kind==="pending_model_output"){if(be==="text"||be==="text_annotation"||be==="text_annotation_delta"){let ae={kind:"text",id:se.id,emittedSourceKeys:new Set};ce.set(ye.index,ae),se=ae,Ae.enqueue({type:"text-start",id:ae.id})}}if(be==="image"&&(se.kind==="pending_model_output"||se.kind==="text"||se.kind==="image")){let ae=ye.delta,Ue={};if(U!=null)Ue.interactionId=U;let Pe=Object.keys(Ue).length>0?{google:Ue}:void 0;if(ae?.data!=null&&ae.data.length>0)Ae.enqueue({type:"file",mediaType:ae.mime_type??"image/png",data:{type:"data",data:ae.data},...Pe?{providerMetadata:Pe}:{}});else if(ae?.uri!=null&&ae.uri.length>0)Ae.enqueue({type:"file",mediaType:ae.mime_type??"image/png",data:{type:"url",url:new URL(ae.uri)},...Pe?{providerMetadata:Pe}:{}});if(se.kind==="image")se.data=void 0,se.uri=void 0;break}if(be==="video"&&(se.kind==="pending_model_output"||se.kind==="text")){let ae=ye.delta,Ue={};if(U!=null)Ue.interactionId=U;let Pe=Object.keys(Ue).length>0?{google:Ue}:void 0;if(ae?.data!=null&&ae.data.length>0)Ae.enqueue({type:"file",mediaType:ae.mime_type??"video/mp4",data:{type:"data",data:ae.data},...Pe?{providerMetadata:Pe}:{}});else if(ae?.uri!=null&&ae.uri.length>0)Ae.enqueue({type:"file",mediaType:ae.mime_type??"video/mp4",data:{type:"url",url:new URL(ae.uri)},...Pe?{providerMetadata:Pe}:{}});break}let ne=ye.delta;if(se.kind==="custom"&&(ne?.type==="processing_call"||ne?.type==="processing_result")){if(ne.signature!=null)se.google.signature=ne.signature;if(ne.type==="processing_call"&&ne.id!=null&&ne.id.length>0)se.google.processingId=ne.id;if(ne.type==="processing_result"&&ne.call_id!=null&&ne.call_id.length>0)se.google.processingCallId=ne.call_id}else if(se.kind==="text"&&ne?.type==="text"){let ae=ne.text??"";if(ae.length>0)Ae.enqueue({type:"text-delta",id:se.id,delta:ae})}else if(se.kind==="text"&&(ne?.type==="text_annotation"||ne?.type==="text_annotation_delta")){let ae=Pt({annotations:ne.annotations,generateId:v});for(let Ue of ae){let Pe=Le(Ue);if(Me.has(Pe))continue;Me.add(Pe),se.emittedSourceKeys.add(Pe),Ae.enqueue(Ue)}}else if(se.kind==="image"&&ne?.type==="image"){if(ne.data!=null)se.data=ne.data;if(ne.mime_type!=null)se.mimeType=ne.mime_type;if(ne.uri!=null)se.uri=ne.uri}else if(se.kind==="reasoning"){if(ne?.type==="thought_summary"){let ae=ne.content;if(ae?.type==="text"&&typeof ae.text==="string")Ae.enqueue({type:"reasoning-delta",id:se.id,delta:ae.text})}else if(ne?.type==="thought_signature"){let ae=ne.signature;if(ae!=null)se.signature=ae}}else if(se.kind==="function_call"&&ne?.type==="arguments_delta"){let ae=typeof ne.arguments==="string"?ne.arguments:"";if(ae.length>0)se.argumentsAccum+=ae,Ae.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:ae});if(ne.id!=null&&ne.id.length>0)se.toolCallId=ne.id;if(ne.signature!=null)se.signature=ne.signature;Z=!0}else if(se.kind==="builtin_tool_call"&&ne?.type===se.blockType){if(ne.id!=null&&ne.id.length>0)se.toolCallId=ne.id;if(ne.arguments!=null&&typeof ne.arguments==="object")se.arguments=ne.arguments;if(ne.name!=null&&se.blockType==="mcp_server_tool_call")se.toolName=ne.name}else if(se.kind==="builtin_tool_result"&&ne?.type===se.blockType){if(ne.call_id!=null&&ne.call_id.length>0)se.callId=ne.call_id;if(ne.result!==void 0)se.result=ne.result;if(ne.is_error!=null)se.isError=ne.is_error;if(ne.name!=null&&se.blockType==="mcp_server_tool_result")se.toolName=ne.name}break}case"step.stop":{let ye=je,se=ce.get(ye.index);if(se==null)break;if(se.kind==="text"){let be=U!=null?{google:{interactionId:U}}:void 0;Ae.enqueue({type:"text-end",id:se.id,...be?{providerMetadata:be}:{}})}else if(se.kind==="reasoning"){let be={};if(se.signature!=null)be.signature=se.signature;if(U!=null)be.interactionId=U;let ne=Object.keys(be).length>0?{google:be}:void 0;Ae.enqueue({type:"reasoning-end",id:se.id,...ne?{providerMetadata:ne}:{}})}else if(se.kind==="image"){let be={};if(U!=null)be.interactionId=U;let ne=Object.keys(be).length>0?{google:be}:void 0;if(se.data!=null&&se.data.length>0)Ae.enqueue({type:"file",mediaType:se.mimeType??"image/png",data:{type:"data",data:se.data},...ne?{providerMetadata:ne}:{}});else if(se.uri!=null&&se.uri.length>0)Ae.enqueue({type:"file",mediaType:se.mimeType??"image/png",data:{type:"url",url:new URL(se.uri)},...ne?{providerMetadata:ne}:{}})}else if(se.kind==="function_call"){let be=se.argumentsAccum.length>0?se.argumentsAccum:"{}";Ae.enqueue({type:"tool-input-end",id:se.toolCallId});let ne={};if(se.signature!=null)ne.signature=se.signature;if(U!=null)ne.interactionId=U;let ae=Object.keys(ne).length>0?{google:ne}:void 0;Ae.enqueue({type:"tool-call",toolCallId:se.toolCallId,toolName:se.toolName,input:be,...ae?{providerMetadata:ae}:{}})}else if(se.kind==="custom")Ae.enqueue({type:"custom",kind:se.customKind,providerMetadata:{google:se.google}});else if(se.kind==="builtin_tool_call"&&!se.callEmitted)Ae.enqueue({type:"tool-call",toolCallId:se.toolCallId,toolName:se.toolName,input:JSON.stringify(se.arguments??{}),providerExecuted:!0}),se.callEmitted=!0;else if(se.kind==="builtin_tool_result"&&!se.resultEmitted){Ae.enqueue({type:"tool-result",toolCallId:se.callId,toolName:se.toolName,result:se.result??null}),se.resultEmitted=!0;let be=An({block:{type:se.blockType,call_id:se.callId,result:se.result},generateId:v});for(let ne of be){let ae=Le(ne);if(Me.has(ae))continue;Me.add(ae),Ae.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)U=ye.id;if(ye?.status!=null)ee=ye.status;if(ye?.usage!=null)G=ye.usage;if(ye?.service_tier!=null)re=ye.service_tier;break}case"error":{let ye=je;ee="failed",Ae.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 Ae=!pe&&(ee==null||ee==="in_progress"),je={unified:Ae?"interrupted":Vt({status:ee,hasFunctionCall:Z}),raw:Ae?void 0:ee},Ne=On(G),ye={google:{...U!=null?{interactionId:U}:{},...re!=null?{serviceTier:re}:{},...Ne!=null?{outputTokensByModality:Ne}:{}}};Ce.enqueue({type:"finish",finishReason:je,usage:Ht(G),providerMetadata:ye})}})}function Mi({prompt:f,previousInteractionId:v,store:x,mediaResolution:R}){let U=[],G=v!=null&&x===!1,re=v!=null&&x!==!1;if(G)U.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:v}):f,Z=[],pe=[];for(let ce of ee)switch(ce.role){case"system":Z.push(ce.content);break;case"user":{let Me=[];for(let Ce of ce.content)if(Ce.type==="text")Me.push({type:"text",text:Ce.text});else if(Ce.type==="file"){let Ae=pn({part:Ce,warnings:U,mediaResolution:R});if(Ae!=null)Me.push(Ae)}let Le=Ni(Me);if(Le.length>0)pe.push({type:"user_input",content:Le});break}case"assistant":{let Me=[],Le=()=>{if(Me.length>0)pe.push({type:"model_output",content:Me}),Me=[]};for(let Ce of ce.content)if(Ce.type==="text")Me.push({type:"text",text:Ce.text});else if(Ce.type==="reasoning"){Le();let Ae=Ce.providerOptions?.google?.signature;pe.push({type:"thought",...Ae!=null?{signature:Ae}:{},summary:Ce.text.length>0?[{type:"text",text:Ce.text}]:void 0})}else if(Ce.type==="file"){let Ae=pn({part:Ce,warnings:U,mediaResolution:R});if(Ae!=null)Me.push(Ae)}else if(Ce.type==="custom"){Le();let Ae=Ce.providerOptions?.google,je=typeof Ae?.signature==="string"?Ae.signature:void 0;if(Ce.kind==="google.processing_call"&&typeof Ae?.processingId==="string")pe.push({type:"processing_call",id:Ae.processingId,...je!=null?{signature:je}:{}});else if(Ce.kind==="google.processing_result"&&typeof Ae?.processingCallId==="string")pe.push({type:"processing_result",call_id:Ae.processingCallId,...je!=null?{signature:je}:{}});else U.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 Ae=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,...Ae!=null?{signature:Ae}:{}})}else U.push({type:"other",message:`google.interactions: unsupported assistant content part type "${Ce.type}"; part dropped.`});Le();break}case"tool":{let Me=[];for(let Le of ce.content){if(Le.type!=="tool-result"){U.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:U});Me.push(Ce)}if(Me.length>0)pe.push({type:"user_input",content:Me});break}}return{input:pe,systemInstruction:Z.length>0?Z.join(`
10
-
11
- `):void 0,warnings:U}}function pn({part:f,warnings:v,mediaResolution:x}){if(f.data.type==="text")return{type:"text",text:f.data.text};let R=z(f.mediaType),U;switch(R){case"image":U="image";break;case"audio":U="audio";break;case"video":U="video";break;case"application":case"text":U="document";break;default:U=void 0}if(U==null){v.push({type:"other",message:`google.interactions: unsupported file media type "${f.mediaType}"; part dropped.`});return}let G=x!=null&&(U==="image"||U==="video")?{resolution:x}:{},re=U==="video"?Ei({part:f,warnings:v}):{};switch(f.data.type){case"data":{let ee=O({part:f});return{type:U,data:T(f.data.data),mime_type:ee,...G,...re}}case"url":return{type:U,uri:f.data.url.toString(),...K(f.mediaType)?{mime_type:f.mediaType}:{},...G,...re};case"reference":{let ee=V({reference:f.data.reference,provider:"google"});return{type:U,uri:ee,...K(f.mediaType)?{mime_type:f.mediaType}:{},...G,...re}}}}function Ei({part:f,warnings:v}){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 R=x;return{processing:{type:"static",...typeof R.startOffset==="number"?{start_offset:`${R.startOffset}s`}:{},...typeof R.endOffset==="number"?{end_offset:`${R.endOffset}s`}:{},...typeof R.fps==="number"?{fps:R.fps}:{}}}}return v.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:v}){let x=[],R=new Set;for(let U of f){if(U.role==="assistant"){if(U.content.some((G)=>G.providerOptions?.google?.interactionId===v)){for(let G of U.content)if(G.type==="tool-call")R.add(G.toolCallId);continue}x.push(U);continue}if(U.role==="tool"){let G=U.content.filter((re)=>{if(re.type!=="tool-result")return!0;return!R.has(re.toolCallId)});if(G.length===0)continue;x.push({...U,content:G});continue}x.push(U)}return x}function Li(f){try{let v=Q(f);if(v!=null&&typeof v==="object"&&!Array.isArray(v))return v;return{value:v}}catch{return{value:f}}}function ji({toolCallId:f,toolName:v,output:x,signature:R,warnings:U}){let G={type:"function_result",call_id:f,name:v,...R!=null?{signature:R}:{}};switch(x.type){case"text":return{...G,result:x.value};case"json":return{...G,result:JSON.stringify(x.value)};case"error-text":return{...G,is_error:!0,result:x.value};case"error-json":return{...G,is_error:!0,result:JSON.stringify(x.value)};case"execution-denied":return{...G,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"){U.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 Z=Ui({part:ee,warnings:U});if(Z!=null)re.push(Z)}else U.push({type:"other",message:`google.interactions: tool-result content part type "${ee.type}" is not supported; part dropped.`});return{...G,result:re}}}}function Ui({part:f,warnings:v}){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:T(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:V({reference:f.data.reference,provider:"google"}),...K(f.mediaType)?{mime_type:f.mediaType}:{}};case"text":v.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 v=[];for(let x of f){let R=v[v.length-1];if(x.type==="text"&&R!=null&&R.type==="text"&&R.annotations==null&&x.annotations==null){let U={type:"text",text:`${R.text}
12
-
13
- ${x.text}`};v[v.length-1]=U;continue}v.push(x)}return v}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=()=>a(["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(),v=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(),w()).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,v,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(),v=t({type:n("image"),data:e().nullish(),mime_type:e().nullish(),resolution:a(["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,v,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(),v=t({type:n("model_output"),content:o(gn()).nullish()}).loose(),x=t({type:n("function_call"),id:e(),name:e(),arguments:y(e(),w()).nullish(),signature:e().nullish()}).loose(),R=t({type:n("thought"),signature:e().nullish(),summary:o(Nn()).nullish()}).loose(),U=t({type:n("processing_call"),id:e(),signature:e().nullish()}).loose(),G=t({type:n("processing_result"),call_id:e(),signature:e().nullish()}).loose(),re=t({type:a(Gn),id:e(),arguments:y(e(),w()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),ee=t({type:a(Dn),call_id:e(),result:w().nullish(),is_error:c().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose();return l([f,v,x,R,U,G,re,ee,t({type:e()}).loose()])},qt=i(()=>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=i(()=>s((()=>{let f=jn(),v=Un(),x=Nn(),R=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(),U=t({event_type:n("step.start"),event_id:e().nullish(),index:r(),step:Pn()}).loose(),G=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(),Z=t({type:n("arguments_delta"),arguments:e().nullish(),id:e().nullish(),signature:e().nullish()}).loose(),pe=t({type:a(["text_annotation_delta","text_annotation"]),annotations:o(v).nullish()}).loose(),ce=t({type:n("image"),data:e().nullish(),mime_type:e().nullish(),resolution:a(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),Me=t({type:n("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose(),Le=t({type:a(Gn),id:e().nullish(),arguments:y(e(),w()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),Ce=t({type:a(Dn),call_id:e().nullish(),result:w().nullish(),is_error:c().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose(),Ae=t({type:e()}).loose(),je=l([G,ce,Me,re,ee,Z,pe,Le,Ce,Ae]),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(),se=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(),ae=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(),Pe=t({event_type:e()}).loose();return l([R,U,Ne,ye,se,be,ne,ae,Ue,Pe])})())),Gi=i(()=>s(t({previousInteractionId:e().nullish(),store:c().nullish(),agent:e().nullish(),agentConfig:l([t({type:n("dynamic")}).loose(),t({type:n("deep-research"),thinkingSummaries:a(["auto","none"]).nullish(),visualization:a(["off","auto"]).nullish(),collaborativePlanning:c().nullish()})]).nullish(),thinkingLevel:a(["minimal","low","medium","high"]).nullish(),thinkingSummaries:a(["auto","none"]).nullish(),responseFormat:o(l([t({type:n("text"),mimeType:e().nullish(),schema:w().nullish()}).loose(),t({type:n("image"),mimeType:e().nullish(),aspectRatio:a(["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:a(["1K","2K","4K","512"]).nullish()}).loose(),t({type:n("audio"),mimeType:e().nullish()}).loose(),t({type:n("video"),aspectRatio:a(["16:9","9:16"]).nullish(),resolution:a(["360p","720p","1080p","4k"]).nullish(),duration:e().nullish(),delivery:a(["inline","uri"]).nullish(),gcsUri:e().nullish()}).loose()])).nullish(),imageConfig:t({aspectRatio:a(["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:a(["1K","2K","4K","512"]).nullish()}).nullish(),mediaResolution:a(["low","medium","high","ultra_high"]).nullish(),responseModalities:o(a(["text","image","audio","video","document"])).nullish(),serviceTier:a(["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:v,processingId:x,processingCallId:R}){let U={};if(f!=null)U.signature=f;if(v!=null)U.interactionId=v;if(x!=null)U.processingId=x;if(R!=null)U.processingCallId=R;return Object.keys(U).length>0?{providerMetadata:{google:U}}:{}}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:v,interactionId:x}){let R=[],U=!1;if(f==null)return{content:R,hasFunctionCall:U};for(let G of f){if(G==null||typeof G!=="object")continue;let re=G.type;if(typeof re!=="string")continue;switch(re){case"user_input":break;case"model_output":{let ee=G.content??[];for(let Z of ee){if(Z==null||typeof Z!=="object")continue;let pe=Z.type;if(pe==="text"){let ce=Z.text??"",Me=Z.annotations;R.push({type:"text",text:ce,...mt({interactionId:x})});let Le=Pt({annotations:Me,generateId:v});for(let Ce of Le)R.push(Ce)}else if(pe==="image"){let ce=Z;if(ce.data!=null&&ce.data.length>0)R.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)R.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=Z;if(ce.data!=null&&ce.data.length>0)R.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)R.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=G,Z=(Array.isArray(ee.summary)?ee.summary:[]).filter((pe)=>pe?.type==="text"&&typeof pe.text==="string").map((pe)=>pe.text).join(`
14
- `);R.push({type:"reasoning",text:Z,...mt({signature:ee.signature,interactionId:x})});break}case"processing_call":{let ee=G,Z=ee.id||v();R.push({type:"custom",kind:"google.processing_call",...mt({signature:ee.signature,interactionId:x,processingId:Z})});break}case"processing_result":{let ee=G,Z=ee.call_id||v();R.push({type:"custom",kind:"google.processing_result",...mt({signature:ee.signature,interactionId:x,processingCallId:Z})});break}case"function_call":{U=!0;let ee=G;R.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=G,Z=re==="mcp_server_tool_call"?ee.name??"mcp_server_tool":qi(re),pe=JSON.stringify(ee.arguments??{});R.push({type:"tool-call",toolCallId:ee.id||v(),toolName:Z,input:pe,providerExecuted:!0})}else if(Pi.has(re)){let ee=G,Z=re==="mcp_server_tool_result"?ee.name??"mcp_server_tool":$i(re);R.push({type:"tool-result",toolCallId:ee.call_id||v(),toolName:Z,result:ee.result??null});let pe=An({block:G,generateId:v});for(let ce of pe)R.push(ce)}}}return{content:R,hasFunctionCall:U}}var Fi=()=>globalThis.fetch;async function Fn({baseURL:f,interactionId:v,headers:x,fetch:R=Fi()}){if(v==null||v.length===0)return;let U=`${f}/interactions/${encodeURIComponent(v)}/cancel`;try{let G=await R(U,{method:"POST",headers:L(d({"Content-Type":"application/json"},x),Se()),body:"{}"});try{await G.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:v,headers:x,fetch:R,abortSignal:U,initialDelayMs:G=Hi,maxDelayMs:re=Vi,timeoutMs:ee=Wi}){if(v==null||v.length===0)throw Error("google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.");let Z=Date.now(),pe=G,ce=`${f}/interactions/${encodeURIComponent(v)}`,Me=()=>Fn({baseURL:f,interactionId:v,headers:x,fetch:R});try{while(!0){if(U?.aborted)throw await Me(),new DOMException("Polling was aborted","AbortError");if(Date.now()-Z>ee)throw Error(`google.interactions: timed out polling interaction ${v} after ${ee}ms.`);await Oe(pe,{abortSignal:U});let{value:Le,rawValue:Ce,responseHeaders:Ae}=await P({url:ce,validateUrl:!1,headers:x,failedResponseHandler:Ze,successfulResponseHandler:p(qt),abortSignal:U,fetch:R});if($t(Le.status))return{response:Le,rawResponse:Ce,responseHeaders:Ae};pe=Math.min(pe*2,re)}}catch(Le){if(W(Le))await Me();throw Le}}function zi({tools:f,toolChoice:v}){let x=[],R=f?.length?f:void 0;if(R==null)return{tools:void 0,toolChoice:void 0,toolWarnings:x};let U=[];for(let ee of R){if(ee.type==="function"){U.push({type:"function",name:ee.name,description:ee.description??"",parameters:ee.inputSchema});continue}if(ee.type==="provider"){let Z=ee.args??{};switch(ee.id){case"google.google_search":{let pe=Z.searchTypes,ce;if(pe!=null&&typeof pe==="object"){let Me=[];if(pe.webSearch!=null)Me.push("web_search");if(pe.imageSearch!=null)Me.push("image_search");if(Me.length>0)ce=Me}U.push({type:"google_search",...ce!=null?{search_types:ce}:{}});break}case"google.code_execution":U.push({type:"code_execution"});break;case"google.url_context":U.push({type:"url_context"});break;case"google.file_search":U.push({type:"file_search",...Z.fileSearchStoreNames!=null?{file_search_store_names:Z.fileSearchStoreNames}:{},...Z.topK!=null?{top_k:Z.topK}:{},...Z.metadataFilter!=null?{metadata_filter:Z.metadataFilter}:{}});break;case"google.google_maps":U.push({type:"google_maps",...Z.latitude!=null?{latitude:Z.latitude}:{},...Z.longitude!=null?{longitude:Z.longitude}:{},...Z.enableWidget!=null?{enable_widget:Z.enableWidget}:{}});break;case"google.computer_use":U.push({type:"computer_use",environment:Z.environment??"browser",...Z.excludedPredefinedFunctions!=null?{excludedPredefinedFunctions:Z.excludedPredefinedFunctions}:{}});break;case"google.mcp_server":U.push({type:"mcp_server",...Z.name!=null?{name:Z.name}:{},...Z.url!=null?{url:Z.url}:{},...Z.headers!=null?{headers:Z.headers}:{},...Z.allowedTools!=null?{allowed_tools:Z.allowedTools}:{}});break;case"google.retrieval":{let pe=Z.vertexAiSearchConfig??void 0;U.push({type:"retrieval",...Z.retrievalTypes!=null?{retrieval_types:Z.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 G=U.some((ee)=>ee.type==="function"),re;if(v!=null&&G)switch(v.type){case"auto":re="auto";break;case"required":re="any";break;case"none":re="none";break;case"tool":re={allowed_tools:{mode:"validated",tools:[v.toolName]}}}return{tools:U.length>0?U:void 0,toolChoice:re,toolWarnings:x}}var Ji=3,Yi=500;function Xi({baseURL:f,interactionId:v,headers:x,fetch:R,abortSignal:U,maxRetries:G=Ji,retryDelayMs:re=Yi}){if(v.length===0)throw Error("google.interactions: cannot stream a background interaction without an id.");let ee={...x,accept:"text/event-stream"},Z,pe=!1,ce=0,Me=!1,Le,Ce=new AbortController,Ae=()=>Ce.abort();if(U!=null)if(U.aborted)Ce.abort();else U.addEventListener("abort",Ae,{once:!0});let je=Ce.signal;function Ne(){let se=`${f}/interactions/${encodeURIComponent(v)}`,be=new URLSearchParams({stream:"true"});if(Z!=null)be.set("last_event_id",Z);return`${se}?${be.toString()}`}async function ye(){let{value:se}=await P({url:Ne(),validateUrl:!1,headers:ee,failedResponseHandler:Ze,successfulResponseHandler:D(qn),abortSignal:je,fetch:R});return se.getReader()}return new ReadableStream({async start(se){try{while(!pe&&!je.aborted){if(Le==null)try{Le=await ye(),Me=!1}catch(be){if(W(be)||je.aborted){se.error(be);return}if(ce++,ce>=G){se.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(!Me){if(ce++,ce>=G){se.error(Error("google.interactions: SSE stream closed without producing any events."));return}await Oe(re*ce,{abortSignal:je})}else ce=0;continue}if(Me=!0,ne.success){let ae=ne.value;if(typeof ae.event_id==="string"&&ae.event_id.length>0)Z=ae.event_id;if(ae.event_type==="interaction.completed"||ae.event_type==="error")pe=!0}se.enqueue(ne)}catch(be){if(W(be)||je.aborted){se.error(be);return}if(Le=void 0,ce++,ce>=G){se.error(be);return}await Oe(re*ce,{abortSignal:je})}}se.close()}catch(be){se.error(be)}finally{if(U!=null)U.removeEventListener("abort",Ae);if(Le?.cancel().catch(()=>{}),Le=void 0,je.aborted&&!pe)await Fn({baseURL:f,interactionId:v,headers:x,fetch:R})}},cancel(){Ce.abort(),Le?.cancel().catch(()=>{}),Le=void 0}})}function Qi({response:f,warnings:v,generateId:x,includeRawChunks:R,headerServiceTier:U}){return new ReadableStream({start(G){G.enqueue({type:"stream-start",warnings:v});let re=typeof f.id==="string"&&f.id.length>0?f.id:void 0,ee,Z=f.created;if(typeof Z==="string"){let Ne=new Date(Z);if(!Number.isNaN(Ne.getTime()))ee=Ne}if(G.enqueue({type:"response-metadata",...re!=null?{id:re}:{},modelId:f.model??void 0,...ee?{timestamp:ee}:{}}),R)G.enqueue({type:"raw",rawValue:f});let{content:pe,hasFunctionCall:ce}=$n({steps:f.steps??null,generateId:x,interactionId:re}),Me=0,Le=()=>`${re??"agent"}:${Me++}`;for(let Ne of pe)switch(Ne.type){case"text":{let ye=Le(),se=Ne.providerMetadata;if(G.enqueue({type:"text-start",id:ye}),Ne.text.length>0)G.enqueue({type:"text-delta",id:ye,delta:Ne.text});G.enqueue({type:"text-end",id:ye,...se?{providerMetadata:se}:{}});break}case"reasoning":{let ye=Le(),se=Ne.providerMetadata;if(G.enqueue({type:"reasoning-start",id:ye}),Ne.text.length>0)G.enqueue({type:"reasoning-delta",id:ye,delta:Ne.text});G.enqueue({type:"reasoning-end",id:ye,...se?{providerMetadata:se}:{}});break}case"tool-call":{let ye=Ne.providerMetadata;G.enqueue({type:"tool-input-start",id:Ne.toolCallId,toolName:Ne.toolName,...Ne.providerExecuted?{providerExecuted:Ne.providerExecuted}:{}}),G.enqueue({type:"tool-input-delta",id:Ne.toolCallId,delta:Ne.input}),G.enqueue({type:"tool-input-end",id:Ne.toolCallId}),G.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":G.enqueue({type:"tool-result",toolCallId:Ne.toolCallId,toolName:Ne.toolName,result:Ne.result});break;case"source":case"file":G.enqueue(Ne)}let Ce=f.service_tier??U,Ae={unified:Vt({status:f.status,hasFunctionCall:ce}),raw:f.status},je={google:{...re!=null?{interactionId:re}:{},...Ce!=null?{serviceTier:Ce}:{}}};G.enqueue({type:"finish",finishReason:Ae,usage:Ht(f.usage),providerMetadata:je}),G.close()}})}var Zi=class f{static[S](v){return{...M({modelId:v.modelId,config:v.config}),agent:v.agent}}static[I](v){return new f(v.agent!=null?{agent:v.agent}:v.modelId,v.config)}constructor(v,x){if(this.specificationVersion="v4",typeof v==="string")this.modelId=v,this.agent=void 0;else if("managedAgent"in v)this.modelId=v.managedAgent,this.agent=v.managedAgent;else this.modelId=v.agent,this.agent=v.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(v){let x=[],R=await h({provider:"google",providerOptions:v.providerOptions,schema:Gi}),U=this.agent!=null;if(!U){if(v.frequencyPenalty!=null)x.push({type:"unsupported",feature:"frequencyPenalty"});if(v.presencePenalty!=null)x.push({type:"unsupported",feature:"presencePenalty"})}let G=v.tools!=null&&v.tools.length>0,re,ee;if(G){let ye=zi({tools:v.tools,toolChoice:v.toolChoice});re=ye.tools,ee=ye.toolChoice,x.push(...ye.toolWarnings)}let Z=[];if(v.responseFormat?.type==="json")if(U)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",...v.responseFormat.schema!=null?{schema:v.responseFormat.schema}:{}};Z.push(ye)}if(R?.responseFormat!=null){for(let ye of R.responseFormat)if(ye.type==="text")Z.push(ht({type:"text",mime_type:ye.mimeType??void 0,schema:ye.schema??void 0}));else if(ye.type==="image")Z.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")Z.push(ht({type:"audio",mime_type:ye.mimeType??void 0}));else if(ye.type==="video")Z.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:Me}=Mi({prompt:v.prompt,previousInteractionId:R?.previousInteractionId??void 0,store:R?.store??void 0,mediaResolution:R?.mediaResolution??void 0});x.push(...Me);let Le=ce,Ce=R?.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 Ae;if(U){let ye=[];if(v.temperature!=null)ye.push("temperature");if(v.topP!=null)ye.push("topP");if(v.topK!=null)ye.push("topK");if(v.frequencyPenalty!=null)ye.push("frequencyPenalty");if(v.presencePenalty!=null)ye.push("presencePenalty");if(v.seed!=null)ye.push("seed");if(v.stopSequences!=null&&v.stopSequences.length>0)ye.push("stopSequences");if(v.maxOutputTokens!=null)ye.push("maxOutputTokens");if(R?.thinkingLevel!=null)ye.push("thinkingLevel");if(R?.thinkingSummaries!=null)ye.push("thinkingSummaries");if(R?.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.`});Ae=void 0}else if(Ae=ht({temperature:v.temperature??void 0,top_p:v.topP??void 0,top_k:v.topK??void 0,seed:v.seed??void 0,stop_sequences:v.stopSequences!=null&&v.stopSequences.length>0?v.stopSequences:void 0,max_output_tokens:v.maxOutputTokens??void 0,thinking_level:R?.thinkingLevel??void 0,thinking_summaries:R?.thinkingSummaries??void 0,tool_choice:ee}),R?.imageConfig!=null){let ye=Z.some((se)=>se.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)Z.push({type:"image",mime_type:"image/png",...R.imageConfig.aspectRatio!=null?{aspect_ratio:R.imageConfig.aspectRatio}:{},...R.imageConfig.imageSize!=null?{image_size:R.imageConfig.imageSize}:{}})}let je;if(U&&R?.agentConfig!=null){let ye=R.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(R?.environment!=null)if(!U)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 R.environment==="string")Ne=R.environment;else{let ye=R.environment,se=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:se!=null&&se.length>0?se:void 0,network:be})}return{args:ht({...U?{agent:this.agent}:{model:this.modelId},input:pe,system_instruction:Le,tools:re,response_format:Z.length>0?Z:void 0,response_modalities:R?.responseModalities!=null?R.responseModalities:void 0,previous_interaction_id:R?.previousInteractionId??void 0,service_tier:R?.serviceTier??void 0,store:R?.store??void 0,generation_config:Ae!=null&&Object.keys(Ae).length>0?Ae:void 0,agent_config:je,environment:Ne,background:R?.background??void 0}),warnings:x,isAgent:U,isBackground:R?.background===!0,pollingTimeoutMs:R?.pollingTimeoutMs??void 0}}async doGenerate(v){let{args:x,warnings:R,isAgent:U,isBackground:G,pollingTimeoutMs:re}=await this.getArgs(v),ee=`${this.config.baseURL}/interactions`,Z=d(this.config.headers?await _(this.config.headers):void 0,v.headers),{responseHeaders:pe,value:ce,rawValue:Me}=await g({url:ee,headers:Z,body:x,failedResponseHandler:Ze,successfulResponseHandler:p(qt),abortSignal:v.abortSignal,fetch:this.config.fetch});if((U||G)&&!$t(ce.status)){let ne=await Ki({baseURL:this.config.baseURL,interactionId:ce.id,headers:Z,fetch:this.config.fetch,abortSignal:v.abortSignal,timeoutMs:re});ce=ne.response,Me=ne.rawResponse,pe=ne.responseHeaders??pe}let Le=typeof ce.id==="string"&&ce.id.length>0?ce.id:void 0,{content:Ce,hasFunctionCall:Ae}=$n({steps:ce.steps??null,generateId:this.config.generateId??C,interactionId:Le}),je={unified:Vt({status:ce.status,hasFunctionCall:Ae}),raw:ce.status},Ne=ce.service_tier??pe?.["x-gemini-service-tier"]??void 0,ye=On(ce.usage),se={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:R,providerMetadata:se,request:{body:x},response:{headers:pe,body:Me,...Le!=null?{id:Le}:{},...be?{timestamp:be}:{},modelId:ce.model??void 0}}}async doStream(v){let{args:x,warnings:R,isBackground:U,pollingTimeoutMs:G}=await this.getArgs(v),re=`${this.config.baseURL}/interactions`,ee=d(this.config.headers?await _(this.config.headers):void 0,v.headers);if(U)return this.doStreamBackground({args:x,warnings:R,url:re,mergedHeaders:ee,options:v,pollingTimeoutMs:G});let Z={...x,stream:!0},{responseHeaders:pe,value:ce}=await g({url:re,headers:ee,body:Z,failedResponseHandler:Ze,successfulResponseHandler:D(qn),abortSignal:v.abortSignal,fetch:this.config.fetch}),Me=pe?.["x-gemini-service-tier"],Le=dn({warnings:R,generateId:this.config.generateId??C,includeRawChunks:v.includeRawChunks,serviceTier:Me});return{stream:ce.pipeThrough(Le),request:{body:Z},response:{headers:pe}}}async doStreamBackground({args:v,warnings:x,url:R,mergedHeaders:U,options:G,pollingTimeoutMs:re}){let{responseHeaders:ee,value:Z}=await g({url:R,headers:U,body:v,failedResponseHandler:Ze,successfulResponseHandler:p(qt),abortSignal:G.abortSignal,fetch:this.config.fetch}),pe=Z.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(Z.status))return{stream:Qi({response:Z,warnings:x,generateId:this.config.generateId??C,includeRawChunks:G.includeRawChunks,headerServiceTier:ce}),request:{body:v},response:{headers:ee}};let Me=Xi({baseURL:this.config.baseURL,interactionId:pe,headers:U,fetch:this.config.fetch,abortSignal:G.abortSignal}),Le=dn({warnings:x,generateId:this.config.generateId??C,includeRawChunks:G.includeRawChunks,serviceTier:ce});return{stream:Me.pipeThrough(Le),request:{body:v},response:{headers:ee}}}};function ht(f){let v={};for(let[x,R]of Object.entries(f)){if(R===void 0)continue;v[x]=R}return v}function Bn(f){let v=new URL(f),x=v.pathname.split("/"),R=x.at(-1);if(R==="v1beta"||R==="v1alpha")x.pop(),v.pathname=x.join("/")||"/";return v}function Wt(f,v){let x=Bn(f);return x.protocol=x.protocol==="https:"?"wss:":"ws:",x.pathname=`${x.pathname.replace(/\/$/,"")}/ws/${v}`,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:v}){if(!f){if(v===!0)this.finishInputTranscription();return}let x=v!=null;if(this.inputTranscriptionBuffer!==""&&(this.inputTranscriptionBoundary==="interrupted"||this.inputTranscriptionBoundary==="turn-complete"&&!x))this.finishInputTranscription();this.inputTranscriptionBoundary="none",this.inputTranscriptionBuffer+=f;let R={itemId:`google-input-${this.inputTranscriptionCounter}`,transcript:this.inputTranscriptionBuffer};if(v===!0)this.finishInputTranscription();return R}finishInputTranscription(){if(this.inputTranscriptionBuffer==="")return;this.inputTranscriptionCounter++,this.inputTranscriptionBuffer=""}parseServerEvent(f){let v=f;if(v.setupComplete!=null)return{type:"session-created",raw:f};if(v.toolCall!=null)return this.beginTurnIfClosed(),(v.toolCall.functionCalls??[]).flatMap((x)=>{let R=JSON.stringify(x.args??{});return[{type:"function-call-arguments-delta",responseId:this.responseId,itemId:this.itemId,callId:x.id,delta:R,raw:f},{type:"function-call-arguments-done",responseId:this.responseId,itemId:this.itemId,callId:x.id,name:x.name,arguments:R,raw:f}]});if(v.toolCallCancellation!=null)return{type:"custom",rawType:"toolCallCancellation",raw:f};if(v.goAway!=null)return{type:"custom",rawType:"goAway",raw:f};if(v.sessionResumptionUpdate!=null)return{type:"custom",rawType:"sessionResumptionUpdate",raw:f};if(v.serverContent!=null)return this.parseServerContent(v.serverContent,f);if(v.inputTranscription!=null){let x=this.accumulateInputTranscription(v.inputTranscription);if(x!=null)return{type:"input-transcription-completed",...x,raw:f}}return{type:"custom",rawType:String(Object.keys(v)[0]),raw:f}}parseServerContent(f,v){let x=[];if(f.interrupted)this.inputTranscriptionBoundary="interrupted",this.preserveInputTranscriptionAcrossTurnComplete=!0,this.turnClosed=!0,x.push({type:"speech-started",raw:v});if(f.modelTurn?.parts){this.beginTurnIfClosed();for(let R of f.modelTurn.parts){if(R.inlineData?.data)this.hasAudio=!0,x.push({type:"audio-delta",responseId:this.responseId,itemId:this.itemId,delta:R.inlineData.data,raw:v});if(R.text)this.hasText=!0,x.push({type:"text-delta",responseId:this.responseId,itemId:this.itemId,delta:R.text,raw:v})}}if(f.outputTranscription?.text)this.hasTranscript=!0,x.push({type:"audio-transcript-delta",responseId:this.responseId,itemId:this.itemId,delta:f.outputTranscription.text,raw:v});if(f.inputTranscription!=null){let R=this.accumulateInputTranscription(f.inputTranscription);if(R!=null)x.push({type:"input-transcription-completed",...R,raw:v})}if(f.generationComplete)x.push({type:"custom",rawType:"generationComplete",raw:v});if(f.interactionStatus!=null)x.push({type:"custom",rawType:"interactionStatus",raw:v});if(f.waitingForInput)x.push({type:"custom",rawType:"waitingForInput",raw:v});if(f.turnComplete){if(this.hasAudio)x.push({type:"audio-done",responseId:this.responseId,itemId:this.itemId,raw:v});if(this.hasText)x.push({type:"text-done",responseId:this.responseId,itemId:this.itemId,raw:v});if(this.hasTranscript)x.push({type:"audio-transcript-done",responseId:this.responseId,itemId:this.itemId,raw:v});if(x.push({type:"response-done",responseId:this.responseId,status:"completed",raw:v}),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:v};return x.length===1?x[0]:x}serializeClientEvent(f,v){switch(f.type){case"session-update":if(f.config.inputAudioFormat?.rate!=null)this.inputAudioRate=f.config.inputAudioFormat.rate;return{setup:Ft(f.config,v)};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 v=await J({text:f.output}),x=v.success?ts(v.value):{output:f.output};return{toolResponse:{functionResponses:[{id:f.callId,name:f.name,response:x}]}}}function os(f){let v=f.split("/").at(-1)?.toLowerCase()??"";return/^gemini-\d+\.\d+-live\b.*thinking/.test(v)}function Ft(f,v){let x={model:Tt(v)},{google:R,...U}=f?.providerOptions??{},G=j(R)?R:void 0,re={};if(f?.outputModalities!=null)re.responseModalities=f.outputModalities.map((Me)=>Me.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((Me)=>({name:Me.name,description:Me.description,parametersJsonSchema:Me.parameters,...G?.defaultToolBehavior!=null?{behavior:G.defaultToolBehavior}:{}}))}];if(f?.inputAudioTranscription!=null)x.inputAudioTranscription={};if(f?.outputAudioTranscription!=null)x.outputAudioTranscription={};let ee=U.generationConfig,Z=G?.thinkingConfig??(j(ee)&&j(ee.thinkingConfig)?ee.thinkingConfig:void 0),pe=os(v)&&Z?.thinkingLevel==null&&Z?.thinkingBudget==null?{...Z,thinkingLevel:"low"}:G?.thinkingConfig,ce=()=>{if(pe==null)return;let Me=j(x.generationConfig)?x.generationConfig:re;x.generationConfig={...Me,thinkingConfig:pe}};if(f?.providerOptions==null)return ce(),x;if(Object.assign(x,U),G?.translationConfig!=null)x.generationConfig={...j(x.generationConfig)?x.generationConfig:re,translationConfig:G.translationConfig};return ce(),x}var is="google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained";function ss(f){let v=Bn(f);return v.pathname=`${v.pathname.replace(/\/$/,"")}/v1alpha/auth_tokens`,v.toString()}function as(f){return Wt(f,is).toString()}var rs=class{constructor(f,v){this.specificationVersion="v4",this.mapper=new es,this.modelId=f,this.provider=v.provider,this.config=v}async doCreateClientSecret(f){let v=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 R=Date.now(),U=(f.expiresAfterSeconds??60)*1000,G=new Date(R+U).toISOString(),re=new Date(R+U+1800000).toISOString(),ee=Ft(f.sessionConfig,this.modelId),Z=await v(`${ss(this.config.baseURL)}?key=${encodeURIComponent(x)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uses:0,expireTime:re,newSessionExpireTime:G,bidiGenerateContentSetup:ee})});if(!Z.ok){let ce=await Z.text();throw Error(`Google realtime auth token request failed: ${Z.status} ${ce}`)}let pe=await Z.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=i(()=>s(t({languageCodes:o(e()).optional(),customVocabulary:o(e()).optional(),wordTimestamp:c().optional(),diarization:c().optional(),mode:a(["SMART","VERBATIM"]).optional()}))),us="google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",cs=3000;function ds(f,v){let x=Wt(f,us);return x.searchParams.set("key",v),x}function hn(f){return f.includes("-live")}var ps=class f{static[S](v){return M({modelId:v.modelId,config:v.config})}static[I](v){return new f(v.modelId,v.config)}get provider(){return this.config.provider}constructor(v,x){this.modelId=v,this.config=x,this.specificationVersion="v4"}async parseOptions(v){return h({provider:"google",providerOptions:v,schema:ls})}async doGenerate(v){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,R=[],U=ms(await this.parseOptions(v.providerOptions)),G={model:this.modelId,input:[{type:"audio",data:T(v.audio),mime_type:v.mediaType}],...U!=null?{generation_config:{transcription_config:U}}:{}},{value:re,responseHeaders:ee,rawValue:Z}=await g({url:`${this.config.baseURL}/interactions`,headers:d(this.config.headers?await _(this.config.headers):void 0,v.headers),body:G,failedResponseHandler:Ze,successfulResponseHandler:p(vs),abortSignal:v.abortSignal,fetch:this.config.fetch}),pe="",ce=[];for(let Me of re.steps??[])for(let Le of Me.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 Ae=mn(Ce.start_offset),je=mn(Ce.end_offset);if(Ce.text==null||Ae==null||je==null)continue;ce.push({text:Ce.text,startSecond:Ae,endSecond:je})}}return{text:pe,segments:ce,language:void 0,durationInSeconds:void 0,warnings:R,...re.usage!=null&&{usage:re.usage},response:{timestamp:x,modelId:this.modelId,headers:ee,body:Z},...re.usage!=null?{providerMetadata:{google:{usage:re.usage}}}:{}}}async doStream(v){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,R=[],U=await this.parseOptions(v.providerOptions);fs(v.inputAudioFormat);let G=d(this.config.headers?await _(this.config.headers):void 0,v.headers),re;for(let[pe,ce]of Object.entries(G))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(G).filter(([pe])=>pe.toLowerCase()!=="x-goog-api-key")),Z={model:Tt(this.modelId),inputAudioTranscription:hs(U)??{}};return{request:{body:Z},response:{timestamp:x,modelId:this.modelId},stream:gs({webSocket:this.config.webSocket,url:ds(this.config.baseURL,re),headers:ee,setup:Z,inputAudioRate:v.inputAudioFormat.rate??16000,finishGraceMs:this.config._internal?.finishGraceMs??cs,warnings:R,audio:v.audio,abortSignal:v.abortSignal,includeRawChunks:v.includeRawChunks})}}};function gs({webSocket:f,url:v,headers:x,setup:R,inputAudioRate:U,finishGraceMs:G,warnings:re,audio:ee,abortSignal:Z,includeRawChunks:pe}){let ce=!1,Me=()=>{};return new ReadableStream({start:(Le)=>{let Ce,Ae,je,Ne=new Promise((Ve)=>{je=Ve}),ye=0,se="",be="",ne="",ae,Ue=!1,Pe,$e,Ke=()=>`google-segment-${ye}`,nt=()=>{if($e!=null)clearTimeout($e),$e=void 0},ze=()=>{if(ce||!Ue)return;nt(),$e=setTimeout(()=>{$e=void 0,Je()},G)};Me=(Ve)=>{if(nt(),Ce!=null)Ce.cancel().catch(()=>{});else ee.cancel().catch(()=>{});Ae?.close(Ve)};let et=(Ve)=>{if(ce)return;ce=!0,Me(),Le.error(Ve)},pt=()=>{if(se===""){if(ne==="")return;se=ne}ne="",Le.enqueue({type:"transcript-final",id:Ke(),text:se}),be+=be===""?se:` ${se}`,se="",ye++},Je=()=>{if(ce)return;pt(),ce=!0,Le.enqueue({type:"finish",text:be,segments:[],language:ae,durationInSeconds:void 0,usage:Pe,...Pe!=null?{providerMetadata:{google:{usageMetadata:Pe}}}:{}}),Le.close(),Me(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:T(lt),mimeType:`audio/pcm;rate=${U}`}}})),await ue(Ve)}}finally{Ce.releaseLock(),Ce=void 0}if(!ce)Ve.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),Ue=!0,ze()};Ae=fe({url:v,headers:x,webSocket:f,abortSignal:Z,onAbort:et,onProcessingError:et,onOpen:(Ve)=>{Le.enqueue({type:"stream-start",warnings:re}),Ve.send(JSON.stringify({setup:R})),Ne.then(()=>ce?void 0:ot(Ve)).catch(et)},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)Pe=lt.usageMetadata;if(lt.error!=null){et(Error(lt.error.message??"Google Live API error"));return}let dt=lt.serverContent,Be=dt?.interimInputTranscription;if(Be?.text)ze(),ne=Be.text,Le.enqueue({type:"transcript-partial",id:Ke(),text:Be.text});let tt=dt?.inputTranscription??lt.inputTranscription;if(tt!=null){if(tt.languageCode!=null)ae=tt.languageCode;if(tt.text)ze(),ne="",se+=tt.text,Le.enqueue({type:"transcript-delta",id:Ke(),delta:tt.text});if(tt.finished===!0)pt()}if(dt?.turnComplete)pt();let Ye=dt?.interactionStatus;if(Ue&&(Ye==="IDLE"||Ye==="REQUIRES_ACTION"||dt?.turnComplete===!0&&Ye==null))Je()},onSocketError:()=>{et(Error("Google Live transcription error"))},onClose:({code:Ve,reason:rt})=>{if(ce)return;if(Ue){Je();return}et(Error(`Google Live transcription WebSocket closed unexpectedly before finishing (code ${Ve??"unknown"}${rt?`, reason: ${rt}`:""}).`))}})},cancel:()=>{if(ce)return;ce=!0,Me()}})}function hs(f){if(f==null)return;let v={};if(f.languageCodes!=null)v.languageCodes=f.languageCodes;if(f.customVocabulary!=null)v.customVocabulary=f.customVocabulary;if(f.wordTimestamp!=null)v.wordTimestamp=f.wordTimestamp;if(f.diarization!=null)v.diarization=f.diarization;if(f.mode!=null)v.mode=f.mode;return Object.keys(v).length>0?v:void 0}function ms(f){if(f==null)return;let v={};if(f.languageCodes!=null)v.language_codes=f.languageCodes;if(f.customVocabulary!=null)v.custom_vocabulary=f.customVocabulary;if(f.mode!=null||f.diarization===!0||f.wordTimestamp===!0)v.mode={type:(f.mode??"VERBATIM").toLowerCase(),...f.diarization===!0?{diarization_mode:"speaker"}:{},...f.wordTimestamp===!0?{timestamp_granularities:["word"]}:{}};return Object.keys(v).length>0?v:void 0}function mn(f){if(f==null)return;let v=Number.parseFloat(f);return Number.isFinite(v)?v: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=i(()=>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(),F()).nullish()}))),bs=i(()=>s(t({echoTargetLanguage:c().optional()}))),Ts="google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",_s=1000,Cs=24000,ws=128;function Ss(f,v){let x=Wt(f,Ts);return x.searchParams.set("key",v),x}var Is=class f{static[S](v){return M({modelId:v.modelId,config:v.config})}static[I](v){return new f(v.modelId,v.config)}get provider(){return this.config.provider}constructor(v,x){this.specificationVersion="v4",this.modelId=v,this.config=x}async doStream(v){if(v.targetLanguage==null)throw new b({argument:"targetLanguage",message:`targetLanguage is required for translation model '${this.modelId}'.`});let x=this.config._internal?.currentDate?.()??new Date,R=await h({provider:"google",providerOptions:v.providerOptions,schema:bs}),U=[];if(Ms(v.inputAudioFormat),v.sourceLanguage!=null)U.push({type:"unsupported",feature:"sourceLanguage",details:"The Gemini Live translation API auto-detects the source language and does not accept a source language."});if(v.outputAudioFormat!=null)U.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 G=d(this.config.headers(),v.headers),re;for(let[pe,ce]of Object.entries(G))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(G).filter(([pe])=>pe.toLowerCase()!=="x-goog-api-key")),Z=Os({modelId:this.modelId,targetLanguage:v.targetLanguage,providerOptions:R});return{request:{body:Z},response:{timestamp:x,modelId:this.modelId},stream:ks({webSocket:this.config.webSocket,url:Ss(this.config.baseURL,re),headers:ee,setup:Z,inputAudioRate:v.inputAudioFormat.rate??16000,finishGraceMs:this.config._internal?.finishGraceMs??_s,warnings:U,audio:v.audio,abortSignal:v.abortSignal,includeRawChunks:v.includeRawChunks})}}};function ks({webSocket:f,url:v,headers:x,setup:R,inputAudioRate:U,finishGraceMs:G,warnings:re,audio:ee,abortSignal:Z,includeRawChunks:pe}){let ce=!1,Me=()=>{};return new ReadableStream({start:(Le)=>{let Ce,Ae,je,Ne=new Promise((Be)=>{je=Be}),ye=0,se="",be="",ne="",ae="",Ue=!1,Pe,$e=!1,Ke=!1,nt=0,ze,et=()=>`google-item-${ye}`,pt=()=>{if(ze!=null)clearTimeout(ze),ze=void 0},Je=()=>{if(ce||ze!=null)return;ze=setTimeout(()=>{ze=void 0,rt()},G)},ot=()=>{$e=!0,nt=0,pt()};Me=(Be)=>{if(pt(),Ce!=null)Ce.cancel().catch(()=>{});else ee.cancel().catch(()=>{});Ae?.close(Be)};let Ve=(Be)=>{if(ce)return;ce=!0,Me(),Le.error(Be)},rt=()=>{if(ce)return;if(be!==""||ae!=="")lt();ce=!0,Le.enqueue({type:"finish",sourceText:se,outputText:ne,usage:Pe}),Le.close(),Me(1000)},lt=()=>{if(be!=="")Le.enqueue({type:"source-transcript-final",id:et(),text:be}),se+=be,be="";if(ae!=="")Le.enqueue({type:"output-text-final",id:et(),text:ae}),ne+=ae,ae="";ye++},dt=async(Be)=>{Ce=ee.getReader();try{while(!0){let{done:tt,value:Ye}=await Ce.read();if(tt||ce)break;Be.send(JSON.stringify({realtimeInput:{audio:{data:T(Ye),mimeType:`audio/pcm;rate=${U}`}}})),await ue(Be)}}finally{Ce.releaseLock(),Ce=void 0}if(!ce){if(Be.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),Ue=!0,Ke&&!$e)Je()}};Ae=fe({url:v,headers:x,webSocket:f,abortSignal:Z,onAbort:Ve,onProcessingError:Ve,onOpen:(Be)=>{Le.enqueue({type:"stream-start",warnings:re}),Be.send(JSON.stringify({setup:R})),Ne.then(()=>ce?void 0:dt(Be)).catch(Ve)},onMessageText:async(Be)=>{if(ce)return;let tt=await J({text:Be});if(!tt.success)return;let Ye=tt.value;if(pe)Le.enqueue({type:"raw",rawValue:Ye});if(Ye.setupComplete!=null)je();if(Ye.usageMetadata!=null)Pe=xs(Pe,Ye.usageMetadata);if(Ye.error!=null){Ve(Error(Ye.error.message??"Google Live API error"));return}let He=Ye.serverContent?.inputTranscription?.text??Ye.inputTranscription?.text;if(He)ot(),be+=He,Le.enqueue({type:"source-transcript-delta",id:et(),delta:He});let qe=Ye.serverContent;if(qe==null)return;for(let ut of qe.modelTurn?.parts??[])if(ut.inlineData?.data){Le.enqueue({type:"audio",id:et(),audio:ut.inlineData.data});let at=Rs(ut.inlineData.data);if(Ue&&at!=null){if(nt+=at,nt>=G){rt();return}}else ot()}if(qe.outputTranscription?.text)ot(),ae+=qe.outputTranscription.text,Le.enqueue({type:"output-text-delta",id:et(),delta:qe.outputTranscription.text});if(qe.turnComplete){if(lt(),$e=!1,Ke=!0,Ue)Je()}},onSocketError:()=>{Ve(Error("Google Live translation error"))},onClose:({code:Be,reason:tt})=>{if(ce)return;if(ze!=null){rt();return}Ve(Error(`Google Live translation WebSocket closed unexpectedly before finishing (code ${Be??"unknown"}${tt?`, reason: ${tt}`:""}).`))}})},cancel:()=>{if(ce)return;ce=!0,Me()}})}function xs(f,v){let x=f?.inputAudioTokens,R=f?.outputAudioTokens;for(let U of v.promptTokensDetails??[])if(U.modality==="AUDIO"&&U.tokenCount!=null)x=(x??0)+U.tokenCount;for(let U of v.responseTokensDetails??[])if(U.modality==="AUDIO"&&U.tokenCount!=null)R=(R??0)+U.tokenCount;if(x==null&&R==null)return f;return{...f,...x!=null?{inputAudioTokens:x}:{},...R!=null?{outputAudioTokens:R}:{}}}function Rs(f){let v;try{v=q(f)}catch{return}if(v.byteLength<2)return;let x=new DataView(v.buffer,v.byteOffset,v.byteLength),R=Math.floor(v.byteLength/2);for(let U=0;U<R;U++)if(Math.abs(x.getInt16(U*2,!0))>ws)return;return R/Cs*1000}function Os({modelId:f,targetLanguage:v,providerOptions:x}){return{model:Tt(f),generationConfig:{responseModalities:["AUDIO"],translationConfig:{targetLanguageCode:v,...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 v=Y(f.baseURL)??Es,x=f.name??"google.generative-ai",R=()=>L({"x-goog-api-key":he({apiKey:f.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...f.headers},`ai-sdk-google/${zn}`),U=(be,ne=be==null||Us(be))=>({"*":[As,new RegExp(`^${v}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")],...ne?Object.fromEntries(Ls.map((ae)=>[ae,[js]])):{}}),G={provider:x,baseURL:v,headers:R,generateId:f.generateId??C,fetch:f.fetch},re=(be)=>new Ct(be,{...G,supportedUrls:()=>U(be)}),ee=()=>new Wo({provider:`${x.replace(/\.generative-ai$/,"")}.batch`,maxLineBytes:f.batchResultDownloads?.maxLineBytes,config:G,supportedUrls:U(void 0,!1)}),Z=(be)=>new Qn(be,{provider:x,baseURL:v,headers:R,fetch:f.fetch}),pe=(be,ne={})=>new ni(be,ne,{provider:x,baseURL:v,headers:R,fetch:f.fetch}),ce=()=>new oi({provider:x,baseURL:v,headers:R,fetch:f.fetch}),Me=(be)=>new hi(be,{provider:x,baseURL:v,headers:R,fetch:f.fetch,generateId:f.generateId??C}),Le=(be)=>new rs(be,{provider:`${x}.realtime`,baseURL:v,headers:R,fetch:f.fetch}),Ce=(be)=>new Is(be,{provider:`${x}.speech-translation`,baseURL:v,headers:R,webSocket:f.webSocket}),Ae=(be)=>new _i(be,{provider:`${x}.speech`,baseURL:v,headers:R,fetch:f.fetch}),je=(be)=>new ps(be,{provider:`${x}.transcription`,baseURL:v,headers:R,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:v,headers:R,generateId:f.generateId??C,fetch:f.fetch}),se=function(be){if(new.target)throw Error("The Google Generative AI model function cannot be called with the new keyword.");return re(be)};return se.specificationVersion="v4",se.languageModel=re,se.chat=re,se.generativeAI=re,se.decisionModel=(be)=>new Xe({model:re(be),provider:`${x.replace(/\.generative-ai$/,"")}.decision`}),se.evaluationModel=se.decisionModel,se.experimental_batch=ee,se.embedding=Z,se.embeddingModel=Z,se.textEmbedding=Z,se.textEmbeddingModel=Z,se.image=pe,se.imageModel=pe,se.video=Me,se.videoModel=Me,se.experimental_realtime=Ne,se.files=ce,se.speech=Ae,se.speechModel=Ae,se.transcription=je,se.transcriptionModel=je,se.translation=Ce,se.speechTranslationModel=Ce,se.interactions=ye,se.tools=ei,se}var Fs=Kt();var Ns=Ee(Kt);function Qs(){oe("google",Ns)}export{Qs as register};
@@ -1 +0,0 @@
1
- import{Pe,mt,Ue,Qe,$e,Fe,gt,_t}from"./embed-hn0r8fmg.js";var i="https://maxgfr.github.io/murmur/cdn/models.json";function l(e){let r=e.endpoint?Fe(e.endpoint):null;if(!r)return null;let o=e.model||"default",t={apiKey:"",model:o,customEndpoint:r,customModel:o};if(e.headers)t.headers=e.headers;return t}function d(e,r={}){let o=r.storageKey??"murmur",t={};if(e.provider)t.providerId=e.provider;if(e.model)t.model=e.model;return _t({catalog:mt({fallbackUrl:r.catalogUrl??i}),storage:gt({prefsKey:`${o}-llm`,dbName:`${o}-secrets`}),recommended:e.provider?[e.provider,...Pe.filter((n)=>n!==e.provider)]:Pe,defaults:t})}async function m(e,r){let o=l(e);if(o)return o;let t=r?await r.load():null;return t&&$e(t)?t:null}export{Ue as describeError,Qe as loadModel,m as resolveSettings,d as visitorStore};
@@ -1 +0,0 @@
1
- import{Pe,mt,Ue,Qe,$e,Fe,mn,gt,_t}from"./embed-hn0r8fmg.js";export{Pe as DEFAULT_RECOMMENDED,mn as ENDPOINT_PRESETS,_t as createLlmSettingsStore,Ue as describeError,$e as isConfigured,mt as liveCatalog,Qe as loadModel,gt as secureStorage,Fe as validateEndpoint};
@@ -1 +0,0 @@
1
- import{vn,Ct}from"./embed-n7jskdxd.js";export{vn as generateText,Ct as streamText};
@@ -1,9 +0,0 @@
1
- import{xt,pt,St}from"./embed-q6y6vgv1.js";var h="script,style,noscript,template,svg,canvas,iframe,nav,header,footer,aside,form,button,dialog,[hidden],[aria-hidden='true'],[data-murmur-ignore],murmur-chat",E="main,article,[role='main'],body",O=/^(P|LI|DT|DD|PRE|BLOCKQUOTE|TABLE|TR|FIGCAPTION|DIV|SECTION|ARTICLE|UL|OL|DL|MAIN|H[1-6])$/;function f(i,{root:l=E,exclude:o=h}={}){let r=l.split(",").map((t)=>i.querySelector(t.trim())).find((t)=>!!t),m=r?.querySelector("h1")?.textContent?.replace(/\s+/g," ").trim()||i.querySelector("title")?.textContent?.trim()||"";if(!r)return{title:m,sections:[]};let u=[],e={heading:"",anchor:"",text:""},x=new Set,d=(t)=>{if(t.nodeType===3){e.text+=(t.textContent??"").replace(/\s+/g," ");return}if(t.nodeType!==1)return;let n=t;if(n.matches(o))return;let s=n.tagName.toUpperCase();if(/^H[1-3]$/.test(s)){u.push(e);let c=(n.textContent??"").replace(/\s+/g," ").trim(),a=n.id||n.closest("[id]")?.id||pt(c);while(x.has(a))a+="-";x.add(a),e={heading:c,anchor:a,text:""};return}if(s==="BR")e.text+=`
2
- `;let p=O.test(s);if(p)e.text+=`
3
-
4
- `;if(s==="LI")e.text+="- ";for(let c of Array.from(n.childNodes))d(c);if(p)e.text+=`
5
-
6
- `};for(let t of Array.from(r.childNodes))d(t);return u.push(e),{title:m,sections:u.map((t)=>({...t,text:t.text.replace(/[ \t]+\n/g,`
7
- `).replace(/\n{3,}/g,`
8
-
9
- `).trim()})).filter((t)=>t.text)}}function S(i,l=i.location?.href??"",o={}){let r=f(i,o);return St([{url:l,title:r.title,sections:r.sections}],o.maxChunk??xt)}export{S as indexDocument};
@@ -1,3 +0,0 @@
1
- import{oe,Ee}from"./embed-hn0r8fmg.js";import{b,Ze,me,u,e,r,c,ae,o,t,l,f,y,a,n,F,S,I,d,q,T,ee,te,le,L,z,C,Pt,he,H,ke,at,i,s,h,g,ne,we,k,O,E,D,p,M,Ce,Y}from"./embed-sgjh2kg2.js";var xe=t({messages:o(F()).nullish(),cached_tokens:r().nullish(),audio_tokens:r().nullish()}).catchall(F()),Ue=t({reasoning_tokens:r().nullish()}).catchall(F()),ve=t({prompt_tokens:r(),completion_tokens:r(),total_tokens:r(),prompt_audio_seconds:r().nullish(),request_count:r().nullish(),service_tier:e().nullish(),num_cached_tokens:r().nullish(),prompt_tokens_details:xe.nullish(),prompt_token_details:xe.nullish(),completion_tokens_details:Ue.nullish()}).catchall(F());function pe(w){if(w==null)return te();let{prompt_tokens:m,completion_tokens:_}=w,P=w.num_cached_tokens??w.prompt_tokens_details?.cached_tokens??w.prompt_token_details?.cached_tokens??0;return{inputTokens:{total:m,noCache:m-P,cacheRead:P||void 0,cacheWrite:void 0},outputTokens:{total:_,text:_,reasoning:void 0},raw:w}}function Se({part:w}){if(w.data.type==="url")return w.data.url.toString();if(w.data.type==="data")return`data:${O({part:w})};base64,${T(w.data.data)}`;throw new u({functionality:`file part data type ${w.data.type}`})}function be(w){let m=[];for(let _=0;_<w.length;_++){let{role:P,content:A}=w[_],v=_===w.length-1;switch(P){case"system":m.push({role:"system",content:A});break;case"user":m.push({role:"user",content:A.map((R)=>{switch(R.type){case"text":return{type:"text",text:R.text};case"file":switch(R.data.type){case"reference":throw new u({functionality:"file parts with provider references"});case"text":throw new u({functionality:"text file parts"});case"url":case"data":if(z(R.mediaType)==="image")return{type:"image_url",image_url:Se({part:R})};else{if(R.data.type==="data"){if(O({part:R})!=="application/pdf")throw new u({functionality:"Only images and PDF file parts are supported"})}else if(R.mediaType!=="application/pdf")throw new u({functionality:"Only images and PDF file parts are supported"});return{type:"document_url",document_url:Se({part:R})}}}}})});break;case"assistant":{let R="",U=!1,x=[],j=[];for(let N of A)switch(N.type){case"text":R+=N.text,x.push({type:"text",text:N.text});break;case"tool-call":j.push({id:N.toolCallId,type:"function",function:{name:N.toolName,arguments:JSON.stringify(N.input)}});break;case"reasoning":U=!0,x.push({type:"thinking",thinking:[{type:"text",text:N.text}],closed:!0});break;default:throw Error(`Unsupported content type in assistant message: ${N.type}`)}m.push({role:"assistant",content:U?x:R,prefix:v?!0:void 0,tool_calls:j.length>0?j:void 0});break}case"tool":for(let R of A){if(R.type==="tool-approval-response")continue;let U=R.output,x;switch(U.type){case"text":case"error-text":x=U.value;break;case"execution-denied":x=U.reason??"Tool call execution denied.";break;case"content":case"json":case"error-json":x=JSON.stringify(U.value)}m.push({role:"tool",name:R.toolName,tool_call_id:R.toolCallId,content:x})}break;default:throw Error(`Unsupported role: ${P}`)}}return m}function Ie(w){switch(w){case"stop":return"stop";case"length":case"model_length":return"length";case"tool_calls":return"tool-calls";case"error":return"error";default:return"other"}}var Re=()=>t({safePrompt:c().optional(),documentImageLimit:r().optional(),documentPageLimit:r().optional(),structuredOutputs:c().optional(),strictJsonSchema:c().optional(),parallelToolCalls:c().optional(),promptCacheKey:e().optional(),reasoningEffort:a(["high","none","low","max"]).optional()}),$e=i(()=>s(Re())),De=i(()=>s(t({object:n("error"),message:e(),type:e(),param:e().nullable(),code:e().nullable()}))),ce=E({errorSchema:De,errorToMessage:(w)=>w.message});function Pe({tools:w,toolChoice:m}){w=w?.length?w:void 0;let _=[];if(w==null)return{tools:void 0,toolChoice:void 0,toolWarnings:_};let P=[];for(let v of w)if(v.type==="provider")_.push({type:"unsupported",feature:`provider-defined tool ${v.id}`});else P.push({type:"function",function:{name:v.name,description:v.description,parameters:v.inputSchema,...v.strict!=null?{strict:v.strict}:{}}});if(m==null)return{tools:P,toolChoice:void 0,toolWarnings:_};let A=m.type;switch(A){case"auto":case"none":return{tools:P,toolChoice:A,toolWarnings:_};case"required":return{tools:P,toolChoice:"any",toolWarnings:_};case"tool":return{tools:P.filter((v)=>v.function.name===m.toolName),toolChoice:"any",toolWarnings:_};default:throw new u({functionality:`tool choice type: ${A}`})}}var Ve=new Set(["codestral-2508","codestral-latest","ministral-14b-2512","ministral-14b-latest","ministral-3b-2512","ministral-3b-latest","ministral-8b-2512","ministral-8b-latest","mistral-code-fim-latest","mistral-code-latest","mistral-large-latest","mistral-large-2512","voxtral-small-2507","voxtral-small-latest"]),Je=new Set(["zai-glm-5","zai-glm-5-3","zai-glm-5-3-flash","zai-glm-latest"]),ze=class w{static[S](m){return M({modelId:m.modelId,config:m.config})}static[I](m){return new w(m.modelId,m.config)}constructor(m,_){this.specificationVersion="v4",this.supportedUrls={"application/pdf":[/^https:\/\/.*$/]},this.modelId=m,this.config=_,this.generateId=_.generateId??C}get provider(){return this.config.provider}async getArgs({prompt:m,maxOutputTokens:_,temperature:P,topP:A,topK:v,frequencyPenalty:R,presencePenalty:U,reasoning:x,stopSequences:j,responseFormat:N,seed:V,providerOptions:X,tools:se,toolChoice:Q}){let Z=[],K=await h({provider:"mistral",providerOptions:X,schema:$e})??{};if(v!=null)Z.push({type:"unsupported",feature:"topK"});let re=!Ve.has(this.modelId),W;if(re){let de=Je.has(this.modelId);if(K.reasoningEffort==null&&x==="none"&&de)Z.push({type:"compatibility",feature:"reasoning",details:'reasoning "none" is not directly supported by this model. mapped to effort "low".'});W=K.reasoningEffort??(H(x)?x==="none"?de?"low":"none":ke({reasoning:x,effortMap:de?{minimal:"low",low:"low",medium:"high",high:"high",xhigh:"max",max:"max"}:{minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},warnings:Z}):void 0)}else if(H(x))Z.push({type:"unsupported",feature:"reasoning",details:"This model does not support reasoning configuration."});let B=K.structuredOutputs??!0,J=K.strictJsonSchema??!1;if(N?.type==="json"&&(!B||N.schema==null))m=Pt({messages:m,schema:N.schema});let G={model:this.modelId,safe_prompt:K.safePrompt,max_tokens:_,temperature:P,top_p:A,...R!=null?{frequency_penalty:R}:{},...U!=null?{presence_penalty:U}:{},stop:j,random_seed:V,reasoning_effort:W,response_format:N?.type==="json"?B&&N?.schema!=null?{type:"json_schema",json_schema:{schema:N.schema,strict:J,name:N.name??"response",description:N.description}}:{type:"json_object"}:void 0,document_image_limit:K.documentImageLimit,document_page_limit:K.documentPageLimit,...K.promptCacheKey!==void 0?{prompt_cache_key:K.promptCacheKey}:{},messages:be(m)},{tools:ie,toolChoice:fe,toolWarnings:ye}=Pe({tools:se,toolChoice:Q});return{args:{...G,tools:ie,tool_choice:fe,...ie!=null&&K.parallelToolCalls!==void 0?{parallel_tool_calls:K.parallelToolCalls}:{}},warnings:[...Z,...ye]}}async doGenerate(m){let{args:_,warnings:P}=await this.getArgs(m),{responseHeaders:A,value:v,rawValue:R}=await g({url:`${this.config.baseURL}/chat/completions`,headers:d(this.config.headers?.(),m.headers),body:_,failedResponseHandler:ce,successfulResponseHandler:p(Ke),abortSignal:m.abortSignal,fetch:this.config.fetch}),U=v.choices[0],x=[];if(U.message.content!=null&&Array.isArray(U.message.content)){for(let j of U.message.content)if(j.type==="thinking"){let N=je(j.thinking);if(N.length>0)x.push({type:"reasoning",text:N})}else if(j.type==="text"){if(j.text.length>0)x.push({type:"text",text:j.text})}}else{let j=Te(U.message.content);if(j!=null&&j.length>0)x.push({type:"text",text:j})}if(U.message.tool_calls!=null)for(let j of U.message.tool_calls)x.push({type:"tool-call",toolCallId:j.id,toolName:j.function.name,input:j.function.arguments});return{content:x,finishReason:{unified:Ie(U.finish_reason),raw:U.finish_reason??void 0},usage:pe(v.usage),request:{body:_},response:{...ee(v),headers:A,body:R},warnings:P}}async doStream(m){let{args:_,warnings:P}=await this.getArgs(m),A={..._,stream:!0},{responseHeaders:v,value:R}=await g({url:`${this.config.baseURL}/chat/completions`,headers:d(this.config.headers?.(),m.headers),body:A,failedResponseHandler:ce,successfulResponseHandler:D(Be),abortSignal:m.abortSignal,fetch:this.config.fetch}),U={unified:"interrupted",raw:void 0},x=void 0,j=!0,N=!1,V=null,X,se=this.generateId;return{stream:R.pipeThrough(new TransformStream({start(Q){X=new Ce(Q,{generateId:se}),Q.enqueue({type:"stream-start",warnings:P})},transform(Q,Z){if(m.includeRawChunks)Z.enqueue({type:"raw",rawValue:Q.rawValue});if(!Q.success){U={unified:"error",raw:void 0},Z.enqueue({type:"error",error:Q.error});return}let K=Q.value;if(j)j=!1,Z.enqueue({type:"response-metadata",...ee(K)});if(K.usage!=null)x=K.usage;let re=K.choices[0],W=re.delta,B=Te(W.content);if(W.content!=null&&Array.isArray(W.content)){for(let J of W.content)if(J.type==="thinking"){let G=je(J.thinking);if(G.length>0){if(V==null){if(N)Z.enqueue({type:"text-end",id:"0"}),N=!1;V=se(),Z.enqueue({type:"reasoning-start",id:V})}Z.enqueue({type:"reasoning-delta",id:V,delta:G})}}}if(B!=null&&B.length>0){if(!N){if(V!=null)Z.enqueue({type:"reasoning-end",id:V}),V=null;Z.enqueue({type:"text-start",id:"0"}),N=!0}Z.enqueue({type:"text-delta",id:"0",delta:B})}if(W?.tool_calls!=null)for(let J of W.tool_calls)X.processDelta(J);if(re.finish_reason!=null)U={unified:Ie(re.finish_reason),raw:re.finish_reason}},flush(Q){if(V!=null)Q.enqueue({type:"reasoning-end",id:V});if(N)Q.enqueue({type:"text-end",id:"0"});X.flush(),Q.enqueue({type:"finish",finishReason:U,usage:pe(x)})}})),request:{body:A},response:{headers:v}}}};function je(w){return w.filter((m)=>m.type==="text").map((m)=>m.text).join("")}function Te(w){if(typeof w==="string")return w;if(w==null)return;let m=[];for(let _ of w){let{type:P}=_;switch(P){case"text":m.push(_.text);break;case"thinking":case"image_url":case"reference":break;default:throw Error(`Unsupported type: ${P}`)}}return m.length?m.join(""):void 0}var qe=()=>l([e(),o(f("type",[t({type:n("text"),text:e()}),t({type:n("image_url"),image_url:l([e(),t({url:e(),detail:e().nullable()})])}),t({type:n("reference"),reference_ids:o(l([e(),r()]))}),t({type:n("thinking"),thinking:o(t({type:n("text"),text:e()}))})]))]).nullish(),Ke=i(()=>s(t({id:e().nullish(),created:r().nullish(),model:e().nullish(),choices:o(t({message:t({role:n("assistant"),content:qe(),tool_calls:o(t({id:e(),function:t({name:e(),arguments:e()})})).nullish()}),index:r(),finish_reason:e().nullish()})),object:n("chat.completion"),usage:ve}))),Be=i(()=>s(t({id:e().nullish(),created:r().nullish(),model:e().nullish(),choices:o(t({delta:t({role:a(["assistant"]).optional(),content:qe(),tool_calls:o(t({index:r().nullish(),id:e().nullish(),function:t({name:e().nullish(),arguments:e().nullish()})})).nullish()}),finish_reason:e().nullish(),index:r()})),usage:ve.nullish()})));function We(w,m){let _=[],P=[],A=new Set,v=(R)=>{if(A.has(R.toolCallId)){let x=null;if(R.output.type==="json"){let j=R.output.value,N=j!=null&&typeof j==="object"&&"info"in j?j.info:void 0;if(N!=null&&typeof N==="object"&&!Array.isArray(N))x="result"in N?N.result??N:N}_.push({type:"function.result",tool_call_id:R.toolCallId,result:typeof x==="string"?x:JSON.stringify(x)});return}let U=be([{role:"tool",content:[R]}])[0];_.push({type:"function.result",tool_call_id:R.toolCallId,result:U.content})};for(let R of w)switch(R.role){case"system":P.push(R.content);break;case"user":{let U=be([R])[0];if(U.role==="user")_.push({type:"message.input",role:"user",content:U.content});break}case"assistant":{let U=[],x=()=>{if(U.length>0)_.push({type:"message.input",role:"assistant",content:U}),U=[]};for(let j of R.content)switch(j.type){case"text":U.push({type:"text",text:j.text});break;case"reasoning":U.push({type:"thinking",thinking:[{type:"text",text:j.text}],closed:!0});break;case"tool-call":if(x(),j.providerExecuted){let N=j.providerOptions?.mistral?.function??j.providerOptions?.mistral?.name,V=j.input;_.push({type:"function.call",tool_call_id:j.toolCallId,name:typeof N==="string"?N:m.toProviderToolName(j.toolName),arguments:typeof V?.arguments==="string"?V.arguments:JSON.stringify(j.input)}),A.add(j.toolCallId)}else _.push({type:"function.call",tool_call_id:j.toolCallId,name:j.toolName,arguments:JSON.stringify(j.input)});break;case"tool-result":x(),v(j);break;default:throw new u({functionality:`assistant content type: ${j.type}`})}x();break}case"tool":for(let U of R.content){if(U.type==="tool-approval-response")continue;v(U)}}return{inputs:_,instructions:P.length>0?P.join(`
2
-
3
- `):void 0}}var Ge=i(()=>s(Re())),ge={"mistral.web_search":"web_search","mistral.web_search_premium":"web_search_premium"};function Fe({tools:w,toolChoice:m}){w=w?.length?w:void 0;let _=[];if(w==null)return{tools:void 0,toolChoice:void 0,toolWarnings:_};let P=[];for(let v of w)if(v.type==="provider"){if(v.id==="mistral.web_search"||v.id==="mistral.web_search_premium"){P.push({type:ge[v.id]});continue}_.push({type:"unsupported",feature:`provider-defined tool ${v.id}`})}else P.push({type:"function",function:{name:v.name,description:v.description,parameters:v.inputSchema,...v.strict!=null?{strict:v.strict}:{}}});if(m==null)return{tools:P,toolChoice:void 0,toolWarnings:_};let A=m.type;switch(A){case"auto":case"none":return{tools:P,toolChoice:A,toolWarnings:_};case"required":return{tools:P,toolChoice:"any",toolWarnings:_};case"tool":{let v=le({tools:w,providerToolNames:ge}).toProviderToolName(m.toolName);return{tools:P.filter((R)=>R.type==="function"?R.function.name===v:R.type===v),toolChoice:"any",toolWarnings:_}}default:throw new u({functionality:`tool choice type: ${A}`})}}var Ye=new Set(["glm-5-2","labs-leanstral-1-5","labs-leanstral-1-5-1","magistral-medium-latest","magistral-small-latest","mistral-large-4","mistral-large-4-0","mistral-medium","mistral-medium-2604","mistral-medium-3","mistral-medium-3-5","mistral-medium-3.5","mistral-medium-latest","mistral-small-2603","mistral-small-latest","mistral-vibe-cli-fast","mistral-vibe-cli-latest","mistral-vibe-cli-with-tools","zai-glm-5-2"]),Qe=class w{static[S](m){return M({modelId:m.modelId,config:m.config})}static[I](m){return new w(m.modelId,m.config)}constructor(m,_){this.specificationVersion="v4",this.supportedUrls={"application/pdf":[/^https:\/\/.*$/]},this.modelId=m,this.config=_,this.generateId=_.generateId??C}get provider(){return this.config.provider}async getArgs({prompt:m,maxOutputTokens:_,temperature:P,topP:A,topK:v,frequencyPenalty:R,presencePenalty:U,reasoning:x,stopSequences:j,responseFormat:N,seed:V,providerOptions:X,tools:se,toolChoice:Q}){let Z=[],K=await h({provider:"mistral",providerOptions:X,schema:Ge})??{};if(v!=null)Z.push({type:"unsupported",feature:"topK"});let re=Ye.has(this.modelId),W;if(re)W=K.reasoningEffort??(H(x)?x==="none"?"none":ke({reasoning:x,effortMap:{minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},warnings:Z}):void 0);else if(H(x))Z.push({type:"unsupported",feature:"reasoning",details:"This model does not support reasoning configuration."});let B=K.structuredOutputs??!0,J=K.strictJsonSchema??!1;if(N?.type==="json"&&(!B||N.schema==null))m=Pt({messages:m,schema:N.schema});let G={max_tokens:_,temperature:P,top_p:A,...R!=null?{frequency_penalty:R}:{},...U!=null?{presence_penalty:U}:{},stop:j,random_seed:V,reasoning_effort:W,response_format:N?.type==="json"?B&&N?.schema!=null?{type:"json_schema",json_schema:{schema:N.schema,strict:J,name:N.name??"response",description:N.description}}:{type:"json_object"}:void 0},{tools:ie,toolChoice:fe,toolWarnings:ye}=Fe({tools:se,toolChoice:Q});for(let[de,He]of Object.entries({safePrompt:K.safePrompt,documentImageLimit:K.documentImageLimit,documentPageLimit:K.documentPageLimit,promptCacheKey:K.promptCacheKey,parallelToolCalls:K.parallelToolCalls}))if(He!=null)Z.push({type:"unsupported",feature:de,details:"Not supported by the Mistral Conversations API."});return{args:{model:this.modelId,store:!1,...We(m,le({tools:se,providerToolNames:ge})),tools:ie,completion_args:{...G,tool_choice:fe}},warnings:[...Z,...ye]}}async doGenerate(m){let{args:_,warnings:P}=await this.getArgs(m),{value:A,rawValue:v,responseHeaders:R}=await g({url:`${this.config.baseURL}/conversations`,headers:d(this.config.headers?.(),m.headers),body:_,failedResponseHandler:ce,successfulResponseHandler:p(nt),abortSignal:m.abortSignal,fetch:this.config.fetch}),U=Me({tools:m.tools,generateId:this.generateId}),x=[],j=!1,N;for(let V of A.outputs)switch(V.type){case"tool.execution":x.push(...U.convertTool(V));break;case"function.call":j=!0,x.push({type:"tool-call",toolCallId:V.tool_call_id,toolName:V.name,input:typeof V.arguments==="string"?V.arguments:JSON.stringify(V.arguments)});break;case"message.output":N=V.model??N;for(let X of typeof V.content==="string"?[{type:"text",text:V.content}]:V.content)x.push(...U.convertChunk(X))}return{content:x,finishReason:{unified:j?"tool-calls":"stop",raw:void 0},usage:pe(A.usage),request:{body:_},response:{id:A.conversation_id,modelId:N,headers:R,body:v},warnings:P}}async doStream(m){let{args:_,warnings:P}=await this.getArgs(m),A={..._,stream:!0},{value:v,responseHeaders:R}=await g({url:`${this.config.baseURL}/conversations`,headers:d(this.config.headers?.(),m.headers),body:A,failedResponseHandler:ce,successfulResponseHandler:D(st),abortSignal:m.abortSignal,fetch:this.config.fetch}),U=Me({tools:m.tools,generateId:this.generateId}),x=new Map,j,N,V,X=!1,se=!1,Q=!1,Z=!1,K=(W)=>{if(N!=null)W.enqueue({type:N.type==="text"?"text-end":"reasoning-end",id:N.id}),N=void 0},re=this.generateId;return{stream:v.pipeThrough(new TransformStream({start(W){j=new Ce(W,{generateId:re}),W.enqueue({type:"stream-start",warnings:P})},transform(W,B){if(m.includeRawChunks)B.enqueue({type:"raw",rawValue:W.rawValue});if(!W.success){se=!0,B.enqueue({type:"error",error:W.error});return}let J=W.value;switch(J.type){case"conversation.response.started":B.enqueue({type:"response-metadata",id:J.conversation_id,...J.created_at!=null?{timestamp:new Date(J.created_at)}:{}});break;case"conversation.response.done":V=J.usage??void 0,Q=!0;break;case"conversation.response.error":se=!0,B.enqueue({type:"error",error:J});break;case"message.output.delta":if(!Z&&J.model!=null)Z=!0,B.enqueue({type:"response-metadata",modelId:J.model});for(let G of U.convertChunk(typeof J.content==="string"?{type:"text",text:J.content}:J.content))if(G.type==="text"||G.type==="reasoning"){let ie=`${J.id}-${J.content_index??0}`;if(N?.id!==ie||N.type!==G.type)K(B),N={id:ie,type:G.type},B.enqueue({type:G.type==="text"?"text-start":"reasoning-start",id:ie});B.enqueue({type:G.type==="text"?"text-delta":"reasoning-delta",id:ie,delta:G.text})}else if(G.type==="source")B.enqueue(G);break;case"function.call.delta":K(B),X=!0,j.processDelta({id:J.tool_call_id,index:J.output_index,function:{name:J.name,arguments:J.arguments}});break;case"tool.execution.started":case"tool.execution.delta":{K(B);let G=x.get(J.id);if(G==null)x.set(J.id,{name:J.name,arguments:J.arguments,function:J.function}),B.enqueue({type:"tool-input-start",id:J.id,toolName:U.toolNameMapping.toCustomToolName(J.name),providerExecuted:!0});else G.arguments+=J.arguments;break}case"tool.execution.done":{let G=x.get(J.id);if(G==null){se=!0,B.enqueue({type:"error",error:Error(`Missing tool execution start for ${J.id}`)});break}B.enqueue({type:"tool-input-delta",id:J.id,delta:JSON.stringify({arguments:G.arguments})}),B.enqueue({type:"tool-input-end",id:J.id});for(let ie of U.convertTool({type:"tool.execution",id:J.id,name:G.name,arguments:G.arguments,function:J.function??G.function,info:J.info}))B.enqueue(ie);x.delete(J.id);break}}},flush(W){K(W),j.flush(),W.enqueue({type:"finish",finishReason:{unified:se||!Q||x.size>0?"error":X?"tool-calls":"stop",raw:void 0},usage:pe(V)})}})),request:{body:A},response:{headers:R}}}};function Me({tools:w,generateId:m}){let _=le({tools:w,providerToolNames:ge}),P=new Set;return{toolNameMapping:_,convertChunk(A){switch(A.type){case"text":return A.text.length>0?[{type:"text",text:A.text}]:[];case"thinking":{let R=A.thinking.map((U)=>U.text).join("");return R.length>0?[{type:"reasoning",text:R}]:[]}case"tool_reference":if(A.url==null||P.has(A.url))return[];let v=m();return P.add(A.url),[{type:"source",sourceType:"url",id:v,url:A.url,title:A.title??A.url}]}},convertTool(A){let v=_.toCustomToolName(A.name);return[{type:"tool-call",toolCallId:A.id,toolName:v,input:JSON.stringify({arguments:A.arguments}),providerExecuted:!0,providerMetadata:{mistral:{type:"tool.execution",name:A.name,...A.function!=null?{function:A.function}:{}}}},{type:"tool-result",toolCallId:A.id,toolName:v,result:{...A.info!=null?{info:A.info}:{}}}]}}}var Oe=()=>f("type",[t({type:n("text"),text:e()}),t({type:n("thinking"),thinking:o(t({type:n("text"),text:e()}))}),t({type:n("tool_reference"),tool:e().nullish(),title:e().nullish(),url:e().nullish()})]),Xe=()=>l([e(),o(Oe())]),et=()=>t({type:n("tool.execution"),id:e(),name:e(),arguments:e(),function:e().nullish(),info:y(e(),F()).nullish()}),tt=()=>t({type:n("function.call"),tool_call_id:e(),name:e(),arguments:l([e(),y(e(),F())])}),Le=()=>ve.extend({prompt_tokens:r().default(0),completion_tokens:r().default(0),total_tokens:r().default(0)}),nt=i(()=>s(t({conversation_id:e(),outputs:o(f("type",[et(),tt(),t({type:n("message.output"),content:Xe(),model:e().nullish()})])),usage:Le().nullish()}))),st=i(()=>s(f("type",[t({type:n("conversation.response.started"),conversation_id:e(),created_at:e().nullish()}),t({type:n("conversation.response.done"),usage:Le().nullish()}),t({type:n("conversation.response.error"),message:e(),code:r()}),t({type:n("message.output.delta"),id:e(),content_index:r().nullish(),content:l([e(),Oe()]),model:e().nullish()}),t({type:n("function.call.delta"),tool_call_id:e(),name:e(),arguments:e(),output_index:r().nullish()}),t({type:a(["tool.execution.started","tool.execution.delta"]),id:e(),name:e(),arguments:e(),function:e().nullish()}),t({type:n("tool.execution.done"),id:e(),name:e(),function:e().nullish(),info:y(e(),F()).nullish()})]))),ot=t({metadata:y(e(),ae()).optional(),outputDimension:r().int().positive().optional(),outputDtype:a(["float","int8","uint8","binary","ubinary"]).optional()}),it=class w{get provider(){return this.config.provider}static[S](m){return M({modelId:m.modelId,config:m.config})}static[I](m){return new w(m.modelId,m.config)}constructor(m,_){this.specificationVersion="v4",this.maxEmbeddingsPerCall=32,this.supportsParallelCalls=!1,this.modelId=m,this.config=_}async doEmbed({values:m,dimensions:_,abortSignal:P,headers:A,providerOptions:v}){if(m.length>this.maxEmbeddingsPerCall)throw new me({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:m});let R=await h({provider:"mistral",providerOptions:v,schema:ot})??{},{responseHeaders:U,value:x,rawValue:j}=await g({url:`${this.config.baseURL}/embeddings`,headers:d(this.config.headers?.(),A),body:{model:this.modelId,input:m,metadata:R.metadata,output_dimension:R.outputDimension??_,output_dtype:R.outputDtype,encoding_format:"float"},failedResponseHandler:ce,successfulResponseHandler:p(rt),abortSignal:P,fetch:this.config.fetch});return{warnings:[],embeddings:x.data.map((N)=>N.embedding),usage:x.usage?{tokens:x.usage.prompt_tokens}:void 0,response:{headers:U,body:j}}}},rt=i(()=>s(t({data:o(t({embedding:o(r())})),usage:t({prompt_tokens:r()}).nullish()}))),lt=i(()=>s(t({refAudio:e().min(1).optional(),expressiveness:r().min(1).max(5).optional(),phonemeHints:y(e().min(1),o(e().min(1)).min(1)).optional()}))),ct=class w{static[S](m){return M({modelId:m.modelId,config:m.config})}static[I](m){return new w(m.modelId,m.config)}get provider(){return this.config.provider}constructor(m,_){this.modelId=m,this.config=_,this.specificationVersion="v4"}async getArgs({text:m,voice:_,outputFormat:P="mp3",instructions:A,speed:v,language:R,providerOptions:U}){let x=[],j=await h({provider:"mistral",providerOptions:U,schema:lt}),N="mp3";if(["pcm","wav","mp3","flac","opus"].includes(P))N=P;else x.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${P}. Using mp3 instead.`});if(A!=null)x.push({type:"unsupported",feature:"instructions",details:"Mistral speech models do not support the `instructions` option. Use a reference audio clip to guide delivery."});if(v!=null)x.push({type:"unsupported",feature:"speed",details:"Mistral speech models do not support the `speed` option. It was ignored."});if(R!=null)x.push({type:"unsupported",feature:"language",details:"Mistral speech models do not support the `language` option. Language is inferred from the input text and voice."});let V=j?.refAudio,X={model:this.modelId,input:m,voice_id:V==null?_:void 0,ref_audio:V,expressiveness:j?.expressiveness,phoneme_hints:j?.phonemeHints,response_format:N,stream:!1};return{requestBody:X,requestBodyValues:{...X,ref_audio:V==null?void 0:"[redacted]"},warnings:x}}async doGenerate(m){let _=this.config._internal?.currentDate?.()??new Date,{requestBody:P,requestBodyValues:A,warnings:v}=await this.getArgs(m),{value:R,responseHeaders:U,rawValue:x}=await we({url:`${this.config.baseURL}/audio/speech`,headers:d({"Content-Type":"application/json"},this.config.headers?.(),m.headers),body:{content:JSON.stringify(P),values:A},failedResponseHandler:ce,successfulResponseHandler:p(ut),abortSignal:m.abortSignal,fetch:this.config.fetch});return{audio:R.audio_data,warnings:v,request:{body:JSON.stringify(A)},response:{timestamp:_,modelId:this.modelId,headers:U,body:x}}}},ut=i(()=>s(t({audio_data:e()}))),dt=i(()=>s(t({language:e().min(1).optional(),returnLanguage:c().optional(),temperature:r().optional(),timestampGranularities:o(a(["segment","word"])).min(1).optional(),diarize:c().optional(),contextBias:o(e().min(1)).optional()}))),pt=class w{static[S](m){return M({modelId:m.modelId,config:m.config})}static[I](m){return new w(m.modelId,m.config)}get provider(){return this.config.provider}constructor(m,_){this.modelId=m,this.config=_,this.specificationVersion="v4"}async getArgs({audio:m,mediaType:_,providerOptions:P}){let A=[],v=await h({provider:"mistral",providerOptions:P,schema:dt});if(["voxtral-mini-2507","voxtral-mini-2602","voxtral-mini-latest"].includes(this.modelId)&&v?.language!=null&&v.timestampGranularities!=null)throw new b({argument:"providerOptions",message:"providerOptions.mistral.language cannot be combined with providerOptions.mistral.timestampGranularities"});if(v?.language!=null&&v.returnLanguage)throw new b({argument:"providerOptions",message:"providerOptions.mistral.language cannot be combined with providerOptions.mistral.returnLanguage"});let R=new FormData,U=m instanceof Uint8Array?new Blob([m]):new Blob([q(m)]);if(R.append("model",this.modelId),R.append("file",new File([U],"audio",{type:_}),`audio.${at(_)}`),v!=null)ue(R,"language",v.language),ue(R,"return_language",v.returnLanguage),ue(R,"temperature",v.temperature),ue(R,"timestamp_granularities",v.timestampGranularities),ue(R,"diarize",v.diarize),ue(R,"context_bias",v.contextBias);return{formData:R,warnings:A}}async doGenerate(m){let _=this.config._internal?.currentDate?.()??new Date,{formData:P,warnings:A}=await this.getArgs(m),{value:v,responseHeaders:R,rawValue:U}=await ne({url:`${this.config.baseURL}/audio/transcriptions`,headers:d(this.config.headers?.(),m.headers),formData:P,failedResponseHandler:ce,successfulResponseHandler:p(mt),abortSignal:m.abortSignal,fetch:this.config.fetch}),x=v.segments?.map((V)=>({text:V.text,startSecond:V.start,endSecond:V.end}))??[],j={};if(v.usage!=null)j.usage={...v.usage.prompt_tokens!=null&&{promptTokens:v.usage.prompt_tokens},...v.usage.completion_tokens!=null&&{completionTokens:v.usage.completion_tokens},...v.usage.total_tokens!=null&&{totalTokens:v.usage.total_tokens},...v.usage.prompt_audio_seconds!=null&&{promptAudioSeconds:v.usage.prompt_audio_seconds},...v.usage.request_count!=null&&{requestCount:v.usage.request_count}};let N=v.segments?.filter((V)=>V.type!=null||V.score!=null||V.speaker_id!=null).map((V)=>({text:V.text,startSecond:V.start,endSecond:V.end,...V.type!=null&&{type:V.type},...V.score!=null&&{score:V.score},...V.speaker_id!=null&&{speakerId:V.speaker_id}}));if(N!=null&&N.length>0)j.segments=N;return{text:v.text,segments:x,language:v.language??void 0,durationInSeconds:v.usage?.prompt_audio_seconds??x.at(-1)?.endSecond??void 0,warnings:A,...v.usage!=null&&{usage:v.usage},response:{timestamp:_,modelId:v.model,headers:R,body:U},...Object.keys(j).length>0&&{providerMetadata:{mistral:j}}}}};function ue(w,m,_){if(_==null)return;if(Array.isArray(_)){for(let P of _)w.append(m,P);return}w.append(m,String(_))}var mt=i(()=>s(t({model:e(),text:e(),language:e().nullish(),segments:o(t({type:n("transcription_segment").nullish(),text:e(),start:r(),end:r(),score:r().nullish(),speaker_id:e().nullish()})).nullish(),usage:t({prompt_tokens:r().nullish(),completion_tokens:r().nullish(),total_tokens:r().nullish(),prompt_audio_seconds:r().nullish(),request_count:r().nullish()}).nullish()}))),gt="4.0.74",Ae=i(()=>s(t({arguments:e()}))),Ne=i(()=>s(t({info:y(e(),F()).optional()}))),ht=k({id:"mistral.web_search",inputSchema:Ae,outputSchema:Ne}),ft=k({id:"mistral.web_search_premium",inputSchema:Ae,outputSchema:Ne}),yt=(w={})=>ht(w),bt=(w={})=>ft(w),vt={webSearch:yt,webSearchPremium:bt};function _e(w={}){let m=Y(w.baseURL)??"https://api.mistral.ai/v1",_=()=>L({Authorization:`Bearer ${he({apiKey:w.apiKey,environmentVariableName:"MISTRAL_API_KEY",description:"Mistral"})}`,...w.headers},`ai-sdk-mistral/${gt}`),P=(j)=>new ze(j,{provider:"mistral.chat",baseURL:m,headers:_,fetch:w.fetch,generateId:w.generateId}),A=(j)=>new it(j,{provider:"mistral.embedding",baseURL:m,headers:_,fetch:w.fetch}),v=(j)=>new Qe(j,{provider:"mistral.conversation",baseURL:m,headers:_,fetch:w.fetch,generateId:w.generateId}),R=(j)=>new ct(j,{provider:"mistral.speech",baseURL:m,headers:_,fetch:w.fetch}),U=(j)=>new pt(j,{provider:"mistral.transcription",baseURL:m,headers:_,fetch:w.fetch}),x=function(j){if(new.target)throw Error("The Mistral model function cannot be called with the new keyword.");return P(j)};return x.specificationVersion="v4",x.languageModel=P,x.chat=P,x.conversation=v,x.tools=vt,x.embedding=A,x.embeddingModel=A,x.textEmbedding=A,x.textEmbeddingModel=A,x.speech=R,x.speechModel=R,x.transcription=U,x.transcriptionModel=U,x.imageModel=(j)=>{throw new Ze({modelId:j,modelType:"imageModel"})},x}var St=_e();var _t=Ee(_e);function Mt(){oe("mistral",_t)}export{Mt as register};
@@ -1,5 +0,0 @@
1
- import{Ct}from"./embed-n7jskdxd.js";import{It}from"./embed-we24qtes.js";import{Ye,qt,Nt,Lt}from"./embed-2xm309sb.js";function M(e,n){let t=[...n].reverse().find((s)=>s.role==="user");return Ye(e)<12&&t?`${t.content} ${e}`:e}function w(e){let n=e.retriever??(e.index?It(e.index):null)??(()=>{throw Error("murmur: pass `index` or `retriever`.")})();return{retriever:n,async ask(t,{history:s=[],signal:u}={}){let i={};if(e.limit!==void 0)i.limit=e.limit;if(e.budgetTokens!==void 0)i.budgetTokens=e.budgetTokens;let o=await n.search(M(t,s),i),d=[e.instructions?.trim(),Nt(e.language),o.length?`Sources:
2
-
3
- ${qt(o)}`:"Sources: none matched this question. Say you could not find it on this site."].filter(Boolean).join(`
4
-
5
- `),g=[...s.slice(-(e.historyTurns??6)*2).map((r)=>({role:r.role,content:r.content})),{role:"user",content:t}],f=typeof e.model==="function"?await e.model():e.model,x=Ct({model:f,instructions:d,messages:g,onError:()=>{},...u?{abortSignal:u}:{}}),a="",c=()=>{},m=()=>{},l=new Promise((r,b)=>{c=r,m=b});l.catch(()=>{});async function*y(){try{for await(let r of x.stream){if(r.type==="error")throw r.error;if(r.type!=="text-delta")continue;a+=r.text,yield r.text}c({text:a,cited:Lt(a,o.length)})}catch(r){throw m(r),r}}return{passages:o,textStream:y(),done:l}}}}export{w as createMurmur};