experimental-ash 0.10.2 → 0.10.4
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/CHANGELOG.md +13 -0
- package/dist/src/chunks/{dev-authored-source-watcher-CDT0dQQf.js → dev-authored-source-watcher-Dli96TWx.js} +1 -1
- package/dist/src/chunks/{host-M56X595D.js → host-Cp4XhAAX.js} +2 -2
- package/dist/src/chunks/{paths-B-Onq-sx.js → paths-CWTvKBbf.js} +1 -1
- package/dist/src/chunks/{prewarm-DQzlGOTi.js → prewarm-DIMA-oZ6.js} +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/run.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +5 -5
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/anthropic/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/google/index.js +8 -3
- package/dist/src/compiled/@ai-sdk/google/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.js +10 -6
- package/dist/src/compiled/@ai-sdk/openai/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/otel/index.js +3 -3
- package/dist/src/compiled/@ai-sdk/otel/package.json +1 -1
- package/dist/src/compiled/@workflow/core/index.js +1 -1
- package/dist/src/compiled/@workflow/core/runtime.js +5 -5
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/_chunks/workflow/{context-errors-zbKocOyk.js → context-errors-CmtmBosi.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/dist-4zn5tehu.js +10 -0
- package/dist/src/compiled/_chunks/workflow/dist-DTWUhyDN.js +5 -0
- package/dist/src/compiled/_chunks/workflow/{resume-hook-CL8Ed91K.js → resume-hook-BqY8TqOE.js} +2 -2
- package/dist/src/compiled/_chunks/workflow/sleep-D30F1GSr.js +1 -0
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/harness/input-requests.js +46 -18
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/public/channels/slack/api.d.ts +34 -0
- package/dist/src/public/channels/slack/api.js +55 -0
- package/dist/src/public/channels/slack/attachments.d.ts +17 -1
- package/dist/src/public/channels/slack/attachments.js +41 -0
- package/dist/src/public/channels/slack/connections.d.ts +57 -0
- package/dist/src/public/channels/slack/connections.js +70 -0
- package/dist/src/public/channels/slack/hitl.d.ts +74 -0
- package/dist/src/public/channels/slack/hitl.js +136 -9
- package/dist/src/public/channels/slack/inbound.d.ts +55 -0
- package/dist/src/public/channels/slack/inbound.js +75 -0
- package/dist/src/public/channels/slack/index.d.ts +1 -1
- package/dist/src/public/channels/slack/interactions.d.ts +74 -0
- package/dist/src/public/channels/slack/interactions.js +311 -0
- package/dist/src/public/channels/slack/limits.d.ts +43 -0
- package/dist/src/public/channels/slack/limits.js +52 -0
- package/dist/src/public/channels/slack/slack.d.ts +12 -2
- package/dist/src/public/channels/slack/slack.js +168 -12
- package/dist/src/public/channels/slack/slackChannel.d.ts +47 -1
- package/dist/src/public/channels/slack/slackChannel.js +41 -138
- package/dist/src/public/definitions/defineChannel.d.ts +2 -0
- package/dist/src/public/definitions/defineChannel.js +2 -0
- package/dist/src/shared/sandbox-session.d.ts +1 -1
- package/package.json +8 -8
- package/dist/src/compiled/_chunks/workflow/dist-Ci2brnHh.js +0 -14
- package/dist/src/compiled/_chunks/workflow/sleep-Dn3i9nxI.js +0 -1
- /package/dist/src/compiled/_chunks/workflow/{dist-0iNBqPYp.js → dist-B6aByiku.js} +0 -0
- /package/dist/src/compiled/_chunks/workflow/{dist-D774SUM4.js → dist-CVo7knbW.js} +0 -0
- /package/dist/src/compiled/_chunks/workflow/{src-ClRYdO4-.js → src-Bc9OYRaN.js} +0 -0
- /package/dist/src/compiled/_chunks/workflow/{symbols-D-4tVV8x.js → symbols-DkV1V0kM.js} +0 -0
- /package/dist/src/compiled/_chunks/workflow/{token-CsNmv7KW.js → token-Cq5QjRq8.js} +0 -0
- /package/dist/src/compiled/_chunks/workflow/{token-j5Cl4rrs.js → token-Duaoxfi5.js} +0 -0
|
@@ -1,6 +1,11 @@
|
|
|
1
|
-
import{AISDKError as e,TooManyEmbeddingValuesForCallError as t,UnsupportedFunctionalityError as n}from"../provider/index.js";import{At as r,Et as i,Nn as a,Rn as o,Tn as s,Xn as c,Zn as l,
|
|
2
|
-
`):`Tool executed successfully.`},...r.length>0?{parts:r}:{}}})}function he(e,t,n){for(let r of n)switch(r.type){case`text`:e.push({functionResponse:{name:t,response:{name:t,content:r.text}}});break;case`file`:r.data.type===`data`&&
|
|
1
|
+
import{AISDKError as e,TooManyEmbeddingValuesForCallError as t,UnsupportedFunctionalityError as n}from"../provider/index.js";import{At as r,Et as i,Nn as a,Rn as o,Tn as s,Xn as c,Zn as l,dn as u,wn as d,yt as f}from"../../_chunks/workflow/schemas-DFZoEyCn.js";import{n as p,t as m}from"../../_chunks/workflow/dist-4zn5tehu.js";import{A as h,D as g,F as _,H as v,M as y,N as b,O as x,P as S,R as C,T as w,U as T,V as E,_ as D,a as O,b as k,c as ee,d as A,g as j,h as M,i as te,l as N,n as P,o as ne,p as F,s as I,v as L,w as R,x as z,y as B}from"../../_chunks/workflow/dist-DTWUhyDN.js";var re=`4.0.0-canary.62`,V=ee({errorSchema:R(()=>T(s({error:s({code:d().nullable(),message:o(),status:o()})}))),errorToMessage:e=>e.error.message}),ie=c([s({text:o()}),s({inlineData:s({mimeType:o(),data:o()})}),s({fileData:s({fileUri:o(),mimeType:o()})})]),ae=R(()=>T(s({outputDimensionality:d().optional(),taskType:f([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:i(i(ie).min(1).nullable()).optional()}))),oe=class e{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}static[p](e){return C({modelId:e.modelId,config:e.config})}static[m](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await h({provider:`google`,providerOptions:i,schema:ae});if(e.length>this.maxEmbeddingsPerCall)throw new t({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=P(this.config.headers?await b(this.config.headers):void 0,n),s=a?.content;if(s!=null&&s.length!==e.length)throw Error(`The number of multimodal content entries (${s.length}) must match the number of values (${e.length}).`);if(e.length===1){let t=s?.[0],n=e[0]?[{text:e[0]}]:[],i=t==null?[{text:e[0]}]:[...n,...t],{responseHeaders:c,value:l,rawValue:u}=await y({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:i},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:V,successfulResponseHandler:N(ce),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:[l.embedding.values],usage:void 0,response:{headers:c,body:u}}}let{responseHeaders:c,value:l,rawValue:u}=await y({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map((e,t)=>{let n=s?.[t],r=e?[{text:e}]:[];return{model:`models/${this.modelId}`,content:{role:`user`,parts:n==null?[{text:e}]:[...r,...n]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}})},failedResponseHandler:V,successfulResponseHandler:N(se),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.embeddings.map(e=>e.values),usage:void 0,response:{headers:c,body:u}}}},se=R(()=>T(s({embeddings:i(s({values:i(d())}))}))),ce=R(()=>T(s({embedding:s({values:i(d())})})));function le(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(ue(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 ue(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var de=/^data:([^;,]+);base64,(.+)$/s;function fe(e){let t=de.exec(e);if(t!=null)return{mediaType:t[1],data:t[2]}}function pe(e){let t=fe(e);if(t!=null)return{inlineData:{mimeType:t.mediaType,data:t.data}}}function me(e,t,n){let r=[],i=[];for(let e of n)switch(e.type){case`text`:i.push(e.text);break;case`file`:if(e.data.type===`data`)r.push({inlineData:{mimeType:S({part:e}),data:O(e.data.data)}});else if(e.data.type===`url`){let t=pe(e.data.url.toString());t==null?i.push(JSON.stringify(e)):r.push(t)}else i.push(JSON.stringify(e));break;default:i.push(JSON.stringify(e));break}e.push({functionResponse:{name:t,response:{name:t,content:i.length>0?i.join(`
|
|
2
|
+
`):`Tool executed successfully.`},...r.length>0?{parts:r}:{}}})}function he(e,t,n){for(let r of n)switch(r.type){case`text`:e.push({functionResponse:{name:t,response:{name:t,content:r.text}}});break;case`file`:r.data.type===`data`&&L(r.mediaType)===`image`?e.push({inlineData:{mimeType:S({part:r}),data:O(r.data.data)}},{text:`Tool executed successfully and returned this image as a response`}):e.push({text:JSON.stringify(r)});break;default:e.push({text:JSON.stringify(r)});break}}function ge(e,t){let r=[],i=[],a=!0,o=t?.isGemmaModel??!1,s=t?.providerOptionsNames??[`google`],c=!s.includes(`google`),l=t?.supportsFunctionResponseParts??!0,u=e=>{for(let t of s){let n=e.providerOptions?.[t];if(n!=null)return n}return c?e.providerOptions?.google:e.providerOptions?.googleVertex??e.providerOptions?.vertex};for(let{role:t,content:o}of e)switch(t){case`system`:if(!a)throw new n({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:switch(t.data.type){case`url`:e.push({fileData:{mimeType:S({part:t}),fileUri:t.data.url.toString()}});break;case`reference`:if(c)throw new n({functionality:`file parts with provider references`});e.push({fileData:{mimeType:S({part:t}),fileUri:_({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:z(t.mediaType)?t.mediaType:`text/plain`,data:O(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:S({part:t}),data:O(t.data.data)}});break}break}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{let t=u(e),r=t?.thoughtSignature==null?void 0:String(t.thoughtSignature);switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:r};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:r};case`reasoning-file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`data`:return{inlineData:{mimeType:e.mediaType,data:O(e.data.data)},thought:!0,thoughtSignature:r}}break;case`file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`reference`:if(c)throw new n({functionality:`file parts with provider references`});return{fileData:{mimeType:e.mediaType,fileUri:_({reference:e.data.reference,provider:`google`})},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`text`:return{inlineData:{mimeType:z(e.mediaType)?e.mediaType:`text/plain`,data:O(new TextEncoder().encode(e.data.text))},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`data`:return{inlineData:{mimeType:e.mediaType,data:O(e.data.data)},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r}}break;case`tool-call`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolCall:{toolType:i,args:typeof e.input==`string`?JSON.parse(e.input):e.input,id:n},thoughtSignature:r}:{functionCall:{name:e.toolName,args:e.input},thoughtSignature:r}}case`tool-result`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolResponse:{toolType:i,response:e.output.type===`json`?e.output.value:{},id:n},thoughtSignature:r}:void 0}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){if(t.type===`tool-approval-response`)continue;let n=u(t),r=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),a=n?.serverToolType==null?void 0:String(n.serverToolType);if(r&&a){let e=n?.thoughtSignature==null?void 0:String(n.thoughtSignature);if(i.length>0){let n=i[i.length-1];if(n.role===`model`){n.parts.push({toolResponse:{toolType:a,response:t.output.type===`json`?t.output.value:{},id:r},thoughtSignature:e});continue}}}let o=t.output;o.type===`content`?l?me(e,t.toolName,o.value):he(e,t.toolName,o.value):e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:o.type===`execution-denied`?o.reason??`Tool call execution denied.`:o.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
|
|
3
3
|
|
|
4
4
|
`);i[0].parts.unshift({text:e+`
|
|
5
5
|
|
|
6
|
-
`})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function B(e){return e.includes(`/`)?e:`models/${e}`}var V=y(()=>h(s({responseModalities:i(d([`TEXT`,`IMAGE`])).optional(),thinkingConfig:s({thinkingBudget:u().optional(),includeThoughts:r().optional(),thinkingLevel:d([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:o().optional(),structuredOutputs:r().optional(),safetySettings:i(s({category:d([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:d([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:d([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:r().optional(),labels:a(o(),o()).optional(),mediaResolution:d([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:s({aspectRatio:d([`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:d([`1K`,`2K`,`4K`,`512`]).optional()}).optional(),retrievalConfig:s({latLng:s({latitude:u(),longitude:u()}).optional()}).optional(),streamFunctionCallArguments:r().optional(),serviceTier:d([`standard`,`flex`,`priority`]).optional()}))),_e={standard:`SERVICE_TIER_STANDARD`,flex:`SERVICE_TIER_FLEX`,priority:`SERVICE_TIER_PRIORITY`};function ve({tools:e,toolChoice:t,modelId:r,isVertexProvider:i=!1}){e=e?.length?e:void 0;let a=[],o=[`gemini-flash-latest`,`gemini-flash-lite-latest`,`gemini-pro-latest`].some(e=>e===r),s=r.includes(`gemini-2`)||r.includes(`gemini-3`)||r.includes(`nano-banana`)||o,c=r.includes(`gemini-3`),l=r.includes(`gemini-2.5`)||r.includes(`gemini-3`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:a};let u=e.some(e=>e.type===`function`),d=e.some(e=>e.type===`provider`);if(u&&d&&!c&&a.push({type:`unsupported`,feature:`combination of function and provider-defined tools`}),d){let n=[];if(e.filter(e=>e.type===`provider`).forEach(e=>{switch(e.id){case`google.google_search`:s?n.push({googleSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Google Search requires Gemini 2.0 or newer.`});break;case`google.enterprise_web_search`:s?n.push({enterpriseWebSearch:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Enterprise Web Search requires Gemini 2.0 or newer.`});break;case`google.url_context`:s?n.push({urlContext:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:s?n.push({codeExecution:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The code execution tool is not supported with other Gemini models than Gemini 2.`});break;case`google.file_search`:l?n.push({fileSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The file search tool is only supported with Gemini 2.5 models and Gemini 3 models.`});break;case`google.vertex_rag_store`:s?n.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:e.args.ragCorpus},similarity_top_k:e.args.topK}}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The RAG store tool is not supported with other Gemini models than Gemini 2.`});break;case`google.google_maps`:s?n.push({googleMaps:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer.`});break;default:a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`});break}}),u&&c&&n.length>0){let r=[];for(let t of e)t.type===`function`&&r.push({name:t.name,description:t.description??``,parameters:z(t.inputSchema)});let o={functionCallingConfig:{mode:`VALIDATED`},...!i&&{includeServerSideToolInvocations:!0}};if(t!=null)switch(t.type){case`auto`:break;case`none`:o.functionCallingConfig={mode:`NONE`};break;case`required`:o.functionCallingConfig={mode:`ANY`};break;case`tool`:o.functionCallingConfig={mode:`ANY`,allowedFunctionNames:[t.toolName]};break}return{tools:[...n,{functionDeclarations:r}],toolConfig:o,toolWarnings:a}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:a}}let f=[],p=!1;for(let t of e)switch(t.type){case`function`:f.push({name:t.name,description:t.description??``,parameters:z(t.inputSchema)}),t.strict===!0&&(p=!0);break;default:a.push({type:`unsupported`,feature:`function tool ${t.name}`});break}if(t==null)return{tools:[{functionDeclarations:f}],toolConfig:p?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:a};let m=t.type;switch(m){case`auto`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`AUTO`}},toolWarnings:a};case`none`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:a};case`required`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`}},toolWarnings:a};case`tool`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:a};default:throw new n({functionality:`tool choice type: ${m}`})}}var ye=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=be(e),i=xe(this.accumulatedArgs,r);if(n.stringValue!=null&&i!==void 0){let e=JSON.stringify(n.stringValue).slice(1,-1);H(this.accumulatedArgs,r,i+n.stringValue),t+=e;continue}let a=Se(n);a!=null&&(H(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 be(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}function xe(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function H(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];r[n]??(r[n]=typeof i==`number`?[]:{}),r=r[n]}r[t[t.length-1]]=n}function Se(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 U({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 W=class e{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??D}static[C](e){return S({modelId:e.modelId,config:e.config})}static[w](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,reasoning:f,providerOptions:p},{isStreaming:h=!1}={}){let g=[],_=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],v;for(let e of _)if(v=await m({provider:e,providerOptions:p,schema:V}),v!=null)break;v==null&&!_.includes(`google`)&&(v=await m({provider:`google`,providerOptions:p,schema:V}));let y=this.config.provider.startsWith(`google.vertex.`);u?.some(e=>e.type===`provider`&&e.id===`google.vertex_rag_store`)&&!y&&g.push({type:`other`,message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`}),v?.streamFunctionCallArguments&&!y&&g.push({type:`other`,message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});let b=v?.serviceTier;v?.serviceTier&&y&&(b=_e[v.serviceTier]);let x=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:S,systemInstruction:C}=ge(e,{isGemmaModel:x,providerOptionsNames:_,supportsFunctionResponseParts:this.modelId.startsWith(`gemini-3`)}),{tools:w,toolConfig:T,toolWarnings:E}=ve({tools:u,toolChoice:d,modelId:this.modelId,isVertexProvider:y}),D=Ee({reasoning:f,modelId:this.modelId,warnings:g}),O=v?.thinkingConfig||D?{...D,...v?.thinkingConfig}:void 0,k=h&&y?v?.streamFunctionCallArguments??!1:void 0,A=T||k||v?.retrievalConfig?{...T,...k&&{functionCallingConfig:{...T?.functionCallingConfig,streamFunctionCallArguments:!0}},...v?.retrievalConfig&&{retrievalConfig:v.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(v?.structuredOutputs??!0)?z(c.schema):void 0,...v?.audioTimestamp&&{audioTimestamp:v.audioTimestamp},responseModalities:v?.responseModalities,thinkingConfig:O,...v?.mediaResolution&&{mediaResolution:v.mediaResolution},...v?.imageConfig&&{imageConfig:v.imageConfig}},contents:S,systemInstruction:x?void 0:C,safetySettings:v?.safetySettings,tools:w,toolConfig:A,cachedContent:v?.cachedContent,labels:v?.labels,serviceTier:b},warnings:[...g,...E],providerOptionsNames:_}}async doGenerate(e){let{args:t,warnings:n,providerOptionsNames:r}=await this.getArgs(e),i=e=>Object.fromEntries(r.map(t=>[t,e])),a=N(this.config.headers?await b(this.config.headers):void 0,e.headers),{responseHeaders:o,value:s,rawValue:c}=await _({url:`${this.config.baseURL}/${B(this.modelId)}:generateContent`,headers:a,body:t,failedResponseHandler:L,successfulResponseHandler:A(Ae),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.candidates[0],u=[],d=l.content?.parts??[],f=s.usageMetadata,p,m;for(let e of d)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();p=t,u.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in e&&e.codeExecutionResult)u.push({type:`tool-result`,toolCallId:p,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output??``}}),p=void 0;else if(`text`in e&&e.text!=null){let t=e.thoughtSignature?i({thoughtSignature:e.thoughtSignature}):void 0;if(e.text.length===0){if(t!=null&&u.length>0){let e=u[u.length-1];e.providerMetadata=t}}else u.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:t})}else if(`functionCall`in e&&e.functionCall.name!=null)u.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args??{}),providerMetadata:e.thoughtSignature?i({thoughtSignature:e.thoughtSignature}):void 0});else if(`inlineData`in e){let t=e.thought===!0,n=!!e.thoughtSignature;u.push({type:t?`reasoning-file`:`file`,data:{type:`data`,data:e.inlineData.data},mediaType:e.inlineData.mimeType,providerMetadata:n?i({thoughtSignature:e.thoughtSignature}):void 0})}else if(`toolCall`in e&&e.toolCall){let t=e.toolCall.id??this.config.generateId();m=t,u.push({type:`tool-call`,toolCallId:t,toolName:`server:${e.toolCall.toolType}`,input:JSON.stringify(e.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:e.thoughtSignature?i({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolCall.toolType}):i({serverToolCallId:t,serverToolType:e.toolCall.toolType})})}else if(`toolResponse`in e&&e.toolResponse){let t=m??e.toolResponse.id??this.config.generateId();u.push({type:`tool-result`,toolCallId:t,toolName:`server:${e.toolResponse.toolType}`,result:e.toolResponse.response??{},providerMetadata:e.thoughtSignature?i({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolResponse.toolType}):i({serverToolCallId:t,serverToolType:e.toolResponse.toolType})}),m=void 0}let h=G({groundingMetadata:l.groundingMetadata,generateId:this.config.generateId})??[];for(let e of h)u.push(e);return{content:u,finishReason:{unified:U({finishReason:l.finishReason,hasToolCalls:u.some(e=>e.type===`tool-call`&&!e.providerExecuted)}),raw:l.finishReason??void 0},usage:R(f),warnings:n,providerMetadata:i({promptFeedback:s.promptFeedback??null,groundingMetadata:l.groundingMetadata??null,urlContextMetadata:l.urlContextMetadata??null,safetyRatings:l.safetyRatings??null,usageMetadata:f??null,finishMessage:l.finishMessage??null,serviceTier:s.serviceTier??null}),request:{body:t},response:{headers:o,body:c}}}async doStream(e){let{args:t,warnings:n,providerOptionsNames:r}=await this.getArgs(e,{isStreaming:!0}),i=e=>Object.fromEntries(r.map(t=>[t,e])),a=N(this.config.headers?await b(this.config.headers):void 0,e.headers),{responseHeaders:o,value:s}=await _({url:`${this.config.baseURL}/${B(this.modelId)}:streamGenerateContent?alt=sse`,headers:a,body:t,failedResponseHandler:L,successfulResponseHandler:re(je),abortSignal:e.abortSignal,fetch:this.config.fetch}),c={unified:`other`,raw:void 0},l,u,d=null,f=null,p=null,m=this.config.generateId,h=!1,g=null,v=null,y=0,x=new Set,S,C,w=[];return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,a=r.usageMetadata;a!=null&&(l=a),r.serviceTier!=null&&(p=r.serviceTier);let o=r.candidates?.[0];if(o==null)return;let s=o.content;o.groundingMetadata!=null&&(d=o.groundingMetadata),o.urlContextMetadata!=null&&(f=o.urlContextMetadata);let _=G({groundingMetadata:o.groundingMetadata,generateId:m});if(_!=null)for(let e of _)e.sourceType===`url`&&!x.has(e.url)&&(x.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=m();S=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=S;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output??``}}),S=void 0)}else if(`text`in t&&t.text!=null){let e=t.thoughtSignature?i({thoughtSignature:t.thoughtSignature}):void 0;t.text.length===0?e!=null&&g!==null&&n.enqueue({type:`text-delta`,id:g,delta:``,providerMetadata:e}):t.thought===!0?(g!==null&&(n.enqueue({type:`text-end`,id:g}),g=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),g===null&&(g=String(y++),n.enqueue({type:`text-start`,id:g,providerMetadata:e})),n.enqueue({type:`text-delta`,id:g,delta:t.text,providerMetadata:e}))}else if(`inlineData`in t){g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),v!==null&&(n.enqueue({type:`reasoning-end`,id:v}),v=null);let e=t.thought===!0,r=t.thoughtSignature?i({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??m();C=e;let r=i({...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=C??t.toolResponse.id??m(),r=i({...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}),C=void 0}for(let t of e){if(!(`functionCall`in t))continue;let e=t.thoughtSignature?i({thoughtSignature:t.thoughtSignature}):void 0,r=t.functionCall.partialArgs!=null||t.functionCall.name!=null&&t.functionCall.willContinue===!0,a=t.functionCall.name==null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue==null,o=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&&t.functionCall.willContinue===!0){let r=m(),i=new ye;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{textDelta:a}=i.processPartialArgs(t.functionCall.partialArgs);a.length>0&&n.enqueue({type:`tool-input-delta`,id:r,delta:a,providerMetadata:e})}}else if(t.functionCall.partialArgs!=null&&w.length>0){let r=w[w.length-1],{textDelta:i}=r.accumulator.processPartialArgs(t.functionCall.partialArgs);i.length>0&&n.enqueue({type:`tool-input-delta`,id:r.toolCallId,delta:i,providerMetadata:e})}}else if(a&&w.length>0){let e=w.pop(),{finalJSON:t,closingDelta:r}=e.accumulator.finalize();r.length>0&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:r,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:t,providerMetadata:e.providerMetadata}),h=!0}else if(o){let r=m(),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}),h=!0}else if(s){let r=m(),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}),h=!0}}}o.finishReason!=null&&(c={unified:U({finishReason:o.finishReason,hasToolCalls:h}),raw:o.finishReason},u=i({promptFeedback:r.promptFeedback??null,groundingMetadata:d,urlContextMetadata:f,safetyRatings:o.safetyRatings??null,usageMetadata:a??null,finishMessage:o.finishMessage??null,serviceTier:p}))},flush(e){g!==null&&e.enqueue({type:`text-end`,id:g}),v!==null&&e.enqueue({type:`reasoning-end`,id:v}),e.enqueue({type:`finish`,finishReason:c,usage:R(l),providerMetadata:u})}})),response:{headers:o},request:{body:t}}}};function Ce(e){return/gemini-3[\.\-]/i.test(e)||/gemini-3$/i.test(e)}function we(){return 65536}function Te(e){let t=e.toLowerCase();return t.includes(`2.5-pro`)||t.includes(`gemini-3-pro-image`)?32768:24576}function Ee({reasoning:e,modelId:t,warnings:n}){if(ie(e))return Ce(t)&&!t.includes(`gemini-3-pro-image`)?De({reasoning:e,warnings:n}):Oe({reasoning:e,modelId:t,warnings:n})}function De({reasoning:e,warnings:t}){if(e===`none`)return{thinkingLevel:`minimal`};let n=v({reasoning:e,effortMap:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`high`},warnings:t});if(n!=null)return{thinkingLevel:n}}function Oe({reasoning:e,modelId:t,warnings:n}){if(e===`none`)return{thinkingBudget:0};let r=ee({reasoning:e,maxOutputTokens:we(),maxReasoningBudget:Te(t),minReasoningBudget:0,warnings:n});if(r!=null)return{thinkingBudget:r}}function G({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 K=()=>s({webSearchQueries:i(o()).nullish(),imageSearchQueries:i(o()).nullish(),retrievalQueries:i(o()).nullish(),searchEntryPoint:s({renderedContent:o()}).nullish(),groundingChunks:i(s({web:s({uri:o(),title:o().nullish()}).nullish(),image:s({sourceUri:o(),imageUri:o(),title:o().nullish(),domain:o().nullish()}).nullish(),retrievedContext:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),fileSearchStore:o().nullish()}).nullish(),maps:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),placeId:o().nullish()}).nullish()})).nullish(),groundingSupports:i(s({segment:s({startIndex:u().nullish(),endIndex:u().nullish(),text:o().nullish()}).nullish(),segment_text:o().nullish(),groundingChunkIndices:i(u()).nullish(),supportChunkIndices:i(u()).nullish(),confidenceScores:i(u()).nullish(),confidenceScore:i(u()).nullish()})).nullish(),retrievalMetadata:c([s({webDynamicRetrievalScore:u()}),s({})]).nullish()}),ke=s({jsonPath:o(),stringValue:o().nullish(),numberValue:u().nullish(),boolValue:r().nullish(),nullValue:l().nullish(),willContinue:r().nullish()}),q=()=>s({parts:i(c([s({functionCall:s({name:o().nullish(),args:l().nullish(),partialArgs:i(ke).nullish(),willContinue:r().nullish()}),thoughtSignature:o().nullish()}),s({inlineData:s({mimeType:o(),data:o()}),thought:r().nullish(),thoughtSignature:o().nullish()}),s({toolCall:s({toolType:o(),args:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({toolResponse:s({toolType:o(),response:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({executableCode:s({language:o(),code:o()}).nullish(),codeExecutionResult:s({outcome:o(),output:o().nullish()}).nullish(),text:o().nullish(),thought:r().nullish(),thoughtSignature:o().nullish()})])).nullish()}),J=()=>s({category:o().nullish(),probability:o().nullish(),probabilityScore:u().nullish(),severity:o().nullish(),severityScore:u().nullish(),blocked:r().nullish()}),Y=i(s({modality:o(),tokenCount:u()})).nullish(),X=s({cachedContentTokenCount:u().nullish(),thoughtsTokenCount:u().nullish(),promptTokenCount:u().nullish(),candidatesTokenCount:u().nullish(),totalTokenCount:u().nullish(),trafficType:o().nullish(),promptTokensDetails:Y,candidatesTokensDetails:Y}),Z=()=>s({urlMetadata:i(s({retrievedUrl:o(),urlRetrievalStatus:o()})).nullish()}),Ae=y(()=>h(s({candidates:i(s({content:q().nullish().or(s({}).strict()),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(J()).nullish(),groundingMetadata:K().nullish(),urlContextMetadata:Z().nullish()})),usageMetadata:X.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(J()).nullish()}).nullish(),serviceTier:o().nullish()}))),je=y(()=>h(s({candidates:i(s({content:q().nullish(),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(J()).nullish(),groundingMetadata:K().nullish(),urlContextMetadata:Z().nullish()})).nullish(),usageMetadata:X.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(J()).nullish()}).nullish(),serviceTier:o().nullish()}))),Me=j({id:`google.code_execution`,inputSchema:s({language:o().describe(`The programming language of the code.`),code:o().describe(`The code to be executed.`)}),outputSchema:s({outcome:o().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:o().describe(`The output from the code execution.`)})}),Ne=j({id:`google.enterprise_web_search`,inputSchema:y(()=>h(s({}))),outputSchema:y(()=>h(s({})))});s({fileSearchStoreNames:i(o()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:u().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:o().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()}).passthrough();var Pe=j({id:`google.file_search`,inputSchema:y(()=>h(s({}))),outputSchema:y(()=>h(s({})))}),Fe=j({id:`google.google_maps`,inputSchema:y(()=>h(s({}))),outputSchema:y(()=>h(s({})))});s({searchTypes:s({webSearch:s({}).optional(),imageSearch:s({}).optional()}).optional(),timeRangeFilter:s({startTime:o(),endTime:o()}).optional()}).passthrough();var Ie={googleSearch:j({id:`google.google_search`,inputSchema:y(()=>h(s({}))),outputSchema:y(()=>h(s({})))}),enterpriseWebSearch:Ne,googleMaps:Fe,urlContext:j({id:`google.url_context`,inputSchema:y(()=>h(s({}))),outputSchema:y(()=>h(s({})))}),fileSearch:Pe,codeExecution:Me,vertexRagStore:j({id:`google.vertex_rag_store`,inputSchema:y(()=>h(s({}))),outputSchema:y(()=>h(s({})))})},Le=y(()=>h(s({personGeneration:d([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:d([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()}))),Re=class e{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v4`}static[C](e){return S({modelId:e.modelId,config:e.config})}static[w](t){return new e(t.modelId,{},t.config)}get maxImagesPerCall(){return this.settings.maxImagesPerCall==null?Q(this.modelId)?10:4:this.settings.maxImagesPerCall}get provider(){return this.config.provider}async doGenerate(e){return Q(this.modelId)?this.doGenerateGemini(e):this.doGenerateImagen(e)}async doGenerateImagen(e){var t;let{prompt:n,n:r=1,size:i,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(u!=null&&u.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(d!=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.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&f.push({type:`unsupported`,feature:`seed`,details:"This model does not support the `seed` option through this provider."});let p=await m({provider:`google`,providerOptions:s,schema:Le}),h=((t=this.config._internal)?.currentDate)?.call(t)??new Date,g={sampleCount:r};a!=null&&(g.aspectRatio=a),p&&Object.assign(g,p);let v={instances:[{prompt:n}],parameters:g},{responseHeaders:y,value:x}=await _({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:N(this.config.headers?await b(this.config.headers):void 0,c),body:v,failedResponseHandler:L,successfulResponseHandler:A(ze),abortSignal:l,fetch:this.config.fetch});return{images:x.predictions.map(e=>e.bytesBase64Encoded),warnings:f,providerMetadata:{google:{images:x.predictions.map(()=>({}))}},response:{timestamp:h,modelId:this.modelId,headers:y}}}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 new W(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??D}).doGenerate({prompt:m,seed:o,providerOptions:{google:{responseModalities:[`IMAGE`],imageConfig:a?{aspectRatio:a}:void 0,...s?.google??{}}},headers:c,abortSignal:l}),g=((t=this.config._internal)?.currentDate)?.call(t)??new Date,_=[];for(let e of h.content)e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`&&_.push(M(e.data.data));return{images:_,warnings:f,providerMetadata:{google:{images:_.map(()=>({}))}},response:{timestamp:g,modelId:this.modelId,headers:h.response?.headers},usage:h.usage?{inputTokens:h.usage.inputTokens.total,outputTokens:h.usage.outputTokens.total,totalTokens:(h.usage.inputTokens.total??0)+(h.usage.outputTokens.total??0)}:void 0}}};function Q(e){return e.startsWith(`gemini-`)}var ze=y(()=>h(s({predictions:i(s({bytesBase64Encoded:o()})).default([])}))),Be=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(t){let n=await m({provider:`google`,providerOptions:t.providerOptions,schema:He}),r=this.config.headers(),i=this.config.fetch??globalThis.fetch,a=[];t.filename!=null&&a.push({type:`unsupported`,feature:`filename`});let o=E(t.data),s=t.mediaType,c=n?.displayName,l=await i(`${this.config.baseURL.replace(/\/v1beta$/,``)}/upload/v1beta/files`,{method:`POST`,headers:{...r,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(o.length),"X-Goog-Upload-Header-Content-Type":s,"Content-Type":`application/json`},body:JSON.stringify({file:{...c==null?{}:{display_name:c}}})});if(!l.ok){let t=await l.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to initiate resumable upload: ${l.status} ${t}`})}let u=l.headers.get(`x-goog-upload-url`);if(!u)throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`No upload URL returned from initiation request`});let d=await i(u,{method:`POST`,headers:{"Content-Length":String(o.length),"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:o});if(!d.ok){let t=await d.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to upload file data: ${d.status} ${t}`})}let f=(await d.json()).file,p=n?.pollIntervalMs??2e3,h=n?.pollTimeoutMs??3e5,g=Date.now();for(;f.state===`PROCESSING`;){if(Date.now()-g>h)throw new e({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${h}ms`});await T(p);let{value:t}=await P({url:`${this.config.baseURL}/${f.name}`,headers:N(r),successfulResponseHandler:A(Ve),failedResponseHandler:L,fetch:this.config.fetch});f=t}if(f.state===`FAILED`)throw new e({name:`GOOGLE_FILES_UPLOAD_FAILED`,message:`File processing failed for ${f.name}`});return{warnings:a,providerReference:{google:f.uri},mediaType:f.mimeType??t.mediaType,providerMetadata:{google:{name:f.name,displayName:f.displayName,mimeType:f.mimeType,sizeBytes:f.sizeBytes,state:f.state,uri:f.uri,...f.createTime==null?{}:{createTime:f.createTime},...f.updateTime==null?{}:{updateTime:f.updateTime},...f.expirationTime==null?{}:{expirationTime:f.expirationTime},...f.sha256Hash==null?{}:{sha256Hash:f.sha256Hash}}}}}},Ve=y(()=>h(s({name:o(),displayName:o().nullish(),mimeType:o(),sizeBytes:o().nullish(),createTime:o().nullish(),updateTime:o().nullish(),expirationTime:o().nullish(),sha256Hash:o().nullish(),uri:o(),state:o()}))),He=y(()=>h(s({displayName:o().nullish(),pollIntervalMs:u().positive().nullish(),pollTimeoutMs:u().positive().nullish()}).passthrough())),Ue=y(()=>h(s({pollIntervalMs:u().positive().nullish(),pollTimeoutMs:u().positive().nullish(),personGeneration:d([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:o().nullish(),referenceImages:i(s({bytesBase64Encoded:o().nullish(),gcsUri:o().nullish()})).nullish()}).passthrough())),We=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async doGenerate(t){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,i=[],a=await m({provider:`google`,providerOptions:t.providerOptions,schema:Ue}),o=[{}],s=o[0];if(t.prompt!=null&&(s.prompt=t.prompt),t.image!=null)if(t.image.type===`url`)i.push({type:`unsupported`,feature:`URL-based image input`,details:`Google Generative AI video models require base64-encoded images. URL will be ignored.`});else{let e=typeof t.image.data==`string`?t.image.data:O(t.image.data);s.image={inlineData:{mimeType:t.image.mediaType||`image/png`,data:e}}}a?.referenceImages!=null&&(s.referenceImages=a.referenceImages.map(e=>e.bytesBase64Encoded?{inlineData:{mimeType:`image/png`,data:e.bytesBase64Encoded}}:e.gcsUri?{gcsUri:e.gcsUri}:e));let c={sampleCount:t.n};if(t.aspectRatio&&(c.aspectRatio=t.aspectRatio),t.resolution&&(c.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[t.resolution]||t.resolution),t.duration&&(c.durationSeconds=t.duration),t.seed&&(c.seed=t.seed),a!=null){let e=a;e.personGeneration!==void 0&&e.personGeneration!==null&&(c.personGeneration=e.personGeneration),e.negativePrompt!==void 0&&e.negativePrompt!==null&&(c.negativePrompt=e.negativePrompt);for(let[t,n]of Object.entries(e))[`pollIntervalMs`,`pollTimeoutMs`,`personGeneration`,`negativePrompt`,`referenceImages`].includes(t)||(c[t]=n)}let{value:l}=await _({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:N(await b(this.config.headers),t.headers),body:{instances:o,parameters:c},successfulResponseHandler:A(Ge),failedResponseHandler:L,abortSignal:t.abortSignal,fetch:this.config.fetch}),u=l.name;if(!u)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No operation name returned from API`});let d=a?.pollIntervalMs??1e4,f=a?.pollTimeoutMs??6e5,p=Date.now(),h=l,g;for(;!h.done;){if(Date.now()-p>f)throw new e({name:`GOOGLE_VIDEO_GENERATION_TIMEOUT`,message:`Video generation timed out after ${f}ms`});if(await T(d),t.abortSignal?.aborted)throw new e({name:`GOOGLE_VIDEO_GENERATION_ABORTED`,message:`Video generation request was aborted`});let{value:n,responseHeaders:r}=await P({url:`${this.config.baseURL}/${u}`,headers:N(await b(this.config.headers),t.headers),successfulResponseHandler:A(Ge),failedResponseHandler:L,abortSignal:t.abortSignal,fetch:this.config.fetch});h=n,g=r}if(h.error)throw new e({name:`GOOGLE_VIDEO_GENERATION_FAILED`,message:`Video generation failed: ${h.error.message}`});let v=h.response;if(!v?.generateVideoResponse?.generatedSamples||v.generateVideoResponse.generatedSamples.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No videos in response. Response: ${JSON.stringify(h)}`});let y=[],x=[],S=(await b(this.config.headers))?.[`x-goog-api-key`];for(let e of v.generateVideoResponse.generatedSamples)if(e.video?.uri){let t=S?`${e.video.uri}${e.video.uri.includes(`?`)?`&`:`?`}key=${S}`:e.video.uri;y.push({type:`url`,url:t,mediaType:`video/mp4`}),x.push({uri:e.video.uri})}if(y.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No valid videos in response`});return{videos:y,warnings:i,response:{timestamp:r,modelId:this.modelId,headers:g},providerMetadata:{google:{videos:x}}}}},Ge=s({name:o().nullish(),done:r().nullish(),error:s({code:u().nullish(),message:o(),status:o().nullish()}).nullish(),response:s({generateVideoResponse:s({generatedSamples:i(s({video:s({uri:o().nullish()}).nullish()})).nullish()}).nullish()}).nullish()});function $(e={}){let t=ne(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=e.name??`google.generative-ai`,r=()=>g({"x-goog-api-key":te({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${I}`),i=i=>new W(i,{provider:n,baseURL:t,headers:r,generateId:e.generateId??D,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 se(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),o=(i,a={})=>new Re(i,a,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),s=()=>new Be({provider:n,baseURL:t,headers:r,fetch:e.fetch}),c=i=>new We(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch,generateId:e.generateId??D}),l=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return i(e)};return l.specificationVersion=`v4`,l.languageModel=i,l.chat=i,l.generativeAI=i,l.embedding=a,l.embeddingModel=a,l.textEmbedding=a,l.textEmbeddingModel=a,l.image=o,l.imageModel=o,l.video=c,l.videoModel=c,l.files=s,l.tools=Ie,l}var Ke=$();export{I as VERSION,$ as createGoogle,$ as createGoogleGenerativeAI,Ke as google};
|
|
6
|
+
`})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function _e(e){return e.includes(`/`)?e:`models/${e}`}var ve=R(()=>T(s({responseModalities:i(f([`TEXT`,`IMAGE`])).optional(),thinkingConfig:s({thinkingBudget:d().optional(),includeThoughts:r().optional(),thinkingLevel:f([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:o().optional(),structuredOutputs:r().optional(),safetySettings:i(s({category:f([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:r().optional(),labels:a(o(),o()).optional(),mediaResolution:f([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:s({aspectRatio:f([`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:f([`1K`,`2K`,`4K`,`512`]).optional()}).optional(),retrievalConfig:s({latLng:s({latitude:d(),longitude:d()}).optional()}).optional(),streamFunctionCallArguments:r().optional(),serviceTier:f([`standard`,`flex`,`priority`]).optional()}))),ye={standard:`SERVICE_TIER_STANDARD`,flex:`SERVICE_TIER_FLEX`,priority:`SERVICE_TIER_PRIORITY`};function be({tools:e,toolChoice:t,modelId:r,isVertexProvider:i=!1}){e=e?.length?e:void 0;let a=[],o=[`gemini-flash-latest`,`gemini-flash-lite-latest`,`gemini-pro-latest`].some(e=>e===r),s=r.includes(`gemini-2`)||r.includes(`gemini-3`)||r.includes(`nano-banana`)||o,c=r.includes(`gemini-3`),l=r.includes(`gemini-2.5`)||r.includes(`gemini-3`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:a};let u=e.some(e=>e.type===`function`),d=e.some(e=>e.type===`provider`);if(u&&d&&!c&&a.push({type:`unsupported`,feature:`combination of function and provider-defined tools`}),d){let n=[];if(e.filter(e=>e.type===`provider`).forEach(e=>{switch(e.id){case`google.google_search`:s?n.push({googleSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Google Search requires Gemini 2.0 or newer.`});break;case`google.enterprise_web_search`:s?n.push({enterpriseWebSearch:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Enterprise Web Search requires Gemini 2.0 or newer.`});break;case`google.url_context`:s?n.push({urlContext:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:s?n.push({codeExecution:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The code execution tool is not supported with other Gemini models than Gemini 2.`});break;case`google.file_search`:l?n.push({fileSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The file search tool is only supported with Gemini 2.5 models and Gemini 3 models.`});break;case`google.vertex_rag_store`:s?n.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:e.args.ragCorpus},similarity_top_k:e.args.topK}}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The RAG store tool is not supported with other Gemini models than Gemini 2.`});break;case`google.google_maps`:s?n.push({googleMaps:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer.`});break;default:a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`});break}}),u&&c&&n.length>0){let r=[];for(let t of e)t.type===`function`&&r.push({name:t.name,description:t.description??``,parameters:H(t.inputSchema)});let o={functionCallingConfig:{mode:`VALIDATED`},...!i&&{includeServerSideToolInvocations:!0}};if(t!=null)switch(t.type){case`auto`:break;case`none`:o.functionCallingConfig={mode:`NONE`};break;case`required`:o.functionCallingConfig={mode:`ANY`};break;case`tool`:o.functionCallingConfig={mode:`ANY`,allowedFunctionNames:[t.toolName]};break}return{tools:[...n,{functionDeclarations:r}],toolConfig:o,toolWarnings:a}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:a}}let f=[],p=!1;for(let t of e)switch(t.type){case`function`:f.push({name:t.name,description:t.description??``,parameters:H(t.inputSchema)}),t.strict===!0&&(p=!0);break;default:a.push({type:`unsupported`,feature:`function tool ${t.name}`});break}if(t==null)return{tools:[{functionDeclarations:f}],toolConfig:p?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:a};let m=t.type;switch(m){case`auto`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`AUTO`}},toolWarnings:a};case`none`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:a};case`required`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`}},toolWarnings:a};case`tool`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:a};default:throw new n({functionality:`tool choice type: ${m}`})}}var xe=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=Se(e),i=Ce(this.accumulatedArgs,r);if(n.stringValue!=null&&i!==void 0){let e=JSON.stringify(n.stringValue).slice(1,-1);we(this.accumulatedArgs,r,i+n.stringValue),t+=e;continue}let a=Te(n);a!=null&&(we(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 Se(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}function Ce(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function we(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];r[n]??(r[n]=typeof i==`number`?[]:{}),r=r[n]}r[t[t.length-1]]=n}function Te(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 Ee({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 De=class e{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??M}static[p](e){return C({modelId:e.modelId,config:e.config})}static[m](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,reasoning:f,providerOptions:p},{isStreaming:m=!1}={}){let g=[],_=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],v;for(let e of _)if(v=await h({provider:e,providerOptions:p,schema:ve}),v!=null)break;v==null&&!_.includes(`google`)&&(v=await h({provider:`google`,providerOptions:p,schema:ve}));let y=this.config.provider.startsWith(`google.vertex.`);u?.some(e=>e.type===`provider`&&e.id===`google.vertex_rag_store`)&&!y&&g.push({type:`other`,message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`}),v?.streamFunctionCallArguments&&!y&&g.push({type:`other`,message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});let b=v?.serviceTier;v?.serviceTier&&y&&(b=ye[v.serviceTier]);let x=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:S,systemInstruction:C}=ge(e,{isGemmaModel:x,providerOptionsNames:_,supportsFunctionResponseParts:this.modelId.startsWith(`gemini-3`)}),{tools:w,toolConfig:T,toolWarnings:E}=be({tools:u,toolChoice:d,modelId:this.modelId,isVertexProvider:y}),D=je({reasoning:f,modelId:this.modelId,warnings:g}),O=v?.thinkingConfig||D?{...D,...v?.thinkingConfig}:void 0,k=m&&y?v?.streamFunctionCallArguments??!1:void 0,ee=T||k||v?.retrievalConfig?{...T,...k&&{functionCallingConfig:{...T?.functionCallingConfig,streamFunctionCallArguments:!0}},...v?.retrievalConfig&&{retrievalConfig:v.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(v?.structuredOutputs??!0)?H(c.schema):void 0,...v?.audioTimestamp&&{audioTimestamp:v.audioTimestamp},responseModalities:v?.responseModalities,thinkingConfig:O,...v?.mediaResolution&&{mediaResolution:v.mediaResolution},...v?.imageConfig&&{imageConfig:v.imageConfig}},contents:S,systemInstruction:x?void 0:C,safetySettings:v?.safetySettings,tools:w,toolConfig:ee,cachedContent:v?.cachedContent,labels:v?.labels,serviceTier:b},warnings:[...g,...E],providerOptionsNames:_}}async doGenerate(e){let{args:t,warnings:n,providerOptionsNames:r}=await this.getArgs(e),i=e=>Object.fromEntries(r.map(t=>[t,e])),a=P(this.config.headers?await b(this.config.headers):void 0,e.headers),{responseHeaders:o,value:s,rawValue:c}=await y({url:`${this.config.baseURL}/${_e(this.modelId)}:generateContent`,headers:a,body:t,failedResponseHandler:V,successfulResponseHandler:N(Ve),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.candidates[0],u=[],d=l.content?.parts??[],f=s.usageMetadata,p,m;for(let e of d)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();p=t,u.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in e&&e.codeExecutionResult)u.push({type:`tool-result`,toolCallId:p,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output??``}}),p=void 0;else if(`text`in e&&e.text!=null){let t=e.thoughtSignature?i({thoughtSignature:e.thoughtSignature}):void 0;if(e.text.length===0){if(t!=null&&u.length>0){let e=u[u.length-1];e.providerMetadata=t}}else u.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:t})}else if(`functionCall`in e&&e.functionCall.name!=null)u.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args??{}),providerMetadata:e.thoughtSignature?i({thoughtSignature:e.thoughtSignature}):void 0});else if(`inlineData`in e){let t=e.thought===!0,n=!!e.thoughtSignature;u.push({type:t?`reasoning-file`:`file`,data:{type:`data`,data:e.inlineData.data},mediaType:e.inlineData.mimeType,providerMetadata:n?i({thoughtSignature:e.thoughtSignature}):void 0})}else if(`toolCall`in e&&e.toolCall){let t=e.toolCall.id??this.config.generateId();m=t,u.push({type:`tool-call`,toolCallId:t,toolName:`server:${e.toolCall.toolType}`,input:JSON.stringify(e.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:e.thoughtSignature?i({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolCall.toolType}):i({serverToolCallId:t,serverToolType:e.toolCall.toolType})})}else if(`toolResponse`in e&&e.toolResponse){let t=m??e.toolResponse.id??this.config.generateId();u.push({type:`tool-result`,toolCallId:t,toolName:`server:${e.toolResponse.toolType}`,result:e.toolResponse.response??{},providerMetadata:e.thoughtSignature?i({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolResponse.toolType}):i({serverToolCallId:t,serverToolType:e.toolResponse.toolType})}),m=void 0}let h=Pe({groundingMetadata:l.groundingMetadata,generateId:this.config.generateId})??[];for(let e of h)u.push(e);return{content:u,finishReason:{unified:Ee({finishReason:l.finishReason,hasToolCalls:u.some(e=>e.type===`tool-call`&&!e.providerExecuted)}),raw:l.finishReason??void 0},usage:le(f),warnings:n,providerMetadata:i({promptFeedback:s.promptFeedback??null,groundingMetadata:l.groundingMetadata??null,urlContextMetadata:l.urlContextMetadata??null,safetyRatings:l.safetyRatings??null,usageMetadata:f??null,finishMessage:l.finishMessage??null,serviceTier:s.serviceTier??null}),request:{body:t},response:{headers:o,body:c}}}async doStream(e){let{args:t,warnings:n,providerOptionsNames:r}=await this.getArgs(e,{isStreaming:!0}),i=e=>Object.fromEntries(r.map(t=>[t,e])),a=P(this.config.headers?await b(this.config.headers):void 0,e.headers),{responseHeaders:o,value:s}=await y({url:`${this.config.baseURL}/${_e(this.modelId)}:streamGenerateContent?alt=sse`,headers:a,body:t,failedResponseHandler:V,successfulResponseHandler:I(He),abortSignal:e.abortSignal,fetch:this.config.fetch}),c={unified:`other`,raw:void 0},l,u,d=null,f=null,p=null,m=this.config.generateId,h=!1,g=null,_=null,v=0,x=new Set,S,C,w=[];return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,a=r.usageMetadata;a!=null&&(l=a),r.serviceTier!=null&&(p=r.serviceTier);let o=r.candidates?.[0];if(o==null)return;let s=o.content;o.groundingMetadata!=null&&(d=o.groundingMetadata),o.urlContextMetadata!=null&&(f=o.urlContextMetadata);let y=Pe({groundingMetadata:o.groundingMetadata,generateId:m});if(y!=null)for(let e of y)e.sourceType===`url`&&!x.has(e.url)&&(x.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=m();S=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=S;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output??``}}),S=void 0)}else if(`text`in t&&t.text!=null){let e=t.thoughtSignature?i({thoughtSignature:t.thoughtSignature}):void 0;t.text.length===0?e!=null&&g!==null&&n.enqueue({type:`text-delta`,id:g,delta:``,providerMetadata:e}):t.thought===!0?(g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),_===null&&(_=String(v++),n.enqueue({type:`reasoning-start`,id:_,providerMetadata:e})),n.enqueue({type:`reasoning-delta`,id:_,delta:t.text,providerMetadata:e})):(_!==null&&(n.enqueue({type:`reasoning-end`,id:_}),_=null),g===null&&(g=String(v++),n.enqueue({type:`text-start`,id:g,providerMetadata:e})),n.enqueue({type:`text-delta`,id:g,delta:t.text,providerMetadata:e}))}else if(`inlineData`in t){g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),_!==null&&(n.enqueue({type:`reasoning-end`,id:_}),_=null);let e=t.thought===!0,r=t.thoughtSignature?i({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??m();C=e;let r=i({...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=C??t.toolResponse.id??m(),r=i({...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}),C=void 0}for(let t of e){if(!(`functionCall`in t))continue;let e=t.thoughtSignature?i({thoughtSignature:t.thoughtSignature}):void 0,r=t.functionCall.partialArgs!=null||t.functionCall.name!=null&&t.functionCall.willContinue===!0,a=t.functionCall.name==null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue==null,o=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&&t.functionCall.willContinue===!0){let r=m(),i=new xe;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{textDelta:a}=i.processPartialArgs(t.functionCall.partialArgs);a.length>0&&n.enqueue({type:`tool-input-delta`,id:r,delta:a,providerMetadata:e})}}else if(t.functionCall.partialArgs!=null&&w.length>0){let r=w[w.length-1],{textDelta:i}=r.accumulator.processPartialArgs(t.functionCall.partialArgs);i.length>0&&n.enqueue({type:`tool-input-delta`,id:r.toolCallId,delta:i,providerMetadata:e})}}else if(a&&w.length>0){let e=w.pop(),{finalJSON:t,closingDelta:r}=e.accumulator.finalize();r.length>0&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:r,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:t,providerMetadata:e.providerMetadata}),h=!0}else if(o){let r=m(),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}),h=!0}else if(s){let r=m(),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}),h=!0}}}o.finishReason!=null&&(c={unified:Ee({finishReason:o.finishReason,hasToolCalls:h}),raw:o.finishReason},u=i({promptFeedback:r.promptFeedback??null,groundingMetadata:d,urlContextMetadata:f,safetyRatings:o.safetyRatings??null,usageMetadata:a??null,finishMessage:o.finishMessage??null,serviceTier:p}))},flush(e){g!==null&&e.enqueue({type:`text-end`,id:g}),_!==null&&e.enqueue({type:`reasoning-end`,id:_}),e.enqueue({type:`finish`,finishReason:c,usage:le(l),providerMetadata:u})}})),response:{headers:o},request:{body:t}}}};function Oe(e){return/gemini-3[\.\-]/i.test(e)||/gemini-3$/i.test(e)}function ke(){return 65536}function Ae(e){let t=e.toLowerCase();return t.includes(`2.5-pro`)||t.includes(`gemini-3-pro-image`)?32768:24576}function je({reasoning:e,modelId:t,warnings:n}){if(k(e))return Oe(t)&&!t.includes(`gemini-3-pro-image`)?Me({reasoning:e,warnings:n}):Ne({reasoning:e,modelId:t,warnings:n})}function Me({reasoning:e,warnings:t}){if(e===`none`)return{thinkingLevel:`minimal`};let n=x({reasoning:e,effortMap:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`high`},warnings:t});if(n!=null)return{thinkingLevel:n}}function Ne({reasoning:e,modelId:t,warnings:n}){if(e===`none`)return{thinkingBudget:0};let r=g({reasoning:e,maxOutputTokens:ke(),maxReasoningBudget:Ae(t),minReasoningBudget:0,warnings:n});if(r!=null)return{thinkingBudget:r}}function Pe({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 Fe=()=>s({webSearchQueries:i(o()).nullish(),imageSearchQueries:i(o()).nullish(),retrievalQueries:i(o()).nullish(),searchEntryPoint:s({renderedContent:o()}).nullish(),groundingChunks:i(s({web:s({uri:o(),title:o().nullish()}).nullish(),image:s({sourceUri:o(),imageUri:o(),title:o().nullish(),domain:o().nullish()}).nullish(),retrievedContext:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),fileSearchStore:o().nullish()}).nullish(),maps:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),placeId:o().nullish()}).nullish()})).nullish(),groundingSupports:i(s({segment:s({startIndex:d().nullish(),endIndex:d().nullish(),text:o().nullish()}).nullish(),segment_text:o().nullish(),groundingChunkIndices:i(d()).nullish(),supportChunkIndices:i(d()).nullish(),confidenceScores:i(d()).nullish(),confidenceScore:i(d()).nullish()})).nullish(),retrievalMetadata:c([s({webDynamicRetrievalScore:d()}),s({})]).nullish()}),Ie=s({jsonPath:o(),stringValue:o().nullish(),numberValue:d().nullish(),boolValue:r().nullish(),nullValue:l().nullish(),willContinue:r().nullish()}),Le=()=>s({parts:i(c([s({functionCall:s({name:o().nullish(),args:l().nullish(),partialArgs:i(Ie).nullish(),willContinue:r().nullish()}),thoughtSignature:o().nullish()}),s({inlineData:s({mimeType:o(),data:o()}),thought:r().nullish(),thoughtSignature:o().nullish()}),s({toolCall:s({toolType:o(),args:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({toolResponse:s({toolType:o(),response:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({executableCode:s({language:o(),code:o()}).nullish(),codeExecutionResult:s({outcome:o(),output:o().nullish()}).nullish(),text:o().nullish(),thought:r().nullish(),thoughtSignature:o().nullish()})])).nullish()}),U=()=>s({category:o().nullish(),probability:o().nullish(),probabilityScore:d().nullish(),severity:o().nullish(),severityScore:d().nullish(),blocked:r().nullish()}),Re=i(s({modality:o(),tokenCount:d()})).nullish(),ze=s({cachedContentTokenCount:d().nullish(),thoughtsTokenCount:d().nullish(),promptTokenCount:d().nullish(),candidatesTokenCount:d().nullish(),totalTokenCount:d().nullish(),trafficType:o().nullish(),promptTokensDetails:Re,candidatesTokensDetails:Re}),Be=()=>s({urlMetadata:i(s({retrievedUrl:o(),urlRetrievalStatus:o()})).nullish()}),Ve=R(()=>T(s({candidates:i(s({content:Le().nullish().or(s({}).strict()),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(U()).nullish(),groundingMetadata:Fe().nullish(),urlContextMetadata:Be().nullish()})),usageMetadata:ze.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(U()).nullish()}).nullish(),serviceTier:o().nullish()}))),He=R(()=>T(s({candidates:i(s({content:Le().nullish(),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(U()).nullish(),groundingMetadata:Fe().nullish(),urlContextMetadata:Be().nullish()})).nullish(),usageMetadata:ze.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(U()).nullish()}).nullish(),serviceTier:o().nullish()}))),Ue=A({id:`google.code_execution`,inputSchema:s({language:o().describe(`The programming language of the code.`),code:o().describe(`The code to be executed.`)}),outputSchema:s({outcome:o().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:o().describe(`The output from the code execution.`)})}),We=A({id:`google.enterprise_web_search`,inputSchema:R(()=>T(s({}))),outputSchema:R(()=>T(s({})))});s({fileSearchStoreNames:i(o()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:d().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:o().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()}).passthrough();var Ge=A({id:`google.file_search`,inputSchema:R(()=>T(s({}))),outputSchema:R(()=>T(s({})))}),Ke=A({id:`google.google_maps`,inputSchema:R(()=>T(s({}))),outputSchema:R(()=>T(s({})))});s({searchTypes:s({webSearch:s({}).optional(),imageSearch:s({}).optional()}).optional(),timeRangeFilter:s({startTime:o(),endTime:o()}).optional()}).passthrough();var qe={googleSearch:A({id:`google.google_search`,inputSchema:R(()=>T(s({}))),outputSchema:R(()=>T(s({})))}),enterpriseWebSearch:We,googleMaps:Ke,urlContext:A({id:`google.url_context`,inputSchema:R(()=>T(s({}))),outputSchema:R(()=>T(s({})))}),fileSearch:Ge,codeExecution:Ue,vertexRagStore:A({id:`google.vertex_rag_store`,inputSchema:R(()=>T(s({}))),outputSchema:R(()=>T(s({})))})},Je=R(()=>T(s({personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:f([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()}))),Ye=class e{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v4`}static[p](e){return C({modelId:e.modelId,config:e.config})}static[m](t){return new e(t.modelId,{},t.config)}get maxImagesPerCall(){return this.settings.maxImagesPerCall==null?Xe(this.modelId)?10:4:this.settings.maxImagesPerCall}get provider(){return this.config.provider}async doGenerate(e){return Xe(this.modelId)?this.doGenerateGemini(e):this.doGenerateImagen(e)}async doGenerateImagen(e){var t;let{prompt:n,n:r=1,size:i,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(u!=null&&u.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(d!=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.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&f.push({type:`unsupported`,feature:`seed`,details:"This model does not support the `seed` option through this provider."});let p=await h({provider:`google`,providerOptions:s,schema:Je}),m=((t=this.config._internal)?.currentDate)?.call(t)??new Date,g={sampleCount:r};a!=null&&(g.aspectRatio=a),p&&Object.assign(g,p);let _={instances:[{prompt:n}],parameters:g},{responseHeaders:v,value:x}=await y({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:P(this.config.headers?await b(this.config.headers):void 0,c),body:_,failedResponseHandler:V,successfulResponseHandler:N(Ze),abortSignal:l,fetch:this.config.fetch});return{images:x.predictions.map(e=>e.bytesBase64Encoded),warnings:f,providerMetadata:{google:{images:x.predictions.map(()=>({}))}},response:{timestamp:m,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 new De(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??M}).doGenerate({prompt:m,seed:o,providerOptions:{google:{responseModalities:[`IMAGE`],imageConfig:a?{aspectRatio:a}:void 0,...s?.google??{}}},headers:c,abortSignal:l}),g=((t=this.config._internal)?.currentDate)?.call(t)??new Date,_=[];for(let e of h.content)e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`&&_.push(O(e.data.data));return{images:_,warnings:f,providerMetadata:{google:{images:_.map(()=>({}))}},response:{timestamp:g,modelId:this.modelId,headers:h.response?.headers},usage:h.usage?{inputTokens:h.usage.inputTokens.total,outputTokens:h.usage.outputTokens.total,totalTokens:(h.usage.inputTokens.total??0)+(h.usage.outputTokens.total??0)}:void 0}}};function Xe(e){return e.startsWith(`gemini-`)}var Ze=R(()=>T(s({predictions:i(s({bytesBase64Encoded:o()})).default([])}))),Qe=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(t){let n=await h({provider:`google`,providerOptions:t.providerOptions,schema:et}),r=this.config.headers(),i=this.config.fetch??globalThis.fetch,a=[];t.filename!=null&&a.push({type:`unsupported`,feature:`filename`});let o=te(t.data),s=t.mediaType,c=n?.displayName,l=await i(`${this.config.baseURL.replace(/\/v1beta$/,``)}/upload/v1beta/files`,{method:`POST`,headers:{...r,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(o.length),"X-Goog-Upload-Header-Content-Type":s,"Content-Type":`application/json`},body:JSON.stringify({file:{...c==null?{}:{display_name:c}}})});if(!l.ok){let t=await l.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to initiate resumable upload: ${l.status} ${t}`})}let u=l.headers.get(`x-goog-upload-url`);if(!u)throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`No upload URL returned from initiation request`});let d=await i(u,{method:`POST`,headers:{"Content-Length":String(o.length),"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:o});if(!d.ok){let t=await d.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to upload file data: ${d.status} ${t}`})}let f=(await d.json()).file,p=n?.pollIntervalMs??2e3,m=n?.pollTimeoutMs??3e5,g=Date.now();for(;f.state===`PROCESSING`;){if(Date.now()-g>m)throw new e({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${m}ms`});await F(p);let{value:t}=await j({url:`${this.config.baseURL}/${f.name}`,headers:P(r),successfulResponseHandler:N($e),failedResponseHandler:V,fetch:this.config.fetch});f=t}if(f.state===`FAILED`)throw new e({name:`GOOGLE_FILES_UPLOAD_FAILED`,message:`File processing failed for ${f.name}`});return{warnings:a,providerReference:{google:f.uri},mediaType:f.mimeType??t.mediaType,providerMetadata:{google:{name:f.name,displayName:f.displayName,mimeType:f.mimeType,sizeBytes:f.sizeBytes,state:f.state,uri:f.uri,...f.createTime==null?{}:{createTime:f.createTime},...f.updateTime==null?{}:{updateTime:f.updateTime},...f.expirationTime==null?{}:{expirationTime:f.expirationTime},...f.sha256Hash==null?{}:{sha256Hash:f.sha256Hash}}}}}},$e=R(()=>T(s({name:o(),displayName:o().nullish(),mimeType:o(),sizeBytes:o().nullish(),createTime:o().nullish(),updateTime:o().nullish(),expirationTime:o().nullish(),sha256Hash:o().nullish(),uri:o(),state:o()}))),et=R(()=>T(s({displayName:o().nullish(),pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish()}).passthrough())),tt=R(()=>T(s({pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish(),personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:o().nullish(),referenceImages:i(s({bytesBase64Encoded:o().nullish(),gcsUri:o().nullish()})).nullish()}).passthrough())),nt=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async doGenerate(t){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,i=[],a=await h({provider:`google`,providerOptions:t.providerOptions,schema:tt}),o=[{}],s=o[0];if(t.prompt!=null&&(s.prompt=t.prompt),t.image!=null)if(t.image.type===`url`)i.push({type:`unsupported`,feature:`URL-based image input`,details:`Google Generative AI video models require base64-encoded images. URL will be ignored.`});else{let e=typeof t.image.data==`string`?t.image.data:ne(t.image.data);s.image={inlineData:{mimeType:t.image.mediaType||`image/png`,data:e}}}a?.referenceImages!=null&&(s.referenceImages=a.referenceImages.map(e=>e.bytesBase64Encoded?{inlineData:{mimeType:`image/png`,data:e.bytesBase64Encoded}}:e.gcsUri?{gcsUri:e.gcsUri}:e));let c={sampleCount:t.n};if(t.aspectRatio&&(c.aspectRatio=t.aspectRatio),t.resolution&&(c.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[t.resolution]||t.resolution),t.duration&&(c.durationSeconds=t.duration),t.seed&&(c.seed=t.seed),a!=null){let e=a;e.personGeneration!==void 0&&e.personGeneration!==null&&(c.personGeneration=e.personGeneration),e.negativePrompt!==void 0&&e.negativePrompt!==null&&(c.negativePrompt=e.negativePrompt);for(let[t,n]of Object.entries(e))[`pollIntervalMs`,`pollTimeoutMs`,`personGeneration`,`negativePrompt`,`referenceImages`].includes(t)||(c[t]=n)}let{value:l}=await y({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:P(await b(this.config.headers),t.headers),body:{instances:o,parameters:c},successfulResponseHandler:N(rt),failedResponseHandler:V,abortSignal:t.abortSignal,fetch:this.config.fetch}),u=l.name;if(!u)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No operation name returned from API`});let d=a?.pollIntervalMs??1e4,f=a?.pollTimeoutMs??6e5,p=Date.now(),m=l,g;for(;!m.done;){if(Date.now()-p>f)throw new e({name:`GOOGLE_VIDEO_GENERATION_TIMEOUT`,message:`Video generation timed out after ${f}ms`});if(await F(d),t.abortSignal?.aborted)throw new e({name:`GOOGLE_VIDEO_GENERATION_ABORTED`,message:`Video generation request was aborted`});let{value:n,responseHeaders:r}=await j({url:`${this.config.baseURL}/${u}`,headers:P(await b(this.config.headers),t.headers),successfulResponseHandler:N(rt),failedResponseHandler:V,abortSignal:t.abortSignal,fetch:this.config.fetch});m=n,g=r}if(m.error)throw new e({name:`GOOGLE_VIDEO_GENERATION_FAILED`,message:`Video generation failed: ${m.error.message}`});let _=m.response;if(!_?.generateVideoResponse?.generatedSamples||_.generateVideoResponse.generatedSamples.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No videos in response. Response: ${JSON.stringify(m)}`});let v=[],x=[],S=(await b(this.config.headers))?.[`x-goog-api-key`];for(let e of _.generateVideoResponse.generatedSamples)if(e.video?.uri){let t=S?`${e.video.uri}${e.video.uri.includes(`?`)?`&`:`?`}key=${S}`:e.video.uri;v.push({type:`url`,url:t,mediaType:`video/mp4`}),x.push({uri:e.video.uri})}if(v.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No valid videos in response`});return{videos:v,warnings:i,response:{timestamp:r,modelId:this.modelId,headers:g},providerMetadata:{google:{videos:x}}}}},rt=s({name:o().nullish(),done:r().nullish(),error:s({code:d().nullish(),message:o(),status:o().nullish()}).nullish(),response:s({generateVideoResponse:s({generatedSamples:i(s({video:s({uri:o().nullish()}).nullish()})).nullish()}).nullish()}).nullish()});function W(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}}var it={pdf:`application/pdf`,txt:`text/plain`,md:`text/markdown`,markdown:`text/markdown`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};function at(e){let t=e.toLowerCase();for(let[e,n]of Object.entries(it))if(t.endsWith(`.${e}`))return n;return`application/octet-stream`}function ot(e){let t=e.split(`/`),n=t[t.length-1];return n&&n.length>0?n:void 0}function st({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.document_uri??n.source??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??ot(r),a=at(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 ct({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.document_uri??r.source??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??ot(i),o=at(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 G({annotations:e,generateId:t}){if(e==null)return[];let n=new Set,r=[];for(let i of e){let e=st({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 K({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 lt=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),ut=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function dt(e){return e.replace(/_call$/,``)}function ft(e){return e.replace(/_result$/,``)}function pt({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;switch(f.event_type){case`interaction.start`:{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`content.start`:{let e=f,n=e.content,a=e.index,o=`${i??`interaction`}:${a}`;if(n?.type===`text`){l.set(a,{kind:`text`,id:o,emittedSourceKeys:new Set}),r.enqueue({type:`text-start`,id:o});let e=G({annotations:n.annotations,generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),r.enqueue(t))}}else if(n?.type===`image`){let e=n;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}})}else if(n?.type===`thought`){let e=n.signature;l.set(a,{kind:`reasoning`,id:o,...e==null?{}:{signature:e}}),r.enqueue({type:`reasoning-start`,id:o})}else if(n?.type===`function_call`){let e=n,t=e.id??o;c=!0;let i={kind:`function_call`,id:o,toolCallId:t,toolName:e.name,arguments:e.arguments??{},...e.signature==null?{}:{signature:e.signature},startEmitted:!1};l.set(a,i),i.toolName!=null&&(r.enqueue({type:`tool-input-start`,id:t,toolName:i.toolName}),i.startEmitted=!0)}else if(n?.type!=null&<.has(n.type)){let e=n.type===`mcp_server_tool_call`?n.name??`mcp_server_tool`:dt(n.type),t=n.id??o,r={kind:`builtin_tool_call`,id:o,blockType:n.type,toolCallId:t,toolName:e,arguments:n.arguments??{},callEmitted:!1};l.set(a,r)}else if(n?.type!=null&&ut.has(n.type)){let e=n.type===`mcp_server_tool_result`?n.name??`mcp_server_tool`:ft(n.type),t=n.call_id??o,r={kind:`builtin_tool_result`,id:o,blockType:n.type,callId:t,toolName:e,result:n.result??null,...n.is_error==null?{}:{isError:n.is_error},resultEmitted:!1};l.set(a,r)}else l.set(a,{kind:`unknown`,id:o});break}case`content.delta`:{let e=f,n=l.get(e.index);if(n==null)break;let i=e.delta;if(n.kind===`text`&&i?.type===`text`){let e=i.text??``;e.length>0&&r.enqueue({type:`text-delta`,id:n.id,delta:e})}else if(n.kind===`text`&&i?.type===`text_annotation`){let e=G({annotations:i.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`&&i?.type===`image`)i.data!=null&&(n.data=i.data),i.mime_type!=null&&(n.mimeType=i.mime_type),i.uri!=null&&(n.uri=i.uri);else if(n.kind===`reasoning`){if(i?.type===`thought_summary`){let e=i.content;e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:n.id,delta:e.text})}else if(i?.type===`thought_signature`){let e=i.signature;e!=null&&(n.signature=e)}}else n.kind===`function_call`&&i?.type===`function_call`?(i.id!=null&&(n.toolCallId=i.id),i.name!=null&&(n.toolName=i.name),i.arguments!=null&&(n.arguments=i.arguments),i.signature!=null&&(n.signature=i.signature),!n.startEmitted&&n.toolName!=null&&(r.enqueue({type:`tool-input-start`,id:n.toolCallId,toolName:n.toolName}),n.startEmitted=!0),c=!0):n.kind===`builtin_tool_call`&&i?.type===n.blockType?(i.id!=null&&(n.toolCallId=i.id),i.arguments!=null&&(n.arguments=i.arguments),i.name!=null&&n.blockType===`mcp_server_tool_call`&&(n.toolName=i.name)):n.kind===`builtin_tool_result`&&i?.type===n.blockType&&(i.call_id!=null&&(n.callId=i.call_id),i.result!==void 0&&(n.result=i.result),i.is_error!=null&&(n.isError=i.is_error),i.name!=null&&n.blockType===`mcp_server_tool_result`&&(n.toolName=i.name));break}case`content.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.toolName??`unknown`,t=JSON.stringify(n.arguments??{});n.startEmitted||r.enqueue({type:`tool-input-start`,id:n.toolCallId,toolName:e}),r.enqueue({type:`tool-input-delta`,id:n.toolCallId,delta:t}),r.enqueue({type:`tool-input-end`,id:n.toolCallId});let a={};n.signature!=null&&(a.signature=n.signature),i!=null&&(a.interactionId=i);let o=Object.keys(a).length>0?{google:a}:void 0;r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:e,input:t,...o?{providerMetadata:o}:{}})}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=ct({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`:s=f.status;break;case`interaction.complete`:{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:K({status:s,hasFunctionCall:c}),raw:s},n={google:{...i==null?{}:{interactionId:i},...o==null?{}:{serviceTier:o}}};e.enqueue({type:`finish`,finishReason:t,usage:W(a),providerMetadata:n})}})}function mt({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?gt({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`){let e={type:`text`,text:n.text};t.push(e)}else if(n.type===`file`){let e=ht({part:n,warnings:i,mediaResolution:r});e!=null&&t.push(e)}let n=bt(t);n.length>0&&l.push({role:`user`,content:n});break}case`assistant`:{let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`reasoning`){let e=n.providerOptions?.google?.signature;t.push({type:`thought`,...e==null?{}:{signature:e},summary:n.text.length>0?[{type:`text`,text:n.text}]:void 0})}else if(n.type===`file`){let e=ht({part:n,warnings:i,mediaResolution:r});e!=null&&t.push(e)}else if(n.type===`tool-call`){let e=n.providerOptions?.google?.signature,r=typeof n.input==`string`?_t(n.input):n.input??{};t.push({type:`function_call`,id:n.toolCallId,name:n.toolName,arguments:r,...e==null?{}:{signature:e}})}else i.push({type:`other`,message:`google.interactions: unsupported assistant content part type "${n.type}"; part dropped.`});t.length>0&&l.push({role:`model`,content:t});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=vt({toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,signature:n.providerOptions?.google?.signature,warnings:i});t.push(e)}t.length>0&&l.push({role:`user`,content:t});break}}let u=c.length>0?c.join(`
|
|
7
|
+
|
|
8
|
+
`):void 0,d;return d=l.length===0?``:l.length===1&&l[0].role===`user`&&Array.isArray(l[0].content)?l[0].content:l,{input:d,systemInstruction:u,warnings:i}}function ht({part:e,warnings:t,mediaResolution:n}){if(e.data.type===`text`)return{type:`text`,text:e.data.text};let r=L(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=S({part:e});return{type:i,data:O(e.data.data),mime_type:t,...a}}case`url`:return{type:i,uri:e.data.url.toString(),...z(e.mediaType)?{mime_type:e.mediaType}:{},...a};case`reference`:{let t=_({reference:e.data.reference,provider:`google`});return{type:i,uri:t,...z(e.mediaType)?{mime_type:e.mediaType}:{},...a}}}}function gt({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):!0);if(e.length===0)continue;n.push({...i,content:e});continue}n.push(i)}return n}function _t(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{value:t}}catch{return{value:e}}}function vt({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(L(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=yt({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 yt({part:e,warnings:t}){switch(e.data.type){case`data`:{let t=z(e.mediaType)?e.mediaType:S({part:{type:`file`,mediaType:e.mediaType,data:e.data}});return{type:`image`,data:O(e.data.data),mime_type:t}}case`url`:return{type:`image`,uri:e.data.url.toString(),...z(e.mediaType)?{mime_type:e.mediaType}:{}};case`reference`:return{type:`image`,uri:_({reference:e.data.reference,provider:`google`}),...z(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 bt(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 q=()=>s({modality:o().nullish(),tokens:d().nullish()}).loose(),xt=()=>s({total_input_tokens:d().nullish(),total_output_tokens:d().nullish(),total_thought_tokens:d().nullish(),total_cached_tokens:d().nullish(),total_tool_use_tokens:d().nullish(),total_tokens:d().nullish(),input_tokens_by_modality:i(q()).nullish(),output_tokens_by_modality:i(q()).nullish(),cached_tokens_by_modality:i(q()).nullish(),tool_use_tokens_by_modality:i(q()).nullish(),grounding_tool_count:i(s({type:o().nullish(),count:d().nullish()}).loose()).nullish()}).loose(),St=()=>f([`in_progress`,`requires_action`,`completed`,`failed`,`cancelled`,`incomplete`]),Ct=()=>c([s({type:u(`url_citation`),url:o().nullish(),title:o().nullish(),start_index:d().nullish(),end_index:d().nullish()}).loose(),s({type:u(`file_citation`),file_name:o().nullish(),document_uri:o().nullish(),source:o().nullish(),page_number:d().nullish(),media_id:o().nullish(),start_index:d().nullish(),end_index:d().nullish(),custom_metadata:a(o(),l()).nullish()}).loose(),s({type:u(`place_citation`),name:o().nullish(),url:o().nullish(),place_id:o().nullish(),start_index:d().nullish(),end_index:d().nullish()}).loose(),s({type:o()}).loose()]),wt=()=>s({type:o(),text:o().nullish(),data:o().nullish(),mime_type:o().nullish()}).loose(),Tt=()=>{let e=s({type:u(`text`),text:o(),annotations:i(Ct()).nullish()}).loose(),t=s({type:u(`thought`),signature:o().nullish(),summary:i(wt()).nullish()}).loose(),n=s({type:u(`function_call`),id:o(),name:o(),arguments:a(o(),l()).nullish(),signature:o().nullish()}).loose();return c([e,s({type:u(`image`),data:o().nullish(),mime_type:o().nullish(),resolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:o().nullish()}).loose(),t,n,s({type:f([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),id:o(),arguments:a(o(),l()).nullish(),name:o().nullish(),server_name:o().nullish(),search_type:o().nullish(),signature:o().nullish()}).loose(),s({type:f([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]),call_id:o(),result:l().nullish(),is_error:r().nullish(),name:o().nullish(),server_name:o().nullish(),signature:o().nullish()}).loose(),s({type:o()}).loose()])},J=R(()=>T(s({id:o().nullish(),created:o().nullish(),updated:o().nullish(),status:St(),model:o().nullish(),agent:o().nullish(),outputs:i(Tt()).nullish(),usage:xt().nullish(),service_tier:o().nullish(),previous_interaction_id:o().nullish(),response_modalities:i(o()).nullish()}).loose())),Et=R(()=>T((()=>{let e=St(),t=Ct(),n=wt(),p=s({event_type:u(`interaction.start`),event_id:o().nullish(),interaction:s({id:o().nullish(),created:o().nullish(),model:o().nullish(),agent:o().nullish(),status:e.nullish()}).loose()}).loose(),m=s({event_type:u(`content.start`),event_id:o().nullish(),index:d(),content:Tt()}).loose(),h=s({type:u(`text`),text:o()}).loose(),g=s({type:u(`thought_summary`),content:n.nullish()}).loose(),_=s({type:u(`thought_signature`),signature:o().nullish()}).loose(),v=s({type:u(`function_call`),id:o(),name:o(),arguments:a(o(),l()).nullish(),signature:o().nullish()}).loose(),y=s({type:u(`text_annotation`),annotations:i(t).nullish()}).loose(),b=c([h,s({type:u(`image`),data:o().nullish(),mime_type:o().nullish(),resolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:o().nullish()}).loose(),g,_,v,y,s({type:f([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),id:o(),arguments:a(o(),l()).nullish(),name:o().nullish(),server_name:o().nullish(),search_type:o().nullish(),signature:o().nullish()}).loose(),s({type:f([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]),call_id:o(),result:l().nullish(),is_error:r().nullish(),name:o().nullish(),server_name:o().nullish(),signature:o().nullish()}).loose(),s({type:o()}).loose()]);return c([p,m,s({event_type:u(`content.delta`),event_id:o().nullish(),index:d(),delta:b}).loose(),s({event_type:u(`content.stop`),event_id:o().nullish(),index:d()}).loose(),s({event_type:u(`interaction.status_update`),event_id:o().nullish(),interaction_id:o().nullish(),status:e}).loose(),s({event_type:u(`interaction.complete`),event_id:o().nullish(),interaction:s({id:o().nullish(),status:e.nullish(),usage:xt().nullish(),service_tier:o().nullish()}).loose()}).loose(),s({event_type:u(`error`),event_id:o().nullish(),error:s({code:o().nullish(),message:o().nullish()}).loose().nullish()}).loose(),s({event_type:o()}).loose()])})())),Dt=R(()=>T(s({previousInteractionId:o().nullish(),store:r().nullish(),agent:o().nullish(),agentConfig:c([s({type:u(`dynamic`)}).loose(),s({type:u(`deep-research`),thinkingSummaries:f([`auto`,`none`]).nullish(),visualization:f([`off`,`auto`]).nullish(),collaborativePlanning:r().nullish()})]).nullish(),thinkingLevel:f([`minimal`,`low`,`medium`,`high`]).nullish(),thinkingSummaries:f([`auto`,`none`]).nullish(),imageConfig:s({aspectRatio:f([`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:f([`1K`,`2K`,`4K`,`512`]).nullish()}).nullish(),mediaResolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),responseModalities:i(f([`text`,`image`,`audio`,`video`,`document`])).nullish(),serviceTier:f([`flex`,`standard`,`priority`]).nullish(),systemInstruction:o().nullish(),signature:o().nullish(),interactionId:o().nullish(),pollingTimeoutMs:d().int().positive().nullish()})));function Y({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 Ot=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),kt=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function At(e){return e.replace(/_call$/,``)}function jt(e){return e.replace(/_result$/,``)}function Mt({outputs: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`text`:{let e=a.text??``,i=a.annotations;r.push({type:`text`,text:e,...Y({interactionId:n})});let o=G({annotations:i,generateId:t});for(let e of o)r.push(e);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,...Y({signature:e.signature,interactionId:n})});break}case`image`:{let e=a;e.data!=null&&e.data.length>0?r.push({type:`file`,mediaType:e.mime_type??`image/png`,data:{type:`data`,data:e.data},...Y({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)},...Y({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??{}),...Y({signature:e.signature,interactionId:n})});break}default:if(Ot.has(e)){let n=a,i=e===`mcp_server_tool_call`?n.name??`mcp_server_tool`:At(e),o=JSON.stringify(n.arguments??{});r.push({type:`tool-call`,toolCallId:n.id??t(),toolName:i,input:o,providerExecuted:!0})}else if(kt.has(e)){let n=a,i=e===`mcp_server_tool_result`?n.name??`mcp_server_tool`:jt(e);r.push({type:`tool-result`,toolCallId:n.call_id??t(),toolName:i,result:n.result??null});let o=ct({block:a,generateId:t});for(let e of o)r.push(e)}break}}return{content:r,hasFunctionCall:i}}var Nt=()=>globalThis.fetch;async function X({baseURL:e,interactionId:t,headers:n,fetch:r=Nt()}){if(t==null||t.length===0)return;let i=`${e}/interactions/${encodeURIComponent(t)}/cancel`;try{let e=await r(i,{method:`POST`,headers:E(P({"Content-Type":`application/json`},n),D()),body:`{}`});try{await e.text()}catch{}}catch{}}var Pt=new Set([`completed`,`failed`,`cancelled`,`incomplete`]);function Z(e){return e!=null&&Pt.has(e)}var Ft=1e3,It=1e4,Lt=1800*1e3;async function Rt({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,initialDelayMs:a=Ft,maxDelayMs:o=It,timeoutMs:s=Lt}){if(t==null||t.length===0)throw Error(`google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.`);let c=Date.now(),l=a,u=`${e}/interactions/${encodeURIComponent(t)}`,d=()=>X({baseURL:e,interactionId:t,headers:n,fetch:r});try{for(;;){if(i?.aborted)throw await d(),new DOMException(`Polling was aborted`,`AbortError`);if(Date.now()-c>s)throw Error(`google.interactions: timed out polling interaction ${t} after ${s}ms.`);await F(l,{abortSignal:i});let{value:e,rawValue:a,responseHeaders:f}=await j({url:u,headers:n,failedResponseHandler:V,successfulResponseHandler:N(J),abortSignal:i,fetch:r});if(Z(e.status))return{response:e,rawResponse:a,responseHeaders:f};l=Math.min(l*2,o)}}catch(e){throw B(e)&&await d(),e}}function zt({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 Bt=3,Vt=500;function Ht({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,maxRetries:a=Bt,retryDelayMs:o=Vt}){if(t.length===0)throw Error(`google.interactions: cannot stream a background interaction without an id.`);let s={...n,accept:`text/event-stream`},c,l=!1,u=0,d=!1,f,p=new AbortController,m=()=>p.abort();i!=null&&(i.aborted?p.abort():i.addEventListener(`abort`,m,{once:!0}));let h=p.signal;function g(){let n=`${e}/interactions/${encodeURIComponent(t)}`,r=new URLSearchParams({stream:`true`});return c!=null&&r.set(`last_event_id`,c),`${n}?${r.toString()}`}async function _(){let{value:e}=await j({url:g(),headers:s,failedResponseHandler:V,successfulResponseHandler:I(Et),abortSignal:h,fetch:r});return e.getReader()}return new ReadableStream({async start(s){try{for(;!l&&!h.aborted;){if(f==null)try{f=await _(),d=!1}catch(e){if(B(e)||h.aborted){s.error(e);return}if(u++,u>=a){s.error(e);return}await F(o*u,{abortSignal:h});continue}try{let{done:e,value:t}=await f.read();if(e){if(f=void 0,l)break;if(d)u=0;else{if(u++,u>=a){s.error(Error(`google.interactions: SSE stream closed without producing any events.`));return}await F(o*u,{abortSignal:h})}continue}if(d=!0,t.success){let e=t.value;typeof e.event_id==`string`&&e.event_id.length>0&&(c=e.event_id),(e.event_type===`interaction.complete`||e.event_type===`error`)&&(l=!0)}s.enqueue(t)}catch(e){if(B(e)||h.aborted){s.error(e);return}if(f=void 0,u++,u>=a){s.error(e);return}await F(o*u,{abortSignal:h})}}s.close()}catch(e){s.error(e)}finally{i?.removeEventListener(`abort`,m),f?.cancel().catch(()=>{}),f=void 0,h.aborted&&!l&&await X({baseURL:e,interactionId:t,headers:n,fetch:r})}},cancel(){p.abort(),f?.cancel().catch(()=>{}),f=void 0}})}function Ut({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}=Mt({outputs:e.outputs??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:K({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:W(e.usage),providerMetadata:h}),a.close()}})}var Wt=class e{constructor(e,t){this.specificationVersion=`v4`,typeof e==`string`?(this.modelId=e,this.agent=void 0):(this.modelId=e.agent,this.agent=e.agent),this.config=t}static[p](e){return{...C({modelId:e.modelId,config:e.config}),agent:e.agent}}static[m](t){return new e(t.agent==null?t.modelId:{agent:t.agent},t.config)}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?this.config.supportedUrls():{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(e){let t=[],n=await h({provider:`google`,providerOptions:e.providerOptions,schema:Dt}),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=zt({tools:e.tools,toolChoice:e.toolChoice});a=n.tools,o=n.toolChoice,t.push(...n.toolWarnings)}let s,c;e.responseFormat?.type===`json`&&(r?t.push({type:`other`,message:`google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored.`}):(s=`application/json`,e.responseFormat.schema!=null&&(c=e.responseFormat.schema)));let{input:l,systemInstruction:u,warnings:d}=mt({prompt:e.prompt,previousInteractionId:n?.previousInteractionId??void 0,store:n?.store??void 0,mediaResolution:n?.mediaResolution??void 0});t.push(...d);let f=u,p=n?.systemInstruction??void 0;f!=null&&p!=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.`}):f==null&&p!=null&&(f=p);let m;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.`}),m=void 0}else m=Q({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,image_config:n?.imageConfig==null?void 0:Q({aspect_ratio:n.imageConfig.aspectRatio??void 0,image_size:n.imageConfig.imageSize??void 0}),tool_choice:o});let g;if(r&&n?.agentConfig!=null){let e=n.agentConfig;e.type===`deep-research`?g=Q({type:`deep-research`,thinking_summaries:e.thinkingSummaries??void 0,visualization:e.visualization??void 0,collaborative_planning:e.collaborativePlanning??void 0}):e.type===`dynamic`&&(g={type:`dynamic`})}return{args:Q({...r?{agent:this.agent}:{model:this.modelId},input:l,system_instruction:f,tools:a,response_format:c,response_mime_type:s,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:m!=null&&Object.keys(m).length>0?m:void 0,agent_config:g,...r?{background:!0}:{}}),warnings:t,isAgent:r,pollingTimeoutMs:n?.pollingTimeoutMs??void 0}}async doGenerate(e){let{args:t,warnings:n,isAgent:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=P(this.config.headers?await b(this.config.headers):void 0,e.headers),{responseHeaders:s,value:c,rawValue:l}=await y({url:a,headers:o,body:t,failedResponseHandler:V,successfulResponseHandler:N(J),abortSignal:e.abortSignal,fetch:this.config.fetch});if(r&&!Z(c.status)){let t=await Rt({baseURL:this.config.baseURL,interactionId:c.id,headers:o,fetch:this.config.fetch,abortSignal:e.abortSignal,timeoutMs:i});c=t.response,l=t.rawResponse,s=t.responseHeaders??s}let u=typeof c.id==`string`&&c.id.length>0?c.id:void 0,{content:d,hasFunctionCall:f}=Mt({outputs:c.outputs??null,generateId:this.config.generateId??M,interactionId:u}),p={unified:K({status:c.status,hasFunctionCall:f}),raw:c.status},m=c.service_tier??s?.[`x-gemini-service-tier`]??void 0,h={google:{...u==null?{}:{interactionId:u},...m==null?{}:{serviceTier:m}}},g;if(typeof c.created==`string`){let e=new Date(c.created);Number.isNaN(e.getTime())||(g=e)}return{content:d,finishReason:p,usage:W(c.usage),warnings:n,providerMetadata:h,request:{body:t},response:{headers:s,body:l,...u==null?{}:{id:u},...g?{timestamp:g}:{},modelId:c.model??void 0}}}async doStream(e){let{args:t,warnings:n,isAgent:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=P(this.config.headers?await b(this.config.headers):void 0,e.headers);if(r)return this.doStreamBackground({args:t,warnings:n,url:a,mergedHeaders:o,options:e,pollingTimeoutMs:i});let s={...t,stream:!0},{responseHeaders:c,value:l}=await y({url:a,headers:o,body:s,failedResponseHandler:V,successfulResponseHandler:I(Et),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c?.[`x-gemini-service-tier`],d=pt({warnings:n,generateId:this.config.generateId??M,includeRawChunks:e.includeRawChunks,serviceTier:u});return{stream:l.pipeThrough(d),request:{body:s},response:{headers:c}}}async doStreamBackground({args:e,warnings:t,url:n,mergedHeaders:r,options:i,pollingTimeoutMs:a}){let{responseHeaders:o,value:s}=await y({url:n,headers:r,body:e,failedResponseHandler:V,successfulResponseHandler:N(J),abortSignal:i.abortSignal,fetch:this.config.fetch}),c=s.id;if(c==null||c.length===0)throw Error(`google.interactions: background POST response did not include an interaction id; cannot stream the result.`);let l=o?.[`x-gemini-service-tier`];if(Z(s.status))return{stream:Ut({response:s,warnings:t,generateId:this.config.generateId??M,includeRawChunks:i.includeRawChunks,headerServiceTier:l}),request:{body:e},response:{headers:o}};let u=Ht({baseURL:this.config.baseURL,interactionId:c,headers:r,fetch:this.config.fetch,abortSignal:i.abortSignal}),d=pt({warnings:t,generateId:this.config.generateId??M,includeRawChunks:i.includeRawChunks,serviceTier:l});return{stream:u.pipeThrough(d),request:{body:e},response:{headers:o}}}};function Q(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function $(e={}){let t=v(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=e.name??`google.generative-ai`,r=()=>E({"x-goog-api-key":w({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${re}`),i=i=>new De(i,{provider:n,baseURL:t,headers:r,generateId:e.generateId??M,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 oe(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),o=(i,a={})=>new Ye(i,a,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),s=()=>new Qe({provider:n,baseURL:t,headers:r,fetch:e.fetch}),c=i=>new nt(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch,generateId:e.generateId??M}),l=i=>new Wt(i,{provider:`${n}.interactions`,baseURL:t,headers:r,generateId:e.generateId??M,fetch:e.fetch}),u=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return i(e)};return u.specificationVersion=`v4`,u.languageModel=i,u.chat=i,u.generativeAI=i,u.embedding=a,u.embeddingModel=a,u.textEmbedding=a,u.textEmbeddingModel=a,u.image=o,u.imageModel=o,u.video=c,u.videoModel=c,u.files=s,u.interactions=l,u.tools=qe,u}var Gt=$();export{re as VERSION,$ as createGoogle,$ as createGoogleGenerativeAI,Gt as google};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AISDKError as e}from"../provider/index.js";import{Bi as t}from"../../_chunks/workflow/core-DOVmxHH8.js";import{At as n,Dt as r,En as i,Et as a,Nn as o,Rn as s,Tn as c,Tt as l,Xn as u,Zn as d,dn as f,fn as p,wn as m}from"../../_chunks/workflow/schemas-DFZoEyCn.js";import{n as h}from"../../_chunks/workflow/compat-CIROS3w4.js";import{D as ee,H as te,K as ne,P as g,S as _,V as re,W as ie,Z as v,n as ae,y as oe}from"../../_chunks/workflow/dist-Ci2brnHh.js";let y;y=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function se(e){return(await y).getRandomValues(new Uint8Array(e))}async function ce(e){let t=``;for(;t.length<e;){let n=await se(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function le(e){return await ce(e)}async function ue(e){let t=await(await y).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function de(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await le(e);return{code_verifier:t,code_challenge:await ue(t)}}var fe=`vercel.ai.error.AI_MCPClientError`,pe=Symbol.for(fe),me,he,b=class extends (he=e,me=pe,he){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i}){super({name:e,message:t,cause:n}),this[me]=!0,this.data=r,this.code=i}static isInstance(t){return e.hasMarker(t,fe)}},x=`2025-11-25`,ge=[x,`2025-06-18`,`2025-03-26`,`2024-11-05`],_e=i(o(s(),d())),ve=p({name:s(),version:s(),title:i(s())}),S=p({_meta:i(c({}).loose())}),C=S,w=c({method:s(),params:i(S)}),T=c({applyDefaults:i(n())}).loose(),ye=p({experimental:i(c({}).loose()),logging:i(c({}).loose()),prompts:i(p({listChanged:i(n())})),resources:i(p({subscribe:i(n()),listChanged:i(n())})),tools:i(p({listChanged:i(n())})),elicitation:i(T)});c({elicitation:i(T)}).loose();var be=C.extend({protocolVersion:s(),capabilities:ye,serverInfo:ve,instructions:i(s())}),E=C.extend({nextCursor:i(s())}),xe=c({name:s(),title:i(s()),description:i(s()),inputSchema:c({type:f(`object`),properties:i(c({}).loose())}).loose(),outputSchema:i(c({}).loose()),annotations:i(c({title:i(s())}).loose()),_meta:_e}).loose(),Se=E.extend({tools:a(xe)}),D=c({type:f(`text`),text:s()}).loose(),O=c({type:f(`image`),data:r(),mimeType:s()}).loose(),Ce=c({uri:s(),name:s(),title:i(s()),description:i(s()),mimeType:i(s()),size:i(m())}).loose(),we=E.extend({resources:a(Ce)}),k=c({uri:s(),name:i(s()),title:i(s()),mimeType:i(s())}).loose(),A=k.extend({text:s()}),j=k.extend({blob:r()}),M=c({type:f(`resource`),resource:u([A,j])}).loose(),N=c({type:f(`resource_link`),uri:s(),name:s(),description:i(s()),mimeType:i(s())}).loose(),Te=C.extend({content:a(u([D,O,M,N])),structuredContent:i(d()),isError:n().default(!1).optional()}).or(C.extend({toolResult:d()})),Ee=c({uriTemplate:s(),name:s(),title:i(s()),description:i(s()),mimeType:i(s())}).loose(),De=C.extend({resourceTemplates:a(Ee)}),Oe=C.extend({contents:a(u([A,j]))}),ke=c({name:s(),description:i(s()),required:i(n())}).loose(),Ae=c({name:s(),title:i(s()),description:i(s()),arguments:i(a(ke))}).loose(),je=E.extend({prompts:a(Ae)}),Me=c({role:u([f(`user`),f(`assistant`)]),content:u([D,O,M,N])}).loose(),Ne=C.extend({description:i(s()),messages:a(Me)}),Pe=S.extend({message:s(),requestedSchema:d()}),P=w.extend({method:f(`elicitation/create`),params:Pe}),F=C.extend({action:u([f(`accept`),f(`decline`),f(`cancel`)]),content:i(o(s(),d()))}),I=`2.0`,Fe=c({jsonrpc:f(I),id:u([s(),m().int()])}).merge(w).strict(),Ie=c({jsonrpc:f(I),id:u([s(),m().int()]),result:C}).strict(),Le=c({jsonrpc:f(I),id:u([s(),m().int()]),error:c({code:m().int(),message:s(),data:i(d())})}).strict(),L=u([Fe,c({jsonrpc:f(I)}).merge(c({method:s(),params:i(S)})).strict(),Ie,Le]);async function R(e){return L.parse(await g({text:e}))}var z=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,Re=c({access_token:s(),id_token:s().optional(),token_type:s(),expires_in:m().optional(),scope:s().optional(),refresh_token:s().optional()}).strip(),B=s().url().superRefine((e,n)=>{if(!URL.canParse(e))return n.addIssue({code:h.custom,message:`URL must be parseable`,fatal:!0}),t}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),ze=c({resource:s().url(),authorization_servers:a(B).optional(),jwks_uri:s().url().optional(),scopes_supported:a(s()).optional(),bearer_methods_supported:a(s()).optional(),resource_signing_alg_values_supported:a(s()).optional(),resource_name:s().optional(),resource_documentation:s().optional(),resource_policy_uri:s().url().optional(),resource_tos_uri:s().url().optional(),tls_client_certificate_bound_access_tokens:n().optional(),authorization_details_types_supported:a(s()).optional(),dpop_signing_alg_values_supported:a(s()).optional(),dpop_bound_access_tokens_required:n().optional()}).passthrough(),Be=c({issuer:s(),authorization_endpoint:B,token_endpoint:B,registration_endpoint:B.optional(),scopes_supported:a(s()).optional(),response_types_supported:a(s()),grant_types_supported:a(s()).optional(),code_challenge_methods_supported:a(s()),token_endpoint_auth_methods_supported:a(s()).optional(),token_endpoint_auth_signing_alg_values_supported:a(s()).optional()}).passthrough(),Ve=c({issuer:s(),authorization_endpoint:B,token_endpoint:B,userinfo_endpoint:B.optional(),jwks_uri:B,registration_endpoint:B.optional(),scopes_supported:a(s()).optional(),response_types_supported:a(s()),grant_types_supported:a(s()).optional(),subject_types_supported:a(s()),id_token_signing_alg_values_supported:a(s()),claims_supported:a(s()).optional(),token_endpoint_auth_methods_supported:a(s()).optional()}).passthrough().merge(Be.pick({code_challenge_methods_supported:!0})),He=c({client_id:s(),client_secret:s().optional(),client_id_issued_at:m().optional(),client_secret_expires_at:m().optional()}).strip(),Ue=c({redirect_uris:a(B),token_endpoint_auth_method:s().optional(),grant_types:a(s()).optional(),response_types:a(s()).optional(),client_name:s().optional(),client_uri:B.optional(),logo_uri:B.optional(),scope:s().optional(),contacts:a(s()).optional(),tos_uri:B.optional(),policy_uri:s().optional(),jwks_uri:B.optional(),jwks:l().optional(),software_id:s().optional(),software_version:s().optional(),software_statement:s().optional()}).strip(),We=c({error:s(),error_description:s().optional(),error_uri:s().optional()}),Ge=Ue.merge(He),Ke=`vercel.ai.error.AI_MCPClientOAuthError`,qe=Symbol.for(Ke),Je,Ye,V=class extends (Ye=e,Je=qe,Ye){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[Je]=!0}static isInstance(t){return e.hasMarker(t,Ke)}},H=class extends V{};H.errorCode=`server_error`;var U=class extends V{};U.errorCode=`invalid_client`;var W=class extends V{};W.errorCode=`invalid_grant`;var G=class extends V{};G.errorCode=`unauthorized_client`;var Xe={[H.errorCode]:H,[U.errorCode]:U,[W.errorCode]:W,[G.errorCode]:G};function Ze(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function K(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function Qe({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var q=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function J(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function $e(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Y(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Y(e,void 0,n):void 0;throw r}}async function et(e,t,n=fetch){return await Y(e,{"MCP-Protocol-Version":t},n)}function tt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function nt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??x,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=$e(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await et(o,a,n);return!r?.metadataUrl&&tt(s,i.pathname)&&(s=await et(new URL(`/.well-known/${t}`,i),a,n)),s}async function rt(e,t,n=fetch){let r=await nt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return ze.parse(await r.json())}function it(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function at(e,{fetchFn:t=fetch,protocolVersion:n=x}={}){let r={"MCP-Protocol-Version":n},i=it(e);for(let{url:e,type:n}of i){let i=await Y(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`)return Be.parse(await i.json());{let t=Ve.parse(await i.json());if(!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function ot(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await de(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,K(o)),{authorizationUrl:l,codeVerifier:d}}function st(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function X(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:ct(i,a,n);return;case`client_secret_post`:lt(i,a,r);return;case`none`:ut(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function ct(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function lt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function ut(e,t){t.set(`client_id`,e)}async function Z(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=We.parse(await g({text:n}));return new(Xe[e]||H)({message:t||``,cause:r})}catch(e){return new H({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function dt(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?s(d,f,e,t):X(st(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,K(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Z(p);return Re.parse(await p.json())}async function ft(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?a(l,u,e,t):X(st(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,K(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Z(d);return Re.parse({refresh_token:r,...await d.json()})}async function pt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Z(a);return Ge.parse(await a.json())}async function Q(e,t){try{return await $(e,t)}catch(n){if(n instanceof U||n instanceof G)return await e.invalidateCredentials?.call(e,`all`),await $(e,t);if(n instanceof W)return await e.invalidateCredentials?.call(e,`tokens`),await $(e,t);throw n}}async function mt(e,t,n){let r=Ze(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Qe({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function $(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;try{s=await rt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await mt(t,e,s),u=await at(c,{fetchFn:o}),d=await Promise.resolve(e.clientInformation());if(!d){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await pt(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(t),d=t}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await e.codeVerifier(),i=await dt(c,{metadata:u,clientInformation:d,authorizationCode:n,codeVerifier:t,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(i),`AUTHORIZED`}let f=await e.tokens();if(f?.refresh_token)try{let t=await ft(c,{metadata:u,clientInformation:d,refreshToken:f.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof V)||e instanceof H))throw e}let p=e.state?await e.state():void 0;p&&e.saveState&&await e.saveState(p);let{authorizationUrl:m,codeVerifier:h}=await ot(c,{metadata:u,clientInformation:d,state:p,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(m),`REDIRECT`}var ht=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":x};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return ne(t,`ai-sdk/${z}`,_())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=J(c);try{if(await Q(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new q;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new b({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new v).getReader(),u=async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await l.read();if(t){if(this.connected)throw this.connected=!1,new b({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:a,data:o}=i;if(a===`endpoint`){if(this.endpoint=new URL(o,this.url),this.endpoint.origin!==this.url.origin)throw new b({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(a===`message`)try{let e=await R(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new b({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new b({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=J(c);try{if(await Q(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new q;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new b({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}},gt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":x};if(this.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return ne(t,`ai-sdk/${z}`,_())}async start(){if(this.abortController)throw new b({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c),u=l.headers.get(`mcp-session-id`);if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=J(l);try{if(await Q(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new q}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(l.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!l.ok){let e=await l.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${e}`;l.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new b({message:t});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let d=l.headers.get(`content-type`)||``;if(d.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>L.parse(e)):[L.parse(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(d.includes(`text/event-stream`)){if(!l.body){let e=new b({message:`MCP HTTP Transport Error: text/event-stream response without body`});throw(o=this.onerror)==null||o.call(this,e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new v).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(a===`message`)try{let e=await R(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let f=new b({message:`MCP HTTP Transport Error: Unexpected content type: ${d}`});throw(s=this.onerror)==null||s.call(this,f),f}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new b({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=await this.commonHeaders({Accept:`text/event-stream`});t&&(a[`last-event-id`]=t);let o=await this.fetchFn(this.url.href,{method:`GET`,headers:a,signal:this.abortController?.signal,redirect:this.redirectMode}),s=o.headers.get(`mcp-session-id`);if(s&&(this.sessionId=s),o.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=J(o);try{if(await Q(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new q;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(o.status===405)return;if(!o.ok||!o.body){let e=new b({message:`MCP HTTP Transport Error: GET SSE failed: ${o.status} ${o.statusText}`});(i=this.onerror)==null||i.call(this,e);return}let c=o.body.pipeThrough(new TextDecoderStream).pipeThrough(new v).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),i===`message`)try{let t=await R(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>c.cancel()},this.inboundReconnectAttempts=0,l()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function _t(e){switch(e.type){case`sse`:return new ht(e);case`http`:return new gt(e);default:throw new b({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function vt(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var yt=`1.0.0`;function bt({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function xt(e){let t=new St(e);return await t.init(),t}var St=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=yt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},vt(e)?this.transport=e:this.transport=_t(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new b({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:x,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:be});if(e===void 0)throw new b({message:`Server sent invalid initialize result`});if(!ge.includes(e.protocolVersion))throw new b({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new b({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new b({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new b({message:`Server does not support prompts`});break;default:throw new b({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new b({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new b({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new b({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:Se,options:t})}async callTool({name:e,args:t,options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Te,options:{signal:n?.abortSignal}})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:we,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Oe,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:De,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:je,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Ne,options:n})}catch(e){throw e}}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!(r in t))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await l.callTool({name:r,args:e,options:t});return i.isError||u==null?i:l.extractStructuredContent(i,u,r)};n[r]={...t===`automatic`?oe({description:a,title:e,providerMetadata:{mcp:{clientName:this.clientInfo.name}},inputSchema:ee({...o,properties:o.properties??{},additionalProperties:!1}),execute:d,toModelOutput:bt}):ie({description:a,title:e,providerMetadata:{mcp:{clientName:this.clientInfo.name}},inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:d,toModelOutput:bt}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await te({value:e.structuredContent,schema:ae(t)});if(!r.success)throw new b({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await re({text:r.text,schema:t});if(!e.success)throw new b({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new b({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==P)throw new b({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=P.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=F.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new b({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new b({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new b({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{F as ElicitResultSchema,P as ElicitationRequestSchema,q as UnauthorizedError,Q as auth,xt as createMCPClient,xt as experimental_createMCPClient};
|
|
1
|
+
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{Bi as n}from"../../_chunks/workflow/core-DOVmxHH8.js";import{At as r,Dt as i,En as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,Zn as f,dn as p,fn as m,wn as h}from"../../_chunks/workflow/schemas-DFZoEyCn.js";import{n as ee}from"../../_chunks/workflow/compat-CIROS3w4.js";import{r as g}from"../../_chunks/workflow/dist-4zn5tehu.js";import{C as te,I as ne,L as re,V as _,_ as v,k as ie,m as ae,r as oe,t as se,z as ce}from"../../_chunks/workflow/dist-DTWUhyDN.js";let y;y=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function le(e){return(await y).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await y).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var me=`vercel.ai.error.AI_MCPClientError`,he=Symbol.for(me),ge,_e,b=class extends (_e=e,ge=he,_e){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i}){super({name:e,message:t,cause:n}),this[ge]=!0,this.data=r,this.code=i}static isInstance(t){return e.hasMarker(t,me)}},x=`2025-11-25`,ve=[x,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=a(s(c(),f())),be=m({name:c(),version:c(),title:a(c())}),S=m({_meta:a(l({}).loose())}),C=S,w=l({method:c(),params:a(S)}),T=l({applyDefaults:a(r())}).loose(),xe=m({experimental:a(l({}).loose()),logging:a(l({}).loose()),prompts:a(m({listChanged:a(r())})),resources:a(m({subscribe:a(r()),listChanged:a(r())})),tools:a(m({listChanged:a(r())})),elicitation:a(T)});l({elicitation:a(T)}).loose();var Se=C.extend({protocolVersion:c(),capabilities:xe,serverInfo:be,instructions:a(c())}),E=C.extend({nextCursor:a(c())}),Ce=l({name:c(),title:a(c()),description:a(c()),inputSchema:l({type:p(`object`),properties:a(l({}).loose())}).loose(),outputSchema:a(l({}).loose()),annotations:a(l({title:a(c())}).loose()),_meta:ye}).loose(),we=E.extend({tools:o(Ce)}),D=l({type:p(`text`),text:c()}).loose(),O=l({type:p(`image`),data:i(),mimeType:c()}).loose(),Te=l({uri:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c()),size:a(h())}).loose(),Ee=E.extend({resources:o(Te)}),k=l({uri:c(),name:a(c()),title:a(c()),mimeType:a(c())}).loose(),A=k.extend({text:c()}),j=k.extend({blob:i()}),M=l({type:p(`resource`),resource:d([A,j])}).loose(),N=l({type:p(`resource_link`),uri:c(),name:c(),description:a(c()),mimeType:a(c())}).loose(),De=C.extend({content:o(d([D,O,M,N])),structuredContent:a(f()),isError:r().default(!1).optional()}).or(C.extend({toolResult:f()})),Oe=l({uriTemplate:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c())}).loose(),ke=C.extend({resourceTemplates:o(Oe)}),Ae=C.extend({contents:o(d([A,j]))}),je=l({name:c(),description:a(c()),required:a(r())}).loose(),Me=l({name:c(),title:a(c()),description:a(c()),arguments:a(o(je))}).loose(),Ne=E.extend({prompts:o(Me)}),Pe=l({role:d([p(`user`),p(`assistant`)]),content:d([D,O,M,N])}).loose(),Fe=C.extend({description:a(c()),messages:o(Pe)}),Ie=S.extend({message:c(),requestedSchema:f()}),P=w.extend({method:p(`elicitation/create`),params:Ie}),F=C.extend({action:d([p(`accept`),p(`decline`),p(`cancel`)]),content:a(s(c(),f()))}),I=`2.0`,Le=l({jsonrpc:p(I),id:d([c(),h().int()])}).merge(w).strict(),Re=l({jsonrpc:p(I),id:d([c(),h().int()]),result:C}).strict(),ze=l({jsonrpc:p(I),id:d([c(),h().int()]),error:l({code:h().int(),message:c(),data:a(f())})}).strict(),L=d([Le,l({jsonrpc:p(I)}).merge(l({method:c(),params:a(S)})).strict(),Re,ze]);async function R(e){return L.parse(await ie({text:e}))}var Be=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,Ve=l({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:h().optional(),scope:c().optional(),refresh_token:c().optional()}).strip(),z=c().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ee.custom,message:`URL must be parseable`,fatal:!0}),n}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),He=l({resource:c().url(),authorization_servers:o(z).optional(),jwks_uri:c().url().optional(),scopes_supported:o(c()).optional(),bearer_methods_supported:o(c()).optional(),resource_signing_alg_values_supported:o(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:r().optional(),authorization_details_types_supported:o(c()).optional(),dpop_signing_alg_values_supported:o(c()).optional(),dpop_bound_access_tokens_required:r().optional()}).passthrough(),Ue=l({issuer:c(),authorization_endpoint:z,token_endpoint:z,registration_endpoint:z.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),code_challenge_methods_supported:o(c()),token_endpoint_auth_methods_supported:o(c()).optional(),token_endpoint_auth_signing_alg_values_supported:o(c()).optional()}).passthrough(),We=l({issuer:c(),authorization_endpoint:z,token_endpoint:z,userinfo_endpoint:z.optional(),jwks_uri:z,registration_endpoint:z.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),subject_types_supported:o(c()),id_token_signing_alg_values_supported:o(c()),claims_supported:o(c()).optional(),token_endpoint_auth_methods_supported:o(c()).optional()}).passthrough().merge(Ue.pick({code_challenge_methods_supported:!0})),Ge=l({client_id:c(),client_secret:c().optional(),client_id_issued_at:h().optional(),client_secret_expires_at:h().optional()}).strip(),Ke=l({redirect_uris:o(z),token_endpoint_auth_method:c().optional(),grant_types:o(c()).optional(),response_types:o(c()).optional(),client_name:c().optional(),client_uri:z.optional(),logo_uri:z.optional(),scope:c().optional(),contacts:o(c()).optional(),tos_uri:z.optional(),policy_uri:c().optional(),jwks_uri:z.optional(),jwks:u().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),qe=l({error:c(),error_description:c().optional(),error_uri:c().optional()}),Je=Ke.merge(Ge),Ye=`vercel.ai.error.AI_MCPClientOAuthError`,Xe=Symbol.for(Ye),Ze,Qe,B=class extends (Qe=e,Ze=Xe,Qe){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[Ze]=!0}static isInstance(t){return e.hasMarker(t,Ye)}},V=class extends B{};V.errorCode=`server_error`;var H=class extends B{};H.errorCode=`invalid_client`;var U=class extends B{};U.errorCode=`invalid_grant`;var W=class extends B{};W.errorCode=`unauthorized_client`;var $e={[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U,[W.errorCode]:W};function et(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function G(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function tt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var K=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function q(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function nt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function rt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function it(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function at(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??x,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=nt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await rt(o,a,n);return!r?.metadataUrl&&it(s,i.pathname)&&(s=await rt(new URL(`/.well-known/${t}`,i),a,n)),s}async function ot(e,t,n=fetch){let r=await at(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return He.parse(await r.json())}function st(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function ct(e,{fetchFn:t=fetch,protocolVersion:n=x}={}){let r={"MCP-Protocol-Version":n},i=st(e);for(let{url:e,type:n}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`)return Ue.parse(await i.json());{let t=We.parse(await i.json());if(!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function lt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await pe(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,G(o)),{authorizationUrl:l,codeVerifier:d}}function ut(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function dt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:ft(i,a,n);return;case`client_secret_post`:pt(i,a,r);return;case`none`:mt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function ft(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function pt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function mt(e,t){t.set(`client_id`,e)}async function Y(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=qe.parse(await ie({text:n}));return new($e[e]||V)({message:t||``,cause:r})}catch(e){return new V({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function ht(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?s(d,f,e,t):dt(ut(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,G(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Y(p);return Ve.parse(await p.json())}async function gt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?a(l,u,e,t):dt(ut(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,G(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Y(d);return Ve.parse({refresh_token:r,...await d.json()})}async function _t(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Y(a);return Je.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof H||n instanceof W)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof U)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function vt(e,t,n){let r=et(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!tt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;try{s=await ot(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await vt(t,e,s),u=await ct(c,{fetchFn:o}),d=await Promise.resolve(e.clientInformation());if(!d){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await _t(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(t),d=t}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await e.codeVerifier(),i=await ht(c,{metadata:u,clientInformation:d,authorizationCode:n,codeVerifier:t,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(i),`AUTHORIZED`}let f=await e.tokens();if(f?.refresh_token)try{let t=await gt(c,{metadata:u,clientInformation:d,refreshToken:f.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof B)||e instanceof V))throw e}let p=e.state?await e.state():void 0;p&&e.saveState&&await e.saveState(p);let{authorizationUrl:m,codeVerifier:h}=await lt(c,{metadata:u,clientInformation:d,state:p,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(m),`REDIRECT`}var yt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return _(t,`ai-sdk/${Be}`,v())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new b({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),u=async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await l.read();if(t){if(this.connected)throw this.connected=!1,new b({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:a,data:o}=i;if(a===`endpoint`){if(this.endpoint=new URL(o,this.url),this.endpoint.origin!==this.url.origin)throw new b({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(a===`message`)try{let e=await R(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new b({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new b({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new b({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}},bt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return _(t,`ai-sdk/${Be}`,v())}async start(){if(this.abortController)throw new b({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c),u=l.headers.get(`mcp-session-id`);if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new K}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(l.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!l.ok){let e=await l.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${e}`;l.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new b({message:t});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let d=l.headers.get(`content-type`)||``;if(d.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>L.parse(e)):[L.parse(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(d.includes(`text/event-stream`)){if(!l.body){let e=new b({message:`MCP HTTP Transport Error: text/event-stream response without body`});throw(o=this.onerror)==null||o.call(this,e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(a===`message`)try{let e=await R(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let f=new b({message:`MCP HTTP Transport Error: Unexpected content type: ${d}`});throw(s=this.onerror)==null||s.call(this,f),f}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new b({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=await this.commonHeaders({Accept:`text/event-stream`});t&&(a[`last-event-id`]=t);let o=await this.fetchFn(this.url.href,{method:`GET`,headers:a,signal:this.abortController?.signal,redirect:this.redirectMode}),s=o.headers.get(`mcp-session-id`);if(s&&(this.sessionId=s),o.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(o);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(o.status===405)return;if(!o.ok||!o.body){let e=new b({message:`MCP HTTP Transport Error: GET SSE failed: ${o.status} ${o.statusText}`});(i=this.onerror)==null||i.call(this,e);return}let c=o.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),i===`message`)try{let t=await R(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>c.cancel()},this.inboundReconnectAttempts=0,l()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function xt(e){switch(e.type){case`sse`:return new yt(e);case`http`:return new bt(e);default:throw new b({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function St(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Ct=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,wt=`ui/resourceUri`,Tt={extensions:{[Ct]:{mimeTypes:[Q]}}};function Et(e){let n=e?.ui;return t(n)?n:void 0}function Dt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Ot(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function kt(e){let t=Et(e._meta),n=t?.resourceUri??e._meta?.[wt],r=Ot(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function At(e){let t=[],n=[];for(let r of e.tools){let e=kt(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function jt({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(oe(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Dt(n._meta)}}async function Mt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return jt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Nt=`1.0.0`;function Pt({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function $(e){let t=new Ft(e);return await t.init(),t}var Ft=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Nt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},St(e)?this.transport=e:this.transport=xt(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new b({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:x,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Se});if(e===void 0)throw new b({message:`Server sent invalid initialize result`});if(!ve.includes(e.protocolVersion))throw new b({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new b({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new b({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new b({message:`Server does not support prompts`});break;default:throw new b({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new b({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new b({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new b({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:we,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:De,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Ee,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Ae,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:ke,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Ne,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Fe,options:n})}catch(e){throw e}}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!(r in t))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=kt({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...d?.resourceUri==null?{}:{app:{...d,mimeType:Q}}},p=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await l.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||u==null?i:l.extractStructuredContent(i,u,r)};n[r]={...t===`automatic`?ae({description:a,title:e,metadata:f,inputSchema:te({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:Pt}):ce({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:Pt}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await re({value:e.structuredContent,schema:se(t)});if(!r.success)throw new b({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await ne({text:r.text,schema:t});if(!e.success)throw new b({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new b({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==P)throw new b({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=P.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=F.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new b({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new b({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new b({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{F as ElicitResultSchema,P as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,K as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Tt as mcpAppClientCapabilities,Mt as readMCPAppResource,At as splitMCPAppTools};
|