experimental-ash 0.8.3 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/dist/docs/public/channels/slack.md +76 -25
  3. package/dist/src/compiled/.vendor-stamp.json +14 -14
  4. package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
  5. package/dist/src/compiled/@ai-sdk/google/index.js +4 -4
  6. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  7. package/dist/src/compiled/@ai-sdk/openai/index.js +6 -6
  8. package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
  9. package/dist/src/compiled/@ai-sdk/provider/_json-schema.d.ts +5 -0
  10. package/dist/src/compiled/@ai-sdk/provider/index.d.ts +6632 -1
  11. package/dist/src/compiled/@chat-adapter/slack/_chat-adapter-shared.d.ts +9 -0
  12. package/dist/src/compiled/@chat-adapter/slack/index.d.ts +632 -54
  13. package/dist/src/compiled/@chat-adapter/slack/index.js +25 -29
  14. package/dist/src/compiled/@chat-adapter/slack/package.json +1 -1
  15. package/dist/src/compiled/@chat-adapter/state-memory/index.d.ts +41 -25
  16. package/dist/src/compiled/@chat-adapter/state-memory/package.json +1 -1
  17. package/dist/src/compiled/@standard-schema/spec/index.d.ts +115 -62
  18. package/dist/src/compiled/@vercel/sandbox/index.d.ts +4 -1
  19. package/dist/src/compiled/@vercel/sandbox/index.js +5 -5
  20. package/dist/src/compiled/@workflow/core/index.js +1 -1
  21. package/dist/src/compiled/@workflow/core/runtime.d.ts +6 -2
  22. package/dist/src/compiled/@workflow/core/runtime.js +4 -4
  23. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  24. package/dist/src/compiled/@workflow/errors/_ms.d.ts +4 -0
  25. package/dist/src/compiled/@workflow/errors/error-codes.d.ts +17 -0
  26. package/dist/src/compiled/@workflow/errors/index.d.ts +438 -56
  27. package/dist/src/compiled/@workflow/errors/index.js +1 -1
  28. package/dist/src/compiled/_chunks/node/{auth-CdwuOxMs.js → auth-vbe4XEEK.js} +2 -2
  29. package/dist/src/compiled/_chunks/node/{dist-B6IOtzm1.js → dist-BdWHjlRQ.js} +12 -12
  30. package/dist/src/compiled/_chunks/node/retry-BOcy5BbJ.js +1 -0
  31. package/dist/src/compiled/_chunks/workflow/{context-errors-CXifqq6a.js → context-errors-zbKocOyk.js} +1 -1
  32. package/dist/src/compiled/_chunks/workflow/{dist-BuELZxm6.js → dist-Ci2brnHh.js} +3 -3
  33. package/dist/src/compiled/_chunks/workflow/{resume-hook-CgfgCU87.js → resume-hook-CL8Ed91K.js} +2 -2
  34. package/dist/src/compiled/_chunks/workflow/sleep-Dn3i9nxI.js +1 -0
  35. package/dist/src/compiled/chat/_mdast.d.ts +24 -0
  36. package/dist/src/compiled/chat/_workflow-serde.d.ts +5 -0
  37. package/dist/src/compiled/chat/index.d.ts +3851 -72
  38. package/dist/src/compiled/chat/index.js +1 -1
  39. package/dist/src/compiled/chat/jsx-runtime-DxGwoLu2.d.ts +782 -0
  40. package/dist/src/compiled/chat/package.json +1 -1
  41. package/dist/src/compiled/just-bash/index.js +1 -1
  42. package/dist/src/execution/authorization-challenge-defaults.d.ts +1 -1
  43. package/dist/src/execution/authorization-challenge-defaults.js +1 -1
  44. package/dist/src/internal/application/package.js +1 -1
  45. package/dist/src/public/channels/slack/index.d.ts +1 -1
  46. package/dist/src/public/channels/slack/slack.d.ts +2 -1
  47. package/dist/src/public/channels/slack/slack.js +5 -1
  48. package/dist/src/public/channels/slack/slackChannel.d.ts +67 -5
  49. package/dist/src/public/channels/slack/slackChannel.js +40 -15
  50. package/dist/src/runtime/connections/authorization-tokens.d.ts +1 -1
  51. package/dist/src/runtime/connections/authorization-tokens.js +1 -1
  52. package/package.json +16 -16
  53. package/dist/src/compiled/_chunks/node/ms-B2k_qBoq.js +0 -1
  54. package/dist/src/compiled/_chunks/workflow/sleep-BzS_cSYx.js +0 -1
  55. /package/dist/src/compiled/_chunks/workflow/{dist-C9DdsXoK.js → dist-0iNBqPYp.js} +0 -0
  56. /package/dist/src/compiled/_chunks/workflow/{dist-BHbmiLmM.js → dist-D774SUM4.js} +0 -0
  57. /package/dist/src/compiled/_chunks/workflow/{src-CidBwKAD.js → src-ClRYdO4-.js} +0 -0
  58. /package/dist/src/compiled/_chunks/workflow/{symbols-BC0BVTM7.js → symbols-D-4tVV8x.js} +0 -0
@@ -1,6 +1,6 @@
1
- import{At as e,Et as t,Nn as n,Rn as r,Tn as i,Xn as a,Zn as o,wn as s,yt as c}from"../../_chunks/workflow/schemas-DFZoEyCn.js";import{AISDKError as l,TooManyEmbeddingValuesForCallError as u,UnsupportedFunctionalityError as d}from"../provider/index.js";import{B as f,C as p,F as m,J as h,K as g,L as _,M as v,O as y,R as b,T as x,U as S,X as C,Y as w,_ as T,a as E,b as D,c as O,d as k,f as A,h as j,j as ee,k as te,o as M,q as ne,r as N,u as re,w as ie,x as P,z as F}from"../../_chunks/workflow/dist-BuELZxm6.js";var I=`4.0.0-canary.53`,L=k({errorSchema:y(()=>h(i({error:i({code:s().nullable(),message:r(),status:r()})}))),errorToMessage:e=>e.error.message}),ae=a([i({text:r()}),i({inlineData:i({mimeType:r(),data:r()})})]),oe=y(()=>h(i({outputDimensionality:s().optional(),taskType:c([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:t(t(ae).min(1).nullable()).optional()}))),se=class e{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}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}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await m({provider:`google`,providerOptions:r,schema:oe});if(e.length>this.maxEmbeddingsPerCall)throw new u({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=N(this.config.headers?await b(this.config.headers):void 0,t),o=i?.content;if(o!=null&&o.length!==e.length)throw Error(`The number of multimodal content entries (${o.length}) must match the number of values (${e.length}).`);if(e.length===1){let t=o?.[0],r=e[0]?[{text:e[0]}]:[],s=t==null?[{text:e[0]}]:[...r,...t],{responseHeaders:c,value:l,rawValue:u}=await _({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:s},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:L,successfulResponseHandler:A(le),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:[l.embedding.values],usage:void 0,response:{headers:c,body:u}}}let{responseHeaders:s,value:c,rawValue:l}=await _({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map((e,t)=>{let n=o?.[t],r=e?[{text:e}]:[];return{model:`models/${this.modelId}`,content:{role:`user`,parts:n==null?[{text:e}]:[...r,...n]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}})},failedResponseHandler:L,successfulResponseHandler:A(ce),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},ce=y(()=>h(i({embeddings:t(i({values:t(s())}))}))),le=y(()=>h(i({embedding:i({values:t(s())})})));function R(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 z(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]=z(n,!1),e),{})),o&&(m.items=Array.isArray(o)?o.map(e=>z(e,!1)):z(o,!1)),s&&(m.allOf=s.map(e=>z(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=z(e[0],!1);typeof t==`object`&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(e=>z(e,!1)),m.nullable=!0}else m.anyOf=c.map(e=>z(e,!1));return l&&(m.oneOf=l.map(e=>z(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:F({part:e}),data:M(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`&&p(r.mediaType)===`image`?e.push({inlineData:{mimeType:F({part:r}),data:M(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 n=[],r=[],i=!0,a=t?.isGemmaModel??!1,o=t?.providerOptionsNames??[`google`],s=!o.includes(`google`),c=t?.supportsFunctionResponseParts??!0,l=e=>{for(let t of o){let n=e.providerOptions?.[t];if(n!=null)return n}return s?e.providerOptions?.google:e.providerOptions?.googleVertex??e.providerOptions?.vertex};for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new d({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:switch(t.data.type){case`url`:e.push({fileData:{mimeType:F({part:t}),fileUri:t.data.url.toString()}});break;case`reference`:if(s)throw new d({functionality:`file parts with provider references`});e.push({fileData:{mimeType:F({part:t}),fileUri:f({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:x(t.mediaType)?t.mediaType:`text/plain`,data:M(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:F({part:t}),data:M(t.data.data)}});break}break}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.map(e=>{let t=l(e),n=t?.thoughtSignature==null?void 0:String(t.thoughtSignature);switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:n};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:n};case`reasoning-file`:switch(e.data.type){case`url`:throw new d({functionality:`File data URLs in assistant messages are not supported`});case`data`:return{inlineData:{mimeType:e.mediaType,data:M(e.data.data)},thought:!0,thoughtSignature:n}}break;case`file`:switch(e.data.type){case`url`:throw new d({functionality:`File data URLs in assistant messages are not supported`});case`reference`:if(s)throw new d({functionality:`file parts with provider references`});return{fileData:{mimeType:e.mediaType,fileUri:f({reference:e.data.reference,provider:`google`})},...t?.thought===!0?{thought:!0}:{},thoughtSignature:n};case`text`:return{inlineData:{mimeType:x(e.mediaType)?e.mediaType:`text/plain`,data:M(new TextEncoder().encode(e.data.text))},...t?.thought===!0?{thought:!0}:{},thoughtSignature:n};case`data`:return{inlineData:{mimeType:e.mediaType,data:M(e.data.data)},...t?.thought===!0?{thought:!0}:{},thoughtSignature:n}}break;case`tool-call`:{let r=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return r&&i?{toolCall:{toolType:i,args:typeof e.input==`string`?JSON.parse(e.input):e.input,id:r},thoughtSignature:n}:{functionCall:{name:e.toolName,args:e.input},thoughtSignature:n}}case`tool-result`:{let r=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return r&&i?{toolResponse:{toolType:i,response:e.output.type===`json`?e.output.value:{},id:r},thoughtSignature:n}:void 0}}}).filter(e=>e!==void 0)});break;case`tool`:{i=!1;let e=[];for(let t of a){if(t.type===`tool-approval-response`)continue;let n=l(t),i=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),a=n?.serverToolType==null?void 0:String(n.serverToolType);if(i&&a){let e=n?.thoughtSignature==null?void 0:String(n.thoughtSignature);if(r.length>0){let n=r[r.length-1];if(n.role===`model`){n.parts.push({toolResponse:{toolType:a,response:t.output.type===`json`?t.output.value:{},id:i},thoughtSignature:e});continue}}}let o=t.output;o.type===`content`?c?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}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
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,wn as u,yt as d}from"../../_chunks/workflow/schemas-DFZoEyCn.js";import{B as f,C as p,F as m,J as h,K as g,L as _,M as v,O as y,R as b,T as x,U as S,X as C,Y as w,_ as T,a as E,b as D,c as O,d as k,f as A,h as j,j as ee,k as te,o as M,q as ne,r as N,u as re,w as ie,x as P,z as F}from"../../_chunks/workflow/dist-Ci2brnHh.js";var I=`4.0.0-canary.53`,L=k({errorSchema:y(()=>h(s({error:s({code:u().nullable(),message:o(),status:o()})}))),errorToMessage:e=>e.error.message}),ae=c([s({text:o()}),s({inlineData:s({mimeType:o(),data:o()})})]),oe=y(()=>h(s({outputDimensionality:u().optional(),taskType:d([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:i(i(ae).min(1).nullable()).optional()}))),se=class e{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}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}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await m({provider:`google`,providerOptions:i,schema:oe});if(e.length>this.maxEmbeddingsPerCall)throw new t({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=N(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 _({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:L,successfulResponseHandler:A(le),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 _({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:L,successfulResponseHandler:A(ce),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.embeddings.map(e=>e.values),usage:void 0,response:{headers:c,body:u}}}},ce=y(()=>h(s({embeddings:i(s({values:i(u())}))}))),le=y(()=>h(s({embedding:s({values:i(u())})})));function R(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 z(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]=z(n,!1),e),{})),o&&(m.items=Array.isArray(o)?o.map(e=>z(e,!1)):z(o,!1)),s&&(m.allOf=s.map(e=>z(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=z(e[0],!1);typeof t==`object`&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(e=>z(e,!1)),m.nullable=!0}else m.anyOf=c.map(e=>z(e,!1));return l&&(m.oneOf=l.map(e=>z(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:F({part:e}),data:M(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`&&p(r.mediaType)===`image`?e.push({inlineData:{mimeType:F({part:r}),data:M(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:F({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:F({part:t}),fileUri:f({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:x(t.mediaType)?t.mediaType:`text/plain`,data:M(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:F({part:t}),data:M(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:M(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:f({reference:e.data.reference,provider:`google`})},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`text`:return{inlineData:{mimeType:x(e.mediaType)?e.mediaType:`text/plain`,data:M(new TextEncoder().encode(e.data.text))},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`data`:return{inlineData:{mimeType:e.mediaType,data:M(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
- `);r[0].parts.unshift({text:e+`
4
+ `);i[0].parts.unshift({text:e+`
5
5
 
6
- `})}return{systemInstruction:n.length>0&&!a?{parts:n}:void 0,contents:r}}function B(e){return e.includes(`/`)?e:`models/${e}`}var V=y(()=>h(i({responseModalities:t(c([`TEXT`,`IMAGE`])).optional(),thinkingConfig:i({thinkingBudget:s().optional(),includeThoughts:e().optional(),thinkingLevel:c([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:r().optional(),structuredOutputs:e().optional(),safetySettings:t(i({category:c([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:c([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:c([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:e().optional(),labels:n(r(),r()).optional(),mediaResolution:c([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:i({aspectRatio:c([`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:c([`1K`,`2K`,`4K`,`512`]).optional()}).optional(),retrievalConfig:i({latLng:i({latitude:s(),longitude:s()}).optional()}).optional(),streamFunctionCallArguments:e().optional(),serviceTier:c([`standard`,`flex`,`priority`]).optional()}))),_e={standard:`SERVICE_TIER_STANDARD`,flex:`SERVICE_TIER_FLEX`,priority:`SERVICE_TIER_PRIORITY`};function ve({tools:e,toolChoice:t,modelId:n,isVertexProvider:r=!1}){e=e?.length?e:void 0;let i=[],a=[`gemini-flash-latest`,`gemini-flash-lite-latest`,`gemini-pro-latest`].some(e=>e===n),o=n.includes(`gemini-2`)||n.includes(`gemini-3`)||n.includes(`nano-banana`)||a,s=n.includes(`gemini-3`),c=n.includes(`gemini-2.5`)||n.includes(`gemini-3`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:i};let l=e.some(e=>e.type===`function`),u=e.some(e=>e.type===`provider`);if(l&&u&&!s&&i.push({type:`unsupported`,feature:`combination of function and provider-defined tools`}),u){let n=[];if(e.filter(e=>e.type===`provider`).forEach(e=>{switch(e.id){case`google.google_search`:o?n.push({googleSearch:{...e.args}}):i.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Google Search requires Gemini 2.0 or newer.`});break;case`google.enterprise_web_search`:o?n.push({enterpriseWebSearch:{}}):i.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Enterprise Web Search requires Gemini 2.0 or newer.`});break;case`google.url_context`:o?n.push({urlContext:{}}):i.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:o?n.push({codeExecution:{}}):i.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The code execution tool is not supported with other Gemini models than Gemini 2.`});break;case`google.file_search`:c?n.push({fileSearch:{...e.args}}):i.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The file search tool is only supported with Gemini 2.5 models and Gemini 3 models.`});break;case`google.vertex_rag_store`:o?n.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:e.args.ragCorpus},similarity_top_k:e.args.topK}}}):i.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The RAG store tool is not supported with other Gemini models than Gemini 2.`});break;case`google.google_maps`:o?n.push({googleMaps:{}}):i.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer.`});break;default:i.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`});break}}),l&&s&&n.length>0){let a=[];for(let t of e)t.type===`function`&&a.push({name:t.name,description:t.description??``,parameters:z(t.inputSchema)});let o={functionCallingConfig:{mode:`VALIDATED`},...!r&&{includeServerSideToolInvocations:!0}};if(t!=null)switch(t.type){case`auto`:break;case`none`:o.functionCallingConfig={mode:`NONE`};break;case`required`:o.functionCallingConfig={mode:`ANY`};break;case`tool`:o.functionCallingConfig={mode:`ANY`,allowedFunctionNames:[t.toolName]};break}return{tools:[...n,{functionDeclarations:a}],toolConfig:o,toolWarnings:i}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:i}}let 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:i.push({type:`unsupported`,feature:`function tool ${t.name}`});break}if(t==null)return{tools:[{functionDeclarations:f}],toolConfig:p?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:i};let m=t.type;switch(m){case`auto`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`AUTO`}},toolWarnings:i};case`none`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:i};case`required`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`}},toolWarnings:i};case`tool`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:i};default:throw new d({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=()=>i({webSearchQueries:t(r()).nullish(),imageSearchQueries:t(r()).nullish(),retrievalQueries:t(r()).nullish(),searchEntryPoint:i({renderedContent:r()}).nullish(),groundingChunks:t(i({web:i({uri:r(),title:r().nullish()}).nullish(),image:i({sourceUri:r(),imageUri:r(),title:r().nullish(),domain:r().nullish()}).nullish(),retrievedContext:i({uri:r().nullish(),title:r().nullish(),text:r().nullish(),fileSearchStore:r().nullish()}).nullish(),maps:i({uri:r().nullish(),title:r().nullish(),text:r().nullish(),placeId:r().nullish()}).nullish()})).nullish(),groundingSupports:t(i({segment:i({startIndex:s().nullish(),endIndex:s().nullish(),text:r().nullish()}).nullish(),segment_text:r().nullish(),groundingChunkIndices:t(s()).nullish(),supportChunkIndices:t(s()).nullish(),confidenceScores:t(s()).nullish(),confidenceScore:t(s()).nullish()})).nullish(),retrievalMetadata:a([i({webDynamicRetrievalScore:s()}),i({})]).nullish()}),ke=i({jsonPath:r(),stringValue:r().nullish(),numberValue:s().nullish(),boolValue:e().nullish(),nullValue:o().nullish(),willContinue:e().nullish()}),q=()=>i({parts:t(a([i({functionCall:i({name:r().nullish(),args:o().nullish(),partialArgs:t(ke).nullish(),willContinue:e().nullish()}),thoughtSignature:r().nullish()}),i({inlineData:i({mimeType:r(),data:r()}),thought:e().nullish(),thoughtSignature:r().nullish()}),i({toolCall:i({toolType:r(),args:o().nullish(),id:r()}),thoughtSignature:r().nullish()}),i({toolResponse:i({toolType:r(),response:o().nullish(),id:r()}),thoughtSignature:r().nullish()}),i({executableCode:i({language:r(),code:r()}).nullish(),codeExecutionResult:i({outcome:r(),output:r().nullish()}).nullish(),text:r().nullish(),thought:e().nullish(),thoughtSignature:r().nullish()})])).nullish()}),J=()=>i({category:r().nullish(),probability:r().nullish(),probabilityScore:s().nullish(),severity:r().nullish(),severityScore:s().nullish(),blocked:e().nullish()}),Y=t(i({modality:r(),tokenCount:s()})).nullish(),X=i({cachedContentTokenCount:s().nullish(),thoughtsTokenCount:s().nullish(),promptTokenCount:s().nullish(),candidatesTokenCount:s().nullish(),totalTokenCount:s().nullish(),trafficType:r().nullish(),promptTokensDetails:Y,candidatesTokensDetails:Y}),Z=()=>i({urlMetadata:t(i({retrievedUrl:r(),urlRetrievalStatus:r()})).nullish()}),Ae=y(()=>h(i({candidates:t(i({content:q().nullish().or(i({}).strict()),finishReason:r().nullish(),finishMessage:r().nullish(),safetyRatings:t(J()).nullish(),groundingMetadata:K().nullish(),urlContextMetadata:Z().nullish()})),usageMetadata:X.nullish(),promptFeedback:i({blockReason:r().nullish(),safetyRatings:t(J()).nullish()}).nullish(),serviceTier:r().nullish()}))),je=y(()=>h(i({candidates:t(i({content:q().nullish(),finishReason:r().nullish(),finishMessage:r().nullish(),safetyRatings:t(J()).nullish(),groundingMetadata:K().nullish(),urlContextMetadata:Z().nullish()})).nullish(),usageMetadata:X.nullish(),promptFeedback:i({blockReason:r().nullish(),safetyRatings:t(J()).nullish()}).nullish(),serviceTier:r().nullish()}))),Me=j({id:`google.code_execution`,inputSchema:i({language:r().describe(`The programming language of the code.`),code:r().describe(`The code to be executed.`)}),outputSchema:i({outcome:r().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:r().describe(`The output from the code execution.`)})}),Ne=j({id:`google.enterprise_web_search`,inputSchema:y(()=>h(i({}))),outputSchema:y(()=>h(i({})))});i({fileSearchStoreNames:t(r()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:s().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:r().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(i({}))),outputSchema:y(()=>h(i({})))}),Fe=j({id:`google.google_maps`,inputSchema:y(()=>h(i({}))),outputSchema:y(()=>h(i({})))});i({searchTypes:i({webSearch:i({}).optional(),imageSearch:i({}).optional()}).optional(),timeRangeFilter:i({startTime:r(),endTime:r()}).optional()}).passthrough();var Ie={googleSearch:j({id:`google.google_search`,inputSchema:y(()=>h(i({}))),outputSchema:y(()=>h(i({})))}),enterpriseWebSearch:Ne,googleMaps:Fe,urlContext:j({id:`google.url_context`,inputSchema:y(()=>h(i({}))),outputSchema:y(()=>h(i({})))}),fileSearch:Pe,codeExecution:Me,vertexRagStore:j({id:`google.vertex_rag_store`,inputSchema:y(()=>h(i({}))),outputSchema:y(()=>h(i({})))})},Le=y(()=>h(i({personGeneration:c([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:c([`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(i({predictions:t(i({bytesBase64Encoded:r()})).default([])}))),Be=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(e){let t=await m({provider:`google`,providerOptions:e.providerOptions,schema:He}),n=this.config.headers(),r=this.config.fetch??globalThis.fetch,i=[];e.filename!=null&&i.push({type:`unsupported`,feature:`filename`});let a=E(e.data),o=e.mediaType,s=t?.displayName,c=await r(`${this.config.baseURL.replace(/\/v1beta$/,``)}/upload/v1beta/files`,{method:`POST`,headers:{...n,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(a.length),"X-Goog-Upload-Header-Content-Type":o,"Content-Type":`application/json`},body:JSON.stringify({file:{...s==null?{}:{display_name:s}}})});if(!c.ok){let e=await c.text();throw new l({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to initiate resumable upload: ${c.status} ${e}`})}let u=c.headers.get(`x-goog-upload-url`);if(!u)throw new l({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`No upload URL returned from initiation request`});let d=await r(u,{method:`POST`,headers:{"Content-Length":String(a.length),"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:a});if(!d.ok){let e=await d.text();throw new l({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to upload file data: ${d.status} ${e}`})}let f=(await d.json()).file,p=t?.pollIntervalMs??2e3,h=t?.pollTimeoutMs??3e5,g=Date.now();for(;f.state===`PROCESSING`;){if(Date.now()-g>h)throw new l({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${h}ms`});await T(p);let{value:e}=await P({url:`${this.config.baseURL}/${f.name}`,headers:N(n),successfulResponseHandler:A(Ve),failedResponseHandler:L,fetch:this.config.fetch});f=e}if(f.state===`FAILED`)throw new l({name:`GOOGLE_FILES_UPLOAD_FAILED`,message:`File processing failed for ${f.name}`});return{warnings:i,providerReference:{google:f.uri},mediaType:f.mimeType??e.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(i({name:r(),displayName:r().nullish(),mimeType:r(),sizeBytes:r().nullish(),createTime:r().nullish(),updateTime:r().nullish(),expirationTime:r().nullish(),sha256Hash:r().nullish(),uri:r(),state:r()}))),He=y(()=>h(i({displayName:r().nullish(),pollIntervalMs:s().positive().nullish(),pollTimeoutMs:s().positive().nullish()}).passthrough())),Ue=y(()=>h(i({pollIntervalMs:s().positive().nullish(),pollTimeoutMs:s().positive().nullish(),personGeneration:c([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:r().nullish(),referenceImages:t(i({bytesBase64Encoded:r().nullish(),gcsUri:r().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(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,r=[],i=await m({provider:`google`,providerOptions:e.providerOptions,schema:Ue}),a=[{}],o=a[0];if(e.prompt!=null&&(o.prompt=e.prompt),e.image!=null)if(e.image.type===`url`)r.push({type:`unsupported`,feature:`URL-based image input`,details:`Google Generative AI video models require base64-encoded images. URL will be ignored.`});else{let t=typeof e.image.data==`string`?e.image.data:O(e.image.data);o.image={inlineData:{mimeType:e.image.mediaType||`image/png`,data:t}}}i?.referenceImages!=null&&(o.referenceImages=i.referenceImages.map(e=>e.bytesBase64Encoded?{inlineData:{mimeType:`image/png`,data:e.bytesBase64Encoded}}:e.gcsUri?{gcsUri:e.gcsUri}:e));let s={sampleCount:e.n};if(e.aspectRatio&&(s.aspectRatio=e.aspectRatio),e.resolution&&(s.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[e.resolution]||e.resolution),e.duration&&(s.durationSeconds=e.duration),e.seed&&(s.seed=e.seed),i!=null){let e=i;e.personGeneration!==void 0&&e.personGeneration!==null&&(s.personGeneration=e.personGeneration),e.negativePrompt!==void 0&&e.negativePrompt!==null&&(s.negativePrompt=e.negativePrompt);for(let[t,n]of Object.entries(e))[`pollIntervalMs`,`pollTimeoutMs`,`personGeneration`,`negativePrompt`,`referenceImages`].includes(t)||(s[t]=n)}let{value:c}=await _({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:N(await b(this.config.headers),e.headers),body:{instances:a,parameters:s},successfulResponseHandler:A(Ge),failedResponseHandler:L,abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c.name;if(!u)throw new l({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No operation name returned from API`});let d=i?.pollIntervalMs??1e4,f=i?.pollTimeoutMs??6e5,p=Date.now(),h=c,g;for(;!h.done;){if(Date.now()-p>f)throw new l({name:`GOOGLE_VIDEO_GENERATION_TIMEOUT`,message:`Video generation timed out after ${f}ms`});if(await T(d),e.abortSignal?.aborted)throw new l({name:`GOOGLE_VIDEO_GENERATION_ABORTED`,message:`Video generation request was aborted`});let{value:t,responseHeaders:n}=await P({url:`${this.config.baseURL}/${u}`,headers:N(await b(this.config.headers),e.headers),successfulResponseHandler:A(Ge),failedResponseHandler:L,abortSignal:e.abortSignal,fetch:this.config.fetch});h=t,g=n}if(h.error)throw new l({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 l({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 l({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No valid videos in response`});return{videos:y,warnings:r,response:{timestamp:n,modelId:this.modelId,headers:g},providerMetadata:{google:{videos:x}}}}},Ge=i({name:r().nullish(),done:e().nullish(),error:i({code:s().nullish(),message:r(),status:r().nullish()}).nullish(),response:i({generateVideoResponse:i({generatedSamples:t(i({video:i({uri:r().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 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};
@@ -1 +1 @@
1
- import{Bi as e}from"../../_chunks/workflow/core-DOVmxHH8.js";import{At as t,Dt as n,En as r,Et as i,Nn as a,Rn as o,Tn as s,Tt as c,Xn as l,Zn as u,dn as d,fn as f,wn as p}from"../../_chunks/workflow/schemas-DFZoEyCn.js";import{n as m}from"../../_chunks/workflow/compat-CIROS3w4.js";import{AISDKError as h}from"../provider/index.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-BuELZxm6.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=h,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(e){return h.hasMarker(e,fe)}},x=`2025-11-25`,ge=[x,`2025-06-18`,`2025-03-26`,`2024-11-05`],_e=r(a(o(),u())),ve=f({name:o(),version:o(),title:r(o())}),S=f({_meta:r(s({}).loose())}),C=S,w=s({method:o(),params:r(S)}),T=s({applyDefaults:r(t())}).loose(),ye=f({experimental:r(s({}).loose()),logging:r(s({}).loose()),prompts:r(f({listChanged:r(t())})),resources:r(f({subscribe:r(t()),listChanged:r(t())})),tools:r(f({listChanged:r(t())})),elicitation:r(T)});s({elicitation:r(T)}).loose();var be=C.extend({protocolVersion:o(),capabilities:ye,serverInfo:ve,instructions:r(o())}),E=C.extend({nextCursor:r(o())}),xe=s({name:o(),title:r(o()),description:r(o()),inputSchema:s({type:d(`object`),properties:r(s({}).loose())}).loose(),outputSchema:r(s({}).loose()),annotations:r(s({title:r(o())}).loose()),_meta:_e}).loose(),Se=E.extend({tools:i(xe)}),D=s({type:d(`text`),text:o()}).loose(),O=s({type:d(`image`),data:n(),mimeType:o()}).loose(),Ce=s({uri:o(),name:o(),title:r(o()),description:r(o()),mimeType:r(o()),size:r(p())}).loose(),we=E.extend({resources:i(Ce)}),k=s({uri:o(),name:r(o()),title:r(o()),mimeType:r(o())}).loose(),A=k.extend({text:o()}),j=k.extend({blob:n()}),M=s({type:d(`resource`),resource:l([A,j])}).loose(),N=s({type:d(`resource_link`),uri:o(),name:o(),description:r(o()),mimeType:r(o())}).loose(),Te=C.extend({content:i(l([D,O,M,N])),structuredContent:r(u()),isError:t().default(!1).optional()}).or(C.extend({toolResult:u()})),Ee=s({uriTemplate:o(),name:o(),title:r(o()),description:r(o()),mimeType:r(o())}).loose(),De=C.extend({resourceTemplates:i(Ee)}),Oe=C.extend({contents:i(l([A,j]))}),ke=s({name:o(),description:r(o()),required:r(t())}).loose(),Ae=s({name:o(),title:r(o()),description:r(o()),arguments:r(i(ke))}).loose(),je=E.extend({prompts:i(Ae)}),Me=s({role:l([d(`user`),d(`assistant`)]),content:l([D,O,M,N])}).loose(),Ne=C.extend({description:r(o()),messages:i(Me)}),Pe=S.extend({message:o(),requestedSchema:u()}),P=w.extend({method:d(`elicitation/create`),params:Pe}),F=C.extend({action:l([d(`accept`),d(`decline`),d(`cancel`)]),content:r(a(o(),u()))}),I=`2.0`,Fe=s({jsonrpc:d(I),id:l([o(),p().int()])}).merge(w).strict(),Ie=s({jsonrpc:d(I),id:l([o(),p().int()]),result:C}).strict(),Le=s({jsonrpc:d(I),id:l([o(),p().int()]),error:s({code:p().int(),message:o(),data:r(u())})}).strict(),L=l([Fe,s({jsonrpc:d(I)}).merge(s({method:o(),params:r(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=s({access_token:o(),id_token:o().optional(),token_type:o(),expires_in:p().optional(),scope:o().optional(),refresh_token:o().optional()}).strip(),B=o().url().superRefine((t,n)=>{if(!URL.canParse(t))return n.addIssue({code:m.custom,message:`URL must be parseable`,fatal:!0}),e}).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=s({resource:o().url(),authorization_servers:i(B).optional(),jwks_uri:o().url().optional(),scopes_supported:i(o()).optional(),bearer_methods_supported:i(o()).optional(),resource_signing_alg_values_supported:i(o()).optional(),resource_name:o().optional(),resource_documentation:o().optional(),resource_policy_uri:o().url().optional(),resource_tos_uri:o().url().optional(),tls_client_certificate_bound_access_tokens:t().optional(),authorization_details_types_supported:i(o()).optional(),dpop_signing_alg_values_supported:i(o()).optional(),dpop_bound_access_tokens_required:t().optional()}).passthrough(),Be=s({issuer:o(),authorization_endpoint:B,token_endpoint:B,registration_endpoint:B.optional(),scopes_supported:i(o()).optional(),response_types_supported:i(o()),grant_types_supported:i(o()).optional(),code_challenge_methods_supported:i(o()),token_endpoint_auth_methods_supported:i(o()).optional(),token_endpoint_auth_signing_alg_values_supported:i(o()).optional()}).passthrough(),Ve=s({issuer:o(),authorization_endpoint:B,token_endpoint:B,userinfo_endpoint:B.optional(),jwks_uri:B,registration_endpoint:B.optional(),scopes_supported:i(o()).optional(),response_types_supported:i(o()),grant_types_supported:i(o()).optional(),subject_types_supported:i(o()),id_token_signing_alg_values_supported:i(o()),claims_supported:i(o()).optional(),token_endpoint_auth_methods_supported:i(o()).optional()}).passthrough().merge(Be.pick({code_challenge_methods_supported:!0})),He=s({client_id:o(),client_secret:o().optional(),client_id_issued_at:p().optional(),client_secret_expires_at:p().optional()}).strip(),Ue=s({redirect_uris:i(B),token_endpoint_auth_method:o().optional(),grant_types:i(o()).optional(),response_types:i(o()).optional(),client_name:o().optional(),client_uri:B.optional(),logo_uri:B.optional(),scope:o().optional(),contacts:i(o()).optional(),tos_uri:B.optional(),policy_uri:o().optional(),jwks_uri:B.optional(),jwks:c().optional(),software_id:o().optional(),software_version:o().optional(),software_statement:o().optional()}).strip(),We=s({error:o(),error_description:o().optional(),error_uri:o().optional()}),Ge=Ue.merge(He),Ke=`vercel.ai.error.AI_MCPClientOAuthError`,qe=Symbol.for(Ke),Je,Ye,V=class extends (Ye=h,Je=qe,Ye){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[Je]=!0}static isInstance(e){return h.hasMarker(e,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}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};