bunqueue-dashboard 0.0.30 → 0.0.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent/db.ts +178 -40
- package/agent/dbQueryWorker.ts +14 -6
- package/agent/index.ts +4 -1
- package/agent/manager.ts +97 -12
- package/agent/server.ts +11 -5
- package/dist/.vite/manifest.json +200 -151
- package/dist/assets/AddJob-Dvpp--yq.js +3 -0
- package/dist/assets/{Alerts-GhRfE6uG.js → Alerts-CR9jgCCs.js} +1 -1
- package/dist/assets/{AreaChart-Dl_9G6GH.js → AreaChart-2gM0YoZT.js} +1 -1
- package/dist/assets/Benchmark-CkL-Ee-M.js +1 -0
- package/dist/assets/BulkAddJobs-wI6cRZnX.js +5 -0
- package/dist/assets/CopilotPanel-DPZV9opm.js +44 -0
- package/dist/assets/{Cron-BqKxXt_G.js → Cron-gWVkYWad.js} +1 -1
- package/dist/assets/CronManager-BvfW219u.js +1 -0
- package/dist/assets/Database-D2T_ZIGA.js +3 -0
- package/dist/assets/Diagnostics-C2goqq5h.js +1 -0
- package/dist/assets/Dlq-Q4TmmZrK.js +1 -0
- package/dist/assets/{DlqControl-B0VILOwI.js → DlqControl-C5BfE7Gq.js} +1 -1
- package/dist/assets/{DlqPro-D8POex8v.js → DlqPro-ClPNmw-X.js} +1 -1
- package/dist/assets/Flows-DbhMbvSG.js +1 -0
- package/dist/assets/JobInspector-CO_zKjSX.js +2 -0
- package/dist/assets/Jobs-D2rDHPM_.js +1 -0
- package/dist/assets/JobsPro-Drdgdj3s.js +1 -0
- package/dist/assets/Logs-DjwGuRLi.js +1 -0
- package/dist/assets/LogsPro-7uTBjPWX.js +1 -0
- package/dist/assets/{McpServer-CI9Z61Lm.js → McpServer-DAklQDB5.js} +1 -1
- package/dist/assets/{Metrics-qsVJt17r.js → Metrics-Dup9Zinh.js} +1 -1
- package/dist/assets/{MetricsPro-BMNObO4L.js → MetricsPro-PP3TymeP.js} +1 -1
- package/dist/assets/Overview-C7RCDE6r.js +1 -0
- package/dist/assets/{Pagination-EJ2HGoqv.js → Pagination-B9JDi5MI.js} +1 -1
- package/dist/assets/QueueActions-DJTw0h2g.js +1 -0
- package/dist/assets/{QueueControl-2NXIrJqi.js → QueueControl-CxKjUjF-.js} +1 -1
- package/dist/assets/{QueueDetail-7EEYk51J.js → QueueDetail-bf2n-r2h.js} +1 -1
- package/dist/assets/{QueueDetailPro-DDB6mrh6.js → QueueDetailPro-C-XLWFBa.js} +1 -1
- package/dist/assets/Queues-CMQW89J9.js +1 -0
- package/dist/assets/{QueuesOverview-CzbHoeuS.js → QueuesOverview-x7-akDzf.js} +1 -1
- package/dist/assets/{S3Backup-ETwjL2TD.js → S3Backup-1jAySC9R.js} +1 -1
- package/dist/assets/{S3BackupPro-DwX9b_1u.js → S3BackupPro-BG_0OHW7.js} +1 -1
- package/dist/assets/{ServerControl-BOh2ncLo.js → ServerControl-DohTB--h.js} +3 -3
- package/dist/assets/{Settings-_aPq2yDv.js → Settings-CnS5PjNe.js} +1 -1
- package/dist/assets/Usage-C3H0hMSA.js +1 -0
- package/dist/assets/{UsagePro-Dv0izJVc.js → UsagePro-CdnQkP9o.js} +1 -1
- package/dist/assets/Webhooks-CAwVmIEZ.js +1 -0
- package/dist/assets/{Workers-CXwdSXup.js → Workers-lvujKZwF.js} +1 -1
- package/dist/assets/{WorkersPro-BBnrgBbn.js → WorkersPro-CIJKl7U1.js} +1 -1
- package/dist/assets/{connectionStore-B-hNUqwK.js → connectionStore-DO6xQY7h.js} +1 -1
- package/dist/assets/dist-1f1fMHVO.js +11 -0
- package/dist/assets/dist-BlWBaCN6.js +11 -0
- package/dist/assets/dist-DZL8soAh.js +79 -0
- package/dist/assets/dist-DjvZiKhB.js +2 -0
- package/dist/assets/dist-DpZcbP9W.js +11 -0
- package/dist/assets/{exportFile-tdUeW5m5.js → exportFile-C7xhE8Yh.js} +1 -1
- package/dist/assets/{form-C-zZyKfB.js → form-DGinTEEb.js} +1 -1
- package/dist/assets/index-DcVOpnSj.css +1 -0
- package/dist/assets/index-r1ZMLIZ9.js +8 -0
- package/dist/assets/{install-DhTYJCUC.js → install-BIVfix28.js} +1 -1
- package/dist/assets/{react-vendor-B68RYDeC.js → react-vendor-BcouBxpZ.js} +2 -2
- package/dist/assets/useThroughputSeries-CVKzWzdv.js +1 -0
- package/dist/index.html +4 -4
- package/package.json +5 -5
- package/scripts/embedded.gen.ts +122 -112
- package/scripts/serve.ts +300 -88
- package/dist/assets/AddJob-Bsc2w6F0.js +0 -3
- package/dist/assets/Benchmark-Bc_ZEM87.js +0 -1
- package/dist/assets/BulkAddJobs-B9q81JAq.js +0 -5
- package/dist/assets/CopilotPanel-DL61f5jW.js +0 -152
- package/dist/assets/CronManager-DuWur13m.js +0 -1
- package/dist/assets/Database-DSpCA3w7.js +0 -3
- package/dist/assets/Diagnostics-DsBFg_-t.js +0 -1
- package/dist/assets/Dlq-BAQfqBgy.js +0 -1
- package/dist/assets/Flows-BEafLVu_.js +0 -1
- package/dist/assets/JobInspector-Du4zhHVo.js +0 -2
- package/dist/assets/Jobs-9VzulNrm.js +0 -1
- package/dist/assets/JobsPro-YebB40C-.js +0 -1
- package/dist/assets/Logs-DtV3k05m.js +0 -1
- package/dist/assets/LogsPro-C9VmsZL-.js +0 -1
- package/dist/assets/Overview-DtVeV_uf.js +0 -1
- package/dist/assets/QueueActions-qd4d3da3.js +0 -1
- package/dist/assets/Queues-ClEE2_8g.js +0 -1
- package/dist/assets/Usage-B6ESpkgj.js +0 -1
- package/dist/assets/Webhooks-Cs-DqyhB.js +0 -1
- package/dist/assets/index-BFRKPhvf.js +0 -8
- package/dist/assets/index-mF63w920.css +0 -1
- package/dist/assets/useThroughputSeries-BzUriOcf.js +0 -1
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{$ as e,A as t,Bt as n,C as r,Ct as i,Ft as a,Gt as o,I as s,K as c,Lt as l,M as u,Mt as d,Nt as f,Ot as p,P as m,R as h,Rt as g,U as _,V as v,W as y,Z as b,_ as x,_t as S,c as C,ct as w,d as T,gt as E,h as D,ht as O,it as k,j as ee,jt as A,k as j,kt as M,l as te,lt as N,mt as ne,nt as P,ot as re,p as ie,pt as ae,q as oe,qt as F,rt as I,u as se,v as L,wt as R,x as z,yt as B}from"./dist-DZL8soAh.js";var ce=`4.0.8`,V=x({errorSchema:_(()=>O(d({error:d({code:A().nullable(),message:a(),status:a()})}))),errorToMessage:e=>e.error.message}),le=l([d({text:a()}),d({inlineData:d({mimeType:a(),data:a()})}),d({fileData:d({fileUri:a(),mimeType:a()})})]),ue=_(()=>O(d({outputDimensionality:A().optional(),taskType:B([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:i(i(le).min(1).nullable()).optional()}))),de=class t{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=100,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}static[S](e){return N({modelId:e.modelId,config:e.config})}static[E](e){return new t(e.modelId,e.config)}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:i}){let a=await b({provider:`google`,providerOptions:i,schema:ue});if(t.length>this.maxEmbeddingsPerCall)throw new o({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let s=C(this.config.headers?await P(this.config.headers):void 0,n),c=a?.content;if(c!=null&&c.length!==t.length)throw Error(`The number of multimodal content entries (${c.length}) must match the number of values (${t.length}).`);if(t.length===1){let n=c?.[0],i=t[0]?[{text:t[0]}]:[],o=n==null?[{text:t[0]}]:[...i,...n],{responseHeaders:l,value:u,rawValue:d}=await e({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:s,body:{model:`models/${this.modelId}`,content:{parts:o},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:V,successfulResponseHandler:L(pe),abortSignal:r,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 e({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:s,body:{requests:t.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:a?.outputDimensionality,taskType:a?.taskType}})},failedResponseHandler:V,successfulResponseHandler:L(fe),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:u.embeddings.map(e=>e.values),usage:void 0,response:{headers:l,body:d}}}},fe=_(()=>O(d({embeddings:i(d({values:i(A())}))}))),pe=_(()=>O(d({embedding:d({values:i(A())})})));function me(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 H(e,t=!0){if(e==null)return;if(he(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]=H(n,!1),e),{})),o&&(m.items=Array.isArray(o)?o.map(e=>H(e,!1)):H(o,!1)),s&&(m.allOf=s.map(e=>H(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=H(e[0],!1);typeof t==`object`&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(e=>H(e,!1)),m.nullable=!0}else m.anyOf=c.map(e=>H(e,!1));return l&&(m.oneOf=l.map(e=>H(e,!1))),f!==void 0&&(m.minLength=f),m}function he(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var ge=`skip_thought_signature_validator`,_e=/^data:([^;,]+);base64,(.+)$/s;function ve(e){let t=_e.exec(e);if(t!=null)return{mediaType:t[1],data:t[2]}}function ye(e){let t=ve(e);if(t!=null)return{inlineData:{mimeType:t.mediaType,data:t.data}}}function be(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:I({part:e}),data:T(e.data.data)}});else if(e.data.type===`url`){let t=ye(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(`
|
|
2
|
+
`):`Tool executed successfully.`},...i.length>0?{parts:i}:{}}})}function xe(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`:i.data.type===`data`&&u(i.mediaType)===`image`?e.push({inlineData:{mimeType:I({part:i}),data:T(i.data.data)}},{text:`Tool executed successfully and returned this image as a response`}):e.push({text:JSON.stringify(i)});break;default:e.push({text:JSON.stringify(i)});break}}function Se(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1,o=t?.isGemini3Model??!1,s=t?.onWarning,c=t?.providerOptionsNames??[`google`],l=!c.includes(`google`),u=t?.supportsFunctionResponseParts??!0,d=!1,f=[],p=e=>(f.push(e),d=!0,ge),m=e=>{for(let t of c){let n=e.providerOptions?.[t];if(n!=null)return n}return l?e.providerOptions?.google:e.providerOptions?.googleVertex??e.providerOptions?.vertex};for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new F({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)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(l)throw new F({functionality:`file parts with provider references`});e.push({fileData:{mimeType:I({part:t}),fileUri:k({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:h(t.mediaType)?t.mediaType:`text/plain`,data:T(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:I({part:t}),data:T(t.data.data)}});break}break}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{let t=m(e),n=t?.thoughtSignature==null?void 0:String(t.thoughtSignature);switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:n};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:n};case`reasoning-file`:switch(e.data.type){case`url`:throw new F({functionality:`File data URLs in assistant messages are not supported`});case`data`:return{inlineData:{mimeType:e.mediaType,data:T(e.data.data)},thought:!0,thoughtSignature:n}}break;case`file`:switch(e.data.type){case`url`:throw new F({functionality:`File data URLs in assistant messages are not supported`});case`reference`:if(l)throw new F({functionality:`file parts with provider references`});return{fileData:{mimeType:e.mediaType,fileUri:k({reference:e.data.reference,provider:`google`})},...t?.thought===!0?{thought:!0}:{},thoughtSignature:n};case`text`:return{inlineData:{mimeType:h(e.mediaType)?e.mediaType:`text/plain`,data:T(new TextEncoder().encode(e.data.text))},...t?.thought===!0?{thought:!0}:{},thoughtSignature:n};case`data`:return{inlineData:{mimeType:e.mediaType,data:T(e.data.data)},...t?.thought===!0?{thought:!0}:{},thoughtSignature:n}}break;case`tool-call`:{let r=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType),a=n??(o?p(e.toolName):void 0);return r&&i?{toolCall:{toolType:i,args:typeof e.input==`string`?w(e.input):e.input,id:r},thoughtSignature:a}:{functionCall:{...e.toolCallId==null?{}:{id:e.toolCallId},name:e.toolName,args:e.input},thoughtSignature:a}}case`tool-result`:{let r=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return r&&i?{toolResponse:{toolType:i,response:e.output.type===`json`?e.output.value:{},id:r},thoughtSignature:n}:void 0}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){if(t.type===`tool-approval-response`)continue;let n=m(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`?u?be(e,t.toolName,o.value,t.toolCallId):xe(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}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
|
|
3
|
+
|
|
4
|
+
`);r[0].parts.unshift({text:e+`
|
|
5
|
+
|
|
6
|
+
`})}if(d&&s!=null){let e=Array.from(new Set(f));s({type:`other`,message:`Replayed ${f.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&&!a?{parts:n}:void 0,contents:r}}function Ce(e){return e.includes(`/`)?e:`models/${e}`}var we=_(()=>O(d({responseModalities:i(B([`TEXT`,`IMAGE`])).optional(),thinkingConfig:d({thinkingBudget:A().optional(),includeThoughts:R().optional(),thinkingLevel:B([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:a().optional(),structuredOutputs:R().optional(),safetySettings:i(d({category:B([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:B([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:B([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:R().optional(),labels:f(a(),a()).optional(),mediaResolution:B([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:d({aspectRatio:B([`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:B([`1K`,`2K`,`4K`,`512`]).optional()}).optional(),retrievalConfig:d({latLng:d({latitude:A(),longitude:A()}).optional()}).optional(),streamFunctionCallArguments:R().optional(),serviceTier:B([`standard`,`flex`,`priority`]).optional(),sharedRequestType:B([`priority`,`flex`,`standard`]).optional(),requestType:B([`shared`]).optional()})));function Te({tools:e,toolChoice:t,modelId:n,isVertexProvider:r=!1}){e=e?.length?e:void 0;let i=[],a=[`gemini-flash-latest`,`gemini-flash-lite-latest`,`gemini-pro-latest`].some(e=>e===n),o=n.includes(`gemini-2`)||n.includes(`gemini-3`)||n.includes(`nano-banana`)||a,s=n.includes(`gemini-3`),c=n.includes(`gemini-2.5`)||n.includes(`gemini-3`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:i};let l=e.some(e=>e.type===`function`),u=e.some(e=>e.type===`provider`);if(l&&u&&!s&&i.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}}):i.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:{}}):i.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:{}}):i.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:{}}):i.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`:c?n.push({fileSearch:{...e.args}}):i.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}}}):i.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:{}}):i.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:i.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`});break}}),l&&s&&n.length>0){let a=[];for(let t of e)t.type===`function`&&a.push({name:t.name,description:t.description??``,parameters:H(t.inputSchema)});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]};break}return{tools:[...n,{functionDeclarations:a}],toolConfig:o,toolWarnings:i}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:i}}let d=[],f=!1;for(let t of e)switch(t.type){case`function`:d.push({name:t.name,description:t.description??``,parameters:H(t.inputSchema)}),t.strict===!0&&(f=!0);break;default:i.push({type:`unsupported`,feature:`function tool ${t.name}`});break}if(t==null)return{tools:[{functionDeclarations:d}],toolConfig:f?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:i};let p=t.type;switch(p){case`auto`:return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:f?`VALIDATED`:`AUTO`}},toolWarnings:i};case`none`:return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:i};case`required`:return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:f?`VALIDATED`:`ANY`}},toolWarnings:i};case`tool`:return{tools:[{functionDeclarations:d}],toolConfig:{functionCallingConfig:{mode:f?`VALIDATED`:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:i};default:throw new F({functionality:`tool choice type: ${p}`})}}var Ee=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=De(e),i=je(this.accumulatedArgs,r);if(n.stringValue!=null&&i!==void 0){let e=JSON.stringify(n.stringValue).slice(1,-1);Me(this.accumulatedArgs,r,i+n.stringValue),t+=e;continue}let a=Ne(n);a!=null&&(Me(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 De(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 Oe=Object.prototype.hasOwnProperty;function ke(e,t){return Oe.call(e,t)}function Ae(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function je(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;let t=n;if(!ke(t,e))return;n=t[e]}return n}function Me(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];(!ke(r,n)||r[n]==null)&&Ae(r,n,typeof i==`number`?[]:{}),r=r[n]}Ae(r,t[t.length-1],n)}function Ne(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 Pe({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 Fe=class t{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??j}static[S](e){return N({modelId:e.modelId,config:e.config})}static[E](e){return new t(e.modelId,e.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:m=!1}={}){let h=[],g=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],_;for(let e of g)if(_=await b({provider:e,providerOptions:p,schema:we}),_!=null)break;_==null&&!g.includes(`google`)&&(_=await b({provider:`google`,providerOptions:p,schema:we}));let v=this.config.provider.startsWith(`google.vertex.`);u?.some(e=>e.type===`provider`&&e.id===`google.vertex_rag_store`)&&!v&&h.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}).`}),_?.streamFunctionCallArguments&&!v&&h.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`}),_?.serviceTier&&v&&h.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`}),(_?.sharedRequestType||_?.requestType)&&!v&&h.push({type:`other`,message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${this.config.provider}).`});let y=v&&(_?.sharedRequestType||_?.requestType)?{..._.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":_.sharedRequestType},..._.requestType&&{"X-Vertex-AI-LLM-Request-Type":_.requestType}}:void 0,x=v?void 0:_?.serviceTier,S=this.modelId.toLowerCase().startsWith(`gemma-`),C=/^gemini-3[.-]/.test(this.modelId),{contents:w,systemInstruction:T}=Se(e,{isGemmaModel:S,isGemini3Model:C,onWarning:e=>h.push(e),providerOptionsNames:g,supportsFunctionResponseParts:C}),{tools:E,toolConfig:D,toolWarnings:O}=Te({tools:u,toolChoice:d,modelId:this.modelId,isVertexProvider:v}),k=ze({reasoning:f,modelId:this.modelId,warnings:h}),ee=_?.thinkingConfig||k?{...k,..._?.thinkingConfig}:void 0,A=m&&v?_?.streamFunctionCallArguments??!1:void 0,j=D||A||_?.retrievalConfig?{...D,...A&&{functionCallingConfig:{...D?.functionCallingConfig,streamFunctionCallArguments:!0}},..._?.retrievalConfig&&{retrievalConfig:_.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&&(_?.structuredOutputs??!0)?H(c.schema):void 0,..._?.audioTimestamp&&{audioTimestamp:_.audioTimestamp},responseModalities:_?.responseModalities,thinkingConfig:ee,..._?.mediaResolution&&{mediaResolution:_.mediaResolution},..._?.imageConfig&&{imageConfig:_.imageConfig}},contents:w,systemInstruction:S?void 0:T,safetySettings:_?.safetySettings,tools:E,toolConfig:j,cachedContent:_?.cachedContent,labels:_?.labels,serviceTier:x},warnings:[...h,...O],providerOptionsNames:g,extraHeaders:y}}async doGenerate(t){let{args:n,warnings:r,providerOptionsNames:i,extraHeaders:a}=await this.getArgs(t),o=e=>Object.fromEntries(i.map(t=>[t,e])),s=C(this.config.headers?await P(this.config.headers):void 0,t.headers,a),{responseHeaders:c,value:l,rawValue:u}=await e({url:`${this.config.baseURL}/${Ce(this.modelId)}:generateContent`,headers:s,body:n,failedResponseHandler:V,successfulResponseHandler:L(Ye),abortSignal:t.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??``}}),h=void 0;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 _=He({groundingMetadata:d.groundingMetadata,generateId:this.config.generateId})??[];for(let e of _)f.push(e);return{content:f,finishReason:{unified:Pe({finishReason:d.finishReason,hasToolCalls:f.some(e=>e.type===`tool-call`&&!e.providerExecuted)}),raw:d.finishReason??void 0},usage:me(m),warnings:r,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:n},response:{headers:c,body:u}}}async doStream(t){let{args:n,warnings:r,providerOptionsNames:i,extraHeaders:a}=await this.getArgs(t,{isStreaming:!0}),o=e=>Object.fromEntries(i.map(t=>[t,e])),s=C(this.config.headers?await P(this.config.headers):void 0,t.headers,a),{responseHeaders:c,value:l}=await e({url:`${this.config.baseURL}/${Ce(this.modelId)}:streamGenerateContent?alt=sse`,headers:s,body:n,failedResponseHandler:V,successfulResponseHandler:D(Xe),abortSignal:t.abortSignal,fetch:this.config.fetch}),u={unified:`other`,raw:void 0},d,f,p=null,m=null,h=this.config.generateId,g=!1,_=null,v=null,y=0,b=new Set,x,S,w=[],T=e=>{let t=w.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:r})},transform(e,n){if(t.includeRawChunks&&n.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){n.enqueue({type:`error`,error:e.error});return}let r=e.value,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=He({groundingMetadata:a.groundingMetadata,generateId:h});if(c!=null)for(let e of c)e.sourceType===`url`&&!b.has(e.url)&&(b.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();x=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=x;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output??``}}),x=void 0)}else if(`text`in t&&t.text!=null){let e=t.thoughtSignature?o({thoughtSignature:t.thoughtSignature}):void 0;t.text.length===0?e!=null&&_!==null&&n.enqueue({type:`text-delta`,id:_,delta:``,providerMetadata:e}):t.thought===!0?(_!==null&&(n.enqueue({type:`text-end`,id:_}),_=null),v===null&&(v=String(y++),n.enqueue({type:`reasoning-start`,id:v,providerMetadata:e})),n.enqueue({type:`reasoning-delta`,id:v,delta:t.text,providerMetadata:e})):(v!==null&&(n.enqueue({type:`reasoning-end`,id:v}),v=null),_===null&&(_=String(y++),n.enqueue({type:`text-start`,id:_,providerMetadata:e})),n.enqueue({type:`text-delta`,id:_,delta:t.text,providerMetadata:e}))}else if(`inlineData`in t){_!==null&&(n.enqueue({type:`text-end`,id:_}),_=null),v!==null&&(n.enqueue({type:`reasoning-end`,id:v}),v=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();S=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=S??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}),S=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 Ee;if(w.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)&&T(n)}}else if(t.functionCall.partialArgs!=null&&w.length>0){let r=w[w.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)&&T(n)}}else if(i&&w.length>0)T(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:Pe({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){_!==null&&e.enqueue({type:`text-end`,id:_}),v!==null&&e.enqueue({type:`reasoning-end`,id:v}),e.enqueue({type:`finish`,finishReason:u,usage:me(d),providerMetadata:f})}})),response:{headers:c},request:{body:n}}}};function Ie(e){return/gemini-3[\.\-]/i.test(e)||/gemini-3$/i.test(e)}function Le(){return 65536}function Re(e){let t=e.toLowerCase();return t.includes(`2.5-pro`)||t.includes(`gemini-3-pro-image`)?32768:24576}function ze({reasoning:e,modelId:t,warnings:n}){if(s(e))return Ie(t)&&!t.includes(`gemini-3-pro-image`)?Be({reasoning:e,warnings:n}):Ve({reasoning:e,modelId:t,warnings:n})}function Be({reasoning:e,warnings:t}){if(e===`none`)return{thinkingLevel:`minimal`};let n=oe({reasoning:e,effortMap:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`high`},warnings:t});if(n!=null)return{thinkingLevel:n}}function Ve({reasoning:e,modelId:t,warnings:n}){if(e===`none`)return{thinkingBudget:0};let r=c({reasoning:e,maxOutputTokens:Le(),maxReasoningBudget:Re(t),minReasoningBudget:0,warnings:n});if(r!=null)return{thinkingBudget:r}}function He({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 Ue=()=>d({webSearchQueries:i(a()).nullish(),imageSearchQueries:i(a()).nullish(),retrievalQueries:i(a()).nullish(),searchEntryPoint:d({renderedContent:a()}).nullish(),groundingChunks:i(d({web:d({uri:a(),title:a().nullish()}).nullish(),image:d({sourceUri:a(),imageUri:a(),title:a().nullish(),domain:a().nullish()}).nullish(),retrievedContext:d({uri:a().nullish(),title:a().nullish(),text:a().nullish(),fileSearchStore:a().nullish()}).nullish(),maps:d({uri:a().nullish(),title:a().nullish(),text:a().nullish(),placeId:a().nullish()}).nullish()})).nullish(),groundingSupports:i(d({segment:d({startIndex:A().nullish(),endIndex:A().nullish(),text:a().nullish()}).nullish(),segment_text:a().nullish(),groundingChunkIndices:i(A()).nullish(),supportChunkIndices:i(A()).nullish(),confidenceScores:i(A()).nullish(),confidenceScore:i(A()).nullish()})).nullish(),retrievalMetadata:l([d({webDynamicRetrievalScore:A()}),d({})]).nullish()}),We=d({jsonPath:a(),stringValue:a().nullish(),numberValue:A().nullish(),boolValue:R().nullish(),nullValue:g().nullish(),willContinue:R().nullish()}),Ge=()=>d({parts:i(l([d({functionCall:d({id:a().nullish(),name:a().nullish(),args:g().nullish(),partialArgs:i(We).nullish(),willContinue:R().nullish()}),thoughtSignature:a().nullish()}),d({inlineData:d({mimeType:a(),data:a()}),thought:R().nullish(),thoughtSignature:a().nullish()}),d({toolCall:d({toolType:a(),args:g().nullish(),id:a()}),thoughtSignature:a().nullish()}),d({toolResponse:d({toolType:a(),response:g().nullish(),id:a()}),thoughtSignature:a().nullish()}),d({executableCode:d({language:a(),code:a()}).nullish(),codeExecutionResult:d({outcome:a(),output:a().nullish()}).nullish(),text:a().nullish(),thought:R().nullish(),thoughtSignature:a().nullish()})])).nullish()}),U=()=>d({category:a().nullish(),probability:a().nullish(),probabilityScore:A().nullish(),severity:a().nullish(),severityScore:A().nullish(),blocked:R().nullish()}),Ke=i(d({modality:a(),tokenCount:A()})).nullish(),qe=d({cachedContentTokenCount:A().nullish(),thoughtsTokenCount:A().nullish(),promptTokenCount:A().nullish(),candidatesTokenCount:A().nullish(),totalTokenCount:A().nullish(),trafficType:a().nullish(),serviceTier:a().nullish(),promptTokensDetails:Ke,candidatesTokensDetails:Ke}),Je=()=>d({urlMetadata:i(d({retrievedUrl:a(),urlRetrievalStatus:a()})).nullish()}),Ye=_(()=>O(d({candidates:i(d({content:Ge().nullish().or(d({}).strict()),finishReason:a().nullish(),finishMessage:a().nullish(),safetyRatings:i(U()).nullish(),groundingMetadata:Ue().nullish(),urlContextMetadata:Je().nullish()})),usageMetadata:qe.nullish(),promptFeedback:d({blockReason:a().nullish(),safetyRatings:i(U()).nullish()}).nullish()}))),Xe=_(()=>O(d({candidates:i(d({content:Ge().nullish(),finishReason:a().nullish(),finishMessage:a().nullish(),safetyRatings:i(U()).nullish(),groundingMetadata:Ue().nullish(),urlContextMetadata:Je().nullish()})).nullish(),usageMetadata:qe.nullish(),promptFeedback:d({blockReason:a().nullish(),safetyRatings:i(U()).nullish()}).nullish()}))),Ze=z({id:`google.code_execution`,inputSchema:d({language:a().describe(`The programming language of the code.`),code:a().describe(`The code to be executed.`)}),outputSchema:d({outcome:a().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:a().describe(`The output from the code execution.`)})}),Qe=z({id:`google.enterprise_web_search`,inputSchema:_(()=>O(d({}))),outputSchema:_(()=>O(d({})))});M({fileSearchStoreNames:i(a()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:A().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:a().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 $e=z({id:`google.file_search`,inputSchema:_(()=>O(d({}))),outputSchema:_(()=>O(d({})))}),et=z({id:`google.google_maps`,inputSchema:_(()=>O(d({}))),outputSchema:_(()=>O(d({})))}),tt=M({searchTypes:d({webSearch:d({}).optional(),imageSearch:d({}).optional()}).optional(),timeRangeFilter:d({startTime:a(),endTime:a()}).optional()}),nt={googleSearch:z({id:`google.google_search`,inputSchema:_(()=>O(d({}))),outputSchema:_(()=>O(d({})))}),enterpriseWebSearch:Qe,googleMaps:et,urlContext:z({id:`google.url_context`,inputSchema:_(()=>O(d({}))),outputSchema:_(()=>O(d({})))}),fileSearch:$e,codeExecution:Ze,vertexRagStore:z({id:`google.vertex_rag_store`,inputSchema:_(()=>O(d({}))),outputSchema:_(()=>O(d({})))})},rt=_(()=>O(d({personGeneration:B([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:B([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish(),googleSearch:tt.optional()}))),it=class t{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v4`}static[S](e){return N({modelId:e.modelId,config:e.config})}static[E](e){return new t(e.modelId,{},e.config)}get maxImagesPerCall(){return this.settings.maxImagesPerCall==null?at(this.modelId)?10:4:this.settings.maxImagesPerCall}get provider(){return this.config.provider}async doGenerate(e){return at(this.modelId)?this.doGenerateGemini(e):this.doGenerateImagen(e)}async doGenerateImagen(t){var n;let{prompt:r,n:i=1,size:a,aspectRatio:o=`1:1`,seed:s,providerOptions:c,headers:l,abortSignal:u,files:d,mask:f}=t,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 m=await b({provider:`google`,providerOptions:c,schema:rt}),h=((n=this.config._internal)?.currentDate)?.call(n)??new Date,g={sampleCount:i};if(o!=null&&(g.aspectRatio=o),m){let{googleSearch:e,...t}=m;e!=null&&p.push({type:`unsupported`,feature:`googleSearch`,details:`Google Search grounding is only supported on Gemini image models.`}),Object.assign(g,t)}let _={instances:[{prompt:r}],parameters:g},{responseHeaders:v,value:y}=await e({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:C(this.config.headers?await P(this.config.headers):void 0,l),body:_,failedResponseHandler:V,successfulResponseHandler:L(ot),abortSignal:u,fetch:this.config.fetch});return{images:y.predictions.map(e=>e.bytesBase64Encoded),warnings:p,providerMetadata:{google:{images:y.predictions.map(()=>({}))}},response:{timestamp:h,modelId:this.modelId,headers:v}}}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 m=[{role:`user`,content:p}],h=await b({provider:`google`,providerOptions:s,schema:rt}),{googleSearch:g,..._}=s?.google??{},v=await new Fe(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??j}).doGenerate({prompt:m,seed:o,providerOptions:{google:{responseModalities:[`IMAGE`],imageConfig:a?{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}),y=((t=this.config._internal)?.currentDate)?.call(t)??new Date,x=[];for(let e of v.content)e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`&&x.push(T(e.data.data));return{images:x,warnings:f,providerMetadata:{google:{...v.providerMetadata?.google??{},images:x.map(()=>({}))}},response:{timestamp:y,modelId:this.modelId,headers:v.response?.headers},usage:v.usage?{inputTokens:v.usage.inputTokens.total,outputTokens:v.usage.outputTokens.total,totalTokens:(v.usage.inputTokens.total??0)+(v.usage.outputTokens.total??0)}:void 0}}};function at(e){return e.startsWith(`gemini-`)}var ot=_(()=>O(d({predictions:i(d({bytesBase64Encoded:a()})).default([])}))),st=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(e){let i=await b({provider:`google`,providerOptions:e.providerOptions,schema:lt}),a=this.config.headers(),o=this.config.fetch??globalThis.fetch,s=[];e.filename!=null&&s.push({type:`unsupported`,feature:`filename`});let c=se(e.data),l=e.mediaType,u=i?.displayName,d=await o(`${this.config.baseURL.replace(/\/v1beta$/,``)}/upload/v1beta/files`,{method:`POST`,headers:{...a,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(c.length),"X-Goog-Upload-Header-Content-Type":l,"Content-Type":`application/json`},body:JSON.stringify({file:{...u==null?{}:{display_name:u}}})});if(!d.ok){let e=await d.text();throw new n({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to initiate resumable upload: ${d.status} ${e}`})}let f=d.headers.get(`x-goog-upload-url`);if(!f)throw new n({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`No upload URL returned from initiation request`});let p=await o(f,{method:`POST`,headers:{"Content-Length":String(c.length),"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:c});if(!p.ok){let e=await p.text();throw new n({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to upload file data: ${p.status} ${e}`})}let m=(await p.json()).file,h=i?.pollIntervalMs??2e3,g=i?.pollTimeoutMs??3e5,_=Date.now();for(;m.state===`PROCESSING`;){if(Date.now()-_>g)throw new n({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${g}ms`});await r(h);let{value:e}=await t({url:`${this.config.baseURL}/${m.name}`,headers:C(a),successfulResponseHandler:L(ct),failedResponseHandler:V,fetch:this.config.fetch});m=e}if(m.state===`FAILED`)throw new n({name:`GOOGLE_FILES_UPLOAD_FAILED`,message:`File processing failed for ${m.name}`});return{warnings:s,providerReference:{google:m.uri},mediaType:m.mimeType??e.mediaType,providerMetadata:{google:{name:m.name,displayName:m.displayName,mimeType:m.mimeType,sizeBytes:m.sizeBytes,state:m.state,uri:m.uri,...m.createTime==null?{}:{createTime:m.createTime},...m.updateTime==null?{}:{updateTime:m.updateTime},...m.expirationTime==null?{}:{expirationTime:m.expirationTime},...m.sha256Hash==null?{}:{sha256Hash:m.sha256Hash}}}}}},ct=_(()=>O(d({name:a(),displayName:a().nullish(),mimeType:a(),sizeBytes:a().nullish(),createTime:a().nullish(),updateTime:a().nullish(),expirationTime:a().nullish(),sha256Hash:a().nullish(),uri:a(),state:a()}))),lt=_(()=>O(M({displayName:a().nullish(),pollIntervalMs:A().positive().nullish(),pollTimeoutMs:A().positive().nullish()}))),ut=_(()=>O(M({pollIntervalMs:A().positive().nullish(),pollTimeoutMs:A().positive().nullish(),personGeneration:B([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:a().nullish(),referenceImages:i(d({bytesBase64Encoded:a().nullish(),gcsUri:a().nullish()})).nullish()})));function dt(e){return e.frameImages?.find(e=>e.frameType===`first_frame`)?.image}function ft(e){return dt(e)??e.image}function pt(e){return e.frameImages?.find(e=>e.frameType===`last_frame`)?.image}function mt(e){if(!(e.frameImages!=null&&e.frameImages.length>0))return e.inputReferences!=null&&e.inputReferences.length>0?e.inputReferences:void 0}function W(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}let n=typeof e.data==`string`?e.data:ie(e.data);return{inlineData:{mimeType:e.mediaType||`image/png`,data:n}}}function ht(e){return e.bytesBase64Encoded?{inlineData:{mimeType:`image/png`,data:e.bytesBase64Encoded}}:e.gcsUri?{gcsUri:e.gcsUri}:e}function gt(e,t){let n=W(e,t);return n==null?void 0:{image:n,referenceType:`asset`}}var _t=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(i){var a;let o=((a=this.config._internal)?.currentDate)?.call(a)??new Date,s=[],c=await b({provider:`google`,providerOptions:i.providerOptions,schema:ut}),l=[{}],u=l[0];i.prompt!=null&&(u.prompt=i.prompt);let d=ft(i);if(d!=null){let e=W(d,s);e!=null&&(u.image=e)}let f=pt(i);if(f!=null){let e=W(f,s);e!=null&&(u.lastFrame=e)}let p=mt(i);p==null?c?.referenceImages!=null&&(u.referenceImages=c.referenceImages.map(e=>ht(e))):u.referenceImages=p.flatMap(e=>{let t=gt(e,s);return t==null?[]:[t]});let m={sampleCount:i.n};if(i.aspectRatio&&(m.aspectRatio=i.aspectRatio),i.resolution&&(m.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[i.resolution]||i.resolution),i.duration&&(m.durationSeconds=i.duration),i.seed&&(m.seed=i.seed),c!=null){let e=c;e.personGeneration!==void 0&&e.personGeneration!==null&&(m.personGeneration=e.personGeneration),e.negativePrompt!==void 0&&e.negativePrompt!==null&&(m.negativePrompt=e.negativePrompt);for(let[t,n]of Object.entries(e))[`pollIntervalMs`,`pollTimeoutMs`,`personGeneration`,`negativePrompt`,`referenceImages`].includes(t)||(m[t]=n)}let{value:h}=await e({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:C(await P(this.config.headers),i.headers),body:{instances:l,parameters:m},successfulResponseHandler:L(vt),failedResponseHandler:V,abortSignal:i.abortSignal,fetch:this.config.fetch}),g=h.name;if(!g)throw new n({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No operation name returned from API`});let _=c?.pollIntervalMs??1e4,y=c?.pollTimeoutMs??6e5,x=Date.now(),S=h,w;for(;!S.done;){if(Date.now()-x>y)throw new n({name:`GOOGLE_VIDEO_GENERATION_TIMEOUT`,message:`Video generation timed out after ${y}ms`});if(await r(_),i.abortSignal?.aborted)throw new n({name:`GOOGLE_VIDEO_GENERATION_ABORTED`,message:`Video generation request was aborted`});let{value:e,responseHeaders:a}=await t({url:`${this.config.baseURL}/${g}`,headers:C(await P(this.config.headers),i.headers),successfulResponseHandler:L(vt),failedResponseHandler:V,abortSignal:i.abortSignal,fetch:this.config.fetch});S=e,w=a}if(S.error)throw new n({name:`GOOGLE_VIDEO_GENERATION_FAILED`,message:`Video generation failed: ${S.error.message}`});let T=S.response;if(!T?.generateVideoResponse?.generatedSamples||T.generateVideoResponse.generatedSamples.length===0)throw new n({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No videos in response. Response: ${JSON.stringify(S)}`});let E=[],D=[],O=(await P(this.config.headers))?.[`x-goog-api-key`];for(let e of T.generateVideoResponse.generatedSamples)if(e.video?.uri){let t=O&&v(e.video.uri,this.config.baseURL)?`${e.video.uri}${e.video.uri.includes(`?`)?`&`:`?`}key=${O}`:e.video.uri;E.push({type:`url`,url:t,mediaType:`video/mp4`}),D.push({uri:e.video.uri})}if(E.length===0)throw new n({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No valid videos in response`});return{videos:E,warnings:s,response:{timestamp:o,modelId:this.modelId,headers:w},providerMetadata:{google:{videos:D}}}}},vt=d({name:a().nullish(),done:R().nullish(),error:d({code:A().nullish(),message:a(),status:a().nullish()}).nullish(),response:d({generateVideoResponse:d({generatedSamples:i(d({video:d({uri:a().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}),yt=_(()=>O(d({candidates:i(d({content:d({parts:i(d({inlineData:d({mimeType:a().nullish(),data:a().nullish()}).nullish()})).nullish()}).nullish()})).nullish()}))),bt=d({prebuiltVoiceConfig:d({voiceName:a()})}),xt=_(()=>O(d({multiSpeakerVoiceConfig:d({speakerVoiceConfigs:i(d({speaker:a(),voiceConfig:bt}))}).optional()}))),St=`Kore`,Ct=24e3,wt=class t{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}static[S](e){return N({modelId:e.modelId,config:e.config})}static[E](e){return new t(e.modelId,e.config)}get provider(){return this.config.provider}async getArgs({text:e,voice:t=St,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 b({provider:e,providerOptions:o,schema:xt}),l!=null)break;l==null&&!c.includes(`google`)&&(l=await b({provider:`google`,providerOptions:o,schema:xt}));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(t){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,{requestBody:i,warnings:a,outputFormat:o}=await this.getArgs(t),{value:s,responseHeaders:c,rawValue:l}=await e({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:C(this.config.headers?await P(this.config.headers):void 0,t.headers),body:i,failedResponseHandler:V,successfulResponseHandler:L(yt),abortSignal:t.abortSignal,fetch:this.config.fetch}),u,d;for(let e of s.candidates??[]){for(let t of e.content?.parts??[])if(t.inlineData?.data){u=t.inlineData.data,d=t.inlineData.mimeType??void 0;break}if(u!=null)break}let f=Tt(d)??Ct,p=u==null?new Uint8Array:te(u),m=o===`pcm`||p.length===0?p:Et(p,f);return o===`pcm`&&p.length>0&&a.push({type:`unsupported`,feature:`outputFormat`,details:`Returning raw PCM audio (signed 16-bit little-endian, mono, ${f} Hz). These bytes have no container header and are not directly playable; see providerMetadata.google for the sample rate and mime type.`}),{audio:m,warnings:a,request:{body:JSON.stringify(i)},response:{timestamp:r,modelId:this.modelId,headers:c,body:l},providerMetadata:{google:{sampleRate:f,mimeType:d??null}}}}};function Tt(e){if(e==null)return;let t=/rate=(\d+)/.exec(e);return t?Number.parseInt(t[1],10):void 0}function Et(e,t){let n=t*2,r=e.length,i=new ArrayBuffer(44+r),a=new DataView(i);G(a,0,`RIFF`),a.setUint32(4,36+r,!0),G(a,8,`WAVE`),G(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),G(a,36,`data`),a.setUint32(40,r,!0);let o=new Uint8Array(i);return o.set(e,44),o}function G(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function K(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.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 Dt(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 Ot={pdf:`application/pdf`,txt:`text/plain`,md:`text/markdown`,markdown:`text/markdown`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};function kt(e){let t=e.toLowerCase();for(let[e,n]of Object.entries(Ot))if(t.endsWith(`.${e}`))return n;return`application/octet-stream`}function At(e){let t=e.split(`/`),n=t[t.length-1];return n&&n.length>0?n:void 0}function jt({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??At(r),a=kt(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 Mt({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??At(i),o=kt(i);n.push({type:`source`,sourceType:`document`,id:t(),mediaType:o,title:r.title??r.file_name??a??i,...a==null?{}:{filename:a}})}break}default:break}return n}function q({annotations:e,generateId:t}){if(e==null)return[];let n=new Set,r=[];for(let i of e){let e=jt({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 J({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 Nt=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),Pt=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function Ft(e){return e.replace(/_call$/,``)}function It(e){return e.replace(/_result$/,``)}function Lt({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=q({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===`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&&Nt.has(s)){let e=s===`mcp_server_tool_call`?n?.name??`mcp_server_tool`:Ft(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&&Pt.has(s)){let e=s===`mcp_server_tool_result`?n?.name??`mcp_server_tool`:It(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===`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=q({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&&(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&&(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&&(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===`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=Mt({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`;let t=e.error??{message:`Unknown interaction error`};r.enqueue({type:`error`,error:t});break}default:break}},flush(e){let t={unified:J({status:s,hasFunctionCall:c}),raw:s},n=Dt(a),r={google:{...i==null?{}:{interactionId:i},...o==null?{}:{serviceTier:o},...n==null?{}:{outputTokensByModality:n}}};e.enqueue({type:`finish`,finishReason:t,usage:K(a),providerMetadata:r})}})}function Rt({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?Bt({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=zt({part:n,warnings:i,mediaResolution:r});e!=null&&t.push(e)}let n=Wt(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=zt({part:a,warnings:i,mediaResolution:r});e!=null&&t.push(e)}else if(a.type===`tool-call`){n();let e=a.providerOptions?.google?.signature,t=typeof a.input==`string`?Vt(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=Ht({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(`
|
|
7
|
+
|
|
8
|
+
`):void 0,warnings:i}}function zt({part:e,warnings:t,mediaResolution:n}){if(e.data.type===`text`)return{type:`text`,text:e.data.text};let r=u(e.mediaType),i;switch(r){case`image`:i=`image`;break;case`audio`:i=`audio`;break;case`video`:i=`video`;break;case`application`: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}:{};switch(e.data.type){case`data`:{let t=I({part:e});return{type:i,data:T(e.data.data),mime_type:t,...a}}case`url`:return{type:i,uri:e.data.url.toString(),...h(e.mediaType)?{mime_type:e.mediaType}:{},...a};case`reference`:{let t=k({reference:e.data.reference,provider:`google`});return{type:i,uri:t,...h(e.mediaType)?{mime_type:e.mediaType}:{},...a}}}}function Bt({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 Vt(e){try{let t=w(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{value:t}}catch{return{value:e}}}function Ht({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(u(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=Ut({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 Ut({part:e,warnings:t}){switch(e.data.type){case`data`:{let t=h(e.mediaType)?e.mediaType:I({part:{type:`file`,mediaType:e.mediaType,data:e.data}});return{type:`image`,data:T(e.data.data),mime_type:t}}case`url`:return{type:`image`,uri:e.data.url.toString(),...h(e.mediaType)?{mime_type:e.mediaType}:{}};case`reference`:return{type:`image`,uri:k({reference:e.data.reference,provider:`google`}),...h(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 Wt(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}
|
|
9
|
+
|
|
10
|
+
${n.text}`};t[t.length-1]=r;continue}t.push(n)}return t}var Y=()=>d({modality:a().nullish(),tokens:A().nullish()}).loose(),Gt=()=>d({total_input_tokens:A().nullish(),total_output_tokens:A().nullish(),total_thought_tokens:A().nullish(),total_cached_tokens:A().nullish(),total_tool_use_tokens:A().nullish(),total_tokens:A().nullish(),input_tokens_by_modality:i(Y()).nullish(),output_tokens_by_modality:i(Y()).nullish(),cached_tokens_by_modality:i(Y()).nullish(),tool_use_tokens_by_modality:i(Y()).nullish(),grounding_tool_count:i(d({type:a().nullish(),count:A().nullish()}).loose()).nullish()}).loose(),Kt=()=>B([`in_progress`,`requires_action`,`completed`,`failed`,`cancelled`,`incomplete`]),qt=()=>l([d({type:p(`url_citation`),url:a().nullish(),title:a().nullish(),start_index:A().nullish(),end_index:A().nullish()}).loose(),d({type:p(`file_citation`),file_name:a().nullish(),document_uri:a().nullish(),url:a().nullish(),page_number:A().nullish(),media_id:a().nullish(),start_index:A().nullish(),end_index:A().nullish(),custom_metadata:f(a(),g()).nullish()}).loose(),d({type:p(`place_citation`),name:a().nullish(),url:a().nullish(),place_id:a().nullish(),start_index:A().nullish(),end_index:A().nullish()}).loose(),d({type:a()}).loose()]),Jt=()=>d({type:a(),text:a().nullish(),data:a().nullish(),mime_type:a().nullish()}).loose(),Yt=()=>l([d({type:p(`text`),text:a(),annotations:i(qt()).nullish()}).loose(),d({type:p(`image`),data:a().nullish(),mime_type:a().nullish(),resolution:B([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:a().nullish()}).loose(),d({type:p(`video`),data:a().nullish(),mime_type:a().nullish(),uri:a().nullish()}).loose(),d({type:a()}).loose()]),Xt=[`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`],Zt=[`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`],Qt=()=>l([d({type:p(`user_input`),content:i(Yt()).nullish()}).loose(),d({type:p(`model_output`),content:i(Yt()).nullish()}).loose(),d({type:p(`function_call`),id:a(),name:a(),arguments:f(a(),g()).nullish(),signature:a().nullish()}).loose(),d({type:p(`thought`),signature:a().nullish(),summary:i(Jt()).nullish()}).loose(),d({type:B(Xt),id:a(),arguments:f(a(),g()).nullish(),name:a().nullish(),server_name:a().nullish(),search_type:a().nullish(),signature:a().nullish()}).loose(),d({type:B(Zt),call_id:a(),result:g().nullish(),is_error:R().nullish(),name:a().nullish(),server_name:a().nullish(),signature:a().nullish()}).loose(),d({type:a()}).loose()]),X=_(()=>O(d({id:a().nullish(),created:a().nullish(),updated:a().nullish(),status:Kt(),model:a().nullish(),agent:a().nullish(),steps:i(Qt()).nullish(),usage:Gt().nullish(),service_tier:a().nullish(),previous_interaction_id:a().nullish(),response_modalities:i(a()).nullish()}).loose())),$t=_(()=>O((()=>{let e=Kt(),t=qt(),n=Jt(),r=d({event_type:p(`interaction.created`),event_id:a().nullish(),interaction:d({id:a().nullish(),created:a().nullish(),model:a().nullish(),agent:a().nullish(),status:e.nullish()}).loose()}).loose(),o=d({event_type:p(`step.start`),event_id:a().nullish(),index:A(),step:Qt()}).loose(),s=d({type:p(`text`),text:a()}).loose(),c=d({type:p(`thought_summary`),content:n.nullish()}).loose(),u=d({type:p(`thought_signature`),signature:a().nullish()}).loose(),m=d({type:p(`arguments_delta`),arguments:a().nullish(),id:a().nullish(),signature:a().nullish()}).loose(),h=d({type:B([`text_annotation_delta`,`text_annotation`]),annotations:i(t).nullish()}).loose(),_=l([s,d({type:p(`image`),data:a().nullish(),mime_type:a().nullish(),resolution:B([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:a().nullish()}).loose(),d({type:p(`video`),data:a().nullish(),mime_type:a().nullish(),uri:a().nullish()}).loose(),c,u,m,h,d({type:B(Xt),id:a().nullish(),arguments:f(a(),g()).nullish(),name:a().nullish(),server_name:a().nullish(),search_type:a().nullish(),signature:a().nullish()}).loose(),d({type:B(Zt),call_id:a().nullish(),result:g().nullish(),is_error:R().nullish(),name:a().nullish(),server_name:a().nullish(),signature:a().nullish()}).loose(),d({type:a()}).loose()]);return l([r,o,d({event_type:p(`step.delta`),event_id:a().nullish(),index:A(),delta:_}).loose(),d({event_type:p(`step.stop`),event_id:a().nullish(),index:A()}).loose(),d({event_type:p(`interaction.status_update`),event_id:a().nullish(),interaction_id:a().nullish(),status:e.nullish()}).loose(),d({event_type:p(`interaction.in_progress`),event_id:a().nullish(),interaction_id:a().nullish(),status:e.nullish()}).loose(),d({event_type:p(`interaction.requires_action`),event_id:a().nullish(),interaction_id:a().nullish(),status:e.nullish()}).loose(),d({event_type:p(`interaction.completed`),event_id:a().nullish(),interaction:d({id:a().nullish(),status:e.nullish(),usage:Gt().nullish(),service_tier:a().nullish()}).loose()}).loose(),d({event_type:p(`error`),event_id:a().nullish(),error:d({code:a().nullish(),message:a().nullish()}).loose().nullish()}).loose(),d({event_type:a()}).loose()])})())),en=_(()=>O(d({previousInteractionId:a().nullish(),store:R().nullish(),agent:a().nullish(),agentConfig:l([d({type:p(`dynamic`)}).loose(),d({type:p(`deep-research`),thinkingSummaries:B([`auto`,`none`]).nullish(),visualization:B([`off`,`auto`]).nullish(),collaborativePlanning:R().nullish()})]).nullish(),thinkingLevel:B([`minimal`,`low`,`medium`,`high`]).nullish(),thinkingSummaries:B([`auto`,`none`]).nullish(),responseFormat:i(l([d({type:p(`text`),mimeType:a().nullish(),schema:g().nullish()}).loose(),d({type:p(`image`),mimeType:a().nullish(),aspectRatio:B([`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:B([`1K`,`2K`,`4K`,`512`]).nullish()}).loose(),d({type:p(`audio`),mimeType:a().nullish()}).loose()])).nullish(),imageConfig:d({aspectRatio:B([`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:B([`1K`,`2K`,`4K`,`512`]).nullish()}).nullish(),mediaResolution:B([`low`,`medium`,`high`,`ultra_high`]).nullish(),responseModalities:i(B([`text`,`image`,`audio`,`video`,`document`])).nullish(),serviceTier:B([`flex`,`standard`,`priority`]).nullish(),systemInstruction:a().nullish(),signature:a().nullish(),interactionId:a().nullish(),pollingTimeoutMs:A().int().positive().nullish(),background:R().nullish(),environment:l([a(),d({type:p(`remote`),sources:i(l([d({type:p(`gcs`),source:a(),target:a().nullish()}),d({type:p(`repository`),source:a(),target:a().nullish()}),d({type:p(`inline`),content:a(),target:a()})])).nullish(),network:l([p(`disabled`),d({allowlist:i(d({domain:a(),transform:i(f(a(),a())).nullish()}))})]).nullish()})]).nullish()})));function Z({signature:e,interactionId:t}){let n={};return e!=null&&(n.signature=e),t!=null&&(n.interactionId=t),Object.keys(n).length>0?{providerMetadata:{google:n}}:{}}var tn=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),nn=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function rn(e){return e.replace(/_call$/,``)}function an(e){return e.replace(/_result$/,``)}function on({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,...Z({interactionId:n})});let o=q({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},...Z({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)},...Z({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},...Z({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)},...Z({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(`
|
|
11
|
+
`);r.push({type:`reasoning`,text:t,...Z({signature:e.signature,interactionId:n})});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??{}),...Z({signature:e.signature,interactionId:n})});break}default:if(tn.has(e)){let n=a,i=e===`mcp_server_tool_call`?n.name??`mcp_server_tool`:rn(e),o=JSON.stringify(n.arguments??{});r.push({type:`tool-call`,toolCallId:n.id??t(),toolName:i,input:o,providerExecuted:!0})}else if(nn.has(e)){let n=a,i=e===`mcp_server_tool_result`?n.name??`mcp_server_tool`:an(e);r.push({type:`tool-result`,toolCallId:n.call_id??t(),toolName:i,result:n.result??null});let o=Mt({block:a,generateId:t});for(let e of o)r.push(e)}break}}return{content:r,hasFunctionCall:i}}var sn=()=>globalThis.fetch;async function cn({baseURL:e,interactionId:t,headers:n,fetch:r=sn()}){if(t==null||t.length===0)return;let i=`${e}/interactions/${encodeURIComponent(t)}/cancel`;try{let e=await r(i,{method:`POST`,headers:ae(C({"Content-Type":`application/json`},n),ee()),body:`{}`});try{await e.text()}catch{}}catch{}}var ln=new Set([`completed`,`failed`,`cancelled`,`incomplete`]);function Q(e){return e!=null&&ln.has(e)}var un=1e3,dn=1e4,fn=1800*1e3;async function pn({baseURL:e,interactionId:n,headers:i,fetch:a,abortSignal:o,initialDelayMs:s=un,maxDelayMs:c=dn,timeoutMs:l=fn}){if(n==null||n.length===0)throw Error(`google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.`);let u=Date.now(),d=s,f=`${e}/interactions/${encodeURIComponent(n)}`,p=()=>cn({baseURL:e,interactionId:n,headers:i,fetch:a});try{for(;;){if(o?.aborted)throw await p(),new DOMException(`Polling was aborted`,`AbortError`);if(Date.now()-u>l)throw Error(`google.interactions: timed out polling interaction ${n} after ${l}ms.`);await r(d,{abortSignal:o});let{value:e,rawValue:s,responseHeaders:m}=await t({url:f,headers:i,failedResponseHandler:V,successfulResponseHandler:L(X),abortSignal:o,fetch:a});if(Q(e.status))return{response:e,rawResponse:s,responseHeaders:m};d=Math.min(d*2,c)}}catch(e){throw m(e)&&await p(),e}}function mn({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.`});break}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]}};break}return{tools:i.length>0?i:void 0,toolChoice:o,toolWarnings:n}}var hn=3,gn=500;function _n({baseURL:e,interactionId:n,headers:i,fetch:a,abortSignal:o,maxRetries:s=hn,retryDelayMs:c=gn}){if(n.length===0)throw Error(`google.interactions: cannot stream a background interaction without an id.`);let l={...i,accept:`text/event-stream`},u,d=!1,f=0,p=!1,h,g=new AbortController,_=()=>g.abort();o!=null&&(o.aborted?g.abort():o.addEventListener(`abort`,_,{once:!0}));let v=g.signal;function y(){let t=`${e}/interactions/${encodeURIComponent(n)}`,r=new URLSearchParams({stream:`true`});return u!=null&&r.set(`last_event_id`,u),`${t}?${r.toString()}`}async function b(){let{value:e}=await t({url:y(),headers:l,failedResponseHandler:V,successfulResponseHandler:D($t),abortSignal:v,fetch:a});return e.getReader()}return new ReadableStream({async start(t){try{for(;!d&&!v.aborted;){if(h==null)try{h=await b(),p=!1}catch(e){if(m(e)||v.aborted){t.error(e);return}if(f++,f>=s){t.error(e);return}await r(c*f,{abortSignal:v});continue}try{let{done:e,value:n}=await h.read();if(e){if(h=void 0,d)break;if(p)f=0;else{if(f++,f>=s){t.error(Error(`google.interactions: SSE stream closed without producing any events.`));return}await r(c*f,{abortSignal:v})}continue}if(p=!0,n.success){let e=n.value;typeof e.event_id==`string`&&e.event_id.length>0&&(u=e.event_id),(e.event_type===`interaction.completed`||e.event_type===`error`)&&(d=!0)}t.enqueue(n)}catch(e){if(m(e)||v.aborted){t.error(e);return}if(h=void 0,f++,f>=s){t.error(e);return}await r(c*f,{abortSignal:v})}}t.close()}catch(e){t.error(e)}finally{o?.removeEventListener(`abort`,_),h?.cancel().catch(()=>{}),h=void 0,v.aborted&&!d&&await cn({baseURL:e,interactionId:n,headers:i,fetch:a})}},cancel(){g.abort(),h?.cancel().catch(()=>{}),h=void 0}})}function vn({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}=on({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);break;default:break}let p=e.service_tier??i,m={unified:J({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:K(e.usage),providerMetadata:h}),a.close()}})}var yn=class t{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[S](e){return{...N({modelId:e.modelId,config:e.config}),agent:e.agent}}static[E](e){return new t(e.agent==null?e.modelId:{agent:e.agent},e.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 b({provider:`google`,providerOptions:e.providerOptions,schema:en}),r=this.agent!=null,i=e.tools!=null&&e.tools.length>0,a,o;if(i&&r)t.push({type:`other`,message:`google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body.`});else if(i){let n=mn({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}));let{input:c,systemInstruction:l,warnings:u}=Rt({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.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,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(t){let{args:n,warnings:r,isAgent:i,pollingTimeoutMs:a}=await this.getArgs(t),o=`${this.config.baseURL}/interactions`,s=C(this.config.headers?await P(this.config.headers):void 0,t.headers),{responseHeaders:c,value:l,rawValue:u}=await e({url:o,headers:s,body:n,failedResponseHandler:V,successfulResponseHandler:L(X),abortSignal:t.abortSignal,fetch:this.config.fetch});if(i&&!Q(l.status)){let e=await pn({baseURL:this.config.baseURL,interactionId:l.id,headers:s,fetch:this.config.fetch,abortSignal:t.abortSignal,timeoutMs:a});l=e.response,u=e.rawResponse,c=e.responseHeaders??c}let d=typeof l.id==`string`&&l.id.length>0?l.id:void 0,{content:f,hasFunctionCall:p}=on({steps:l.steps??null,generateId:this.config.generateId??j,interactionId:d}),m={unified:J({status:l.status,hasFunctionCall:p}),raw:l.status},h=l.service_tier??c?.[`x-gemini-service-tier`]??void 0,g=Dt(l.usage),_={google:{...d==null?{}:{interactionId:d},...h==null?{}:{serviceTier:h},...g==null?{}:{outputTokensByModality:g}}},v;if(typeof l.created==`string`){let e=new Date(l.created);Number.isNaN(e.getTime())||(v=e)}return{content:f,finishReason:m,usage:K(l.usage),warnings:r,providerMetadata:_,request:{body:n},response:{headers:c,body:u,...d==null?{}:{id:d},...v?{timestamp:v}:{},modelId:l.model??void 0}}}async doStream(t){let{args:n,warnings:r,isBackground:i,pollingTimeoutMs:a}=await this.getArgs(t),o=`${this.config.baseURL}/interactions`,s=C(this.config.headers?await P(this.config.headers):void 0,t.headers);if(i)return this.doStreamBackground({args:n,warnings:r,url:o,mergedHeaders:s,options:t,pollingTimeoutMs:a});let c={...n,stream:!0},{responseHeaders:l,value:u}=await e({url:o,headers:s,body:c,failedResponseHandler:V,successfulResponseHandler:D($t),abortSignal:t.abortSignal,fetch:this.config.fetch}),d=l?.[`x-gemini-service-tier`],f=Lt({warnings:r,generateId:this.config.generateId??j,includeRawChunks:t.includeRawChunks,serviceTier:d});return{stream:u.pipeThrough(f),request:{body:c},response:{headers:l}}}async doStreamBackground({args:t,warnings:n,url:r,mergedHeaders:i,options:a,pollingTimeoutMs:o}){let{responseHeaders:s,value:c}=await e({url:r,headers:i,body:t,failedResponseHandler:V,successfulResponseHandler:L(X),abortSignal:a.abortSignal,fetch:this.config.fetch}),l=c.id;if(l==null||l.length===0)throw Error(`google.interactions: background POST response did not include an interaction id; cannot stream the result.`);let u=s?.[`x-gemini-service-tier`];if(Q(c.status))return{stream:vn({response:c,warnings:n,generateId:this.config.generateId??j,includeRawChunks:a.includeRawChunks,headerServiceTier:u}),request:{body:t},response:{headers:s}};let d=_n({baseURL:this.config.baseURL,interactionId:l,headers:i,fetch:this.config.fetch,abortSignal:a.abortSignal}),f=Lt({warnings:n,generateId:this.config.generateId??j,includeRawChunks:a.includeRawChunks,serviceTier:u});return{stream:d.pipeThrough(f),request:{body:t},response:{headers:s}}}};function $(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function bn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var xn=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.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:`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.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:Cn(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 Sn(t);case`audio-message`:return null}break}}return null}};async function Sn(e){let t=await re({text:e.output}),n=t.success?t.value:{};return{toolResponse:{functionResponses:[{id:e.callId,name:e.name,response:n}]}}}function Cn(e,t){let n={model:Ce(t)},r={};if(e?.outputModalities==null?r.responseModalities=[`AUDIO`]:r.responseModalities=e.outputModalities.map(e=>e.toUpperCase()),e?.voice!=null&&(r.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.voice}}}),n.generationConfig=r,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,parameters:H(e.parameters)}))}]),e?.inputAudioTranscription!=null&&(n.inputAudioTranscription={}),e?.outputAudioTranscription!=null&&(n.outputAudioTranscription={}),e?.providerOptions==null)return n;let{google:i,...a}=e.providerOptions;Object.assign(n,a);let o=bn(i)?i:void 0;return o?.translationConfig!=null&&(n.generationConfig={...bn(n.generationConfig)?n.generationConfig:r,translationConfig:o.translationConfig}),n}var wn=`google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained`;function Tn(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 En(e){let t=Tn(e);return t.pathname=`${t.pathname.replace(/\/$/,``)}/v1alpha/auth_tokens`,t.toString()}function Dn(e){let t=Tn(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=`${t.pathname.replace(/\/$/,``)}/ws/${wn}`,t.toString()}var On=class{constructor(e,t){this.specificationVersion=`v4`,this.mapper=new xn,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+1800*1e3).toISOString(),s=Cn(e.sessionConfig,this.modelId),c=await t(`${En(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:Dn(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 Cn(e,this.modelId)}};function kn(e={}){let t=ne(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=e.name??`google.generative-ai`,r=()=>ae({"x-goog-api-key":y({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${ce}`),i=i=>new Fe(i,{provider:n,baseURL:t,headers:r,generateId:e.generateId??j,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),a=i=>new de(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),o=(i,a={})=>new it(i,a,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),s=()=>new st({provider:n,baseURL:t,headers:r,fetch:e.fetch}),c=i=>new _t(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch,generateId:e.generateId??j}),l=i=>new On(i,{provider:`${n}.realtime`,baseURL:t,headers:r,fetch:e.fetch}),u=i=>new wt(i,{provider:`${n}.speech`,baseURL:t,headers:r,fetch:e.fetch}),d=Object.assign(e=>l(e),{getToken:async e=>{let t=await l(e.model).doCreateClientSecret({sessionConfig:e.sessionConfig,expiresAfterSeconds:e.expiresAfterSeconds});return{token:t.token,url:t.url,expiresAt:t.expiresAt}}}),f=i=>new yn(i,{provider:`${n}.interactions`,baseURL:t,headers:r,generateId:e.generateId??j,fetch:e.fetch}),p=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return i(e)};return p.specificationVersion=`v4`,p.languageModel=i,p.chat=i,p.generativeAI=i,p.embedding=a,p.embeddingModel=a,p.textEmbedding=a,p.textEmbeddingModel=a,p.image=o,p.imageModel=o,p.video=c,p.videoModel=c,p.experimental_realtime=d,p.files=s,p.speech=u,p.speechModel=u,p.interactions=f,p.tools=nt,p}kn();export{kn as createGoogle,kn as createGoogleGenerativeAI};
|