UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

14 lines 137 kB
import{AISDKError as e,InvalidArgumentError as t,InvalidResponseDataError as n,TooManyEmbeddingValuesForCallError as r,UnsupportedFunctionalityError as i}from"../provider/index.js";import{A as a,C as o,T as s,_ as c,b as l,c as u,g as d,k as f,r as p,u as m,y as h}from"../../_chunks/workflow/schemas-4CmFgxN_.js";import{$ as g,C as _,D as v,F as y,G as b,H as x,I as S,J as C,L as w,M as T,N as E,O as D,P as O,R as k,S as A,T as j,V as M,W as N,X as P,_ as F,a as ee,at as I,bt as te,c as ne,ct as L,d as re,dt as R,g as ie,h as ae,i as z,it as B,l as V,lt as oe,m as se,o as ce,ot as le,q as ue,rt as de,s as fe,tt as H,ut as pe,vt as me,w as he,xt as U,y as ge,yt as _e}from"../../_chunks/workflow/dist-C3919PVU.js";import{n as W,r as G,t as ve}from"../../_chunks/workflow/experimental-evaluation-D8_K_Pe9.js";var ye=`4.0.74`,be=N(()=>U(l({error:l({code:h().nullable(),message:s(),status:s(),details:u(a()).nullish()})}))),K=ae({errorSchema:be,errorToMessage:e=>e.error.message}),xe=f([l({text:s()}),l({inlineData:l({mimeType:s(),data:s()})}),l({fileData:l({fileUri:s(),mimeType:s()})})]),Se=N(()=>U(l({outputDimensionality:h().optional(),taskType:p([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:u(u(xe).min(1).nullable()).optional()}))),Ce=class e{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=100,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}static[G](e){return R({modelId:e.modelId,config:e.config})}static[W](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:i}){let a=await g({provider:`google`,providerOptions:i,schema:Se});if(e.length>this.maxEmbeddingsPerCall)throw new r({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=z(this.config.headers?await B(this.config.headers):void 0,t),s=a?.content;if(s!=null&&s.length!==e.length)throw Error(`The number of multimodal content entries (${s.length}) must match the number of values (${e.length}).`);if(e.length===1){let t=s?.[0],r=e[0]?[{text:e[0]}]:[],i=t==null?[{text:e[0]}]:[...r,...t],{responseHeaders:c,value:l,rawValue:u}=await H({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:i},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:K,successfulResponseHandler:F(Te),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:[l.embedding.values],usage:void 0,response:{headers:c,body:u}}}let{responseHeaders:c,value:l,rawValue:u}=await H({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map((e,t)=>{let n=s?.[t],r=e?[{text:e}]:[];return{model:`models/${this.modelId}`,content:{role:`user`,parts:n==null?[{text:e}]:[...r,...n]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}})},failedResponseHandler:K,successfulResponseHandler:F(we),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:l.embeddings.map(e=>e.values),usage:void 0,response:{headers:c,body:u}}}},we=N(()=>U(l({embeddings:u(l({values:u(h())}))}))),Te=N(()=>U(l({embedding:l({values:u(h())})})));function q(e){return e.includes(`/`)?e:`models/${e}`}function Ee(e){if(e==null)return ge();let t=e.promptTokenCount??0,n=e.candidatesTokenCount??0,r=e.cachedContentTokenCount??0,i=e.thoughtsTokenCount??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n+i,text:n,reasoning:i},raw:e}}var De=`skip_thought_signature_validator`,Oe=/^data:([^;,]+);base64,(.+)$/s;function ke(e){let t=Oe.exec(e);if(t!=null)return{mediaType:t[1],data:t[2]}}function Ae(e){let t=ke(e);if(t!=null)return{inlineData:{mimeType:t.mediaType,data:t.data}}}function je(e,t,n,r,i=!0){let a=[],o=[];for(let e of n)switch(e.type){case`text`:o.push(e.text);break;case`file`:if(e.data.type===`data`)a.push({inlineData:{mimeType:I({part:e}),data:V(e.data.data)}});else if(e.data.type===`url`){let t=Ae(e.data.url.toString());t==null?o.push(JSON.stringify(e)):a.push(t)}else o.push(JSON.stringify(e));break;default:o.push(JSON.stringify(e))}e.push({functionResponse:{...i&&r!=null?{id:r}:{},name:t,response:{name:t,content:o.length>0?o.join(`
`):`Tool executed successfully.`},...a.length>0?{parts:a}:{}}})}function Me(e,t,n,r,i=!0){for(let a of n)switch(a.type){case`text`:e.push({functionResponse:{...i&&r!=null?{id:r}:{},name:t,response:{name:t,content:a.text}}});break;case`file`:if(a.data.type===`data`){let t=y(a.mediaType);e.push({inlineData:{mimeType:I({part:a}),data:V(a.data.data)}},{text:`Tool executed successfully and returned this ${t===`image`?`image`:`file`} as a response`})}else e.push({text:JSON.stringify(a)});break;default:e.push({text:JSON.stringify(a)})}}function Ne(e,t){let n=[],r=[],a=!0,o=t?.isGemmaModel??!1,s=t?.isGemini3Model??!1,c=t?.onWarning,l=t?.providerOptionsNames??[`google`],u=!l.includes(`google`),d=t?.supportsFunctionResponseParts??!0,f=t?.includeFunctionCallIds??!0,p=!1,m=[],h=e=>(m.push(e),p=!0,De),g=e=>{for(let t of l){let n=e.providerOptions?.[t];if(n!=null)return n}return u?e.providerOptions?.google:e.providerOptions?.googleVertex??e.providerOptions?.vertex};for(let{role:t,content:o}of e)switch(t){case`system`:if(!a)throw new i({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:switch(t.data.type){case`url`:e.push({fileData:{mimeType:I({part:t}),fileUri:t.data.url.toString()}});break;case`reference`:if(u)throw new i({functionality:`file parts with provider references`});e.push({fileData:{mimeType:I({part:t}),fileUri:le({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:k(t.mediaType)?t.mediaType:`text/plain`,data:V(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:I({part:t}),data:V(t.data.data)}})}}r.push({role:`user`,parts:e});break}case`assistant`:{a=!1;let e=!1;r.push({role:`model`,parts:o.map(t=>{let n=g(t),r=n?.thoughtSignature==null?void 0:String(n.thoughtSignature);switch(t.type){case`text`:return t.text.length===0?void 0:{text:t.text,thoughtSignature:r};case`reasoning`:return t.text.length===0?void 0:{text:t.text,thought:!0,thoughtSignature:r};case`reasoning-file`:switch(t.data.type){case`url`:throw new i({functionality:`File data URLs in assistant messages are not supported`});case`data`:return{inlineData:{mimeType:t.mediaType,data:V(t.data.data)},thought:!0,thoughtSignature:r}}break;case`file`:switch(t.data.type){case`url`:throw new i({functionality:`File data URLs in assistant messages are not supported`});case`reference`:if(u)throw new i({functionality:`file parts with provider references`});return{fileData:{mimeType:t.mediaType,fileUri:le({reference:t.data.reference,provider:`google`})},...n?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`text`:return{inlineData:{mimeType:k(t.mediaType)?t.mediaType:`text/plain`,data:V(new TextEncoder().encode(t.data.text))},...n?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`data`:return{inlineData:{mimeType:t.mediaType,data:V(t.data.data)},...n?.thought===!0?{thought:!0}:{},thoughtSignature:r}}break;case`tool-call`:{let i=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),a=n?.serverToolType==null?void 0:String(n.serverToolType),o=i!=null&&a!=null,c=r??(s&&(o||r!=null||!e)?h(t.toolName):void 0);return!o&&r!=null&&(e=!0),o?{toolCall:{toolType:a,args:typeof t.input==`string`?pe(t.input):t.input,id:i},thoughtSignature:c}:{functionCall:{...f&&t.toolCallId!=null?{id:t.toolCallId}:{},name:t.toolName,args:t.input},thoughtSignature:c}}case`tool-result`:{let e=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),i=n?.serverToolType==null?void 0:String(n.serverToolType);return e&&i?{toolResponse:{toolType:i,response:t.output.type===`json`?t.output.value:{},id:e},thoughtSignature:r}:void 0}}}).filter(e=>e!==void 0)});break}case`tool`:{a=!1;let e=[];for(let t of o){if(t.type===`tool-approval-response`)continue;let n=g(t),i=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),a=n?.serverToolType==null?void 0:String(n.serverToolType);if(i&&a){let e=n?.thoughtSignature==null?void 0:String(n.thoughtSignature);if(r.length>0){let n=r[r.length-1];if(n.role===`model`){n.parts.push({toolResponse:{toolType:a,response:t.output.type===`json`?t.output.value:{},id:i},thoughtSignature:e});continue}}}let o=t.output;o.type===`content`?d?je(e,t.toolName,o.value,t.toolCallId,f):Me(e,t.toolName,o.value,t.toolCallId,f):e.push({functionResponse:{...f&&t.toolCallId!=null?{id:t.toolCallId}:{},name:t.toolName,response:{name:t.toolName,content:o.type===`execution-denied`?o.reason??`Tool call execution denied.`:o.value}}})}r.push({role:`user`,parts:e});break}}if(o&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`

`);r[0].parts.unshift({text:e+`

`})}if(p&&c!=null){let e=Array.from(new Set(m));c({type:`other`,message:`Replayed ${m.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${e.map(e=>`\`${e}\``).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:n.length>0&&!o?{parts:n}:void 0,contents:r}}async function Pe(e,{abortSignal:t,maxBytes:n}){let r=[];for(let i of e){if(i.role===`assistant`){let e=[];for(let r of i.content)e.push(r.type===`tool-result`?{...r,output:await Fe(r.output,{abortSignal:t,maxBytes:n})}:r);r.push({...i,content:e});continue}if(i.role===`tool`){let e=[];for(let r of i.content){if(r.type!==`tool-result`){e.push(r);continue}e.push({...r,output:await Fe(r.output,{abortSignal:t,maxBytes:n})})}r.push({...i,content:e});continue}r.push(i)}return r}async function Fe(e,{abortSignal:t,maxBytes:n}){if(e.type!==`content`)return e;let r=[];for(let i of e.value){if(i.type!==`file`||i.data.type!==`url`){r.push(i);continue}let e=await D(i.data.url.toString(),{abortSignal:t,maxBytes:n}),a=new Uint8Array(await e.arrayBuffer()),o=v({data:a,topLevelType:`image`});r.push({...i,data:{type:`data`,data:a},mediaType:o??(e.type&&!k(i.mediaType)?e.type:i.mediaType)})}return{...e,value:r}}function Ie(e){let{const:t,properties:n,items:r,additionalProperties:i,anyOf:a,oneOf:o,...s}=e;return{...s,...t===void 0?{}:{enum:[t]},...n==null?{}:{properties:Le(n)},...r==null?{}:{items:Array.isArray(r)?r.map(J):J(r)},...i==null?{}:{additionalProperties:typeof i==`boolean`?i:J(i)},...a==null?{}:{anyOf:a.map(J)},...o==null?{}:{oneOf:o.map(J)},...s.$defs==null?{}:{$defs:Le(s.$defs)}}}function Le(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,J(t)]))}function J(e){return typeof e==`boolean`?e:Ie(e)}var Y=N(()=>U(l({responseModalities:u(p([`TEXT`,`IMAGE`])).optional(),thinkingConfig:l({thinkingBudget:h().optional(),includeThoughts:m().optional(),thinkingLevel:p([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:s().optional(),structuredOutputs:m().optional(),safetySettings:u(l({category:p([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:p([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:p([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:m().optional(),labels:o(s(),s()).optional(),mediaResolution:p([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:l({aspectRatio:p([`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:p([`1K`,`2K`,`4K`,`512`]).optional(),personGeneration:p([`PERSON_GENERATION_UNSPECIFIED`,`ALLOW_ALL`,`ALLOW_ADULT`,`ALLOW_NONE`]).optional(),prominentPeople:p([`PROMINENT_PEOPLE_UNSPECIFIED`,`ALLOW_PROMINENT_PEOPLE`,`BLOCK_PROMINENT_PEOPLE`]).optional(),imageOutputOptions:l({mimeType:p([`image/jpeg`,`image/png`]).optional(),compressionQuality:h().optional()}).optional()}).optional(),retrievalConfig:l({latLng:l({latitude:h(),longitude:h()}).optional()}).optional(),streamFunctionCallArguments:m().optional(),serviceTier:p([`standard`,`flex`,`priority`]).optional(),sharedRequestType:p([`priority`,`flex`,`standard`]).optional(),requestType:p([`shared`]).optional()}))),Re=/(^|\/)gemini-1(?:[.-]|$)/i,ze=/(^|\/)gemini-2(?:[.-]|$)/i,Be=/(^|\/)gemini-2\.5(?:[.-]|$)/i,Ve=/(^|\/)gemini-/i;function He(e){return Re.test(e)||/(^|\/)gemini-pro(?:-vision)?$/i.test(e)||/(^|\/)gemini-robotics-er-1\.5(?:[.-]|$)/i.test(e)}function Ue(e){let t=Ve.test(e),n=ze.test(e),r=He(e),i=t&&!(r||n);return{supportsGemini2Tools:t&&!r||e.toLowerCase().includes(`nano-banana`),supportsFileSearch:Be.test(e)||i,usesGemini3Features:i}}function We({tools:e,toolChoice:t,modelId:n,isVertexProvider:r=!1}){e=e?.length?e:void 0;let a=[],{supportsGemini2Tools:o,supportsFileSearch:s,usesGemini3Features:c}=Ue(n);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:a};let l=e.some(e=>e.type===`function`),u=e.some(e=>e.type===`provider`);if(l&&u&&!c&&a.push({type:`unsupported`,feature:`combination of function and provider-defined tools`}),u){let n=[];if(e.filter(e=>e.type===`provider`).forEach(e=>{switch(e.id){case`google.google_search`:o?n.push({googleSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Google Search requires Gemini 2.0 or newer.`});break;case`google.enterprise_web_search`:o?n.push({enterpriseWebSearch:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Enterprise Web Search requires Gemini 2.0 or newer.`});break;case`google.url_context`:o?n.push({urlContext:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:o?n.push({codeExecution:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The code execution tool is not supported with other Gemini models than Gemini 2.`});break;case`google.file_search`:s?n.push({fileSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The file search tool is only supported with Gemini 2.5 models and Gemini 3 models.`});break;case`google.vertex_rag_store`:o?n.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:e.args.ragCorpus},similarity_top_k:e.args.topK}}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The RAG store tool is not supported with other Gemini models than Gemini 2.`});break;case`google.google_maps`:o?n.push({googleMaps:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer.`});break;default:a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`})}}),l&&c&&n.length>0){let i=[];for(let t of e)t.type===`function`&&i.push(Ge(t));let o={functionCallingConfig:{mode:`VALIDATED`},...!r&&{includeServerSideToolInvocations:!0}};if(t!=null)switch(t.type){case`auto`:break;case`none`:o.functionCallingConfig={mode:`NONE`};break;case`required`:o.functionCallingConfig={mode:`ANY`};break;case`tool`:o.functionCallingConfig={mode:`ANY`,allowedFunctionNames:[t.toolName]}}return{tools:[...n,{functionDeclarations:i}],toolConfig:o,toolWarnings:a}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:a}}let d=[],f=!1;for(let t of e)switch(t.type){case`function`:d.push(Ge(t)),t.strict===!0&&(f=!0);break;default:a.push({type:`unsupported`,feature:`function tool ${t.name}`})}if(t==null)return{tools:[{functionDeclarations:d}],toolConfig:f?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:a};let p=t.type;switch(p){case`auto`:return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:f?`VALIDATED`:`AUTO`}},toolWarnings:a};case`none`:return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:a};case`required`:return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:a};case`tool`:return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:a};default:throw new i({functionality:`tool choice type: ${p}`})}}function Ge(e){return{name:e.name,description:e.description??``,parametersJsonSchema:e.inputSchema}}var Ke=class{constructor(){this.accumulatedArgs={},this.jsonText=``,this.pathStack=[],this.stringOpen=!1}processPartialArgs(e){let t=``;for(let n of e){let e=n.jsonPath.replace(/^\$\./,``);if(!e)continue;let r=qe(e),i=Ze(this.accumulatedArgs,r);if(n.stringValue!=null&&i!==void 0){let e=JSON.stringify(n.stringValue).slice(1,-1);Qe(this.accumulatedArgs,r,i+n.stringValue),t+=e;continue}let a=$e(n);a!=null&&(Qe(this.accumulatedArgs,r,a.value),t+=this.emitNavigationTo(r,n,a.json))}return this.jsonText+=t,{currentJSON:this.accumulatedArgs,textDelta:t}}finalize(){let e=JSON.stringify(this.accumulatedArgs);return{finalJSON:e,closingDelta:e.slice(this.jsonText.length)}}ensureRoot(){return this.pathStack.length===0?(this.pathStack.push({segment:``,isArray:!1,childCount:0}),`{`):``}emitNavigationTo(e,t,n){let r=``;this.stringOpen&&=(r+=`"`,!1),r+=this.ensureRoot();let i=e.slice(0,-1),a=e[e.length-1],o=this.findCommonStackDepth(i);return r+=this.closeDownTo(o),r+=this.openDownTo(i,a),r+=this.emitLeaf(a,t,n),r}findCommonStackDepth(e){let t=Math.min(this.pathStack.length-1,e.length),n=0;for(let r=0;r<t&&this.pathStack[r+1].segment===e[r];r++)n++;return n+1}closeDownTo(e){let t=``;for(;this.pathStack.length>e;){let e=this.pathStack.pop();t+=e.isArray?`]`:`}`}return t}openDownTo(e,t){let n=``,r=this.pathStack.length-1;for(let i=r;i<e.length;i++){let r=e[i],a=this.pathStack[this.pathStack.length-1];a.childCount>0&&(n+=`,`),a.childCount++,typeof r==`string`&&(n+=`${JSON.stringify(r)}:`);let o=typeof(i+1<e.length?e[i+1]:t)==`number`;n+=o?`[`:`{`,this.pathStack.push({segment:r,isArray:o,childCount:0})}return n}emitLeaf(e,t,n){let r=``,i=this.pathStack[this.pathStack.length-1];return i.childCount>0&&(r+=`,`),i.childCount++,typeof e==`string`&&(r+=`${JSON.stringify(e)}:`),t.stringValue!=null&&t.willContinue?(r+=n.slice(0,-1),this.stringOpen=!0):r+=n,r}};function qe(e){let t=[];for(let n of e.split(`.`)){let e=n.indexOf(`[`);if(e===-1)t.push(n);else{e>0&&t.push(n.slice(0,e));for(let e of n.matchAll(/\[(\d+)\]/g))t.push(parseInt(e[1],10))}}return t}var Je=Object.prototype.hasOwnProperty;function Ye(e,t){return Je.call(e,t)}function Xe(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function Ze(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;let t=n;if(!Ye(t,e))return;n=t[e]}return n}function Qe(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];(!Ye(r,n)||r[n]==null)&&Xe(r,n,typeof i==`number`?[]:{}),r=r[n]}Xe(r,t[t.length-1],n)}function $e(e){let t=e.stringValue??e.numberValue??e.boolValue;if(t!=null)return{value:t,json:JSON.stringify(t)};if(`nullValue`in e)return{value:null,json:`null`}}function et({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`: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 tt=[`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`],nt=/(^|\/)gemini-2\.5(?:[.-]|$)/i,X=class e{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??T}static[G](e){return R({modelId:e.modelId,config:e.config})}static[W](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}static async prepareRequest({modelId:e,config:t,options:{prompt:n,maxOutputTokens:r,temperature:i,topP:a,topK:o,frequencyPenalty:s,presencePenalty:c,stopSequences:l,responseFormat:u,seed:d,tools:f,toolChoice:p,reasoning:m,providerOptions:h,abortSignal:_},isStreaming:v=!1}){let y=[],b=t.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],x;for(let e of b)if(x=await g({provider:e,providerOptions:h,schema:Y}),x!=null)break;x==null&&!b.includes(`google`)&&(x=await g({provider:`google`,providerOptions:h,schema:Y}));let S=t.provider.startsWith(`google.vertex.`);f?.some(e=>e.type===`provider`&&e.id===`google.vertex_rag_store`)&&!S&&y.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 (${t.provider}).`}),x?.streamFunctionCallArguments&&!S&&y.push({type:`other`,message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${t.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`}),x?.serviceTier&&S&&y.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`}),(x?.sharedRequestType||x?.requestType)&&!S&&y.push({type:`other`,message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${t.provider}).`});let C=S&&(x?.sharedRequestType||x?.requestType)?{...x.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":x.sharedRequestType},...x.requestType&&{"X-Vertex-AI-LLM-Request-Type":x.requestType}}:void 0,w=S?void 0:x?.serviceTier,T=x?.imageConfig;if(T!=null&&!S){let{personGeneration:e,prominentPeople:n,imageOutputOptions:r,...i}=T,a=Object.entries({personGeneration:e,prominentPeople:n,imageOutputOptions:r}).filter(([,e])=>e!=null).map(([e])=>`'imageConfig.${e}'`);a.length>0&&(y.push({type:`other`,message:`${a.join(`, `)} ${a.length===1?`is a Vertex AI option and is`:`are Vertex AI options and are`} ignored with the current Google provider (${t.provider}).`}),T=i)}let E=e.toLowerCase().startsWith(`gemma-`),D=!S&&nt.test(e);D&&s!=null&&y.push({type:`unsupported`,feature:`frequencyPenalty`}),D&&c!=null&&y.push({type:`unsupported`,feature:`presencePenalty`});let{usesGemini3Features:O}=Ue(e),{contents:k,systemInstruction:A}=Ne(t.downloadToolResultFiles?await Pe(n,{abortSignal:_,maxBytes:t.downloadToolResultFiles.maxBytes}):n,{isGemmaModel:E,isGemini3Model:O,onWarning:e=>y.push(e),providerOptionsNames:b,supportsFunctionResponseParts:O,includeFunctionCallIds:!S}),{tools:j,toolConfig:M,toolWarnings:N}=We({tools:f,toolChoice:p,modelId:e,isVertexProvider:S}),P=he({tools:f,providerToolNames:{"google.code_execution":`code_execution`}}),F=at({reasoning:m,modelId:e,warnings:y}),ee=x?.thinkingConfig||F?{...F,...x?.thinkingConfig}:void 0,I=v&&S?x?.streamFunctionCallArguments??!1:void 0,te=x?.threshold,ne=x?.safetySettings??(te==null?void 0:tt.map(e=>({category:e,threshold:te}))),L=M||I||x?.retrievalConfig?{...M,...I&&{functionCallingConfig:{...M?.functionCallingConfig,streamFunctionCallArguments:!0}},...x?.retrievalConfig&&{retrievalConfig:x.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:r,temperature:i,topK:o,topP:a,frequencyPenalty:D?void 0:s,presencePenalty:D?void 0:c,stopSequences:l,seed:d,responseMimeType:u?.type===`json`?`application/json`:void 0,responseJsonSchema:u?.type===`json`&&u.schema!=null&&(x?.structuredOutputs??!0)?Ie(u.schema):void 0,...x?.audioTimestamp&&{audioTimestamp:x.audioTimestamp},responseModalities:x?.responseModalities,thinkingConfig:ee,...x?.mediaResolution&&{mediaResolution:x.mediaResolution},...T&&{imageConfig:T}},contents:k,systemInstruction:E?void 0:A,safetySettings:ne,tools:j,toolConfig:L,cachedContent:x?.cachedContent,labels:x?.labels,serviceTier:w},warnings:[...y,...N],providerOptionsNames:b,extraHeaders:C,toolNameMapping:P}}getArgs(t,{isStreaming:n=!1}={}){return e.prepareRequest({modelId:this.modelId,config:this.config,options:t,isStreaming:n})}static convertGenerateContentResponse({config:e,response:t,warnings:n,providerOptionsNames:r,toolNameMapping:i}){let a=e=>Object.fromEntries(r.map(t=>[t,e])),o=t.candidates?.[0],s=t.promptFeedback?.blockReason,c=o?.finishReason==null&&s!=null,l=o?.finishReason??s??void 0,u=[],d=o?.content?.parts??[],f=t.usageMetadata,p,m;for(let t of d)if(`executableCode`in t&&t.executableCode?.code){let n=e.generateId();p=n,u.push({type:`tool-call`,toolCallId:n,toolName:i?.toCustomToolName(`code_execution`)??`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in t&&t.codeExecutionResult)u.push({type:`tool-result`,toolCallId:p,toolName:i?.toCustomToolName(`code_execution`)??`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output??``}});else if(`text`in t&&t.text!=null){let e=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0;if(t.text.length===0){if(e!=null&&u.length>0){let t=u[u.length-1];t.providerMetadata=e}}else u.push({type:t.thought===!0?`reasoning`:`text`,text:t.text,providerMetadata:e})}else if(`functionCall`in t&&t.functionCall.name!=null)u.push({type:`tool-call`,toolCallId:t.functionCall.id||e.generateId(),toolName:t.functionCall.name,input:JSON.stringify(t.functionCall.args??{}),providerMetadata:t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0});else if(`inlineData`in t){let e=t.thought===!0,n=!!t.thoughtSignature;u.push({type:e?`reasoning-file`:`file`,data:{type:`data`,data:t.inlineData.data},mediaType:t.inlineData.mimeType,providerMetadata:n?a({thoughtSignature:t.thoughtSignature}):void 0})}else if(`toolCall`in t&&t.toolCall){let n=t.toolCall.id||e.generateId();m=n,u.push({type:`tool-call`,toolCallId:n,toolName:`server:${t.toolCall.toolType}`,input:JSON.stringify(t.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:t.thoughtSignature?a({thoughtSignature:t.thoughtSignature,serverToolCallId:n,serverToolType:t.toolCall.toolType}):a({serverToolCallId:n,serverToolType:t.toolCall.toolType})})}else if(`toolResponse`in t&&t.toolResponse){let n=m||t.toolResponse.id||e.generateId();u.push({type:`tool-result`,toolCallId:n,toolName:`server:${t.toolResponse.toolType}`,result:t.toolResponse.response??{},providerMetadata:t.thoughtSignature?a({thoughtSignature:t.thoughtSignature,serverToolCallId:n,serverToolType:t.toolResponse.toolType}):a({serverToolCallId:n,serverToolType:t.toolResponse.toolType})}),m=void 0}let h=lt({groundingMetadata:o?.groundingMetadata,generateId:e.generateId})??[];for(let e of h)u.push(e);return{content:u,finishReason:{unified:c?`content-filter`:et({finishReason:l,hasToolCalls:u.some(e=>e.type===`tool-call`&&!e.providerExecuted)}),raw:l},usage:Ee(f),warnings:n,providerMetadata:a({promptFeedback:t.promptFeedback??null,groundingMetadata:o?.groundingMetadata??null,urlContextMetadata:o?.urlContextMetadata??null,safetyRatings:o?.safetyRatings??null,usageMetadata:f??null,finishMessage:o?.finishMessage??null,serviceTier:f?.serviceTier??null}),response:{id:t.responseId??void 0}}}async doGenerate(t){let{args:n,warnings:r,providerOptionsNames:i,extraHeaders:a,toolNameMapping:o}=await this.getArgs(t),s=z(this.config.headers?await B(this.config.headers):void 0,t.headers,a),{responseHeaders:c,value:l,rawValue:u}=await H({url:`${this.config.baseURL}/${q(this.modelId)}:generateContent`,headers:s,body:n,failedResponseHandler:K,successfulResponseHandler:F(_t),abortSignal:t.abortSignal,fetch:this.config.fetch}),d=e.convertGenerateContentResponse({config:this.config,response:l,warnings:r,providerOptionsNames:i,toolNameMapping:o});return{...d,request:{body:n},response:{...d.response,headers:c,body:u}}}async doStream(e){let{args:t,warnings:n,providerOptionsNames:r,extraHeaders:i,toolNameMapping:a}=await this.getArgs(e,{isStreaming:!0}),o=e=>Object.fromEntries(r.map(t=>[t,e])),s=z(this.config.headers?await B(this.config.headers):void 0,e.headers,i),{responseHeaders:c,value:l}=await H({url:`${this.config.baseURL}/${q(this.modelId)}:streamGenerateContent?alt=sse`,headers:s,body:t,failedResponseHandler:K,successfulResponseHandler:se(vt),abortSignal:e.abortSignal,fetch:this.config.fetch}),u={unified:`other`,raw:void 0},d,f=null,p=null,m=null,h=null,g=null,_,v=this.config.generateId,y=!1,b=!1,x=null,S=null,C=0,w=new Set,T,E,D=[],O=e=>{let t=D.pop();if(t==null)return;let{finalJSON:n,closingDelta:r}=t.accumulator.finalize();r.length>0&&e.enqueue({type:`tool-input-delta`,id:t.toolCallId,delta:r,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-input-end`,id:t.toolCallId,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-call`,toolCallId:t.toolCallId,toolName:t.toolName,input:n,providerMetadata:t.providerMetadata}),y=!0};return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;!b&&r.responseId!=null&&(b=!0,n.enqueue({type:`response-metadata`,id:r.responseId}));let i=r.usageMetadata;i!=null&&(d=i),r.promptFeedback!=null&&_==null&&(f=r.promptFeedback,yt(r.promptFeedback.blockReason)&&(_=r.promptFeedback.blockReason,u={unified:`content-filter`,raw:_}));let s=r.candidates?.[0];if(s!=null&&(s.groundingMetadata!=null&&(p=s.groundingMetadata),s.urlContextMetadata!=null&&(m=s.urlContextMetadata),s.safetyRatings!=null&&(h=s.safetyRatings),s.finishMessage!=null&&(g=s.finishMessage)),_!=null||s==null)return;let c=s.content,l=lt({groundingMetadata:s.groundingMetadata,generateId:v});if(l!=null)for(let e of l)e.sourceType===`url`&&!w.has(e.url)&&(w.add(e.url),n.enqueue(e));if(c!=null){let e=c.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=v();T=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:a.toCustomToolName(`code_execution`),input:JSON.stringify(t.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=T;e&&n.enqueue({type:`tool-result`,toolCallId:e,toolName:a.toCustomToolName(`code_execution`),result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output??``}})}else if(`text`in t&&t.text!=null){let e=t.thoughtSignature?o({thoughtSignature:t.thoughtSignature}):void 0;t.text.length===0?e!=null&&x!==null&&n.enqueue({type:`text-delta`,id:x,delta:``,providerMetadata:e}):t.thought===!0?(x!==null&&(n.enqueue({type:`text-end`,id:x}),x=null),S===null&&(S=String(C++),n.enqueue({type:`reasoning-start`,id:S,providerMetadata:e})),n.enqueue({type:`reasoning-delta`,id:S,delta:t.text,providerMetadata:e})):(S!==null&&(n.enqueue({type:`reasoning-end`,id:S}),S=null),x===null&&(x=String(C++),n.enqueue({type:`text-start`,id:x,providerMetadata:e})),n.enqueue({type:`text-delta`,id:x,delta:t.text,providerMetadata:e}))}else if(`inlineData`in t){x!==null&&(n.enqueue({type:`text-end`,id:x}),x=null),S!==null&&(n.enqueue({type:`reasoning-end`,id:S}),S=null);let e=t.thought===!0,r=t.thoughtSignature?o({thoughtSignature:t.thoughtSignature}):void 0;n.enqueue({type:e?`reasoning-file`:`file`,mediaType:t.inlineData.mimeType,data:{type:`data`,data:t.inlineData.data},providerMetadata:r})}else if(`toolCall`in t&&t.toolCall){let e=t.toolCall.id||v();E=e;let r=o({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolCall.toolType});n.enqueue({type:`tool-call`,toolCallId:e,toolName:`server:${t.toolCall.toolType}`,input:JSON.stringify(t.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:r})}else if(`toolResponse`in t&&t.toolResponse){let e=E||t.toolResponse.id||v(),r=o({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolResponse.toolType});n.enqueue({type:`tool-result`,toolCallId:e,toolName:`server:${t.toolResponse.toolType}`,result:t.toolResponse.response??{},providerMetadata:r}),E=void 0}for(let t of e){if(!(`functionCall`in t))continue;let e=t.thoughtSignature?o({thoughtSignature:t.thoughtSignature}):void 0,r=t.functionCall.partialArgs!=null||t.functionCall.name!=null&&t.functionCall.willContinue===!0,i=t.functionCall.name==null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue==null,a=t.functionCall.name!=null&&t.functionCall.args!=null&&t.functionCall.partialArgs==null,s=t.functionCall.name!=null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue!==!0;if(r){if(t.functionCall.name!=null){let r=t.functionCall.id||v(),i=new Ke;if(D.push({toolCallId:r,toolName:t.functionCall.name,accumulator:i,providerMetadata:e}),n.enqueue({type:`tool-input-start`,id:r,toolName:t.functionCall.name,providerMetadata:e}),t.functionCall.partialArgs!=null){let a=t.functionCall.partialArgs,{textDelta:o}=i.processPartialArgs(a);o.length>0&&n.enqueue({type:`tool-input-delta`,id:r,delta:o,providerMetadata:e}),t.functionCall.willContinue!==!0&&a.every(e=>e.willContinue!==!0)&&O(n)}}else if(t.functionCall.partialArgs!=null&&D.length>0){let r=D[D.length-1],i=t.functionCall.partialArgs,{textDelta:a}=r.accumulator.processPartialArgs(i);a.length>0&&n.enqueue({type:`tool-input-delta`,id:r.toolCallId,delta:a,providerMetadata:e}),t.functionCall.willContinue!==!0&&i.every(e=>e.willContinue!==!0)&&O(n)}}else if(i&&D.length>0)O(n);else if(a){let r=t.functionCall.id||v(),i=t.functionCall.name,a=typeof t.functionCall.args==`string`?t.functionCall.args:JSON.stringify(t.functionCall.args??{});n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-delta`,id:r,delta:a,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:a,providerMetadata:e}),y=!0}else if(s){let r=t.functionCall.id||v(),i=t.functionCall.name;n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:`{}`,providerMetadata:e}),y=!0}}}s.finishReason!=null&&(u={unified:et({finishReason:s.finishReason,hasToolCalls:y}),raw:s.finishReason})},flush(e){x!==null&&e.enqueue({type:`text-end`,id:x}),S!==null&&e.enqueue({type:`reasoning-end`,id:S}),e.enqueue({type:`finish`,finishReason:u,usage:Ee(d),providerMetadata:o({promptFeedback:f,groundingMetadata:p,urlContextMetadata:m,safetyRatings:h,usageMetadata:d??null,finishMessage:g,serviceTier:d?.serviceTier??null})})}})),response:{headers:c},request:{body:t}}}};function rt(){return 65536}function it(e){let t=e.toLowerCase();return t.includes(`2.5-pro`)||t.includes(`gemini-3-pro-image`)?32768:24576}function at({reasoning:e,modelId:t,warnings:n}){if(w(e))return Ue(t).usesGemini3Features&&!t.includes(`gemini-3-pro-image`)?ot({reasoning:e,modelId:t,warnings:n}):ct({reasoning:e,modelId:t,warnings:n})}function ot({reasoning:e,modelId:t,warnings:n}){let r=st(t);if(e===`none`)return{thinkingLevel:r};let i=C({reasoning:e,effortMap:{minimal:r,low:`low`,medium:`medium`,high:`high`,xhigh:`high`},warnings:n});if(i!=null)return{thinkingLevel:i}}function st(e){let t=e.split(`/`).at(-1)?.toLowerCase();if(t===`gemini-flash-latest`)return`low`;let n=/^gemini-(\d+)\.(\d+)-flash(?:$|-(?!lite(?:-|$)))/.exec(t??``);if(n==null)return`minimal`;let r=Number(n[1]),i=Number(n[2]);return r>3||r===3&&i>=7?`low`:`minimal`}function ct({reasoning:e,modelId:t,warnings:n}){if(e===`none`)return{thinkingBudget:0};let r=ue({reasoning:e,maxOutputTokens:rt(),maxReasoningBudget:it(t),minReasoningBudget:0,warnings:n});if(r!=null)return{thinkingBudget:r}}function lt({groundingMetadata:e,generateId:t}){if(!e?.groundingChunks)return;let n=[];for(let r of e.groundingChunks)if(r.web!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.web.uri,title:r.web.title??void 0});else if(r.image!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.image.sourceUri,title:r.image.title??void 0});else if(r.retrievedContext!=null){let e=r.retrievedContext.uri,i=r.retrievedContext.fileSearchStore;if(e&&(e.startsWith(`http://`)||e.startsWith(`https://`)))n.push({type:`source`,sourceType:`url`,id:t(),url:e,title:r.retrievedContext.title??void 0});else if(e){let i=r.retrievedContext.title??`Unknown Document`,a=`application/octet-stream`,o;e.endsWith(`.pdf`)?(a=`application/pdf`,o=e.split(`/`).pop()):e.endsWith(`.txt`)?(a=`text/plain`,o=e.split(`/`).pop()):e.endsWith(`.docx`)?(a=`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,o=e.split(`/`).pop()):e.endsWith(`.doc`)?(a=`application/msword`,o=e.split(`/`).pop()):(e.match(/\.(md|markdown)$/)&&(a=`text/markdown`),o=e.split(`/`).pop()),n.push({type:`source`,sourceType:`document`,id:t(),mediaType:a,title:i,filename:o})}else if(i){let e=r.retrievedContext.title??`Unknown Document`;n.push({type:`source`,sourceType:`document`,id:t(),mediaType:`application/octet-stream`,title:e,filename:i.split(`/`).pop()})}}else r.maps!=null&&r.maps.uri&&n.push({type:`source`,sourceType:`url`,id:t(),url:r.maps.uri,title:r.maps.title??void 0});return n.length>0?n:void 0}var ut=()=>l({webSearchQueries:u(s()).nullish(),imageSearchQueries:u(s()).nullish(),retrievalQueries:u(s()).nullish(),searchEntryPoint:l({renderedContent:s()}).nullish(),groundingChunks:u(l({web:l({uri:s(),title:s().nullish()}).nullish(),image:l({sourceUri:s(),imageUri:s(),title:s().nullish(),domain:s().nullish()}).nullish(),retrievedContext:l({uri:s().nullish(),title:s().nullish(),text:s().nullish(),fileSearchStore:s().nullish()}).nullish(),maps:l({uri:s().nullish(),title:s().nullish(),text:s().nullish(),placeId:s().nullish()}).nullish()})).nullish(),groundingSupports:u(l({segment:l({startIndex:h().nullish(),endIndex:h().nullish(),text:s().nullish()}).nullish(),segment_text:s().nullish(),groundingChunkIndices:u(h()).nullish(),supportChunkIndices:u(h()).nullish(),confidenceScores:u(h()).nullish(),confidenceScore:u(h()).nullish()})).nullish(),retrievalMetadata:f([l({webDynamicRetrievalScore:h()}),l({})]).nullish()}),dt=l({jsonPath:s(),stringValue:s().nullish(),numberValue:h().nullish(),boolValue:m().nullish(),nullValue:a().nullish(),willContinue:m().nullish()}),ft=()=>l({parts:u(f([l({functionCall:l({id:s().nullish(),name:s().nullish(),args:a().nullish(),partialArgs:u(dt).nullish(),willContinue:m().nullish()}),thoughtSignature:s().nullish()}),l({inlineData:l({mimeType:s(),data:s()}),thought:m().nullish(),thoughtSignature:s().nullish()}),l({toolCall:l({toolType:s(),args:a().nullish(),id:s()}),thoughtSignature:s().nullish()}),l({toolResponse:l({toolType:s(),response:a().nullish(),id:s()}),thoughtSignature:s().nullish()}),l({executableCode:l({language:s(),code:s()}).nullish(),codeExecutionResult:l({outcome:s(),output:s().nullish()}).nullish(),text:s().nullish(),thought:m().nullish(),thoughtSignature:s().nullish()})])).nullish()}),pt=()=>l({category:s().nullish(),probability:s().nullish(),probabilityScore:h().nullish(),severity:s().nullish(),severityScore:h().nullish(),blocked:m().nullish()}),mt=u(l({modality:s(),tokenCount:h()}).loose()).nullish(),ht=l({cachedContentTokenCount:h().nullish(),thoughtsTokenCount:h().nullish(),promptTokenCount:h().nullish(),candidatesTokenCount:h().nullish(),toolUsePromptTokenCount:h().nullish(),totalTokenCount:h().nullish(),trafficType:s().nullish(),serviceTier:s().nullish(),promptTokensDetails:mt,cacheTokensDetails:mt,candidatesTokensDetails:mt,toolUsePromptTokensDetails:mt}).loose(),gt=()=>l({urlMetadata:u(l({retrievedUrl:s(),urlRetrievalStatus:s()})).nullish()}),_t=N(()=>U(l({responseId:s().nullish(),candidates:u(l({content:ft().nullish().or(l({}).strict()),finishReason:s().nullish(),finishMessage:s().nullish(),safetyRatings:u(pt()).nullish(),groundingMetadata:ut().nullish(),urlContextMetadata:gt().nullish()})).nullish(),usageMetadata:ht.nullish(),promptFeedback:l({blockReason:s().nullish(),safetyRatings:u(pt()).nullish()}).nullish()}))),vt=N(()=>U(l({responseId:s().nullish(),candidates:u(l({content:ft().nullish(),finishReason:s().nullish(),finishMessage:s().nullish(),safetyRatings:u(pt()).nullish(),groundingMetadata:ut().nullish(),urlContextMetadata:gt().nullish()})).nullish(),usageMetadata:ht.nullish(),promptFeedback:l({blockReason:s().nullish(),safetyRatings:u(pt()).nullish()}).nullish()})));function yt(e){return e!=null&&e!==``&&e!==`BLOCK_REASON_UNSPECIFIED`&&e!==`BLOCKED_REASON_UNSPECIFIED`}var bt=c({searchTypes:l({webSearch:l({}).optional(),imageSearch:l({}).optional()}).optional(),timeRangeFilter:l({startTime:s(),endTime:s()}).optional()}),xt=A({id:`google.google_search`,inputSchema:N(()=>U(l({}))),outputSchema:N(()=>U(l({})))}),St=N(()=>U(l({googleSearch:bt.optional()}))),Ct=2147483648,wt=2e7,Tt=new Set([`text`,`reasoning`,`source`,`tool-call`,`tool-result`]);function Et(e){for(let t of e){let e=t.type;if(e!==`text`&&e!==`image`)throw new i({functionality:`batch request type: ${e}`,message:`The Google Batch API does not support batch requests with type "${e}".`})}}var Dt=l({code:f([h(),s()]).nullish(),message:s().nullish(),status:s().nullish()}),Ot=l({requestCount:f([s(),h()]).nullish(),successfulRequestCount:f([s(),h()]).nullish(),failedRequestCount:f([s(),h()]).nullish(),pendingRequestCount:f([s(),h()]).nullish()}),kt=l({responsesFile:s().nullish(),inlinedResponses:l({inlinedResponses:u(l({metadata:l({key:s()}),response:a().nullish(),error:Dt.nullish()}))}).nullish()}),At=()=>l({name:s(),metadata:l({state:s().nullish(),createTime:s().nullish(),batchStats:Ot.nullish(),output:kt.nullish()}).nullish(),done:m().nullish(),error:Dt.nullish(),response:kt.nullish()}),jt=N(()=>U(At())),Mt=N(()=>U(l({operations:u(At()).nullish(),nextPageToken:s().nullish()}))),Nt=N(()=>U(l({}))),Pt=N(()=>U(l({file:l({name:s(),expirationTime:s().nullish()})}))),Ft=N(()=>U(l({key:s(),response:a().nullish(),error:Dt.nullish()}))),It=N(()=>U(l({candidates:u(a()).nullish(),promptFeedback:l({blockReason:s().nullish()}).nullish()}))),Lt=class{constructor(e){this.specificationVersion=`v4`,this.provider=e.provider,this.batchConfig=e.config,this.supportedUrls=e.supportedUrls,this.batchGenerateId=e.config.generateId??T}async doStartBatch(e){Et(e.requests);let n=Ut(e.requests),r=[],i=`ai-sdk-batch-${this.batchGenerateId()}`,a=[],o={batch:{displayName:i,...e.webhookUrl!=null&&{webhookConfig:{uris:[e.webhookUrl]}},inputConfig:{requests:{requests:a}}}},s=new TextEncoder,c=s.encode(JSON.stringify(o)).byteLength,l;for(let t of e.requests){let e=t.type===`text`?await X.prepareRequest({modelId:t.modelId,config:this.batchConfig,options:t.options}):await this.prepareImageRequest(t),n={request:e.args,metadata:{key:t.id}};if(l==null){let r=s.encode(JSON.stringify(n)).byteLength,i=c+r+ +(a.length>0);if(i<wt)a.push(n),c=i;else{l=[];for(let e of a)l.push(JSON.stringify({key:e.metadata.key,request:e.request}),`
`);a.length=0,l.push(JSON.stringify({key:t.id,request:e.args}),`
`)}}else l.push(JSON.stringify({key:t.id,request:e.args}),`
`);for(let n of e.warnings)r.push({requestId:t.id,warning:n})}let u=await this.getHeaders(e.headers),d=`${this.batchConfig.baseURL}/${q(n)}:batchGenerateContent`;if(l==null){let{value:t}=await H({url:d,headers:u,body:o,failedResponseHandler:K,successfulResponseHandler:F(jt),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch});return{batchId:t.name,...Z(t),warnings:r}}let f=new Blob(l,{type:`application/jsonl`});if(l.length=0,f.size>Ct)throw new t({argument:`requests`,message:`Google batch input files must not exceed 2 GB.`});let{value:p}=await H({url:`${this.getBaseOrigin()}/upload/v1beta/files`,headers:z(u,{"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(f.size),"X-Goog-Upload-Header-Content-Type":`application/jsonl`}),body:{file:{display_name:`${i}-input`}},failedResponseHandler:K,successfulResponseHandler:Ht,abortSignal:e.abortSignal,fetch:this.batchConfig.fetch}),{value:m}=await de({url:p,headers:{"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`,"Content-Type":`application/jsonl`},body:{content:f,values:{byteLength:f.size,mediaType:`application/jsonl`}},failedResponseHandler:K,successfulResponseHandler:F(Pt),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch}),{value:h}=await H({url:d,headers:u,body:{batch:{displayName:i,...e.webhookUrl!=null&&{webhookConfig:{uris:[e.webhookUrl]}},inputConfig:{fileName:m.file.name}}},failedResponseHandler:K,successfulResponseHandler:F(jt),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch});return{batchId:h.name,...Z(h),providerMetadata:{google:{inputFileId:m.file.name,...m.file.expirationTime==null?{}:{inputFileExpiresAt:m.file.expirationTime}}},warnings:r}}async doGetBatchStatus(e){return Z(await this.retrieveBatch(e))}async doCancelBatch(e){return await H({url:`${this.batchConfig.baseURL}/${e.batchId}:cancel`,headers:await this.getHeaders(e.headers),body:{},failedResponseHandler:K,successfulResponseHandler:F(Nt),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch}),{}}async doListBatches(e){let t=new URL(`${this.batchConfig.baseURL}/batches`);e.limit!=null&&t.searchParams.set(`pageSize`,String(e.limit)),e.cursor!=null&&t.searchParams.set(`pageToken`,e.cursor);let{value:n}=await E({url:t.toString(),headers:await this.getHeaders(e.headers),failedResponseHandler:K,successfulResponseHandler:F(Mt),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return{batches:(n.operations??[]).map(e=>({batchId:e.name,...Z(e)})),...n.nextPageToken==null?{}:{nextCursor:n.nextPageToken}}}async doGetBatchResults(e){let r=await this.retrieveBatch(e),i=Z(r);if(i.status===`pending`)throw new t({argument:`batchId`,message:`Google batch "${e.batchId}" is not complete.`});let a=r.metadata?.output?.inlinedResponses?.inlinedResponses??r.response?.inlinedResponses?.inlinedResponses;if(a!=null)return ce(this.iterateBatchResults(a.map(e=>({key:e.metadata.key,response:e.response,error:e.error}))));let o=r.metadata?.output?.responsesFile??r.response?.responsesFile;if(o==null){if(i.status===`completed`)throw new n({data:r,message:`Google batch "${e.batchId}" completed without batch output.`});return new ReadableStream({start(e){e.close()}})}let s=o.split(`/`).map(e=>encodeURIComponent(e)).join(`/`),{value:c}=await E({url:`${this.getBaseOrigin()}/download/v1beta/${s}:download?alt=media`,headers:await this.getHeaders(e.headers),failedResponseHandler:K,successfulResponseHandler:ie(Ft),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return ce(this.iterateBatchResults(c))}async retrieveBatch(e){let{value:t}=await E({url:`${this.batchConfig.baseURL}/${e.batchId}`,headers:await this.getHeaders(e.headers),failedResponseHandler:K,successfulResponseHandler:F(jt),abortSignal:e.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return t}async*iterateBatchResults(e){for await(let t of e){if(t.error!=null){let e=Vt(t.error,`Google batch request failed.`),n=t.error.status===`CANCELLED`||String(t.error.code)===`1`?`cancelled`:`failed`;yield{type:`text`,id:t.key,status:n,error:e};continue}if(t.response==null){yield{type:`text`,id:t.key,status:`failed`,error:{message:`Google returned a batch result without a response or error.`,code:`invalid_batch_result`}};continue}let e=await oe({value:t.response,schema:It});if(e.success&&(e.value.candidates==null||e.value.candidates.length===0)){let n=e.value.promptFeedback??void 0,r=n?.blockReason??void 0;yield{type:`text`,id:t.key,status:`failed`,error:{message:r==null?`Google returned a batch response without any candidates.`:`Google blocked the batch request (${r}).`,code:r==null?`invalid_response`:`prompt_blocked`,...r==null?{}:{type:r}},...n==null?{}:{providerMetadata:{google:{promptFeedback:{blockReason:n.blockReason??null}}}}};continue}let n=await oe({value:t.response,schema:_t});if(!n.success){yield{type:`text`,id:t.key,status:`failed`,error:{message:`Google returned an invalid GenerateContent batch result.`,code:`invalid_response`}};continue}let r=X.convertGenerateContentResponse({config:this.batchConfig,response:n.value,warnings:[],providerOptionsNames:[`google`]}),i=Wt(r);if(i!=null){yield{type:`image`,id:t.key,status:`succeeded`,result:i};continue}let a=r.content.find(e=>!Tt.has(e.type));if(a!=null){yield{type:`text`,id:t.key,status:`failed`,error:{message:`Google returned a "${a.type}" content block, but that content is not supported in AI SDK text batches.`,code:`unsupported_content`}};continue}yield{type:`text`,id:t.key,status:`succeeded`,result:r}}}async prepareImageRequest(e){let{prompt:t,n,size:r,aspectRatio:a,seed:o,files:s,mask:c,providerOptions:l}=e.options,u=[];if(c!=null)throw new i({functionality:`mask-based image editing in Google batches`});if(n>1)throw new i({functionality:`multiple images per Google batch request`});r!=null&&u.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."});let d=[];t!=null&&d.push({type:`text`,text:t});for(let e of s??[])d.push(e.type===`url`?{type:`file`,data:{type:`url`,url:new URL(e.url)},mediaType:`image/*`}:{type:`file`,data:{type:`data`,data:e.data},mediaType:e.mediaType});let f=await g({provider:`google`,providerOptions:l,schema:St}),{responseModalities:p,imageConfig:m,...h}=await g({provider:`google`,providerOptions:l,schema:Y})??{},_=await g({provider:`google`,providerOptions:{google:{...h,responseModalities:[`IMAGE`],imageConfig:a!=null||m!=null?{...m,...a==null?{}:{aspectRatio:a}}:void 0}},schema:Y}),v=await X.prepareRequest({modelId:e.modelId,config:this.batchConfig,options:{prompt:[{role:`user`,content:d}],seed:o,providerOptions:{google:_??{responseModalities:[`IMAGE`]}},tools:f?.googleSearch==null?void 0:[{type:`provider`,id:`google.google_search`,name:`google_search`,args:f.googleSearch}]}});return{...v,warnings:[...u,...v.warnings]}}async getHeaders(e){return z(this.batchConfig.headers?await B(this.batchConfig.headers):void 0,e)}getBaseOrigin(){return this.batchConfig.baseURL.replace(/\/v1beta$/,``)}};function Z(e){let t=e.metadata?.state??void 0,n=zt(e.metadata?.batchStats),r=e.metadata?.createTime??void 0,i=e.error==null?void 0:Vt(e.error,`Google batch failed.`);return{status:Rt({rawStatus:t,done:e.done??void 0,hasError:i!=null}),...t==null?{}:{rawStatus:t},...n==null?{}:{requestCounts:n},...i==null?{}:{error:i},...r==null?{}:{createdAt:r}}}function Rt({rawStatus:e,done:t,hasError:n}){if(n)return`failed`;if(e==null)return t?`completed`:`pending`;switch(e.replace(/^(?:BATCH|JOB)_STATE_/,``)){case`SUCCEEDED`:return`completed`;case`FAILED`:case`CANCELLED`:case`EXPIRED`:return`failed`;default:return`pending`}}function zt(e){let t=Bt(e?.requestCount),n=Bt(e?.successfulRequestCount??0),r=Bt(e?.failedRequestCount??0),i=Bt(e?.pendingRequestCount??0);return P({total:t,pending:i,completed:n,failed:r})}function Bt(e){let t=typeof e==`string`&&/^\d+$/.test(e)?Number(e):e;return typeof t==`number`&&Number.isSafeInteger(t)&&t>=0?t:void 0}function Vt(e,t){return{message:e.message??t,...e.status==null?{}:{type:e.status},...e.code==null?{}:{code:String(e.code)}}}var Ht=async({response:e})=>{let t=e.headers.get(`x-goog-upload-url`);if(t==null)throw new n({data:e.headers,message:`Google did not return a resumable upload URL.`});return{value:t}};function Ut(e){let n=e[0]?.modelId;if(n==null)throw new t({argument:`requests`,message:`Google batches require at least one request.`});for(let r of e)if(r.modelId!==n)throw new t({argument:`requests`,message:`Google batches require every request to use the same model because the model is part of the batch endpoint.`});return n}function Wt(e){let t=e.content.flatMap(e=>e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`?[V(e.data.data)]:[]);if(t.length===0)return;let n=e.providerMetadata?.google??{};return{images:t,warnings:e.warnings,providerMetadata:{google:{...n,images:t.map(()=>({}))}},response:{timestamp:new Date,modelId:e.response?.modelId??``,headers:e.response?.headers},usage:{inputTokens:e.usage.inputTokens.total,outputTokens:e.usage.outputTokens.total,totalTokens:(e.usage.inputTokens.total??0)+(e.usage.outputTokens.total??0)}}}var Gt=A({id:`google.code_execution`,inputSchema:l({language:s().describe(`The programming language of the code.`),code:s().describe(`The code to be executed.`)}),outputSchema:l({outcome:s().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:s().describe(`The output from the code execution.`)})}),Kt=A({id:`google.enterprise_web_search`,inputSchema:N(()=>U(l({}))),outputSchema:N(()=>U(l({})))});c({fileSearchStoreNames:u(s()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:h().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:s().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 qt=A({id:`google.file_search`,inputSchema:N(()=>U(l({}))),outputSchema:N(()=>U(l({})))}),Jt={googleSearch:xt,enterpriseWebSearch:Kt,googleMaps:A({id:`google.google_maps`,inputSchema:N(()=>U(l({}))),outputSchema:N(()=>U(l({})))}),urlContext:A({id:`google.url_context`,inputSchema:N(()=>U(l({}))),outputSchema:N(()=>U(l({})))}),fileSearch:qt,codeExecution:Gt,vertexRagStore:A({id:`google.vertex_rag_store`,inputSchema:N(()=>U(l({}))),outputSchema:N(()=>U(l({})))})},Yt=class e{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v4`}static[G](e){return R({modelId:e.modelId,config:e.config})}static[W](t){return new e(t.modelId,{},t.config)}get maxImagesPerCall(){return this.settings.maxImagesPerCall==null?10:this.settings.maxImagesPerCall}get provider(){return this.config.provider}async doGenerate(e){var t;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:n,n:r,size:i,aspectRatio:a,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(d!=null)throw Error(`Gemini image models do not support mask-based image editing.`);if(r!=null&&r>1)throw Error(`Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."});let p=[];if(n!=null&&p.push({type:`text`,text:n}),u!=null&&u.length>0)for(let e of u)e.type===`url`?p.push({type:`file`,data:{type:`url`,url:new URL(e.url)},mediaType:`image/*`}):p.push({type:`file`,data:{type:`data`,data:typeof e.data==`string`?e.data:new Uint8Array(e.data)},mediaType:e.mediaType});let m=[{role:`user`,content:p}],h=await g({provider:`google`,providerOptions:s,schema:St}),{googleSearch:_,responseModalities:v,imageConfig:y,...b}=s?.google??{},x=await new X(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??T}).doGenerate({prompt:m,seed:o,providerOptions:{google:{...b,responseModalities:[`IMAGE`],imageConfig:a!=null||y!=null?{...y,...a==null?{}:{aspectRatio:a}}:void 0}},tools:h?.googleSearch==null?void 0:[{type:`provider`,id:`google.google_search`,name:`google_search`,args:h.googleSearch}],headers:c,abortSignal:l}),S=((t=this.config._internal)?.currentDate)?.call(t)??new Date,C=[];for(let e of x.content)e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`&&C.push(V(e.data.data));let w=x.providerMetadata?.google??{};return{images:C,...x.finishReason.unified===`content-filter`?{isRetryable:!1}:{},warnings:f,providerMetadata:{google:{...w,images:C.map(()=>({}))}},response:{timestamp:S,modelId:this.modelId,headers:x.response?.headers},usage:x.usage?{inputTokens:x.usage.inputTokens.total,outputTokens:x.usage.outputTokens.total,totalTokens:(x.usage.inputTokens.total??0)+(x.usage.outputTokens.total??0)}:void 0}}};function Xt(e){let t=encodeURIComponent(e);return t===`.`?`%252E`:t===`..`?`%252E%252E`:t}var Zt=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(t){let n=await g({provider:`google`,providerOptions:t.providerOptions,schema:en}),r=z(this.config.headers(),t.headers),i=this.config.fetch??globalThis.fetch,a=[];t.filename!=null&&a.push({type:`unsupported`,feature:`filename`});let o=ne(t.data),s=t.mediaType,c=n?.displayName,l=await i(`${this.config.baseURL.replace(/\/v1beta$/,``)}/upload/v1beta/files`,{method:`POST`,headers:{...r,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(o.length),"X-Goog-Upload-Header-Content-Type":s,"Content-Type":`application/json`},body:JSON.stringify({file:{...c==null?{}:{display_name:c}}}),signal:t.abortSignal});if(!l.ok){let t=await l.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to initiate resumable upload: ${l.status} ${t}`})}let u=l.headers.get(`x-goog-upload-url`);if(!u)throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`No upload URL returned from initiation request`});let d=await i(u,{method:`POST`,headers:{"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:Qt(o),signal:t.abortSignal});if(!d.ok){let t=await d.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to upload file data: ${d.status} ${t}`})}let f=(await d.json()).file,p=n?.pollIntervalMs??2e3,m=n?.pollTimeoutMs??3e5,h=Date.now();for(;f.state===`PROCESSING`;){if(Date.now()-h>m)throw new e({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${m}ms`});await j(p,{abortSignal:t.abortSignal});let n=/^files\/([^/]+)$/.exec(f.name),i=n==null?Xt(f.name):`files/${Xt(n[1])}`,{value:a}=await E({url:`${this.config.baseURL}/${i}`,validateUrl:!1,headers:z(r),successfulResponseHandler:F($t),failedResponseHandler:K,abortSignal:t.abortSignal,fetch:this.config.fetch});f=a}if(f.state===`FAILED`)throw new e({name:`GOOGLE_FILES_UPLOAD_FAILED`,message:`File processing failed for ${f.name}`});return{warnings:a,providerReference:{google:f.uri},mediaType:f.mimeType??t.mediaType,providerMetadata:{google:{name:f.name,displayName:f.displayName,mimeType:f.mimeType,sizeBytes:f.sizeBytes,state:f.state,uri:f.uri,...f.createTime==null?{}:{createTime:f.createTime},...f.updateTime==null?{}:{updateTime:f.updateTime},...f.expirationTime==null?{}:{expirationTime:f.expirationTime},...f.sha256Hash==null?{}:{sha256Hash:f.sha256Hash}}}}}};function Qt(e){return e.buffer instanceof ArrayBuffer?e:new Uint8Array(e)}var $t=N(()=>U(l({name:s(),displayName:s().nullish(),mimeType:s(),sizeBytes:s().nullish(),createTime:s().nullish(),updateTime:s().nullish(),expirationTime:s().nullish(),sha256Hash:s().nullish(),uri:s(),state:s()}))),en=N(()=>U(c({displayName:s().nullish(),pollIntervalMs:h().positive().nullish(),pollTimeoutMs:h().positive().nullish()}))),tn=N(()=>U(c({pollIntervalMs:h().positive().nullish(),pollTimeoutMs:h().positive().nullish(),personGeneration:p([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:s().nullish(),referenceImages:u(l({bytesBase64Encoded:s().nullish(),gcsUri:s().nullish()})).nullish()})));function nn(e){return e.frameImages?.find(e=>e.frameType===`first_frame`)?.image}function rn(e){return nn(e)??e.image}function an(e){return e.frameImages?.find(e=>e.frameType===`last_frame`)?.image}function on(e){if(!(e.frameImages!=null&&e.frameImages.length>0))return e.inputReferences!=null&&e.inputReferences.length>0?e.inputReferences:void 0}function sn(e,t){if(e.type===`url`){if(e.url.startsWith(`gs://`))return{gcsUri:e.url,mimeType:`image/png`};t.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 e.data==`string`?e.data:re(e.data),mimeType:e.mediaType||`image/png`}}function cn(e){return e.bytesBase64Encoded?{image:{bytesBase64Encoded:e.bytesBase64Encoded,mimeType:`image/png`},referenceType:`asset`}:e.gcsUri?{image:{gcsUri:e.gcsUri,mimeType:`image/png`},referenceType:`asset`}:e}function ln(e,t){let n=sn(e,t);return n==null?void 0:{image:n,referenceType:`asset`}}var un=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async buildRequest(e){let t=[],n=await g({provider:`google`,providerOptions:e.providerOptions,schema:tn}),r=[{}],i=r[0];e.prompt!=null&&(i.prompt=e.prompt);let a=rn(e);if(a!=null){let e=sn(a,t);e!=null&&(i.image=e)}let o=an(e);if(o!=null){let e=sn(o,t);e!=null&&(i.lastFrame=e)}let s=on(e);s==null?n?.referenceImages!=null&&(i.referenceImages=n.referenceImages.map(e=>cn(e))):i.referenceImages=s.flatMap(e=>{let n=ln(e,t);return n==null?[]:[n]});let c={sampleCount:e.n};if(e.aspectRatio&&(c.aspectRatio=e.aspectRatio),e.resolution&&(c.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[e.resolution]||e.resolution),e.duration&&(c.durationSeconds=e.duration),e.seed&&(c.seed=e.seed),n!=null){let e=n;e.personGeneration!==void 0&&e.personGeneration!==null&&(c.personGeneration=e.personGeneration),e.negativePrompt!==void 0&&e.negativePrompt!==null&&(c.negativePrompt=e.negativePrompt);for(let[t,n]of Object.entries(e))[`pollIntervalMs`,`pollTimeoutMs`,`personGeneration`,`negativePrompt`,`referenceImages`].includes(t)||(c[t]=n)}return{instances:r,parameters:c,warnings:t,googleOptions:n}}async buildCompletedResult(t,n,r,i){let a=t.response;if(!a?.generateVideoResponse?.generatedSamples||a.generateVideoResponse.generatedSamples.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No videos in response. Response: ${JSON.stringify(t)}`});let o=[],s=[],c=(await B(this.config.headers))?.[`x-goog-api-key`];for(let e of a.generateVideoResponse.generatedSamples)if(e.video?.uri){let t=c&&x(e.video.uri,this.config.baseURL)?`${e.video.uri}${e.video.uri.includes(`?`)?`&`:`?`}key=${c}`:e.video.uri;o.push({type:`url`,url:t,mediaType:`video/mp4`}),s.push({uri:e.video.uri})}if(o.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No valid videos in response`});return{status:`completed`,videos:o,warnings:r,response:{timestamp:i,modelId:this.modelId,headers:n},providerMetadata:{google:{videos:s}}}}async doStart(t){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,{instances:i,parameters:a,warnings:o}=await this.buildRequest(t),{value:s,responseHeaders:c}=await H({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:z(await B(this.config.headers),t.headers),body:{instances:i,parameters:a},successfulResponseHandler:F(dn),failedResponseHandler:K,abortSignal:t.abortSignal,fetch:this.config.fetch}),l=s.name;if(!l)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No operation name returned from API`});return{operation:{operationName:l},warnings:o,response:{timestamp:r,modelId:this.modelId,headers:c}}}async doStatus(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{operationName:r}=e.operation,{value:i,responseHeaders:a}=await E({url:`${this.config.baseURL}/${r}`,validateUrl:!1,headers:z(await B(this.config.headers),e.headers),successfulResponseHandler:F(dn),failedResponseHandler:K,abortSignal:e.abortSignal,fetch:this.config.fetch});return i.done?i.error?{status:`error`,error:`Video generation failed: ${i.error.message}`,response:{timestamp:n,modelId:this.modelId,headers:a}}:this.buildCompletedResult(i,a,[],n):{status:`pending`,response:{timestamp:n,modelId:this.modelId,headers:a}}}},dn=l({name:s().nullish(),done:m().nullish(),error:l({code:h().nullish(),message:s(),status:s().nullish()}).nullish(),response:l({generateVideoResponse:l({generatedSamples:u(l({video:l({uri:s().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}),fn=N(()=>U(l({candidates:u(l({content:l({parts:u(l({inlineData:l({mimeType:s().nullish(),data:s().nullish()}).nullish()})).nullish()}).nullish()})).nullish()}))),pn=l({voiceName:s()}),mn=l({prebuiltVoiceConfig:pn}),hn=N(()=>U(l({multiSpeakerVoiceConfig:l({speakerVoiceConfigs:u(l({speaker:s(),voiceConfig:mn}))}).optional()}))),gn=`Kore`,_n=24e3,vn=class e{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}static[G](e){return R({modelId:e.modelId,config:e.config})}static[W](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async getArgs({text:e,voice:t=gn,outputFormat:n,instructions:r,speed:i,language:a,providerOptions:o}){let s=[],c=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],l;for(let e of c)if(l=await g({provider:e,providerOptions:o,schema:hn}),l!=null)break;l==null&&!c.includes(`google`)&&(l=await g({provider:`google`,providerOptions:o,schema:hn}));let u=l?.multiSpeakerVoiceConfig,d=u?{multiSpeakerVoiceConfig:u}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:t}}},f=e;r!=null&&(u?s.push({type:`unsupported`,feature:`instructions`,details:"Google Gemini TTS ignores `instructions` when `multiSpeakerVoiceConfig` is set, because prepending them would break multi-speaker transcript parsing."}):f=`${r}: ${e}`),i!=null&&s.push({type:`unsupported`,feature:`speed`,details:"Google Gemini TTS models do not support the `speed` option. It was ignored."}),a!=null&&s.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 p=`wav`;return n===`pcm`?p=`pcm`:n!=null&&n!==`wav`&&s.push({type:`unsupported`,feature:`outputFormat`,details:`Unsupported output format: ${n}. Using wav instead.`}),{requestBody:{contents:[{role:`user`,parts:[{text:f}]}],generationConfig:{responseModalities:[`AUDIO`],speechConfig:d}},warnings:s,outputFormat:p}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i,outputFormat:a}=await this.getArgs(e),{value:o,responseHeaders:s,rawValue:c}=await H({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:z(this.config.headers?await B(this.config.headers):void 0,e.headers),body:r,failedResponseHandler:K,successfulResponseHandler:F(fn),abortSignal:e.abortSignal,fetch:this.config.fetch}),l,u;for(let e of o.candidates??[]){for(let t of e.content?.parts??[])if(t.inlineData?.data){l=t.inlineData.data,u=t.inlineData.mimeType??void 0;break}if(l!=null)break}let d=yn(u)??_n,f=l==null?new Uint8Array:fe(l),p=a===`pcm`||f.length===0?f:bn(f,d);return a===`pcm`&&f.length>0&&i.push({type:`unsupported`,feature:`outputFormat`,details:`Returning raw PCM audio (signed 16-bit little-endian, mono, ${d} Hz). These bytes have no container header and are not directly playable; see providerMetadata.google for the sample rate and mime type.`}),{audio:p,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:s,body:c},providerMetadata:{google:{sampleRate:d,mimeType:u??null}}}}};function yn(e){if(e==null)return;let t=/rate=(\d+)/.exec(e);return t?Number.parseInt(t[1],10):void 0}function bn(e,t){let n=t*2,r=e.length,i=new ArrayBuffer(44+r),a=new DataView(i);xn(a,0,`RIFF`),a.setUint32(4,36+r,!0),xn(a,8,`WAVE`),xn(a,12,`fmt `),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,1,!0),a.setUint32(24,t,!0),a.setUint32(28,n,!0),a.setUint16(32,2,!0),a.setUint16(34,16,!0),xn(a,36,`data`),a.setUint32(40,r,!0);let o=new Uint8Array(i);return o.set(e,44),o}function xn(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function Sn(e){if(e==null)return ge();let t=e.total_input_tokens??0,n=e.total_output_tokens??0,r=e.total_thought_tokens??0,i=e.total_cached_tokens??0;return{inputTokens:{total:e.total_input_tokens??void 0,noCache:e.total_input_tokens==null?void 0:t-i,cacheRead:e.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:e.total_output_tokens==null&&e.total_thought_tokens==null?void 0:n+r,text:e.total_output_tokens??void 0,reasoning:e.total_thought_tokens??void 0},raw:e}}function Cn(e){let t=e?.output_tokens_by_modality;if(t==null)return;let n={};for(let e of t)e?.modality!=null&&e.tokens!=null&&(n[e.modality]=e.tokens);return Object.keys(n).length>0?n:void 0}var wn={pdf:`application/pdf`,txt:`text/plain`,md:`text/markdown`,markdown:`text/markdown`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};function Tn(e){let t=e.toLowerCase();for(let[e,n]of Object.entries(wn))if(t.endsWith(`.${e}`))return n;return`application/octet-stream`}function En(e){let t=e.split(`/`),n=t[t.length-1];return n&&n.length>0?n:void 0}function Dn({annotation:e,generateId:t}){switch(e.type){case`url_citation`:{let n=e;return n.url==null||n.url.length===0?void 0:{type:`source`,sourceType:`url`,id:t(),url:n.url,...n.title==null?{}:{title:n.title}}}case`file_citation`:{let n=e,r=n.url??n.document_uri??n.file_name;if(r==null||r.length===0)return;if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`source`,sourceType:`url`,id:t(),url:r,...n.file_name==null?{}:{title:n.file_name}};let i=n.file_name??En(r),a=Tn(r);return{type:`source`,sourceType:`document`,id:t(),mediaType:a,title:n.file_name??i??r,...i==null?{}:{filename:i}}}case`place_citation`:{let n=e;return n.url==null||n.url.length===0?void 0:{type:`source`,sourceType:`url`,id:t(),url:n.url,...n.name==null?{}:{title:n.name}}}default:return}}function On({block:e,generateId:t}){let n=[];switch(e.type){case`url_context_result`:{let r=e.result??[];for(let e of r)e?.url!=null&&e.url.length!==0&&(e.status==null||e.status===`success`)&&n.push({type:`source`,sourceType:`url`,id:t(),url:e.url});break}case`google_search_result`:{let r=e.result??[];for(let e of r){let r=e?.url;r!=null&&r.length!==0&&n.push({type:`source`,sourceType:`url`,id:t(),url:r,...e.title==null?{}:{title:e.title}})}break}case`google_maps_result`:{let r=e.result??[];for(let e of r)for(let r of e.places??[])r.url!=null&&r.url.length!==0&&n.push({type:`source`,sourceType:`url`,id:t(),url:r.url,...r.name==null?{}:{title:r.name}});break}case`file_search_result`:{let r=e.result??[];for(let e of r){if(typeof e!=`object`||!e)continue;let r=e,i=r.url??r.document_uri??r.file_name;if(i==null||i.length===0)continue;if(i.startsWith(`http://`)||i.startsWith(`https://`)){n.push({type:`source`,sourceType:`url`,id:t(),url:i,...r.title==null?{}:{title:r.title}});continue}let a=r.file_name??En(i),o=Tn(i);n.push({type:`source`,sourceType:`document`,id:t(),mediaType:o,title:r.title??r.file_name??a??i,...a==null?{}:{filename:a}})}break}}return n}function kn({annotations:e,generateId:t}){if(e==null)return[];let n=new Set,r=[];for(let i of e){let e=Dn({annotation:i,generateId:t});if(e==null)continue;let a=e.sourceType===`url`?`url:${e.url}`:`doc:${e.filename??e.title}`;n.has(a)||(n.add(a),r.push(e))}return r}function An({status:e,hasFunctionCall:t}){switch(e){case`completed`:return t?`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 jn=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),Mn=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function Nn(e){return e.replace(/_call$/,``)}function Pn(e){return e.replace(/_result$/,``)}function Fn({warnings:e,generateId:t,includeRawChunks:n,serviceTier:r}){let i,a,o=r,s,c=!1,l=new Map,u=new Set;function d(e){return e.sourceType===`url`?`url:${e.url}`:`doc:${e.filename??e.title}`}return new TransformStream({start(t){t.enqueue({type:`stream-start`,warnings:e})},transform(e,r){if(n&&r.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){s=`failed`,r.enqueue({type:`error`,error:e.error});return}let f=e.value,p=f.event_type;switch(p){case`interaction.created`:{let e=f.interaction;i=e?.id!=null&&e.id.length>0?e.id:void 0;let t=e?.created,n;if(typeof t==`string`){let e=new Date(t);Number.isNaN(e.getTime())||(n=e)}r.enqueue({type:`response-metadata`,...i==null?{}:{id:i},modelId:e?.model,...n?{timestamp:n}:{}});break}case`step.start`:{let e=f,n=e.step,a=e.index,o=`${i??`interaction`}:${a}`,s=n?.type;if(s===`model_output`){let e=n?.content?.[0];if(e?.type===`text`){l.set(a,{kind:`text`,id:o,emittedSourceKeys:new Set}),r.enqueue({type:`text-start`,id:o});let n=kn({annotations:e.annotations,generateId:t});for(let e of n){let t=d(e);u.has(t)||(u.add(t),r.enqueue(e))}}else e?.type===`image`?l.set(a,{kind:`image`,id:o,...e.data==null?{}:{data:e.data},...e.mime_type==null?{}:{mimeType:e.mime_type},...e.uri==null?{}:{uri:e.uri}}):l.set(a,{kind:`pending_model_output`,id:o})}else if(s===`thought`){let e=n?.signature;if(l.set(a,{kind:`reasoning`,id:o,...e==null?{}:{signature:e}}),r.enqueue({type:`reasoning-start`,id:o}),Array.isArray(n?.summary))for(let e of n.summary)e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:o,delta:e.text})}else if(s===`processing_call`||s===`processing_result`){let e={};n?.signature!=null&&(e.signature=n.signature),i!=null&&(e.interactionId=i),s===`processing_call`?e.processingId=n?.id||o:e.processingCallId=n?.call_id||o,l.set(a,{kind:`custom`,id:o,customKind:`google.${s}`,google:e})}else if(s===`function_call`){let e=n?.id||o,t=n?.name??`unknown`;c=!0;let i={kind:`function_call`,id:o,toolCallId:e,toolName:t,argumentsAccum:``,...n?.signature==null?{}:{signature:n.signature}};l.set(a,i),r.enqueue({type:`tool-input-start`,id:e,toolName:t})}else if(s!=null&&jn.has(s)){let e=s===`mcp_server_tool_call`?n?.name??`mcp_server_tool`:Nn(s),t={kind:`builtin_tool_call`,id:o,blockType:s,toolCallId:n?.id||o,toolName:e,arguments:n?.arguments??{},callEmitted:!1};l.set(a,t)}else if(s!=null&&Mn.has(s)){let e=s===`mcp_server_tool_result`?n?.name??`mcp_server_tool`:Pn(s),t={kind:`builtin_tool_result`,id:o,blockType:s,callId:n?.call_id||o,toolName:e,result:n?.result??null,...n?.is_error==null?{}:{isError:n.is_error},resultEmitted:!1};l.set(a,t)}else l.set(a,{kind:`unknown`,id:o});break}case`step.delta`:{let e=f,n=l.get(e.index);if(n==null)break;let a=e.delta?.type;if(n.kind===`pending_model_output`&&(a===`text`||a===`text_annotation`||a===`text_annotation_delta`)){let t={kind:`text`,id:n.id,emittedSourceKeys:new Set};l.set(e.index,t),n=t,r.enqueue({type:`text-start`,id:t.id})}if(a===`image`&&(n.kind===`pending_model_output`||n.kind===`text`||n.kind===`image`)){let t=e.delta,a={};i!=null&&(a.interactionId=i);let o=Object.keys(a).length>0?{google:a}:void 0;t?.data!=null&&t.data.length>0?r.enqueue({type:`file`,mediaType:t.mime_type??`image/png`,data:{type:`data`,data:t.data},...o?{providerMetadata:o}:{}}):t?.uri!=null&&t.uri.length>0&&r.enqueue({type:`file`,mediaType:t.mime_type??`image/png`,data:{type:`url`,url:new URL(t.uri)},...o?{providerMetadata:o}:{}}),n.kind===`image`&&(n.data=void 0,n.uri=void 0);break}if(a===`video`&&(n.kind===`pending_model_output`||n.kind===`text`)){let t=e.delta,n={};i!=null&&(n.interactionId=i);let a=Object.keys(n).length>0?{google:n}:void 0;t?.data!=null&&t.data.length>0?r.enqueue({type:`file`,mediaType:t.mime_type??`video/mp4`,data:{type:`data`,data:t.data},...a?{providerMetadata:a}:{}}):t?.uri!=null&&t.uri.length>0&&r.enqueue({type:`file`,mediaType:t.mime_type??`video/mp4`,data:{type:`url`,url:new URL(t.uri)},...a?{providerMetadata:a}:{}});break}let o=e.delta;if(n.kind===`custom`&&(o?.type===`processing_call`||o?.type===`processing_result`))o.signature!=null&&(n.google.signature=o.signature),o.type===`processing_call`&&o.id!=null&&o.id.length>0&&(n.google.processingId=o.id),o.type===`processing_result`&&o.call_id!=null&&o.call_id.length>0&&(n.google.processingCallId=o.call_id);else if(n.kind===`text`&&o?.type===`text`){let e=o.text??``;e.length>0&&r.enqueue({type:`text-delta`,id:n.id,delta:e})}else if(n.kind===`text`&&(o?.type===`text_annotation`||o?.type===`text_annotation_delta`)){let e=kn({annotations:o.annotations,generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),n.emittedSourceKeys.add(e),r.enqueue(t))}}else if(n.kind===`image`&&o?.type===`image`)o.data!=null&&(n.data=o.data),o.mime_type!=null&&(n.mimeType=o.mime_type),o.uri!=null&&(n.uri=o.uri);else if(n.kind===`reasoning`){if(o?.type===`thought_summary`){let e=o.content;e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:n.id,delta:e.text})}else if(o?.type===`thought_signature`){let e=o.signature;e!=null&&(n.signature=e)}}else if(n.kind===`function_call`&&o?.type===`arguments_delta`){let e=typeof o.arguments==`string`?o.arguments:``;e.length>0&&(n.argumentsAccum+=e,r.enqueue({type:`tool-input-delta`,id:n.toolCallId,delta:e})),o.id!=null&&o.id.length>0&&(n.toolCallId=o.id),o.signature!=null&&(n.signature=o.signature),c=!0}else n.kind===`builtin_tool_call`&&o?.type===n.blockType?(o.id!=null&&o.id.length>0&&(n.toolCallId=o.id),o.arguments!=null&&typeof o.arguments==`object`&&(n.arguments=o.arguments),o.name!=null&&n.blockType===`mcp_server_tool_call`&&(n.toolName=o.name)):n.kind===`builtin_tool_result`&&o?.type===n.blockType&&(o.call_id!=null&&o.call_id.length>0&&(n.callId=o.call_id),o.result!==void 0&&(n.result=o.result),o.is_error!=null&&(n.isError=o.is_error),o.name!=null&&n.blockType===`mcp_server_tool_result`&&(n.toolName=o.name));break}case`step.stop`:{let e=f,n=l.get(e.index);if(n==null)break;if(n.kind===`text`){let e=i==null?void 0:{google:{interactionId:i}};r.enqueue({type:`text-end`,id:n.id,...e?{providerMetadata:e}:{}})}else if(n.kind===`reasoning`){let e={};n.signature!=null&&(e.signature=n.signature),i!=null&&(e.interactionId=i);let t=Object.keys(e).length>0?{google:e}:void 0;r.enqueue({type:`reasoning-end`,id:n.id,...t?{providerMetadata:t}:{}})}else if(n.kind===`image`){let e={};i!=null&&(e.interactionId=i);let t=Object.keys(e).length>0?{google:e}:void 0;n.data!=null&&n.data.length>0?r.enqueue({type:`file`,mediaType:n.mimeType??`image/png`,data:{type:`data`,data:n.data},...t?{providerMetadata:t}:{}}):n.uri!=null&&n.uri.length>0&&r.enqueue({type:`file`,mediaType:n.mimeType??`image/png`,data:{type:`url`,url:new URL(n.uri)},...t?{providerMetadata:t}:{}})}else if(n.kind===`function_call`){let e=n.argumentsAccum.length>0?n.argumentsAccum:`{}`;r.enqueue({type:`tool-input-end`,id:n.toolCallId});let t={};n.signature!=null&&(t.signature=n.signature),i!=null&&(t.interactionId=i);let a=Object.keys(t).length>0?{google:t}:void 0;r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:n.toolName,input:e,...a?{providerMetadata:a}:{}})}else if(n.kind===`custom`)r.enqueue({type:`custom`,kind:n.customKind,providerMetadata:{google:n.google}});else if(n.kind===`builtin_tool_call`&&!n.callEmitted)r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:n.toolName,input:JSON.stringify(n.arguments??{}),providerExecuted:!0}),n.callEmitted=!0;else if(n.kind===`builtin_tool_result`&&!n.resultEmitted){r.enqueue({type:`tool-result`,toolCallId:n.callId,toolName:n.toolName,result:n.result??null}),n.resultEmitted=!0;let e=On({block:{type:n.blockType,call_id:n.callId,result:n.result},generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),r.enqueue(t))}}l.delete(e.index);break}case`interaction.status_update`:case`interaction.in_progress`:case`interaction.requires_action`:{let e=f;s=e.status==null?p===`interaction.requires_action`?`requires_action`:`in_progress`:e.status;break}case`interaction.completed`:{let e=f.interaction;e?.id!=null&&e.id.length>0&&(i=e.id),e?.status!=null&&(s=e.status),e?.usage!=null&&(a=e.usage),e?.service_tier!=null&&(o=e.service_tier);break}case`error`:{let e=f;s=`failed`,r.enqueue({type:`error`,error:_({message:e.error?.message??`Unknown interaction error`,type:e.event_type,code:e.error?.code??void 0,data:e})});break}}},flush(e){let t={unified:An({status:s,hasFunctionCall:c}),raw:s},n=Cn(a),r={google:{...i==null?{}:{interactionId:i},...o==null?{}:{serviceTier:o},...n==null?{}:{outputTokensByModality:n}}};e.enqueue({type:`finish`,finishReason:t,usage:Sn(a),providerMetadata:r})}})}function In({prompt:e,previousInteractionId:t,store:n,mediaResolution:r}){let i=[],a=t!=null&&n===!1,o=t!=null&&n!==!1;a&&i.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 s=o?zn({prompt:e,previousInteractionId:t}):e,c=[],l=[];for(let e of s)switch(e.role){case`system`:c.push(e.content);break;case`user`:{let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`file`){let e=Ln({part:n,warnings:i,mediaResolution:r});e!=null&&t.push(e)}let n=Un(t);n.length>0&&l.push({type:`user_input`,content:n});break}case`assistant`:{let t=[],n=()=>{t.length>0&&(l.push({type:`model_output`,content:t}),t=[])};for(let a of e.content)if(a.type===`text`)t.push({type:`text`,text:a.text});else if(a.type===`reasoning`){n();let e=a.providerOptions?.google?.signature;l.push({type:`thought`,...e==null?{}:{signature:e},summary:a.text.length>0?[{type:`text`,text:a.text}]:void 0})}else if(a.type===`file`){let e=Ln({part:a,warnings:i,mediaResolution:r});e!=null&&t.push(e)}else if(a.type===`custom`){n();let e=a.providerOptions?.google,t=typeof e?.signature==`string`?e.signature:void 0;a.kind===`google.processing_call`&&typeof e?.processingId==`string`?l.push({type:`processing_call`,id:e.processingId,...t==null?{}:{signature:t}}):a.kind===`google.processing_result`&&typeof e?.processingCallId==`string`?l.push({type:`processing_result`,call_id:e.processingCallId,...t==null?{}:{signature:t}}):i.push({type:`other`,message:`google.interactions: unsupported or invalid custom assistant content part "${a.kind}"; part dropped.`})}else if(a.type===`tool-call`){n();let e=a.providerOptions?.google?.signature,t=typeof a.input==`string`?Bn(a.input):a.input??{};l.push({type:`function_call`,id:a.toolCallId,name:a.toolName,arguments:t,...e==null?{}:{signature:e}})}else i.push({type:`other`,message:`google.interactions: unsupported assistant content part type "${a.type}"; part dropped.`});n();break}case`tool`:{let t=[];for(let n of e.content){if(n.type!==`tool-result`){i.push({type:`other`,message:`google.interactions: unsupported tool message part type "${n.type}"; part dropped.`});continue}let e=Vn({toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,signature:n.providerOptions?.google?.signature,warnings:i});t.push(e)}t.length>0&&l.push({type:`user_input`,content:t});break}}return{input:l,systemInstruction:c.length>0?c.join(`

`):void 0,warnings:i}}function Ln({part:e,warnings:t,mediaResolution:n}){if(e.data.type===`text`)return{type:`text`,text:e.data.text};let r=y(e.mediaType),i;switch(r){case`image`:i=`image`;break;case`audio`:i=`audio`;break;case`video`:i=`video`;break;case`application`:case`text`:i=`document`;break;default:i=void 0}if(i==null){t.push({type:`other`,message:`google.interactions: unsupported file media type "${e.mediaType}"; part dropped.`});return}let a=n!=null&&(i===`image`||i===`video`)?{resolution:n}:{},o=i===`video`?Rn({part:e,warnings:t}):{};switch(e.data.type){case`data`:{let t=I({part:e});return{type:i,data:V(e.data.data),mime_type:t,...a,...o}}case`url`:return{type:i,uri:e.data.url.toString(),...k(e.mediaType)?{mime_type:e.mediaType}:{},...a,...o};case`reference`:{let t=le({reference:e.data.reference,provider:`google`});return{type:i,uri:t,...k(e.mediaType)?{mime_type:e.mediaType}:{},...a,...o}}}}function Rn({part:e,warnings:t}){let n=e.providerOptions?.google?.processing;if(n==null)return{};if(n===`agentic`||n===`static`)return{processing:n};if(typeof n==`object`&&!Array.isArray(n)&&n.type===`static`){let e=n;return{processing:{type:`static`,...typeof e.startOffset==`number`?{start_offset:e.startOffset}:{},...typeof e.endOffset==`number`?{end_offset:e.endOffset}:{},...typeof e.fps==`number`?{fps:e.fps}:{}}}}return t.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 zn({prompt:e,previousInteractionId:t}){let n=[],r=new Set;for(let i of e){if(i.role===`assistant`){if(i.content.some(e=>e.providerOptions?.google?.interactionId===t)){for(let e of i.content)e.type===`tool-call`&&r.add(e.toolCallId);continue}n.push(i);continue}if(i.role===`tool`){let e=i.content.filter(e=>e.type!==`tool-result`||!r.has(e.toolCallId));if(e.length===0)continue;n.push({...i,content:e});continue}n.push(i)}return n}function Bn(e){try{let t=pe(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{value:t}}catch{return{value:e}}}function Vn({toolCallId:e,toolName:t,output:n,signature:r,warnings:i}){let a={type:`function_result`,call_id:e,name:t,...r==null?{}:{signature:r}};switch(n.type){case`text`:return{...a,result:n.value};case`json`:return{...a,result:JSON.stringify(n.value)};case`error-text`:return{...a,is_error:!0,result:n.value};case`error-json`:return{...a,is_error:!0,result:JSON.stringify(n.value)};case`execution-denied`:return{...a,is_error:!0,result:n.reason??`Tool execution denied by user.`};case`content`:{let e=[];for(let t of n.value)if(t.type===`text`)e.push({type:`text`,text:t.text});else if(t.type===`file`){if(y(t.mediaType)!==`image`){i.push({type:`other`,message:`google.interactions: tool-result file with mediaType "${t.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let n=Hn({part:t,warnings:i});n!=null&&e.push(n)}else i.push({type:`other`,message:`google.interactions: tool-result content part type "${t.type}" is not supported; part dropped.`});return{...a,result:e}}}}function Hn({part:e,warnings:t}){switch(e.data.type){case`data`:{let t=k(e.mediaType)?e.mediaType:I({part:{type:`file`,mediaType:e.mediaType,data:e.data}});return{type:`image`,data:V(e.data.data),mime_type:t}}case`url`:return{type:`image`,uri:e.data.url.toString(),...k(e.mediaType)?{mime_type:e.mediaType}:{}};case`reference`:return{type:`image`,uri:le({reference:e.data.reference,provider:`google`}),...k(e.mediaType)?{mime_type:e.mediaType}:{}};case`text`:t.push({type:`other`,message:'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'});return}}function Un(e){if(e.length<2)return e;let t=[];for(let n of e){let e=t[t.length-1];if(n.type===`text`&&e!=null&&e.type===`text`&&e.annotations==null&&n.annotations==null){let r={type:`text`,text:`${e.text}

${n.text}`};t[t.length-1]=r;continue}t.push(n)}return t}var Wn=()=>l({modality:s().nullish(),tokens:h().nullish()}).loose(),Gn=()=>l({total_input_tokens:h().nullish(),total_output_tokens:h().nullish(),total_thought_tokens:h().nullish(),total_cached_tokens:h().nullish(),total_tool_use_tokens:h().nullish(),total_tokens:h().nullish(),input_tokens_by_modality:u(Wn()).nullish(),output_tokens_by_modality:u(Wn()).nullish(),cached_tokens_by_modality:u(Wn()).nullish(),tool_use_tokens_by_modality:u(Wn()).nullish(),grounding_tool_count:u(l({type:s().nullish(),count:h().nullish()}).loose()).nullish()}).loose(),Kn=()=>p([`in_progress`,`requires_action`,`completed`,`failed`,`cancelled`,`incomplete`]),qn=()=>{let e=l({type:d(`url_citation`),url:s().nullish(),title:s().nullish(),start_index:h().nullish(),end_index:h().nullish()}).loose(),t=l({type:d(`file_citation`),file_name:s().nullish(),document_uri:s().nullish(),url:s().nullish(),page_number:h().nullish(),media_id:s().nullish(),start_index:h().nullish(),end_index:h().nullish(),custom_metadata:o(s(),a()).nullish()}).loose(),n=l({type:d(`place_citation`),name:s().nullish(),url:s().nullish(),place_id:s().nullish(),start_index:h().nullish(),end_index:h().nullish()}).loose();return f([e,t,n,l({type:s()}).loose()])},Jn=()=>l({type:s(),text:s().nullish(),data:s().nullish(),mime_type:s().nullish()}).loose(),Yn=()=>{let e=l({type:d(`text`),text:s(),annotations:u(qn()).nullish()}).loose(),t=l({type:d(`image`),data:s().nullish(),mime_type:s().nullish(),resolution:p([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:s().nullish()}).loose(),n=l({type:d(`video`),data:s().nullish(),mime_type:s().nullish(),uri:s().nullish()}).loose();return f([e,t,n,l({type:s()}).loose()])},Xn=[`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`],Zn=[`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`],Qn=()=>{let e=l({type:d(`user_input`),content:u(Yn()).nullish()}).loose(),t=l({type:d(`model_output`),content:u(Yn()).nullish()}).loose(),n=l({type:d(`function_call`),id:s(),name:s(),arguments:o(s(),a()).nullish(),signature:s().nullish()}).loose(),r=l({type:d(`thought`),signature:s().nullish(),summary:u(Jn()).nullish()}).loose(),i=l({type:d(`processing_call`),id:s(),signature:s().nullish()}).loose(),c=l({type:d(`processing_result`),call_id:s(),signature:s().nullish()}).loose(),h=l({type:p(Xn),id:s(),arguments:o(s(),a()).nullish(),name:s().nullish(),server_name:s().nullish(),search_type:s().nullish(),signature:s().nullish()}).loose(),g=l({type:p(Zn),call_id:s(),result:a().nullish(),is_error:m().nullish(),name:s().nullish(),server_name:s().nullish(),signature:s().nullish()}).loose();return f([e,t,n,r,i,c,h,g,l({type:s()}).loose()])},$n=N(()=>U(l({id:s().nullish(),created:s().nullish(),updated:s().nullish(),status:Kn(),model:s().nullish(),agent:s().nullish(),steps:u(Qn()).nullish(),usage:Gn().nullish(),service_tier:s().nullish(),previous_interaction_id:s().nullish(),response_modalities:u(s()).nullish()}).loose())),er=N(()=>U((()=>{let e=Kn(),t=qn(),n=Jn(),r=l({event_type:d(`interaction.created`),event_id:s().nullish(),interaction:l({id:s().nullish(),created:s().nullish(),model:s().nullish(),agent:s().nullish(),status:e.nullish()}).loose()}).loose(),i=l({event_type:d(`step.start`),event_id:s().nullish(),index:h(),step:Qn()}).loose(),c=l({type:d(`text`),text:s()}).loose(),g=l({type:d(`thought_summary`),content:n.nullish()}).loose(),_=l({type:d(`thought_signature`),signature:s().nullish()}).loose(),v=l({type:d(`arguments_delta`),arguments:s().nullish(),id:s().nullish(),signature:s().nullish()}).loose(),y=l({type:p([`text_annotation_delta`,`text_annotation`]),annotations:u(t).nullish()}).loose(),b=l({type:d(`image`),data:s().nullish(),mime_type:s().nullish(),resolution:p([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:s().nullish()}).loose(),x=l({type:d(`video`),data:s().nullish(),mime_type:s().nullish(),uri:s().nullish()}).loose(),S=l({type:p(Xn),id:s().nullish(),arguments:o(s(),a()).nullish(),name:s().nullish(),server_name:s().nullish(),search_type:s().nullish(),signature:s().nullish()}).loose(),C=l({type:p(Zn),call_id:s().nullish(),result:a().nullish(),is_error:m().nullish(),name:s().nullish(),server_name:s().nullish(),signature:s().nullish()}).loose(),w=l({type:s()}).loose(),T=f([c,b,x,g,_,v,y,S,C,w]),E=l({event_type:d(`step.delta`),event_id:s().nullish(),index:h(),delta:T}).loose(),D=l({event_type:d(`step.stop`),event_id:s().nullish(),index:h()}).loose(),O=l({event_type:d(`interaction.status_update`),event_id:s().nullish(),interaction_id:s().nullish(),status:e.nullish()}).loose(),k=l({event_type:d(`interaction.in_progress`),event_id:s().nullish(),interaction_id:s().nullish(),status:e.nullish()}).loose(),A=l({event_type:d(`interaction.requires_action`),event_id:s().nullish(),interaction_id:s().nullish(),status:e.nullish()}).loose(),j=l({event_type:d(`interaction.completed`),event_id:s().nullish(),interaction:l({id:s().nullish(),status:e.nullish(),usage:Gn().nullish(),service_tier:s().nullish()}).loose()}).loose(),M=l({event_type:d(`error`),event_id:s().nullish(),error:l({code:s().nullish(),message:s().nullish()}).loose().nullish()}).loose(),N=l({event_type:s()}).loose();return f([r,i,E,D,O,k,A,j,M,N])})())),tr=N(()=>U(l({previousInteractionId:s().nullish(),store:m().nullish(),agent:s().nullish(),agentConfig:f([l({type:d(`dynamic`)}).loose(),l({type:d(`deep-research`),thinkingSummaries:p([`auto`,`none`]).nullish(),visualization:p([`off`,`auto`]).nullish(),collaborativePlanning:m().nullish()})]).nullish(),thinkingLevel:p([`minimal`,`low`,`medium`,`high`]).nullish(),thinkingSummaries:p([`auto`,`none`]).nullish(),responseFormat:u(f([l({type:d(`text`),mimeType:s().nullish(),schema:a().nullish()}).loose(),l({type:d(`image`),mimeType:s().nullish(),aspectRatio:p([`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:p([`1K`,`2K`,`4K`,`512`]).nullish()}).loose(),l({type:d(`audio`),mimeType:s().nullish()}).loose(),l({type:d(`video`),aspectRatio:p([`16:9`,`9:16`]).nullish(),resolution:p([`360p`,`720p`,`1080p`,`4k`]).nullish(),duration:s().nullish(),delivery:p([`inline`,`uri`]).nullish(),gcsUri:s().nullish()}).loose()])).nullish(),imageConfig:l({aspectRatio:p([`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:p([`1K`,`2K`,`4K`,`512`]).nullish()}).nullish(),mediaResolution:p([`low`,`medium`,`high`,`ultra_high`]).nullish(),responseModalities:u(p([`text`,`image`,`audio`,`video`,`document`])).nullish(),serviceTier:p([`flex`,`standard`,`priority`]).nullish(),systemInstruction:s().nullish(),signature:s().nullish(),interactionId:s().nullish(),pollingTimeoutMs:h().int().positive().nullish(),background:m().nullish(),environment:f([s(),l({type:d(`remote`),sources:u(f([l({type:d(`gcs`),source:s(),target:s().nullish()}),l({type:d(`repository`),source:s(),target:s().nullish()}),l({type:d(`inline`),content:s(),target:s()})])).nullish(),network:f([d(`disabled`),l({allowlist:u(l({domain:s(),transform:u(o(s(),s())).nullish()}))})]).nullish()})]).nullish()})));function Q({signature:e,interactionId:t,processingId:n,processingCallId:r}){let i={};return e!=null&&(i.signature=e),t!=null&&(i.interactionId=t),n!=null&&(i.processingId=n),r!=null&&(i.processingCallId=r),Object.keys(i).length>0?{providerMetadata:{google:i}}:{}}var nr=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),rr=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function ir(e){return e.replace(/_call$/,``)}function ar(e){return e.replace(/_result$/,``)}function or({steps:e,generateId:t,interactionId:n}){let r=[],i=!1;if(e==null)return{content:r,hasFunctionCall:i};for(let a of e){if(typeof a!=`object`||!a)continue;let e=a.type;if(typeof e==`string`)switch(e){case`user_input`:break;case`model_output`:{let e=a.content??[];for(let i of e){if(typeof i!=`object`||!i)continue;let e=i.type;if(e===`text`){let e=i.text??``,a=i.annotations;r.push({type:`text`,text:e,...Q({interactionId:n})});let o=kn({annotations:a,generateId:t});for(let e of o)r.push(e)}else if(e===`image`){let e=i;e.data!=null&&e.data.length>0?r.push({type:`file`,mediaType:e.mime_type??`image/png`,data:{type:`data`,data:e.data},...Q({interactionId:n})}):e.uri!=null&&e.uri.length>0&&r.push({type:`file`,mediaType:e.mime_type??`image/png`,data:{type:`url`,url:new URL(e.uri)},...Q({interactionId:n})})}else if(e===`video`){let e=i;e.data!=null&&e.data.length>0?r.push({type:`file`,mediaType:e.mime_type??`video/mp4`,data:{type:`data`,data:e.data},...Q({interactionId:n})}):e.uri!=null&&e.uri.length>0&&r.push({type:`file`,mediaType:e.mime_type??`video/mp4`,data:{type:`url`,url:new URL(e.uri)},...Q({interactionId:n})})}}break}case`thought`:{let e=a,t=(Array.isArray(e.summary)?e.summary:[]).filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
`);r.push({type:`reasoning`,text:t,...Q({signature:e.signature,interactionId:n})});break}case`processing_call`:{let e=a,i=e.id||t();r.push({type:`custom`,kind:`google.processing_call`,...Q({signature:e.signature,interactionId:n,processingId:i})});break}case`processing_result`:{let e=a,i=e.call_id||t();r.push({type:`custom`,kind:`google.processing_result`,...Q({signature:e.signature,interactionId:n,processingCallId:i})});break}case`function_call`:{i=!0;let e=a;r.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.arguments??{}),...Q({signature:e.signature,interactionId:n})});break}default:if(nr.has(e)){let n=a,i=e===`mcp_server_tool_call`?n.name??`mcp_server_tool`:ir(e),o=JSON.stringify(n.arguments??{});r.push({type:`tool-call`,toolCallId:n.id||t(),toolName:i,input:o,providerExecuted:!0})}else if(rr.has(e)){let n=a,i=e===`mcp_server_tool_result`?n.name??`mcp_server_tool`:ar(e);r.push({type:`tool-result`,toolCallId:n.call_id||t(),toolName:i,result:n.result??null});let o=On({block:a,generateId:t});for(let e of o)r.push(e)}}}return{content:r,hasFunctionCall:i}}var sr=()=>globalThis.fetch;async function cr({baseURL:e,interactionId:t,headers:n,fetch:r=sr()}){if(t==null||t.length===0)return;let i=`${e}/interactions/${encodeURIComponent(t)}/cancel`;try{let e=await r(i,{method:`POST`,headers:_e(z({"Content-Type":`application/json`},n),O()),body:`{}`});try{await e.text()}catch{}}catch{}}var lr=new Set([`completed`,`failed`,`cancelled`,`incomplete`]);function ur(e){return e!=null&&lr.has(e)}var dr=1e3,fr=1e4,pr=18e5;async function mr({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,initialDelayMs:a=dr,maxDelayMs:o=fr,timeoutMs:s=pr}){if(t==null||t.length===0)throw Error(`google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.`);let c=Date.now(),l=a,u=`${e}/interactions/${encodeURIComponent(t)}`,d=()=>cr({baseURL:e,interactionId:t,headers:n,fetch:r});try{for(;;){if(i?.aborted)throw await d(),new DOMException(`Polling was aborted`,`AbortError`);if(Date.now()-c>s)throw Error(`google.interactions: timed out polling interaction ${t} after ${s}ms.`);await j(l,{abortSignal:i});let{value:e,rawValue:a,responseHeaders:f}=await E({url:u,validateUrl:!1,headers:n,failedResponseHandler:K,successfulResponseHandler:F($n),abortSignal:i,fetch:r});if(ur(e.status))return{response:e,rawResponse:a,responseHeaders:f};l=Math.min(l*2,o)}}catch(e){throw S(e)&&await d(),e}}function hr({tools:e,toolChoice:t}){let n=[],r=e?.length?e:void 0;if(r==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let i=[];for(let e of r){if(e.type===`function`){i.push({type:`function`,name:e.name,description:e.description??``,parameters:e.inputSchema});continue}if(e.type===`provider`){let t=e.args??{};switch(e.id){case`google.google_search`:{let e=t.searchTypes,n;if(typeof e==`object`&&e){let t=[];e.webSearch!=null&&t.push(`web_search`),e.imageSearch!=null&&t.push(`image_search`),t.length>0&&(n=t)}i.push({type:`google_search`,...n==null?{}:{search_types:n}});break}case`google.code_execution`:i.push({type:`code_execution`});break;case`google.url_context`:i.push({type:`url_context`});break;case`google.file_search`:i.push({type:`file_search`,...t.fileSearchStoreNames==null?{}:{file_search_store_names:t.fileSearchStoreNames},...t.topK==null?{}:{top_k:t.topK},...t.metadataFilter==null?{}:{metadata_filter:t.metadataFilter}});break;case`google.google_maps`:i.push({type:`google_maps`,...t.latitude==null?{}:{latitude:t.latitude},...t.longitude==null?{}:{longitude:t.longitude},...t.enableWidget==null?{}:{enable_widget:t.enableWidget}});break;case`google.computer_use`:i.push({type:`computer_use`,environment:t.environment??`browser`,...t.excludedPredefinedFunctions==null?{}:{excludedPredefinedFunctions:t.excludedPredefinedFunctions}});break;case`google.mcp_server`:i.push({type:`mcp_server`,...t.name==null?{}:{name:t.name},...t.url==null?{}:{url:t.url},...t.headers==null?{}:{headers:t.headers},...t.allowedTools==null?{}:{allowed_tools:t.allowedTools}});break;case`google.retrieval`:{let e=t.vertexAiSearchConfig??void 0;i.push({type:`retrieval`,...t.retrievalTypes==null?{retrieval_types:[`vertex_ai_search`]}:{retrieval_types:t.retrievalTypes},...e==null?{}:{vertex_ai_search_config:e}});break}default:n.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`provider-defined tool ${e.id} is not supported by google.interactions; tool dropped.`})}continue}n.push({type:`unsupported`,feature:`tool of type ${e.type}`,details:`Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped.`})}let a=i.some(e=>e.type===`function`),o;if(t!=null&&a)switch(t.type){case`auto`:o=`auto`;break;case`required`:o=`any`;break;case`none`:o=`none`;break;case`tool`:o={allowed_tools:{mode:`validated`,tools:[t.toolName]}}}return{tools:i.length>0?i:void 0,toolChoice:o,toolWarnings:n}}var gr=3,_r=500;function vr({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,maxRetries:a=gr,retryDelayMs:o=_r}){if(t.length===0)throw Error(`google.interactions: cannot stream a background interaction without an id.`);let s={...n,accept:`text/event-stream`},c,l=!1,u=0,d=!1,f,p=new AbortController,m=()=>p.abort();i!=null&&(i.aborted?p.abort():i.addEventListener(`abort`,m,{once:!0}));let h=p.signal;function g(){let n=`${e}/interactions/${encodeURIComponent(t)}`,r=new URLSearchParams({stream:`true`});return c!=null&&r.set(`last_event_id`,c),`${n}?${r.toString()}`}async function _(){let{value:e}=await E({url:g(),validateUrl:!1,headers:s,failedResponseHandler:K,successfulResponseHandler:se(er),abortSignal:h,fetch:r});return e.getReader()}return new ReadableStream({async start(s){try{for(;!l&&!h.aborted;){if(f==null)try{f=await _(),d=!1}catch(e){if(S(e)||h.aborted){s.error(e);return}if(u++,u>=a){s.error(e);return}await j(o*u,{abortSignal:h});continue}try{let{done:e,value:t}=await f.read();if(e){if(f=void 0,l)break;if(d)u=0;else{if(u++,u>=a){s.error(Error(`google.interactions: SSE stream closed without producing any events.`));return}await j(o*u,{abortSignal:h})}continue}if(d=!0,t.success){let e=t.value;typeof e.event_id==`string`&&e.event_id.length>0&&(c=e.event_id),(e.event_type===`interaction.completed`||e.event_type===`error`)&&(l=!0)}s.enqueue(t)}catch(e){if(S(e)||h.aborted){s.error(e);return}if(f=void 0,u++,u>=a){s.error(e);return}await j(o*u,{abortSignal:h})}}s.close()}catch(e){s.error(e)}finally{i?.removeEventListener(`abort`,m),f?.cancel().catch(()=>{}),f=void 0,h.aborted&&!l&&await cr({baseURL:e,interactionId:t,headers:n,fetch:r})}},cancel(){p.abort(),f?.cancel().catch(()=>{}),f=void 0}})}function yr({response:e,warnings:t,generateId:n,includeRawChunks:r,headerServiceTier:i}){return new ReadableStream({start(a){a.enqueue({type:`stream-start`,warnings:t});let o=typeof e.id==`string`&&e.id.length>0?e.id:void 0,s,c=e.created;if(typeof c==`string`){let e=new Date(c);Number.isNaN(e.getTime())||(s=e)}a.enqueue({type:`response-metadata`,...o==null?{}:{id:o},modelId:e.model??void 0,...s?{timestamp:s}:{}}),r&&a.enqueue({type:`raw`,rawValue:e});let{content:l,hasFunctionCall:u}=or({steps:e.steps??null,generateId:n,interactionId:o}),d=0,f=()=>`${o??`agent`}:${d++}`;for(let e of l)switch(e.type){case`text`:{let t=f(),n=e.providerMetadata;a.enqueue({type:`text-start`,id:t}),e.text.length>0&&a.enqueue({type:`text-delta`,id:t,delta:e.text}),a.enqueue({type:`text-end`,id:t,...n?{providerMetadata:n}:{}});break}case`reasoning`:{let t=f(),n=e.providerMetadata;a.enqueue({type:`reasoning-start`,id:t}),e.text.length>0&&a.enqueue({type:`reasoning-delta`,id:t,delta:e.text}),a.enqueue({type:`reasoning-end`,id:t,...n?{providerMetadata:n}:{}});break}case`tool-call`:{let t=e.providerMetadata;a.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{}}),a.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.input}),a.enqueue({type:`tool-input-end`,id:e.toolCallId}),a.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...t?{providerMetadata:t}:{}});break}case`tool-result`:a.enqueue({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result});break;case`source`:case`file`:a.enqueue(e)}let p=e.service_tier??i,m={unified:An({status:e.status,hasFunctionCall:u}),raw:e.status},h={google:{...o==null?{}:{interactionId:o},...p==null?{}:{serviceTier:p}}};a.enqueue({type:`finish`,finishReason:m,usage:Sn(e.usage),providerMetadata:h}),a.close()}})}var br=class e{constructor(e,t){this.specificationVersion=`v4`,typeof e==`string`?(this.modelId=e,this.agent=void 0):`managedAgent`in e?(this.modelId=e.managedAgent,this.agent=e.managedAgent):(this.modelId=e.agent,this.agent=e.agent),this.config=t}static[G](e){return{...R({modelId:e.modelId,config:e.config}),agent:e.agent}}static[W](t){return new e(t.agent==null?t.modelId:{agent:t.agent},t.config)}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?this.config.supportedUrls():{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(e){let t=[],n=await g({provider:`google`,providerOptions:e.providerOptions,schema:tr}),r=this.agent!=null;r||(e.frequencyPenalty!=null&&t.push({type:`unsupported`,feature:`frequencyPenalty`}),e.presencePenalty!=null&&t.push({type:`unsupported`,feature:`presencePenalty`}));let i=e.tools!=null&&e.tools.length>0,a,o;if(i){let n=hr({tools:e.tools,toolChoice:e.toolChoice});a=n.tools,o=n.toolChoice,t.push(...n.toolWarnings)}let s=[];if(e.responseFormat?.type===`json`){if(r)t.push({type:`other`,message:`google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored.`});else{let t={type:`text`,mime_type:`application/json`,...e.responseFormat.schema==null?{}:{schema:e.responseFormat.schema}};s.push(t)}}if(n?.responseFormat!=null)for(let e of n.responseFormat)e.type===`text`?s.push($({type:`text`,mime_type:e.mimeType??void 0,schema:e.schema??void 0})):e.type===`image`?s.push($({type:`image`,mime_type:e.mimeType??void 0,aspect_ratio:e.aspectRatio??void 0,image_size:e.imageSize??void 0})):e.type===`audio`?s.push($({type:`audio`,mime_type:e.mimeType??void 0})):e.type===`video`&&s.push($({type:`video`,aspect_ratio:e.aspectRatio??void 0,resolution:e.resolution??void 0,duration:e.duration??void 0,delivery:e.delivery??void 0,gcs_uri:e.gcsUri??void 0}));let{input:c,systemInstruction:l,warnings:u}=In({prompt:e.prompt,previousInteractionId:n?.previousInteractionId??void 0,store:n?.store??void 0,mediaResolution:n?.mediaResolution??void 0});t.push(...u);let d=l,f=n?.systemInstruction??void 0;d!=null&&f!=null?t.push({type:`other`,message:`google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message.`}):d==null&&f!=null&&(d=f);let p;if(r){let r=[];e.temperature!=null&&r.push(`temperature`),e.topP!=null&&r.push(`topP`),e.topK!=null&&r.push(`topK`),e.frequencyPenalty!=null&&r.push(`frequencyPenalty`),e.presencePenalty!=null&&r.push(`presencePenalty`),e.seed!=null&&r.push(`seed`),e.stopSequences!=null&&e.stopSequences.length>0&&r.push(`stopSequences`),e.maxOutputTokens!=null&&r.push(`maxOutputTokens`),n?.thinkingLevel!=null&&r.push(`thinkingLevel`),n?.thinkingSummaries!=null&&r.push(`thinkingSummaries`),n?.imageConfig!=null&&r.push(`imageConfig`),r.length>0&&t.push({type:`other`,message:`google.interactions: ${r.join(`, `)} ${r.length===1?`is`:`are`} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`}),p=void 0}else if(p=$({temperature:e.temperature??void 0,top_p:e.topP??void 0,top_k:e.topK??void 0,seed:e.seed??void 0,stop_sequences:e.stopSequences!=null&&e.stopSequences.length>0?e.stopSequences:void 0,max_output_tokens:e.maxOutputTokens??void 0,thinking_level:n?.thinkingLevel??void 0,thinking_summaries:n?.thinkingSummaries??void 0,tool_choice:o}),n?.imageConfig!=null){let e=s.some(e=>e.type===`image`);t.push({type:`other`,message:e?`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.`}),e||s.push({type:`image`,mime_type:`image/png`,...n.imageConfig.aspectRatio==null?{}:{aspect_ratio:n.imageConfig.aspectRatio},...n.imageConfig.imageSize==null?{}:{image_size:n.imageConfig.imageSize}})}let m;if(r&&n?.agentConfig!=null){let e=n.agentConfig;e.type===`deep-research`?m=$({type:`deep-research`,thinking_summaries:e.thinkingSummaries??void 0,visualization:e.visualization??void 0,collaborative_planning:e.collaborativePlanning??void 0}):e.type===`dynamic`&&(m={type:`dynamic`})}let h;if(n?.environment!=null){if(!r)t.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 n.environment==`string`)h=n.environment;else{let e=n.environment,t=e.sources?.map(e=>e.type===`inline`?{type:`inline`,content:e.content,target:e.target}:$({type:e.type,source:e.source,target:e.target??void 0})),r;e.network===`disabled`?r=`disabled`:e.network!=null&&(r={allowlist:e.network.allowlist.map(e=>$({domain:e.domain,transform:e.transform??void 0}))}),h=$({type:`remote`,sources:t!=null&&t.length>0?t:void 0,network:r})}}return{args:$({...r?{agent:this.agent}:{model:this.modelId},input:c,system_instruction:d,tools:a,response_format:s.length>0?s:void 0,response_modalities:n?.responseModalities==null?void 0:n.responseModalities,previous_interaction_id:n?.previousInteractionId??void 0,service_tier:n?.serviceTier??void 0,store:n?.store??void 0,generation_config:p!=null&&Object.keys(p).length>0?p:void 0,agent_config:m,environment:h,background:n?.background??void 0}),warnings:t,isAgent:r,isBackground:n?.background===!0,pollingTimeoutMs:n?.pollingTimeoutMs??void 0}}async doGenerate(e){let{args:t,warnings:n,isAgent:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=z(this.config.headers?await B(this.config.headers):void 0,e.headers),{responseHeaders:s,value:c,rawValue:l}=await H({url:a,headers:o,body:t,failedResponseHandler:K,successfulResponseHandler:F($n),abortSignal:e.abortSignal,fetch:this.config.fetch});if(r&&!ur(c.status)){let t=await mr({baseURL:this.config.baseURL,interactionId:c.id,headers:o,fetch:this.config.fetch,abortSignal:e.abortSignal,timeoutMs:i});c=t.response,l=t.rawResponse,s=t.responseHeaders??s}let u=typeof c.id==`string`&&c.id.length>0?c.id:void 0,{content:d,hasFunctionCall:f}=or({steps:c.steps??null,generateId:this.config.generateId??T,interactionId:u}),p={unified:An({status:c.status,hasFunctionCall:f}),raw:c.status},m=c.service_tier??s?.[`x-gemini-service-tier`]??void 0,h=Cn(c.usage),g={google:{...u==null?{}:{interactionId:u},...m==null?{}:{serviceTier:m},...h==null?{}:{outputTokensByModality:h}}},_;if(typeof c.created==`string`){let e=new Date(c.created);Number.isNaN(e.getTime())||(_=e)}return{content:d,finishReason:p,usage:Sn(c.usage),warnings:n,providerMetadata:g,request:{body:t},response:{headers:s,body:l,...u==null?{}:{id:u},..._?{timestamp:_}:{},modelId:c.model??void 0}}}async doStream(e){let{args:t,warnings:n,isBackground:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=z(this.config.headers?await B(this.config.headers):void 0,e.headers);if(r)return this.doStreamBackground({args:t,warnings:n,url:a,mergedHeaders:o,options:e,pollingTimeoutMs:i});let s={...t,stream:!0},{responseHeaders:c,value:l}=await H({url:a,headers:o,body:s,failedResponseHandler:K,successfulResponseHandler:se(er),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c?.[`x-gemini-service-tier`],d=Fn({warnings:n,generateId:this.config.generateId??T,includeRawChunks:e.includeRawChunks,serviceTier:u});return{stream:l.pipeThrough(d),request:{body:s},response:{headers:c}}}async doStreamBackground({args:e,warnings:t,url:n,mergedHeaders:r,options:i,pollingTimeoutMs:a}){let{responseHeaders:o,value:s}=await H({url:n,headers:r,body:e,failedResponseHandler:K,successfulResponseHandler:F($n),abortSignal:i.abortSignal,fetch:this.config.fetch}),c=s.id;if(c==null||c.length===0)throw Error(`google.interactions: background POST response did not include an interaction id; cannot stream the result.`);let l=o?.[`x-gemini-service-tier`];if(ur(s.status))return{stream:yr({response:s,warnings:t,generateId:this.config.generateId??T,includeRawChunks:i.includeRawChunks,headerServiceTier:l}),request:{body:e},response:{headers:o}};let u=vr({baseURL:this.config.baseURL,interactionId:c,headers:r,fetch:this.config.fetch,abortSignal:i.abortSignal}),d=Fn({warnings:t,generateId:this.config.generateId??T,includeRawChunks:i.includeRawChunks,serviceTier:l});return{stream:u.pipeThrough(d),request:{body:e},response:{headers:o}}}};function $(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function xr(e){let t=new URL(e),n=t.pathname.split(`/`),r=n.at(-1);return(r===`v1beta`||r===`v1alpha`)&&(n.pop(),t.pathname=n.join(`/`)||`/`),t}function Sr(e,t){let n=xr(e);return n.protocol=n.protocol===`https:`?`wss:`:`ws:`,n.pathname=`${n.pathname.replace(/\/$/,``)}/ws/${t}`,n}var Cr=class{constructor(){this.turnCounter=0,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,this.turnClosed=!1,this.inputAudioRate=16e3}get responseId(){return`google-resp-${this.turnCounter}`}get itemId(){return`google-item-${this.turnCounter}`}beginTurnIfClosed(){this.turnClosed&&=(this.turnCounter++,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,!1)}parseServerEvent(e){let t=e;return t.setupComplete==null?t.toolCall==null?t.toolCallCancellation==null?t.goAway==null?t.sessionResumptionUpdate==null?t.serverContent==null?t.inputTranscription?.text==null?{type:`custom`,rawType:String(Object.keys(t)[0]),raw:e}:{type:`input-transcription-completed`,itemId:`google-input-${this.turnCounter}`,transcript:t.inputTranscription.text,raw:e}:this.parseServerContent(t.serverContent,e):{type:`custom`,rawType:`sessionResumptionUpdate`,raw:e}:{type:`custom`,rawType:`goAway`,raw:e}:{type:`custom`,rawType:`toolCallCancellation`,raw:e}:(this.beginTurnIfClosed(),(t.toolCall.functionCalls??[]).flatMap(t=>{let n=JSON.stringify(t.args??{});return[{type:`function-call-arguments-delta`,responseId:this.responseId,itemId:this.itemId,callId:t.id,delta:n,raw:e},{type:`function-call-arguments-done`,responseId:this.responseId,itemId:this.itemId,callId:t.id,name:t.name,arguments:n,raw:e}]})):{type:`session-created`,raw:e}}parseServerContent(e,t){let n=[];if(e.interrupted&&n.push({type:`speech-started`,raw:t}),e.modelTurn?.parts){this.beginTurnIfClosed();for(let r of e.modelTurn.parts)r.inlineData?.data&&(this.hasAudio=!0,n.push({type:`audio-delta`,responseId:this.responseId,itemId:this.itemId,delta:r.inlineData.data,raw:t})),r.text&&(this.hasText=!0,n.push({type:`text-delta`,responseId:this.responseId,itemId:this.itemId,delta:r.text,raw:t}))}return e.outputTranscription?.text&&(this.hasTranscript=!0,n.push({type:`audio-transcript-delta`,responseId:this.responseId,itemId:this.itemId,delta:e.outputTranscription.text,raw:t})),e.inputTranscription?.text&&n.push({type:`input-transcription-completed`,itemId:`google-input-${this.turnCounter}`,transcript:e.inputTranscription.text,raw:t}),e.generationComplete&&n.push({type:`custom`,rawType:`generationComplete`,raw:t}),e.interactionStatus!=null&&n.push({type:`custom`,rawType:`interactionStatus`,raw:t}),e.waitingForInput&&n.push({type:`custom`,rawType:`waitingForInput`,raw:t}),e.turnComplete&&(this.hasAudio&&n.push({type:`audio-done`,responseId:this.responseId,itemId:this.itemId,raw:t}),this.hasText&&n.push({type:`text-done`,responseId:this.responseId,itemId:this.itemId,raw:t}),this.hasTranscript&&n.push({type:`audio-transcript-done`,responseId:this.responseId,itemId:this.itemId,raw:t}),n.push({type:`response-done`,responseId:this.responseId,status:`completed`,raw:t}),this.turnClosed=!0),n.length===0?{type:`custom`,rawType:`serverContent`,raw:t}:n.length===1?n[0]:n}serializeClientEvent(e,t){switch(e.type){case`session-update`:return e.config.inputAudioFormat?.rate!=null&&(this.inputAudioRate=e.config.inputAudioFormat.rate),{setup:Dr(e.config,t)};case`input-audio-append`:return{realtimeInput:{audio:{data:e.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 t=e.item;switch(t.type){case`text-message`:return{realtimeInput:{text:t.text}};case`function-call-output`:return Tr(t);case`audio-message`:return null}break}}return null}};function wr(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{output:e}}async function Tr(e){let t=await L({text:e.output}),n=t.success?wr(t.value):{output:e.output};return{toolResponse:{functionResponses:[{id:e.callId,name:e.name,response:n}]}}}function Er(e){let t=e.split(`/`).at(-1)?.toLowerCase()??``;return/^gemini-\d+\.\d+-live\b.*thinking/.test(t)}function Dr(e,t){let n={model:q(t)},{google:r,...i}=e?.providerOptions??{},a=M(r)?r:void 0,o={};o.responseModalities=e?.outputModalities==null?[`AUDIO`]:e.outputModalities.map(e=>e.toUpperCase()),e?.voice!=null&&(o.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.voice}}}),n.generationConfig=o,e?.instructions!=null&&(n.systemInstruction={parts:[{text:e.instructions}]}),e?.tools!=null&&e.tools.length>0&&(n.tools=[{functionDeclarations:e.tools.map(e=>({name:e.name,description:e.description,parametersJsonSchema:e.parameters,...a?.defaultToolBehavior==null?{}:{behavior:a.defaultToolBehavior}}))}]),e?.inputAudioTranscription!=null&&(n.inputAudioTranscription={}),e?.outputAudioTranscription!=null&&(n.outputAudioTranscription={});let s=a?.thinkingConfig??(Er(t)?{thinkingLevel:`low`}:void 0),c=()=>{if(s==null)return;let e=M(n.generationConfig)?n.generationConfig:o;n.generationConfig={...e,thinkingConfig:s}};return e?.providerOptions==null?(c(),n):(Object.assign(n,i),a?.translationConfig!=null&&(n.generationConfig={...M(n.generationConfig)?n.generationConfig:o,translationConfig:a.translationConfig}),c(),n)}var Or=`google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained`;function kr(e){let t=xr(e);return t.pathname=`${t.pathname.replace(/\/$/,``)}/v1alpha/auth_tokens`,t.toString()}function Ar(e){return Sr(e,Or).toString()}var jr=class{constructor(e,t){this.specificationVersion=`v4`,this.mapper=new Cr,this.modelId=e,this.provider=t.provider,this.config=t}async doCreateClientSecret(e){let t=this.config.fetch??fetch,n=this.config.headers()[`x-goog-api-key`];if(!n)throw Error(`Google Generative AI API key is required for realtime token creation.`);let r=Date.now(),i=(e.expiresAfterSeconds??60)*1e3,a=new Date(r+i).toISOString(),o=new Date(r+i+18e5).toISOString(),s=Dr(e.sessionConfig,this.modelId),c=await t(`${kr(this.config.baseURL)}?key=${encodeURIComponent(n)}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({uses:0,expireTime:o,newSessionExpireTime:a,bidiGenerateContentSetup:s})});if(!c.ok){let e=await c.text();throw Error(`Google realtime auth token request failed: ${c.status} ${e}`)}let l=await c.json();return{token:l.name,url:Ar(this.config.baseURL),expiresAt:l.expireTime?Math.floor(new Date(l.expireTime).getTime()/1e3):void 0}}getWebSocketConfig(e){return{url:`${e.url}?access_token=${encodeURIComponent(e.token)}`}}parseServerEvent(e){return this.mapper.parseServerEvent(e)}serializeClientEvent(e){return this.mapper.serializeClientEvent(e,this.modelId)}buildSessionConfig(e){return Dr(e,this.modelId)}},Mr=l({languageCodes:u(s()).optional(),customVocabulary:u(s()).optional(),wordTimestamp:m().optional(),diarization:m().optional(),mode:p([`SMART`,`VERBATIM`]).optional()}),Nr=`google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent`,Pr=3e3;function Fr(e,t){let n=Sr(e,Nr);return n.searchParams.set(`key`,t),n}function Ir(e){return e.includes(`-live`)}var Lr=class e{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}static[G](e){return R({modelId:e.modelId,config:e.config})}static[W](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async parseOptions(e){return g({provider:`google`,providerOptions:e,schema:Mr})}async doGenerate(e){var n;if(Ir(this.modelId))throw new t({argument:`modelId`,message:`Model '${this.modelId}' only supports streaming transcription. Use experimental_streamTranscribe, or a unary model such as 'gemini-3.5-transcribe'.`});let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,i=[],a=Br(await this.parseOptions(e.providerOptions)),o={model:this.modelId,input:[{type:`audio`,data:V(e.audio),mime_type:e.mediaType}],...a==null?{}:{generation_config:{transcription_config:a}}},{value:s,responseHeaders:c,rawValue:l}=await H({url:`${this.config.baseURL}/interactions`,headers:z(this.config.headers?await B(this.config.headers):void 0,e.headers),body:o,failedResponseHandler:K,successfulResponseHandler:F(Wr),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=``,d=[];for(let e of s.steps??[])for(let t of e.content??[])if(t.type===`text`&&t.text!=null){u+=t.text;for(let e of t.annotations??[]){if(e.type!==`word_info`)continue;let t=Vr(e.start_offset),n=Vr(e.end_offset);e.text!=null&&t!=null&&n!=null&&d.push({text:e.text,startSecond:t,endSecond:n})}}return{text:u,segments:d,language:void 0,durationInSeconds:void 0,warnings:i,response:{timestamp:r,modelId:this.modelId,headers:c,body:l},...s.usage==null?{}:{providerMetadata:{google:{usage:s.usage}}}}}async doStream(e){var n;if(!Ir(this.modelId))throw new t({argument:`modelId`,message:`Model '${this.modelId}' does not support streaming transcription. Use a live model such as 'gemini-3.5-transcribe-live'.`});let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,i=[],a=await this.parseOptions(e.providerOptions);Hr(e.inputAudioFormat);let o=z(this.config.headers?await B(this.config.headers):void 0,e.headers),s;for(let[e,t]of Object.entries(o))e.toLowerCase()===`x-goog-api-key`&&t!=null&&(s=t);if(s==null)throw Error(`Google Generative AI API key is required for streaming transcription.`);let c=Object.fromEntries(Object.entries(o).filter(([e])=>e.toLowerCase()!==`x-goog-api-key`)),l={model:q(this.modelId),inputAudioTranscription:zr(a)??{}};return{request:{body:l},response:{timestamp:r,modelId:this.modelId},stream:Rr({webSocket:this.config.webSocket,url:Fr(this.config.baseURL,s),headers:c,setup:l,inputAudioRate:e.inputAudioFormat.rate??16e3,finishGraceMs:this.config._internal?.finishGraceMs??Pr,warnings:i,audio:e.audio,abortSignal:e.abortSignal,includeRawChunks:e.includeRawChunks})}}};function Rr({webSocket:e,url:t,headers:n,setup:r,inputAudioRate:i,finishGraceMs:a,warnings:o,audio:s,abortSignal:c,includeRawChunks:l}){let u=!1,d=()=>{};return new ReadableStream({start:f=>{let p,m,h,g=new Promise(e=>{h=e}),_=0,v=``,y=``,b=``,x,S=!1,C,w,T=()=>`google-segment-${_}`,E=()=>{w!=null&&(clearTimeout(w),w=void 0)},D=()=>{!u&&S&&(E(),w=setTimeout(()=>{w=void 0,A()},a))};d=e=>{E(),p==null?s.cancel().catch(()=>{}):p.cancel().catch(()=>{}),m?.close(e)};let O=e=>{u||(u=!0,d(),f.error(e))},k=()=>{if(v===``){if(b===``)return;v=b}b=``,f.enqueue({type:`transcript-final`,id:T(),text:v}),y+=y===``?v:` ${v}`,v=``,_++},A=()=>{u||(k(),u=!0,f.enqueue({type:`finish`,text:y,segments:[],language:x,durationInSeconds:void 0,...C==null?{}:{providerMetadata:{google:{usageMetadata:C}}}}),f.close(),d(1e3))},j=async e=>{p=s.getReader();try{for(;;){let{done:t,value:n}=await p.read();if(t||u)break;e.send(JSON.stringify({realtimeInput:{audio:{data:V(n),mimeType:`audio/pcm;rate=${i}`}}})),await me(e)}}finally{p.releaseLock(),p=void 0}u||(e.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),S=!0,D())};m=ee({url:t,headers:n,webSocket:e,abortSignal:c,onAbort:O,onProcessingError:O,onOpen:e=>{f.enqueue({type:`stream-start`,warnings:o}),e.send(JSON.stringify({setup:r})),g.then(()=>u?void 0:j(e)).catch(O)},onMessageText:async e=>{if(u)return;let t=await L({text:e});if(!t.success)return;let n=t.value;if(l&&f.enqueue({type:`raw`,rawValue:n}),n.setupComplete!=null&&h(),n.usageMetadata!=null&&(C=n.usageMetadata),n.error!=null){O(Error(n.error.message??`Google Live API error`));return}let r=n.serverContent,i=r?.interimInputTranscription;i?.text&&(D(),b=i.text,f.enqueue({type:`transcript-partial`,id:T(),text:i.text}));let a=r?.inputTranscription??n.inputTranscription;a!=null&&(a.languageCode!=null&&(x=a.languageCode),a.text&&(D(),b=``,v+=a.text,f.enqueue({type:`transcript-delta`,id:T(),delta:a.text})),a.finished===!0&&k()),r?.turnComplete&&k();let o=r?.interactionStatus;S&&(o===`IDLE`||o===`REQUIRES_ACTION`||r?.turnComplete===!0&&o==null)&&A()},onSocketError:()=>{O(Error(`Google Live transcription error`))},onClose:({code:e,reason:t})=>{if(!u){if(S){A();return}O(Error(`Google Live transcription WebSocket closed unexpectedly before finishing (code ${e??`unknown`}${t?`, reason: ${t}`:``}).`))}}})},cancel:()=>{u||(u=!0,d())}})}function zr(e){if(e==null)return;let t={};return e.languageCodes!=null&&(t.languageCodes=e.languageCodes),e.customVocabulary!=null&&(t.customVocabulary=e.customVocabulary),e.wordTimestamp!=null&&(t.wordTimestamp=e.wordTimestamp),e.diarization!=null&&(t.diarization=e.diarization),e.mode!=null&&(t.mode=e.mode),Object.keys(t).length>0?t:void 0}function Br(e){if(e==null)return;let t={};return e.languageCodes!=null&&(t.language_codes=e.languageCodes),e.customVocabulary!=null&&(t.custom_vocabulary=e.customVocabulary),(e.mode!=null||e.diarization===!0||e.wordTimestamp===!0)&&(t.mode={type:(e.mode??`VERBATIM`).toLowerCase(),...e.diarization===!0?{diarization_mode:`speaker`}:{},...e.wordTimestamp===!0?{timestamp_granularities:[`word`]}:{}}),Object.keys(t).length>0?t:void 0}function Vr(e){if(e==null)return;let t=Number.parseFloat(e);return Number.isFinite(t)?t:void 0}function Hr(e){if(e.type!==`audio/pcm`||e.rate!=null&&e.rate!==16e3)throw new t({argument:`inputAudioFormat`,message:`The Gemini Live transcription API only supports 16kHz 16-bit PCM input audio.`})}var Ur=l({type:s().nullish(),text:s().nullish(),speaker:s().nullish(),start_offset:s().nullish(),end_offset:s().nullish()}),Wr=l({status:s().nullish(),steps:u(l({type:s().nullish(),content:u(l({type:s().nullish(),text:s().nullish(),annotations:u(Ur).nullish()})).nullish()})).nullish(),usage:o(s(),a()).nullish()}),Gr=N(()=>U(l({echoTargetLanguage:m().optional()}))),Kr=`google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent`,qr=1e3,Jr=24e3,Yr=128;function Xr(e,t){let n=Sr(e,Kr);return n.searchParams.set(`key`,t),n}var Zr=class e{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t}static[G](e){return R({modelId:e.modelId,config:e.config})}static[W](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doStream(e){var n;if(e.targetLanguage==null)throw new t({argument:`targetLanguage`,message:`targetLanguage is required for translation model '${this.modelId}'.`});let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,i=await g({provider:`google`,providerOptions:e.providerOptions,schema:Gr}),a=[];ni(e.inputAudioFormat),e.sourceLanguage!=null&&a.push({type:`unsupported`,feature:`sourceLanguage`,details:`The Gemini Live translation API auto-detects the source language and does not accept a source language.`}),e.outputAudioFormat!=null&&a.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 o=z(this.config.headers(),e.headers),s;for(let[e,t]of Object.entries(o))e.toLowerCase()===`x-goog-api-key`&&t!=null&&(s=t);if(s==null)throw Error(`Google Generative AI API key is required for streaming translation.`);let c=Object.fromEntries(Object.entries(o).filter(([e])=>e.toLowerCase()!==`x-goog-api-key`)),l=ti({modelId:this.modelId,targetLanguage:e.targetLanguage,providerOptions:i});return{request:{body:l},response:{timestamp:r,modelId:this.modelId},stream:Qr({webSocket:this.config.webSocket,url:Xr(this.config.baseURL,s),headers:c,setup:l,inputAudioRate:e.inputAudioFormat.rate??16e3,finishGraceMs:this.config._internal?.finishGraceMs??qr,warnings:a,audio:e.audio,abortSignal:e.abortSignal,includeRawChunks:e.includeRawChunks})}}};function Qr({webSocket:e,url:t,headers:n,setup:r,inputAudioRate:i,finishGraceMs:a,warnings:o,audio:s,abortSignal:c,includeRawChunks:l}){let u=!1,d=()=>{};return new ReadableStream({start:f=>{let p,m,h,g=new Promise(e=>{h=e}),_=0,v=``,y=``,b=``,x=``,S=!1,C,w=!1,T=!1,E=0,D,O=()=>`google-item-${_}`,k=()=>{D!=null&&(clearTimeout(D),D=void 0)},A=()=>{u||D!=null||(D=setTimeout(()=>{D=void 0,N()},a))},j=()=>{w=!0,E=0,k()};d=e=>{k(),p==null?s.cancel().catch(()=>{}):p.cancel().catch(()=>{}),m?.close(e)};let M=e=>{u||(u=!0,d(),f.error(e))},N=()=>{u||((y!==``||x!==``)&&P(),u=!0,f.enqueue({type:`finish`,sourceText:v,outputText:b,usage:C}),f.close(),d(1e3))},P=()=>{y!==``&&(f.enqueue({type:`source-transcript-final`,id:O(),text:y}),v+=y,y=``),x!==``&&(f.enqueue({type:`output-text-final`,id:O(),text:x}),b+=x,x=``),_++},F=async e=>{p=s.getReader();try{for(;;){let{done:t,value:n}=await p.read();if(t||u)break;e.send(JSON.stringify({realtimeInput:{audio:{data:V(n),mimeType:`audio/pcm;rate=${i}`}}})),await me(e)}}finally{p.releaseLock(),p=void 0}u||(e.send(JSON.stringify({realtimeInput:{audioStreamEnd:!0}})),S=!0,T&&!w&&A())};m=ee({url:t,headers:n,webSocket:e,abortSignal:c,onAbort:M,onProcessingError:M,onOpen:e=>{f.enqueue({type:`stream-start`,warnings:o}),e.send(JSON.stringify({setup:r})),g.then(()=>u?void 0:F(e)).catch(M)},onMessageText:async e=>{if(u)return;let t=await L({text:e});if(!t.success)return;let n=t.value;if(l&&f.enqueue({type:`raw`,rawValue:n}),n.setupComplete!=null&&h(),n.usageMetadata!=null&&(C=$r(C,n.usageMetadata)),n.error!=null){M(Error(n.error.message??`Google Live API error`));return}let r=n.serverContent?.inputTranscription?.text??n.inputTranscription?.text;r&&(j(),y+=r,f.enqueue({type:`source-transcript-delta`,id:O(),delta:r}));let i=n.serverContent;if(i!=null){for(let e of i.modelTurn?.parts??[])if(e.inlineData?.data){f.enqueue({type:`audio`,id:O(),audio:e.inlineData.data});let t=ei(e.inlineData.data);if(S&&t!=null){if(E+=t,E>=a){N();return}}else j()}i.outputTranscription?.text&&(j(),x+=i.outputTranscription.text,f.enqueue({type:`output-text-delta`,id:O(),delta:i.outputTranscription.text})),i.turnComplete&&(P(),w=!1,T=!0,S&&A())}},onSocketError:()=>{M(Error(`Google Live translation error`))},onClose:({code:e,reason:t})=>{if(!u){if(D!=null){N();return}M(Error(`Google Live translation WebSocket closed unexpectedly before finishing (code ${e??`unknown`}${t?`, reason: ${t}`:``}).`))}}})},cancel:()=>{u||(u=!0,d())}})}function $r(e,t){let n=e?.inputAudioTokens,r=e?.outputAudioTokens;for(let e of t.promptTokensDetails??[])e.modality===`AUDIO`&&e.tokenCount!=null&&(n=(n??0)+e.tokenCount);for(let e of t.responseTokensDetails??[])e.modality===`AUDIO`&&e.tokenCount!=null&&(r=(r??0)+e.tokenCount);return n==null&&r==null?e:{...e,...n==null?{}:{inputAudioTokens:n},...r==null?{}:{outputAudioTokens:r}}}function ei(e){let t;try{t=fe(e)}catch{return}if(t.byteLength<2)return;let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=Math.floor(t.byteLength/2);for(let e=0;e<r;e++)if(Math.abs(n.getInt16(e*2,!0))>Yr)return;return r/Jr*1e3}function ti({modelId:e,targetLanguage:t,providerOptions:n}){return{model:q(e),generationConfig:{responseModalities:[`AUDIO`],translationConfig:{targetLanguageCode:t,...n?.echoTargetLanguage==null?{}:{echoTargetLanguage:n.echoTargetLanguage}}},inputAudioTranscription:{},outputAudioTranscription:{}}}function ni(e){if(e.type!==`audio/pcm`||e.rate!=null&&e.rate!==16e3)throw new t({argument:`inputAudioFormat`,message:`The Gemini Live translation API only supports 16kHz 16-bit PCM input audio.`})}var ri=`https://generativelanguage.googleapis.com/v1beta`,ii=/^https:\/\/generativelanguage\.googleapis\.com\/v1beta\/files\/.*$/,ai=[`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`],oi=/^https:\/\/.*$/;function si(e){return/(^|\/)gemini-/.test(e)&&!/(^|\/)gemini-2\.0/.test(e)}function ci(e={}){let t=te(e.baseURL)??ri,n=e.name??`google.generative-ai`,r=()=>_e({"x-goog-api-key":b({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${ye}`),i=(e,n=e==null||si(e))=>({"*":[ii,RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)],...n?Object.fromEntries(ai.map(e=>[e,[oi]])):{}}),a={provider:n,baseURL:t,headers:r,generateId:e.generateId??T,fetch:e.fetch},o=e=>new X(e,{...a,supportedUrls:()=>i(e)}),s=()=>new Lt({provider:`${n.replace(/\.generative-ai$/,``)}.batch`,config:a,supportedUrls:i(void 0,!1)}),c=i=>new Ce(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),l=(i,a={})=>new Yt(i,a,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),u=()=>new Zt({provider:n,baseURL:t,headers:r,fetch:e.fetch}),d=i=>new un(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch,generateId:e.generateId??T}),f=i=>new jr(i,{provider:`${n}.realtime`,baseURL:t,headers:r,fetch:e.fetch}),p=i=>new Zr(i,{provider:`${n}.speech-translation`,baseURL:t,headers:r,webSocket:e.webSocket}),m=i=>new vn(i,{provider:`${n}.speech`,baseURL:t,headers:r,fetch:e.fetch}),h=i=>new Lr(i,{provider:`${n}.transcription`,baseURL:t,headers:r,fetch:e.fetch,webSocket:e.webSocket}),g=Object.assign(e=>f(e),{getToken:async e=>{let t=await f(e.model).doCreateClientSecret({sessionConfig:e.sessionConfig,expiresAfterSeconds:e.expiresAfterSeconds});return{token:t.token,url:t.url,expiresAt:t.expiresAt}}}),_=i=>new br(i,{provider:`${n}.interactions`,baseURL:t,headers:r,generateId:e.generateId??T,fetch:e.fetch}),v=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return o(e)};return v.specificationVersion=`v4`,v.languageModel=o,v.chat=o,v.generativeAI=o,v.evaluationModel=e=>new ve({model:o(e),provider:`${n.replace(/\.generative-ai$/,``)}.evaluation`}),v.experimental_batch=s,v.embedding=c,v.embeddingModel=c,v.textEmbedding=c,v.textEmbeddingModel=c,v.image=l,v.imageModel=l,v.video=d,v.videoModel=d,v.experimental_realtime=g,v.files=u,v.speech=m,v.speechModel=m,v.transcription=h,v.transcriptionModel=h,v.translation=p,v.speechTranslationModel=p,v.interactions=_,v.tools=Jt,v}var li=ci();export{jr as Experimental_GoogleRealtimeModel,Zr as Experimental_GoogleSpeechTranslationModel,Zr as Experimental_GoogleTranslationModel,Lr as GoogleTranscriptionModel,ye as VERSION,ci as createGoogle,ci as createGoogleGenerativeAI,li as google};