eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
6 lines (4 loc) • 107 kB
JavaScript
import{AISDKError as e,TooManyEmbeddingValuesForCallError as t,UnsupportedFunctionalityError as n}from"../provider/index.js";import{B as r,C as i,Ct as a,D as o,E as s,F as c,G as l,H as u,J as d,M as f,P as p,R as m,S as h,T as g,U as _,V as v,_t as y,a as b,bt as x,d as S,et as C,f as w,ft as T,g as E,gt as D,ht as O,it as k,j as A,k as ee,l as te,nt as j,o as ne,p as M,q as re,r as N,rt as P,s as F,st as I,tt as ie,ut as L,v as R,vt as z,w as B,wt as V,x as H,xt as U}from"../../_chunks/workflow/dist-C_VDTghO.js";var ae=`4.0.21`,W=w({errorSchema:A(()=>j(z({error:z({code:y().nullable(),message:U(),status:U()})}))),errorToMessage:e=>e.error.message}),oe=a([z({text:U()}),z({inlineData:z({mimeType:U(),data:U()})}),z({fileData:z({fileUri:U(),mimeType:U()})})]),se=A(()=>j(z({outputDimensionality:y().optional(),taskType:I([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:L(L(oe).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[k](e){return d({modelId:e.modelId,config:e.config})}static[P](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:i,providerOptions:a}){let o=await m({provider:`google`,providerOptions:a,schema:se});if(e.length>this.maxEmbeddingsPerCall)throw new t({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let s=N(this.config.headers?await v(this.config.headers):void 0,n),c=o?.content;if(c!=null&&c.length!==e.length)throw Error(`The number of multimodal content entries (${c.length}) must match the number of values (${e.length}).`);if(e.length===1){let t=c?.[0],n=e[0]?[{text:e[0]}]:[],a=t==null?[{text:e[0]}]:[...n,...t],{responseHeaders:l,value:u,rawValue:d}=await r({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:s,body:{model:`models/${this.modelId}`,content:{parts:a},outputDimensionality:o?.outputDimensionality,taskType:o?.taskType},failedResponseHandler:W,successfulResponseHandler:M(ue),abortSignal:i,fetch:this.config.fetch});return{warnings:[],embeddings:[u.embedding.values],usage:void 0,response:{headers:l,body:d}}}let{responseHeaders:l,value:u,rawValue:d}=await r({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:s,body:{requests:e.map((e,t)=>{let n=c?.[t],r=e?[{text:e}]:[];return{model:`models/${this.modelId}`,content:{role:`user`,parts:n==null?[{text:e}]:[...r,...n]},outputDimensionality:o?.outputDimensionality,taskType:o?.taskType}})},failedResponseHandler:W,successfulResponseHandler:M(le),abortSignal:i,fetch:this.config.fetch});return{warnings:[],embeddings:u.embeddings.map(e=>e.values),usage:void 0,response:{headers:l,body:d}}}},le=A(()=>j(z({embeddings:L(z({values:L(y())}))}))),ue=A(()=>j(z({embedding:z({values:L(y())})})));function de(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};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}}function G(e,t=!0){if(e==null)return;if(fe(e))return t?void 0:typeof e==`object`&&e.description?{type:`object`,description:e.description}:{type:`object`};if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:n,description:r,required:i,properties:a,items:o,allOf:s,anyOf:c,oneOf:l,format:u,const:d,minLength:f,enum:p}=e,m={};if(r&&(m.description=r),i&&(m.required=i),u&&(m.format=u),d!==void 0&&(m.enum=[d]),n)if(Array.isArray(n)){let e=n.includes(`null`),t=n.filter(e=>e!==`null`);t.length===0?m.type=`null`:(m.anyOf=t.map(e=>({type:e})),e&&(m.nullable=!0))}else m.type=n;if(p!==void 0&&(m.enum=p),a!=null&&(m.properties=Object.entries(a).reduce((e,[t,n])=>(e[t]=G(n,!1),e),{})),o&&(m.items=Array.isArray(o)?o.map(e=>G(e,!1)):G(o,!1)),s&&(m.allOf=s.map(e=>G(e,!1))),c)if(c.some(e=>typeof e==`object`&&e?.type===`null`)){let e=c.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=G(e[0],!1);typeof t==`object`&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(e=>G(e,!1)),m.nullable=!0}else m.anyOf=c.map(e=>G(e,!1));return l&&(m.oneOf=l.map(e=>G(e,!1))),f!==void 0&&(m.minLength=f),m}function fe(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var pe=`skip_thought_signature_validator`,me=/^data:([^;,]+);base64,(.+)$/s;function he(e){let t=me.exec(e);if(t!=null)return{mediaType:t[1],data:t[2]}}function ge(e){let t=he(e);if(t!=null)return{inlineData:{mimeType:t.mediaType,data:t.data}}}function _e(e,t,n,r){let i=[],a=[];for(let e of n)switch(e.type){case`text`:a.push(e.text);break;case`file`:if(e.data.type===`data`)i.push({inlineData:{mimeType:u({part:e}),data:F(e.data.data)}});else if(e.data.type===`url`){let t=ge(e.data.url.toString());t==null?a.push(JSON.stringify(e)):i.push(t)}else a.push(JSON.stringify(e));break;default:a.push(JSON.stringify(e));break}e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:a.length>0?a.join(`
`):`Tool executed successfully.`},...i.length>0?{parts:i}:{}}})}function ve(e,t,n,r){for(let i of n)switch(i.type){case`text`:e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:i.text}}});break;case`file`:if(i.data.type===`data`){let t=B(i.mediaType);e.push({inlineData:{mimeType:u({part:i}),data:F(i.data.data)}},{text:`Tool executed successfully and returned this ${t===`image`?`image`:`file`} as a response`})}else e.push({text:JSON.stringify(i)});break;default:e.push({text:JSON.stringify(i)});break}}function ye(e,t){let r=[],i=[],a=!0,s=t?.isGemmaModel??!1,c=t?.isGemini3Model??!1,l=t?.onWarning,d=t?.providerOptionsNames??[`google`],f=!d.includes(`google`),p=t?.supportsFunctionResponseParts??!0,m=!1,h=[],g=e=>(h.push(e),m=!0,pe),v=e=>{for(let t of d){let n=e.providerOptions?.[t];if(n!=null)return n}return f?e.providerOptions?.google:e.providerOptions?.googleVertex??e.providerOptions?.vertex};for(let{role:t,content:s}of e)switch(t){case`system`:if(!a)throw new n({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:s});break;case`user`:{a=!1;let e=[];for(let t of s)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:switch(t.data.type){case`url`:e.push({fileData:{mimeType:u({part:t}),fileUri:t.data.url.toString()}});break;case`reference`:if(f)throw new n({functionality:`file parts with provider references`});e.push({fileData:{mimeType:u({part:t}),fileUri:_({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:o(t.mediaType)?t.mediaType:`text/plain`,data:F(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:u({part:t}),data:F(t.data.data)}});break}break}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:s.map(e=>{let t=v(e),r=t?.thoughtSignature==null?void 0:String(t.thoughtSignature);switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:r};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:r};case`reasoning-file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`data`:return{inlineData:{mimeType:e.mediaType,data:F(e.data.data)},thought:!0,thoughtSignature:r}}break;case`file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`reference`:if(f)throw new n({functionality:`file parts with provider references`});return{fileData:{mimeType:e.mediaType,fileUri:_({reference:e.data.reference,provider:`google`})},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`text`:return{inlineData:{mimeType:o(e.mediaType)?e.mediaType:`text/plain`,data:F(new TextEncoder().encode(e.data.text))},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`data`:return{inlineData:{mimeType:e.mediaType,data:F(e.data.data)},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r}}break;case`tool-call`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType),a=r??(c?g(e.toolName):void 0);return n&&i?{toolCall:{toolType:i,args:typeof e.input==`string`?re(e.input):e.input,id:n},thoughtSignature:a}:{functionCall:{...e.toolCallId==null?{}:{id:e.toolCallId},name:e.toolName,args:e.input},thoughtSignature:a}}case`tool-result`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolResponse:{toolType:i,response:e.output.type===`json`?e.output.value:{},id:n},thoughtSignature:r}:void 0}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of s){if(t.type===`tool-approval-response`)continue;let n=v(t),r=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),a=n?.serverToolType==null?void 0:String(n.serverToolType);if(r&&a){let e=n?.thoughtSignature==null?void 0:String(n.thoughtSignature);if(i.length>0){let n=i[i.length-1];if(n.role===`model`){n.parts.push({toolResponse:{toolType:a,response:t.output.type===`json`?t.output.value:{},id:r},thoughtSignature:e});continue}}}let o=t.output;o.type===`content`?p?_e(e,t.toolName,o.value,t.toolCallId):ve(e,t.toolName,o.value,t.toolCallId):e.push({functionResponse:{...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}}})}i.push({role:`user`,parts:e});break}}if(s&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
`);i[0].parts.unshift({text:e+`
`})}if(m&&l!=null){let e=Array.from(new Set(h));l({type:`other`,message:`Replayed ${h.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:r.length>0&&!s?{parts:r}:void 0,contents:i}}function K(e){return e.includes(`/`)?e:`models/${e}`}var be=A(()=>j(z({responseModalities:L(I([`TEXT`,`IMAGE`])).optional(),thinkingConfig:z({thinkingBudget:y().optional(),includeThoughts:T().optional(),thinkingLevel:I([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:U().optional(),structuredOutputs:T().optional(),safetySettings:L(z({category:I([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:I([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:I([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:T().optional(),labels:x(U(),U()).optional(),mediaResolution:I([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:z({aspectRatio:I([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).optional(),imageSize:I([`1K`,`2K`,`4K`,`512`]).optional(),personGeneration:I([`PERSON_GENERATION_UNSPECIFIED`,`ALLOW_ALL`,`ALLOW_ADULT`,`ALLOW_NONE`]).optional(),prominentPeople:I([`PROMINENT_PEOPLE_UNSPECIFIED`,`ALLOW_PROMINENT_PEOPLE`,`BLOCK_PROMINENT_PEOPLE`]).optional(),imageOutputOptions:z({mimeType:I([`image/jpeg`,`image/png`]).optional(),compressionQuality:y().optional()}).optional()}).optional(),retrievalConfig:z({latLng:z({latitude:y(),longitude:y()}).optional()}).optional(),streamFunctionCallArguments:T().optional(),serviceTier:I([`standard`,`flex`,`priority`]).optional(),sharedRequestType:I([`priority`,`flex`,`standard`]).optional(),requestType:I([`shared`]).optional()})));function xe({tools:e,toolChoice:t,modelId:r,isVertexProvider:i=!1}){e=e?.length?e:void 0;let a=[],o=[`gemini-flash-latest`,`gemini-flash-lite-latest`,`gemini-pro-latest`].some(e=>e===r),s=r.includes(`gemini-2`)||r.includes(`gemini-3`)||r.includes(`nano-banana`)||o,c=r.includes(`gemini-3`),l=r.includes(`gemini-2.5`)||r.includes(`gemini-3`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:a};let u=e.some(e=>e.type===`function`),d=e.some(e=>e.type===`provider`);if(u&&d&&!c&&a.push({type:`unsupported`,feature:`combination of function and provider-defined tools`}),d){let n=[];if(e.filter(e=>e.type===`provider`).forEach(e=>{switch(e.id){case`google.google_search`:s?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`:s?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`:s?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`:s?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`:l?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`:s?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`:s?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}`});break}}),u&&c&&n.length>0){let r=[];for(let t of e)t.type===`function`&&r.push({name:t.name,description:t.description??``,parameters:G(t.inputSchema)});let o={functionCallingConfig:{mode:`VALIDATED`},...!i&&{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]};break}return{tools:[...n,{functionDeclarations:r}],toolConfig:o,toolWarnings:a}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:a}}let f=[],p=!1;for(let t of e)switch(t.type){case`function`:f.push({name:t.name,description:t.description??``,parameters:G(t.inputSchema)}),t.strict===!0&&(p=!0);break;default:a.push({type:`unsupported`,feature:`function tool ${t.name}`});break}if(t==null)return{tools:[{functionDeclarations:f}],toolConfig:p?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:a};let m=t.type;switch(m){case`auto`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`AUTO`}},toolWarnings:a};case`none`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:a};case`required`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`}},toolWarnings:a};case`tool`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:a};default:throw new n({functionality:`tool choice type: ${m}`})}}var Se=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=Ce(e),i=De(this.accumulatedArgs,r);if(n.stringValue!=null&&i!==void 0){let e=JSON.stringify(n.stringValue).slice(1,-1);Oe(this.accumulatedArgs,r,i+n.stringValue),t+=e;continue}let a=ke(n);a!=null&&(Oe(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 Ce(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 we=Object.prototype.hasOwnProperty;function Te(e,t){return we.call(e,t)}function Ee(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function De(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;let t=n;if(!Te(t,e))return;n=t[e]}return n}function Oe(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];(!Te(r,n)||r[n]==null)&&Ee(r,n,typeof i==`number`?[]:{}),r=r[n]}Ee(r,t[t.length-1],n)}function ke(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 Ae({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 je=[`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`],Me=class e{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??H}static[k](e){return d({modelId:e.modelId,config:e.config})}static[P](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)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,reasoning:f,providerOptions:p},{isStreaming:h=!1}={}){let g=[],_=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],v;for(let e of _)if(v=await m({provider:e,providerOptions:p,schema:be}),v!=null)break;v==null&&!_.includes(`google`)&&(v=await m({provider:`google`,providerOptions:p,schema:be}));let y=this.config.provider.startsWith(`google.vertex.`);u?.some(e=>e.type===`provider`&&e.id===`google.vertex_rag_store`)&&!y&&g.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 (${this.config.provider}).`}),v?.streamFunctionCallArguments&&!y&&g.push({type:`other`,message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`}),v?.serviceTier&&y&&g.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`}),(v?.sharedRequestType||v?.requestType)&&!y&&g.push({type:`other`,message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${this.config.provider}).`});let b=y&&(v?.sharedRequestType||v?.requestType)?{...v.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":v.sharedRequestType},...v.requestType&&{"X-Vertex-AI-LLM-Request-Type":v.requestType}}:void 0,x=y?void 0:v?.serviceTier,S=v?.imageConfig;if(S!=null&&!y){let{personGeneration:e,prominentPeople:t,imageOutputOptions:n,...r}=S,i=Object.entries({personGeneration:e,prominentPeople:t,imageOutputOptions:n}).filter(([,e])=>e!=null).map(([e])=>`'imageConfig.${e}'`);i.length>0&&(g.push({type:`other`,message:`${i.join(`, `)} ${i.length===1?`is a Vertex AI option and is`:`are Vertex AI options and are`} ignored with the current Google provider (${this.config.provider}).`}),S=r)}let C=this.modelId.toLowerCase().startsWith(`gemma-`),w=/^gemini-3[.-]/.test(this.modelId),{contents:T,systemInstruction:E}=ye(e,{isGemmaModel:C,isGemini3Model:w,onWarning:e=>g.push(e),providerOptionsNames:_,supportsFunctionResponseParts:w}),{tools:D,toolConfig:O,toolWarnings:k}=xe({tools:u,toolChoice:d,modelId:this.modelId,isVertexProvider:y}),A=Ie({reasoning:f,modelId:this.modelId,warnings:g}),ee=v?.thinkingConfig||A?{...A,...v?.thinkingConfig}:void 0,te=h&&y?v?.streamFunctionCallArguments??!1:void 0,j=v?.threshold,ne=v?.safetySettings??(j==null?void 0:je.map(e=>({category:e,threshold:j}))),M=O||te||v?.retrievalConfig?{...O,...te&&{functionCallingConfig:{...O?.functionCallingConfig,streamFunctionCallArguments:!0}},...v?.retrievalConfig&&{retrievalConfig:v.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(v?.structuredOutputs??!0)?G(c.schema):void 0,...v?.audioTimestamp&&{audioTimestamp:v.audioTimestamp},responseModalities:v?.responseModalities,thinkingConfig:ee,...v?.mediaResolution&&{mediaResolution:v.mediaResolution},...S&&{imageConfig:S}},contents:T,systemInstruction:C?void 0:E,safetySettings:ne,tools:D,toolConfig:M,cachedContent:v?.cachedContent,labels:v?.labels,serviceTier:x},warnings:[...g,...k],providerOptionsNames:_,extraHeaders:b}}async doGenerate(e){let{args:t,warnings:n,providerOptionsNames:i,extraHeaders:a}=await this.getArgs(e),o=e=>Object.fromEntries(i.map(t=>[t,e])),s=N(this.config.headers?await v(this.config.headers):void 0,e.headers,a),{responseHeaders:c,value:l,rawValue:u}=await r({url:`${this.config.baseURL}/${K(this.modelId)}:generateContent`,headers:s,body:t,failedResponseHandler:W,successfulResponseHandler:M(Ke),abortSignal:e.abortSignal,fetch:this.config.fetch}),d=l.candidates[0],f=[],p=d.content?.parts??[],m=l.usageMetadata,h,g;for(let e of p)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();h=t,f.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in e&&e.codeExecutionResult)f.push({type:`tool-result`,toolCallId:h,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output??``}});else if(`text`in e&&e.text!=null){let t=e.thoughtSignature?o({thoughtSignature:e.thoughtSignature}):void 0;if(e.text.length===0){if(t!=null&&f.length>0){let e=f[f.length-1];e.providerMetadata=t}}else f.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:t})}else if(`functionCall`in e&&e.functionCall.name!=null)f.push({type:`tool-call`,toolCallId:e.functionCall.id??this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args??{}),providerMetadata:e.thoughtSignature?o({thoughtSignature:e.thoughtSignature}):void 0});else if(`inlineData`in e){let t=e.thought===!0,n=!!e.thoughtSignature;f.push({type:t?`reasoning-file`:`file`,data:{type:`data`,data:e.inlineData.data},mediaType:e.inlineData.mimeType,providerMetadata:n?o({thoughtSignature:e.thoughtSignature}):void 0})}else if(`toolCall`in e&&e.toolCall){let t=e.toolCall.id??this.config.generateId();g=t,f.push({type:`tool-call`,toolCallId:t,toolName:`server:${e.toolCall.toolType}`,input:JSON.stringify(e.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:e.thoughtSignature?o({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolCall.toolType}):o({serverToolCallId:t,serverToolType:e.toolCall.toolType})})}else if(`toolResponse`in e&&e.toolResponse){let t=g??e.toolResponse.id??this.config.generateId();f.push({type:`tool-result`,toolCallId:t,toolName:`server:${e.toolResponse.toolType}`,result:e.toolResponse.response??{},providerMetadata:e.thoughtSignature?o({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolResponse.toolType}):o({serverToolCallId:t,serverToolType:e.toolResponse.toolType})}),g=void 0}let _=ze({groundingMetadata:d.groundingMetadata,generateId:this.config.generateId})??[];for(let e of _)f.push(e);return{content:f,finishReason:{unified:Ae({finishReason:d.finishReason,hasToolCalls:f.some(e=>e.type===`tool-call`&&!e.providerExecuted)}),raw:d.finishReason??void 0},usage:de(m),warnings:n,providerMetadata:o({promptFeedback:l.promptFeedback??null,groundingMetadata:d.groundingMetadata??null,urlContextMetadata:d.urlContextMetadata??null,safetyRatings:d.safetyRatings??null,usageMetadata:m??null,finishMessage:d.finishMessage??null,serviceTier:m?.serviceTier??null}),request:{body:t},response:{id:l.responseId??void 0,headers:c,body:u}}}async doStream(e){let{args:t,warnings:n,providerOptionsNames:i,extraHeaders:a}=await this.getArgs(e,{isStreaming:!0}),o=e=>Object.fromEntries(i.map(t=>[t,e])),s=N(this.config.headers?await v(this.config.headers):void 0,e.headers,a),{responseHeaders:c,value:l}=await r({url:`${this.config.baseURL}/${K(this.modelId)}:streamGenerateContent?alt=sse`,headers:s,body:t,failedResponseHandler:W,successfulResponseHandler:S(qe),abortSignal:e.abortSignal,fetch:this.config.fetch}),u={unified:`other`,raw:void 0},d,f,p=null,m=null,h=this.config.generateId,g=!1,_=!1,y=null,b=null,x=0,C=new Set,w,T,E=[],D=e=>{let t=E.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}),g=!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;!_&&r.responseId!=null&&(_=!0,n.enqueue({type:`response-metadata`,id:r.responseId}));let i=r.usageMetadata;i!=null&&(d=i);let a=r.candidates?.[0];if(a==null)return;let s=a.content;a.groundingMetadata!=null&&(p=a.groundingMetadata),a.urlContextMetadata!=null&&(m=a.urlContextMetadata);let c=ze({groundingMetadata:a.groundingMetadata,generateId:h});if(c!=null)for(let e of c)e.sourceType===`url`&&!C.has(e.url)&&(C.add(e.url),n.enqueue(e));if(s!=null){let e=s.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=h();w=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=w;e&&n.enqueue({type:`tool-result`,toolCallId:e,toolName:`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&&y!==null&&n.enqueue({type:`text-delta`,id:y,delta:``,providerMetadata:e}):t.thought===!0?(y!==null&&(n.enqueue({type:`text-end`,id:y}),y=null),b===null&&(b=String(x++),n.enqueue({type:`reasoning-start`,id:b,providerMetadata:e})),n.enqueue({type:`reasoning-delta`,id:b,delta:t.text,providerMetadata:e})):(b!==null&&(n.enqueue({type:`reasoning-end`,id:b}),b=null),y===null&&(y=String(x++),n.enqueue({type:`text-start`,id:y,providerMetadata:e})),n.enqueue({type:`text-delta`,id:y,delta:t.text,providerMetadata:e}))}else if(`inlineData`in t){y!==null&&(n.enqueue({type:`text-end`,id:y}),y=null),b!==null&&(n.enqueue({type:`reasoning-end`,id:b}),b=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??h();T=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=T??t.toolResponse.id??h(),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}),T=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??h(),i=new Se;if(E.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)&&D(n)}}else if(t.functionCall.partialArgs!=null&&E.length>0){let r=E[E.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)&&D(n)}}else if(i&&E.length>0)D(n);else if(a){let r=t.functionCall.id??h(),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}),g=!0}else if(s){let r=t.functionCall.id??h(),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}),g=!0}}}a.finishReason!=null&&(u={unified:Ae({finishReason:a.finishReason,hasToolCalls:g}),raw:a.finishReason},f=o({promptFeedback:r.promptFeedback??null,groundingMetadata:p,urlContextMetadata:m,safetyRatings:a.safetyRatings??null,usageMetadata:i??null,finishMessage:a.finishMessage??null,serviceTier:d?.serviceTier??null}))},flush(e){y!==null&&e.enqueue({type:`text-end`,id:y}),b!==null&&e.enqueue({type:`reasoning-end`,id:b}),e.enqueue({type:`finish`,finishReason:u,usage:de(d),providerMetadata:f})}})),response:{headers:c},request:{body:t}}}};function Ne(e){return/gemini-3[\.\-]/i.test(e)||/gemini-3$/i.test(e)}function Pe(){return 65536}function Fe(e){let t=e.toLowerCase();return t.includes(`2.5-pro`)||t.includes(`gemini-3-pro-image`)?32768:24576}function Ie({reasoning:e,modelId:t,warnings:n}){if(s(e))return Ne(t)&&!t.includes(`gemini-3-pro-image`)?Le({reasoning:e,warnings:n}):Re({reasoning:e,modelId:t,warnings:n})}function Le({reasoning:e,warnings:t}){if(e===`none`)return{thinkingLevel:`minimal`};let n=c({reasoning:e,effortMap:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`high`},warnings:t});if(n!=null)return{thinkingLevel:n}}function Re({reasoning:e,modelId:t,warnings:n}){if(e===`none`)return{thinkingBudget:0};let r=p({reasoning:e,maxOutputTokens:Pe(),maxReasoningBudget:Fe(t),minReasoningBudget:0,warnings:n});if(r!=null)return{thinkingBudget:r}}function ze({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 Be=()=>z({webSearchQueries:L(U()).nullish(),imageSearchQueries:L(U()).nullish(),retrievalQueries:L(U()).nullish(),searchEntryPoint:z({renderedContent:U()}).nullish(),groundingChunks:L(z({web:z({uri:U(),title:U().nullish()}).nullish(),image:z({sourceUri:U(),imageUri:U(),title:U().nullish(),domain:U().nullish()}).nullish(),retrievedContext:z({uri:U().nullish(),title:U().nullish(),text:U().nullish(),fileSearchStore:U().nullish()}).nullish(),maps:z({uri:U().nullish(),title:U().nullish(),text:U().nullish(),placeId:U().nullish()}).nullish()})).nullish(),groundingSupports:L(z({segment:z({startIndex:y().nullish(),endIndex:y().nullish(),text:U().nullish()}).nullish(),segment_text:U().nullish(),groundingChunkIndices:L(y()).nullish(),supportChunkIndices:L(y()).nullish(),confidenceScores:L(y()).nullish(),confidenceScore:L(y()).nullish()})).nullish(),retrievalMetadata:a([z({webDynamicRetrievalScore:y()}),z({})]).nullish()}),Ve=z({jsonPath:U(),stringValue:U().nullish(),numberValue:y().nullish(),boolValue:T().nullish(),nullValue:V().nullish(),willContinue:T().nullish()}),He=()=>z({parts:L(a([z({functionCall:z({id:U().nullish(),name:U().nullish(),args:V().nullish(),partialArgs:L(Ve).nullish(),willContinue:T().nullish()}),thoughtSignature:U().nullish()}),z({inlineData:z({mimeType:U(),data:U()}),thought:T().nullish(),thoughtSignature:U().nullish()}),z({toolCall:z({toolType:U(),args:V().nullish(),id:U()}),thoughtSignature:U().nullish()}),z({toolResponse:z({toolType:U(),response:V().nullish(),id:U()}),thoughtSignature:U().nullish()}),z({executableCode:z({language:U(),code:U()}).nullish(),codeExecutionResult:z({outcome:U(),output:U().nullish()}).nullish(),text:U().nullish(),thought:T().nullish(),thoughtSignature:U().nullish()})])).nullish()}),q=()=>z({category:U().nullish(),probability:U().nullish(),probabilityScore:y().nullish(),severity:U().nullish(),severityScore:y().nullish(),blocked:T().nullish()}),Ue=L(z({modality:U(),tokenCount:y()})).nullish(),We=z({cachedContentTokenCount:y().nullish(),thoughtsTokenCount:y().nullish(),promptTokenCount:y().nullish(),candidatesTokenCount:y().nullish(),totalTokenCount:y().nullish(),trafficType:U().nullish(),serviceTier:U().nullish(),promptTokensDetails:Ue,candidatesTokensDetails:Ue}),Ge=()=>z({urlMetadata:L(z({retrievedUrl:U(),urlRetrievalStatus:U()})).nullish()}),Ke=A(()=>j(z({responseId:U().nullish(),candidates:L(z({content:He().nullish().or(z({}).strict()),finishReason:U().nullish(),finishMessage:U().nullish(),safetyRatings:L(q()).nullish(),groundingMetadata:Be().nullish(),urlContextMetadata:Ge().nullish()})),usageMetadata:We.nullish(),promptFeedback:z({blockReason:U().nullish(),safetyRatings:L(q()).nullish()}).nullish()}))),qe=A(()=>j(z({responseId:U().nullish(),candidates:L(z({content:He().nullish(),finishReason:U().nullish(),finishMessage:U().nullish(),safetyRatings:L(q()).nullish(),groundingMetadata:Be().nullish(),urlContextMetadata:Ge().nullish()})).nullish(),usageMetadata:We.nullish(),promptFeedback:z({blockReason:U().nullish(),safetyRatings:L(q()).nullish()}).nullish()}))),Je=E({id:`google.code_execution`,inputSchema:z({language:U().describe(`The programming language of the code.`),code:U().describe(`The code to be executed.`)}),outputSchema:z({outcome:U().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:U().describe(`The output from the code execution.`)})}),Ye=E({id:`google.enterprise_web_search`,inputSchema:A(()=>j(z({}))),outputSchema:A(()=>j(z({})))});D({fileSearchStoreNames:L(U()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:y().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:U().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 Xe=E({id:`google.file_search`,inputSchema:A(()=>j(z({}))),outputSchema:A(()=>j(z({})))}),Ze=E({id:`google.google_maps`,inputSchema:A(()=>j(z({}))),outputSchema:A(()=>j(z({})))}),Qe=D({searchTypes:z({webSearch:z({}).optional(),imageSearch:z({}).optional()}).optional(),timeRangeFilter:z({startTime:U(),endTime:U()}).optional()}),$e={googleSearch:E({id:`google.google_search`,inputSchema:A(()=>j(z({}))),outputSchema:A(()=>j(z({})))}),enterpriseWebSearch:Ye,googleMaps:Ze,urlContext:E({id:`google.url_context`,inputSchema:A(()=>j(z({}))),outputSchema:A(()=>j(z({})))}),fileSearch:Xe,codeExecution:Je,vertexRagStore:E({id:`google.vertex_rag_store`,inputSchema:A(()=>j(z({}))),outputSchema:A(()=>j(z({})))})},et=A(()=>j(z({personGeneration:I([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:I([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish(),googleSearch:Qe.optional()}))),tt=class e{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v4`}static[k](e){return d({modelId:e.modelId,config:e.config})}static[P](t){return new e(t.modelId,{},t.config)}get maxImagesPerCall(){return this.settings.maxImagesPerCall==null?nt(this.modelId)?10:4:this.settings.maxImagesPerCall}get provider(){return this.config.provider}async doGenerate(e){return nt(this.modelId)?this.doGenerateGemini(e):this.doGenerateImagen(e)}async doGenerateImagen(e){var t;let{prompt:n,n:i=1,size:a,aspectRatio:o=`1:1`,seed:s,providerOptions:c,headers:l,abortSignal:u,files:d,mask:f}=e,p=[];if(d!=null&&d.length>0)throw Error(`Google Gemini API does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);if(f!=null)throw Error(`Google Gemini API does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);a!=null&&p.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),s!=null&&p.push({type:`unsupported`,feature:`seed`,details:"This model does not support the `seed` option through this provider."});let h=await m({provider:`google`,providerOptions:c,schema:et}),g=((t=this.config._internal)?.currentDate)?.call(t)??new Date,_={sampleCount:i};if(o!=null&&(_.aspectRatio=o),h){let{googleSearch:e,...t}=h;e!=null&&p.push({type:`unsupported`,feature:`googleSearch`,details:`Google Search grounding is only supported on Gemini image models.`}),Object.assign(_,t)}let y={instances:[{prompt:n}],parameters:_},{responseHeaders:b,value:x}=await r({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:N(this.config.headers?await v(this.config.headers):void 0,l),body:y,failedResponseHandler:W,successfulResponseHandler:M(rt),abortSignal:u,fetch:this.config.fetch});return{images:x.predictions.map(e=>e.bytesBase64Encoded),warnings:p,providerMetadata:{google:{images:x.predictions.map(()=>({}))}},response:{timestamp:g,modelId:this.modelId,headers:b}}}async doGenerateGemini(e){var t;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 h=[{role:`user`,content:p}],g=await m({provider:`google`,providerOptions:s,schema:et}),{googleSearch:_,...v}=s?.google??{},y=await new Me(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??H}).doGenerate({prompt:h,seed:o,providerOptions:{google:{responseModalities:[`IMAGE`],imageConfig:a?{aspectRatio:a}:void 0,...v}},tools:g?.googleSearch==null?void 0:[{type:`provider`,id:`google.google_search`,name:`google_search`,args:g.googleSearch}],headers:c,abortSignal:l}),b=((t=this.config._internal)?.currentDate)?.call(t)??new Date,x=[];for(let e of y.content)e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`&&x.push(F(e.data.data));return{images:x,warnings:f,providerMetadata:{google:{...y.providerMetadata?.google??{},images:x.map(()=>({}))}},response:{timestamp:b,modelId:this.modelId,headers:y.response?.headers},usage:y.usage?{inputTokens:y.usage.inputTokens.total,outputTokens:y.usage.outputTokens.total,totalTokens:(y.usage.inputTokens.total??0)+(y.usage.outputTokens.total??0)}:void 0}}};function nt(e){return e.startsWith(`gemini-`)}var rt=A(()=>j(z({predictions:L(z({bytesBase64Encoded:U()})).default([])}))),it=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(t){let n=await m({provider:`google`,providerOptions:t.providerOptions,schema:ot}),r=this.config.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}}})});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:{"Content-Length":String(o.length),"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:o});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,g=n?.pollTimeoutMs??3e5,_=Date.now();for(;f.state===`PROCESSING`;){if(Date.now()-_>g)throw new e({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${g}ms`});await R(p);let{value:t}=await h({url:`${this.config.baseURL}/${f.name}`,validateUrl:!1,headers:N(r),successfulResponseHandler:M(at),failedResponseHandler:W,fetch:this.config.fetch});f=t}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}}}}}},at=A(()=>j(z({name:U(),displayName:U().nullish(),mimeType:U(),sizeBytes:U().nullish(),createTime:U().nullish(),updateTime:U().nullish(),expirationTime:U().nullish(),sha256Hash:U().nullish(),uri:U(),state:U()}))),ot=A(()=>j(D({displayName:U().nullish(),pollIntervalMs:y().positive().nullish(),pollTimeoutMs:y().positive().nullish()}))),st=A(()=>j(D({pollIntervalMs:y().positive().nullish(),pollTimeoutMs:y().positive().nullish(),personGeneration:I([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:U().nullish(),referenceImages:L(z({bytesBase64Encoded:U().nullish(),gcsUri:U().nullish()})).nullish()})));function ct(e){return e.frameImages?.find(e=>e.frameType===`first_frame`)?.image}function lt(e){return ct(e)??e.image}function ut(e){return e.frameImages?.find(e=>e.frameType===`last_frame`)?.image}function dt(e){if(!(e.frameImages!=null&&e.frameImages.length>0))return e.inputReferences!=null&&e.inputReferences.length>0?e.inputReferences:void 0}function J(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:te(e.data),mimeType:e.mediaType||`image/png`}}function ft(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 pt(e,t){let n=J(e,t);return n==null?void 0:{image:n,referenceType:`asset`}}var mt=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async doGenerate(t){var n;let i=((n=this.config._internal)?.currentDate)?.call(n)??new Date,a=[],o=await m({provider:`google`,providerOptions:t.providerOptions,schema:st}),s=[{}],c=s[0];t.prompt!=null&&(c.prompt=t.prompt);let l=lt(t);if(l!=null){let e=J(l,a);e!=null&&(c.image=e)}let u=ut(t);if(u!=null){let e=J(u,a);e!=null&&(c.lastFrame=e)}let d=dt(t);d==null?o?.referenceImages!=null&&(c.referenceImages=o.referenceImages.map(e=>ft(e))):c.referenceImages=d.flatMap(e=>{let t=pt(e,a);return t==null?[]:[t]});let f={sampleCount:t.n};if(t.aspectRatio&&(f.aspectRatio=t.aspectRatio),t.resolution&&(f.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[t.resolution]||t.resolution),t.duration&&(f.durationSeconds=t.duration),t.seed&&(f.seed=t.seed),o!=null){let e=o;e.personGeneration!==void 0&&e.personGeneration!==null&&(f.personGeneration=e.personGeneration),e.negativePr