murmur-rag 1.0.0 → 1.2.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 +27 -23
  2. package/dist/cdn/anthropic-ynz7717b.js +2 -0
  3. package/dist/cdn/chunk-hpx6rpea.js +1 -0
  4. package/dist/cdn/{embed-59r4jck6.js → embed-0m8xctqy.js} +3 -3
  5. package/dist/cdn/{embed-pnm9593k.js → embed-7pk91zq8.js} +2 -2
  6. package/dist/cdn/embed-dbkjhg16.js +83 -0
  7. package/dist/cdn/{embed-q6y6vgv1.js → embed-krrjjyf5.js} +4 -4
  8. package/dist/cdn/embed-n5nzhrf2.js +9 -0
  9. package/dist/cdn/{embed-hn0r8fmg.js → embed-rp9gb1qq.js} +2 -2
  10. package/dist/cdn/embed-xtkxyrpe.js +44 -0
  11. package/dist/cdn/google-k5kwa54v.js +14 -0
  12. package/dist/cdn/index-db4ne93m.js +1 -0
  13. package/dist/cdn/index-gyd02jvt.js +9 -0
  14. package/dist/cdn/index-qc8kgsdt.js +1 -0
  15. package/dist/cdn/index-t0qn2m4r.js +1 -0
  16. package/dist/cdn/index-y0faj89r.js +1 -0
  17. package/dist/cdn/mistral-p2qcnn42.js +3 -0
  18. package/dist/cdn/murmur-d6t6cjc7.js +5 -0
  19. package/dist/cdn/murmur.js +24 -5
  20. package/dist/cdn/openai-compatible-psnkrpxy.js +11 -0
  21. package/dist/cdn/openai-d3q1d6cz.js +18 -0
  22. package/dist/cdn/retriever-6qvn2maq.js +1 -0
  23. package/dist/cdn/transformers.web-xn16v7pz.js +46 -0
  24. package/dist/cli.js +2 -0
  25. package/dist/lib/chunks/{index-ynjdey8j.js → index-8h9c8ekq.js} +4 -2
  26. package/dist/lib/chunks/{index-6re28wc1.js → index-b77xqap3.js} +13 -1
  27. package/dist/lib/chunks/{index-10g918kt.js → index-p86sy3y4.js} +1 -1
  28. package/dist/lib/chunks/{index-4at214g0.js → index-y3v46yjp.js} +314 -27
  29. package/dist/lib/chunks/{murmur-c1c79eh8.js → murmur-t36hd4vt.js} +2 -2
  30. package/dist/lib/chunks/{retriever-h8nz6jsc.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 +2 -0
  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 +32 -1
  43. package/dist/types/widget/styles.d.ts +1 -1
  44. package/package.json +17 -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-hv290nbv.js +0 -9
  54. package/dist/cdn/index-kk9hgxdc.js +0 -1
  55. package/dist/cdn/mistral-16bekg8b.js +0 -3
  56. package/dist/cdn/murmur-bnm335nb.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-m8peqj5t.js +0 -1
@@ -0,0 +1,14 @@
1
+ import{oe,Ie}from"./embed-rp9gb1qq.js";import{et}from"./embed-0m8xctqy.js";import{m,b,P,me,u,e,r,c,v,Ae,o,t,U,l,y,i,n,G,k,T,d,Oe,ue,fe,ae,N,X,M,we,Yt,te,le,xe,ke,Z,F,Te,z,K,He,Me,tn,de,C,R,L,Ze,he,W,Se,it,ge,Q,a,s,j,J,h,g,ve,S,_,O,H,I,D,p,_e,E,Y}from"./embed-dbkjhg16.js";var zn="4.0.107",fn=()=>t({code:r().nullable(),message:e(),status:e(),details:o(v()).nullish()}),Jn=a(()=>s(t({error:fn()}))),Xe=I({errorSchema:Jn,errorToMessage:(f)=>f.error.message}),Yn=()=>l([t({text:e()}),t({inlineData:t({mimeType:e(),data:e()})}),t({fileData:t({fileUri:e(),mimeType:e()})})]),Xn=a(()=>s(t({outputDimensionality:r().optional(),taskType:i(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),content:o(o(Yn()).min(1).nullable()).optional()}))),Qn=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.specificationVersion="v4",this.maxEmbeddingsPerCall=100,this.supportsParallelCalls=!0,this[tn]=({providerOptions:A,values:q,startIndex:B,endIndex:re})=>{let ee=A?.google?.content;if(!Array.isArray(ee))return A;return zt({multimodalContent:ee,values:q}),{...A,google:{...A?.google,content:ee.slice(B,re)}}},this.modelId=w,this.config=x}async doEmbed({values:w,dimensions:x,headers:A,abortSignal:q,providerOptions:B}){let re=await h({provider:"google",providerOptions:B,schema:Xn});if(w.length>this.maxEmbeddingsPerCall)throw new me({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:w});let ee=d(this.config.headers?await _(this.config.headers):void 0,A),V=re?.content;if(zt({multimodalContent:V,values:w}),w.length===1){let Le=V?.[0],Ce=w[0]?[{text:w[0]}]:[],Ee=Le!=null?[...Ce,...Le]:[{text:w[0]}],{responseHeaders:je,value:Ne,rawValue:ye}=await g({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:ee,body:{model:`models/${this.modelId}`,content:{parts:Ee},outputDimensionality:re?.outputDimensionality??x,taskType:re?.taskType},failedResponseHandler:Xe,successfulResponseHandler:p(eo),abortSignal:q,fetch:this.config.fetch});return{warnings:[],embeddings:[Ne.embedding.values],usage:void 0,response:{headers:je,body:ye}}}let{responseHeaders:pe,value:ce,rawValue:Re}=await g({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:ee,body:{requests:w.map((Le,Ce)=>{let Ee=V?.[Ce],je=Le?[{text:Le}]:[];return{model:`models/${this.modelId}`,content:{role:"user",parts:Ee!=null?[...je,...Ee]:[{text:Le}]},outputDimensionality:re?.outputDimensionality??x,taskType:re?.taskType}})},failedResponseHandler:Xe,successfulResponseHandler:p(Zn),abortSignal:q,fetch:this.config.fetch});return{warnings:[],embeddings:ce.embeddings.map((Le)=>Le.values),usage:void 0,response:{headers:pe,body:Re}}}},Zn=a(()=>s(t({embeddings:o(t({values:o(r())}))}))),eo=a(()=>s(t({embedding:t({values:o(r())})})));function zt({multimodalContent:f,values:w}){if(f!=null&&f.length!==w.length)throw Error(`The number of multimodal content entries (${f.length}) must match the number of values (${w.length}).`)}function Tt(f){return f.includes("/")?f:`models/${f}`}function to({stream:f,getContinuationToken:w,continueStream:x}){let A=f.getReader(),q;return new ReadableStream({async pull(B){while(!0){let{done:re,value:ee}=await A.read();if(!re){if(ee.success){let pe=w(ee.value);if(pe!=null)q=pe}B.enqueue(ee);return}if(q==null){B.close();return}let V=q;q=void 0;try{A=(await x(V)).getReader(),B.enqueue({type:"continuation-start"});return}catch(pe){B.enqueue({success:!1,error:pe,rawValue:void 0}),B.close();return}}},async cancel(B){await A.cancel(B)}})}function Jt(f){if(f==null)return te();let w=f.promptTokenCount??0,x=f.candidatesTokenCount??0,A=f.toolUsePromptTokenCount??0,q=f.cachedContentTokenCount??0,B=f.thoughtsTokenCount??0,re=w+A;return{inputTokens:{total:re,noCache:re-q,cacheRead:q,cacheWrite:void 0},outputTokens:{total:x+B,text:x,reasoning:B},raw:f}}function jt(f,w){if(f==null||w==null)return w??f;return{...f,...w,promptTokenCount:vt(f.promptTokenCount,w.promptTokenCount),candidatesTokenCount:vt(f.candidatesTokenCount,w.candidatesTokenCount),toolUsePromptTokenCount:vt(f.toolUsePromptTokenCount,w.toolUsePromptTokenCount),totalTokenCount:vt(f.totalTokenCount,w.totalTokenCount),cachedContentTokenCount:vt(f.cachedContentTokenCount,w.cachedContentTokenCount),thoughtsTokenCount:vt(f.thoughtsTokenCount,w.thoughtsTokenCount),promptTokensDetails:kt(f.promptTokensDetails,w.promptTokensDetails),cacheTokensDetails:kt(f.cacheTokensDetails,w.cacheTokensDetails),candidatesTokensDetails:kt(f.candidatesTokensDetails,w.candidatesTokensDetails),toolUsePromptTokensDetails:kt(f.toolUsePromptTokensDetails,w.toolUsePromptTokensDetails)}}function vt(f,w){return f==null&&w==null?w??f:(f??0)+(w??0)}function kt(f,w){if(f==null||w==null)return w??f;let x=new Map;for(let{modality:A,tokenCount:q}of[...f,...w])x.set(A,(x.get(A)??0)+q);return Array.from(x,([A,q])=>({modality:A,tokenCount:q}))}var yn=t({language:e().describe("The programming language of the code."),code:e().describe("The code to be executed.")}),vn=t({outcome:e().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:e().describe("The output from the code execution.")}),no=S({id:"google.code_execution",inputSchema:yn,outputSchema:vn}),oo="skip_thought_signature_validator",io=/^data:([^;,]+);base64,(.+)$/s;function so(f){let w=io.exec(f);if(w==null)return;return{mediaType:w[1],data:w[2]}}function ao(f){let w=so(f);if(w==null)return;return{inlineData:{mimeType:w.mediaType,data:w.data}}}function Gt(f){if(Array.isArray(f))return f.some(Gt);if(typeof f!=="object"||f===null)return!1;return Object.entries(f).some(([w,x])=>w==="$ref"||Gt(x))}function Xt(f){return Gt(f)?JSON.stringify(f):f}function ro(f,w,x,A,q=!0,B={}){let re=[],ee=[];for(let V of x)switch(V.type){case"text":ee.push(V.text);break;case"file":if(V.data.type==="data")re.push({inlineData:{mimeType:O({part:V}),data:M(V.data.data)}});else if(V.data.type==="url"){let pe=V.data.url.toString(),ce=ao(pe),Re=V.data.url.protocol==="gs:"&&V.data.originalUrl!=null?V.data.originalUrl:pe;if(ce!=null)re.push(ce);else if(K(V.mediaType)&&Ze({url:Re,mediaType:V.mediaType,supportedUrls:B}))re.push({fileData:{mimeType:V.mediaType,fileUri:Re}});else ee.push(JSON.stringify(V))}else ee.push(JSON.stringify(V));break;default:ee.push(JSON.stringify(V))}f.push({functionResponse:{...q&&A!=null?{id:A}:{},name:w,response:{name:w,content:ee.length>0?ee.join(`
2
+ `):"Tool executed successfully."},...re.length>0?{parts:re}:{}}})}function lo(f,w,x,A,q=!0){for(let B of x)switch(B.type){case"text":f.push({functionResponse:{...q&&A!=null?{id:A}:{},name:w,response:{name:w,content:B.text}}});break;case"file":if(B.data.type==="data"){let re=z(B.mediaType);f.push({inlineData:{mimeType:O({part:B}),data:M(B.data.data)}},{text:`Tool executed successfully and returned this ${re==="image"?"image":"file"} as a response`})}else f.push({text:JSON.stringify(B)});break;default:f.push({text:JSON.stringify(B)})}}function uo(f,w){let x=[],A=[],q=!0,B=w?.isGemmaModel??!1,re=w?.isGemini3Model??!1,ee=w?.onWarning,V=w?.providerOptionsNames??["google"],pe=!V.includes("google"),ce=w?.supportsFunctionResponseParts??!0,Re=w?.includeFunctionCallIds??!0,Le=w?.supportedFunctionResponseUrls??{},Ce=!1,Ee=[],je=(ye)=>(Ee.push(ye),Ce=!0,oo),Ne=(ye)=>{for(let ie of V){let be=ye.providerOptions?.[ie];if(be!=null)return be}if(pe)return ye.providerOptions?.google;return ye.providerOptions?.googleVertex??ye.providerOptions?.vertex};for(let{role:ye,content:ie}of f)switch(ye){case"system":if(!q)throw new u({functionality:"system messages are only supported at the beginning of the conversation"});x.push({text:ie});break;case"user":{q=!1;let be=[];for(let ne of ie)switch(ne.type){case"text":be.push({text:ne.text});break;case"file":switch(ne.data.type){case"url":be.push({fileData:{mimeType:O({part:ne}),fileUri:ne.data.url.protocol==="gs:"&&ne.data.originalUrl!=null?ne.data.originalUrl:ne.data.url.toString()}});break;case"reference":if(pe)throw new u({functionality:"file parts with provider references"});be.push({fileData:{mimeType:O({part:ne}),fileUri:H({reference:ne.data.reference,provider:"google"})}});break;case"text":be.push({inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:M(new TextEncoder().encode(ne.data.text))}});break;case"data":be.push({inlineData:{mimeType:O({part:ne}),data:M(ne.data.data)}})}}A.push({role:"user",parts:be});break}case"assistant":{q=!1;let be=!1;A.push({role:"model",parts:ie.map((ne)=>{let se=Ne(ne),Ue=se?.thoughtSignature!=null?String(se.thoughtSignature):void 0;switch(ne.type){case"text":return ne.text.length===0?void 0:{text:ne.text,thoughtSignature:Ue};case"reasoning":return ne.text.length===0?void 0:{text:ne.text,thought:!0,thoughtSignature:Ue};case"reasoning-file":switch(ne.data.type){case"url":throw new u({functionality:"File data URLs in assistant messages are not supported"});case"data":return{inlineData:{mimeType:ne.mediaType,data:M(ne.data.data)},thought:!0,thoughtSignature:Ue}}break;case"file":switch(ne.data.type){case"url":throw new u({functionality:"File data URLs in assistant messages are not supported"});case"reference":if(pe)throw new u({functionality:"file parts with provider references"});return{fileData:{mimeType:ne.mediaType,fileUri:H({reference:ne.data.reference,provider:"google"})},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"text":return{inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:M(new TextEncoder().encode(ne.data.text))},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"data":return{inlineData:{mimeType:ne.mediaType,data:M(ne.data.data)},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue}}break;case"tool-call":{if(ne.providerExecuted===!0&&ne.toolName==="code_execution")return{executableCode:yn.parse(typeof ne.input==="string"?Q(ne.input):ne.input)};let De=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,qe=se?.serverToolType!=null?String(se.serverToolType):void 0,We=De!=null&&qe!=null,nt=Ue??(re&&!(!We&&Ue==null&&be)?je(ne.toolName):void 0);if(!We&&Ue!=null)be=!0;if(We)return{toolCall:{toolType:qe,args:typeof ne.input==="string"?Q(ne.input):ne.input,id:De},thoughtSignature:nt};return{functionCall:{...Re&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,args:ne.input},thoughtSignature:nt}}case"tool-result":{if(ne.toolName==="code_execution"&&ne.output.type==="json")return{codeExecutionResult:vn.parse(ne.output.value)};let De=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,qe=se?.serverToolType!=null?String(se.serverToolType):void 0;if(De&&qe)return{toolResponse:{toolType:qe,response:ne.output.type==="json"?ne.output.value:{},id:De},thoughtSignature:Ue};return}}}).filter((ne)=>ne!==void 0)});break}case"tool":{q=!1;let be=[];for(let ne of ie){if(ne.type==="tool-approval-response")continue;let se=Ne(ne),Ue=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,De=se?.serverToolType!=null?String(se.serverToolType):void 0;if(Ue&&De){let We=se?.thoughtSignature!=null?String(se.thoughtSignature):void 0;if(A.length>0){let nt=A[A.length-1];if(nt.role==="model"){nt.parts.push({toolResponse:{toolType:De,response:ne.output.type==="json"?ne.output.value:{},id:Ue},thoughtSignature:We});continue}}}let qe=ne.output;if(qe.type==="content")if(ce)ro(be,ne.toolName,qe.value,ne.toolCallId,Re,Le);else lo(be,ne.toolName,qe.value,ne.toolCallId,Re);else{let We=qe.type==="error-text"||qe.type==="error-json"||qe.type==="execution-denied";be.push({functionResponse:{...Re&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,response:{name:ne.toolName,...We?{error:qe.type==="execution-denied"?qe.reason??"Tool call execution denied.":Xt(qe.value)}:{content:Xt(qe.value)}}}})}}A.push({role:"user",parts:be});break}}if(B&&x.length>0&&A.length>0&&A[0].role==="user"){let ye=x.map((ie)=>ie.text).join(`
3
+
4
+ `);A[0].parts.unshift({text:ye+`
5
+
6
+ `})}if(Ce&&ee!=null){let ye=Array.from(new Set(Ee));ee({type:"other",message:`Replayed ${Ee.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${ye.map((ie)=>`\`${ie}\``).join(", ")}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`})}return{systemInstruction:x.length>0&&!B?{parts:x}:void 0,contents:A}}async function co(f,{abortSignal:w,maxBytes:x,supportedUrls:A={}}){let q=[];for(let B of f){if(B.role==="assistant"){let re=[];for(let ee of B.content)re.push(ee.type==="tool-result"?{...ee,output:await Qt(ee.output,{abortSignal:w,maxBytes:x,supportedUrls:A})}:ee);q.push({...B,content:re});continue}if(B.role==="tool"){let re=[];for(let ee of B.content){if(ee.type!=="tool-result"){re.push(ee);continue}re.push({...ee,output:await Qt(ee.output,{abortSignal:w,maxBytes:x,supportedUrls:A})})}q.push({...B,content:re});continue}q.push(B)}return q}async function Qt(f,{abortSignal:w,maxBytes:x,supportedUrls:A}){if(f.type!=="content")return f;let q=[];for(let B of f.value){if(B.type!=="file"||B.data.type!=="url"){q.push(B);continue}if(Ze({url:B.data.url.toString(),mediaType:B.mediaType,supportedUrls:A})){q.push(B);continue}let re=await Me(B.data.url.toString(),{abortSignal:w,maxBytes:x}),ee=new Uint8Array(await re.arrayBuffer()),V=Te({data:ee,topLevelType:"image"});q.push({...B,data:{type:"data",data:ee},mediaType:V??(re.type&&!K(B.mediaType)?re.type:B.mediaType)})}return{...f,value:q}}function bn(f){let{const:w,properties:x,items:A,additionalProperties:q,anyOf:B,oneOf:re,...ee}=f;return{...ee,...w!==void 0?{enum:[w]}:{},...x!=null?{properties:Zt(x)}:{},...A!=null?{items:Array.isArray(A)?A.map(bt):bt(A)}:{},...q!=null?{additionalProperties:typeof q==="boolean"?q:bt(q)}:{},...B!=null?{anyOf:B.map(bt)}:{},...re!=null?{oneOf:re.map(bt)}:{},...ee.$defs!=null?{$defs:Zt(ee.$defs)}:{}}}function Zt(f){return Object.fromEntries(Object.entries(f).map(([w,x])=>[w,bt(x)]))}function bt(f){return typeof f==="boolean"?f:bn(f)}var Et=a(()=>s(t({responseModalities:o(i(["TEXT","IMAGE","AUDIO"])).optional(),thinkingConfig:t({thinkingBudget:r().optional(),includeThoughts:c().optional(),thinkingLevel:i(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:e().optional(),structuredOutputs:c().optional(),safetySettings:o(t({category:i(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:i(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:i(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:c().optional(),labels:y(e(),e()).optional(),mediaResolution:i(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:t({aspectRatio:i(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).optional(),imageSize:i(["1K","2K","4K","512"]).optional(),personGeneration:i(["PERSON_GENERATION_UNSPECIFIED","ALLOW_ALL","ALLOW_ADULT","ALLOW_NONE"]).optional(),prominentPeople:i(["PROMINENT_PEOPLE_UNSPECIFIED","ALLOW_PROMINENT_PEOPLE","BLOCK_PROMINENT_PEOPLE"]).optional(),imageOutputOptions:t({mimeType:i(["image/jpeg","image/png"]).optional(),compressionQuality:r().optional()}).optional()}).optional(),retrievalConfig:t({latLng:t({latitude:r(),longitude:r()}).optional()}).optional(),streamFunctionCallArguments:c().optional(),serviceTier:i(["standard","flex","priority"]).optional(),continuationToken:e().optional(),sharedRequestType:i(["priority","flex","standard"]).optional(),requestType:i(["shared"]).optional()}))),po=/(^|[/.])gemini-1(?:[.-]|$)/i,go=/(^|[/.])gemini-2(?:[.-]|$)/i,ho=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,mo=/(^|[/.])gemini-/i;function fo(f){return po.test(f)||/(^|[/.])gemini-pro(?:-vision)?$/i.test(f)||/(^|[/.])gemini-robotics-er-1\.5(?:[.-]|$)/i.test(f)}function At(f){let w=mo.test(f),x=go.test(f),A=fo(f),q=w&&!(A||x);return{supportsGemini2Tools:w&&!A||f.toLowerCase().includes("nano-banana"),supportsFileSearch:ho.test(f)||q,usesGemini3Features:q}}function yo({tools:f,toolChoice:w,modelId:x,isVertexProvider:A=!1}){f=f?.length?f:void 0;let q=[],{supportsGemini2Tools:B,supportsFileSearch:re,usesGemini3Features:ee}=At(x);if(f==null)return{tools:void 0,toolConfig:void 0,toolWarnings:q};let V=f.some((Ce)=>Ce.type==="function"),pe=f.some((Ce)=>Ce.type==="provider");if(V&&pe&&!ee)q.push({type:"unsupported",feature:"combination of function and provider-defined tools"});if(pe){let Ce=[];if(f.filter((Ee)=>Ee.type==="provider").forEach((Ee)=>{switch(Ee.id){case"google.google_search":if(B)Ce.push({googleSearch:{...Ee.args}});else q.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":if(B)Ce.push({enterpriseWebSearch:{}});else q.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":if(B)Ce.push({urlContext:{}});else q.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(B)Ce.push({codeExecution:{}});else q.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The code execution tool is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":if(re)Ce.push({fileSearch:{...Ee.args}});else q.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":if(B)Ce.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:Ee.args.ragCorpus},similarity_top_k:Ee.args.topK}}});else q.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":if(B)Ce.push({googleMaps:{}});else q.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:q.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`})}}),V&&ee&&Ce.length>0){let Ee=[];for(let Ne of f)if(Ne.type==="function")Ee.push(en(Ne));let je={functionCallingConfig:{mode:"VALIDATED"},...!A&&{includeServerSideToolInvocations:!0}};if(w!=null)switch(w.type){case"auto":break;case"none":je.functionCallingConfig={mode:"NONE"};break;case"required":je.functionCallingConfig={mode:"ANY"};break;case"tool":je.functionCallingConfig={mode:"ANY",allowedFunctionNames:[w.toolName]}}return{tools:[...Ce,{functionDeclarations:Ee}],toolConfig:je,toolWarnings:q}}return{tools:Ce.length>0?Ce:void 0,toolConfig:void 0,toolWarnings:q}}let ce=[],Re=!1;for(let Ce of f)switch(Ce.type){case"function":if(ce.push(en(Ce)),Ce.strict===!0)Re=!0;break;default:q.push({type:"unsupported",feature:`function tool ${Ce.name}`})}if(w==null)return{tools:[{functionDeclarations:ce}],toolConfig:Re?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:q};let Le=w.type;switch(Le){case"auto":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:Re?"VALIDATED":"AUTO"}},toolWarnings:q};case"none":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:q};case"required":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:q};case"tool":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[w.toolName]}},toolWarnings:q};default:throw new u({functionality:`tool choice type: ${Le}`})}}function en(f){return{name:f.name,description:f.description??"",parametersJsonSchema:f.inputSchema}}var vo=class{constructor(){this.accumulatedArgs={},this.jsonText="",this.pathStack=[],this.stringOpen=!1}processPartialArgs(f){let w="";for(let x of f){let A=x.jsonPath.endsWith("[]"),q=(A?x.jsonPath.slice(0,-2):x.jsonPath).replace(/^\$\./,"");if(!q||q==="$")continue;let B=bo(q),re=_o(this.accumulatedArgs,B);if(x.stringValue!=null&&re!==void 0){let V=JSON.stringify(x.stringValue).slice(1,-1);Ut(this.accumulatedArgs,B,re+x.stringValue),w+=V;continue}let ee=Co(x);if(ee==null){if(re!==void 0||x.willContinue===!0)continue;Ut(this.accumulatedArgs,B,A?[]:{}),w+=this.emitContainer(B,A);continue}Ut(this.accumulatedArgs,B,ee.value),w+=this.emitNavigationTo(B,x,ee.json)}return this.jsonText+=w,{currentJSON:this.accumulatedArgs,textDelta:w}}finalize(){let f=JSON.stringify(this.accumulatedArgs);return{finalJSON:f,closingDelta:f.slice(this.jsonText.length)}}ensureRoot(){if(this.pathStack.length===0)return this.pathStack.push({segment:"",isArray:!1,childCount:0}),"{";return""}emitNavigationTo(f,w,x){let A="";if(this.stringOpen)A+='"',this.stringOpen=!1;A+=this.ensureRoot();let q=f.slice(0,-1),B=f[f.length-1],re=this.findCommonStackDepth(q);return A+=this.closeDownTo(re),A+=this.openDownTo(q,B),A+=this.emitLeaf(B,w,x),A}emitContainer(f,w){let x="";if(this.stringOpen)x+='"',this.stringOpen=!1;x+=this.ensureRoot();let A=this.findCommonStackDepth(f);return x+=this.closeDownTo(A),x+=this.openDownTo(f,w?0:""),x}findCommonStackDepth(f){let w=Math.min(this.pathStack.length-1,f.length),x=0;for(let A=0;A<w;A++)if(this.pathStack[A+1].segment===f[A])x++;else break;return x+1}closeDownTo(f){let w="";while(this.pathStack.length>f){let x=this.pathStack.pop();w+=x.isArray?"]":"}"}return w}openDownTo(f,w){let x="",A=this.pathStack.length-1;for(let q=A;q<f.length;q++){let B=f[q],re=this.pathStack[this.pathStack.length-1];if(re.childCount>0)x+=",";if(re.childCount++,typeof B==="string")x+=`${JSON.stringify(B)}:`;let ee=typeof(q+1<f.length?f[q+1]:w)==="number";x+=ee?"[":"{",this.pathStack.push({segment:B,isArray:ee,childCount:0})}return x}emitLeaf(f,w,x){let A="",q=this.pathStack[this.pathStack.length-1];if(q.childCount>0)A+=",";if(q.childCount++,typeof f==="string")A+=`${JSON.stringify(f)}:`;if(w.stringValue!=null&&w.willContinue)A+=x.slice(0,-1),this.stringOpen=!0;else A+=x;return A}};function bo(f){let w=[];for(let x of f.split(".")){let A=x.indexOf("[");if(A===-1)w.push(x);else{if(A>0)w.push(x.slice(0,A));for(let q of x.matchAll(/\[(\d+)\]/g))w.push(parseInt(q[1],10))}}return w}var To=Object.prototype.hasOwnProperty;function Tn(f,w){return To.call(f,w)}function nn(f,w,x){Object.defineProperty(f,w,{value:x,enumerable:!0,configurable:!0,writable:!0})}function _o(f,w){let x=f;for(let A of w){if(x==null||typeof x!=="object")return;let q=x;if(!Tn(q,A))return;x=q[A]}return x}function Ut(f,w,x){let A=f;for(let q=0;q<w.length-1;q++){let B=w[q],re=w[q+1];if(!Tn(A,B)||A[B]==null)nn(A,B,typeof re==="number"?[]:{});A=A[B]}nn(A,w[w.length-1],x)}function Co(f){let w=f.stringValue??f.numberValue??f.boolValue;if(w!=null)return{value:w,json:JSON.stringify(w)};if("nullValue"in f)return{value:null,json:"null"}}function on({finishReason:f,hasToolCalls:w}){switch(f){case"STOP":return w?"tool-calls":"stop";case"MAX_TOKENS":case"CONTINUATION":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";default:return"other"}}var wo=["HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT"],So=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,Io={"image/png":[/^gs:\/\/.*$/],"image/jpeg":[/^gs:\/\/.*$/],"image/webp":[/^gs:\/\/.*$/],"application/pdf":[/^gs:\/\/.*$/],"text/plain":[/^gs:\/\/.*$/]},Ct=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}constructor(w,x){this.specificationVersion="v4",this.modelId=w,this.config=x,this.generateId=x.generateId??C}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?.()??{}}static async prepareRequest({modelId:w,config:x,options:{prompt:A,maxOutputTokens:q,temperature:B,topP:re,topK:ee,frequencyPenalty:V,presencePenalty:pe,stopSequences:ce,responseFormat:Re,seed:Le,tools:Ce,toolChoice:Ee,reasoning:je,providerOptions:Ne,abortSignal:ye},isStreaming:ie=!1}){let be=[],ne=x.provider.includes("vertex")?["googleVertex","vertex"]:["google"],se;for(let at of ne)if(se=await h({provider:at,providerOptions:Ne,schema:Et}),se!=null)break;if(se==null&&!ne.includes("google"))se=await h({provider:"google",providerOptions:Ne,schema:Et});let Ue=x.provider.startsWith("google.vertex.");if(Ce?.some((at)=>at.type==="provider"&&at.id==="google.vertex_rag_store")&&!Ue)be.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${x.provider}).`});if(se?.streamFunctionCallArguments&&!Ue)be.push({type:"other",message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${x.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});if(se?.serviceTier&&Ue)be.push({type:"other",message:"'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo"});if((se?.sharedRequestType||se?.requestType)&&!Ue)be.push({type:"other",message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${x.provider}).`});let De=Ue&&(se?.sharedRequestType||se?.requestType)?{...se.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":se.sharedRequestType},...se.requestType&&{"X-Vertex-AI-LLM-Request-Type":se.requestType}}:void 0,qe=Ue?void 0:se?.serviceTier,We=se?.imageConfig;if(We!=null&&!Ue){let{personGeneration:at,prominentPeople:st,imageOutputOptions:wt,...St}=We,Ye=Object.entries({personGeneration:at,prominentPeople:st,imageOutputOptions:wt}).filter(([,Ge])=>Ge!=null).map(([Ge])=>`'imageConfig.${Ge}'`);if(Ye.length>0)be.push({type:"other",message:`${Ye.join(", ")} ${Ye.length===1?"is a Vertex AI option and is":"are Vertex AI options and are"} ignored with the current Google provider (${x.provider}).`}),We=St}let nt=w.toLowerCase().startsWith("gemma-"),Ke=!Ue&&So.test(w);if(Ke&&V!=null)be.push({type:"unsupported",feature:"frequencyPenalty"});if(Ke&&pe!=null)be.push({type:"unsupported",feature:"presencePenalty"});let{usesGemini3Features:Qe}=At(w),pt=Qe&&x.downloadToolResultFiles?.supportsGoogleCloudStorageUrls?Io:void 0,{contents:ze,systemInstruction:ot}=uo(x.downloadToolResultFiles?await co(A,{abortSignal:ye,maxBytes:x.downloadToolResultFiles.maxBytes,supportedUrls:pt}):A,{isGemmaModel:nt,isGemini3Model:Qe,onWarning:(at)=>be.push(at),providerOptionsNames:ne,supportsFunctionResponseParts:Qe,includeFunctionCallIds:!Ue,supportedFunctionResponseUrls:pt}),{tools:Ve,toolConfig:rt,toolWarnings:lt}=yo({tools:Ce,toolChoice:Ee,modelId:w,isVertexProvider:Ue}),dt=le({tools:Ce,providerToolNames:{"google.code_execution":"code_execution"}}),Fe=se?.thinkingConfig?.thinkingBudget!=null||se?.thinkingConfig?.thinkingLevel!=null?void 0:Ro({reasoning:je,modelId:w,warnings:be}),tt=se?.thinkingConfig||Fe?{...Fe,...se?.thinkingConfig}:void 0,Je=ie&&Ue?se?.streamFunctionCallArguments??!1:void 0,Be=se?.threshold,Pe=se?.safetySettings??(Be!=null?wo.map((at)=>({category:at,threshold:Be})):void 0),ut=rt||Je||se?.retrievalConfig?{...rt,...Je&&{functionCallingConfig:{...rt?.functionCallingConfig,streamFunctionCallArguments:!0}},...se?.retrievalConfig&&{retrievalConfig:se.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:q,temperature:B,topK:ee,topP:re,frequencyPenalty:Ke?void 0:V,presencePenalty:Ke?void 0:pe,stopSequences:ce,seed:Le,responseMimeType:Re?.type==="json"?"application/json":void 0,responseJsonSchema:Re?.type==="json"&&Re.schema!=null&&(se?.structuredOutputs??!0)?bn(Re.schema):void 0,...se?.audioTimestamp&&{audioTimestamp:se.audioTimestamp},responseModalities:se?.responseModalities,thinkingConfig:tt,...se?.mediaResolution&&{mediaResolution:se.mediaResolution},...We&&{imageConfig:We}},contents:ze,systemInstruction:nt?void 0:ot,safetySettings:Pe,tools:Ve,toolConfig:ut,cachedContent:se?.cachedContent,labels:se?.labels,serviceTier:qe,...se?.continuationToken!=null&&{continuationToken:se.continuationToken}},warnings:[...be,...lt],providerOptionsNames:ne,extraHeaders:De,toolNameMapping:dt}}async getArgs(w,{isStreaming:x=!1}={}){let{responseFormat:A,tools:q,toolChoice:B}=w,re;if(A?.type==="json"&&A.schema!=null&&q?.some((ee)=>ee.type==="function")&&/(^|\/)gemini-/i.test(this.modelId)&&(!At(this.modelId).usesGemini3Features||B?.type==="required"||B?.type==="tool")){let ee="json";for(let V=1;q.some((pe)=>pe.name===ee);V++)ee=`json_${V}`;re={type:"function",name:ee,description:A.description??"Respond with a JSON object.",inputSchema:A.schema}}return{...await f.prepareRequest({modelId:this.modelId,config:this.config,options:re==null?w:{...w,responseFormat:void 0,tools:[...q??[],re],toolChoice:B?.type==="tool"?B:B?.type==="none"?{type:"tool",toolName:re.name}:{type:"required"}},isStreaming:x}),jsonResponseToolName:re?.name}}static convertGenerateContentResponse({config:w,response:x,warnings:A,providerOptionsNames:q,toolNameMapping:B,jsonResponseToolName:re,initialPromptTokenCount:ee,groundingMetadataPerRequest:V}){let pe=(se)=>Object.fromEntries(q.map((Ue)=>[Ue,se])),ce=x.candidates?.[0],Re=x.promptFeedback?.blockReason,Le=an(Re)?Re:void 0,Ce=ce?.finishReason==null&&Le!=null,Ee=ce?.finishReason??Le,je=[],Ne=ce?.content?.parts??[],ye=x.usageMetadata,ie,be;for(let se of Ne)if("executableCode"in se&&se.executableCode?.code){let Ue=w.generateId();ie=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:B?.toCustomToolName("code_execution")??"code_execution",input:JSON.stringify(se.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in se&&se.codeExecutionResult)je.push({type:"tool-result",toolCallId:ie,toolName:B?.toCustomToolName("code_execution")??"code_execution",result:{outcome:se.codeExecutionResult.outcome,output:se.codeExecutionResult.output??""}});else if("text"in se&&se.text!=null){if(re!=null&&se.thought!==!0)continue;let Ue=se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature}):void 0;if(se.text.length===0){if(Ue!=null&&je.length>0){let De=je[je.length-1];De.providerMetadata=Ue}}else je.push({type:se.thought===!0?"reasoning":"text",text:se.text,providerMetadata:Ue})}else if("functionCall"in se&&se.functionCall.name!=null){if(se.functionCall.name===re){je.push({type:"text",text:typeof se.functionCall.args==="string"?se.functionCall.args:JSON.stringify(se.functionCall.args??{}),...se.thoughtSignature?{providerMetadata:pe({thoughtSignature:se.thoughtSignature})}:{}});continue}je.push({type:"tool-call",toolCallId:se.functionCall.id||w.generateId(),toolName:se.functionCall.name,input:JSON.stringify(se.functionCall.args??{}),providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature}):void 0})}else if("inlineData"in se){let Ue=se.thought===!0,De=!!se.thoughtSignature;je.push({type:Ue?"reasoning-file":"file",data:{type:"data",data:se.inlineData.data},mediaType:se.inlineData.mimeType,providerMetadata:De?pe({thoughtSignature:se.thoughtSignature}):void 0})}else if("toolCall"in se&&se.toolCall){let Ue=se.toolCall.id||w.generateId();be=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:`server:${se.toolCall.toolType}`,input:JSON.stringify(se.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature,serverToolCallId:Ue,serverToolType:se.toolCall.toolType}):pe({serverToolCallId:Ue,serverToolType:se.toolCall.toolType})})}else if("toolResponse"in se&&se.toolResponse){let Ue=be||se.toolResponse.id||w.generateId();je.push({type:"tool-result",toolCallId:Ue,toolName:`server:${se.toolResponse.toolType}`,result:se.toolResponse.response??{},providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature,serverToolCallId:Ue,serverToolType:se.toolResponse.toolType}):pe({serverToolCallId:Ue,serverToolType:se.toolResponse.toolType})}),be=void 0}let ne=sn({groundingMetadata:ce?.groundingMetadata,generateId:w.generateId})??[];for(let se of ne)je.push(se);return{content:je,finishReason:{unified:Ce?"content-filter":on({finishReason:Ee,hasToolCalls:je.some((se)=>se.type==="tool-call"&&!se.providerExecuted)}),raw:Ee},usage:Jt(ye),warnings:A,providerMetadata:pe({promptFeedback:x.promptFeedback??null,groundingMetadata:ce?.groundingMetadata??null,...V!=null?{groundingMetadataPerRequest:V}:{},urlContextMetadata:ce?.urlContextMetadata??null,safetyRatings:ce?.safetyRatings??null,usageMetadata:ye??null,finishMessage:ce?.finishMessage??null,serviceTier:ye?.serviceTier??null,...ce?.continuationToken!=null?{continuationToken:ce.continuationToken}:{},...ee!=null?{initialPromptTokenCount:ee}:{}}),response:{id:x.responseId??void 0}}}async doGenerate(w){let{args:x,warnings:A,providerOptionsNames:q,extraHeaders:B,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(w),V=d(this.config.headers?await _(this.config.headers):void 0,w.headers,B),pe=(ne)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:generateContent`,headers:V,body:ne,failedResponseHandler:Xe,successfulResponseHandler:p(In),abortSignal:w.abortSignal,fetch:this.config.fetch}),{responseHeaders:ce,value:Re,rawValue:Le}=await pe(x),Ce=[],Ee=[],je,Ne=Re.usageMetadata?.promptTokenCount,ye=!1;while(!0){let ne=Re.candidates?.[0];Ee.push(ne?.groundingMetadata??null);let se=ne?.finishReason==="CONTINUATION"?ne.continuationToken:void 0;if(je=jt(je,Re.usageMetadata??void 0),se==null)break;Ce.push(...f.convertGenerateContentResponse({config:this.config,response:Re,warnings:A,providerOptionsNames:q,toolNameMapping:re,jsonResponseToolName:ee}).content),ye=!0,{responseHeaders:ce,value:Re,rawValue:Le}=await pe({...x,continuationToken:se})}let ie=f.convertGenerateContentResponse({config:this.config,response:{...Re,usageMetadata:je},warnings:A,providerOptionsNames:q,toolNameMapping:re,jsonResponseToolName:ee,initialPromptTokenCount:ye?Ne:void 0,groundingMetadataPerRequest:ye?Ee:void 0}),be={...ie,content:[...Ce,...ie.content]};return{...be,request:{body:x},response:{...be.response,headers:ce,body:Le}}}async doStream(w){let{args:x,warnings:A,providerOptionsNames:q,extraHeaders:B,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(w,{isStreaming:!0}),V=(Be)=>Object.fromEntries(q.map((Pe)=>[Pe,Be])),pe=d(this.config.headers?await _(this.config.headers):void 0,w.headers,B),ce=(Be)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:streamGenerateContent?alt=sse`,headers:pe,body:Be,failedResponseHandler:Xe,successfulResponseHandler:D(Lo),abortSignal:w.abortSignal,fetch:this.config.fetch}),{responseHeaders:Re,value:Le}=await ce(x),Ce=[],Ee=null,je=to({stream:Le,getContinuationToken:(Be)=>{let Pe=Be.candidates?.[0];if(Pe?.groundingMetadata!=null)Ee=Pe.groundingMetadata;return Pe?.finishReason==="CONTINUATION"?Pe.continuationToken??void 0:void 0},continueStream:async(Be)=>{let{value:Pe}=await ce({...x,continuationToken:Be});return Ce.push(Ee),Ee=null,Pe}}),Ne={unified:"interrupted",raw:void 0},ye=void 0,ie=void 0,be=void 0,ne=null,se=null,Ue=null,De=null,qe=null,We=null,nt,Ke=this.config.generateId,Qe=!1,pt=!1,ze=null,ot=null,Ve=0,rt=new Set,lt,dt,Fe=[],tt=(Be)=>{let Pe=Fe.pop();if(Pe==null)return;let{finalJSON:ut,closingDelta:at}=Pe.accumulator.finalize();if(at.length>0)Be.enqueue({type:"tool-input-delta",id:Pe.toolCallId,delta:at,providerMetadata:Pe.providerMetadata});Be.enqueue({type:"tool-input-end",id:Pe.toolCallId,providerMetadata:Pe.providerMetadata}),Be.enqueue({type:"tool-call",toolCallId:Pe.toolCallId,toolName:Pe.toolName,input:ut,providerMetadata:Pe.providerMetadata}),Qe=!0},Je={stream:je.pipeThrough(new TransformStream({start(Be){Be.enqueue({type:"stream-start",warnings:A})},transform(Be,Pe){if("type"in Be){Ne={unified:"interrupted",raw:void 0};return}if(w.includeRawChunks)Pe.enqueue({type:"raw",rawValue:Be.rawValue});if(!Be.success){if(Ne.unified==="interrupted")Ne={unified:"error",raw:void 0};Pe.enqueue({type:"error",error:Be.error});return}let ut=Be.value;if(ut.error!=null){Ne={unified:"error",raw:void 0};let Ye=ut.error;Pe.enqueue({type:"error",error:xe({message:Ye.message,type:Ye.status,code:Ye.code??void 0,statusCode:Ye.code??void 0,isRetryable:Ye.code!=null&&(Ye.code===408||Ye.code===409||Ye.code===429||Ye.code>=500),data:Ye})});return}if(!pt&&ut.responseId!=null)pt=!0,Pe.enqueue({type:"response-metadata",id:ut.responseId});let at=ut.usageMetadata;if(at!=null)ye=at;if(ut.promptFeedback!=null&&nt==null){if(ne=ut.promptFeedback,an(ut.promptFeedback.blockReason))nt=ut.promptFeedback.blockReason,Ne={unified:"content-filter",raw:nt}}let st=ut.candidates?.[0];if(st!=null){if(st.groundingMetadata!=null)se=st.groundingMetadata;if(st.urlContextMetadata!=null)Ue=st.urlContextMetadata;if(st.safetyRatings!=null)De=st.safetyRatings;if(st.finishMessage!=null)qe=st.finishMessage;if(st.continuationToken!=null)We=st.continuationToken}if(nt!=null||st==null)return;let wt=st.content,St=sn({groundingMetadata:st.groundingMetadata,generateId:Ke});if(St!=null){for(let Ye of St)if(Ye.sourceType==="url"&&!rt.has(Ye.url))rt.add(Ye.url),Pe.enqueue(Ye)}if(wt!=null){let Ye=wt.parts??[];for(let Ge of Ye)if("executableCode"in Ge&&Ge.executableCode?.code){let $e=Ke();lt=$e,Pe.enqueue({type:"tool-call",toolCallId:$e,toolName:re.toCustomToolName("code_execution"),input:JSON.stringify(Ge.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in Ge&&Ge.codeExecutionResult){let $e=lt;if($e)Pe.enqueue({type:"tool-result",toolCallId:$e,toolName:re.toCustomToolName("code_execution"),result:{outcome:Ge.codeExecutionResult.outcome,output:Ge.codeExecutionResult.output??""}})}else if("text"in Ge&&Ge.text!=null){let $e=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0;if(Ge.text.length===0){if($e!=null&&ze!==null)Pe.enqueue({type:"text-delta",id:ze,delta:"",providerMetadata:$e})}else if(Ge.thought===!0){if(ze!==null)Pe.enqueue({type:"text-end",id:ze}),ze=null;if(ot===null)ot=String(Ve++),Pe.enqueue({type:"reasoning-start",id:ot,providerMetadata:$e});Pe.enqueue({type:"reasoning-delta",id:ot,delta:Ge.text,providerMetadata:$e})}else{if(ot!==null)Pe.enqueue({type:"reasoning-end",id:ot}),ot=null;if(ze===null)ze=String(Ve++),Pe.enqueue({type:"text-start",id:ze,providerMetadata:$e});Pe.enqueue({type:"text-delta",id:ze,delta:Ge.text,providerMetadata:$e})}}else if("inlineData"in Ge){if(ze!==null)Pe.enqueue({type:"text-end",id:ze}),ze=null;if(ot!==null)Pe.enqueue({type:"reasoning-end",id:ot}),ot=null;let $e=Ge.thought===!0,yt=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0;Pe.enqueue({type:$e?"reasoning-file":"file",mediaType:Ge.inlineData.mimeType,data:{type:"data",data:Ge.inlineData.data},providerMetadata:yt})}else if("toolCall"in Ge&&Ge.toolCall){let $e=Ge.toolCall.id||Ke();dt=$e;let yt=V({...Ge.thoughtSignature?{thoughtSignature:Ge.thoughtSignature}:{},serverToolCallId:$e,serverToolType:Ge.toolCall.toolType});Pe.enqueue({type:"tool-call",toolCallId:$e,toolName:`server:${Ge.toolCall.toolType}`,input:JSON.stringify(Ge.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:yt})}else if("toolResponse"in Ge&&Ge.toolResponse){let $e=dt||Ge.toolResponse.id||Ke(),yt=V({...Ge.thoughtSignature?{thoughtSignature:Ge.thoughtSignature}:{},serverToolCallId:$e,serverToolType:Ge.toolResponse.toolType});Pe.enqueue({type:"tool-result",toolCallId:$e,toolName:`server:${Ge.toolResponse.toolType}`,result:Ge.toolResponse.response??{},providerMetadata:yt}),dt=void 0}for(let Ge of Ye){if(!("functionCall"in Ge))continue;let $e=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0,yt=Ge.functionCall.partialArgs!=null||Ge.functionCall.name!=null&&Ge.functionCall.willContinue===!0,Hn=Ge.functionCall.name==null&&Ge.functionCall.args==null&&Ge.functionCall.partialArgs==null&&Ge.functionCall.willContinue==null,Vn=Ge.functionCall.name!=null&&Ge.functionCall.args!=null&&Ge.functionCall.partialArgs==null,Wn=Ge.functionCall.name!=null&&Ge.functionCall.args==null&&Ge.functionCall.partialArgs==null&&Ge.functionCall.willContinue!==!0;if(yt){if(Ge.functionCall.name!=null){let ct=Ge.functionCall.id||Ke(),gt=new vo;if(Fe.push({toolCallId:ct,toolName:Ge.functionCall.name,accumulator:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-start",id:ct,toolName:Ge.functionCall.name,providerMetadata:$e}),Ge.functionCall.partialArgs!=null){let ft=Ge.functionCall.partialArgs,{textDelta:It}=gt.processPartialArgs(ft);if(It.length>0)Pe.enqueue({type:"tool-input-delta",id:ct,delta:It,providerMetadata:$e});if(Ge.functionCall.willContinue!==!0&&ft.every((Kn)=>Kn.willContinue!==!0))tt(Pe)}}else if(Ge.functionCall.partialArgs!=null&&Fe.length>0){let ct=Fe[Fe.length-1],gt=Ge.functionCall.partialArgs,{textDelta:ft}=ct.accumulator.processPartialArgs(gt);if(ft.length>0)Pe.enqueue({type:"tool-input-delta",id:ct.toolCallId,delta:ft,providerMetadata:$e});if(Ge.functionCall.willContinue!==!0&&gt.every((It)=>It.willContinue!==!0))tt(Pe)}}else if(Hn&&Fe.length>0)tt(Pe);else if(Vn){let ct=Ge.functionCall.id||Ke(),gt=Ge.functionCall.name,ft=typeof Ge.functionCall.args==="string"?Ge.functionCall.args:JSON.stringify(Ge.functionCall.args??{});Pe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-delta",id:ct,delta:ft,providerMetadata:$e}),Pe.enqueue({type:"tool-input-end",id:ct,providerMetadata:$e}),Pe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:ft,providerMetadata:$e}),Qe=!0}else if(Wn){let ct=Ge.functionCall.id||Ke(),gt=Ge.functionCall.name;Pe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-end",id:ct,providerMetadata:$e}),Pe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:"{}",providerMetadata:$e}),Qe=!0}}}if(st.finishReason==="CONTINUATION"){if(ie==null)be=ye?.promptTokenCount;ie=jt(ie,ye),ye=void 0}if(st.finishReason!=null)Ne={unified:on({finishReason:st.finishReason,hasToolCalls:Qe}),raw:st.finishReason}},flush(Be){if(ye=jt(ie,ye),ze!==null)Be.enqueue({type:"text-end",id:ze});if(ot!==null)Be.enqueue({type:"reasoning-end",id:ot});Be.enqueue({type:"finish",finishReason:Ne,usage:Jt(ye),providerMetadata:V({promptFeedback:ne,groundingMetadata:se,...Ce.length>0?{groundingMetadataPerRequest:[...Ce,Ee]}:{},urlContextMetadata:Ue,safetyRatings:De,usageMetadata:ye??null,finishMessage:qe,serviceTier:ye?.serviceTier??null,...We!=null&&(Ne.raw==="MAX_TOKENS"||Ne.raw==="CONTINUATION")?{continuationToken:We}:{},...be!=null?{initialPromptTokenCount:be}:{}})})}})),response:{headers:Re},request:{body:x}};return{...Je,stream:ee==null?Je.stream:Je.stream.pipeThrough(Yt(ee))}}};function ko(){return 65536}function xo(f){let w=f.toLowerCase();if(w.includes("2.5-pro")||w.includes("gemini-3-pro-image"))return 32768;return 24576}function Ro({reasoning:f,modelId:w,warnings:x}){if(!W(f))return;if(At(w).usesGemini3Features&&!w.includes("gemini-3-pro-image"))return Oo({reasoning:f,modelId:w,warnings:x});return Eo({reasoning:f,modelId:w,warnings:x})}function Oo({reasoning:f,modelId:w,warnings:x}){let A=Mo(w);if(f==="none")return{thinkingLevel:A};let q=Se({reasoning:f,effortMap:{minimal:A,low:"low",medium:"medium",high:"high",xhigh:"high",max:"high"},warnings:x});if(q==null)return;return{thinkingLevel:q}}function Mo(f){let w=/(?:^|[/.])(gemini-[^/]*)$/i.exec(f)?.[1].toLowerCase();if(w==="gemini-flash-latest")return"low";let x=/^gemini-(\d+)(?:\.\d+)?-pro(?:$|-)/.exec(w??"");if(Number(x?.[1])>=3)return"low";let A=/^gemini-(\d+)\.(\d+)-flash(?:$|-(?!lite(?:-|$)))/.exec(w??"");if(A==null)return"minimal";let q=Number(A[1]),B=Number(A[2]);return q>3||q===3&&B>=7?"low":"minimal"}function Eo({reasoning:f,modelId:w,warnings:x}){if(f==="none")return{thinkingBudget:0};let A=it({reasoning:f,maxOutputTokens:ko(),maxReasoningBudget:xo(w),minReasoningBudget:0,warnings:x});if(A==null)return;return{thinkingBudget:A}}function sn({groundingMetadata:f,generateId:w}){if(!f?.groundingChunks)return;let x=[];for(let A of f.groundingChunks)if(A.web!=null)x.push({type:"source",sourceType:"url",id:w(),url:A.web.uri,title:A.web.title??void 0});else if(A.image!=null)x.push({type:"source",sourceType:"url",id:w(),url:A.image.sourceUri,title:A.image.title??void 0});else if(A.retrievedContext!=null){let q=A.retrievedContext.uri,B=A.retrievedContext.fileSearchStore;if(q&&(q.startsWith("http://")||q.startsWith("https://")))x.push({type:"source",sourceType:"url",id:w(),url:q,title:A.retrievedContext.title??void 0});else if(q){let re=A.retrievedContext.title??"Unknown Document",ee="application/octet-stream",V=void 0;if(q.endsWith(".pdf"))ee="application/pdf",V=q.split("/").pop();else if(q.endsWith(".txt"))ee="text/plain",V=q.split("/").pop();else if(q.endsWith(".docx"))ee="application/vnd.openxmlformats-officedocument.wordprocessingml.document",V=q.split("/").pop();else if(q.endsWith(".doc"))ee="application/msword",V=q.split("/").pop();else if(q.match(/\.(md|markdown)$/))ee="text/markdown",V=q.split("/").pop();else V=q.split("/").pop();x.push({type:"source",sourceType:"document",id:w(),mediaType:ee,title:re,filename:V})}else if(B){let re=A.retrievedContext.title??"Unknown Document";x.push({type:"source",sourceType:"document",id:w(),mediaType:"application/octet-stream",title:re,filename:B.split("/").pop()})}}else if(A.maps!=null){if(A.maps.uri)x.push({type:"source",sourceType:"url",id:w(),url:A.maps.uri,title:A.maps.title??void 0})}return x.length>0?x:void 0}var _n=()=>t({webSearchQueries:o(e()).nullish(),imageSearchQueries:o(e()).nullish(),retrievalQueries:o(e()).nullish(),searchEntryPoint:t({renderedContent:e()}).nullish(),groundingChunks:o(t({web:t({uri:e(),title:e().nullish()}).nullish(),image:t({sourceUri:e(),imageUri:e(),title:e().nullish(),domain:e().nullish()}).nullish(),retrievedContext:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),fileSearchStore:e().nullish(),customMetadata:o(t({key:e(),stringValue:e().nullish(),numericValue:r().nullish(),stringListValue:t({values:o(e()).nullish()}).nullish()})).nullish()}).nullish(),maps:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),placeId:e().nullish()}).nullish()})).nullish(),groundingSupports:o(t({segment:t({startIndex:r().nullish(),endIndex:r().nullish(),text:e().nullish()}).nullish(),segment_text:e().nullish(),groundingChunkIndices:o(r()).nullish(),supportChunkIndices:o(r()).nullish(),confidenceScores:o(r()).nullish(),confidenceScore:o(r()).nullish()})).nullish(),retrievalMetadata:l([t({webDynamicRetrievalScore:r()}),t({})]).nullish()}),Ao=()=>t({jsonPath:e(),stringValue:e().nullish(),numberValue:r().nullish(),boolValue:c().nullish(),nullValue:v().nullish(),willContinue:c().nullish()}),Cn=()=>t({parts:o(l([t({functionCall:t({id:e().nullish(),name:e().nullish(),args:v().nullish(),partialArgs:o(Ao()).nullish(),willContinue:c().nullish()}),thoughtSignature:e().nullish()}),t({inlineData:t({mimeType:e(),data:e()}),thought:c().nullish(),thoughtSignature:e().nullish()}),t({toolCall:t({toolType:e(),args:v().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({toolResponse:t({toolType:e(),response:v().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({executableCode:t({language:e(),code:e()}).nullish(),codeExecutionResult:t({outcome:e(),output:e().nullish()}).nullish(),text:e().nullish(),thought:c().nullish(),thoughtSignature:e().nullish()})])).nullish()}),Lt=()=>t({category:e().nullish(),probability:e().nullish(),probabilityScore:r().nullish(),severity:e().nullish(),severityScore:r().nullish(),blocked:c().nullish()}),xt=()=>o(t({modality:e(),tokenCount:r()}).loose()).nullish(),wn=()=>t({cachedContentTokenCount:r().nullish(),thoughtsTokenCount:r().nullish(),promptTokenCount:r().nullish(),candidatesTokenCount:r().nullish(),toolUsePromptTokenCount:r().nullish(),totalTokenCount:r().nullish(),trafficType:e().nullish(),serviceTier:e().nullish(),promptTokensDetails:xt(),cacheTokensDetails:xt(),candidatesTokensDetails:xt(),toolUsePromptTokensDetails:xt()}).loose(),Sn=()=>t({urlMetadata:o(t({retrievedUrl:e(),urlRetrievalStatus:e()})).nullish()}),In=a(()=>s(t({responseId:e().nullish(),candidates:o(t({content:Cn().nullish().or(t({}).strict()),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(Lt()).nullish(),groundingMetadata:_n().nullish(),urlContextMetadata:Sn().nullish()})).nullish(),usageMetadata:wn().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(Lt()).nullish()}).nullish()}))),Lo=a(()=>s(t({error:fn().nullish(),responseId:e().nullish(),candidates:o(t({content:Cn().nullish(),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(Lt()).nullish(),groundingMetadata:_n().nullish(),urlContextMetadata:Sn().nullish()})).nullish(),usageMetadata:wn().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(Lt()).nullish()}).nullish()})));function an(f){return f!=null&&f!==""&&f!=="BLOCK_REASON_UNSPECIFIED"&&f!=="BLOCKED_REASON_UNSPECIFIED"}var jo=()=>U({searchTypes:t({webSearch:t({}).optional(),imageSearch:t({}).optional()}).optional(),timeRangeFilter:t({startTime:e(),endTime:e()}).optional()}),Uo=S({id:"google.google_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),kn=a(()=>s(t({googleSearch:jo().optional()}))),No=2147483648,Go=20000000,Do=new Set(["text","reasoning","source","tool-call","tool-result"]);function Po(f){for(let w of f){let x=w.type;if(x!=="text"&&x!=="image")throw new u({functionality:`batch request type: ${x}`,message:`The Google Batch API does not support batch requests with type "${x}".`})}}var Bt=()=>t({code:l([r(),e()]).nullish(),message:e().nullish(),status:e().nullish()}),qo=()=>t({requestCount:l([e(),r()]).nullish(),successfulRequestCount:l([e(),r()]).nullish(),failedRequestCount:l([e(),r()]).nullish(),pendingRequestCount:l([e(),r()]).nullish()}),rn=()=>t({responsesFile:e().nullish(),inlinedResponses:t({inlinedResponses:o(t({metadata:t({key:e()}),response:v().nullish(),error:Bt().nullish()}))}).nullish()}),xn=()=>t({name:e(),metadata:t({state:e().nullish(),createTime:e().nullish(),batchStats:qo().nullish(),output:rn().nullish()}).nullish(),done:c().nullish(),error:Bt().nullish(),response:rn().nullish()}),Nt=a(()=>s(xn())),$o=a(()=>s(t({operations:o(xn()).nullish(),nextPageToken:e().nullish()}))),Fo=a(()=>s(t({}))),Bo=a(()=>s(t({file:t({name:e(),expirationTime:e().nullish()})}))),Ho=a(()=>s(t({key:e(),response:v().nullish(),error:Bt().nullish()}))),Vo=a(()=>s(t({candidates:o(v()).nullish(),promptFeedback:t({blockReason:e().nullish()}).nullish()}))),Wo=class{constructor(f){this.specificationVersion="v4",this.provider=f.provider,this.batchConfig=f.config,this.supportedUrls=f.supportedUrls,this.batchGenerateId=f.config.generateId??C,this.maxLineBytes=f.maxLineBytes}async doStartBatch(f){Po(f.requests);let w=Yo(f.requests),x=[],A=`ai-sdk-batch-${this.batchGenerateId()}`,q=[],B={batch:{displayName:A,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{requests:{requests:q}}}},re=new TextEncoder,ee=re.encode(JSON.stringify(B)).byteLength,V;for(let je of f.requests){let Ne=je.type==="text"?await Ct.prepareRequest({modelId:je.modelId,config:this.batchConfig,options:je.options}):await this.prepareImageRequest(je),ye={request:Ne.args,metadata:{key:je.id}};if(V==null){let ie=re.encode(JSON.stringify(ye)).byteLength,be=ee+ie+(q.length>0?1:0);if(be<Go)q.push(ye),ee=be;else{V=[];for(let ne of q)V.push(JSON.stringify({key:ne.metadata.key,request:ne.request}),`
7
+ `);q.length=0,V.push(JSON.stringify({key:je.id,request:Ne.args}),`
8
+ `)}}else V.push(JSON.stringify({key:je.id,request:Ne.args}),`
9
+ `);for(let ie of Ne.warnings)x.push({requestId:je.id,warning:ie})}let pe=await this.getHeaders(f.headers),ce=`${this.batchConfig.baseURL}/${Tt(w)}:batchGenerateContent`;if(V==null){let{value:je}=await g({url:ce,headers:pe,body:B,failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch});return{batchId:je.name,..._t(je),warnings:x}}let Re=new Blob(V,{type:"application/jsonl"});if(V.length=0,Re.size>No)throw new b({argument:"requests",message:"Google batch input files must not exceed 2 GB."});let{value:Le}=await g({url:`${this.getBaseOrigin()}/upload/v1beta/files`,headers:d(pe,{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(Re.size),"X-Goog-Upload-Header-Content-Type":"application/jsonl"}),body:{file:{display_name:`${A}-input`}},failedResponseHandler:Xe,successfulResponseHandler:Jo,abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{value:Ce}=await ve({url:Le,headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize","Content-Type":"application/jsonl"},body:{content:Re,values:{byteLength:Re.size,mediaType:"application/jsonl"}},failedResponseHandler:Xe,successfulResponseHandler:p(Bo),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{value:Ee}=await g({url:ce,headers:pe,body:{batch:{displayName:A,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{fileName:Ce.file.name}}},failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch});return{batchId:Ee.name,..._t(Ee),providerMetadata:{google:{inputFileId:Ce.file.name,...Ce.file.expirationTime!=null?{inputFileExpiresAt:Ce.file.expirationTime}:{}}},warnings:x}}async doGetBatchStatus(f){return _t(await this.retrieveBatch(f))}async doCancelBatch(f){return await g({url:`${this.batchConfig.baseURL}/${f.batchId}:cancel`,headers:await this.getHeaders(f.headers),body:{},failedResponseHandler:Xe,successfulResponseHandler:p(Fo),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{}}async doListBatches(f){let w=new URL(`${this.batchConfig.baseURL}/batches`);if(f.limit!=null)w.searchParams.set("pageSize",String(f.limit));if(f.cursor!=null)w.searchParams.set("pageToken",f.cursor);let{value:x}=await R({url:w.toString(),headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:p($o),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return{batches:(x.operations??[]).map((A)=>({batchId:A.name,..._t(A)})),...x.nextPageToken!=null?{nextCursor:x.nextPageToken}:{}}}async doGetBatchResults(f){let w=await this.retrieveBatch(f),x=_t(w);if(x.status==="pending")throw new b({argument:"batchId",message:`Google batch "${f.batchId}" is not complete.`});let A=w.metadata?.output?.inlinedResponses?.inlinedResponses??w.response?.inlinedResponses?.inlinedResponses;if(A!=null)return ae(this.iterateBatchResults(A.map((ee)=>({key:ee.metadata.key,response:ee.response,error:ee.error}))));let q=w.metadata?.output?.responsesFile??w.response?.responsesFile;if(q==null){if(x.status==="completed")throw new P({data:w,message:`Google batch "${f.batchId}" completed without batch output.`});return new ReadableStream({start(ee){ee.close()}})}let B=q.split("/").map((ee)=>encodeURIComponent(ee)).join("/"),{value:re}=await R({url:`${this.getBaseOrigin()}/download/v1beta/${B}:download?alt=media`,headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:_e(Ho,{maxLineBytes:this.maxLineBytes}),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return ae(this.iterateBatchResults(re))}async retrieveBatch(f){let{value:w}=await R({url:`${this.batchConfig.baseURL}/${f.batchId}`,headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return w}async*iterateBatchResults(f){for await(let w of f){if(w.error!=null){let ee=Rn(w.error,"Google batch request failed."),V=w.error.status==="CANCELLED"||String(w.error.code)==="1"?"cancelled":"failed";yield{type:"text",id:w.key,status:V,error:ee};continue}if(w.response==null){yield{type:"text",id:w.key,status:"failed",error:{message:"Google returned a batch result without a response or error.",code:"invalid_batch_result"}};continue}let x=await j({value:w.response,schema:Vo});if(x.success&&(x.value.candidates==null||x.value.candidates.length===0)){let ee=x.value.promptFeedback??void 0,V=ee?.blockReason??void 0;yield{type:"text",id:w.key,status:"failed",error:{message:V==null?"Google returned a batch response without any candidates.":`Google blocked the batch request (${V}).`,code:V==null?"invalid_response":"prompt_blocked",...V!=null?{type:V}:{}},...ee!=null?{providerMetadata:{google:{promptFeedback:{blockReason:ee.blockReason??null}}}}:{}};continue}let A=await j({value:w.response,schema:In});if(!A.success){yield{type:"text",id:w.key,status:"failed",error:{message:"Google returned an invalid GenerateContent batch result.",code:"invalid_response"}};continue}let q=Ct.convertGenerateContentResponse({config:this.batchConfig,response:A.value,warnings:[],providerOptionsNames:["google"]}),B=Xo(q);if(B!=null){yield{type:"image",id:w.key,status:"succeeded",result:B};continue}let re=q.content.find((ee)=>!Do.has(ee.type));if(re!=null){yield{type:"text",id:w.key,status:"failed",error:{message:`Google returned a "${re.type}" content block, but that content is not supported in AI SDK text batches.`,code:"unsupported_content"}};continue}yield{type:"text",id:w.key,status:"succeeded",result:q}}}async prepareImageRequest(f){let{prompt:w,n:x,size:A,aspectRatio:q,seed:B,files:re,mask:ee,providerOptions:V}=f.options,pe=[];if(ee!=null)throw new u({functionality:"mask-based image editing in Google batches"});if(x>1)throw new u({functionality:"multiple images per Google batch request"});if(A!=null)pe.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let ce=[];if(w!=null)ce.push({type:"text",text:w});for(let ye of re??[])ce.push(ye.type==="url"?{type:"file",data:{type:"url",url:new URL(ye.url)},mediaType:"image/*"}:{type:"file",data:{type:"data",data:ye.data},mediaType:ye.mediaType});let Re=await h({provider:"google",providerOptions:V,schema:kn}),{responseModalities:Le,imageConfig:Ce,...Ee}=await h({provider:"google",providerOptions:V,schema:Et})??{},je=await h({provider:"google",providerOptions:{google:{...Ee,responseModalities:["IMAGE"],imageConfig:q!=null||Ce!=null?{...Ce,...q!=null?{aspectRatio:q}:{}}:void 0}},schema:Et}),Ne=await Ct.prepareRequest({modelId:f.modelId,config:this.batchConfig,options:{prompt:[{role:"user",content:ce}],seed:B,providerOptions:{google:je??{responseModalities:["IMAGE"]}},tools:Re?.googleSearch!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Re.googleSearch}]:void 0}});return{...Ne,warnings:[...pe,...Ne.warnings]}}async getHeaders(f){return d(this.batchConfig.headers?await _(this.batchConfig.headers):void 0,f)}getBaseOrigin(){return this.batchConfig.baseURL.replace(/\/v1beta$/,"")}};function _t(f){let w=f.metadata?.state??void 0,x=zo(f.metadata?.batchStats),A=f.metadata?.createTime??void 0,q=f.error!=null?Rn(f.error,"Google batch failed."):void 0;return{status:Ko({rawStatus:w,done:f.done??void 0,hasError:q!=null}),...w!=null?{rawStatus:w}:{},...x!=null?{requestCounts:x}:{},...q!=null?{error:q}:{},...A!=null?{createdAt:A}:{}}}function Ko({rawStatus:f,done:w,hasError:x}){if(x)return"failed";if(f==null)return w?"completed":"pending";switch(f.replace(/^(?:BATCH|JOB)_STATE_/,"")){case"SUCCEEDED":return"completed";case"FAILED":case"CANCELLED":case"EXPIRED":return"failed";default:return"pending"}}function zo(f){let w=Rt(f?.requestCount),x=Rt(f?.successfulRequestCount??0),A=Rt(f?.failedRequestCount??0),q=Rt(f?.pendingRequestCount??0);return ge({total:w,pending:q,completed:x,failed:A})}function Rt(f){let w=typeof f==="string"&&/^\d+$/.test(f)?Number(f):f;return typeof w==="number"&&Number.isSafeInteger(w)&&w>=0?w:void 0}function Rn(f,w){return{message:f.message??w,...f.status!=null?{type:f.status}:{},...f.code!=null?{code:String(f.code)}:{}}}var Jo=async({response:f})=>{let w=f.headers.get("x-goog-upload-url");if(w==null)throw new P({data:f.headers,message:"Google did not return a resumable upload URL."});return{value:w}};function Yo(f){let w=f[0]?.modelId;if(w==null)throw new b({argument:"requests",message:"Google batches require at least one request."});for(let x of f)if(x.modelId!==w)throw new b({argument:"requests",message:"Google batches require every request to use the same model because the model is part of the batch endpoint."});return w}function Xo(f){let w=f.content.flatMap((A)=>A.type==="file"&&A.mediaType.startsWith("image/")&&A.data.type==="data"?[M(A.data.data)]:[]);if(w.length===0)return;let x=f.providerMetadata?.google??{};return{images:w,warnings:f.warnings,providerMetadata:{google:{...x,images:w.map(()=>({}))}},response:{timestamp:new Date,modelId:f.response?.modelId??"",headers:f.response?.headers},usage:{inputTokens:f.usage.inputTokens.total,outputTokens:f.usage.outputTokens.total,totalTokens:(f.usage.inputTokens.total??0)+(f.usage.outputTokens.total??0)}}}var Qo=S({id:"google.enterprise_web_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))});a(()=>s(U({fileSearchStoreNames:o(e()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:r().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:e().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()})));var Zo=S({id:"google.file_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),ei={googleSearch:Uo,enterpriseWebSearch:Qo,googleMaps:S({id:"google.google_maps",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),urlContext:S({id:"google.url_context",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),fileSearch:Zo,codeExecution:no,vertexRagStore:S({id:"google.vertex_rag_store",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))})},ti=new Set(["gemini-2.5-flash-image","gemini-3-pro-image-preview","gemini-3.1-flash-image-preview","gemini-nano-banana-2.1"]),ni=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,{},w.config)}get maxImagesPerCall(){if(this.settings.maxImagesPerCall!=null)return this.settings.maxImagesPerCall;return 1}get supportsFileInputs(){return ti.has(this.modelId)?!0:void 0}get supportsMaskInputs(){return this.supportsFileInputs===!0?!1:void 0}get provider(){return this.config.provider}constructor(w,x,A){this.modelId=w,this.settings=x,this.config=A,this.specificationVersion="v4"}async doGenerate(w){if(!this.modelId.startsWith("gemini-"))throw Error("Google image models other than Gemini are no longer supported. Use a model ID that starts with `gemini-`.");let{prompt:x,size:A,aspectRatio:q,seed:B,providerOptions:re,headers:ee,abortSignal:V,files:pe,mask:ce}=w,Re=[];if(ce!=null)throw Error("Gemini image models do not support mask-based image editing.");if(A!=null)Re.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let Le=[];if(x!=null)Le.push({type:"text",text:x});if(pe!=null&&pe.length>0)for(let De of pe)if(De.type==="url")Le.push({type:"file",data:{type:"url",url:new URL(De.url)},mediaType:"image/*"});else Le.push({type:"file",data:{type:"data",data:typeof De.data==="string"?De.data:new Uint8Array(De.data)},mediaType:De.mediaType});let Ce=[{role:"user",content:Le}],Ee=await h({provider:"google",providerOptions:re,schema:kn}),{googleSearch:je,responseModalities:Ne,imageConfig:ye,...ie}=re?.google??{},be=await new Ct(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??C}).doGenerate({prompt:Ce,seed:B,providerOptions:{google:{...ie,responseModalities:["IMAGE"],imageConfig:q!=null||ye!=null?{...ye,...q!=null?{aspectRatio:q}:{}}:void 0}},tools:Ee?.googleSearch!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Ee.googleSearch}]:void 0,headers:ee,abortSignal:V}),ne=this.config._internal?.currentDate?.()??new Date,se=[];for(let De of be.content)if(De.type==="file"&&De.mediaType.startsWith("image/")&&De.data.type==="data")se.push(M(De.data.data));let Ue=be.providerMetadata?.google??{};return{images:se,...be.finishReason.unified==="content-filter"?{isRetryable:!1}:{},warnings:Re,providerMetadata:{google:{...Ue,finishReason:be.finishReason.raw??null,images:se.map(()=>({}))}},response:{timestamp:ne,modelId:this.modelId,headers:be.response?.headers},usage:be.usage?{inputTokens:be.usage.inputTokens.total,outputTokens:be.usage.outputTokens.total,totalTokens:(be.usage.inputTokens.total??0)+(be.usage.outputTokens.total??0)}:void 0}}},oi=class{get provider(){return this.config.provider}constructor(f){this.config=f,this.specificationVersion="v4"}async uploadFile(f){let w=await h({provider:"google",providerOptions:f.providerOptions,schema:ai}),x=d(this.config.headers(),f.headers),A=this.config.fetch??globalThis.fetch,q=[];if(f.filename!=null)q.push({type:"unsupported",feature:"filename"});let B=we(f.data),re=f.mediaType,ee=w?.displayName,V=await A(`${this.config.baseURL.replace(/\/v1beta$/,"")}/upload/v1beta/files`,{method:"POST",headers:{...x,"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(B.length),"X-Goog-Upload-Header-Content-Type":re,"Content-Type":"application/json"},body:JSON.stringify({file:{...ee!=null?{display_name:ee}:{}}}),signal:f.abortSignal});if(!V.ok){let je=await V.text();throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to initiate resumable upload: ${V.status} ${je}`})}let pe=V.headers.get("x-goog-upload-url");if(!pe)throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:"No upload URL returned from initiation request"});let ce=await A(pe,{method:"POST",headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"},body:ii(B),signal:f.abortSignal});if(!ce.ok){let je=await ce.text();throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to upload file data: ${ce.status} ${je}`})}let Re=(await ce.json()).file,Le=w?.pollIntervalMs??2000,Ce=w?.pollTimeoutMs??300000,Ee=Date.now();while(Re.state==="PROCESSING"){if(Date.now()-Ee>Ce)throw new m({name:"GOOGLE_FILES_UPLOAD_TIMEOUT",message:`File processing timed out after ${Ce}ms`});await Oe(Le,{abortSignal:f.abortSignal});let je=/^files\/([^/]+)$/.exec(Re.name),Ne=je!=null?`files/${de(je[1])}`:de(Re.name),{value:ye}=await R({url:`${this.config.baseURL}/${Ne}`,validateUrl:!1,headers:d(x),successfulResponseHandler:p(si),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch});Re=ye}if(Re.state==="FAILED")throw new m({name:"GOOGLE_FILES_UPLOAD_FAILED",message:`File processing failed for ${Re.name}`});return{warnings:q,providerReference:{google:Re.uri},mediaType:Re.mimeType??f.mediaType,providerMetadata:{google:{name:Re.name,displayName:Re.displayName,mimeType:Re.mimeType,sizeBytes:Re.sizeBytes,state:Re.state,uri:Re.uri,...Re.createTime!=null?{createTime:Re.createTime}:{},...Re.updateTime!=null?{updateTime:Re.updateTime}:{},...Re.expirationTime!=null?{expirationTime:Re.expirationTime}:{},...Re.sha256Hash!=null?{sha256Hash:Re.sha256Hash}:{}}}}}};function ii(f){if(f.buffer instanceof ArrayBuffer)return f;return new Uint8Array(f)}var si=a(()=>s(t({name:e(),displayName:e().nullish(),mimeType:e(),sizeBytes:e().nullish(),createTime:e().nullish(),updateTime:e().nullish(),expirationTime:e().nullish(),sha256Hash:e().nullish(),uri:e(),state:e()}))),ai=a(()=>s(U({displayName:e().nullish(),pollIntervalMs:r().positive().nullish(),pollTimeoutMs:r().positive().nullish()}))),ri=a(()=>s(U({pollIntervalMs:r().positive().nullish(),pollTimeoutMs:r().positive().nullish(),personGeneration:i(["dont_allow","allow_adult","allow_all"]).nullish(),negativePrompt:e().nullish(),referenceImages:o(t({bytesBase64Encoded:e().nullish(),gcsUri:e().nullish()})).nullish()})));function li(f){return f.frameImages?.find((w)=>w.frameType==="first_frame")?.image}function ui(f){return li(f)??f.image}function ci(f){return f.frameImages?.find((w)=>w.frameType==="last_frame")?.image}function di(f){if(f.frameImages!=null&&f.frameImages.length>0)return;return f.inputReferences!=null&&f.inputReferences.length>0?f.inputReferences:void 0}function Dt(f,w){if(f.type==="url"){if(f.url.startsWith("gs://"))return{gcsUri:f.url,mimeType:"image/png"};w.push({type:"unsupported",feature:"URL-based image input",details:"Google Generative AI video models require base64-encoded images or GCS URIs. URL will be ignored."});return}return{bytesBase64Encoded:typeof f.data==="string"?f.data:X(f.data),mimeType:f.mediaType||"image/png"}}function pi(f){if(f.bytesBase64Encoded)return{image:{bytesBase64Encoded:f.bytesBase64Encoded,mimeType:"image/png"},referenceType:"asset"};if(f.gcsUri)return{image:{gcsUri:f.gcsUri,mimeType:"image/png"},referenceType:"asset"};return f}function gi(f,w){let x=Dt(f,w);return x!=null?{image:x,referenceType:"asset"}:void 0}var hi=class{get provider(){return this.config.provider}get maxVideosPerCall(){return 4}constructor(f,w){this.modelId=f,this.config=w,this.specificationVersion="v4"}async buildRequest(f){let w=[],x=await h({provider:"google",providerOptions:f.providerOptions,schema:ri}),A=[{}],q=A[0];if(f.prompt!=null)q.prompt=f.prompt;let B=ui(f);if(B!=null){let pe=Dt(B,w);if(pe!=null)q.image=pe}let re=ci(f);if(re!=null){let pe=Dt(re,w);if(pe!=null)q.lastFrame=pe}let ee=di(f);if(ee!=null)q.referenceImages=ee.flatMap((pe)=>{let ce=gi(pe,w);return ce!=null?[ce]:[]});else if(x?.referenceImages!=null)q.referenceImages=x.referenceImages.map((pe)=>pi(pe));let V={sampleCount:f.n};if(f.aspectRatio)V.aspectRatio=f.aspectRatio;if(f.resolution)V.resolution={"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"}[f.resolution]||f.resolution;if(f.duration)V.durationSeconds=f.duration;if(f.seed)V.seed=f.seed;if(x!=null){let pe=x;if(pe.personGeneration!==void 0&&pe.personGeneration!==null)V.personGeneration=pe.personGeneration;if(pe.negativePrompt!==void 0&&pe.negativePrompt!==null)V.negativePrompt=pe.negativePrompt;for(let[ce,Re]of Object.entries(pe))if(!["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","referenceImages"].includes(ce))V[ce]=Re}return{instances:A,parameters:V,warnings:w,googleOptions:x}}async buildCompletedResult(f,w,x,A){let q=f.response;if(!q?.generateVideoResponse?.generatedSamples||q.generateVideoResponse.generatedSamples.length===0)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:`No videos in response. Response: ${JSON.stringify(f)}`});let B=[],re=[],ee=(await _(this.config.headers))?.["x-goog-api-key"];for(let V of q.generateVideoResponse.generatedSamples)if(V.video?.uri){let pe=ee&&He(V.video.uri,this.config.baseURL)?`${V.video.uri}${V.video.uri.includes("?")?"&":"?"}key=${ee}`:V.video.uri;B.push({type:"url",url:pe,mediaType:"video/mp4"}),re.push({uri:V.video.uri})}if(B.length===0)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{status:"completed",videos:B,warnings:x,response:{timestamp:A,modelId:this.modelId,headers:w},providerMetadata:{google:{videos:re}}}}async doStart(f){let w=this.config._internal?.currentDate?.()??new Date,{instances:x,parameters:A,warnings:q}=await this.buildRequest(f),{value:B,responseHeaders:re}=await g({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:d(await _(this.config.headers),f.headers),body:{instances:x,parameters:A},successfulResponseHandler:p(ln),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch}),ee=B.name;if(!ee)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No operation name returned from API"});return{operation:{operationName:ee},warnings:q,response:{timestamp:w,modelId:this.modelId,headers:re}}}async doStatus(f){let w=this.config._internal?.currentDate?.()??new Date,{operationName:x}=f.operation,{value:A,responseHeaders:q}=await R({url:`${this.config.baseURL}/${x}`,validateUrl:!1,headers:d(await _(this.config.headers),f.headers),successfulResponseHandler:p(ln),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch});if(!A.done)return{status:"pending",response:{timestamp:w,modelId:this.modelId,headers:q}};if(A.error)return{status:"error",error:`Video generation failed: ${A.error.message}`,response:{timestamp:w,modelId:this.modelId,headers:q}};return this.buildCompletedResult(A,q,[],w)}},ln=a(()=>s(t({name:e().nullish(),done:c().nullish(),error:t({code:r().nullish(),message:e(),status:e().nullish()}).nullish(),response:t({generateVideoResponse:t({generatedSamples:o(t({video:t({uri:e().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}))),mi=a(()=>s(t({candidates:o(t({content:t({parts:o(t({inlineData:t({mimeType:e().nullish(),data:e().nullish()}).nullish()})).nullish()}).nullish()})).nullish(),usageMetadata:y(e(),G()).nullish()})));function fi({text:f,voice:w,providerOptions:x}){let A=x?.google,q=A!=null&&typeof A==="object"?A:void 0,B=q&&"turns"in q?q.turns:void 0,re=[];if(Array.isArray(B)&&B.length>0){for(let pe of B){if(pe==null||typeof pe!=="object"||!("text"in pe)||typeof pe.text!=="string")break;re.push(pe.text)}if(re.length===B.length)f=re.join("")}let ee=q&&"multiSpeakerVoiceConfig"in q?q.multiSpeakerVoiceConfig:void 0,V=ee!=null&&typeof ee==="object"&&"speakerVoiceConfigs"in ee&&Array.isArray(ee.speakerVoiceConfigs)?ee.speakerVoiceConfigs:[];return{text:f,usesCustomVoice:w?.startsWith("voice_")===!0||w?.startsWith("voicekey_")===!0||V.some((pe)=>pe!=null&&typeof pe==="object"&&("voiceConfig"in pe)&&pe.voiceConfig!=null&&typeof pe.voiceConfig==="object"&&("voice"in pe.voiceConfig))}}var yi=()=>t({voiceName:e()}),vi=()=>t({prebuiltVoiceConfig:yi(),voice:Ae().optional()}),un=()=>t({speaker:e().min(1).optional(),style:e().optional()}),cn=a(()=>s(t({speechMetadata:un().optional(),turns:o(t({text:e(),speechMetadata:un().optional()})).min(1).optional(),multiSpeakerVoiceConfig:t({speakerVoiceConfigs:o(t({speaker:e(),voiceConfig:vi()}))}).optional()}))),bi="Kore",Ti=24000,_i=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.modelId=w,this.config=x,this.specificationVersion="v4"}async getArgs({text:w,voice:x=bi,outputFormat:A,instructions:q,speed:B,language:re,providerOptions:ee}){let V=[],pe=this.config.provider.includes("vertex")?["googleVertex","vertex"]:["google"],ce;for(let be of pe)if(ce=await h({provider:be,providerOptions:ee,schema:cn}),ce!=null)break;if(ce==null&&!pe.includes("google"))ce=await h({provider:"google",providerOptions:ee,schema:cn});let Re=!this.modelId.startsWith("gemini-2.5-")&&!this.modelId.startsWith("gemini-3.1-"),Le=fi({text:w,voice:x,providerOptions:{google:ce}});if(Le.usesCustomVoice)throw new b({argument:"voice",message:"Custom voices are not supported. Use a prebuilt voice instead."});let Ce=ce?.multiSpeakerVoiceConfig,Ee=Ce?{multiSpeakerVoiceConfig:Ce}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:x}}},je=w;if(q!=null&&!Re)if(Ce)V.push({type:"unsupported",feature:"instructions",details:"Google Gemini TTS ignores `instructions` when `multiSpeakerVoiceConfig` is set, because prepending them would break multi-speaker transcript parsing."});else je=`${q}: ${w}`;let Ne=[{text:je}];if(Re){if(ce?.turns&&ce.speechMetadata)throw new b({argument:"providerOptions",message:"Set speechMetadata on each turn when using turns."});if(ce?.turns&&w!=="")V.push({type:"unsupported",feature:"text",details:"Google TTS turns replace the top-level text."});Ne=(ce?.turns??[{text:w,speechMetadata:ce?.speechMetadata}]).map((be)=>{let ne=be.speechMetadata?.style??q,se=be.speechMetadata?.speaker;if(Ce&&!Ce.speakerVoiceConfigs.some((Ue)=>Ue.speaker===se))throw new b({argument:"speechMetadata.speaker",message:"Every multi-speaker turn must specify a speechMetadata.speaker matching a configured speaker."});return{text:be.text,...ne!=null||se!=null?{speechMetadata:{style:ne,speaker:se}}:{}}})}else if(ce?.turns||ce?.speechMetadata)throw new b({argument:"providerOptions",message:"Structured speech metadata and turns require Gemini 3.8 TTS."});if(Le.text.length===0)throw new b({argument:"text",message:"Speech input must contain a non-empty transcript."});if(B!=null)V.push({type:"unsupported",feature:"speed",details:"Google Gemini TTS models do not support the `speed` option. It was ignored."});if(re!=null)V.push({type:"unsupported",feature:"language",details:"Google Gemini TTS models do not support the `language` option. Language is detected automatically from the input text."});let ye=Re?{wav:"AUDIO_WAV","audio/wav":"AUDIO_WAV",pcm:"AUDIO_L16","audio/l16":"AUDIO_L16",mulaw:"AUDIO_MULAW","audio/mulaw":"AUDIO_MULAW",alaw:"AUDIO_ALAW","audio/alaw":"AUDIO_ALAW"}:{wav:"AUDIO_WAV",pcm:"AUDIO_L16"},ie="wav";if(A!=null&&Object.prototype.hasOwnProperty.call(ye,A))ie=A;else if(A!=null)V.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${A}. Using wav instead.`});return{requestBody:{contents:[{role:"user",parts:Ne}],generationConfig:{responseModalities:["AUDIO"],speechConfig:Ee,...Re&&A!=null?{responseFormat:{audio:{mimeType:ye[ie]}}}:{}}},warnings:V,outputFormat:ye[ie],usesStructuredSpeech:Re}}async doGenerate(w){let x=this.config._internal?.currentDate?.()??new Date,{requestBody:A,warnings:q,outputFormat:B,usesStructuredSpeech:re}=await this.getArgs(w),{value:ee,responseHeaders:V,rawValue:pe}=await g({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:d(this.config.headers?await _(this.config.headers):void 0,w.headers),body:A,failedResponseHandler:Xe,successfulResponseHandler:p(mi),abortSignal:w.abortSignal,fetch:this.config.fetch}),ce,Re;for(let Ne of ee.candidates??[]){for(let ye of Ne.content?.parts??[])if(ye.inlineData?.data){ce=ye.inlineData.data,Re=ye.inlineData.mimeType??void 0;break}if(ce!=null)break}let Le=Ci(Re)??Ti,Ce=ce!=null?N(ce):new Uint8Array(0),Ee=/^audio\/(?:l16|pcm)(?:;|$)/i.test(Re??"")||Re==null&&!re,je=B==="AUDIO_WAV"&&Ee&&Ce.length>0?wi(Ce,Le):Ce;if(B==="AUDIO_L16"&&Ce.length>0&&!re)q.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:q,...ee.usageMetadata!=null&&{usage:ee.usageMetadata},request:{body:JSON.stringify(A)},response:{timestamp:x,modelId:this.modelId,headers:V,body:pe},providerMetadata:{google:{sampleRate:Le,mimeType:Re??null}}}}};function Ci(f){if(f==null)return;let w=/rate=(\d+)/.exec(f);return w?Number.parseInt(w[1],10):void 0}function wi(f,w){let B=w*2,re=f.length,ee=new ArrayBuffer(44+re),V=new DataView(ee);Ot(V,0,"RIFF"),V.setUint32(4,36+re,!0),Ot(V,8,"WAVE"),Ot(V,12,"fmt "),V.setUint32(16,16,!0),V.setUint16(20,1,!0),V.setUint16(22,1,!0),V.setUint32(24,w,!0),V.setUint32(28,B,!0),V.setUint16(32,2,!0),V.setUint16(34,16,!0),Ot(V,36,"data"),V.setUint32(40,re,!0);let pe=new Uint8Array(ee);return pe.set(f,44),pe}function Ot(f,w,x){for(let A=0;A<x.length;A++)f.setUint8(w+A,x.charCodeAt(A))}function Ht(f){if(f==null)return te();let w=f.total_input_tokens??0,x=f.total_output_tokens??0,A=f.total_thought_tokens??0,q=f.total_cached_tokens??0;return{inputTokens:{total:f.total_input_tokens??void 0,noCache:f.total_input_tokens==null?void 0:w-q,cacheRead:f.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:f.total_output_tokens==null&&f.total_thought_tokens==null?void 0:x+A,text:f.total_output_tokens??void 0,reasoning:f.total_thought_tokens??void 0},raw:f}}function On(f){let w=f?.output_tokens_by_modality;if(w==null)return;let x={};for(let A of w)if(A?.modality!=null&&A.tokens!=null)x[A.modality]=A.tokens;return Object.keys(x).length>0?x:void 0}var Si={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function Mn(f){let w=f.toLowerCase();for(let[x,A]of Object.entries(Si))if(w.endsWith(`.${x}`))return A;return"application/octet-stream"}function En(f){let w=f.split("/"),x=w[w.length-1];return x&&x.length>0?x:void 0}function Ii({annotation:f,generateId:w}){switch(f.type){case"url_citation":{let x=f;if(x.url==null||x.url.length===0)return;return{type:"source",sourceType:"url",id:w(),url:x.url,...x.title!=null?{title:x.title}:{}}}case"file_citation":{let x=f,A=x.url??x.document_uri??x.file_name;if(A==null||A.length===0)return;if(A.startsWith("http://")||A.startsWith("https://"))return{type:"source",sourceType:"url",id:w(),url:A,...x.file_name!=null?{title:x.file_name}:{}};let q=x.file_name??En(A),B=Mn(A);return{type:"source",sourceType:"document",id:w(),mediaType:B,title:x.file_name??q??A,...q!=null?{filename:q}:{}}}case"place_citation":{let x=f;if(x.url==null||x.url.length===0)return;return{type:"source",sourceType:"url",id:w(),url:x.url,...x.name!=null?{title:x.name}:{}}}default:return}}function An({block:f,generateId:w}){let x=[];switch(f.type){case"url_context_result":{let A=f.result??[];for(let q of A){if(q?.url==null||q.url.length===0)continue;if(q.status!=null&&q.status!=="success")continue;x.push({type:"source",sourceType:"url",id:w(),url:q.url})}break}case"google_search_result":{let A=f.result??[];for(let q of A){let B=q?.url;if(B==null||B.length===0)continue;x.push({type:"source",sourceType:"url",id:w(),url:B,...q.title!=null?{title:q.title}:{}})}break}case"google_maps_result":{let A=f.result??[];for(let q of A)for(let B of q.places??[]){if(B.url==null||B.url.length===0)continue;x.push({type:"source",sourceType:"url",id:w(),url:B.url,...B.name!=null?{title:B.name}:{}})}break}case"file_search_result":{let A=f.result??[];for(let q of A){if(q==null||typeof q!=="object")continue;let B=q,re=B.url??B.document_uri??B.file_name;if(re==null||re.length===0)continue;if(re.startsWith("http://")||re.startsWith("https://")){x.push({type:"source",sourceType:"url",id:w(),url:re,...B.title!=null?{title:B.title}:{}});continue}let ee=B.file_name??En(re),V=Mn(re);x.push({type:"source",sourceType:"document",id:w(),mediaType:V,title:B.title??B.file_name??ee??re,...ee!=null?{filename:ee}:{}})}break}}return x}function Pt({annotations:f,generateId:w}){if(f==null)return[];let x=new Set,A=[];for(let q of f){let B=Ii({annotation:q,generateId:w});if(B==null)continue;let re=B.sourceType==="url"?`url:${B.url}`:`doc:${B.filename??B.title}`;if(x.has(re))continue;x.add(re),A.push(B)}return A}function Vt({status:f,hasFunctionCall:w}){switch(f){case"completed":return w?"tool-calls":"stop";case"requires_action":return"tool-calls";case"failed":return"error";case"incomplete":return"length";case"cancelled":return"other";default:return"other"}}var ki=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),xi=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function Ri(f){return f.replace(/_call$/,"")}function Oi(f){return f.replace(/_result$/,"")}function dn({warnings:f,generateId:w,includeRawChunks:x,serviceTier:A}){let q,B,re=A,ee,V=!1,pe=!1,ce=new Map,Re=new Set;function Le(Ce){return Ce.sourceType==="url"?`url:${Ce.url}`:`doc:${Ce.filename??Ce.title}`}return new TransformStream({start(Ce){Ce.enqueue({type:"stream-start",warnings:f})},transform(Ce,Ee){if(x)Ee.enqueue({type:"raw",rawValue:Ce.rawValue});if(!Ce.success){ee="failed",Ee.enqueue({type:"error",error:Ce.error});return}let je=Ce.value,Ne=je.event_type;switch(Ne){case"interaction.created":{let ye=je.interaction;q=ye?.id!=null&&ye.id.length>0?ye.id:void 0;let ie=ye?.created,be;if(typeof ie==="string"){let ne=new Date(ie);if(!Number.isNaN(ne.getTime()))be=ne}Ee.enqueue({type:"response-metadata",...q!=null?{id:q}:{},modelId:ye?.model,...be?{timestamp:be}:{}});break}case"step.start":{let ye=je,{step:ie,index:be}=ye,ne=`${q??"interaction"}:${be}`,se=ie?.type;if(se==="model_output"){let Ue=ie?.content?.[0];if(Ue?.type==="text"){ce.set(be,{kind:"text",id:ne,emittedSourceKeys:new Set}),Ee.enqueue({type:"text-start",id:ne});let De=Pt({annotations:Ue.annotations,generateId:w});for(let qe of De){let We=Le(qe);if(Re.has(We))continue;Re.add(We),Ee.enqueue(qe)}}else if(Ue?.type==="image")ce.set(be,{kind:"image",id:ne,...Ue.data!=null?{data:Ue.data}:{},...Ue.mime_type!=null?{mimeType:Ue.mime_type}:{},...Ue.uri!=null?{uri:Ue.uri}:{}});else ce.set(be,{kind:"pending_model_output",id:ne})}else if(se==="thought"){let Ue=ie?.signature;if(ce.set(be,{kind:"reasoning",id:ne,...Ue!=null?{signature:Ue}:{}}),Ee.enqueue({type:"reasoning-start",id:ne}),Array.isArray(ie?.summary)){for(let De of ie.summary)if(De?.type==="text"&&typeof De.text==="string")Ee.enqueue({type:"reasoning-delta",id:ne,delta:De.text})}}else if(se==="processing_call"||se==="processing_result"){let Ue={};if(ie?.signature!=null)Ue.signature=ie.signature;if(q!=null)Ue.interactionId=q;if(se==="processing_call")Ue.processingId=ie?.id||ne;else Ue.processingCallId=ie?.call_id||ne;ce.set(be,{kind:"custom",id:ne,customKind:`google.${se}`,google:Ue})}else if(se==="function_call"){let Ue=ie?.id||ne,De=ie?.name??"unknown";V=!0;let qe={kind:"function_call",id:ne,toolCallId:Ue,toolName:De,argumentsAccum:"",...ie?.signature!=null?{signature:ie.signature}:{}};ce.set(be,qe),Ee.enqueue({type:"tool-input-start",id:Ue,toolName:De})}else if(se!=null&&ki.has(se)){let Ue=se==="mcp_server_tool_call"?ie?.name??"mcp_server_tool":Ri(se),De={kind:"builtin_tool_call",id:ne,blockType:se,toolCallId:ie?.id||ne,toolName:Ue,arguments:ie?.arguments??{},callEmitted:!1};ce.set(be,De)}else if(se!=null&&xi.has(se)){let Ue=se==="mcp_server_tool_result"?ie?.name??"mcp_server_tool":Oi(se),De={kind:"builtin_tool_result",id:ne,blockType:se,callId:ie?.call_id||ne,toolName:Ue,result:ie?.result??null,...ie?.is_error!=null?{isError:ie.is_error}:{},resultEmitted:!1};ce.set(be,De)}else ce.set(be,{kind:"unknown",id:ne});break}case"step.delta":{let ye=je,ie=ce.get(ye.index);if(ie==null)break;let be=ye.delta?.type;if(ie.kind==="pending_model_output"){if(be==="text"||be==="text_annotation"||be==="text_annotation_delta"){let se={kind:"text",id:ie.id,emittedSourceKeys:new Set};ce.set(ye.index,se),ie=se,Ee.enqueue({type:"text-start",id:se.id})}}if(be==="image"&&(ie.kind==="pending_model_output"||ie.kind==="text"||ie.kind==="image")){let se=ye.delta,Ue={};if(q!=null)Ue.interactionId=q;let De=Object.keys(Ue).length>0?{google:Ue}:void 0;if(se?.data!=null&&se.data.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"image/png",data:{type:"data",data:se.data},...De?{providerMetadata:De}:{}});else if(se?.uri!=null&&se.uri.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"image/png",data:{type:"url",url:new URL(se.uri)},...De?{providerMetadata:De}:{}});if(ie.kind==="image")ie.data=void 0,ie.uri=void 0;break}if(be==="video"&&(ie.kind==="pending_model_output"||ie.kind==="text")){let se=ye.delta,Ue={};if(q!=null)Ue.interactionId=q;let De=Object.keys(Ue).length>0?{google:Ue}:void 0;if(se?.data!=null&&se.data.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"video/mp4",data:{type:"data",data:se.data},...De?{providerMetadata:De}:{}});else if(se?.uri!=null&&se.uri.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"video/mp4",data:{type:"url",url:new URL(se.uri)},...De?{providerMetadata:De}:{}});break}let ne=ye.delta;if(ie.kind==="custom"&&(ne?.type==="processing_call"||ne?.type==="processing_result")){if(ne.signature!=null)ie.google.signature=ne.signature;if(ne.type==="processing_call"&&ne.id!=null&&ne.id.length>0)ie.google.processingId=ne.id;if(ne.type==="processing_result"&&ne.call_id!=null&&ne.call_id.length>0)ie.google.processingCallId=ne.call_id}else if(ie.kind==="text"&&ne?.type==="text"){let se=ne.text??"";if(se.length>0)Ee.enqueue({type:"text-delta",id:ie.id,delta:se})}else if(ie.kind==="text"&&(ne?.type==="text_annotation"||ne?.type==="text_annotation_delta")){let se=Pt({annotations:ne.annotations,generateId:w});for(let Ue of se){let De=Le(Ue);if(Re.has(De))continue;Re.add(De),ie.emittedSourceKeys.add(De),Ee.enqueue(Ue)}}else if(ie.kind==="image"&&ne?.type==="image"){if(ne.data!=null)ie.data=ne.data;if(ne.mime_type!=null)ie.mimeType=ne.mime_type;if(ne.uri!=null)ie.uri=ne.uri}else if(ie.kind==="reasoning"){if(ne?.type==="thought_summary"){let se=ne.content;if(se?.type==="text"&&typeof se.text==="string")Ee.enqueue({type:"reasoning-delta",id:ie.id,delta:se.text})}else if(ne?.type==="thought_signature"){let se=ne.signature;if(se!=null)ie.signature=se}}else if(ie.kind==="function_call"&&ne?.type==="arguments_delta"){let se=typeof ne.arguments==="string"?ne.arguments:"";if(se.length>0)ie.argumentsAccum+=se,Ee.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:se});if(ne.id!=null&&ne.id.length>0)ie.toolCallId=ne.id;if(ne.signature!=null)ie.signature=ne.signature;V=!0}else if(ie.kind==="builtin_tool_call"&&ne?.type===ie.blockType){if(ne.id!=null&&ne.id.length>0)ie.toolCallId=ne.id;if(ne.arguments!=null&&typeof ne.arguments==="object")ie.arguments=ne.arguments;if(ne.name!=null&&ie.blockType==="mcp_server_tool_call")ie.toolName=ne.name}else if(ie.kind==="builtin_tool_result"&&ne?.type===ie.blockType){if(ne.call_id!=null&&ne.call_id.length>0)ie.callId=ne.call_id;if(ne.result!==void 0)ie.result=ne.result;if(ne.is_error!=null)ie.isError=ne.is_error;if(ne.name!=null&&ie.blockType==="mcp_server_tool_result")ie.toolName=ne.name}break}case"step.stop":{let ye=je,ie=ce.get(ye.index);if(ie==null)break;if(ie.kind==="text"){let be=q!=null?{google:{interactionId:q}}:void 0;Ee.enqueue({type:"text-end",id:ie.id,...be?{providerMetadata:be}:{}})}else if(ie.kind==="reasoning"){let be={};if(ie.signature!=null)be.signature=ie.signature;if(q!=null)be.interactionId=q;let ne=Object.keys(be).length>0?{google:be}:void 0;Ee.enqueue({type:"reasoning-end",id:ie.id,...ne?{providerMetadata:ne}:{}})}else if(ie.kind==="image"){let be={};if(q!=null)be.interactionId=q;let ne=Object.keys(be).length>0?{google:be}:void 0;if(ie.data!=null&&ie.data.length>0)Ee.enqueue({type:"file",mediaType:ie.mimeType??"image/png",data:{type:"data",data:ie.data},...ne?{providerMetadata:ne}:{}});else if(ie.uri!=null&&ie.uri.length>0)Ee.enqueue({type:"file",mediaType:ie.mimeType??"image/png",data:{type:"url",url:new URL(ie.uri)},...ne?{providerMetadata:ne}:{}})}else if(ie.kind==="function_call"){let be=ie.argumentsAccum.length>0?ie.argumentsAccum:"{}";Ee.enqueue({type:"tool-input-end",id:ie.toolCallId});let ne={};if(ie.signature!=null)ne.signature=ie.signature;if(q!=null)ne.interactionId=q;let se=Object.keys(ne).length>0?{google:ne}:void 0;Ee.enqueue({type:"tool-call",toolCallId:ie.toolCallId,toolName:ie.toolName,input:be,...se?{providerMetadata:se}:{}})}else if(ie.kind==="custom")Ee.enqueue({type:"custom",kind:ie.customKind,providerMetadata:{google:ie.google}});else if(ie.kind==="builtin_tool_call"&&!ie.callEmitted)Ee.enqueue({type:"tool-call",toolCallId:ie.toolCallId,toolName:ie.toolName,input:JSON.stringify(ie.arguments??{}),providerExecuted:!0}),ie.callEmitted=!0;else if(ie.kind==="builtin_tool_result"&&!ie.resultEmitted){Ee.enqueue({type:"tool-result",toolCallId:ie.callId,toolName:ie.toolName,result:ie.result??null}),ie.resultEmitted=!0;let be=An({block:{type:ie.blockType,call_id:ie.callId,result:ie.result},generateId:w});for(let ne of be){let se=Le(ne);if(Re.has(se))continue;Re.add(se),Ee.enqueue(ne)}}ce.delete(ye.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{let ye=je;if(ye.status!=null)ee=ye.status;else if(Ne==="interaction.requires_action")ee="requires_action";else ee="in_progress";break}case"interaction.completed":{pe=!0;let ye=je.interaction;if(ye?.id!=null&&ye.id.length>0)q=ye.id;if(ye?.status!=null)ee=ye.status;if(ye?.usage!=null)B=ye.usage;if(ye?.service_tier!=null)re=ye.service_tier;break}case"error":{let ye=je;ee="failed",Ee.enqueue({type:"error",error:xe({message:ye.error?.message??"Unknown interaction error",type:ye.event_type,code:ye.error?.code??void 0,data:ye})});break}}},flush(Ce){let Ee=!pe&&(ee==null||ee==="in_progress"),je={unified:Ee?"interrupted":Vt({status:ee,hasFunctionCall:V}),raw:Ee?void 0:ee},Ne=On(B),ye={google:{...q!=null?{interactionId:q}:{},...re!=null?{serviceTier:re}:{},...Ne!=null?{outputTokensByModality:Ne}:{}}};Ce.enqueue({type:"finish",finishReason:je,usage:Ht(B),providerMetadata:ye})}})}function Mi({prompt:f,previousInteractionId:w,store:x,mediaResolution:A}){let q=[],B=w!=null&&x===!1,re=w!=null&&x!==!1;if(B)q.push({type:"other",message:"google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted."});let ee=re?Ai({prompt:f,previousInteractionId:w}):f,V=[],pe=[];for(let ce of ee)switch(ce.role){case"system":V.push(ce.content);break;case"user":{let Re=[];for(let Ce of ce.content)if(Ce.type==="text")Re.push({type:"text",text:Ce.text});else if(Ce.type==="file"){let Ee=pn({part:Ce,warnings:q,mediaResolution:A});if(Ee!=null)Re.push(Ee)}let Le=Ni(Re);if(Le.length>0)pe.push({type:"user_input",content:Le});break}case"assistant":{let Re=[],Le=()=>{if(Re.length>0)pe.push({type:"model_output",content:Re}),Re=[]};for(let Ce of ce.content)if(Ce.type==="text")Re.push({type:"text",text:Ce.text});else if(Ce.type==="reasoning"){Le();let Ee=Ce.providerOptions?.google?.signature;pe.push({type:"thought",...Ee!=null?{signature:Ee}:{},summary:Ce.text.length>0?[{type:"text",text:Ce.text}]:void 0})}else if(Ce.type==="file"){let Ee=pn({part:Ce,warnings:q,mediaResolution:A});if(Ee!=null)Re.push(Ee)}else if(Ce.type==="custom"){Le();let Ee=Ce.providerOptions?.google,je=typeof Ee?.signature==="string"?Ee.signature:void 0;if(Ce.kind==="google.processing_call"&&typeof Ee?.processingId==="string")pe.push({type:"processing_call",id:Ee.processingId,...je!=null?{signature:je}:{}});else if(Ce.kind==="google.processing_result"&&typeof Ee?.processingCallId==="string")pe.push({type:"processing_result",call_id:Ee.processingCallId,...je!=null?{signature:je}:{}});else q.push({type:"other",message:`google.interactions: unsupported or invalid custom assistant content part "${Ce.kind}"; part dropped.`})}else if(Ce.type==="tool-call"){Le();let Ee=Ce.providerOptions?.google?.signature,je=typeof Ce.input==="string"?Li(Ce.input):Ce.input??{};pe.push({type:"function_call",id:Ce.toolCallId,name:Ce.toolName,arguments:je,...Ee!=null?{signature:Ee}:{}})}else q.push({type:"other",message:`google.interactions: unsupported assistant content part type "${Ce.type}"; part dropped.`});Le();break}case"tool":{let Re=[];for(let Le of ce.content){if(Le.type!=="tool-result"){q.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:q});Re.push(Ce)}if(Re.length>0)pe.push({type:"user_input",content:Re});break}}return{input:pe,systemInstruction:V.length>0?V.join(`
10
+
11
+ `):void 0,warnings:q}}function pn({part:f,warnings:w,mediaResolution:x}){if(f.data.type==="text")return{type:"text",text:f.data.text};let A=z(f.mediaType),q;switch(A){case"image":q="image";break;case"audio":q="audio";break;case"video":q="video";break;case"application":case"text":q="document";break;default:q=void 0}if(q==null){w.push({type:"other",message:`google.interactions: unsupported file media type "${f.mediaType}"; part dropped.`});return}let B=x!=null&&(q==="image"||q==="video")?{resolution:x}:{},re=q==="video"?Ei({part:f,warnings:w}):{};switch(f.data.type){case"data":{let ee=O({part:f});return{type:q,data:M(f.data.data),mime_type:ee,...B,...re}}case"url":return{type:q,uri:f.data.url.toString(),...K(f.mediaType)?{mime_type:f.mediaType}:{},...B,...re};case"reference":{let ee=H({reference:f.data.reference,provider:"google"});return{type:q,uri:ee,...K(f.mediaType)?{mime_type:f.mediaType}:{},...B,...re}}}}function Ei({part:f,warnings:w}){let x=f.providerOptions?.google?.processing;if(x==null)return{};if(x==="agentic"||x==="static")return{processing:x};if(typeof x==="object"&&!Array.isArray(x)&&x.type==="static"){let A=x;return{processing:{type:"static",...typeof A.startOffset==="number"?{start_offset:`${A.startOffset}s`}:{},...typeof A.endOffset==="number"?{end_offset:`${A.endOffset}s`}:{},...typeof A.fps==="number"?{fps:A.fps}:{}}}}return w.push({type:"other",message:'google.interactions: invalid providerOptions.google.processing on video file part; expected "agentic", "static", or a static processing configuration. Option dropped.'}),{}}function Ai({prompt:f,previousInteractionId:w}){let x=[],A=new Set;for(let q of f){if(q.role==="assistant"){if(q.content.some((B)=>B.providerOptions?.google?.interactionId===w)){for(let B of q.content)if(B.type==="tool-call")A.add(B.toolCallId);continue}x.push(q);continue}if(q.role==="tool"){let B=q.content.filter((re)=>{if(re.type!=="tool-result")return!0;return!A.has(re.toolCallId)});if(B.length===0)continue;x.push({...q,content:B});continue}x.push(q)}return x}function Li(f){try{let w=Q(f);if(w!=null&&typeof w==="object"&&!Array.isArray(w))return w;return{value:w}}catch{return{value:f}}}function ji({toolCallId:f,toolName:w,output:x,signature:A,warnings:q}){let B={type:"function_result",call_id:f,name:w,...A!=null?{signature:A}:{}};switch(x.type){case"text":return{...B,result:x.value};case"json":return{...B,result:JSON.stringify(x.value)};case"error-text":return{...B,is_error:!0,result:x.value};case"error-json":return{...B,is_error:!0,result:JSON.stringify(x.value)};case"execution-denied":return{...B,is_error:!0,result:x.reason??"Tool execution denied by user."};case"content":{let re=[];for(let ee of x.value)if(ee.type==="text")re.push({type:"text",text:ee.text});else if(ee.type==="file"){if(z(ee.mediaType)!=="image"){q.push({type:"other",message:`google.interactions: tool-result file with mediaType "${ee.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let V=Ui({part:ee,warnings:q});if(V!=null)re.push(V)}else q.push({type:"other",message:`google.interactions: tool-result content part type "${ee.type}" is not supported; part dropped.`});return{...B,result:re}}}}function Ui({part:f,warnings:w}){switch(f.data.type){case"data":{let x=K(f.mediaType)?f.mediaType:O({part:{type:"file",mediaType:f.mediaType,data:f.data}});return{type:"image",data:M(f.data.data),mime_type:x}}case"url":return{type:"image",uri:f.data.url.toString(),...K(f.mediaType)?{mime_type:f.mediaType}:{}};case"reference":return{type:"image",uri:H({reference:f.data.reference,provider:"google"}),...K(f.mediaType)?{mime_type:f.mediaType}:{}};case"text":w.push({type:"other",message:'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'});return}}function Ni(f){if(f.length<2)return f;let w=[];for(let x of f){let A=w[w.length-1];if(x.type==="text"&&A!=null&&A.type==="text"&&A.annotations==null&&x.annotations==null){let q={type:"text",text:`${A.text}
12
+
13
+ ${x.text}`};w[w.length-1]=q;continue}w.push(x)}return w}var Mt=()=>t({modality:e().nullish(),tokens:r().nullish()}).loose(),Ln=()=>t({total_input_tokens:r().nullish(),total_output_tokens:r().nullish(),total_thought_tokens:r().nullish(),total_cached_tokens:r().nullish(),total_tool_use_tokens:r().nullish(),total_tokens:r().nullish(),input_tokens_by_modality:o(Mt()).nullish(),output_tokens_by_modality:o(Mt()).nullish(),cached_tokens_by_modality:o(Mt()).nullish(),tool_use_tokens_by_modality:o(Mt()).nullish(),grounding_tool_count:o(t({type:e().nullish(),count:r().nullish()}).loose()).nullish()}).loose(),jn=()=>i(["in_progress","requires_action","completed","failed","cancelled","incomplete"]),Un=()=>{let f=t({type:n("url_citation"),url:e().nullish(),title:e().nullish(),start_index:r().nullish(),end_index:r().nullish()}).loose(),w=t({type:n("file_citation"),file_name:e().nullish(),document_uri:e().nullish(),url:e().nullish(),page_number:r().nullish(),media_id:e().nullish(),start_index:r().nullish(),end_index:r().nullish(),custom_metadata:y(e(),v()).nullish()}).loose(),x=t({type:n("place_citation"),name:e().nullish(),url:e().nullish(),place_id:e().nullish(),start_index:r().nullish(),end_index:r().nullish()}).loose();return l([f,w,x,t({type:e()}).loose()])},Nn=()=>t({type:e(),text:e().nullish(),data:e().nullish(),mime_type:e().nullish()}).loose(),gn=()=>{let f=t({type:n("text"),text:e(),annotations:o(Un()).nullish()}).loose(),w=t({type:n("image"),data:e().nullish(),mime_type:e().nullish(),resolution:i(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),x=t({type:n("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose();return l([f,w,x,t({type:e()}).loose()])},Gn=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],Dn=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],Pn=()=>{let f=t({type:n("user_input"),content:o(gn()).nullish()}).loose(),w=t({type:n("model_output"),content:o(gn()).nullish()}).loose(),x=t({type:n("function_call"),id:e(),name:e(),arguments:y(e(),v()).nullish(),signature:e().nullish()}).loose(),A=t({type:n("thought"),signature:e().nullish(),summary:o(Nn()).nullish()}).loose(),q=t({type:n("processing_call"),id:e(),signature:e().nullish()}).loose(),B=t({type:n("processing_result"),call_id:e(),signature:e().nullish()}).loose(),re=t({type:i(Gn),id:e(),arguments:y(e(),v()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),ee=t({type:i(Dn),call_id:e(),result:v().nullish(),is_error:c().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose();return l([f,w,x,A,q,B,re,ee,t({type:e()}).loose()])},qt=a(()=>s(t({id:e().nullish(),created:e().nullish(),updated:e().nullish(),status:jn(),model:e().nullish(),agent:e().nullish(),steps:o(Pn()).nullish(),usage:Ln().nullish(),service_tier:e().nullish(),previous_interaction_id:e().nullish(),response_modalities:o(e()).nullish()}).loose())),qn=a(()=>s((()=>{let f=jn(),w=Un(),x=Nn(),A=t({event_type:n("interaction.created"),event_id:e().nullish(),interaction:t({id:e().nullish(),created:e().nullish(),model:e().nullish(),agent:e().nullish(),status:f.nullish()}).loose()}).loose(),q=t({event_type:n("step.start"),event_id:e().nullish(),index:r(),step:Pn()}).loose(),B=t({type:n("text"),text:e()}).loose(),re=t({type:n("thought_summary"),content:x.nullish()}).loose(),ee=t({type:n("thought_signature"),signature:e().nullish()}).loose(),V=t({type:n("arguments_delta"),arguments:e().nullish(),id:e().nullish(),signature:e().nullish()}).loose(),pe=t({type:i(["text_annotation_delta","text_annotation"]),annotations:o(w).nullish()}).loose(),ce=t({type:n("image"),data:e().nullish(),mime_type:e().nullish(),resolution:i(["low","medium","high","ultra_high"]).nullish(),uri:e().nullish()}).loose(),Re=t({type:n("video"),data:e().nullish(),mime_type:e().nullish(),uri:e().nullish()}).loose(),Le=t({type:i(Gn),id:e().nullish(),arguments:y(e(),v()).nullish(),name:e().nullish(),server_name:e().nullish(),search_type:e().nullish(),signature:e().nullish()}).loose(),Ce=t({type:i(Dn),call_id:e().nullish(),result:v().nullish(),is_error:c().nullish(),name:e().nullish(),server_name:e().nullish(),signature:e().nullish()}).loose(),Ee=t({type:e()}).loose(),je=l([B,ce,Re,re,ee,V,pe,Le,Ce,Ee]),Ne=t({event_type:n("step.delta"),event_id:e().nullish(),index:r(),delta:je}).loose(),ye=t({event_type:n("step.stop"),event_id:e().nullish(),index:r()}).loose(),ie=t({event_type:n("interaction.status_update"),event_id:e().nullish(),interaction_id:e().nullish(),status:f.nullish()}).loose(),be=t({event_type:n("interaction.in_progress"),event_id:e().nullish(),interaction_id:e().nullish(),status:f.nullish()}).loose(),ne=t({event_type:n("interaction.requires_action"),event_id:e().nullish(),interaction_id:e().nullish(),status:f.nullish()}).loose(),se=t({event_type:n("interaction.completed"),event_id:e().nullish(),interaction:t({id:e().nullish(),status:f.nullish(),usage:Ln().nullish(),service_tier:e().nullish()}).loose()}).loose(),Ue=t({event_type:n("error"),event_id:e().nullish(),error:t({code:e().nullish(),message:e().nullish()}).loose().nullish()}).loose(),De=t({event_type:e()}).loose();return l([A,q,Ne,ye,ie,be,ne,se,Ue,De])})())),Gi=a(()=>s(t({previousInteractionId:e().nullish(),store:c().nullish(),agent:e().nullish(),agentConfig:l([t({type:n("dynamic")}).loose(),t({type:n("deep-research"),thinkingSummaries:i(["auto","none"]).nullish(),visualization:i(["off","auto"]).nullish(),collaborativePlanning:c().nullish()})]).nullish(),thinkingLevel:i(["minimal","low","medium","high"]).nullish(),thinkingSummaries:i(["auto","none"]).nullish(),responseFormat:o(l([t({type:n("text"),mimeType:e().nullish(),schema:v().nullish()}).loose(),t({type:n("image"),mimeType:e().nullish(),aspectRatio:i(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:i(["1K","2K","4K","512"]).nullish()}).loose(),t({type:n("audio"),mimeType:e().nullish()}).loose(),t({type:n("video"),aspectRatio:i(["16:9","9:16"]).nullish(),resolution:i(["360p","720p","1080p","4k"]).nullish(),duration:e().nullish(),delivery:i(["inline","uri"]).nullish(),gcsUri:e().nullish()}).loose()])).nullish(),imageConfig:t({aspectRatio:i(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:i(["1K","2K","4K","512"]).nullish()}).nullish(),mediaResolution:i(["low","medium","high","ultra_high"]).nullish(),responseModalities:o(i(["text","image","audio","video","document"])).nullish(),serviceTier:i(["flex","standard","priority"]).nullish(),systemInstruction:e().nullish(),signature:e().nullish(),interactionId:e().nullish(),pollingTimeoutMs:r().int().positive().nullish(),background:c().nullish(),environment:l([e(),t({type:n("remote"),sources:o(l([t({type:n("gcs"),source:e(),target:e().nullish()}),t({type:n("repository"),source:e(),target:e().nullish()}),t({type:n("inline"),content:e(),target:e()})])).nullish(),network:l([n("disabled"),t({allowlist:o(t({domain:e(),transform:o(y(e(),e())).nullish()}))})]).nullish()})]).nullish()})));function mt({signature:f,interactionId:w,processingId:x,processingCallId:A}){let q={};if(f!=null)q.signature=f;if(w!=null)q.interactionId=w;if(x!=null)q.processingId=x;if(A!=null)q.processingCallId=A;return Object.keys(q).length>0?{providerMetadata:{google:q}}:{}}var Di=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),Pi=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function qi(f){return f.replace(/_call$/,"")}function $i(f){return f.replace(/_result$/,"")}function $n({steps:f,generateId:w,interactionId:x}){let A=[],q=!1;if(f==null)return{content:A,hasFunctionCall:q};for(let B of f){if(B==null||typeof B!=="object")continue;let re=B.type;if(typeof re!=="string")continue;switch(re){case"user_input":break;case"model_output":{let ee=B.content??[];for(let V of ee){if(V==null||typeof V!=="object")continue;let pe=V.type;if(pe==="text"){let ce=V.text??"",Re=V.annotations;A.push({type:"text",text:ce,...mt({interactionId:x})});let Le=Pt({annotations:Re,generateId:w});for(let Ce of Le)A.push(Ce)}else if(pe==="image"){let ce=V;if(ce.data!=null&&ce.data.length>0)A.push({type:"file",mediaType:ce.mime_type??"image/png",data:{type:"data",data:ce.data},...mt({interactionId:x})});else if(ce.uri!=null&&ce.uri.length>0)A.push({type:"file",mediaType:ce.mime_type??"image/png",data:{type:"url",url:new URL(ce.uri)},...mt({interactionId:x})})}else if(pe==="video"){let ce=V;if(ce.data!=null&&ce.data.length>0)A.push({type:"file",mediaType:ce.mime_type??"video/mp4",data:{type:"data",data:ce.data},...mt({interactionId:x})});else if(ce.uri!=null&&ce.uri.length>0)A.push({type:"file",mediaType:ce.mime_type??"video/mp4",data:{type:"url",url:new URL(ce.uri)},...mt({interactionId:x})})}}break}case"thought":{let ee=B,V=(Array.isArray(ee.summary)?ee.summary:[]).filter((pe)=>pe?.type==="text"&&typeof pe.text==="string").map((pe)=>pe.text).join(`
14
+ `);A.push({type:"reasoning",text:V,...mt({signature:ee.signature,interactionId:x})});break}case"processing_call":{let ee=B,V=ee.id||w();A.push({type:"custom",kind:"google.processing_call",...mt({signature:ee.signature,interactionId:x,processingId:V})});break}case"processing_result":{let ee=B,V=ee.call_id||w();A.push({type:"custom",kind:"google.processing_result",...mt({signature:ee.signature,interactionId:x,processingCallId:V})});break}case"function_call":{q=!0;let ee=B;A.push({type:"tool-call",toolCallId:ee.id,toolName:ee.name,input:JSON.stringify(ee.arguments??{}),...mt({signature:ee.signature,interactionId:x})});break}default:if(Di.has(re)){let ee=B,V=re==="mcp_server_tool_call"?ee.name??"mcp_server_tool":qi(re),pe=JSON.stringify(ee.arguments??{});A.push({type:"tool-call",toolCallId:ee.id||w(),toolName:V,input:pe,providerExecuted:!0})}else if(Pi.has(re)){let ee=B,V=re==="mcp_server_tool_result"?ee.name??"mcp_server_tool":$i(re);A.push({type:"tool-result",toolCallId:ee.call_id||w(),toolName:V,result:ee.result??null});let pe=An({block:B,generateId:w});for(let ce of pe)A.push(ce)}}}return{content:A,hasFunctionCall:q}}var Fi=()=>globalThis.fetch;async function Fn({baseURL:f,interactionId:w,headers:x,fetch:A=Fi()}){if(w==null||w.length===0)return;let q=`${f}/interactions/${encodeURIComponent(w)}/cancel`;try{let B=await A(q,{method:"POST",headers:F(d({"Content-Type":"application/json"},x),ke()),body:"{}"});try{await B.text()}catch{}}catch{}}var Bi=new Set(["completed","failed","cancelled","incomplete"]);function $t(f){return f!=null&&Bi.has(f)}var Hi=1000,Vi=1e4,Wi=1800000;async function Ki({baseURL:f,interactionId:w,headers:x,fetch:A,abortSignal:q,initialDelayMs:B=Hi,maxDelayMs:re=Vi,timeoutMs:ee=Wi}){if(w==null||w.length===0)throw Error("google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.");let V=Date.now(),pe=B,ce=`${f}/interactions/${encodeURIComponent(w)}`,Re=()=>Fn({baseURL:f,interactionId:w,headers:x,fetch:A});try{while(!0){if(q?.aborted)throw await Re(),new DOMException("Polling was aborted","AbortError");if(Date.now()-V>ee)throw Error(`google.interactions: timed out polling interaction ${w} after ${ee}ms.`);await Oe(pe,{abortSignal:q});let{value:Le,rawValue:Ce,responseHeaders:Ee}=await R({url:ce,validateUrl:!1,headers:x,failedResponseHandler:Xe,successfulResponseHandler:p(qt),abortSignal:q,fetch:A});if($t(Le.status))return{response:Le,rawResponse:Ce,responseHeaders:Ee};pe=Math.min(pe*2,re)}}catch(Le){if(Z(Le))await Re();throw Le}}function zi({tools:f,toolChoice:w}){let x=[],A=f?.length?f:void 0;if(A==null)return{tools:void 0,toolChoice:void 0,toolWarnings:x};let q=[];for(let ee of A){if(ee.type==="function"){q.push({type:"function",name:ee.name,description:ee.description??"",parameters:ee.inputSchema});continue}if(ee.type==="provider"){let V=ee.args??{};switch(ee.id){case"google.google_search":{let pe=V.searchTypes,ce;if(pe!=null&&typeof pe==="object"){let Re=[];if(pe.webSearch!=null)Re.push("web_search");if(pe.imageSearch!=null)Re.push("image_search");if(Re.length>0)ce=Re}q.push({type:"google_search",...ce!=null?{search_types:ce}:{}});break}case"google.code_execution":q.push({type:"code_execution"});break;case"google.url_context":q.push({type:"url_context"});break;case"google.file_search":q.push({type:"file_search",...V.fileSearchStoreNames!=null?{file_search_store_names:V.fileSearchStoreNames}:{},...V.topK!=null?{top_k:V.topK}:{},...V.metadataFilter!=null?{metadata_filter:V.metadataFilter}:{}});break;case"google.google_maps":q.push({type:"google_maps",...V.latitude!=null?{latitude:V.latitude}:{},...V.longitude!=null?{longitude:V.longitude}:{},...V.enableWidget!=null?{enable_widget:V.enableWidget}:{}});break;case"google.computer_use":q.push({type:"computer_use",environment:V.environment??"browser",...V.excludedPredefinedFunctions!=null?{excludedPredefinedFunctions:V.excludedPredefinedFunctions}:{}});break;case"google.mcp_server":q.push({type:"mcp_server",...V.name!=null?{name:V.name}:{},...V.url!=null?{url:V.url}:{},...V.headers!=null?{headers:V.headers}:{},...V.allowedTools!=null?{allowed_tools:V.allowedTools}:{}});break;case"google.retrieval":{let pe=V.vertexAiSearchConfig??void 0;q.push({type:"retrieval",...V.retrievalTypes!=null?{retrieval_types:V.retrievalTypes}:{retrieval_types:["vertex_ai_search"]},...pe!=null?{vertex_ai_search_config:pe}:{}});break}default:x.push({type:"unsupported",feature:`provider-defined tool ${ee.id}`,details:`provider-defined tool ${ee.id} is not supported by google.interactions; tool dropped.`})}continue}x.push({type:"unsupported",feature:`tool of type ${ee.type}`,details:"Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."})}let B=q.some((ee)=>ee.type==="function"),re;if(w!=null&&B)switch(w.type){case"auto":re="auto";break;case"required":re="any";break;case"none":re="none";break;case"tool":re={allowed_tools:{mode:"validated",tools:[w.toolName]}}}return{tools:q.length>0?q:void 0,toolChoice:re,toolWarnings:x}}var Ji=3,Yi=500;function Xi({baseURL:f,interactionId:w,headers:x,fetch:A,abortSignal:q,maxRetries:B=Ji,retryDelayMs:re=Yi}){if(w.length===0)throw Error("google.interactions: cannot stream a background interaction without an id.");let ee={...x,accept:"text/event-stream"},V,pe=!1,ce=0,Re=!1,Le,Ce=new AbortController,Ee=()=>Ce.abort();if(q!=null)if(q.aborted)Ce.abort();else q.addEventListener("abort",Ee,{once:!0});let je=Ce.signal;function Ne(){let ie=`${f}/interactions/${encodeURIComponent(w)}`,be=new URLSearchParams({stream:"true"});if(V!=null)be.set("last_event_id",V);return`${ie}?${be.toString()}`}async function ye(){let{value:ie}=await R({url:Ne(),validateUrl:!1,headers:ee,failedResponseHandler:Xe,successfulResponseHandler:D(qn),abortSignal:je,fetch:A});return ie.getReader()}return new ReadableStream({async start(ie){try{while(!pe&&!je.aborted){if(Le==null)try{Le=await ye(),Re=!1}catch(be){if(Z(be)||je.aborted){ie.error(be);return}if(ce++,ce>=B){ie.error(be);return}await Oe(re*ce,{abortSignal:je});continue}try{let{done:be,value:ne}=await Le.read();if(be){if(Le=void 0,pe)break;if(!Re){if(ce++,ce>=B){ie.error(Error("google.interactions: SSE stream closed without producing any events."));return}await Oe(re*ce,{abortSignal:je})}else ce=0;continue}if(Re=!0,ne.success){let se=ne.value;if(typeof se.event_id==="string"&&se.event_id.length>0)V=se.event_id;if(se.event_type==="interaction.completed"||se.event_type==="error")pe=!0}ie.enqueue(ne)}catch(be){if(Z(be)||je.aborted){ie.error(be);return}if(Le=void 0,ce++,ce>=B){ie.error(be);return}await Oe(re*ce,{abortSignal:je})}}ie.close()}catch(be){ie.error(be)}finally{if(q!=null)q.removeEventListener("abort",Ee);if(Le?.cancel().catch(()=>{}),Le=void 0,je.aborted&&!pe)await Fn({baseURL:f,interactionId:w,headers:x,fetch:A})}},cancel(){Ce.abort(),Le?.cancel().catch(()=>{}),Le=void 0}})}function Qi({response:f,warnings:w,generateId:x,includeRawChunks:A,headerServiceTier:q}){return new ReadableStream({start(B){B.enqueue({type:"stream-start",warnings:w});let re=typeof f.id==="string"&&f.id.length>0?f.id:void 0,ee,V=f.created;if(typeof V==="string"){let Ne=new Date(V);if(!Number.isNaN(Ne.getTime()))ee=Ne}if(B.enqueue({type:"response-metadata",...re!=null?{id:re}:{},modelId:f.model??void 0,...ee?{timestamp:ee}:{}}),A)B.enqueue({type:"raw",rawValue:f});let{content:pe,hasFunctionCall:ce}=$n({steps:f.steps??null,generateId:x,interactionId:re}),Re=0,Le=()=>`${re??"agent"}:${Re++}`;for(let Ne of pe)switch(Ne.type){case"text":{let ye=Le(),ie=Ne.providerMetadata;if(B.enqueue({type:"text-start",id:ye}),Ne.text.length>0)B.enqueue({type:"text-delta",id:ye,delta:Ne.text});B.enqueue({type:"text-end",id:ye,...ie?{providerMetadata:ie}:{}});break}case"reasoning":{let ye=Le(),ie=Ne.providerMetadata;if(B.enqueue({type:"reasoning-start",id:ye}),Ne.text.length>0)B.enqueue({type:"reasoning-delta",id:ye,delta:Ne.text});B.enqueue({type:"reasoning-end",id:ye,...ie?{providerMetadata:ie}:{}});break}case"tool-call":{let ye=Ne.providerMetadata;B.enqueue({type:"tool-input-start",id:Ne.toolCallId,toolName:Ne.toolName,...Ne.providerExecuted?{providerExecuted:Ne.providerExecuted}:{}}),B.enqueue({type:"tool-input-delta",id:Ne.toolCallId,delta:Ne.input}),B.enqueue({type:"tool-input-end",id:Ne.toolCallId}),B.enqueue({type:"tool-call",toolCallId:Ne.toolCallId,toolName:Ne.toolName,input:Ne.input,...Ne.providerExecuted?{providerExecuted:Ne.providerExecuted}:{},...ye?{providerMetadata:ye}:{}});break}case"tool-result":B.enqueue({type:"tool-result",toolCallId:Ne.toolCallId,toolName:Ne.toolName,result:Ne.result});break;case"source":case"file":B.enqueue(Ne)}let Ce=f.service_tier??q,Ee={unified:Vt({status:f.status,hasFunctionCall:ce}),raw:f.status},je={google:{...re!=null?{interactionId:re}:{},...Ce!=null?{serviceTier:Ce}:{}}};B.enqueue({type:"finish",finishReason:Ee,usage:Ht(f.usage),providerMetadata:je}),B.close()}})}var Zi=class f{static[k](w){return{...E({modelId:w.modelId,config:w.config}),agent:w.agent}}static[T](w){return new f(w.agent!=null?{agent:w.agent}:w.modelId,w.config)}constructor(w,x){if(this.specificationVersion="v4",typeof w==="string")this.modelId=w,this.agent=void 0;else if("managedAgent"in w)this.modelId=w.managedAgent,this.agent=w.managedAgent;else this.modelId=w.agent,this.agent=w.agent;this.config=x}get provider(){return this.config.provider}get supportedUrls(){if(this.config.supportedUrls)return this.config.supportedUrls();return{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(w){let x=[],A=await h({provider:"google",providerOptions:w.providerOptions,schema:Gi}),q=this.agent!=null;if(!q){if(w.frequencyPenalty!=null)x.push({type:"unsupported",feature:"frequencyPenalty"});if(w.presencePenalty!=null)x.push({type:"unsupported",feature:"presencePenalty"})}let B=w.tools!=null&&w.tools.length>0,re,ee;if(B){let ye=zi({tools:w.tools,toolChoice:w.toolChoice});re=ye.tools,ee=ye.toolChoice,x.push(...ye.toolWarnings)}let V=[];if(w.responseFormat?.type==="json")if(q)x.push({type:"other",message:"google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."});else{let ye={type:"text",mime_type:"application/json",...w.responseFormat.schema!=null?{schema:w.responseFormat.schema}:{}};V.push(ye)}if(A?.responseFormat!=null){for(let ye of A.responseFormat)if(ye.type==="text")V.push(ht({type:"text",mime_type:ye.mimeType??void 0,schema:ye.schema??void 0}));else if(ye.type==="image")V.push(ht({type:"image",mime_type:ye.mimeType??void 0,aspect_ratio:ye.aspectRatio??void 0,image_size:ye.imageSize??void 0}));else if(ye.type==="audio")V.push(ht({type:"audio",mime_type:ye.mimeType??void 0}));else if(ye.type==="video")V.push(ht({type:"video",aspect_ratio:ye.aspectRatio??void 0,resolution:ye.resolution??void 0,duration:ye.duration??void 0,delivery:ye.delivery??void 0,gcs_uri:ye.gcsUri??void 0}))}let{input:pe,systemInstruction:ce,warnings:Re}=Mi({prompt:w.prompt,previousInteractionId:A?.previousInteractionId??void 0,store:A?.store??void 0,mediaResolution:A?.mediaResolution??void 0});x.push(...Re);let Le=ce,Ce=A?.systemInstruction??void 0;if(Le!=null&&Ce!=null)x.push({type:"other",message:"google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."});else if(Le==null&&Ce!=null)Le=Ce;let Ee;if(q){let ye=[];if(w.temperature!=null)ye.push("temperature");if(w.topP!=null)ye.push("topP");if(w.topK!=null)ye.push("topK");if(w.frequencyPenalty!=null)ye.push("frequencyPenalty");if(w.presencePenalty!=null)ye.push("presencePenalty");if(w.seed!=null)ye.push("seed");if(w.stopSequences!=null&&w.stopSequences.length>0)ye.push("stopSequences");if(w.maxOutputTokens!=null)ye.push("maxOutputTokens");if(A?.thinkingLevel!=null)ye.push("thinkingLevel");if(A?.thinkingSummaries!=null)ye.push("thinkingSummaries");if(A?.imageConfig!=null)ye.push("imageConfig");if(ye.length>0)x.push({type:"other",message:`google.interactions: ${ye.join(", ")} ${ye.length===1?"is":"are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`});Ee=void 0}else if(Ee=ht({temperature:w.temperature??void 0,top_p:w.topP??void 0,top_k:w.topK??void 0,seed:w.seed??void 0,stop_sequences:w.stopSequences!=null&&w.stopSequences.length>0?w.stopSequences:void 0,max_output_tokens:w.maxOutputTokens??void 0,thinking_level:A?.thinkingLevel??void 0,thinking_summaries:A?.thinkingSummaries??void 0,tool_choice:ee}),A?.imageConfig!=null){let ye=V.some((ie)=>ie.type==="image");if(x.push({type:"other",message:ye?"google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.":'google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.'}),!ye)V.push({type:"image",mime_type:"image/png",...A.imageConfig.aspectRatio!=null?{aspect_ratio:A.imageConfig.aspectRatio}:{},...A.imageConfig.imageSize!=null?{image_size:A.imageConfig.imageSize}:{}})}let je;if(q&&A?.agentConfig!=null){let ye=A.agentConfig;if(ye.type==="deep-research")je=ht({type:"deep-research",thinking_summaries:ye.thinkingSummaries??void 0,visualization:ye.visualization??void 0,collaborative_planning:ye.collaborativePlanning??void 0});else if(ye.type==="dynamic")je={type:"dynamic"}}let Ne;if(A?.environment!=null)if(!q)x.push({type:"other",message:"google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."});else if(typeof A.environment==="string")Ne=A.environment;else{let ye=A.environment,ie=ye.sources?.map((ne)=>{if(ne.type==="inline")return{type:"inline",content:ne.content,target:ne.target};return ht({type:ne.type,source:ne.source,target:ne.target??void 0})}),be;if(ye.network==="disabled")be="disabled";else if(ye.network!=null)be={allowlist:ye.network.allowlist.map((ne)=>ht({domain:ne.domain,transform:ne.transform??void 0}))};Ne=ht({type:"remote",sources:ie!=null&&ie.length>0?ie:void 0,network:be})}return{args:ht({...q?{agent:this.agent}:{model:this.modelId},input:pe,system_instruction:Le,tools:re,response_format:V.length>0?V:void 0,response_modalities:A?.responseModalities!=null?A.responseModalities:void 0,previous_interaction_id:A?.previousInteractionId??void 0,service_tier:A?.serviceTier??void 0,store:A?.store??void 0,generation_config:Ee!=null&&Object.keys(Ee).length>0?Ee:void 0,agent_config:je,environment:Ne,background:A?.background??void 0}),warnings:x,isAgent:q,isBackground:A?.background===!0,pollingTimeoutMs:A?.pollingTimeoutMs??void 0}}async doGenerate(w){let{args:x,warnings:A,isAgent:q,isBackground:B,pollingTimeoutMs:re}=await this.getArgs(w),ee=`${this.config.baseURL}/interactions`,V=d(this.config.headers?await _(this.config.headers):void 0,w.headers),{responseHeaders:pe,value:ce,rawValue:Re}=await g({url:ee,headers:V,body:x,failedResponseHandler:Xe,successfulResponseHandler:p(qt),abortSignal:w.abortSignal,fetch:this.config.fetch});if((q||B)&&!$t(ce.status)){let ne=await Ki({baseURL:this.config.baseURL,interactionId:ce.id,headers:V,fetch:this.config.fetch,abortSignal:w.abortSignal,timeoutMs:re});ce=ne.response,Re=ne.rawResponse,pe=ne.responseHeaders??pe}let Le=typeof ce.id==="string"&&ce.id.length>0?ce.id:void 0,{content:Ce,hasFunctionCall:Ee}=$n({steps:ce.steps??null,generateId:this.config.generateId??C,interactionId:Le}),je={unified:Vt({status:ce.status,hasFunctionCall:Ee}),raw:ce.status},Ne=ce.service_tier??pe?.["x-gemini-service-tier"]??void 0,ye=On(ce.usage),ie={google:{...Le!=null?{interactionId:Le}:{},...Ne!=null?{serviceTier:Ne}:{},...ye!=null?{outputTokensByModality:ye}:{}}},be;if(typeof ce.created==="string"){let ne=new Date(ce.created);if(!Number.isNaN(ne.getTime()))be=ne}return{content:Ce,finishReason:je,usage:Ht(ce.usage),warnings:A,providerMetadata:ie,request:{body:x},response:{headers:pe,body:Re,...Le!=null?{id:Le}:{},...be?{timestamp:be}:{},modelId:ce.model??void 0}}}async doStream(w){let{args:x,warnings:A,isBackground:q,pollingTimeoutMs:B}=await this.getArgs(w),re=`${this.config.baseURL}/interactions`,ee=d(this.config.headers?await _(this.config.headers):void 0,w.headers);if(q)return this.doStreamBackground({args:x,warnings:A,url:re,mergedHeaders:ee,options:w,pollingTimeoutMs:B});let V={...x,stream:!0},{responseHeaders:pe,value:ce}=await g({url:re,headers:ee,body:V,failedResponseHandler:Xe,successfulResponseHandler:D(qn),abortSignal:w.abortSignal,fetch:this.config.fetch}),Re=pe?.["x-gemini-service-tier"],Le=dn({warnings:A,generateId:this.config.generateId??C,includeRawChunks:w.includeRawChunks,serviceTier:Re});return{stream:ce.pipeThrough(Le),request:{body:V},response:{headers:pe}}}async doStreamBackground({args:w,warnings:x,url:A,mergedHeaders:q,options:B,pollingTimeoutMs:re}){let{responseHeaders:ee,value:V}=await g({url:A,headers:q,body:w,failedResponseHandler:Xe,successfulResponseHandler:p(qt),abortSignal:B.abortSignal,fetch:this.config.fetch}),pe=V.id;if(pe==null||pe.length===0)throw Error("google.interactions: background POST response did not include an interaction id; cannot stream the result.");let ce=ee?.["x-gemini-service-tier"];if($t(V.status))return{stream:Qi({response:V,warnings:x,generateId:this.config.generateId??C,includeRawChunks:B.includeRawChunks,headerServiceTier:ce}),request:{body:w},response:{headers:ee}};let Re=Xi({baseURL:this.config.baseURL,interactionId:pe,headers:q,fetch:this.config.fetch,abortSignal:B.abortSignal}),Le=dn({warnings:x,generateId:this.config.generateId??C,includeRawChunks:B.includeRawChunks,serviceTier:ce});return{stream:Re.pipeThrough(Le),request:{body:w},response:{headers:ee}}}};function ht(f){let w={};for(let[x,A]of Object.entries(f)){if(A===void 0)continue;w[x]=A}return w}function Bn(f){let w=new URL(f),x=w.pathname.split("/"),A=x.at(-1);if(A==="v1beta"||A==="v1alpha")x.pop(),w.pathname=x.join("/")||"/";return w}function Wt(f,w){let x=Bn(f);return x.protocol=x.protocol==="https:"?"wss:":"ws:",x.pathname=`${x.pathname.replace(/\/$/,"")}/ws/${w}`,x}var es=class{constructor(){this.turnCounter=0,this.inputTranscriptionCounter=0,this.inputTranscriptionBuffer="",this.inputTranscriptionBoundary="none",this.preserveInputTranscriptionAcrossTurnComplete=!1,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,this.turnClosed=!1,this.inputAudioRate=16000}get responseId(){return`google-resp-${this.turnCounter}`}get itemId(){return`google-item-${this.turnCounter}`}beginTurnIfClosed(){if(!this.turnClosed)return;this.turnCounter++,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,this.turnClosed=!1,this.preserveInputTranscriptionAcrossTurnComplete=!1}accumulateInputTranscription({text:f,finished:w}){if(!f){if(w===!0)this.finishInputTranscription();return}let x=w!=null;if(this.inputTranscriptionBuffer!==""&&(this.inputTranscriptionBoundary==="interrupted"||this.inputTranscriptionBoundary==="turn-complete"&&!x))this.finishInputTranscription();this.inputTranscriptionBoundary="none",this.inputTranscriptionBuffer+=f;let A={itemId:`google-input-${this.inputTranscriptionCounter}`,transcript:this.inputTranscriptionBuffer};if(w===!0)this.finishInputTranscription();return A}finishInputTranscription(){if(this.inputTranscriptionBuffer==="")return;this.inputTranscriptionCounter++,this.inputTranscriptionBuffer=""}parseServerEvent(f){let w=f;if(w.setupComplete!=null)return{type:"session-created",raw:f};if(w.toolCall!=null)return this.beginTurnIfClosed(),(w.toolCall.functionCalls??[]).flatMap((x)=>{let A=JSON.stringify(x.args??{});return[{type:"function-call-arguments-delta",responseId:this.responseId,itemId:this.itemId,callId:x.id,delta:A,raw:f},{type:"function-call-arguments-done",responseId:this.responseId,itemId:this.itemId,callId:x.id,name:x.name,arguments:A,raw:f}]});if(w.toolCallCancellation!=null)return{type:"custom",rawType:"toolCallCancellation",raw:f};if(w.goAway!=null)return{type:"custom",rawType:"goAway",raw:f};if(w.sessionResumptionUpdate!=null)return{type:"custom",rawType:"sessionResumptionUpdate",raw:f};if(w.serverContent!=null)return this.parseServerContent(w.serverContent,f);if(w.inputTranscription!=null){let x=this.accumulateInputTranscription(w.inputTranscription);if(x!=null)return{type:"input-transcription-completed",...x,raw:f}}return{type:"custom",rawType:String(Object.keys(w)[0]),raw:f}}parseServerContent(f,w){let x=[];if(f.interrupted)this.inputTranscriptionBoundary="interrupted",this.preserveInputTranscriptionAcrossTurnComplete=!0,this.turnClosed=!0,x.push({type:"speech-started",raw:w});if(f.modelTurn?.parts){this.beginTurnIfClosed();for(let A of f.modelTurn.parts){if(A.inlineData?.data)this.hasAudio=!0,x.push({type:"audio-delta",responseId:this.responseId,itemId:this.itemId,delta:A.inlineData.data,raw:w});if(A.text)this.hasText=!0,x.push({type:"text-delta",responseId:this.responseId,itemId:this.itemId,delta:A.text,raw:w})}}if(f.outputTranscription?.text)this.hasTranscript=!0,x.push({type:"audio-transcript-delta",responseId:this.responseId,itemId:this.itemId,delta:f.outputTranscription.text,raw:w});if(f.inputTranscription!=null){let A=this.accumulateInputTranscription(f.inputTranscription);if(A!=null)x.push({type:"input-transcription-completed",...A,raw:w})}if(f.generationComplete)x.push({type:"custom",rawType:"generationComplete",raw:w});if(f.interactionStatus!=null)x.push({type:"custom",rawType:"interactionStatus",raw:w});if(f.waitingForInput)x.push({type:"custom",rawType:"waitingForInput",raw:w});if(f.turnComplete){if(this.hasAudio)x.push({type:"audio-done",responseId:this.responseId,itemId:this.itemId,raw:w});if(this.hasText)x.push({type:"text-done",responseId:this.responseId,itemId:this.itemId,raw:w});if(this.hasTranscript)x.push({type:"audio-transcript-done",responseId:this.responseId,itemId:this.itemId,raw:w});if(x.push({type:"response-done",responseId:this.responseId,status:"completed",raw:w}),this.turnClosed=!0,this.preserveInputTranscriptionAcrossTurnComplete)this.preserveInputTranscriptionAcrossTurnComplete=!1;else if(this.inputTranscriptionBoundary!=="interrupted")this.inputTranscriptionBoundary="turn-complete"}if(x.length===0)return{type:"custom",rawType:"serverContent",raw:w};return x.length===1?x[0]:x}serializeClientEvent(f,w){switch(f.type){case"session-update":if(f.config.inputAudioFormat?.rate!=null)this.inputAudioRate=f.config.inputAudioFormat.rate;return{setup:Ft(f.config,w)};case"input-audio-append":return{realtimeInput:{audio:{data:f.audio,mimeType:`audio/pcm;rate=${this.inputAudioRate}`}}};case"input-audio-commit":return{realtimeInput:{audioStreamEnd:!0}};case"input-audio-clear":case"response-create":case"response-cancel":case"conversation-item-truncate":return null;case"conversation-item-create":{let x=f.item;switch(x.type){case"text-message":return{realtimeInput:{text:x.text}};case"function-call-output":return ns(x);case"audio-message":return null}break}}return null}};function ts(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)?f:{output:f}}async function ns(f){let w=await J({text:f.output}),x=w.success?ts(w.value):{output:f.output};return{toolResponse:{functionResponses:[{id:f.callId,name:f.name,response:x}]}}}function os(f){let w=f.split("/").at(-1)?.toLowerCase()??"";return/^gemini-\d+\.\d+-live\b.*thinking/.test(w)}function Ft(f,w){let x={model:Tt(w)},{google:A,...q}=f?.providerOptions??{},B=L(A)?A:void 0,re={};if(f?.outputModalities!=null)re.responseModalities=f.outputModalities.map((Re)=>Re.toUpperCase());else re.responseModalities=["AUDIO"];if(f?.voice!=null)re.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:f.voice}}};if(x.generationConfig=re,f?.instructions!=null)x.systemInstruction={parts:[{text:f.instructions}]};if(f?.tools!=null&&f.tools.length>0)x.tools=[{functionDeclarations:f.tools.map((Re)=>({name:Re.name,description:Re.description,parametersJsonSchema:Re.parameters,...B?.defaultToolBehavior!=null?{behavior:B.defaultToolBehavior}:{}}))}];if(f?.inputAudioTranscription!=null)x.inputAudioTranscription={};if(f?.outputAudioTranscription!=null)x.outputAudioTranscription={};let ee=q.generationConfig,V=B?.thinkingConfig??(L(ee)&&L(ee.thinkingConfig)?ee.thinkingConfig:void 0),pe=os(w)&&V?.thinkingLevel==null&&V?.thinkingBudget==null?{...V,thinkingLevel:"low"}:B?.thinkingConfig,ce=()=>{if(pe==null)return;let Re=L(x.generationConfig)?x.generationConfig:re;x.generationConfig={...Re,thinkingConfig:pe}};if(f?.providerOptions==null)return ce(),x;if(Object.assign(x,q),B?.translationConfig!=null)x.generationConfig={...L(x.generationConfig)?x.generationConfig:re,translationConfig:B.translationConfig};return ce(),x}var is="google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained";function ss(f){let w=Bn(f);return w.pathname=`${w.pathname.replace(/\/$/,"")}/v1alpha/auth_tokens`,w.toString()}function as(f){return Wt(f,is).toString()}var rs=class{constructor(f,w){this.specificationVersion="v4",this.mapper=new es,this.modelId=f,this.provider=w.provider,this.config=w}async doCreateClientSecret(f){let w=this.config.fetch??fetch,x=this.config.headers()["x-goog-api-key"];if(!x)throw Error("Google Generative AI API key is required for realtime token creation.");let A=Date.now(),q=(f.expiresAfterSeconds??60)*1000,B=new Date(A+q).toISOString(),re=new Date(A+q+1800000).toISOString(),ee=Ft(f.sessionConfig,this.modelId),V=await w(`${ss(this.config.baseURL)}?key=${encodeURIComponent(x)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({uses:0,expireTime:re,newSessionExpireTime:B,bidiGenerateContentSetup:ee})});if(!V.ok){let ce=await V.text();throw Error(`Google realtime auth token request failed: ${V.status} ${ce}`)}let pe=await V.json();return{token:pe.name,url:as(this.config.baseURL),expiresAt:pe.expireTime?Math.floor(new Date(pe.expireTime).getTime()/1000):void 0}}getWebSocketConfig(f){return{url:`${f.url}?access_token=${encodeURIComponent(f.token)}`}}parseServerEvent(f){return this.mapper.parseServerEvent(f)}serializeClientEvent(f){return this.mapper.serializeClientEvent(f,this.modelId)}buildSessionConfig(f){return Ft(f,this.modelId)}};var ls=a(()=>s(t({languageCodes:o(e()).optional(),customVocabulary:o(e()).optional(),wordTimestamp:c().optional(),diarization:c().optional(),mode:i(["SMART","VERBATIM"]).optional()}))),us="google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",cs=3000;function ds(f,w){let x=Wt(f,us);return x.searchParams.set("key",w),x}function hn(f){return f.includes("-live")}var ps=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.modelId=w,this.config=x,this.specificationVersion="v4"}async parseOptions(w){return h({provider:"google",providerOptions:w,schema:ls})}async doGenerate(w){if(hn(this.modelId))throw new b({argument:"modelId",message:`Model '${this.modelId}' only supports streaming transcription. Use experimental_streamTranscribe, or a unary model such as 'gemini-3.5-transcribe'.`});let x=this.config._internal?.currentDate?.()??new Date,A=[],q=ms(await this.parseOptions(w.providerOptions)),B={model:this.modelId,input:[{type:"audio",data:M(w.audio),mime_type:w.mediaType}],...q!=null?{generation_config:{transcription_config:q}}:{}},{value:re,responseHeaders:ee,rawValue:V}=await g({url:`${this.config.baseURL}/interactions`,headers:d(this.config.headers?await _(this.config.headers):void 0,w.headers),body:B,failedResponseHandler:Xe,successfulResponseHandler:p(vs),abortSignal:w.abortSignal,fetch:this.config.fetch}),pe="",ce=[];for(let Re of re.steps??[])for(let Le of Re.content??[]){if(Le.type!=="text"||Le.text==null)continue;pe+=Le.text;for(let Ce of Le.annotations??[]){if(Ce.type!=="word_info")continue;let Ee=mn(Ce.start_offset),je=mn(Ce.end_offset);if(Ce.text==null||Ee==null||je==null)continue;ce.push({text:Ce.text,startSecond:Ee,endSecond:je})}}return{text:pe,segments:ce,language:void 0,durationInSeconds:void 0,warnings:A,...re.usage!=null&&{usage:re.usage},response:{timestamp:x,modelId:this.modelId,headers:ee,body:V},...re.usage!=null?{providerMetadata:{google:{usage:re.usage}}}:{}}}async doStream(w){if(!hn(this.modelId))throw new b({argument:"modelId",message:`Model '${this.modelId}' does not support streaming transcription. Use a live model such as 'gemini-3.5-transcribe-live'.`});let x=this.config._internal?.currentDate?.()??new Date,A=[],q=await this.parseOptions(w.providerOptions);fs(w.inputAudioFormat);let B=d(this.config.headers?await _(this.config.headers):void 0,w.headers),re;for(let[pe,ce]of Object.entries(B))if(pe.toLowerCase()==="x-goog-api-key"&&ce!=null)re=ce;if(re==null)throw Error("Google Generative AI API key is required for streaming transcription.");let ee=Object.fromEntries(Object.entries(B).filter(([pe])=>pe.toLowerCase()!=="x-goog-api-key")),V={model:Tt(this.modelId),inputAudioTranscription:hs(q)??{}};return{request:{body:V},response:{timestamp:x,modelId:this.modelId},stream:gs({webSocket:this.config.webSocket,url:ds(this.config.baseURL,re),headers:ee,setup:V,inputAudioRate:w.inputAudioFormat.rate??16000,finishGraceMs:this.config._internal?.finishGraceMs??cs,warnings:A,audio:w.audio,abortSignal:w.abortSignal,includeRawChunks:w.includeRawChunks})}}};function gs({webSocket:f,url:w,headers:x,setup:A,inputAudioRate:q,finishGraceMs:B,warnings:re,audio:ee,abortSignal:V,includeRawChunks:pe}){let ce=!1,Re=()=>{};return new ReadableStream({start:(Le)=>{let Ce,Ee,je,Ne=new Promise((Ve)=>{je=Ve}),ye=0,ie="",be="",ne="",se,Ue=!1,De,qe,We=()=>`google-segment-${ye}`,nt=()=>{if(qe!=null)clearTimeout(qe),qe=void 0},Ke=()=>{if(ce||!Ue)return;nt(),qe=setTimeout(()=>{qe=void 0,ze()},B)};Re=(Ve)=>{if(nt(),Ce!=null)Ce.cancel().catch(()=>{});else ee.cancel().catch(()=>{});Ee?.close(Ve)};let Qe=(Ve)=>{if(ce)return;ce=!0,Re(),Le.error(Ve)},pt=()=>{if(ie===""){if(ne==="")return;ie=ne}ne="",Le.enqueue({type:"transcript-final",id:We(),text:ie}),be+=be===""?ie:` ${ie}`,ie="",ye++},ze=()=>{if(ce)return;pt(),ce=!0,Le.enqueue({type:"finish",text:be,segments:[],language:se,durationInSeconds:void 0,usage:De,...De!=null?{providerMetadata:{google:{usageMetadata:De}}}:{}}),Le.close(),Re(1000)},ot=async(Ve)=>{Ce=ee.getReader();try{while(!0){let{done:rt,value:lt}=await Ce.read();if(rt||ce)break;Ve.send(JSON.stringify({realtimeInput:{audio:{data:M(lt),mimeType:`audio/pcm;rate=${q}`}}})),await ue(Ve)}}finally{Ce.releaseLock(),Ce=void 0}if(!ce)Ve.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),Ue=!0,Ke()};Ee=fe({url:w,headers:x,webSocket:f,abortSignal:V,onAbort:Qe,onProcessingError:Qe,onOpen:(Ve)=>{Le.enqueue({type:"stream-start",warnings:re}),Ve.send(JSON.stringify({setup:A})),Ne.then(()=>ce?void 0:ot(Ve)).catch(Qe)},onMessageText:async(Ve)=>{if(ce)return;let rt=await J({text:Ve});if(!rt.success)return;let lt=rt.value;if(pe)Le.enqueue({type:"raw",rawValue:lt});if(lt.setupComplete!=null)je();if(lt.usageMetadata!=null)De=lt.usageMetadata;if(lt.error!=null){Qe(Error(lt.error.message??"Google Live API error"));return}let dt=lt.serverContent,Fe=dt?.interimInputTranscription;if(Fe?.text)Ke(),ne=Fe.text,Le.enqueue({type:"transcript-partial",id:We(),text:Fe.text});let tt=dt?.inputTranscription??lt.inputTranscription;if(tt!=null){if(tt.languageCode!=null)se=tt.languageCode;if(tt.text)Ke(),ne="",ie+=tt.text,Le.enqueue({type:"transcript-delta",id:We(),delta:tt.text});if(tt.finished===!0)pt()}if(dt?.turnComplete)pt();let Je=dt?.interactionStatus;if(Ue&&(Je==="IDLE"||Je==="REQUIRES_ACTION"||dt?.turnComplete===!0&&Je==null))ze()},onSocketError:()=>{Qe(Error("Google Live transcription error"))},onClose:({code:Ve,reason:rt})=>{if(ce)return;if(Ue){ze();return}Qe(Error(`Google Live transcription WebSocket closed unexpectedly before finishing (code ${Ve??"unknown"}${rt?`, reason: ${rt}`:""}).`))}})},cancel:()=>{if(ce)return;ce=!0,Re()}})}function hs(f){if(f==null)return;let w={};if(f.languageCodes!=null)w.languageCodes=f.languageCodes;if(f.customVocabulary!=null)w.customVocabulary=f.customVocabulary;if(f.wordTimestamp!=null)w.wordTimestamp=f.wordTimestamp;if(f.diarization!=null)w.diarization=f.diarization;if(f.mode!=null)w.mode=f.mode;return Object.keys(w).length>0?w:void 0}function ms(f){if(f==null)return;let w={};if(f.languageCodes!=null)w.language_codes=f.languageCodes;if(f.customVocabulary!=null)w.custom_vocabulary=f.customVocabulary;if(f.mode!=null||f.diarization===!0||f.wordTimestamp===!0)w.mode={type:(f.mode??"VERBATIM").toLowerCase(),...f.diarization===!0?{diarization_mode:"speaker"}:{},...f.wordTimestamp===!0?{timestamp_granularities:["word"]}:{}};return Object.keys(w).length>0?w:void 0}function mn(f){if(f==null)return;let w=Number.parseFloat(f);return Number.isFinite(w)?w:void 0}function fs(f){if(f.type!=="audio/pcm"||f.rate!=null&&f.rate!==16000)throw new b({argument:"inputAudioFormat",message:"The Gemini Live transcription API only supports 16kHz 16-bit PCM input audio."})}var ys=()=>t({type:e().nullish(),text:e().nullish(),speaker:e().nullish(),start_offset:e().nullish(),end_offset:e().nullish()}),vs=a(()=>s(t({status:e().nullish(),steps:o(t({type:e().nullish(),content:o(t({type:e().nullish(),text:e().nullish(),annotations:o(ys()).nullish()})).nullish()})).nullish(),usage:y(e(),G()).nullish()}))),bs=a(()=>s(t({echoTargetLanguage:c().optional()}))),Ts="google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",_s=1000,Cs=24000,ws=128;function Ss(f,w){let x=Wt(f,Ts);return x.searchParams.set("key",w),x}var Is=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.specificationVersion="v4",this.modelId=w,this.config=x}async doStream(w){if(w.targetLanguage==null)throw new b({argument:"targetLanguage",message:`targetLanguage is required for translation model '${this.modelId}'.`});let x=this.config._internal?.currentDate?.()??new Date,A=await h({provider:"google",providerOptions:w.providerOptions,schema:bs}),q=[];if(Ms(w.inputAudioFormat),w.sourceLanguage!=null)q.push({type:"unsupported",feature:"sourceLanguage",details:"The Gemini Live translation API auto-detects the source language and does not accept a source language."});if(w.outputAudioFormat!=null)q.push({type:"unsupported",feature:"outputAudioFormat",details:"The Gemini Live API always outputs 24kHz 16-bit PCM audio and does not accept an output audio format."});let B=d(this.config.headers(),w.headers),re;for(let[pe,ce]of Object.entries(B))if(pe.toLowerCase()==="x-goog-api-key"&&ce!=null)re=ce;if(re==null)throw Error("Google Generative AI API key is required for streaming translation.");let ee=Object.fromEntries(Object.entries(B).filter(([pe])=>pe.toLowerCase()!=="x-goog-api-key")),V=Os({modelId:this.modelId,targetLanguage:w.targetLanguage,providerOptions:A});return{request:{body:V},response:{timestamp:x,modelId:this.modelId},stream:ks({webSocket:this.config.webSocket,url:Ss(this.config.baseURL,re),headers:ee,setup:V,inputAudioRate:w.inputAudioFormat.rate??16000,finishGraceMs:this.config._internal?.finishGraceMs??_s,warnings:q,audio:w.audio,abortSignal:w.abortSignal,includeRawChunks:w.includeRawChunks})}}};function ks({webSocket:f,url:w,headers:x,setup:A,inputAudioRate:q,finishGraceMs:B,warnings:re,audio:ee,abortSignal:V,includeRawChunks:pe}){let ce=!1,Re=()=>{};return new ReadableStream({start:(Le)=>{let Ce,Ee,je,Ne=new Promise((Fe)=>{je=Fe}),ye=0,ie="",be="",ne="",se="",Ue=!1,De,qe=!1,We=!1,nt=0,Ke,Qe=()=>`google-item-${ye}`,pt=()=>{if(Ke!=null)clearTimeout(Ke),Ke=void 0},ze=()=>{if(ce||Ke!=null)return;Ke=setTimeout(()=>{Ke=void 0,rt()},B)},ot=()=>{qe=!0,nt=0,pt()};Re=(Fe)=>{if(pt(),Ce!=null)Ce.cancel().catch(()=>{});else ee.cancel().catch(()=>{});Ee?.close(Fe)};let Ve=(Fe)=>{if(ce)return;ce=!0,Re(),Le.error(Fe)},rt=()=>{if(ce)return;if(be!==""||se!=="")lt();ce=!0,Le.enqueue({type:"finish",sourceText:ie,outputText:ne,usage:De}),Le.close(),Re(1000)},lt=()=>{if(be!=="")Le.enqueue({type:"source-transcript-final",id:Qe(),text:be}),ie+=be,be="";if(se!=="")Le.enqueue({type:"output-text-final",id:Qe(),text:se}),ne+=se,se="";ye++},dt=async(Fe)=>{Ce=ee.getReader();try{while(!0){let{done:tt,value:Je}=await Ce.read();if(tt||ce)break;Fe.send(JSON.stringify({realtimeInput:{audio:{data:M(Je),mimeType:`audio/pcm;rate=${q}`}}})),await ue(Fe)}}finally{Ce.releaseLock(),Ce=void 0}if(!ce){if(Fe.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),Ue=!0,We&&!qe)ze()}};Ee=fe({url:w,headers:x,webSocket:f,abortSignal:V,onAbort:Ve,onProcessingError:Ve,onOpen:(Fe)=>{Le.enqueue({type:"stream-start",warnings:re}),Fe.send(JSON.stringify({setup:A})),Ne.then(()=>ce?void 0:dt(Fe)).catch(Ve)},onMessageText:async(Fe)=>{if(ce)return;let tt=await J({text:Fe});if(!tt.success)return;let Je=tt.value;if(pe)Le.enqueue({type:"raw",rawValue:Je});if(Je.setupComplete!=null)je();if(Je.usageMetadata!=null)De=xs(De,Je.usageMetadata);if(Je.error!=null){Ve(Error(Je.error.message??"Google Live API error"));return}let Be=Je.serverContent?.inputTranscription?.text??Je.inputTranscription?.text;if(Be)ot(),be+=Be,Le.enqueue({type:"source-transcript-delta",id:Qe(),delta:Be});let Pe=Je.serverContent;if(Pe==null)return;for(let ut of Pe.modelTurn?.parts??[])if(ut.inlineData?.data){Le.enqueue({type:"audio",id:Qe(),audio:ut.inlineData.data});let at=Rs(ut.inlineData.data);if(Ue&&at!=null){if(nt+=at,nt>=B){rt();return}}else ot()}if(Pe.outputTranscription?.text)ot(),se+=Pe.outputTranscription.text,Le.enqueue({type:"output-text-delta",id:Qe(),delta:Pe.outputTranscription.text});if(Pe.turnComplete){if(lt(),qe=!1,We=!0,Ue)ze()}},onSocketError:()=>{Ve(Error("Google Live translation error"))},onClose:({code:Fe,reason:tt})=>{if(ce)return;if(Ke!=null){rt();return}Ve(Error(`Google Live translation WebSocket closed unexpectedly before finishing (code ${Fe??"unknown"}${tt?`, reason: ${tt}`:""}).`))}})},cancel:()=>{if(ce)return;ce=!0,Re()}})}function xs(f,w){let x=f?.inputAudioTokens,A=f?.outputAudioTokens;for(let q of w.promptTokensDetails??[])if(q.modality==="AUDIO"&&q.tokenCount!=null)x=(x??0)+q.tokenCount;for(let q of w.responseTokensDetails??[])if(q.modality==="AUDIO"&&q.tokenCount!=null)A=(A??0)+q.tokenCount;if(x==null&&A==null)return f;return{...f,...x!=null?{inputAudioTokens:x}:{},...A!=null?{outputAudioTokens:A}:{}}}function Rs(f){let w;try{w=N(f)}catch{return}if(w.byteLength<2)return;let x=new DataView(w.buffer,w.byteOffset,w.byteLength),A=Math.floor(w.byteLength/2);for(let q=0;q<A;q++)if(Math.abs(x.getInt16(q*2,!0))>ws)return;return A/Cs*1000}function Os({modelId:f,targetLanguage:w,providerOptions:x}){return{model:Tt(f),generationConfig:{responseModalities:["AUDIO"],translationConfig:{targetLanguageCode:w,...x?.echoTargetLanguage!=null?{echoTargetLanguage:x.echoTargetLanguage}:{}}},inputAudioTranscription:{},outputAudioTranscription:{}}}function Ms(f){if(f.type!=="audio/pcm"||f.rate!=null&&f.rate!==16000)throw new b({argument:"inputAudioFormat",message:"The Gemini Live translation API only supports 16kHz 16-bit PCM input audio."})}var Es="https://generativelanguage.googleapis.com/v1beta",As=/^https:\/\/generativelanguage\.googleapis\.com\/v1beta\/files\/.*$/,Ls=["text/html","text/css","text/plain","text/xml","text/csv","text/rtf","text/javascript","application/json","application/pdf","image/bmp","image/jpeg","image/png","image/webp","video/mp4","video/mpeg","video/quicktime","video/avi","video/x-flv","video/mpg","video/webm","video/wmv","video/3gpp"],js=/^https:\/\/.*$/;function Us(f){return/(^|\/)gemini-/.test(f)&&!/(^|\/)gemini-2\.0/.test(f)}function Kt(f={}){let w=Y(f.baseURL)??Es,x=f.name??"google.generative-ai",A=()=>F({"x-goog-api-key":he({apiKey:f.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...f.headers},`ai-sdk-google/${zn}`),q=(be,ne=be==null||Us(be))=>({"*":[As,new RegExp(`^${w}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")],...ne?Object.fromEntries(Ls.map((se)=>[se,[js]])):{}}),B={provider:x,baseURL:w,headers:A,generateId:f.generateId??C,fetch:f.fetch},re=(be)=>new Ct(be,{...B,supportedUrls:()=>q(be)}),ee=()=>new Wo({provider:`${x.replace(/\.generative-ai$/,"")}.batch`,maxLineBytes:f.batchResultDownloads?.maxLineBytes,config:B,supportedUrls:q(void 0,!1)}),V=(be)=>new Qn(be,{provider:x,baseURL:w,headers:A,fetch:f.fetch}),pe=(be,ne={})=>new ni(be,ne,{provider:x,baseURL:w,headers:A,fetch:f.fetch}),ce=()=>new oi({provider:x,baseURL:w,headers:A,fetch:f.fetch}),Re=(be)=>new hi(be,{provider:x,baseURL:w,headers:A,fetch:f.fetch,generateId:f.generateId??C}),Le=(be)=>new rs(be,{provider:`${x}.realtime`,baseURL:w,headers:A,fetch:f.fetch}),Ce=(be)=>new Is(be,{provider:`${x}.speech-translation`,baseURL:w,headers:A,webSocket:f.webSocket}),Ee=(be)=>new _i(be,{provider:`${x}.speech`,baseURL:w,headers:A,fetch:f.fetch}),je=(be)=>new ps(be,{provider:`${x}.transcription`,baseURL:w,headers:A,fetch:f.fetch,webSocket:f.webSocket}),Ne=Object.assign((be)=>Le(be),{getToken:async(be)=>{let ne=await Le(be.model).doCreateClientSecret({sessionConfig:be.sessionConfig,expiresAfterSeconds:be.expiresAfterSeconds});return{token:ne.token,url:ne.url,expiresAt:ne.expiresAt}}}),ye=(be)=>new Zi(be,{provider:`${x}.interactions`,baseURL:w,headers:A,generateId:f.generateId??C,fetch:f.fetch}),ie=function(be){if(new.target)throw Error("The Google Generative AI model function cannot be called with the new keyword.");return re(be)};return ie.specificationVersion="v4",ie.languageModel=re,ie.chat=re,ie.generativeAI=re,ie.decisionModel=(be)=>new et({model:re(be),provider:`${x.replace(/\.generative-ai$/,"")}.decision`}),ie.evaluationModel=ie.decisionModel,ie.experimental_batch=ee,ie.embedding=V,ie.embeddingModel=V,ie.textEmbedding=V,ie.textEmbeddingModel=V,ie.image=pe,ie.imageModel=pe,ie.video=Re,ie.videoModel=Re,ie.experimental_realtime=Ne,ie.files=ce,ie.speech=Ee,ie.speechModel=Ee,ie.transcription=je,ie.transcriptionModel=je,ie.translation=Ce,ie.speechTranslationModel=Ce,ie.interactions=ye,ie.tools=ei,ie}var Fs=Kt();var Ns=Ie(Kt);function Qs(){oe("google",Ns)}export{Qs as register};
@@ -0,0 +1 @@
1
+ import{q}from"./embed-n5nzhrf2.js";var k={id:"onnx-community/LFM3-1.7B-ONNX",dtype:"q4f16",name:"LFM3 1.7B",sizeMB:1090};async function L(){let e=globalThis.navigator?.gpu;if(!e)return!1;try{return!!await e.requestAdapter()}catch{return!1}}function M(e){return e.flatMap((t)=>{if(t.role==="system")return[{role:"system",content:t.content}];if(t.role==="tool")return[];let o=t.content.map((n)=>n.type==="text"?n.text:"").join("").trim();return o?[{role:t.role,content:o}]:[]})}var d=new Map,f=new Map;function x(e=k,t){let o=`${e.id}@${e.dtype}`,n=f.get(o)??new Set;if(f.set(o,n),t)n.add(t);let a=d.get(o);if(!a)a=(async()=>{if(!await L())throw new b("webgpu","This browser has no WebGPU.");let{pipeline:r}=await (q("xn16v7pz"),import("./transformers.web-xn16v7pz.js"));return await r("text-generation",e.id,{dtype:e.dtype,device:"webgpu",progress_callback:(i)=>{if(i.status!=="progress_total")return;let p={loaded:i.loaded??0,total:i.total??0,progress:Math.min(1,(i.progress??0)/100)};for(let u of n)u(p)}})})(),a.catch(()=>d.delete(o)),d.set(o,a);return a}class b extends Error{code;constructor(e,t){super(t);this.code=e;this.name="LocalModelError"}}var w=(e,t)=>({inputTokens:{total:e,noCache:e,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:t,text:t,reasoning:void 0}});function _(e={}){let t=e.spec??k;async function o(n,a){let r=await x(t,e.onProgress),{TextStreamer:s,InterruptableStoppingCriteria:i,StoppingCriteriaList:p}=await (q("xn16v7pz"),import("./transformers.web-xn16v7pz.js")),u=new i,c=new p;c.push(u);let g=()=>u.interrupt();n.abortSignal?.addEventListener("abort",g,{once:!0});let l=0,y=new s(r.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,decode_kwargs:{clean_up_tokenization_spaces:!1},callback_function:(m)=>{if(m)a(m)},token_callback_function:()=>{l++}});try{await r(M(n.prompt),{max_new_tokens:n.maxOutputTokens??e.maxNewTokens??512,do_sample:!0,temperature:n.temperature??0.1,top_k:50,repetition_penalty:1.1,streamer:y,stopping_criteria:c,tokenizer_encode_kwargs:{enable_thinking:!1}})}finally{n.abortSignal?.removeEventListener("abort",g)}return{tokens:l,interrupted:u.interrupted}}return{specificationVersion:"v4",provider:"murmur-local",modelId:t.id,supportedUrls:{},async doGenerate(n){let a="",{tokens:r,interrupted:s}=await o(n,(i)=>{a+=i});return{content:[{type:"text",text:a}],finishReason:{unified:s?"other":"stop",raw:void 0},usage:w(0,r),warnings:[]}},async doStream(n){return{stream:new ReadableStream({start(r){r.enqueue({type:"stream-start",warnings:[]}),r.enqueue({type:"text-start",id:"0"}),o(n,(s)=>r.enqueue({type:"text-delta",id:"0",delta:s})).then(({tokens:s,interrupted:i})=>{r.enqueue({type:"text-end",id:"0"}),r.enqueue({type:"finish",finishReason:{unified:i?"other":"stop",raw:void 0},usage:w(0,s)}),r.close()},(s)=>{r.enqueue({type:"error",error:s}),r.close()})}})}}}}export{k as DEFAULT_LOCAL_MODEL,L as hasWebGPU,_ as localModel};
@@ -0,0 +1,9 @@
1
+ import{kt,mt,Tt}from"./embed-krrjjyf5.js";var E="script,style,noscript,template,svg,canvas,iframe,nav,header,footer,aside,form,button,dialog,[hidden],[aria-hidden='true'],[data-murmur-ignore],murmur-chat",O="main,article,[role='main'],body",D=/^(P|LI|DT|DD|PRE|BLOCKQUOTE|TABLE|TR|FIGCAPTION|DIV|SECTION|ARTICLE|UL|OL|DL|MAIN|H[1-6])$/;function g(o,{root:l=O,exclude:s=E}={}){let r=l.split(",").map((t)=>o.querySelector(t.trim())).find((t)=>!!t),p=r?.querySelector("h1")?.textContent?.replace(/\s+/g," ").trim()||o.querySelector("title")?.textContent?.trim()||"";if(!r)return{title:p,sections:[]};let u=[],e={heading:"",anchor:"",text:""},d=new Map,f=(t)=>{if(t.nodeType===3){e.text+=(t.textContent??"").replace(/\s+/g," ");return}if(t.nodeType!==1)return;let n=t;if(n.matches(s))return;let i=n.tagName.toUpperCase();if(/^H[1-3]$/.test(i)){u.push(e);let c=(n.textContent??"").replace(/\s+/g," ").trim(),m=n.id||n.closest("[id]")?.id||"";if(!m){let a=mt(c),x=d.get(a)??0;d.set(a,x+1),m=x?`${a}-${x}`:a}e={heading:c,anchor:m,text:""};return}if(i==="BR")e.text+=`
2
+ `;if((i==="TD"||i==="TH")&&!/(^|\n)\s*$/.test(e.text))e.text+=" | ";let h=D.test(i);if(h)e.text+=`
3
+
4
+ `;if(i==="LI")e.text+="- ";for(let c of Array.from(n.childNodes))f(c);if(h)e.text+=`
5
+
6
+ `};for(let t of Array.from(r.childNodes))f(t);return u.push(e),{title:p,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 L(o,l=o.location?.href??"",s={}){let r=g(o,s);return Tt([{url:l,title:r.title,sections:r.sections}],s.maxChunk??kt)}export{L as indexDocument};
@@ -0,0 +1 @@
1
+ import{Re,ft,De,Qe,Le,Ue,gn,_t,yt}from"./embed-rp9gb1qq.js";export{Re as DEFAULT_RECOMMENDED,gn as ENDPOINT_PRESETS,yt as createLlmSettingsStore,De as describeError,Le as isConfigured,ft as liveCatalog,Qe as loadModel,_t as secureStorage,Ue as validateEndpoint};
@@ -0,0 +1 @@
1
+ import{Re,ft,De,Qe,Le,Ue,_t,yt}from"./embed-rp9gb1qq.js";var i="https://maxgfr.github.io/murmur/cdn/models.json";function l(e){let r=e.endpoint?Ue(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 yt({catalog:ft({fallbackUrl:r.catalogUrl??i}),storage:_t({prefsKey:`${o}-llm`,dbName:`${o}-secrets`}),recommended:e.provider?[e.provider,...Re.filter((n)=>n!==e.provider)]:Re,defaults:t})}async function m(e,r){let o=l(e);if(o)return o;let t=r?await r.load():null;return t&&Le(t)?t:null}export{De as describeError,Le as isConfigured,Qe as loadModel,m as resolveSettings,d as visitorStore};
@@ -0,0 +1 @@
1
+ import{xn,At}from"./embed-xtkxyrpe.js";export{xn as generateText,At as streamText};
@@ -0,0 +1,3 @@
1
+ import{oe,Ie}from"./embed-rp9gb1qq.js";import{b,Ge,me,u,e,r,c,ie,o,t,l,f,y,i,n,G,k,T,d,N,M,ee,te,le,F,z,C,Nt,he,W,Se,lt,a,s,h,g,ne,ve,S,O,I,D,p,E,Ce,Y}from"./embed-dbkjhg16.js";var xe=t({messages:o(G()).nullish(),cached_tokens:r().nullish(),audio_tokens:r().nullish()}).catchall(G()),Ue=t({reasoning_tokens:r().nullish()}).catchall(G()),_e=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(G());function pe(w){if(w==null)return te();let{prompt_tokens:m,completion_tokens:_}=w,H=w.num_cached_tokens??w.prompt_tokens_details?.cached_tokens??w.prompt_token_details?.cached_tokens??0;return{inputTokens:{total:m,noCache:m-H,cacheRead:H||void 0,cacheWrite:void 0},outputTokens:{total:_,text:_,reasoning:void 0},raw:w}}function ke({part:w}){if(w.data.type==="url")return w.data.url.toString();if(w.data.type==="data")return`data:${O({part:w})};base64,${M(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:H,content:q}=w[_],v=_===w.length-1;switch(H){case"system":m.push({role:"system",content:q});break;case"user":m.push({role:"user",content:q.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:ke({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:ke({part:R})}}}}})});break;case"assistant":{let R="",A=!1,x=[],j=[];for(let L of q)switch(L.type){case"text":R+=L.text,x.push({type:"text",text:L.text});break;case"tool-call":j.push({id:L.toolCallId,type:"function",function:{name:L.toolName,arguments:JSON.stringify(L.input)}});break;case"reasoning":A=!0,x.push({type:"thinking",thinking:[{type:"text",text:L.text}],closed:!0});break;default:throw Error(`Unsupported content type in assistant message: ${L.type}`)}m.push({role:"assistant",content:A?x:R,prefix:v?!0:void 0,tool_calls:j.length>0?j:void 0});break}case"tool":for(let R of q){if(R.type==="tool-approval-response")continue;let A=R.output,x;switch(A.type){case"text":case"error-text":x=A.value;break;case"execution-denied":x=A.reason??"Tool call execution denied.";break;case"content":case"json":case"error-json":x=JSON.stringify(A.value)}m.push({role:"tool",name:R.toolName,tool_call_id:R.toolCallId,content:x})}break;default:throw Error(`Unsupported role: ${H}`)}}return m}function je(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 Ee=()=>t({safePrompt:c().optional(),documentImageLimit:r().optional(),documentPageLimit:r().optional(),structuredOutputs:c().optional(),strictJsonSchema:c().optional(),parallelToolCalls:c().optional(),promptCacheKey:e().optional(),reasoningEffort:i(["high","none","low","max"]).optional()}),$e=a(()=>s(Ee())),De=a(()=>s(t({object:n("error"),message:e(),type:e(),param:e().nullable(),code:e().nullable()}))),ce=I({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 H=[];for(let v of w)if(v.type==="provider")_.push({type:"unsupported",feature:`provider-defined tool ${v.id}`});else H.push({type:"function",function:{name:v.name,description:v.description,parameters:v.inputSchema,...v.strict!=null?{strict:v.strict}:{}}});if(m==null)return{tools:H,toolChoice:void 0,toolWarnings:_};let q=m.type;switch(q){case"auto":case"none":return{tools:H,toolChoice:q,toolWarnings:_};case"required":return{tools:H,toolChoice:"any",toolWarnings:_};case"tool":return{tools:H.filter((v)=>v.function.name===m.toolName),toolChoice:"any",toolWarnings:_};default:throw new u({functionality:`tool choice type: ${q}`})}}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[k](m){return E({modelId:m.modelId,config:m.config})}static[T](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:H,topP:q,topK:v,frequencyPenalty:R,presencePenalty:A,reasoning:x,stopSequences:j,responseFormat:L,seed:U,providerOptions:X,tools:se,toolChoice:Q}){let Z=[],V=await h({provider:"mistral",providerOptions:X,schema:$e})??{};if(v!=null)Z.push({type:"unsupported",feature:"topK"});let re=!Ve.has(this.modelId),K;if(re){let de=Je.has(this.modelId);if(V.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".'});K=V.reasoningEffort??(W(x)?x==="none"?de?"low":"none":Se({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(W(x))Z.push({type:"unsupported",feature:"reasoning",details:"This model does not support reasoning configuration."});let J=V.structuredOutputs??!0,P=V.strictJsonSchema??!1;if(L?.type==="json"&&(!J||L.schema==null))m=Nt({messages:m,schema:L.schema});let B={model:this.modelId,safe_prompt:V.safePrompt,max_tokens:_,temperature:H,top_p:q,...R!=null?{frequency_penalty:R}:{},...A!=null?{presence_penalty:A}:{},stop:j,random_seed:U,reasoning_effort:K,response_format:L?.type==="json"?J&&L?.schema!=null?{type:"json_schema",json_schema:{schema:L.schema,strict:P,name:L.name??"response",description:L.description}}:{type:"json_object"}:void 0,document_image_limit:V.documentImageLimit,document_page_limit:V.documentPageLimit,...V.promptCacheKey!==void 0?{prompt_cache_key:V.promptCacheKey}:{},messages:be(m)},{tools:ae,toolChoice:fe,toolWarnings:ye}=Pe({tools:se,toolChoice:Q});return{args:{...B,tools:ae,tool_choice:fe,...ae!=null&&V.parallelToolCalls!==void 0?{parallel_tool_calls:V.parallelToolCalls}:{}},warnings:[...Z,...ye]}}async doGenerate(m){let{args:_,warnings:H}=await this.getArgs(m),{responseHeaders:q,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}),A=v.choices[0],x=[];if(A.message.content!=null&&Array.isArray(A.message.content)){for(let j of A.message.content)if(j.type==="thinking"){let L=Te(j.thinking);if(L.length>0)x.push({type:"reasoning",text:L})}else if(j.type==="text"){if(j.text.length>0)x.push({type:"text",text:j.text})}}else{let j=Me(A.message.content);if(j!=null&&j.length>0)x.push({type:"text",text:j})}if(A.message.tool_calls!=null)for(let j of A.message.tool_calls)x.push({type:"tool-call",toolCallId:j.id,toolName:j.function.name,input:j.function.arguments});return{content:x,finishReason:{unified:je(A.finish_reason),raw:A.finish_reason??void 0},usage:pe(v.usage),request:{body:_},response:{...ee(v),headers:q,body:R},warnings:H}}async doStream(m){let{args:_,warnings:H}=await this.getArgs(m),q={..._,stream:!0},{responseHeaders:v,value:R}=await g({url:`${this.config.baseURL}/chat/completions`,headers:d(this.config.headers?.(),m.headers),body:q,failedResponseHandler:ce,successfulResponseHandler:D(Be),abortSignal:m.abortSignal,fetch:this.config.fetch}),A={unified:"interrupted",raw:void 0},x=void 0,j=!0,L=!1,U=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:H})},transform(Q,Z){if(m.includeRawChunks)Z.enqueue({type:"raw",rawValue:Q.rawValue});if(!Q.success){A={unified:"error",raw:void 0},Z.enqueue({type:"error",error:Q.error});return}let V=Q.value;if(j)j=!1,Z.enqueue({type:"response-metadata",...ee(V)});if(V.usage!=null)x=V.usage;let re=V.choices[0],K=re.delta,J=Me(K.content);if(K.content!=null&&Array.isArray(K.content)){for(let P of K.content)if(P.type==="thinking"){let B=Te(P.thinking);if(B.length>0){if(U==null){if(L)Z.enqueue({type:"text-end",id:"0"}),L=!1;U=se(),Z.enqueue({type:"reasoning-start",id:U})}Z.enqueue({type:"reasoning-delta",id:U,delta:B})}}}if(J!=null&&J.length>0){if(!L){if(U!=null)Z.enqueue({type:"reasoning-end",id:U}),U=null;Z.enqueue({type:"text-start",id:"0"}),L=!0}Z.enqueue({type:"text-delta",id:"0",delta:J})}if(K?.tool_calls!=null)for(let P of K.tool_calls)X.processDelta(P);if(re.finish_reason!=null)A={unified:je(re.finish_reason),raw:re.finish_reason}},flush(Q){if(U!=null)Q.enqueue({type:"reasoning-end",id:U});if(L)Q.enqueue({type:"text-end",id:"0"});X.flush(),Q.enqueue({type:"finish",finishReason:A,usage:pe(x)})}})),request:{body:q},response:{headers:v}}}};function Te(w){return w.filter((m)=>m.type==="text").map((m)=>m.text).join("")}function Me(w){if(typeof w==="string")return w;if(w==null)return;let m=[];for(let _ of w){let{type:H}=_;switch(H){case"text":m.push(_.text);break;case"thinking":case"image_url":case"reference":break;default:throw Error(`Unsupported type: ${H}`)}}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=a(()=>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:_e}))),Be=a(()=>s(t({id:e().nullish(),created:r().nullish(),model:e().nullish(),choices:o(t({delta:t({role:i(["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:_e.nullish()})));function We(w,m){let _=[],H=[],q=new Set,v=(R)=>{if(q.has(R.toolCallId)){let x=null;if(R.output.type==="json"){let j=R.output.value,L=j!=null&&typeof j==="object"&&"info"in j?j.info:void 0;if(L!=null&&typeof L==="object"&&!Array.isArray(L))x="result"in L?L.result??L:L}_.push({type:"function.result",tool_call_id:R.toolCallId,result:typeof x==="string"?x:JSON.stringify(x)});return}let A=be([{role:"tool",content:[R]}])[0];_.push({type:"function.result",tool_call_id:R.toolCallId,result:A.content})};for(let R of w)switch(R.role){case"system":H.push(R.content);break;case"user":{let A=be([R])[0];if(A.role==="user")_.push({type:"message.input",role:"user",content:A.content});break}case"assistant":{let A=[],x=()=>{if(A.length>0)_.push({type:"message.input",role:"assistant",content:A}),A=[]};for(let j of R.content)switch(j.type){case"text":A.push({type:"text",text:j.text});break;case"reasoning":A.push({type:"thinking",thinking:[{type:"text",text:j.text}],closed:!0});break;case"tool-call":if(x(),j.providerExecuted){let L=j.providerOptions?.mistral?.function??j.providerOptions?.mistral?.name,U=j.input;_.push({type:"function.call",tool_call_id:j.toolCallId,name:typeof L==="string"?L:m.toProviderToolName(j.toolName),arguments:typeof U?.arguments==="string"?U.arguments:JSON.stringify(j.input)}),q.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 A of R.content){if(A.type==="tool-approval-response")continue;v(A)}}return{inputs:_,instructions:H.length>0?H.join(`
2
+
3
+ `):void 0}}var Fe=a(()=>s(Ee())),ge={"mistral.web_search":"web_search","mistral.web_search_premium":"web_search_premium"};function Ze({tools:w,toolChoice:m}){w=w?.length?w:void 0;let _=[];if(w==null)return{tools:void 0,toolChoice:void 0,toolWarnings:_};let H=[];for(let v of w)if(v.type==="provider"){if(v.id==="mistral.web_search"||v.id==="mistral.web_search_premium"){H.push({type:ge[v.id]});continue}_.push({type:"unsupported",feature:`provider-defined tool ${v.id}`})}else H.push({type:"function",function:{name:v.name,description:v.description,parameters:v.inputSchema,...v.strict!=null?{strict:v.strict}:{}}});if(m==null)return{tools:H,toolChoice:void 0,toolWarnings:_};let q=m.type;switch(q){case"auto":case"none":return{tools:H,toolChoice:q,toolWarnings:_};case"required":return{tools:H,toolChoice:"any",toolWarnings:_};case"tool":{let v=le({tools:w,providerToolNames:ge}).toProviderToolName(m.toolName);return{tools:H.filter((R)=>R.type==="function"?R.function.name===v:R.type===v),toolChoice:"any",toolWarnings:_}}default:throw new u({functionality:`tool choice type: ${q}`})}}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[k](m){return E({modelId:m.modelId,config:m.config})}static[T](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:H,topP:q,topK:v,frequencyPenalty:R,presencePenalty:A,reasoning:x,stopSequences:j,responseFormat:L,seed:U,providerOptions:X,tools:se,toolChoice:Q}){let Z=[],V=await h({provider:"mistral",providerOptions:X,schema:Fe})??{};if(v!=null)Z.push({type:"unsupported",feature:"topK"});let re=Ye.has(this.modelId),K;if(re)K=V.reasoningEffort??(W(x)?x==="none"?"none":Se({reasoning:x,effortMap:{minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},warnings:Z}):void 0);else if(W(x))Z.push({type:"unsupported",feature:"reasoning",details:"This model does not support reasoning configuration."});let J=V.structuredOutputs??!0,P=V.strictJsonSchema??!1;if(L?.type==="json"&&(!J||L.schema==null))m=Nt({messages:m,schema:L.schema});let B={max_tokens:_,temperature:H,top_p:q,...R!=null?{frequency_penalty:R}:{},...A!=null?{presence_penalty:A}:{},stop:j,random_seed:U,reasoning_effort:K,response_format:L?.type==="json"?J&&L?.schema!=null?{type:"json_schema",json_schema:{schema:L.schema,strict:P,name:L.name??"response",description:L.description}}:{type:"json_object"}:void 0},{tools:ae,toolChoice:fe,toolWarnings:ye}=Ze({tools:se,toolChoice:Q});for(let[de,He]of Object.entries({safePrompt:V.safePrompt,documentImageLimit:V.documentImageLimit,documentPageLimit:V.documentPageLimit,promptCacheKey:V.promptCacheKey,parallelToolCalls:V.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:ae,completion_args:{...B,tool_choice:fe}},warnings:[...Z,...ye]}}async doGenerate(m){let{args:_,warnings:H}=await this.getArgs(m),{value:q,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}),A=Re({tools:m.tools,generateId:this.generateId}),x=[],j=!1,L;for(let U of q.outputs)switch(U.type){case"tool.execution":x.push(...A.convertTool(U));break;case"function.call":j=!0,x.push({type:"tool-call",toolCallId:U.tool_call_id,toolName:U.name,input:typeof U.arguments==="string"?U.arguments:JSON.stringify(U.arguments)});break;case"message.output":L=U.model??L;for(let X of typeof U.content==="string"?[{type:"text",text:U.content}]:U.content)x.push(...A.convertChunk(X))}return{content:x,finishReason:{unified:j?"tool-calls":"stop",raw:void 0},usage:pe(q.usage),request:{body:_},response:{id:q.conversation_id,modelId:L,headers:R,body:v},warnings:H}}async doStream(m){let{args:_,warnings:H}=await this.getArgs(m),q={..._,stream:!0},{value:v,responseHeaders:R}=await g({url:`${this.config.baseURL}/conversations`,headers:d(this.config.headers?.(),m.headers),body:q,failedResponseHandler:ce,successfulResponseHandler:D(st),abortSignal:m.abortSignal,fetch:this.config.fetch}),A=Re({tools:m.tools,generateId:this.generateId}),x=new Map,j,L,U,X=!1,se=!1,Q=!1,Z=!1,V=(K)=>{if(L!=null)K.enqueue({type:L.type==="text"?"text-end":"reasoning-end",id:L.id}),L=void 0},re=this.generateId;return{stream:v.pipeThrough(new TransformStream({start(K){j=new Ce(K,{generateId:re}),K.enqueue({type:"stream-start",warnings:H})},transform(K,J){if(m.includeRawChunks)J.enqueue({type:"raw",rawValue:K.rawValue});if(!K.success){se=!0,J.enqueue({type:"error",error:K.error});return}let P=K.value;switch(P.type){case"conversation.response.started":J.enqueue({type:"response-metadata",id:P.conversation_id,...P.created_at!=null?{timestamp:new Date(P.created_at)}:{}});break;case"conversation.response.done":U=P.usage??void 0,Q=!0;break;case"conversation.response.error":se=!0,J.enqueue({type:"error",error:P});break;case"message.output.delta":if(!Z&&P.model!=null)Z=!0,J.enqueue({type:"response-metadata",modelId:P.model});for(let B of A.convertChunk(typeof P.content==="string"?{type:"text",text:P.content}:P.content))if(B.type==="text"||B.type==="reasoning"){let ae=`${P.id}-${P.content_index??0}`;if(L?.id!==ae||L.type!==B.type)V(J),L={id:ae,type:B.type},J.enqueue({type:B.type==="text"?"text-start":"reasoning-start",id:ae});J.enqueue({type:B.type==="text"?"text-delta":"reasoning-delta",id:ae,delta:B.text})}else if(B.type==="source")J.enqueue(B);break;case"function.call.delta":V(J),X=!0,j.processDelta({id:P.tool_call_id,index:P.output_index,function:{name:P.name,arguments:P.arguments}});break;case"tool.execution.started":case"tool.execution.delta":{V(J);let B=x.get(P.id);if(B==null)x.set(P.id,{name:P.name,arguments:P.arguments,function:P.function}),J.enqueue({type:"tool-input-start",id:P.id,toolName:A.toolNameMapping.toCustomToolName(P.name),providerExecuted:!0});else B.arguments+=P.arguments;break}case"tool.execution.done":{let B=x.get(P.id);if(B==null){se=!0,J.enqueue({type:"error",error:Error(`Missing tool execution start for ${P.id}`)});break}J.enqueue({type:"tool-input-delta",id:P.id,delta:JSON.stringify({arguments:B.arguments})}),J.enqueue({type:"tool-input-end",id:P.id});for(let ae of A.convertTool({type:"tool.execution",id:P.id,name:B.name,arguments:B.arguments,function:P.function??B.function,info:P.info}))J.enqueue(ae);x.delete(P.id);break}}},flush(K){V(K),j.flush(),K.enqueue({type:"finish",finishReason:{unified:se||!Q||x.size>0?"error":X?"tool-calls":"stop",raw:void 0},usage:pe(U)})}})),request:{body:q},response:{headers:R}}}};function Re({tools:w,generateId:m}){let _=le({tools:w,providerToolNames:ge}),H=new Set;return{toolNameMapping:_,convertChunk(q){switch(q.type){case"text":return q.text.length>0?[{type:"text",text:q.text}]:[];case"thinking":{let R=q.thinking.map((A)=>A.text).join("");return R.length>0?[{type:"reasoning",text:R}]:[]}case"tool_reference":if(q.url==null||H.has(q.url))return[];let v=m();return H.add(q.url),[{type:"source",sourceType:"url",id:v,url:q.url,title:q.title??q.url}]}},convertTool(q){let v=_.toCustomToolName(q.name);return[{type:"tool-call",toolCallId:q.id,toolName:v,input:JSON.stringify({arguments:q.arguments}),providerExecuted:!0,providerMetadata:{mistral:{type:"tool.execution",name:q.name,...q.function!=null?{function:q.function}:{}}}},{type:"tool-result",toolCallId:q.id,toolName:v,result:{...q.info!=null?{info:q.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(),G()).nullish()}),tt=()=>t({type:n("function.call"),tool_call_id:e(),name:e(),arguments:l([e(),y(e(),G())])}),Le=()=>_e.extend({prompt_tokens:r().default(0),completion_tokens:r().default(0),total_tokens:r().default(0)}),nt=a(()=>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=a(()=>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:i(["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(),G()).nullish()})]))),ot=t({metadata:y(e(),ie()).optional(),outputDimension:r().int().positive().optional(),outputDtype:i(["float","int8","uint8","binary","ubinary"]).optional()}),at=class w{get provider(){return this.config.provider}static[k](m){return E({modelId:m.modelId,config:m.config})}static[T](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:H,headers:q,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:A,value:x,rawValue:j}=await g({url:`${this.config.baseURL}/embeddings`,headers:d(this.config.headers?.(),q),body:{model:this.modelId,input:m,metadata:R.metadata,output_dimension:R.outputDimension??_,output_dtype:R.outputDtype,encoding_format:"float"},failedResponseHandler:ce,successfulResponseHandler:p(it),abortSignal:H,fetch:this.config.fetch});return{warnings:[],embeddings:x.data.map((L)=>L.embedding),usage:x.usage?{tokens:x.usage.prompt_tokens}:void 0,response:{headers:A,body:j}}}},it=a(()=>s(t({data:o(t({embedding:o(r())})),usage:t({prompt_tokens:r()}).nullish()}))),rt=a(()=>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[k](m){return E({modelId:m.modelId,config:m.config})}static[T](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:H="mp3",instructions:q,speed:v,language:R,providerOptions:A}){let x=[],j=await h({provider:"mistral",providerOptions:A,schema:rt}),L="mp3";if(["pcm","wav","mp3","flac","opus"].includes(H))L=H;else x.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${H}. Using mp3 instead.`});if(q!=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 U=j?.refAudio,X={model:this.modelId,input:m,voice_id:U==null?_:void 0,ref_audio:U,expressiveness:j?.expressiveness,phoneme_hints:j?.phonemeHints,response_format:L,stream:!1};return{requestBody:X,requestBodyValues:{...X,ref_audio:U==null?void 0:"[redacted]"},warnings:x}}async doGenerate(m){let _=this.config._internal?.currentDate?.()??new Date,{requestBody:H,requestBodyValues:q,warnings:v}=await this.getArgs(m),{value:R,responseHeaders:A,rawValue:x}=await ve({url:`${this.config.baseURL}/audio/speech`,headers:d({"Content-Type":"application/json"},this.config.headers?.(),m.headers),body:{content:JSON.stringify(H),values:q},failedResponseHandler:ce,successfulResponseHandler:p(ut),abortSignal:m.abortSignal,fetch:this.config.fetch});return{audio:R.audio_data,warnings:v,request:{body:JSON.stringify(q)},response:{timestamp:_,modelId:this.modelId,headers:A,body:x}}}},ut=a(()=>s(t({audio_data:e()}))),dt=a(()=>s(t({language:e().min(1).optional(),returnLanguage:c().optional(),temperature:r().optional(),timestampGranularities:o(i(["segment","word"])).min(1).optional(),diarize:c().optional(),contextBias:o(e().min(1)).optional()}))),pt=class w{static[k](m){return E({modelId:m.modelId,config:m.config})}static[T](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:H}){let q=[],v=await h({provider:"mistral",providerOptions:H,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,A=m instanceof Uint8Array?new Blob([m]):new Blob([N(m)]);if(R.append("model",this.modelId),R.append("file",new File([A],"audio",{type:_}),`audio.${lt(_)}`),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:q}}async doGenerate(m){let _=this.config._internal?.currentDate?.()??new Date,{formData:H,warnings:q}=await this.getArgs(m),{value:v,responseHeaders:R,rawValue:A}=await ne({url:`${this.config.baseURL}/audio/transcriptions`,headers:d(this.config.headers?.(),m.headers),formData:H,failedResponseHandler:ce,successfulResponseHandler:p(mt),abortSignal:m.abortSignal,fetch:this.config.fetch}),x=v.segments?.map((U)=>({text:U.text,startSecond:U.start,endSecond:U.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 L=v.segments?.filter((U)=>U.type!=null||U.score!=null||U.speaker_id!=null).map((U)=>({text:U.text,startSecond:U.start,endSecond:U.end,...U.type!=null&&{type:U.type},...U.score!=null&&{score:U.score},...U.speaker_id!=null&&{speakerId:U.speaker_id}}));if(L!=null&&L.length>0)j.segments=L;return{text:v.text,segments:x,language:v.language??void 0,durationInSeconds:v.usage?.prompt_audio_seconds??x.at(-1)?.endSecond??void 0,warnings:q,...v.usage!=null&&{usage:v.usage},response:{timestamp:_,modelId:v.model,headers:R,body:A},...Object.keys(j).length>0&&{providerMetadata:{mistral:j}}}}};function ue(w,m,_){if(_==null)return;if(Array.isArray(_)){for(let H of _)w.append(m,H);return}w.append(m,String(_))}var mt=a(()=>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=a(()=>s(t({arguments:e()}))),Ne=a(()=>s(t({info:y(e(),G()).optional()}))),ht=S({id:"mistral.web_search",inputSchema:Ae,outputSchema:Ne}),ft=S({id:"mistral.web_search_premium",inputSchema:Ae,outputSchema:Ne}),yt=(w={})=>ht(w),bt=(w={})=>ft(w),vt={webSearch:yt,webSearchPremium:bt};function we(w={}){let m=Y(w.baseURL)??"https://api.mistral.ai/v1",_=()=>F({Authorization:`Bearer ${he({apiKey:w.apiKey,environmentVariableName:"MISTRAL_API_KEY",description:"Mistral"})}`,...w.headers},`ai-sdk-mistral/${gt}`),H=(j)=>new ze(j,{provider:"mistral.chat",baseURL:m,headers:_,fetch:w.fetch,generateId:w.generateId}),q=(j)=>new at(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}),A=(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 H(j)};return x.specificationVersion="v4",x.languageModel=H,x.chat=H,x.conversation=v,x.tools=vt,x.embedding=q,x.embeddingModel=q,x.textEmbedding=q,x.textEmbeddingModel=q,x.speech=R,x.speechModel=R,x.transcription=A,x.transcriptionModel=A,x.imageModel=(j)=>{throw new Ge({modelId:j,modelType:"imageModel"})},x}var St=we();var _t=Ie(we);function Mt(){oe("mistral",_t)}export{Mt as register};
@@ -0,0 +1,5 @@
1
+ import{At}from"./embed-xtkxyrpe.js";import{Mt}from"./embed-7pk91zq8.js";import{Ye,Ft,zt,Xe,Dt}from"./embed-n5nzhrf2.js";function M(e,s){let t=[...s].reverse().find((o)=>o.role==="user");return Ye(e)<12&&t?`${t.content} ${e}`:e}function T(e){let s=e.retriever??(e.index?Mt(e.index):null)??(()=>{throw Error("murmur: pass `index` or `retriever`.")})();return{retriever:s,async ask(t,{history:o=[],signal:u}={}){let a={};if(e.limit!==void 0)a.limit=e.limit;if(e.budgetTokens!==void 0)a.budgetTokens=e.budgetTokens;let i=await s.search(M(t,o),a),d=[e.instructions?.trim(),zt(e.language),i.length?`Sources:
2
+
3
+ ${Ft(i)}`:"Sources: none matched this question. Say you could not find it on this site."].filter(Boolean).join(`
4
+
5
+ `),g=[...o.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=At({model:f,instructions:d,messages:g,onError:()=>{},...u?{abortSignal:u}:{}}),n="",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;n+=r.text,yield r.text}n=Xe(n),c({text:n,cited:Dt(n,i.length)})}catch(r){throw m(r),r}}return{passages:i,textStream:y(),done:l}}}}export{T as createMurmur};