shiplightai 0.1.19 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agentHelpers-IUFVFV55.js → agentHelpers-2TII7YCW.js} +1 -1
- package/dist/{agentLogin-YX4SQCJ7.js → agentLogin-GDOU6BCP.js} +1 -1
- package/dist/{chunk-XCDECDBJ.js → chunk-2F3YRAA7.js} +13 -13
- package/dist/{chunk-SJ4ND636.js → chunk-32JFHFFG.js} +17 -17
- package/dist/{chunk-M5SWSS6P.js → chunk-JHSENQ4F.js} +5 -5
- package/dist/chunk-JNRJXAJS.js +18 -0
- package/dist/chunk-LPSNOKYP.js +61 -0
- package/dist/{chunk-KVT4XXRU.js → chunk-RTTIJBGI.js} +5 -5
- package/dist/chunk-THVHM4KG.js +11 -0
- package/dist/cjs/debugger-pw.cjs +8 -4
- package/dist/cjs/fixture.cjs +97 -97
- package/dist/cjs/index.cjs +120 -120
- package/dist/cli.js +523 -515
- package/dist/debugger-pw.js +1 -1
- package/dist/{dist-REAH3DVS.js → dist-CXOVVE77.js} +1 -1
- package/dist/dist-SRXGJZ7P.js +3 -0
- package/dist/fixture.js +1 -1
- package/dist/{handler-UXMAYIOA.js → handler-BAP4TGW6.js} +1 -1
- package/dist/index.js +5 -13
- package/dist/{task-QLOM6Q36.js → task-VW6MUEKX.js} +1 -1
- package/dist/testFlow-ZLC5L5GT.js +3 -0
- package/package.json +1 -1
- package/dist/chunk-AZ7CG3SO.js +0 -18
- package/dist/chunk-BWEKM3LZ.js +0 -61
- package/dist/dist-T7XB7SCU.js +0 -3
- package/dist/testFlow-UHBHQTD7.js +0 -3
|
@@ -48,9 +48,9 @@ Error message: ${Tr(r)}`,cause:r}),this[dc]=!0,this.value=e}static isInstance(e)
|
|
|
48
48
|
|
|
49
49
|
`);i[0].parts.unshift({text:p+`
|
|
50
50
|
|
|
51
|
-
`})}return{systemInstruction:a.length>0&&!l?{parts:a}:void 0,contents:i}}function lh(t){return t.includes("/")?t:`models/${t}`}var wE=q(()=>H(Qn.object({error:Qn.object({code:Qn.number().nullable(),message:Qn.string(),status:Qn.string()})}))),ch=Qe({errorSchema:wE,errorToMessage:t=>t.error.message}),uh=q(()=>H(Le.object({responseModalities:Le.array(Le.enum(["TEXT","IMAGE"])).optional(),thinkingConfig:Le.object({thinkingBudget:Le.number().optional(),includeThoughts:Le.boolean().optional(),thinkingLevel:Le.enum(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:Le.string().optional(),structuredOutputs:Le.boolean().optional(),safetySettings:Le.array(Le.object({category:Le.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Le.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Le.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:Le.boolean().optional(),labels:Le.record(Le.string(),Le.string()).optional(),mediaResolution:Le.enum(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:Le.object({aspectRatio:Le.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"]).optional(),imageSize:Le.enum(["1K","2K","4K"]).optional()}).optional(),retrievalConfig:Le.object({latLng:Le.object({latitude:Le.number(),longitude:Le.number()}).optional()}).optional()})));function EE({tools:t,toolChoice:e,modelId:r}){var n;t=t?.length?t:void 0;let o=[],a=["gemini-flash-latest","gemini-flash-lite-latest","gemini-pro-latest"].some(y=>y===r),i=r.includes("gemini-2")||r.includes("gemini-3")||a,s=r.includes("gemini-1.5-flash")&&!r.includes("-8b"),l=r.includes("gemini-2.5")||r.includes("gemini-3");if(t==null)return{tools:void 0,toolConfig:void 0,toolWarnings:o};let c=t.some(y=>y.type==="function"),p=t.some(y=>y.type==="provider");if(c&&p&&o.push({type:"unsupported",feature:"combination of function and provider-defined tools"}),p){let y=[];return t.filter(f=>f.type==="provider").forEach(f=>{switch(f.id){case"google.google_search":i?y.push({googleSearch:{}}):s?y.push({googleSearchRetrieval:{dynamicRetrievalConfig:{mode:f.args.mode,dynamicThreshold:f.args.dynamicThreshold}}}):y.push({googleSearchRetrieval:{}});break;case"google.enterprise_web_search":i?y.push({enterpriseWebSearch:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":i?y.push({urlContext:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":i?y.push({codeExecution:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":l?y.push({fileSearch:{...f.args}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":i?y.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:f.args.ragCorpus},similarity_top_k:f.args.topK}}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":i?y.push({googleMaps:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`});break}}),{tools:y.length>0?y:void 0,toolConfig:void 0,toolWarnings:o}}let h=[];for(let y of t)switch(y.type){case"function":h.push({name:y.name,description:(n=y.description)!=null?n:"",parameters:or(y.inputSchema)});break;default:o.push({type:"unsupported",feature:`function tool ${y.name}`});break}if(e==null)return{tools:[{functionDeclarations:h}],toolConfig:void 0,toolWarnings:o};let g=e.type;switch(g){case"auto":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:o};case"none":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:o};case"required":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:o};case"tool":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[e.toolName]}},toolWarnings:o};default:{let y=g;throw new tt({functionality:`tool choice type: ${y}`})}}}function dh({finishReason:t,hasToolCalls:e}){switch(t){case"STOP":return e?"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";case"FINISH_REASON_UNSPECIFIED":case"OTHER":default:return"other"}}var hh=class{constructor(t,e){this.specificationVersion="v3";var r;this.modelId=t,this.config=e,this.generateId=(r=e.generateId)!=null?r:xt}get provider(){return this.config.provider}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:o,frequencyPenalty:a,presencePenalty:i,stopSequences:s,responseFormat:l,seed:c,tools:p,toolChoice:h,providerOptions:g}){var y;let S=[],f=this.config.provider.includes("vertex")?"vertex":"google",b=await Ve({provider:f,providerOptions:g,schema:uh});b==null&&f!=="google"&&(b=await Ve({provider:"google",providerOptions:g,schema:uh})),p?.some(O=>O.type==="provider"&&O.id==="google.vertex_rag_store")&&!this.config.provider.startsWith("google.vertex.")&&S.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}).`});let _=this.modelId.toLowerCase().startsWith("gemma-"),{contents:M,systemInstruction:B}=_E(t,{isGemmaModel:_,providerOptionsName:f}),{tools:Z,toolConfig:N,toolWarnings:R}=EE({tools:p,toolChoice:h,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:e,temperature:r,topK:o,topP:n,frequencyPenalty:a,presencePenalty:i,stopSequences:s,seed:c,responseMimeType:l?.type==="json"?"application/json":void 0,responseSchema:l?.type==="json"&&l.schema!=null&&((y=b?.structuredOutputs)==null||y)?or(l.schema):void 0,...b?.audioTimestamp&&{audioTimestamp:b.audioTimestamp},responseModalities:b?.responseModalities,thinkingConfig:b?.thinkingConfig,...b?.mediaResolution&&{mediaResolution:b.mediaResolution},...b?.imageConfig&&{imageConfig:b.imageConfig}},contents:M,systemInstruction:_?void 0:B,safetySettings:b?.safetySettings,tools:Z,toolConfig:b?.retrievalConfig?{...N,retrievalConfig:b.retrievalConfig}:N,cachedContent:b?.cachedContent,labels:b?.labels},warnings:[...S,...R],providerOptionsName:f}}async doGenerate(t){var e,r,n,o,a,i,s,l,c;let{args:p,warnings:h,providerOptionsName:g}=await this.getArgs(t),y=Ge(await Te(this.config.headers),t.headers),{responseHeaders:S,value:f,rawValue:b}=await Ue({url:`${this.config.baseURL}/${lh(this.modelId)}:generateContent`,headers:y,body:p,failedResponseHandler:ch,successfulResponseHandler:qe(xE),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=f.candidates[0],M=[],B=(r=(e=_.content)==null?void 0:e.parts)!=null?r:[],Z=f.usageMetadata,N;for(let O of B)if("executableCode"in O&&((n=O.executableCode)!=null&&n.code)){let ee=this.config.generateId();N=ee,M.push({type:"tool-call",toolCallId:ee,toolName:"code_execution",input:JSON.stringify(O.executableCode),providerExecuted:!0})}else"codeExecutionResult"in O&&O.codeExecutionResult?(M.push({type:"tool-result",toolCallId:N,toolName:"code_execution",result:{outcome:O.codeExecutionResult.outcome,output:O.codeExecutionResult.output}}),N=void 0):"text"in O&&O.text!=null&&O.text.length>0?M.push({type:O.thought===!0?"reasoning":"text",text:O.text,providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0}):"functionCall"in O?M.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:O.functionCall.name,input:JSON.stringify(O.functionCall.args),providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0}):"inlineData"in O&&M.push({type:"file",data:O.inlineData.data,mediaType:O.inlineData.mimeType,providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0});let R=(o=ph({groundingMetadata:_.groundingMetadata,generateId:this.config.generateId}))!=null?o:[];for(let O of R)M.push(O);return{content:M,finishReason:{unified:dh({finishReason:_.finishReason,hasToolCalls:M.some(O=>O.type==="tool-call"&&!O.providerExecuted)}),raw:(a=_.finishReason)!=null?a:void 0},usage:sh(Z),warnings:h,providerMetadata:{[g]:{promptFeedback:(i=f.promptFeedback)!=null?i:null,groundingMetadata:(s=_.groundingMetadata)!=null?s:null,urlContextMetadata:(l=_.urlContextMetadata)!=null?l:null,safetyRatings:(c=_.safetyRatings)!=null?c:null,usageMetadata:Z??null}},request:{body:p},response:{headers:S,body:b}}}async doStream(t){let{args:e,warnings:r,providerOptionsName:n}=await this.getArgs(t),o=Ge(await Te(this.config.headers),t.headers),{responseHeaders:a,value:i}=await Ue({url:`${this.config.baseURL}/${lh(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:e,failedResponseHandler:ch,successfulResponseHandler:Sr(SE),abortSignal:t.abortSignal,fetch:this.config.fetch}),s={unified:"other",raw:void 0},l,c,p=this.config.generateId,h=!1,g=null,y=null,S=0,f=new Set,b;return{stream:i.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:r})},transform(_,M){var B,Z,N,R,O,ee,E;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){M.enqueue({type:"error",error:_.error});return}let Q=_.value,X=Q.usageMetadata;X!=null&&(l=X);let W=(B=Q.candidates)==null?void 0:B[0];if(W==null)return;let ue=W.content,V=ph({groundingMetadata:W.groundingMetadata,generateId:p});if(V!=null)for(let K of V)K.sourceType==="url"&&!f.has(K.url)&&(f.add(K.url),M.enqueue(K));if(ue!=null){let K=(Z=ue.parts)!=null?Z:[];for(let j of K)if("executableCode"in j&&((N=j.executableCode)!=null&&N.code)){let ve=p();b=ve,M.enqueue({type:"tool-call",toolCallId:ve,toolName:"code_execution",input:JSON.stringify(j.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in j&&j.codeExecutionResult){let ve=b;ve&&(M.enqueue({type:"tool-result",toolCallId:ve,toolName:"code_execution",result:{outcome:j.codeExecutionResult.outcome,output:j.codeExecutionResult.output}}),b=void 0)}else"text"in j&&j.text!=null&&j.text.length>0?j.thought===!0?(g!==null&&(M.enqueue({type:"text-end",id:g}),g=null),y===null&&(y=String(S++),M.enqueue({type:"reasoning-start",id:y,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),M.enqueue({type:"reasoning-delta",id:y,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):(y!==null&&(M.enqueue({type:"reasoning-end",id:y}),y=null),g===null&&(g=String(S++),M.enqueue({type:"text-start",id:g,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),M.enqueue({type:"text-delta",id:g,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):"inlineData"in j&&M.enqueue({type:"file",mediaType:j.inlineData.mimeType,data:j.inlineData.data});let me=TE({parts:ue.parts,generateId:p,providerOptionsName:n});if(me!=null)for(let j of me)M.enqueue({type:"tool-input-start",id:j.toolCallId,toolName:j.toolName,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-input-delta",id:j.toolCallId,delta:j.args,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-input-end",id:j.toolCallId,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-call",toolCallId:j.toolCallId,toolName:j.toolName,input:j.args,providerMetadata:j.providerMetadata}),h=!0}W.finishReason!=null&&(s={unified:dh({finishReason:W.finishReason,hasToolCalls:h}),raw:W.finishReason},c={[n]:{promptFeedback:(R=Q.promptFeedback)!=null?R:null,groundingMetadata:(O=W.groundingMetadata)!=null?O:null,urlContextMetadata:(ee=W.urlContextMetadata)!=null?ee:null,safetyRatings:(E=W.safetyRatings)!=null?E:null}},X!=null&&(c[n].usageMetadata=X))},flush(_){g!==null&&_.enqueue({type:"text-end",id:g}),y!==null&&_.enqueue({type:"reasoning-end",id:y}),_.enqueue({type:"finish",finishReason:s,usage:sh(l),providerMetadata:c})}})),response:{headers:a},request:{body:e}}}};function TE({parts:t,generateId:e,providerOptionsName:r}){let n=t?.filter(o=>"functionCall"in o);return n==null||n.length===0?void 0:n.map(o=>({type:"tool-call",toolCallId:e(),toolName:o.functionCall.name,args:JSON.stringify(o.functionCall.args),providerMetadata:o.thoughtSignature?{[r]:{thoughtSignature:o.thoughtSignature}}:void 0}))}function ph({groundingMetadata:t,generateId:e}){var r,n,o,a,i;if(!t?.groundingChunks)return;let s=[];for(let l of t.groundingChunks)if(l.web!=null)s.push({type:"source",sourceType:"url",id:e(),url:l.web.uri,title:(r=l.web.title)!=null?r:void 0});else if(l.retrievedContext!=null){let c=l.retrievedContext.uri,p=l.retrievedContext.fileSearchStore;if(c&&(c.startsWith("http://")||c.startsWith("https://")))s.push({type:"source",sourceType:"url",id:e(),url:c,title:(n=l.retrievedContext.title)!=null?n:void 0});else if(c){let h=(o=l.retrievedContext.title)!=null?o:"Unknown Document",g="application/octet-stream",y;c.endsWith(".pdf")?(g="application/pdf",y=c.split("/").pop()):c.endsWith(".txt")?(g="text/plain",y=c.split("/").pop()):c.endsWith(".docx")?(g="application/vnd.openxmlformats-officedocument.wordprocessingml.document",y=c.split("/").pop()):c.endsWith(".doc")?(g="application/msword",y=c.split("/").pop()):(c.match(/\.(md|markdown)$/)&&(g="text/markdown"),y=c.split("/").pop()),s.push({type:"source",sourceType:"document",id:e(),mediaType:g,title:h,filename:y})}else if(p){let h=(a=l.retrievedContext.title)!=null?a:"Unknown Document";s.push({type:"source",sourceType:"document",id:e(),mediaType:"application/octet-stream",title:h,filename:p.split("/").pop()})}}else l.maps!=null&&l.maps.uri&&s.push({type:"source",sourceType:"url",id:e(),url:l.maps.uri,title:(i=l.maps.title)!=null?i:void 0});return s.length>0?s:void 0}var fh=()=>G.object({webSearchQueries:G.array(G.string()).nullish(),retrievalQueries:G.array(G.string()).nullish(),searchEntryPoint:G.object({renderedContent:G.string()}).nullish(),groundingChunks:G.array(G.object({web:G.object({uri:G.string(),title:G.string().nullish()}).nullish(),retrievedContext:G.object({uri:G.string().nullish(),title:G.string().nullish(),text:G.string().nullish(),fileSearchStore:G.string().nullish()}).nullish(),maps:G.object({uri:G.string().nullish(),title:G.string().nullish(),text:G.string().nullish(),placeId:G.string().nullish()}).nullish()})).nullish(),groundingSupports:G.array(G.object({segment:G.object({startIndex:G.number().nullish(),endIndex:G.number().nullish(),text:G.string().nullish()}),segment_text:G.string().nullish(),groundingChunkIndices:G.array(G.number()).nullish(),supportChunkIndices:G.array(G.number()).nullish(),confidenceScores:G.array(G.number()).nullish(),confidenceScore:G.array(G.number()).nullish()})).nullish(),retrievalMetadata:G.union([G.object({webDynamicRetrievalScore:G.number()}),G.object({})]).nullish()}),mh=()=>G.object({parts:G.array(G.union([G.object({functionCall:G.object({name:G.string(),args:G.unknown()}),thoughtSignature:G.string().nullish()}),G.object({inlineData:G.object({mimeType:G.string(),data:G.string()}),thoughtSignature:G.string().nullish()}),G.object({executableCode:G.object({language:G.string(),code:G.string()}).nullish(),codeExecutionResult:G.object({outcome:G.string(),output:G.string()}).nullish(),text:G.string().nullish(),thought:G.boolean().nullish(),thoughtSignature:G.string().nullish()})])).nullish()}),Ea=()=>G.object({category:G.string().nullish(),probability:G.string().nullish(),probabilityScore:G.number().nullish(),severity:G.string().nullish(),severityScore:G.number().nullish(),blocked:G.boolean().nullish()}),gh=G.object({cachedContentTokenCount:G.number().nullish(),thoughtsTokenCount:G.number().nullish(),promptTokenCount:G.number().nullish(),candidatesTokenCount:G.number().nullish(),totalTokenCount:G.number().nullish(),trafficType:G.string().nullish()}),yh=()=>G.object({urlMetadata:G.array(G.object({retrievedUrl:G.string(),urlRetrievalStatus:G.string()}))}),xE=q(()=>H(G.object({candidates:G.array(G.object({content:mh().nullish().or(G.object({}).strict()),finishReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish(),groundingMetadata:fh().nullish(),urlContextMetadata:yh().nullish()})),usageMetadata:gh.nullish(),promptFeedback:G.object({blockReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish()}).nullish()}))),SE=q(()=>H(G.object({candidates:G.array(G.object({content:mh().nullish(),finishReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish(),groundingMetadata:fh().nullish(),urlContextMetadata:yh().nullish()})).nullish(),usageMetadata:gh.nullish(),promptFeedback:G.object({blockReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish()}).nullish()}))),CE=Ze({id:"google.code_execution",inputSchema:yn.object({language:yn.string().describe("The programming language of the code."),code:yn.string().describe("The code to be executed.")}),outputSchema:yn.object({outcome:yn.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:yn.string().describe("The output from the code execution.")})}),AE=Ee({id:"google.enterprise_web_search",inputSchema:q(()=>H(IE.object({})))}),kE=eo.object({fileSearchStoreNames:eo.array(eo.string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:eo.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:eo.string().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(),RE=q(()=>H(kE)),OE=Ee({id:"google.file_search",inputSchema:RE}),ME=Ee({id:"google.google_maps",inputSchema:q(()=>H(NE.object({})))}),PE=Ee({id:"google.google_search",inputSchema:q(()=>H(Xs.object({mode:Xs.enum(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:Xs.number().default(1)})))}),jE=Ee({id:"google.url_context",inputSchema:q(()=>H(DE.object({})))}),LE=Ee({id:"google.vertex_rag_store",inputSchema:Zs.object({ragCorpus:Zs.string(),topK:Zs.number().optional()})}),kr={googleSearch:PE,enterpriseWebSearch:AE,googleMaps:ME,urlContext:jE,fileSearch:OE,codeExecution:CE,vertexRagStore:LE};import{z as Rr}from"zod/v4";import{z as to}from"zod/v4";import{z as ro}from"zod/v4";import{z as et}from"zod/v4";var Qs=null,vh=null;function FE(t){return(!Qs||t!==vh)&&(Qs=new Eh.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],...t}),vh=t),Qs}async function UE(t){let n=await(await FE(t||{}).getClient()).getAccessToken();return n?.token||null}var HE="4.0.15",qE=to.object({error:to.object({code:to.number().nullable(),message:to.string(),status:to.string()})}),Th=Qe({errorSchema:qE,errorToMessage:t=>t.error.message}),bh=ro.object({outputDimensionality:ro.number().optional(),taskType:ro.enum(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),title:ro.string().optional(),autoTruncate:ro.boolean().optional()}),$E=class{constructor(t,e){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){let o=await Ve({provider:"vertex",providerOptions:n,schema:bh});if(o==null&&(o=await Ve({provider:"google",providerOptions:n,schema:bh})),o=o??{},t.length>this.maxEmbeddingsPerCall)throw new fo({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let a=Ge(await Te(this.config.headers),e),i=`${this.config.baseURL}/models/${this.modelId}:predict`,{responseHeaders:s,value:l,rawValue:c}=await Ue({url:i,headers:a,body:{instances:t.map(p=>({content:p,task_type:o.taskType,title:o.title})),parameters:{outputDimensionality:o.outputDimensionality,autoTruncate:o.autoTruncate}},failedResponseHandler:Th,successfulResponseHandler:qe(GE),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.predictions.map(p=>p.embeddings.values),usage:{tokens:l.predictions.reduce((p,h)=>p+h.embeddings.statistics.token_count,0)},response:{headers:s,body:c}}}},GE=Rr.object({predictions:Rr.array(Rr.object({embeddings:Rr.object({values:Rr.array(Rr.number()),statistics:Rr.object({token_count:Rr.number()})})}))}),BE=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxImagesPerCall=4}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:o,providerOptions:a,headers:i,abortSignal:s,files:l,mask:c}){var p,h,g,y,S,f,b;let _=[];r!=null&&_.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let M=await Ve({provider:"vertex",providerOptions:a,schema:zE}),{edit:B,...Z}=M??{},{mode:N,baseSteps:R,maskMode:O,maskDilation:ee}=B??{},E=l!=null&&l.length>0,Q;if(E){let V=[];for(let K=0;K<l.length;K++){let me=l[K];V.push({referenceType:"REFERENCE_TYPE_RAW",referenceId:K+1,referenceImage:{bytesBase64Encoded:_h(me)}})}c!=null&&V.push({referenceType:"REFERENCE_TYPE_MASK",referenceId:l.length+1,referenceImage:{bytesBase64Encoded:_h(c)},maskImageConfig:{maskMode:O??"MASK_MODE_USER_PROVIDED",...ee!=null?{dilation:ee}:{}}}),Q={instances:[{prompt:t,referenceImages:V}],parameters:{sampleCount:e,...n!=null?{aspectRatio:n}:{},...o!=null?{seed:o}:{},editMode:N??"EDIT_MODE_INPAINT_INSERTION",...R!=null?{editConfig:{baseSteps:R}}:{},...Z}}}else Q={instances:[{prompt:t}],parameters:{sampleCount:e,...n!=null?{aspectRatio:n}:{},...o!=null?{seed:o}:{},...Z}};let X=(g=(h=(p=this.config._internal)==null?void 0:p.currentDate)==null?void 0:h.call(p))!=null?g:new Date,{value:W,responseHeaders:ue}=await Ue({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:Ge(await Te(this.config.headers),i),body:Q,failedResponseHandler:Th,successfulResponseHandler:qe(VE),abortSignal:s,fetch:this.config.fetch});return{images:(S=(y=W.predictions)==null?void 0:y.map(({bytesBase64Encoded:V})=>V))!=null?S:[],warnings:_,response:{timestamp:X,modelId:this.modelId,headers:ue},providerMetadata:{vertex:{images:(b=(f=W.predictions)==null?void 0:f.map(V=>{let{prompt:K}=V;return{...K!=null&&{revisedPrompt:K}}}))!=null?b:[]}}}}},VE=et.object({predictions:et.array(et.object({bytesBase64Encoded:et.string(),mimeType:et.string(),prompt:et.string().nullish()})).nullish()}),zE=et.object({negativePrompt:et.string().nullish(),personGeneration:et.enum(["dont_allow","allow_adult","allow_all"]).nullish(),safetySetting:et.enum(["block_low_and_above","block_medium_and_above","block_only_high","block_none"]).nullish(),addWatermark:et.boolean().nullish(),storageUri:et.string().nullish(),sampleImageSize:et.enum(["1K","2K"]).nullish(),edit:et.object({baseSteps:et.number().nullish(),mode:et.enum(["EDIT_MODE_INPAINT_INSERTION","EDIT_MODE_INPAINT_REMOVAL","EDIT_MODE_OUTPAINT","EDIT_MODE_CONTROLLED_EDITING","EDIT_MODE_PRODUCT_IMAGE","EDIT_MODE_BGSWAP"]).nullish(),maskMode:et.enum(["MASK_MODE_DEFAULT","MASK_MODE_USER_PROVIDED","MASK_MODE_DETECTION_BOX","MASK_MODE_CLOTHING_AREA","MASK_MODE_PARSED_PERSON"]).nullish(),maskDilation:et.number().nullish()}).nullish()});function _h(t){if(t.type==="url")throw new Error("URL-based images are not supported for Google Vertex image editing. Please provide the image data directly.");return typeof t.data=="string"?t.data:Jt(t.data)}var WE={googleSearch:kr.googleSearch,enterpriseWebSearch:kr.enterpriseWebSearch,googleMaps:kr.googleMaps,urlContext:kr.urlContext,fileSearch:kr.fileSearch,codeExecution:kr.codeExecution,vertexRagStore:kr.vertexRagStore},JE="https://aiplatform.googleapis.com/v1/publishers/google";function KE(t,e){return async(r,n)=>{let o=new URL(r.toString());return o.searchParams.set("key",t),(e??fetch)(o.toString(),n)}}function wh(t={}){let e=Lt({settingValue:t.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"}),r=()=>Wa({settingValue:t.project,settingName:"project",environmentVariableName:"GOOGLE_VERTEX_PROJECT",description:"Google Vertex project"}),n=()=>Wa({settingValue:t.location,settingName:"location",environmentVariableName:"GOOGLE_VERTEX_LOCATION",description:"Google Vertex location"}),o=()=>{var p,h;if(e)return(p=dr(t.baseURL))!=null?p:JE;let g=n(),y=r(),S=`${g==="global"?"":g+"-"}aiplatform.googleapis.com`;return(h=dr(t.baseURL))!=null?h:`https://${S}/v1beta1/projects/${y}/locations/${g}/publishers/google`},a=p=>{let h=async()=>{var g;let y=await Te((g=t.headers)!=null?g:{});return lt(y,`ai-sdk/google-vertex/${HE}`)};return{provider:`google.vertex.${p}`,headers:h,fetch:e?KE(e,t.fetch):t.fetch,baseURL:o()}},i=p=>{var h;return new hh(p,{...a("chat"),generateId:(h=t.generateId)!=null?h:xt,supportedUrls:()=>({"*":[/^https?:\/\/.*$/,/^gs:\/\/.*$/]})})},s=p=>new $E(p,a("embedding")),l=p=>new BE(p,a("image")),c=function(p){if(new.target)throw new Error("The Google Vertex AI model function cannot be called with the new keyword.");return i(p)};return c.specificationVersion="v3",c.languageModel=i,c.embeddingModel=s,c.textEmbeddingModel=s,c.image=l,c.imageModel=l,c.tools=WE,c}function el(t={}){return Lt({settingValue:t.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"})?wh(t):wh({...t,headers:async()=>({Authorization:`Bearer ${await UE(t.googleAuthOptions)}`,...await Te(t.headers)})})}var Fk=el();var xh={MEDIA_RESOLUTION_HIGH:"MEDIA_RESOLUTION_HIGH",MEDIA_RESOLUTION_MEDIUM:"MEDIA_RESOLUTION_MEDIUM",MEDIA_RESOLUTION_LOW:"MEDIA_RESOLUTION_LOW"};function Sh(){let t=(Sn().env||{}).GOOGLE_GENAI_USE_VERTEXAI;return t==="True"||t==="true"}function Ch(t){let e=Sn().env||{};if(Sh()){let n=e.GOOGLE_CLOUD_PROJECT;if(!n)throw new Error("GOOGLE_CLOUD_PROJECT is required when using Vertex AI");let o=t==="gemini-3-flash-preview"?"global":e.GOOGLE_CLOUD_LOCATION;if(!o)throw new Error("GOOGLE_CLOUD_LOCATION is required when using Vertex AI");return ce.debug(`Using Vertex AI provider: model=${t}, location=${o}`),el({project:n,location:o})(t)}let r=e.GOOGLE_API_KEY;if(!r)throw new Error("Google API key is missing. Set GOOGLE_API_KEY in SDK config or environment.");return ce.debug(`Using Google AI provider (API key): model=${t}`),Za({apiKey:r})(t)}function Ih(t,e){let r={thinkingConfig:{thinkingBudget:512,includeThoughts:!0}},n={thinkingConfig:{thinkingLevel:"minimal",includeThoughts:!0},mediaResolution:xh.MEDIA_RESOLUTION_HIGH},o;switch(e){case"gemini-3-flash-preview":o={...n};break;default:o={...r},t===1&&(o.mediaResolution=xh.MEDIA_RESOLUTION_HIGH)}return Sh()?{vertex:o}:{google:o}}import{z as no}from"zod/v4";import{z as u}from"zod/v4";import{z as re}from"zod/v4";import{z as Vt}from"zod/v4";import{z as ze}from"zod/v4";import{z as Me}from"zod/v4";import{z as zt}from"zod/v4";import{z as ne}from"zod/v4";import{z as Br}from"zod/v4";import{z as ol}from"zod/v4";import{z as al}from"zod/v4";import{z as oo}from"zod/v4";import{z as Ot}from"zod/v4";import{z as De}from"zod/v4";import{z as yr}from"zod/v4";import{z as vr}from"zod/v4";import{z as br}from"zod/v4";import{z as Vr}from"zod/v4";var YE="3.0.13",XE=q(()=>H(no.object({type:no.literal("error"),error:no.object({type:no.string(),message:no.string()})}))),Ah=Qe({errorSchema:XE,errorToMessage:t=>t.error.message}),ZE=q(()=>H(u.object({type:u.literal("message"),id:u.string().nullish(),model:u.string().nullish(),content:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string(),citations:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("web_search_result_location"),cited_text:u.string(),url:u.string(),title:u.string(),encrypted_index:u.string()}),u.object({type:u.literal("page_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_page_number:u.number(),end_page_number:u.number()}),u.object({type:u.literal("char_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_char_index:u.number(),end_char_index:u.number()})])).optional()}),u.object({type:u.literal("thinking"),thinking:u.string(),signature:u.string()}),u.object({type:u.literal("redacted_thinking"),data:u.string()}),u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.unknown(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()}),u.object({type:u.literal("server_tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).nullish()}),u.object({type:u.literal("mcp_tool_use"),id:u.string(),name:u.string(),input:u.unknown(),server_name:u.string()}),u.object({type:u.literal("mcp_tool_result"),tool_use_id:u.string(),is_error:u.boolean(),content:u.array(u.union([u.string(),u.object({type:u.literal("text"),text:u.string()})]))}),u.object({type:u.literal("web_fetch_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("web_fetch_result"),url:u.string(),retrieved_at:u.string(),content:u.object({type:u.literal("document"),title:u.string().nullable(),citations:u.object({enabled:u.boolean()}).optional(),source:u.union([u.object({type:u.literal("base64"),media_type:u.literal("application/pdf"),data:u.string()}),u.object({type:u.literal("text"),media_type:u.literal("text/plain"),data:u.string()})])})}),u.object({type:u.literal("web_fetch_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("web_search_tool_result"),tool_use_id:u.string(),content:u.union([u.array(u.object({type:u.literal("web_search_result"),url:u.string(),title:u.string(),encrypted_content:u.string(),page_age:u.string().nullish()})),u.object({type:u.literal("web_search_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("code_execution_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("code_execution_result"),stdout:u.string(),stderr:u.string(),return_code:u.number(),content:u.array(u.object({type:u.literal("code_execution_output"),file_id:u.string()})).optional().default([])}),u.object({type:u.literal("code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("bash_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("bash_code_execution_result"),content:u.array(u.object({type:u.literal("bash_code_execution_output"),file_id:u.string()})),stdout:u.string(),stderr:u.string(),return_code:u.number()}),u.object({type:u.literal("bash_code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("text_editor_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("text_editor_code_execution_tool_result_error"),error_code:u.string()}),u.object({type:u.literal("text_editor_code_execution_view_result"),content:u.string(),file_type:u.string(),num_lines:u.number().nullable(),start_line:u.number().nullable(),total_lines:u.number().nullable()}),u.object({type:u.literal("text_editor_code_execution_create_result"),is_file_update:u.boolean()}),u.object({type:u.literal("text_editor_code_execution_str_replace_result"),lines:u.array(u.string()).nullable(),new_lines:u.number().nullable(),new_start:u.number().nullable(),old_lines:u.number().nullable(),old_start:u.number().nullable()})])}),u.object({type:u.literal("tool_search_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("tool_search_tool_search_result"),tool_references:u.array(u.object({type:u.literal("tool_reference"),tool_name:u.string()}))}),u.object({type:u.literal("tool_search_tool_result_error"),error_code:u.string()})])})])),stop_reason:u.string().nullish(),stop_sequence:u.string().nullish(),usage:u.looseObject({input_tokens:u.number(),output_tokens:u.number(),cache_creation_input_tokens:u.number().nullish(),cache_read_input_tokens:u.number().nullish()}),container:u.object({expires_at:u.string(),id:u.string(),skills:u.array(u.object({type:u.union([u.literal("anthropic"),u.literal("custom")]),skill_id:u.string(),version:u.string()})).nullish()}).nullish(),context_management:u.object({applied_edits:u.array(u.union([u.object({type:u.literal("clear_tool_uses_20250919"),cleared_tool_uses:u.number(),cleared_input_tokens:u.number()}),u.object({type:u.literal("clear_thinking_20251015"),cleared_thinking_turns:u.number(),cleared_input_tokens:u.number()})]))}).nullish()}))),QE=q(()=>H(u.discriminatedUnion("type",[u.object({type:u.literal("message_start"),message:u.object({id:u.string().nullish(),model:u.string().nullish(),role:u.string().nullish(),usage:u.looseObject({input_tokens:u.number(),cache_creation_input_tokens:u.number().nullish(),cache_read_input_tokens:u.number().nullish()}),content:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.unknown(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()})])).nullish(),stop_reason:u.string().nullish(),container:u.object({expires_at:u.string(),id:u.string()}).nullish()})}),u.object({type:u.literal("content_block_start"),index:u.number(),content_block:u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string()}),u.object({type:u.literal("thinking"),thinking:u.string()}),u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).optional(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()}),u.object({type:u.literal("redacted_thinking"),data:u.string()}),u.object({type:u.literal("server_tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).nullish()}),u.object({type:u.literal("mcp_tool_use"),id:u.string(),name:u.string(),input:u.unknown(),server_name:u.string()}),u.object({type:u.literal("mcp_tool_result"),tool_use_id:u.string(),is_error:u.boolean(),content:u.array(u.union([u.string(),u.object({type:u.literal("text"),text:u.string()})]))}),u.object({type:u.literal("web_fetch_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("web_fetch_result"),url:u.string(),retrieved_at:u.string(),content:u.object({type:u.literal("document"),title:u.string().nullable(),citations:u.object({enabled:u.boolean()}).optional(),source:u.union([u.object({type:u.literal("base64"),media_type:u.literal("application/pdf"),data:u.string()}),u.object({type:u.literal("text"),media_type:u.literal("text/plain"),data:u.string()})])})}),u.object({type:u.literal("web_fetch_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("web_search_tool_result"),tool_use_id:u.string(),content:u.union([u.array(u.object({type:u.literal("web_search_result"),url:u.string(),title:u.string(),encrypted_content:u.string(),page_age:u.string().nullish()})),u.object({type:u.literal("web_search_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("code_execution_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("code_execution_result"),stdout:u.string(),stderr:u.string(),return_code:u.number(),content:u.array(u.object({type:u.literal("code_execution_output"),file_id:u.string()})).optional().default([])}),u.object({type:u.literal("code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("bash_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("bash_code_execution_result"),content:u.array(u.object({type:u.literal("bash_code_execution_output"),file_id:u.string()})),stdout:u.string(),stderr:u.string(),return_code:u.number()}),u.object({type:u.literal("bash_code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("text_editor_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("text_editor_code_execution_tool_result_error"),error_code:u.string()}),u.object({type:u.literal("text_editor_code_execution_view_result"),content:u.string(),file_type:u.string(),num_lines:u.number().nullable(),start_line:u.number().nullable(),total_lines:u.number().nullable()}),u.object({type:u.literal("text_editor_code_execution_create_result"),is_file_update:u.boolean()}),u.object({type:u.literal("text_editor_code_execution_str_replace_result"),lines:u.array(u.string()).nullable(),new_lines:u.number().nullable(),new_start:u.number().nullable(),old_lines:u.number().nullable(),old_start:u.number().nullable()})])}),u.object({type:u.literal("tool_search_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("tool_search_tool_search_result"),tool_references:u.array(u.object({type:u.literal("tool_reference"),tool_name:u.string()}))}),u.object({type:u.literal("tool_search_tool_result_error"),error_code:u.string()})])})])}),u.object({type:u.literal("content_block_delta"),index:u.number(),delta:u.discriminatedUnion("type",[u.object({type:u.literal("input_json_delta"),partial_json:u.string()}),u.object({type:u.literal("text_delta"),text:u.string()}),u.object({type:u.literal("thinking_delta"),thinking:u.string()}),u.object({type:u.literal("signature_delta"),signature:u.string()}),u.object({type:u.literal("citations_delta"),citation:u.discriminatedUnion("type",[u.object({type:u.literal("web_search_result_location"),cited_text:u.string(),url:u.string(),title:u.string(),encrypted_index:u.string()}),u.object({type:u.literal("page_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_page_number:u.number(),end_page_number:u.number()}),u.object({type:u.literal("char_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_char_index:u.number(),end_char_index:u.number()})])})])}),u.object({type:u.literal("content_block_stop"),index:u.number()}),u.object({type:u.literal("error"),error:u.object({type:u.string(),message:u.string()})}),u.object({type:u.literal("message_delta"),delta:u.object({stop_reason:u.string().nullish(),stop_sequence:u.string().nullish(),container:u.object({expires_at:u.string(),id:u.string(),skills:u.array(u.object({type:u.union([u.literal("anthropic"),u.literal("custom")]),skill_id:u.string(),version:u.string()})).nullish()}).nullish(),context_management:u.object({applied_edits:u.array(u.union([u.object({type:u.literal("clear_tool_uses_20250919"),cleared_tool_uses:u.number(),cleared_input_tokens:u.number()}),u.object({type:u.literal("clear_thinking_20251015"),cleared_thinking_turns:u.number(),cleared_input_tokens:u.number()})]))}).nullish()}),usage:u.looseObject({input_tokens:u.number().nullish(),output_tokens:u.number(),cache_creation_input_tokens:u.number().nullish()})}),u.object({type:u.literal("message_stop")}),u.object({type:u.literal("ping")})]))),eT=q(()=>H(u.object({signature:u.string().optional(),redactedData:u.string().optional()}))),kh=re.object({citations:re.object({enabled:re.boolean()}).optional(),title:re.string().optional(),context:re.string().optional()}),tT=re.object({sendReasoning:re.boolean().optional(),structuredOutputMode:re.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:re.object({type:re.union([re.literal("enabled"),re.literal("disabled")]),budgetTokens:re.number().optional()}).optional(),disableParallelToolUse:re.boolean().optional(),cacheControl:re.object({type:re.literal("ephemeral"),ttl:re.union([re.literal("5m"),re.literal("1h")]).optional()}).optional(),mcpServers:re.array(re.object({type:re.literal("url"),name:re.string(),url:re.string(),authorizationToken:re.string().nullish(),toolConfiguration:re.object({enabled:re.boolean().nullish(),allowedTools:re.array(re.string()).nullish()}).nullish()})).optional(),container:re.object({id:re.string().optional(),skills:re.array(re.object({type:re.union([re.literal("anthropic"),re.literal("custom")]),skillId:re.string(),version:re.string().optional()})).optional()}).optional(),toolStreaming:re.boolean().optional(),effort:re.enum(["low","medium","high"]).optional(),contextManagement:re.object({edits:re.array(re.discriminatedUnion("type",[re.object({type:re.literal("clear_tool_uses_20250919"),trigger:re.discriminatedUnion("type",[re.object({type:re.literal("input_tokens"),value:re.number()}),re.object({type:re.literal("tool_uses"),value:re.number()})]).optional(),keep:re.object({type:re.literal("tool_uses"),value:re.number()}).optional(),clearAtLeast:re.object({type:re.literal("input_tokens"),value:re.number()}).optional(),clearToolInputs:re.boolean().optional(),excludeTools:re.array(re.string()).optional()}),re.object({type:re.literal("clear_thinking_20251015"),keep:re.union([re.literal("all"),re.object({type:re.literal("thinking_turns"),value:re.number()})]).optional()})]))}).optional()}),Rh=4;function rT(t){var e;let r=t?.anthropic;return(e=r?.cacheControl)!=null?e:r?.cache_control}var il=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(t,e){let r=rT(t);if(r){if(!e.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${e.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>Rh){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${Rh} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return r}}getWarnings(){return this.warnings}},nT=q(()=>H(Vt.object({maxCharacters:Vt.number().optional()}))),oT=q(()=>H(Vt.object({command:Vt.enum(["view","create","str_replace","insert"]),path:Vt.string(),file_text:Vt.string().optional(),insert_line:Vt.number().int().optional(),new_str:Vt.string().optional(),old_str:Vt.string().optional(),view_range:Vt.array(Vt.number().int()).optional()}))),aT=Ee({id:"anthropic.text_editor_20250728",inputSchema:oT}),iT=(t={})=>aT(t),sT=q(()=>H(ze.object({maxUses:ze.number().optional(),allowedDomains:ze.array(ze.string()).optional(),blockedDomains:ze.array(ze.string()).optional(),userLocation:ze.object({type:ze.literal("approximate"),city:ze.string().optional(),region:ze.string().optional(),country:ze.string().optional(),timezone:ze.string().optional()}).optional()}))),Ph=q(()=>H(ze.array(ze.object({url:ze.string(),title:ze.string().nullable(),pageAge:ze.string().nullable(),encryptedContent:ze.string(),type:ze.literal("web_search_result")})))),lT=q(()=>H(ze.object({query:ze.string()}))),cT=Ze({id:"anthropic.web_search_20250305",inputSchema:lT,outputSchema:Ph,supportsDeferredResults:!0}),uT=(t={})=>cT(t),dT=q(()=>H(Me.object({maxUses:Me.number().optional(),allowedDomains:Me.array(Me.string()).optional(),blockedDomains:Me.array(Me.string()).optional(),citations:Me.object({enabled:Me.boolean()}).optional(),maxContentTokens:Me.number().optional()}))),Dh=q(()=>H(Me.object({type:Me.literal("web_fetch_result"),url:Me.string(),content:Me.object({type:Me.literal("document"),title:Me.string().nullable(),citations:Me.object({enabled:Me.boolean()}).optional(),source:Me.union([Me.object({type:Me.literal("base64"),mediaType:Me.literal("application/pdf"),data:Me.string()}),Me.object({type:Me.literal("text"),mediaType:Me.literal("text/plain"),data:Me.string()})])}),retrievedAt:Me.string().nullable()}))),pT=q(()=>H(Me.object({url:Me.string()}))),hT=Ze({id:"anthropic.web_fetch_20250910",inputSchema:pT,outputSchema:Dh,supportsDeferredResults:!0}),fT=(t={})=>hT(t);async function mT({tools:t,toolChoice:e,disableParallelToolUse:r,cacheControlValidator:n,supportsStructuredOutput:o}){var a;t=t?.length?t:void 0;let i=[],s=new Set,l=n||new il;if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:s};let c=[];for(let h of t)switch(h.type){case"function":{let g=l.getCacheControl(h.providerOptions,{type:"tool definition",canCache:!0}),y=(a=h.providerOptions)==null?void 0:a.anthropic,S=y?.deferLoading,f=y?.allowedCallers;c.push({name:h.name,description:h.description,input_schema:h.inputSchema,cache_control:g,...o===!0&&h.strict!=null?{strict:h.strict}:{},...S!=null?{defer_loading:S}:{},...f!=null?{allowed_callers:f}:{},...h.inputExamples!=null?{input_examples:h.inputExamples.map(b=>b.input)}:{}}),o===!0&&s.add("structured-outputs-2025-11-13"),(h.inputExamples!=null||f!=null)&&s.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(h.id){case"anthropic.code_execution_20250522":{s.add("code-execution-2025-05-22"),c.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{s.add("code-execution-2025-08-25"),c.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.computer_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"computer",type:"computer_20250124",display_width_px:h.args.displayWidthPx,display_height_px:h.args.displayHeightPx,display_number:h.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"computer",type:"computer_20241022",display_width_px:h.args.displayWidthPx,display_height_px:h.args.displayHeightPx,display_number:h.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{s.add("computer-use-2025-01-24"),c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let g=await St({value:h.args,schema:nT});c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:g.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{s.add("context-management-2025-06-27"),c.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{s.add("web-fetch-2025-09-10");let g=await St({value:h.args,schema:dT});c.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:g.maxUses,allowed_domains:g.allowedDomains,blocked_domains:g.blockedDomains,citations:g.citations,max_content_tokens:g.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let g=await St({value:h.args,schema:sT});c.push({type:"web_search_20250305",name:"web_search",max_uses:g.maxUses,allowed_domains:g.allowedDomains,blocked_domains:g.blockedDomains,user_location:g.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{s.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{s.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}default:{i.push({type:"unsupported",feature:`provider-defined tool ${h.id}`});break}}break}default:{i.push({type:"unsupported",feature:`tool ${h}`});break}}if(e==null)return{tools:c,toolChoice:r?{type:"auto",disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:s};let p=e.type;switch(p){case"auto":return{tools:c,toolChoice:{type:"auto",disable_parallel_tool_use:r},toolWarnings:i,betas:s};case"required":return{tools:c,toolChoice:{type:"any",disable_parallel_tool_use:r},toolWarnings:i,betas:s};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:s};case"tool":return{tools:c,toolChoice:{type:"tool",name:e.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:s};default:{let h=p;throw new tt({functionality:`tool choice type: ${h}`})}}}function Oh(t){var e,r;let n=t.input_tokens,o=t.output_tokens,a=(e=t.cache_creation_input_tokens)!=null?e:0,i=(r=t.cache_read_input_tokens)!=null?r:0;return{inputTokens:{total:n+a+i,noCache:n,cacheRead:i,cacheWrite:a},outputTokens:{total:o,text:void 0,reasoning:void 0},raw:t}}var jh=q(()=>H(zt.object({type:zt.literal("code_execution_result"),stdout:zt.string(),stderr:zt.string(),return_code:zt.number(),content:zt.array(zt.object({type:zt.literal("code_execution_output"),file_id:zt.string()})).optional().default([])}))),gT=q(()=>H(zt.object({code:zt.string()}))),yT=Ze({id:"anthropic.code_execution_20250522",inputSchema:gT,outputSchema:jh}),vT=(t={})=>yT(t),Lh=q(()=>H(ne.discriminatedUnion("type",[ne.object({type:ne.literal("code_execution_result"),stdout:ne.string(),stderr:ne.string(),return_code:ne.number(),content:ne.array(ne.object({type:ne.literal("code_execution_output"),file_id:ne.string()})).optional().default([])}),ne.object({type:ne.literal("bash_code_execution_result"),content:ne.array(ne.object({type:ne.literal("bash_code_execution_output"),file_id:ne.string()})),stdout:ne.string(),stderr:ne.string(),return_code:ne.number()}),ne.object({type:ne.literal("bash_code_execution_tool_result_error"),error_code:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution_tool_result_error"),error_code:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution_view_result"),content:ne.string(),file_type:ne.string(),num_lines:ne.number().nullable(),start_line:ne.number().nullable(),total_lines:ne.number().nullable()}),ne.object({type:ne.literal("text_editor_code_execution_create_result"),is_file_update:ne.boolean()}),ne.object({type:ne.literal("text_editor_code_execution_str_replace_result"),lines:ne.array(ne.string()).nullable(),new_lines:ne.number().nullable(),new_start:ne.number().nullable(),old_lines:ne.number().nullable(),old_start:ne.number().nullable()})]))),bT=q(()=>H(ne.discriminatedUnion("type",[ne.object({type:ne.literal("programmatic-tool-call"),code:ne.string()}),ne.object({type:ne.literal("bash_code_execution"),command:ne.string()}),ne.discriminatedUnion("command",[ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("view"),path:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("create"),path:ne.string(),file_text:ne.string().nullish()}),ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("str_replace"),path:ne.string(),old_str:ne.string(),new_str:ne.string()})])]))),_T=Ze({id:"anthropic.code_execution_20250825",inputSchema:bT,outputSchema:Lh,supportsDeferredResults:!0}),wT=(t={})=>_T(t),Fh=q(()=>H(Br.array(Br.object({type:Br.literal("tool_reference"),toolName:Br.string()})))),ET=q(()=>H(Br.object({pattern:Br.string(),limit:Br.number().optional()}))),TT=Ze({id:"anthropic.tool_search_regex_20251119",inputSchema:ET,outputSchema:Fh}),xT=(t={})=>TT(t);function ST(t){if(typeof t=="string")return Buffer.from(t,"base64").toString("utf-8");if(t instanceof Uint8Array)return new TextDecoder().decode(t);throw t instanceof URL?new tt({functionality:"URL-based text documents are not supported for citations"}):new tt({functionality:`unsupported data type for text documents: ${typeof t}`})}function tl(t){return t instanceof URL||CT(t)}function CT(t){return typeof t=="string"&&/^https?:\/\//i.test(t)}function rl(t){return t instanceof URL?t.toString():t}async function IT({prompt:t,sendReasoning:e,warnings:r,cacheControlValidator:n,toolNameMapping:o}){var a,i,s,l,c,p,h,g,y,S,f,b,_,M,B;let Z=new Set,N=AT(t),R=n||new il,O,ee=[];async function E(X){var W,ue;let V=await Ve({provider:"anthropic",providerOptions:X,schema:kh});return(ue=(W=V?.citations)==null?void 0:W.enabled)!=null?ue:!1}async function Q(X){let W=await Ve({provider:"anthropic",providerOptions:X,schema:kh});return{title:W?.title,context:W?.context}}for(let X=0;X<N.length;X++){let W=N[X],ue=X===N.length-1,V=W.type;switch(V){case"system":{if(O!=null)throw new tt({functionality:"Multiple system messages that are separated by user/assistant messages"});O=W.messages.map(({content:K,providerOptions:me})=>({type:"text",text:K,cache_control:R.getCacheControl(me,{type:"system message",canCache:!0})}));break}case"user":{let K=[];for(let me of W.messages){let{role:j,content:ve}=me;switch(j){case"user":{for(let Se=0;Se<ve.length;Se++){let fe=ve[Se],Fe=Se===ve.length-1,z=(a=R.getCacheControl(fe.providerOptions,{type:"user message part",canCache:!0}))!=null?a:Fe?R.getCacheControl(me.providerOptions,{type:"user message",canCache:!0}):void 0;switch(fe.type){case"text":{K.push({type:"text",text:fe.text,cache_control:z});break}case"file":{if(fe.mediaType.startsWith("image/"))K.push({type:"image",source:tl(fe.data)?{type:"url",url:rl(fe.data)}:{type:"base64",media_type:fe.mediaType==="image/*"?"image/jpeg":fe.mediaType,data:lr(fe.data)},cache_control:z});else if(fe.mediaType==="application/pdf"){Z.add("pdfs-2024-09-25");let U=await E(fe.providerOptions),be=await Q(fe.providerOptions);K.push({type:"document",source:tl(fe.data)?{type:"url",url:rl(fe.data)}:{type:"base64",media_type:"application/pdf",data:lr(fe.data)},title:(i=be.title)!=null?i:fe.filename,...be.context&&{context:be.context},...U&&{citations:{enabled:!0}},cache_control:z})}else if(fe.mediaType==="text/plain"){let U=await E(fe.providerOptions),be=await Q(fe.providerOptions);K.push({type:"document",source:tl(fe.data)?{type:"url",url:rl(fe.data)}:{type:"text",media_type:"text/plain",data:ST(fe.data)},title:(s=be.title)!=null?s:fe.filename,...be.context&&{context:be.context},...U&&{citations:{enabled:!0}},cache_control:z})}else throw new tt({functionality:`media type: ${fe.mediaType}`});break}}}break}case"tool":{for(let Se=0;Se<ve.length;Se++){let fe=ve[Se];if(fe.type==="tool-approval-response")continue;let Fe=Se===ve.length-1,z=(l=R.getCacheControl(fe.providerOptions,{type:"tool result part",canCache:!0}))!=null?l:Fe?R.getCacheControl(me.providerOptions,{type:"tool result message",canCache:!0}):void 0,U=fe.output,be;switch(U.type){case"content":be=U.value.map(we=>{switch(we.type){case"text":return{type:"text",text:we.text};case"image-data":return{type:"image",source:{type:"base64",media_type:we.mediaType,data:we.data}};case"image-url":return{type:"image",source:{type:"url",url:we.url}};case"file-url":return{type:"document",source:{type:"url",url:we.url}};case"file-data":{if(we.mediaType==="application/pdf")return Z.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:we.mediaType,data:we.data}};r.push({type:"other",message:`unsupported tool content part type: ${we.type} with media type: ${we.mediaType}`});return}default:{r.push({type:"other",message:`unsupported tool content part type: ${we.type}`});return}}}).filter(nu);break;case"text":case"error-text":be=U.value;break;case"execution-denied":be=(c=U.reason)!=null?c:"Tool execution denied.";break;case"json":case"error-json":default:be=JSON.stringify(U.value);break}K.push({type:"tool_result",tool_use_id:fe.toolCallId,content:be,is_error:U.type==="error-text"||U.type==="error-json"?!0:void 0,cache_control:z})}break}default:{let Se=j;throw new Error(`Unsupported role: ${Se}`)}}}ee.push({role:"user",content:K});break}case"assistant":{let K=[],me=new Set;for(let j=0;j<W.messages.length;j++){let ve=W.messages[j],Se=j===W.messages.length-1,{content:fe}=ve;for(let Fe=0;Fe<fe.length;Fe++){let z=fe[Fe],U=Fe===fe.length-1,be=(p=R.getCacheControl(z.providerOptions,{type:"assistant message part",canCache:!0}))!=null?p:U?R.getCacheControl(ve.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(z.type){case"text":{K.push({type:"text",text:ue&&Se&&U?z.text.trim():z.text,cache_control:be});break}case"reasoning":{if(e){let we=await Ve({provider:"anthropic",providerOptions:z.providerOptions,schema:eT});we!=null?we.signature!=null?(R.getCacheControl(z.providerOptions,{type:"thinking block",canCache:!1}),K.push({type:"thinking",thinking:z.text,signature:we.signature})):we.redactedData!=null?(R.getCacheControl(z.providerOptions,{type:"redacted thinking block",canCache:!1}),K.push({type:"redacted_thinking",data:we.redactedData})):r.push({type:"other",message:"unsupported reasoning metadata"}):r.push({type:"other",message:"unsupported reasoning metadata"})}else r.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(z.providerExecuted){let ae=o.toProviderToolName(z.toolName);if(((g=(h=z.providerOptions)==null?void 0:h.anthropic)==null?void 0:g.type)==="mcp-tool-use"){me.add(z.toolCallId);let d=(S=(y=z.providerOptions)==null?void 0:y.anthropic)==null?void 0:S.serverName;if(d==null||typeof d!="string"){r.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}K.push({type:"mcp_tool_use",id:z.toolCallId,name:z.toolName,input:z.input,server_name:d,cache_control:be})}else if(ae==="code_execution"&&z.input!=null&&typeof z.input=="object"&&"type"in z.input&&typeof z.input.type=="string"&&(z.input.type==="bash_code_execution"||z.input.type==="text_editor_code_execution"))K.push({type:"server_tool_use",id:z.toolCallId,name:z.input.type,input:z.input,cache_control:be});else if(ae==="code_execution"&&z.input!=null&&typeof z.input=="object"&&"type"in z.input&&z.input.type==="programmatic-tool-call"){let{type:d,...m}=z.input;K.push({type:"server_tool_use",id:z.toolCallId,name:"code_execution",input:m,cache_control:be})}else ae==="code_execution"||ae==="web_fetch"||ae==="web_search"?K.push({type:"server_tool_use",id:z.toolCallId,name:ae,input:z.input,cache_control:be}):ae==="tool_search_tool_regex"||ae==="tool_search_tool_bm25"?K.push({type:"server_tool_use",id:z.toolCallId,name:ae,input:z.input,cache_control:be}):r.push({type:"other",message:`provider executed tool call for tool ${z.toolName} is not supported`});break}let we=(f=z.providerOptions)==null?void 0:f.anthropic,de=we?.caller?we.caller.type==="code_execution_20250825"&&we.caller.toolId?{type:"code_execution_20250825",tool_id:we.caller.toolId}:we.caller.type==="direct"?{type:"direct"}:void 0:void 0;K.push({type:"tool_use",id:z.toolCallId,name:z.toolName,input:z.input,...de&&{caller:de},cache_control:be});break}case"tool-result":{let we=o.toProviderToolName(z.toolName);if(me.has(z.toolCallId)){let de=z.output;if(de.type!=="json"&&de.type!=="error-json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}K.push({type:"mcp_tool_result",tool_use_id:z.toolCallId,is_error:de.type==="error-json",content:de.value,cache_control:be})}else if(we==="code_execution"){let de=z.output;if(de.type==="error-text"||de.type==="error-json"){let ae={};try{typeof de.value=="string"?ae=JSON.parse(de.value):typeof de.value=="object"&&de.value!==null&&(ae=de.value)}catch{}ae.type==="code_execution_tool_result_error"?K.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(b=ae.errorCode)!=null?b:"unknown"},cache_control:be}):K.push({type:"bash_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:be,content:{type:"bash_code_execution_tool_result_error",error_code:(_=ae.errorCode)!=null?_:"unknown"}});break}if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}if(de.value==null||typeof de.value!="object"||!("type"in de.value)||typeof de.value.type!="string"){r.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${z.toolName}`});break}if(de.value.type==="code_execution_result"){let ae=await St({value:de.value,schema:jh});K.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:ae.type,stdout:ae.stdout,stderr:ae.stderr,return_code:ae.return_code,content:(M=ae.content)!=null?M:[]},cache_control:be})}else{let ae=await St({value:de.value,schema:Lh});ae.type==="code_execution_result"?K.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:ae.type,stdout:ae.stdout,stderr:ae.stderr,return_code:ae.return_code,content:(B=ae.content)!=null?B:[]},cache_control:be}):ae.type==="bash_code_execution_result"||ae.type==="bash_code_execution_tool_result_error"?K.push({type:"bash_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:be,content:ae}):K.push({type:"text_editor_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:be,content:ae})}break}if(we==="web_fetch"){let de=z.output;if(de.type==="error-json"){let Y=JSON.parse(de.value);K.push({type:"web_fetch_tool_result",tool_use_id:z.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:Y.errorCode},cache_control:be});break}if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}let ae=await St({value:de.value,schema:Dh});K.push({type:"web_fetch_tool_result",tool_use_id:z.toolCallId,content:{type:"web_fetch_result",url:ae.url,retrieved_at:ae.retrievedAt,content:{type:"document",title:ae.content.title,citations:ae.content.citations,source:{type:ae.content.source.type,media_type:ae.content.source.mediaType,data:ae.content.source.data}}},cache_control:be});break}if(we==="web_search"){let de=z.output;if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}let ae=await St({value:de.value,schema:Ph});K.push({type:"web_search_tool_result",tool_use_id:z.toolCallId,content:ae.map(Y=>({url:Y.url,title:Y.title,page_age:Y.pageAge,encrypted_content:Y.encryptedContent,type:Y.type})),cache_control:be});break}if(we==="tool_search_tool_regex"||we==="tool_search_tool_bm25"){let de=z.output;if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}let Y=(await St({value:de.value,schema:Fh})).map(d=>({type:"tool_reference",tool_name:d.toolName}));K.push({type:"tool_search_tool_result",tool_use_id:z.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:Y},cache_control:be});break}r.push({type:"other",message:`provider executed tool result for tool ${z.toolName} is not supported`});break}}}}ee.push({role:"assistant",content:K});break}default:{let K=V;throw new Error(`content type: ${K}`)}}}return{prompt:{system:O,messages:ee},betas:Z}}function AT(t){let e=[],r;for(let n of t){let{role:o}=n;switch(o){case"system":{r?.type!=="system"&&(r={type:"system",messages:[]},e.push(r)),r.messages.push(n);break}case"assistant":{r?.type!=="assistant"&&(r={type:"assistant",messages:[]},e.push(r)),r.messages.push(n);break}case"user":{r?.type!=="user"&&(r={type:"user",messages:[]},e.push(r)),r.messages.push(n);break}case"tool":{r?.type!=="user"&&(r={type:"user",messages:[]},e.push(r)),r.messages.push(n);break}default:{let a=o;throw new Error(`Unsupported role: ${a}`)}}}return e}function nl({finishReason:t,isJsonResponseFromTool:e}){switch(t){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return e?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";default:return"other"}}function Nh(t,e,r){var n;if(t.type!=="page_location"&&t.type!=="char_location")return;let o=e[t.document_index];if(o)return{type:"source",sourceType:"document",id:r(),mediaType:o.mediaType,title:(n=t.document_title)!=null?n:o.title,filename:o.filename,providerMetadata:{anthropic:t.type==="page_location"?{citedText:t.cited_text,startPageNumber:t.start_page_number,endPageNumber:t.end_page_number}:{citedText:t.cited_text,startCharIndex:t.start_char_index,endCharIndex:t.end_char_index}}}}var kT=class{constructor(t,e){this.specificationVersion="v3";var r;this.modelId=t,this.config=e,this.generateId=(r=e.generateId)!=null?r:xt}supportsUrl(t){return t.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({userSuppliedBetas:t,prompt:e,maxOutputTokens:r,temperature:n,topP:o,topK:a,frequencyPenalty:i,presencePenalty:s,stopSequences:l,responseFormat:c,seed:p,tools:h,toolChoice:g,providerOptions:y,stream:S}){var f,b,_,M,B,Z;let N=[];i!=null&&N.push({type:"unsupported",feature:"frequencyPenalty"}),s!=null&&N.push({type:"unsupported",feature:"presencePenalty"}),p!=null&&N.push({type:"unsupported",feature:"seed"}),n!=null&&n>1?(N.push({type:"unsupported",feature:"temperature",details:`${n} exceeds anthropic maximum of 1.0. clamped to 1.0`}),n=1):n!=null&&n<0&&(N.push({type:"unsupported",feature:"temperature",details:`${n} is below anthropic minimum of 0. clamped to 0`}),n=0),c?.type==="json"&&c.schema==null&&N.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let R=await Ve({provider:"anthropic",providerOptions:y,schema:tT}),{maxOutputTokens:O,supportsStructuredOutput:ee,isKnownModel:E}=RT(this.modelId),Q=((f=this.config.supportsNativeStructuredOutput)!=null?f:!0)&&ee,X=(b=R?.structuredOutputMode)!=null?b:"auto",W=X==="outputFormat"||X==="auto"&&Q,ue=c?.type==="json"&&c.schema!=null&&!W?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:c.schema}:void 0,V=R?.contextManagement,K=new il,me=Xc({tools:h,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:j,betas:ve}=await IT({prompt:e,sendReasoning:(_=R?.sendReasoning)!=null?_:!0,warnings:N,cacheControlValidator:K,toolNameMapping:me}),Se=((M=R?.thinking)==null?void 0:M.type)==="enabled",fe=(B=R?.thinking)==null?void 0:B.budgetTokens,Fe=r??O,z={model:this.modelId,max_tokens:Fe,temperature:n,top_k:a,top_p:o,stop_sequences:l,...Se&&{thinking:{type:"enabled",budget_tokens:fe}},...R?.effort&&{output_config:{effort:R.effort}},...W&&c?.type==="json"&&c.schema!=null&&{output_format:{type:"json_schema",schema:c.schema}},...R?.mcpServers&&R.mcpServers.length>0&&{mcp_servers:R.mcpServers.map(d=>({type:d.type,name:d.name,url:d.url,authorization_token:d.authorizationToken,tool_configuration:d.toolConfiguration?{allowed_tools:d.toolConfiguration.allowedTools,enabled:d.toolConfiguration.enabled}:void 0}))},...R?.container&&{container:R.container.skills&&R.container.skills.length>0?{id:R.container.id,skills:R.container.skills.map(d=>({type:d.type,skill_id:d.skillId,version:d.version}))}:R.container.id},system:j.system,messages:j.messages,...V&&{context_management:{edits:V.edits.map(d=>{let m=d.type;switch(m){case"clear_tool_uses_20250919":return{type:d.type,...d.trigger!==void 0&&{trigger:d.trigger},...d.keep!==void 0&&{keep:d.keep},...d.clearAtLeast!==void 0&&{clear_at_least:d.clearAtLeast},...d.clearToolInputs!==void 0&&{clear_tool_inputs:d.clearToolInputs},...d.excludeTools!==void 0&&{exclude_tools:d.excludeTools}};case"clear_thinking_20251015":return{type:d.type,...d.keep!==void 0&&{keep:d.keep}};default:N.push({type:"other",message:`Unknown context management strategy: ${m}`});return}}).filter(d=>d!==void 0)}}};Se?(fe==null&&(N.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),z.thinking={type:"enabled",budget_tokens:1024},fe=1024),z.temperature!=null&&(z.temperature=void 0,N.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),a!=null&&(z.top_k=void 0,N.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(z.top_p=void 0,N.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),z.max_tokens=Fe+(fe??0)):o!=null&&n!=null&&(N.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),z.top_p=void 0),E&&z.max_tokens>O&&(r!=null&&N.push({type:"unsupported",feature:"maxOutputTokens",details:`${z.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${O} max output tokens. The max output tokens have been limited to ${O}.`}),z.max_tokens=O),R?.mcpServers&&R.mcpServers.length>0&&ve.add("mcp-client-2025-04-04"),V&&ve.add("context-management-2025-06-27"),R?.container&&R.container.skills&&R.container.skills.length>0&&(ve.add("code-execution-2025-08-25"),ve.add("skills-2025-10-02"),ve.add("files-api-2025-04-14"),h?.some(d=>d.type==="provider"&&d.id==="anthropic.code_execution_20250825")||N.push({type:"other",message:"code execution tool is required when using skills"})),R?.effort&&ve.add("effort-2025-11-24"),S&&((Z=R?.toolStreaming)==null||Z)&&ve.add("fine-grained-tool-streaming-2025-05-14"),W&&c?.type==="json"&&c.schema!=null&&ve.add("structured-outputs-2025-11-13");let{tools:be,toolChoice:we,toolWarnings:de,betas:ae}=await mT(ue!=null?{tools:[...h??[],ue],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:K,supportsStructuredOutput:Q}:{tools:h??[],toolChoice:g,disableParallelToolUse:R?.disableParallelToolUse,cacheControlValidator:K,supportsStructuredOutput:Q}),Y=K.getWarnings();return{args:{...z,tools:be,tool_choice:we,stream:S===!0?!0:void 0},warnings:[...N,...de,...Y],betas:new Set([...ve,...ae,...t]),usesJsonResponseTool:ue!=null,toolNameMapping:me}}async getHeaders({betas:t,headers:e}){return Ge(await Te(this.config.headers),e,t.size>0?{"anthropic-beta":Array.from(t).join(",")}:{})}async getBetasFromHeaders(t){var e,r;let o=(e=(await Te(this.config.headers))["anthropic-beta"])!=null?e:"",a=(r=t?.["anthropic-beta"])!=null?r:"";return new Set([...o.toLowerCase().split(","),...a.toLowerCase().split(",")].map(i=>i.trim()).filter(i=>i!==""))}buildRequestUrl(t){var e,r,n;return(n=(r=(e=this.config).buildRequestUrl)==null?void 0:r.call(e,this.config.baseURL,t))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(t){var e,r,n;return(n=(r=(e=this.config).transformRequestBody)==null?void 0:r.call(e,t))!=null?n:t}extractCitationDocuments(t){let e=r=>{var n,o;if(r.type!=="file"||r.mediaType!=="application/pdf"&&r.mediaType!=="text/plain")return!1;let a=(n=r.providerOptions)==null?void 0:n.anthropic,i=a?.citations;return(o=i?.enabled)!=null?o:!1};return t.filter(r=>r.role==="user").flatMap(r=>r.content).filter(e).map(r=>{var n;let o=r;return{title:(n=o.filename)!=null?n:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(t){var e,r,n,o,a,i,s,l,c,p,h;let{args:g,warnings:y,betas:S,usesJsonResponseTool:f,toolNameMapping:b}=await this.getArgs({...t,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),_=this.extractCitationDocuments(t.prompt),{responseHeaders:M,value:B,rawValue:Z}=await Ue({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:S,headers:t.headers}),body:this.transformRequestBody(g),failedResponseHandler:Ah,successfulResponseHandler:qe(ZE),abortSignal:t.abortSignal,fetch:this.config.fetch}),N=[],R={},O={},ee=!1;for(let E of B.content)switch(E.type){case"text":{if(!f&&(N.push({type:"text",text:E.text}),E.citations))for(let Q of E.citations){let X=Nh(Q,_,this.generateId);X&&N.push(X)}break}case"thinking":{N.push({type:"reasoning",text:E.thinking,providerMetadata:{anthropic:{signature:E.signature}}});break}case"redacted_thinking":{N.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:E.data}}});break}case"tool_use":{if(f&&E.name==="json")ee=!0,N.push({type:"text",text:JSON.stringify(E.input)});else{let X=E.caller,W=X?{type:X.type,toolId:"tool_id"in X?X.tool_id:void 0}:void 0;N.push({type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),...W&&{providerMetadata:{anthropic:{caller:W}}}})}break}case"server_tool_use":{if(E.name==="text_editor_code_execution"||E.name==="bash_code_execution")N.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName("code_execution"),input:JSON.stringify({type:E.name,...E.input}),providerExecuted:!0});else if(E.name==="web_search"||E.name==="code_execution"||E.name==="web_fetch"){let Q=E.name==="code_execution"&&E.input!=null&&typeof E.input=="object"&&"code"in E.input&&!("type"in E.input)?{type:"programmatic-tool-call",...E.input}:E.input;N.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName(E.name),input:JSON.stringify(Q),providerExecuted:!0})}else(E.name==="tool_search_tool_regex"||E.name==="tool_search_tool_bm25")&&(O[E.id]=E.name,N.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName(E.name),input:JSON.stringify(E.input),providerExecuted:!0}));break}case"mcp_tool_use":{R[E.id]={type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:E.server_name}}},N.push(R[E.id]);break}case"mcp_tool_result":{N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:R[E.tool_use_id].toolName,isError:E.is_error,result:E.content,dynamic:!0,providerMetadata:R[E.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{E.content.type==="web_fetch_result"?N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:E.content.url,retrievedAt:E.content.retrieved_at,content:{type:E.content.content.type,title:E.content.content.title,citations:E.content.content.citations,source:{type:E.content.content.source.type,mediaType:E.content.content.source.media_type,data:E.content.content.source.data}}}}):E.content.type==="web_fetch_tool_result_error"&&N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:E.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(E.content)){N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_search"),result:E.content.map(Q=>{var X;return{url:Q.url,title:Q.title,pageAge:(X=Q.page_age)!=null?X:null,encryptedContent:Q.encrypted_content,type:Q.type}})});for(let Q of E.content)N.push({type:"source",sourceType:"url",id:this.generateId(),url:Q.url,title:Q.title,providerMetadata:{anthropic:{pageAge:(e=Q.page_age)!=null?e:null}}})}else N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:E.content.error_code}});break}case"code_execution_tool_result":{E.content.type==="code_execution_result"?N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),result:{type:E.content.type,stdout:E.content.stdout,stderr:E.content.stderr,return_code:E.content.return_code,content:(r=E.content.content)!=null?r:[]}}):E.content.type==="code_execution_tool_result_error"&&N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:E.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),result:E.content});break}case"tool_search_tool_result":{let Q=(n=O[E.tool_use_id])!=null?n:"tool_search_tool_regex";E.content.type==="tool_search_tool_search_result"?N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName(Q),result:E.content.tool_references.map(X=>({type:X.type,toolName:X.tool_name}))}):N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName(Q),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:E.content.error_code}});break}}return{content:N,finishReason:{unified:nl({finishReason:B.stop_reason,isJsonResponseFromTool:ee}),raw:(o=B.stop_reason)!=null?o:void 0},usage:Oh(B.usage),request:{body:g},response:{id:(a=B.id)!=null?a:void 0,modelId:(i=B.model)!=null?i:void 0,headers:M,body:Z},warnings:y,providerMetadata:{anthropic:{usage:B.usage,cacheCreationInputTokens:(s=B.usage.cache_creation_input_tokens)!=null?s:null,stopSequence:(l=B.stop_sequence)!=null?l:null,container:B.container?{expiresAt:B.container.expires_at,id:B.container.id,skills:(p=(c=B.container.skills)==null?void 0:c.map(E=>({type:E.type,skillId:E.skill_id,version:E.version})))!=null?p:null}:null,contextManagement:(h=Mh(B.context_management))!=null?h:null}}}}async doStream(t){var e,r;let{args:n,warnings:o,betas:a,usesJsonResponseTool:i,toolNameMapping:s}=await this.getArgs({...t,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),l=this.extractCitationDocuments(t.prompt),c=this.buildRequestUrl(!0),{responseHeaders:p,value:h}=await Ue({url:c,headers:await this.getHeaders({betas:a,headers:t.headers}),body:this.transformRequestBody(n),failedResponseHandler:Ah,successfulResponseHandler:Sr(QE),abortSignal:t.abortSignal,fetch:this.config.fetch}),g={unified:"other",raw:void 0},y={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},S={},f={},b={},_=null,M,B=null,Z=null,N=null,R=!1,O,ee=this.generateId,E=h.pipeThrough(new TransformStream({start(ue){ue.enqueue({type:"stream-start",warnings:o})},transform(ue,V){var K,me,j,ve,Se,fe,Fe,z,U,be,we,de,ae;if(t.includeRawChunks&&V.enqueue({type:"raw",rawValue:ue.rawValue}),!ue.success){V.enqueue({type:"error",error:ue.error});return}let Y=ue.value;switch(Y.type){case"ping":return;case"content_block_start":{let d=Y.content_block,m=d.type;switch(O=m,m){case"text":{if(i)return;S[Y.index]={type:"text"},V.enqueue({type:"text-start",id:String(Y.index)});return}case"thinking":{S[Y.index]={type:"reasoning"},V.enqueue({type:"reasoning-start",id:String(Y.index)});return}case"redacted_thinking":{S[Y.index]={type:"reasoning"},V.enqueue({type:"reasoning-start",id:String(Y.index),providerMetadata:{anthropic:{redactedData:d.data}}});return}case"tool_use":{if(i&&d.name==="json")R=!0,S[Y.index]={type:"text"},V.enqueue({type:"text-start",id:String(Y.index)});else{let C=d.caller,x=C?{type:C.type,toolId:"tool_id"in C?C.tool_id:void 0}:void 0,D=d.input&&Object.keys(d.input).length>0?JSON.stringify(d.input):"";S[Y.index]={type:"tool-call",toolCallId:d.id,toolName:d.name,input:D,firstDelta:D.length===0,...x&&{caller:x}},V.enqueue({type:"tool-input-start",id:d.id,toolName:d.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(d.name)){let v=d.name==="text_editor_code_execution"||d.name==="bash_code_execution"?"code_execution":d.name,C=s.toCustomToolName(v);S[Y.index]={type:"tool-call",toolCallId:d.id,toolName:C,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:d.name},V.enqueue({type:"tool-input-start",id:d.id,toolName:C,providerExecuted:!0})}else if(d.name==="tool_search_tool_regex"||d.name==="tool_search_tool_bm25"){b[d.id]=d.name;let v=s.toCustomToolName(d.name);S[Y.index]={type:"tool-call",toolCallId:d.id,toolName:v,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:d.name},V.enqueue({type:"tool-input-start",id:d.id,toolName:v,providerExecuted:!0})}return}case"web_fetch_tool_result":{d.content.type==="web_fetch_result"?V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:d.content.url,retrievedAt:d.content.retrieved_at,content:{type:d.content.content.type,title:d.content.content.title,citations:d.content.content.citations,source:{type:d.content.content.source.type,mediaType:d.content.content.source.media_type,data:d.content.content.source.data}}}}):d.content.type==="web_fetch_tool_result_error"&&V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:d.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(d.content)){V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_search"),result:d.content.map(v=>{var C;return{url:v.url,title:v.title,pageAge:(C=v.page_age)!=null?C:null,encryptedContent:v.encrypted_content,type:v.type}})});for(let v of d.content)V.enqueue({type:"source",sourceType:"url",id:ee(),url:v.url,title:v.title,providerMetadata:{anthropic:{pageAge:(K=v.page_age)!=null?K:null}}})}else V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:d.content.error_code}});return}case"code_execution_tool_result":{d.content.type==="code_execution_result"?V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),result:{type:d.content.type,stdout:d.content.stdout,stderr:d.content.stderr,return_code:d.content.return_code,content:(me=d.content.content)!=null?me:[]}}):d.content.type==="code_execution_tool_result_error"&&V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:d.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),result:d.content});return}case"tool_search_tool_result":{let v=(j=b[d.tool_use_id])!=null?j:"tool_search_tool_regex";d.content.type==="tool_search_tool_search_result"?V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName(v),result:d.content.tool_references.map(C=>({type:C.type,toolName:C.tool_name}))}):V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName(v),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:d.content.error_code}});return}case"mcp_tool_use":{f[d.id]={type:"tool-call",toolCallId:d.id,toolName:d.name,input:JSON.stringify(d.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:d.server_name}}},V.enqueue(f[d.id]);return}case"mcp_tool_result":{V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:f[d.tool_use_id].toolName,isError:d.is_error,result:d.content,dynamic:!0,providerMetadata:f[d.tool_use_id].providerMetadata});return}default:{let v=m;throw new Error(`Unsupported content block type: ${v}`)}}}case"content_block_stop":{if(S[Y.index]!=null){let d=S[Y.index];switch(d.type){case"text":{V.enqueue({type:"text-end",id:String(Y.index)});break}case"reasoning":{V.enqueue({type:"reasoning-end",id:String(Y.index)});break}case"tool-call":if(!(i&&d.toolName==="json")){V.enqueue({type:"tool-input-end",id:d.toolCallId});let v=d.input===""?"{}":d.input;if(d.providerToolName==="code_execution")try{let C=JSON.parse(v);C!=null&&typeof C=="object"&&"code"in C&&!("type"in C)&&(v=JSON.stringify({type:"programmatic-tool-call",...C}))}catch{}V.enqueue({type:"tool-call",toolCallId:d.toolCallId,toolName:d.toolName,input:v,providerExecuted:d.providerExecuted,...d.caller&&{providerMetadata:{anthropic:{caller:d.caller}}}})}break}delete S[Y.index]}O=void 0;return}case"content_block_delta":{let d=Y.delta.type;switch(d){case"text_delta":{if(i)return;V.enqueue({type:"text-delta",id:String(Y.index),delta:Y.delta.text});return}case"thinking_delta":{V.enqueue({type:"reasoning-delta",id:String(Y.index),delta:Y.delta.thinking});return}case"signature_delta":{O==="thinking"&&V.enqueue({type:"reasoning-delta",id:String(Y.index),delta:"",providerMetadata:{anthropic:{signature:Y.delta.signature}}});return}case"input_json_delta":{let m=S[Y.index],v=Y.delta.partial_json;if(v.length===0)return;if(R){if(m?.type!=="text")return;V.enqueue({type:"text-delta",id:String(Y.index),delta:v})}else{if(m?.type!=="tool-call")return;m.firstDelta&&(m.providerToolName==="bash_code_execution"||m.providerToolName==="text_editor_code_execution")&&(v=`{"type": "${m.providerToolName}",${v.substring(1)}`),V.enqueue({type:"tool-input-delta",id:m.toolCallId,delta:v}),m.input+=v,m.firstDelta=!1}return}case"citations_delta":{let m=Y.delta.citation,v=Nh(m,l,ee);v&&V.enqueue(v);return}default:{let m=d;throw new Error(`Unsupported delta type: ${m}`)}}}case"message_start":{if(y.input_tokens=Y.message.usage.input_tokens,y.cache_read_input_tokens=(ve=Y.message.usage.cache_read_input_tokens)!=null?ve:0,y.cache_creation_input_tokens=(Se=Y.message.usage.cache_creation_input_tokens)!=null?Se:0,M={...Y.message.usage},B=(fe=Y.message.usage.cache_creation_input_tokens)!=null?fe:null,Y.message.container!=null&&(N={expiresAt:Y.message.container.expires_at,id:Y.message.container.id,skills:null}),Y.message.stop_reason!=null&&(g={unified:nl({finishReason:Y.message.stop_reason,isJsonResponseFromTool:R}),raw:Y.message.stop_reason}),V.enqueue({type:"response-metadata",id:(Fe=Y.message.id)!=null?Fe:void 0,modelId:(z=Y.message.model)!=null?z:void 0}),Y.message.content!=null)for(let d=0;d<Y.message.content.length;d++){let m=Y.message.content[d];if(m.type==="tool_use"){let v=m.caller,C=v?{type:v.type,toolId:"tool_id"in v?v.tool_id:void 0}:void 0;V.enqueue({type:"tool-input-start",id:m.id,toolName:m.name});let x=JSON.stringify((U=m.input)!=null?U:{});V.enqueue({type:"tool-input-delta",id:m.id,delta:x}),V.enqueue({type:"tool-input-end",id:m.id}),V.enqueue({type:"tool-call",toolCallId:m.id,toolName:m.name,input:x,...C&&{providerMetadata:{anthropic:{caller:C}}}})}}return}case"message_delta":{Y.usage.input_tokens!=null&&y.input_tokens!==Y.usage.input_tokens&&(y.input_tokens=Y.usage.input_tokens),y.output_tokens=Y.usage.output_tokens,g={unified:nl({finishReason:Y.delta.stop_reason,isJsonResponseFromTool:R}),raw:(be=Y.delta.stop_reason)!=null?be:void 0},Z=(we=Y.delta.stop_sequence)!=null?we:null,N=Y.delta.container!=null?{expiresAt:Y.delta.container.expires_at,id:Y.delta.container.id,skills:(ae=(de=Y.delta.container.skills)==null?void 0:de.map(d=>({type:d.type,skillId:d.skill_id,version:d.version})))!=null?ae:null}:null,Y.delta.context_management&&(_=Mh(Y.delta.context_management)),M={...M,...Y.usage};return}case"message_stop":{V.enqueue({type:"finish",finishReason:g,usage:Oh(y),providerMetadata:{anthropic:{usage:M??null,cacheCreationInputTokens:B,stopSequence:Z,container:N,contextManagement:_}}});return}case"error":{V.enqueue({type:"error",error:Y.error});return}default:{let d=Y;throw new Error(`Unsupported chunk type: ${d}`)}}}})),[Q,X]=E.tee(),W=Q.getReader();try{await W.read();let ue=await W.read();if(((e=ue.value)==null?void 0:e.type)==="raw"&&(ue=await W.read()),((r=ue.value)==null?void 0:r.type)==="error"){let V=ue.value.error;throw new $e({message:V.message,url:c,requestBodyValues:n,statusCode:V.type==="overloaded_error"?529:500,responseHeaders:p,responseBody:JSON.stringify(V),isRetryable:V.type==="overloaded_error"})}}finally{W.cancel().catch(()=>{}),W.releaseLock()}return{stream:X,request:{body:n},response:{headers:p}}}};function RT(t){return t.includes("claude-sonnet-4-5")||t.includes("claude-opus-4-5")||t.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,isKnownModel:!0}:t.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,isKnownModel:!0}:t.includes("claude-sonnet-4-")||t.includes("claude-3-7-sonnet")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-3-5-haiku")?{maxOutputTokens:8192,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!1}}function Mh(t){return t?{appliedEdits:t.applied_edits.map(e=>{switch(e.type){case"clear_tool_uses_20250919":return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case"clear_thinking_20251015":return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens}}}).filter(e=>e!==void 0)}:null}var OT=q(()=>H(ol.object({command:ol.string(),restart:ol.boolean().optional()}))),NT=Ee({id:"anthropic.bash_20241022",inputSchema:OT}),MT=q(()=>H(al.object({command:al.string(),restart:al.boolean().optional()}))),PT=Ee({id:"anthropic.bash_20250124",inputSchema:MT}),DT=q(()=>H(oo.object({action:oo.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:oo.array(oo.number().int()).optional(),text:oo.string().optional()}))),jT=Ee({id:"anthropic.computer_20241022",inputSchema:DT}),LT=q(()=>H(Ot.object({action:Ot.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:Ot.tuple([Ot.number().int(),Ot.number().int()]).optional(),duration:Ot.number().optional(),scroll_amount:Ot.number().optional(),scroll_direction:Ot.enum(["up","down","left","right"]).optional(),start_coordinate:Ot.tuple([Ot.number().int(),Ot.number().int()]).optional(),text:Ot.string().optional()}))),FT=Ee({id:"anthropic.computer_20250124",inputSchema:LT}),UT=q(()=>H(De.discriminatedUnion("command",[De.object({command:De.literal("view"),path:De.string(),view_range:De.tuple([De.number(),De.number()]).optional()}),De.object({command:De.literal("create"),path:De.string(),file_text:De.string()}),De.object({command:De.literal("str_replace"),path:De.string(),old_str:De.string(),new_str:De.string()}),De.object({command:De.literal("insert"),path:De.string(),insert_line:De.number(),insert_text:De.string()}),De.object({command:De.literal("delete"),path:De.string()}),De.object({command:De.literal("rename"),old_path:De.string(),new_path:De.string()})]))),HT=Ee({id:"anthropic.memory_20250818",inputSchema:UT}),qT=q(()=>H(yr.object({command:yr.enum(["view","create","str_replace","insert","undo_edit"]),path:yr.string(),file_text:yr.string().optional(),insert_line:yr.number().int().optional(),new_str:yr.string().optional(),old_str:yr.string().optional(),view_range:yr.array(yr.number().int()).optional()}))),$T=Ee({id:"anthropic.text_editor_20241022",inputSchema:qT}),GT=q(()=>H(vr.object({command:vr.enum(["view","create","str_replace","insert","undo_edit"]),path:vr.string(),file_text:vr.string().optional(),insert_line:vr.number().int().optional(),new_str:vr.string().optional(),old_str:vr.string().optional(),view_range:vr.array(vr.number().int()).optional()}))),BT=Ee({id:"anthropic.text_editor_20250124",inputSchema:GT}),VT=q(()=>H(br.object({command:br.enum(["view","create","str_replace","insert"]),path:br.string(),file_text:br.string().optional(),insert_line:br.number().int().optional(),new_str:br.string().optional(),old_str:br.string().optional(),view_range:br.array(br.number().int()).optional()}))),zT=Ee({id:"anthropic.text_editor_20250429",inputSchema:VT}),WT=q(()=>H(Vr.array(Vr.object({type:Vr.literal("tool_reference"),toolName:Vr.string()})))),JT=q(()=>H(Vr.object({query:Vr.string(),limit:Vr.number().optional()}))),KT=Ze({id:"anthropic.tool_search_bm25_20251119",inputSchema:JT,outputSchema:WT}),YT=(t={})=>KT(t),XT={bash_20241022:NT,bash_20250124:PT,codeExecution_20250522:vT,codeExecution_20250825:wT,computer_20241022:jT,computer_20250124:FT,memory_20250818:HT,textEditor_20241022:$T,textEditor_20250124:BT,textEditor_20250429:zT,textEditor_20250728:iT,webFetch_20250910:fT,webSearch_20250305:uT,toolSearchRegex_20251119:xT,toolSearchBm25_20251119:YT};function sl(t={}){var e,r;let n=(e=dr(Lt({settingValue:t.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?e:"https://api.anthropic.com/v1",o=(r=t.name)!=null?r:"anthropic.messages",a=()=>lt({"anthropic-version":"2023-06-01","x-api-key":wo({apiKey:t.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...t.headers},`ai-sdk/anthropic/${YE}`),i=l=>{var c;return new kT(l,{provider:o,baseURL:n,headers:a,fetch:t.fetch,generateId:(c=t.generateId)!=null?c:xt,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},s=function(l){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return i(l)};return s.specificationVersion="v3",s.languageModel=i,s.chat=i,s.messages=i,s.embeddingModel=l=>{throw new Ha({modelId:l,modelType:"embeddingModel"})},s.textEmbeddingModel=s.embeddingModel,s.imageModel=l=>{throw new Ha({modelId:l,modelType:"imageModel"})},s.tools=XT,s}var LR=sl();function Uh(t){let e=Sn().env?.ANTHROPIC_API_KEY;if(!e)throw new Error("ANTHROPIC_API_KEY not configured in SDK config");return ce.debug(`Using Anthropic provider: model=${t}`),sl({apiKey:e})(t)}function Hh(t){return{anthropic:{structuredOutputMode:"jsonTool"}}}function WR(t){if(t.startsWith("claude-"))return Uh(t);if(t.startsWith("gemini-"))return Ch(t);throw new Error(`Unsupported model: ${t}. Use 'claude-*' or 'gemini-*' models.`)}function JR(t,e){return t.startsWith("claude-")?Hh(t):Ih(e,t)}async function $h(){let{default:t}=await import("sharp");return t}var qh=768;async function ll(t,e){let r=await $h(),n=await r(t).metadata(),o=n.width||0,a=n.height||0;if(o===0||a===0)throw new Error("Invalid image dimensions");let i=a,s=0,l=Math.floor((o-i)/2),c=Math.max(0,o-i),p=(S,f)=>{let b=r(t).extract({left:S,top:0,width:f,height:i});return e?.resize&&(b=b.resize(qh,qh)),b.png().toBuffer()},[h,g,y]=await Promise.all([p(s,Math.min(i,o)),p(l,Math.min(i,o-l)),p(c,Math.min(i,o-c))]);return[h,g,y]}async function Gh(t){let e=(await $h())(t),r=await e.metadata(),n=r.width||0,o=r.height||0;if(n===0||o===0)throw new Error("Invalid image dimensions");let{data:a}=await e.grayscale().raw().toBuffer({resolveWithObject:!0}),i=[];for(let s=0;s<o;s++){i[s]=[];for(let l=0;l<n;l++)i[s][l]=a[s*n+l]}return{pixels:i,width:n,height:o}}var cl=new Set(["button","link","textbox","checkbox","radio","combobox","listbox","menuitem","menuitemcheckbox","menuitemradio","option","tab","switch","slider","spinbutton","searchbox","scrollbar","treeitem","gridcell"]),Ta=new Set(["click","mousedown","mouseup","dblclick","pointerdown","pointerup","touchstart","touchend"]),Bh=["[onclick]","[onmousedown]","[ontouchstart]","div","span","li","tr","td","[role]",'[class*="btn"]','[class*="button"]','[class*="click"]',"[data-action]","[data-click]"],Vh=500;function XR(t){return t?cl.has(t):!1}function ZR(t){return Ta.has(t)}function QR(t){return t.filter(e=>Ta.has(e.type))}function zh(t,e){return t.length>e?t.slice(0,e)+"...":t}var Wh=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","data-id","data-testid","data-test-id","data-handlepos","data-item-id"],Jh={"react-flow__(\\S+)":"$1"};var Kh=class{constructor(t,e=null){this.isVisible=t,this.parent=e}},ao=class extends Kh{constructor(t,e,r=null){super(e,r),this.text=t,this.type="TEXT_NODE"}hasParentWithHighlightIndex(){let t=this.parent;for(;t!==null;){if(t.highlightIndex!==null)return!0;t=t.parent}return!1}isParentInViewport(){return this.parent===null?!1:this.parent.isInViewport}isParentTopElement(){return this.parent===null?!1:this.parent.isTopElement}},ar=class xa extends Kh{constructor(e,r,n,o,a,i=!1,s=!1,l=!1,c=!1,p=!1,h=!1,g=null,y=null,S=null,f=null,b=[],_=null){super(a,_),this.tagName=e,this.xpath=r,this.attributes=n,this.children=o,this.isInteractive=i,this.isScrollable=s,this.markAsClickable=l,this.isTopElement=c,this.isInViewport=p,this.shadowRoot=h,this.highlightIndex=g,this.viewportCoordinates=y,this.pageCoordinates=S,this.viewportInfo=f,this.isNew=null,this.shadowHostXPaths=b}getAllTextTillNextClickableElement(e=-1){let r=[],n=(o,a)=>{if(!(e!==-1&&a>e)&&!(o instanceof xa&&o!==this&&o.highlightIndex!==null)){if(o instanceof ao)r.push(o.text);else if(o instanceof xa)for(let i of o.children)n(i,a+1)}};return n(this,0),r.join(`
|
|
52
|
-
`).trim()}clickableElementsToString(e){let r=e?.includeAttributes??
|
|
53
|
-
`)}};var ZT=`(
|
|
51
|
+
`})}return{systemInstruction:a.length>0&&!l?{parts:a}:void 0,contents:i}}function lh(t){return t.includes("/")?t:`models/${t}`}var wE=q(()=>H(Qn.object({error:Qn.object({code:Qn.number().nullable(),message:Qn.string(),status:Qn.string()})}))),ch=Qe({errorSchema:wE,errorToMessage:t=>t.error.message}),uh=q(()=>H(Le.object({responseModalities:Le.array(Le.enum(["TEXT","IMAGE"])).optional(),thinkingConfig:Le.object({thinkingBudget:Le.number().optional(),includeThoughts:Le.boolean().optional(),thinkingLevel:Le.enum(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:Le.string().optional(),structuredOutputs:Le.boolean().optional(),safetySettings:Le.array(Le.object({category:Le.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Le.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Le.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:Le.boolean().optional(),labels:Le.record(Le.string(),Le.string()).optional(),mediaResolution:Le.enum(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:Le.object({aspectRatio:Le.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"]).optional(),imageSize:Le.enum(["1K","2K","4K"]).optional()}).optional(),retrievalConfig:Le.object({latLng:Le.object({latitude:Le.number(),longitude:Le.number()}).optional()}).optional()})));function EE({tools:t,toolChoice:e,modelId:r}){var n;t=t?.length?t:void 0;let o=[],a=["gemini-flash-latest","gemini-flash-lite-latest","gemini-pro-latest"].some(y=>y===r),i=r.includes("gemini-2")||r.includes("gemini-3")||a,s=r.includes("gemini-1.5-flash")&&!r.includes("-8b"),l=r.includes("gemini-2.5")||r.includes("gemini-3");if(t==null)return{tools:void 0,toolConfig:void 0,toolWarnings:o};let c=t.some(y=>y.type==="function"),p=t.some(y=>y.type==="provider");if(c&&p&&o.push({type:"unsupported",feature:"combination of function and provider-defined tools"}),p){let y=[];return t.filter(f=>f.type==="provider").forEach(f=>{switch(f.id){case"google.google_search":i?y.push({googleSearch:{}}):s?y.push({googleSearchRetrieval:{dynamicRetrievalConfig:{mode:f.args.mode,dynamicThreshold:f.args.dynamicThreshold}}}):y.push({googleSearchRetrieval:{}});break;case"google.enterprise_web_search":i?y.push({enterpriseWebSearch:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":i?y.push({urlContext:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":i?y.push({codeExecution:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":l?y.push({fileSearch:{...f.args}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":i?y.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:f.args.ragCorpus},similarity_top_k:f.args.topK}}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":i?y.push({googleMaps:{}}):o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:o.push({type:"unsupported",feature:`provider-defined tool ${f.id}`});break}}),{tools:y.length>0?y:void 0,toolConfig:void 0,toolWarnings:o}}let h=[];for(let y of t)switch(y.type){case"function":h.push({name:y.name,description:(n=y.description)!=null?n:"",parameters:or(y.inputSchema)});break;default:o.push({type:"unsupported",feature:`function tool ${y.name}`});break}if(e==null)return{tools:[{functionDeclarations:h}],toolConfig:void 0,toolWarnings:o};let g=e.type;switch(g){case"auto":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:o};case"none":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:o};case"required":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:o};case"tool":return{tools:[{functionDeclarations:h}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[e.toolName]}},toolWarnings:o};default:{let y=g;throw new tt({functionality:`tool choice type: ${y}`})}}}function dh({finishReason:t,hasToolCalls:e}){switch(t){case"STOP":return e?"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";case"FINISH_REASON_UNSPECIFIED":case"OTHER":default:return"other"}}var hh=class{constructor(t,e){this.specificationVersion="v3";var r;this.modelId=t,this.config=e,this.generateId=(r=e.generateId)!=null?r:xt}get provider(){return this.config.provider}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:o,frequencyPenalty:a,presencePenalty:i,stopSequences:s,responseFormat:l,seed:c,tools:p,toolChoice:h,providerOptions:g}){var y;let S=[],f=this.config.provider.includes("vertex")?"vertex":"google",b=await Ve({provider:f,providerOptions:g,schema:uh});b==null&&f!=="google"&&(b=await Ve({provider:"google",providerOptions:g,schema:uh})),p?.some(O=>O.type==="provider"&&O.id==="google.vertex_rag_store")&&!this.config.provider.startsWith("google.vertex.")&&S.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}).`});let _=this.modelId.toLowerCase().startsWith("gemma-"),{contents:M,systemInstruction:B}=_E(t,{isGemmaModel:_,providerOptionsName:f}),{tools:Z,toolConfig:N,toolWarnings:R}=EE({tools:p,toolChoice:h,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:e,temperature:r,topK:o,topP:n,frequencyPenalty:a,presencePenalty:i,stopSequences:s,seed:c,responseMimeType:l?.type==="json"?"application/json":void 0,responseSchema:l?.type==="json"&&l.schema!=null&&((y=b?.structuredOutputs)==null||y)?or(l.schema):void 0,...b?.audioTimestamp&&{audioTimestamp:b.audioTimestamp},responseModalities:b?.responseModalities,thinkingConfig:b?.thinkingConfig,...b?.mediaResolution&&{mediaResolution:b.mediaResolution},...b?.imageConfig&&{imageConfig:b.imageConfig}},contents:M,systemInstruction:_?void 0:B,safetySettings:b?.safetySettings,tools:Z,toolConfig:b?.retrievalConfig?{...N,retrievalConfig:b.retrievalConfig}:N,cachedContent:b?.cachedContent,labels:b?.labels},warnings:[...S,...R],providerOptionsName:f}}async doGenerate(t){var e,r,n,o,a,i,s,l,c;let{args:p,warnings:h,providerOptionsName:g}=await this.getArgs(t),y=Ge(await Te(this.config.headers),t.headers),{responseHeaders:S,value:f,rawValue:b}=await Ue({url:`${this.config.baseURL}/${lh(this.modelId)}:generateContent`,headers:y,body:p,failedResponseHandler:ch,successfulResponseHandler:qe(xE),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=f.candidates[0],M=[],B=(r=(e=_.content)==null?void 0:e.parts)!=null?r:[],Z=f.usageMetadata,N;for(let O of B)if("executableCode"in O&&((n=O.executableCode)!=null&&n.code)){let ee=this.config.generateId();N=ee,M.push({type:"tool-call",toolCallId:ee,toolName:"code_execution",input:JSON.stringify(O.executableCode),providerExecuted:!0})}else"codeExecutionResult"in O&&O.codeExecutionResult?(M.push({type:"tool-result",toolCallId:N,toolName:"code_execution",result:{outcome:O.codeExecutionResult.outcome,output:O.codeExecutionResult.output}}),N=void 0):"text"in O&&O.text!=null&&O.text.length>0?M.push({type:O.thought===!0?"reasoning":"text",text:O.text,providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0}):"functionCall"in O?M.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:O.functionCall.name,input:JSON.stringify(O.functionCall.args),providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0}):"inlineData"in O&&M.push({type:"file",data:O.inlineData.data,mediaType:O.inlineData.mimeType,providerMetadata:O.thoughtSignature?{[g]:{thoughtSignature:O.thoughtSignature}}:void 0});let R=(o=ph({groundingMetadata:_.groundingMetadata,generateId:this.config.generateId}))!=null?o:[];for(let O of R)M.push(O);return{content:M,finishReason:{unified:dh({finishReason:_.finishReason,hasToolCalls:M.some(O=>O.type==="tool-call"&&!O.providerExecuted)}),raw:(a=_.finishReason)!=null?a:void 0},usage:sh(Z),warnings:h,providerMetadata:{[g]:{promptFeedback:(i=f.promptFeedback)!=null?i:null,groundingMetadata:(s=_.groundingMetadata)!=null?s:null,urlContextMetadata:(l=_.urlContextMetadata)!=null?l:null,safetyRatings:(c=_.safetyRatings)!=null?c:null,usageMetadata:Z??null}},request:{body:p},response:{headers:S,body:b}}}async doStream(t){let{args:e,warnings:r,providerOptionsName:n}=await this.getArgs(t),o=Ge(await Te(this.config.headers),t.headers),{responseHeaders:a,value:i}=await Ue({url:`${this.config.baseURL}/${lh(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:e,failedResponseHandler:ch,successfulResponseHandler:Sr(SE),abortSignal:t.abortSignal,fetch:this.config.fetch}),s={unified:"other",raw:void 0},l,c,p=this.config.generateId,h=!1,g=null,y=null,S=0,f=new Set,b;return{stream:i.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:r})},transform(_,M){var B,Z,N,R,O,ee,E;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){M.enqueue({type:"error",error:_.error});return}let Q=_.value,X=Q.usageMetadata;X!=null&&(l=X);let W=(B=Q.candidates)==null?void 0:B[0];if(W==null)return;let ue=W.content,V=ph({groundingMetadata:W.groundingMetadata,generateId:p});if(V!=null)for(let K of V)K.sourceType==="url"&&!f.has(K.url)&&(f.add(K.url),M.enqueue(K));if(ue!=null){let K=(Z=ue.parts)!=null?Z:[];for(let j of K)if("executableCode"in j&&((N=j.executableCode)!=null&&N.code)){let ve=p();b=ve,M.enqueue({type:"tool-call",toolCallId:ve,toolName:"code_execution",input:JSON.stringify(j.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in j&&j.codeExecutionResult){let ve=b;ve&&(M.enqueue({type:"tool-result",toolCallId:ve,toolName:"code_execution",result:{outcome:j.codeExecutionResult.outcome,output:j.codeExecutionResult.output}}),b=void 0)}else"text"in j&&j.text!=null&&j.text.length>0?j.thought===!0?(g!==null&&(M.enqueue({type:"text-end",id:g}),g=null),y===null&&(y=String(S++),M.enqueue({type:"reasoning-start",id:y,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),M.enqueue({type:"reasoning-delta",id:y,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):(y!==null&&(M.enqueue({type:"reasoning-end",id:y}),y=null),g===null&&(g=String(S++),M.enqueue({type:"text-start",id:g,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})),M.enqueue({type:"text-delta",id:g,delta:j.text,providerMetadata:j.thoughtSignature?{[n]:{thoughtSignature:j.thoughtSignature}}:void 0})):"inlineData"in j&&M.enqueue({type:"file",mediaType:j.inlineData.mimeType,data:j.inlineData.data});let me=TE({parts:ue.parts,generateId:p,providerOptionsName:n});if(me!=null)for(let j of me)M.enqueue({type:"tool-input-start",id:j.toolCallId,toolName:j.toolName,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-input-delta",id:j.toolCallId,delta:j.args,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-input-end",id:j.toolCallId,providerMetadata:j.providerMetadata}),M.enqueue({type:"tool-call",toolCallId:j.toolCallId,toolName:j.toolName,input:j.args,providerMetadata:j.providerMetadata}),h=!0}W.finishReason!=null&&(s={unified:dh({finishReason:W.finishReason,hasToolCalls:h}),raw:W.finishReason},c={[n]:{promptFeedback:(R=Q.promptFeedback)!=null?R:null,groundingMetadata:(O=W.groundingMetadata)!=null?O:null,urlContextMetadata:(ee=W.urlContextMetadata)!=null?ee:null,safetyRatings:(E=W.safetyRatings)!=null?E:null}},X!=null&&(c[n].usageMetadata=X))},flush(_){g!==null&&_.enqueue({type:"text-end",id:g}),y!==null&&_.enqueue({type:"reasoning-end",id:y}),_.enqueue({type:"finish",finishReason:s,usage:sh(l),providerMetadata:c})}})),response:{headers:a},request:{body:e}}}};function TE({parts:t,generateId:e,providerOptionsName:r}){let n=t?.filter(o=>"functionCall"in o);return n==null||n.length===0?void 0:n.map(o=>({type:"tool-call",toolCallId:e(),toolName:o.functionCall.name,args:JSON.stringify(o.functionCall.args),providerMetadata:o.thoughtSignature?{[r]:{thoughtSignature:o.thoughtSignature}}:void 0}))}function ph({groundingMetadata:t,generateId:e}){var r,n,o,a,i;if(!t?.groundingChunks)return;let s=[];for(let l of t.groundingChunks)if(l.web!=null)s.push({type:"source",sourceType:"url",id:e(),url:l.web.uri,title:(r=l.web.title)!=null?r:void 0});else if(l.retrievedContext!=null){let c=l.retrievedContext.uri,p=l.retrievedContext.fileSearchStore;if(c&&(c.startsWith("http://")||c.startsWith("https://")))s.push({type:"source",sourceType:"url",id:e(),url:c,title:(n=l.retrievedContext.title)!=null?n:void 0});else if(c){let h=(o=l.retrievedContext.title)!=null?o:"Unknown Document",g="application/octet-stream",y;c.endsWith(".pdf")?(g="application/pdf",y=c.split("/").pop()):c.endsWith(".txt")?(g="text/plain",y=c.split("/").pop()):c.endsWith(".docx")?(g="application/vnd.openxmlformats-officedocument.wordprocessingml.document",y=c.split("/").pop()):c.endsWith(".doc")?(g="application/msword",y=c.split("/").pop()):(c.match(/\.(md|markdown)$/)&&(g="text/markdown"),y=c.split("/").pop()),s.push({type:"source",sourceType:"document",id:e(),mediaType:g,title:h,filename:y})}else if(p){let h=(a=l.retrievedContext.title)!=null?a:"Unknown Document";s.push({type:"source",sourceType:"document",id:e(),mediaType:"application/octet-stream",title:h,filename:p.split("/").pop()})}}else l.maps!=null&&l.maps.uri&&s.push({type:"source",sourceType:"url",id:e(),url:l.maps.uri,title:(i=l.maps.title)!=null?i:void 0});return s.length>0?s:void 0}var fh=()=>G.object({webSearchQueries:G.array(G.string()).nullish(),retrievalQueries:G.array(G.string()).nullish(),searchEntryPoint:G.object({renderedContent:G.string()}).nullish(),groundingChunks:G.array(G.object({web:G.object({uri:G.string(),title:G.string().nullish()}).nullish(),retrievedContext:G.object({uri:G.string().nullish(),title:G.string().nullish(),text:G.string().nullish(),fileSearchStore:G.string().nullish()}).nullish(),maps:G.object({uri:G.string().nullish(),title:G.string().nullish(),text:G.string().nullish(),placeId:G.string().nullish()}).nullish()})).nullish(),groundingSupports:G.array(G.object({segment:G.object({startIndex:G.number().nullish(),endIndex:G.number().nullish(),text:G.string().nullish()}),segment_text:G.string().nullish(),groundingChunkIndices:G.array(G.number()).nullish(),supportChunkIndices:G.array(G.number()).nullish(),confidenceScores:G.array(G.number()).nullish(),confidenceScore:G.array(G.number()).nullish()})).nullish(),retrievalMetadata:G.union([G.object({webDynamicRetrievalScore:G.number()}),G.object({})]).nullish()}),mh=()=>G.object({parts:G.array(G.union([G.object({functionCall:G.object({name:G.string(),args:G.unknown()}),thoughtSignature:G.string().nullish()}),G.object({inlineData:G.object({mimeType:G.string(),data:G.string()}),thoughtSignature:G.string().nullish()}),G.object({executableCode:G.object({language:G.string(),code:G.string()}).nullish(),codeExecutionResult:G.object({outcome:G.string(),output:G.string()}).nullish(),text:G.string().nullish(),thought:G.boolean().nullish(),thoughtSignature:G.string().nullish()})])).nullish()}),Ea=()=>G.object({category:G.string().nullish(),probability:G.string().nullish(),probabilityScore:G.number().nullish(),severity:G.string().nullish(),severityScore:G.number().nullish(),blocked:G.boolean().nullish()}),gh=G.object({cachedContentTokenCount:G.number().nullish(),thoughtsTokenCount:G.number().nullish(),promptTokenCount:G.number().nullish(),candidatesTokenCount:G.number().nullish(),totalTokenCount:G.number().nullish(),trafficType:G.string().nullish()}),yh=()=>G.object({urlMetadata:G.array(G.object({retrievedUrl:G.string(),urlRetrievalStatus:G.string()}))}),xE=q(()=>H(G.object({candidates:G.array(G.object({content:mh().nullish().or(G.object({}).strict()),finishReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish(),groundingMetadata:fh().nullish(),urlContextMetadata:yh().nullish()})),usageMetadata:gh.nullish(),promptFeedback:G.object({blockReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish()}).nullish()}))),SE=q(()=>H(G.object({candidates:G.array(G.object({content:mh().nullish(),finishReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish(),groundingMetadata:fh().nullish(),urlContextMetadata:yh().nullish()})).nullish(),usageMetadata:gh.nullish(),promptFeedback:G.object({blockReason:G.string().nullish(),safetyRatings:G.array(Ea()).nullish()}).nullish()}))),CE=Ze({id:"google.code_execution",inputSchema:yn.object({language:yn.string().describe("The programming language of the code."),code:yn.string().describe("The code to be executed.")}),outputSchema:yn.object({outcome:yn.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:yn.string().describe("The output from the code execution.")})}),AE=Ee({id:"google.enterprise_web_search",inputSchema:q(()=>H(IE.object({})))}),kE=eo.object({fileSearchStoreNames:eo.array(eo.string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:eo.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:eo.string().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(),RE=q(()=>H(kE)),OE=Ee({id:"google.file_search",inputSchema:RE}),ME=Ee({id:"google.google_maps",inputSchema:q(()=>H(NE.object({})))}),PE=Ee({id:"google.google_search",inputSchema:q(()=>H(Xs.object({mode:Xs.enum(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:Xs.number().default(1)})))}),jE=Ee({id:"google.url_context",inputSchema:q(()=>H(DE.object({})))}),LE=Ee({id:"google.vertex_rag_store",inputSchema:Zs.object({ragCorpus:Zs.string(),topK:Zs.number().optional()})}),kr={googleSearch:PE,enterpriseWebSearch:AE,googleMaps:ME,urlContext:jE,fileSearch:OE,codeExecution:CE,vertexRagStore:LE};import{z as Rr}from"zod/v4";import{z as to}from"zod/v4";import{z as ro}from"zod/v4";import{z as et}from"zod/v4";var Qs=null,vh=null;function FE(t){return(!Qs||t!==vh)&&(Qs=new Eh.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],...t}),vh=t),Qs}async function UE(t){let n=await(await FE(t||{}).getClient()).getAccessToken();return n?.token||null}var HE="4.0.15",qE=to.object({error:to.object({code:to.number().nullable(),message:to.string(),status:to.string()})}),Th=Qe({errorSchema:qE,errorToMessage:t=>t.error.message}),bh=ro.object({outputDimensionality:ro.number().optional(),taskType:ro.enum(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),title:ro.string().optional(),autoTruncate:ro.boolean().optional()}),$E=class{constructor(t,e){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){let o=await Ve({provider:"vertex",providerOptions:n,schema:bh});if(o==null&&(o=await Ve({provider:"google",providerOptions:n,schema:bh})),o=o??{},t.length>this.maxEmbeddingsPerCall)throw new fo({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let a=Ge(await Te(this.config.headers),e),i=`${this.config.baseURL}/models/${this.modelId}:predict`,{responseHeaders:s,value:l,rawValue:c}=await Ue({url:i,headers:a,body:{instances:t.map(p=>({content:p,task_type:o.taskType,title:o.title})),parameters:{outputDimensionality:o.outputDimensionality,autoTruncate:o.autoTruncate}},failedResponseHandler:Th,successfulResponseHandler:qe(GE),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.predictions.map(p=>p.embeddings.values),usage:{tokens:l.predictions.reduce((p,h)=>p+h.embeddings.statistics.token_count,0)},response:{headers:s,body:c}}}},GE=Rr.object({predictions:Rr.array(Rr.object({embeddings:Rr.object({values:Rr.array(Rr.number()),statistics:Rr.object({token_count:Rr.number()})})}))}),BE=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxImagesPerCall=4}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:o,providerOptions:a,headers:i,abortSignal:s,files:l,mask:c}){var p,h,g,y,S,f,b;let _=[];r!=null&&_.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let M=await Ve({provider:"vertex",providerOptions:a,schema:zE}),{edit:B,...Z}=M??{},{mode:N,baseSteps:R,maskMode:O,maskDilation:ee}=B??{},E=l!=null&&l.length>0,Q;if(E){let V=[];for(let K=0;K<l.length;K++){let me=l[K];V.push({referenceType:"REFERENCE_TYPE_RAW",referenceId:K+1,referenceImage:{bytesBase64Encoded:_h(me)}})}c!=null&&V.push({referenceType:"REFERENCE_TYPE_MASK",referenceId:l.length+1,referenceImage:{bytesBase64Encoded:_h(c)},maskImageConfig:{maskMode:O??"MASK_MODE_USER_PROVIDED",...ee!=null?{dilation:ee}:{}}}),Q={instances:[{prompt:t,referenceImages:V}],parameters:{sampleCount:e,...n!=null?{aspectRatio:n}:{},...o!=null?{seed:o}:{},editMode:N??"EDIT_MODE_INPAINT_INSERTION",...R!=null?{editConfig:{baseSteps:R}}:{},...Z}}}else Q={instances:[{prompt:t}],parameters:{sampleCount:e,...n!=null?{aspectRatio:n}:{},...o!=null?{seed:o}:{},...Z}};let X=(g=(h=(p=this.config._internal)==null?void 0:p.currentDate)==null?void 0:h.call(p))!=null?g:new Date,{value:W,responseHeaders:ue}=await Ue({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:Ge(await Te(this.config.headers),i),body:Q,failedResponseHandler:Th,successfulResponseHandler:qe(VE),abortSignal:s,fetch:this.config.fetch});return{images:(S=(y=W.predictions)==null?void 0:y.map(({bytesBase64Encoded:V})=>V))!=null?S:[],warnings:_,response:{timestamp:X,modelId:this.modelId,headers:ue},providerMetadata:{vertex:{images:(b=(f=W.predictions)==null?void 0:f.map(V=>{let{prompt:K}=V;return{...K!=null&&{revisedPrompt:K}}}))!=null?b:[]}}}}},VE=et.object({predictions:et.array(et.object({bytesBase64Encoded:et.string(),mimeType:et.string(),prompt:et.string().nullish()})).nullish()}),zE=et.object({negativePrompt:et.string().nullish(),personGeneration:et.enum(["dont_allow","allow_adult","allow_all"]).nullish(),safetySetting:et.enum(["block_low_and_above","block_medium_and_above","block_only_high","block_none"]).nullish(),addWatermark:et.boolean().nullish(),storageUri:et.string().nullish(),sampleImageSize:et.enum(["1K","2K"]).nullish(),edit:et.object({baseSteps:et.number().nullish(),mode:et.enum(["EDIT_MODE_INPAINT_INSERTION","EDIT_MODE_INPAINT_REMOVAL","EDIT_MODE_OUTPAINT","EDIT_MODE_CONTROLLED_EDITING","EDIT_MODE_PRODUCT_IMAGE","EDIT_MODE_BGSWAP"]).nullish(),maskMode:et.enum(["MASK_MODE_DEFAULT","MASK_MODE_USER_PROVIDED","MASK_MODE_DETECTION_BOX","MASK_MODE_CLOTHING_AREA","MASK_MODE_PARSED_PERSON"]).nullish(),maskDilation:et.number().nullish()}).nullish()});function _h(t){if(t.type==="url")throw new Error("URL-based images are not supported for Google Vertex image editing. Please provide the image data directly.");return typeof t.data=="string"?t.data:Jt(t.data)}var WE={googleSearch:kr.googleSearch,enterpriseWebSearch:kr.enterpriseWebSearch,googleMaps:kr.googleMaps,urlContext:kr.urlContext,fileSearch:kr.fileSearch,codeExecution:kr.codeExecution,vertexRagStore:kr.vertexRagStore},JE="https://aiplatform.googleapis.com/v1/publishers/google";function KE(t,e){return async(r,n)=>{let o=new URL(r.toString());return o.searchParams.set("key",t),(e??fetch)(o.toString(),n)}}function wh(t={}){let e=Lt({settingValue:t.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"}),r=()=>Wa({settingValue:t.project,settingName:"project",environmentVariableName:"GOOGLE_VERTEX_PROJECT",description:"Google Vertex project"}),n=()=>Wa({settingValue:t.location,settingName:"location",environmentVariableName:"GOOGLE_VERTEX_LOCATION",description:"Google Vertex location"}),o=()=>{var p,h;if(e)return(p=dr(t.baseURL))!=null?p:JE;let g=n(),y=r(),S=`${g==="global"?"":g+"-"}aiplatform.googleapis.com`;return(h=dr(t.baseURL))!=null?h:`https://${S}/v1beta1/projects/${y}/locations/${g}/publishers/google`},a=p=>{let h=async()=>{var g;let y=await Te((g=t.headers)!=null?g:{});return lt(y,`ai-sdk/google-vertex/${HE}`)};return{provider:`google.vertex.${p}`,headers:h,fetch:e?KE(e,t.fetch):t.fetch,baseURL:o()}},i=p=>{var h;return new hh(p,{...a("chat"),generateId:(h=t.generateId)!=null?h:xt,supportedUrls:()=>({"*":[/^https?:\/\/.*$/,/^gs:\/\/.*$/]})})},s=p=>new $E(p,a("embedding")),l=p=>new BE(p,a("image")),c=function(p){if(new.target)throw new Error("The Google Vertex AI model function cannot be called with the new keyword.");return i(p)};return c.specificationVersion="v3",c.languageModel=i,c.embeddingModel=s,c.textEmbeddingModel=s,c.image=l,c.imageModel=l,c.tools=WE,c}function el(t={}){return Lt({settingValue:t.apiKey,environmentVariableName:"GOOGLE_VERTEX_API_KEY"})?wh(t):wh({...t,headers:async()=>({Authorization:`Bearer ${await UE(t.googleAuthOptions)}`,...await Te(t.headers)})})}var Fk=el();var xh={MEDIA_RESOLUTION_HIGH:"MEDIA_RESOLUTION_HIGH",MEDIA_RESOLUTION_MEDIUM:"MEDIA_RESOLUTION_MEDIUM",MEDIA_RESOLUTION_LOW:"MEDIA_RESOLUTION_LOW"};function Sh(){let t=(Sn().env||{}).GOOGLE_GENAI_USE_VERTEXAI;return t==="True"||t==="true"}function Ch(t){let e=Sn().env||{};if(Sh()){let n=e.GOOGLE_CLOUD_PROJECT;if(!n)throw new Error("GOOGLE_CLOUD_PROJECT is required when using Vertex AI");let o=t==="gemini-3-flash-preview"?"global":e.GOOGLE_CLOUD_LOCATION;if(!o)throw new Error("GOOGLE_CLOUD_LOCATION is required when using Vertex AI");return ce.debug(`Using Vertex AI provider: model=${t}, location=${o}`),el({project:n,location:o})(t)}let r=e.GOOGLE_API_KEY;if(!r)throw new Error("Google API key is missing. Set GOOGLE_API_KEY in SDK config or environment.");return ce.debug(`Using Google AI provider (API key): model=${t}`),Za({apiKey:r})(t)}function Ih(t,e){let r={thinkingConfig:{thinkingBudget:512,includeThoughts:!0}},n={thinkingConfig:{thinkingLevel:"minimal",includeThoughts:!0},mediaResolution:xh.MEDIA_RESOLUTION_HIGH},o;switch(e){case"gemini-3-flash-preview":o={...n};break;default:o={...r},t===1&&(o.mediaResolution=xh.MEDIA_RESOLUTION_HIGH)}return Sh()?{vertex:o}:{google:o}}import{z as no}from"zod/v4";import{z as u}from"zod/v4";import{z as re}from"zod/v4";import{z as Vt}from"zod/v4";import{z as ze}from"zod/v4";import{z as Me}from"zod/v4";import{z as zt}from"zod/v4";import{z as ne}from"zod/v4";import{z as Br}from"zod/v4";import{z as ol}from"zod/v4";import{z as al}from"zod/v4";import{z as oo}from"zod/v4";import{z as Ot}from"zod/v4";import{z as De}from"zod/v4";import{z as yr}from"zod/v4";import{z as vr}from"zod/v4";import{z as br}from"zod/v4";import{z as Vr}from"zod/v4";var YE="3.0.13",XE=q(()=>H(no.object({type:no.literal("error"),error:no.object({type:no.string(),message:no.string()})}))),Ah=Qe({errorSchema:XE,errorToMessage:t=>t.error.message}),ZE=q(()=>H(u.object({type:u.literal("message"),id:u.string().nullish(),model:u.string().nullish(),content:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string(),citations:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("web_search_result_location"),cited_text:u.string(),url:u.string(),title:u.string(),encrypted_index:u.string()}),u.object({type:u.literal("page_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_page_number:u.number(),end_page_number:u.number()}),u.object({type:u.literal("char_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_char_index:u.number(),end_char_index:u.number()})])).optional()}),u.object({type:u.literal("thinking"),thinking:u.string(),signature:u.string()}),u.object({type:u.literal("redacted_thinking"),data:u.string()}),u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.unknown(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()}),u.object({type:u.literal("server_tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).nullish()}),u.object({type:u.literal("mcp_tool_use"),id:u.string(),name:u.string(),input:u.unknown(),server_name:u.string()}),u.object({type:u.literal("mcp_tool_result"),tool_use_id:u.string(),is_error:u.boolean(),content:u.array(u.union([u.string(),u.object({type:u.literal("text"),text:u.string()})]))}),u.object({type:u.literal("web_fetch_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("web_fetch_result"),url:u.string(),retrieved_at:u.string(),content:u.object({type:u.literal("document"),title:u.string().nullable(),citations:u.object({enabled:u.boolean()}).optional(),source:u.union([u.object({type:u.literal("base64"),media_type:u.literal("application/pdf"),data:u.string()}),u.object({type:u.literal("text"),media_type:u.literal("text/plain"),data:u.string()})])})}),u.object({type:u.literal("web_fetch_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("web_search_tool_result"),tool_use_id:u.string(),content:u.union([u.array(u.object({type:u.literal("web_search_result"),url:u.string(),title:u.string(),encrypted_content:u.string(),page_age:u.string().nullish()})),u.object({type:u.literal("web_search_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("code_execution_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("code_execution_result"),stdout:u.string(),stderr:u.string(),return_code:u.number(),content:u.array(u.object({type:u.literal("code_execution_output"),file_id:u.string()})).optional().default([])}),u.object({type:u.literal("code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("bash_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("bash_code_execution_result"),content:u.array(u.object({type:u.literal("bash_code_execution_output"),file_id:u.string()})),stdout:u.string(),stderr:u.string(),return_code:u.number()}),u.object({type:u.literal("bash_code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("text_editor_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("text_editor_code_execution_tool_result_error"),error_code:u.string()}),u.object({type:u.literal("text_editor_code_execution_view_result"),content:u.string(),file_type:u.string(),num_lines:u.number().nullable(),start_line:u.number().nullable(),total_lines:u.number().nullable()}),u.object({type:u.literal("text_editor_code_execution_create_result"),is_file_update:u.boolean()}),u.object({type:u.literal("text_editor_code_execution_str_replace_result"),lines:u.array(u.string()).nullable(),new_lines:u.number().nullable(),new_start:u.number().nullable(),old_lines:u.number().nullable(),old_start:u.number().nullable()})])}),u.object({type:u.literal("tool_search_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("tool_search_tool_search_result"),tool_references:u.array(u.object({type:u.literal("tool_reference"),tool_name:u.string()}))}),u.object({type:u.literal("tool_search_tool_result_error"),error_code:u.string()})])})])),stop_reason:u.string().nullish(),stop_sequence:u.string().nullish(),usage:u.looseObject({input_tokens:u.number(),output_tokens:u.number(),cache_creation_input_tokens:u.number().nullish(),cache_read_input_tokens:u.number().nullish()}),container:u.object({expires_at:u.string(),id:u.string(),skills:u.array(u.object({type:u.union([u.literal("anthropic"),u.literal("custom")]),skill_id:u.string(),version:u.string()})).nullish()}).nullish(),context_management:u.object({applied_edits:u.array(u.union([u.object({type:u.literal("clear_tool_uses_20250919"),cleared_tool_uses:u.number(),cleared_input_tokens:u.number()}),u.object({type:u.literal("clear_thinking_20251015"),cleared_thinking_turns:u.number(),cleared_input_tokens:u.number()})]))}).nullish()}))),QE=q(()=>H(u.discriminatedUnion("type",[u.object({type:u.literal("message_start"),message:u.object({id:u.string().nullish(),model:u.string().nullish(),role:u.string().nullish(),usage:u.looseObject({input_tokens:u.number(),cache_creation_input_tokens:u.number().nullish(),cache_read_input_tokens:u.number().nullish()}),content:u.array(u.discriminatedUnion("type",[u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.unknown(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()})])).nullish(),stop_reason:u.string().nullish(),container:u.object({expires_at:u.string(),id:u.string()}).nullish()})}),u.object({type:u.literal("content_block_start"),index:u.number(),content_block:u.discriminatedUnion("type",[u.object({type:u.literal("text"),text:u.string()}),u.object({type:u.literal("thinking"),thinking:u.string()}),u.object({type:u.literal("tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).optional(),caller:u.union([u.object({type:u.literal("code_execution_20250825"),tool_id:u.string()}),u.object({type:u.literal("direct")})]).optional()}),u.object({type:u.literal("redacted_thinking"),data:u.string()}),u.object({type:u.literal("server_tool_use"),id:u.string(),name:u.string(),input:u.record(u.string(),u.unknown()).nullish()}),u.object({type:u.literal("mcp_tool_use"),id:u.string(),name:u.string(),input:u.unknown(),server_name:u.string()}),u.object({type:u.literal("mcp_tool_result"),tool_use_id:u.string(),is_error:u.boolean(),content:u.array(u.union([u.string(),u.object({type:u.literal("text"),text:u.string()})]))}),u.object({type:u.literal("web_fetch_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("web_fetch_result"),url:u.string(),retrieved_at:u.string(),content:u.object({type:u.literal("document"),title:u.string().nullable(),citations:u.object({enabled:u.boolean()}).optional(),source:u.union([u.object({type:u.literal("base64"),media_type:u.literal("application/pdf"),data:u.string()}),u.object({type:u.literal("text"),media_type:u.literal("text/plain"),data:u.string()})])})}),u.object({type:u.literal("web_fetch_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("web_search_tool_result"),tool_use_id:u.string(),content:u.union([u.array(u.object({type:u.literal("web_search_result"),url:u.string(),title:u.string(),encrypted_content:u.string(),page_age:u.string().nullish()})),u.object({type:u.literal("web_search_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("code_execution_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("code_execution_result"),stdout:u.string(),stderr:u.string(),return_code:u.number(),content:u.array(u.object({type:u.literal("code_execution_output"),file_id:u.string()})).optional().default([])}),u.object({type:u.literal("code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("bash_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("bash_code_execution_result"),content:u.array(u.object({type:u.literal("bash_code_execution_output"),file_id:u.string()})),stdout:u.string(),stderr:u.string(),return_code:u.number()}),u.object({type:u.literal("bash_code_execution_tool_result_error"),error_code:u.string()})])}),u.object({type:u.literal("text_editor_code_execution_tool_result"),tool_use_id:u.string(),content:u.discriminatedUnion("type",[u.object({type:u.literal("text_editor_code_execution_tool_result_error"),error_code:u.string()}),u.object({type:u.literal("text_editor_code_execution_view_result"),content:u.string(),file_type:u.string(),num_lines:u.number().nullable(),start_line:u.number().nullable(),total_lines:u.number().nullable()}),u.object({type:u.literal("text_editor_code_execution_create_result"),is_file_update:u.boolean()}),u.object({type:u.literal("text_editor_code_execution_str_replace_result"),lines:u.array(u.string()).nullable(),new_lines:u.number().nullable(),new_start:u.number().nullable(),old_lines:u.number().nullable(),old_start:u.number().nullable()})])}),u.object({type:u.literal("tool_search_tool_result"),tool_use_id:u.string(),content:u.union([u.object({type:u.literal("tool_search_tool_search_result"),tool_references:u.array(u.object({type:u.literal("tool_reference"),tool_name:u.string()}))}),u.object({type:u.literal("tool_search_tool_result_error"),error_code:u.string()})])})])}),u.object({type:u.literal("content_block_delta"),index:u.number(),delta:u.discriminatedUnion("type",[u.object({type:u.literal("input_json_delta"),partial_json:u.string()}),u.object({type:u.literal("text_delta"),text:u.string()}),u.object({type:u.literal("thinking_delta"),thinking:u.string()}),u.object({type:u.literal("signature_delta"),signature:u.string()}),u.object({type:u.literal("citations_delta"),citation:u.discriminatedUnion("type",[u.object({type:u.literal("web_search_result_location"),cited_text:u.string(),url:u.string(),title:u.string(),encrypted_index:u.string()}),u.object({type:u.literal("page_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_page_number:u.number(),end_page_number:u.number()}),u.object({type:u.literal("char_location"),cited_text:u.string(),document_index:u.number(),document_title:u.string().nullable(),start_char_index:u.number(),end_char_index:u.number()})])})])}),u.object({type:u.literal("content_block_stop"),index:u.number()}),u.object({type:u.literal("error"),error:u.object({type:u.string(),message:u.string()})}),u.object({type:u.literal("message_delta"),delta:u.object({stop_reason:u.string().nullish(),stop_sequence:u.string().nullish(),container:u.object({expires_at:u.string(),id:u.string(),skills:u.array(u.object({type:u.union([u.literal("anthropic"),u.literal("custom")]),skill_id:u.string(),version:u.string()})).nullish()}).nullish(),context_management:u.object({applied_edits:u.array(u.union([u.object({type:u.literal("clear_tool_uses_20250919"),cleared_tool_uses:u.number(),cleared_input_tokens:u.number()}),u.object({type:u.literal("clear_thinking_20251015"),cleared_thinking_turns:u.number(),cleared_input_tokens:u.number()})]))}).nullish()}),usage:u.looseObject({input_tokens:u.number().nullish(),output_tokens:u.number(),cache_creation_input_tokens:u.number().nullish()})}),u.object({type:u.literal("message_stop")}),u.object({type:u.literal("ping")})]))),eT=q(()=>H(u.object({signature:u.string().optional(),redactedData:u.string().optional()}))),kh=re.object({citations:re.object({enabled:re.boolean()}).optional(),title:re.string().optional(),context:re.string().optional()}),tT=re.object({sendReasoning:re.boolean().optional(),structuredOutputMode:re.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:re.object({type:re.union([re.literal("enabled"),re.literal("disabled")]),budgetTokens:re.number().optional()}).optional(),disableParallelToolUse:re.boolean().optional(),cacheControl:re.object({type:re.literal("ephemeral"),ttl:re.union([re.literal("5m"),re.literal("1h")]).optional()}).optional(),mcpServers:re.array(re.object({type:re.literal("url"),name:re.string(),url:re.string(),authorizationToken:re.string().nullish(),toolConfiguration:re.object({enabled:re.boolean().nullish(),allowedTools:re.array(re.string()).nullish()}).nullish()})).optional(),container:re.object({id:re.string().optional(),skills:re.array(re.object({type:re.union([re.literal("anthropic"),re.literal("custom")]),skillId:re.string(),version:re.string().optional()})).optional()}).optional(),toolStreaming:re.boolean().optional(),effort:re.enum(["low","medium","high"]).optional(),contextManagement:re.object({edits:re.array(re.discriminatedUnion("type",[re.object({type:re.literal("clear_tool_uses_20250919"),trigger:re.discriminatedUnion("type",[re.object({type:re.literal("input_tokens"),value:re.number()}),re.object({type:re.literal("tool_uses"),value:re.number()})]).optional(),keep:re.object({type:re.literal("tool_uses"),value:re.number()}).optional(),clearAtLeast:re.object({type:re.literal("input_tokens"),value:re.number()}).optional(),clearToolInputs:re.boolean().optional(),excludeTools:re.array(re.string()).optional()}),re.object({type:re.literal("clear_thinking_20251015"),keep:re.union([re.literal("all"),re.object({type:re.literal("thinking_turns"),value:re.number()})]).optional()})]))}).optional()}),Rh=4;function rT(t){var e;let r=t?.anthropic;return(e=r?.cacheControl)!=null?e:r?.cache_control}var il=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(t,e){let r=rT(t);if(r){if(!e.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${e.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>Rh){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${Rh} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return r}}getWarnings(){return this.warnings}},nT=q(()=>H(Vt.object({maxCharacters:Vt.number().optional()}))),oT=q(()=>H(Vt.object({command:Vt.enum(["view","create","str_replace","insert"]),path:Vt.string(),file_text:Vt.string().optional(),insert_line:Vt.number().int().optional(),new_str:Vt.string().optional(),old_str:Vt.string().optional(),view_range:Vt.array(Vt.number().int()).optional()}))),aT=Ee({id:"anthropic.text_editor_20250728",inputSchema:oT}),iT=(t={})=>aT(t),sT=q(()=>H(ze.object({maxUses:ze.number().optional(),allowedDomains:ze.array(ze.string()).optional(),blockedDomains:ze.array(ze.string()).optional(),userLocation:ze.object({type:ze.literal("approximate"),city:ze.string().optional(),region:ze.string().optional(),country:ze.string().optional(),timezone:ze.string().optional()}).optional()}))),Ph=q(()=>H(ze.array(ze.object({url:ze.string(),title:ze.string().nullable(),pageAge:ze.string().nullable(),encryptedContent:ze.string(),type:ze.literal("web_search_result")})))),lT=q(()=>H(ze.object({query:ze.string()}))),cT=Ze({id:"anthropic.web_search_20250305",inputSchema:lT,outputSchema:Ph,supportsDeferredResults:!0}),uT=(t={})=>cT(t),dT=q(()=>H(Me.object({maxUses:Me.number().optional(),allowedDomains:Me.array(Me.string()).optional(),blockedDomains:Me.array(Me.string()).optional(),citations:Me.object({enabled:Me.boolean()}).optional(),maxContentTokens:Me.number().optional()}))),Dh=q(()=>H(Me.object({type:Me.literal("web_fetch_result"),url:Me.string(),content:Me.object({type:Me.literal("document"),title:Me.string().nullable(),citations:Me.object({enabled:Me.boolean()}).optional(),source:Me.union([Me.object({type:Me.literal("base64"),mediaType:Me.literal("application/pdf"),data:Me.string()}),Me.object({type:Me.literal("text"),mediaType:Me.literal("text/plain"),data:Me.string()})])}),retrievedAt:Me.string().nullable()}))),pT=q(()=>H(Me.object({url:Me.string()}))),hT=Ze({id:"anthropic.web_fetch_20250910",inputSchema:pT,outputSchema:Dh,supportsDeferredResults:!0}),fT=(t={})=>hT(t);async function mT({tools:t,toolChoice:e,disableParallelToolUse:r,cacheControlValidator:n,supportsStructuredOutput:o}){var a;t=t?.length?t:void 0;let i=[],s=new Set,l=n||new il;if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:s};let c=[];for(let h of t)switch(h.type){case"function":{let g=l.getCacheControl(h.providerOptions,{type:"tool definition",canCache:!0}),y=(a=h.providerOptions)==null?void 0:a.anthropic,S=y?.deferLoading,f=y?.allowedCallers;c.push({name:h.name,description:h.description,input_schema:h.inputSchema,cache_control:g,...o===!0&&h.strict!=null?{strict:h.strict}:{},...S!=null?{defer_loading:S}:{},...f!=null?{allowed_callers:f}:{},...h.inputExamples!=null?{input_examples:h.inputExamples.map(b=>b.input)}:{}}),o===!0&&s.add("structured-outputs-2025-11-13"),(h.inputExamples!=null||f!=null)&&s.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(h.id){case"anthropic.code_execution_20250522":{s.add("code-execution-2025-05-22"),c.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{s.add("code-execution-2025-08-25"),c.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.computer_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"computer",type:"computer_20250124",display_width_px:h.args.displayWidthPx,display_height_px:h.args.displayHeightPx,display_number:h.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"computer",type:"computer_20241022",display_width_px:h.args.displayWidthPx,display_height_px:h.args.displayHeightPx,display_number:h.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{s.add("computer-use-2025-01-24"),c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let g=await St({value:h.args,schema:nT});c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:g.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{s.add("computer-use-2025-01-24"),c.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{s.add("computer-use-2024-10-22"),c.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{s.add("context-management-2025-06-27"),c.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{s.add("web-fetch-2025-09-10");let g=await St({value:h.args,schema:dT});c.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:g.maxUses,allowed_domains:g.allowedDomains,blocked_domains:g.blockedDomains,citations:g.citations,max_content_tokens:g.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let g=await St({value:h.args,schema:sT});c.push({type:"web_search_20250305",name:"web_search",max_uses:g.maxUses,allowed_domains:g.allowedDomains,blocked_domains:g.blockedDomains,user_location:g.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{s.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{s.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}default:{i.push({type:"unsupported",feature:`provider-defined tool ${h.id}`});break}}break}default:{i.push({type:"unsupported",feature:`tool ${h}`});break}}if(e==null)return{tools:c,toolChoice:r?{type:"auto",disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:s};let p=e.type;switch(p){case"auto":return{tools:c,toolChoice:{type:"auto",disable_parallel_tool_use:r},toolWarnings:i,betas:s};case"required":return{tools:c,toolChoice:{type:"any",disable_parallel_tool_use:r},toolWarnings:i,betas:s};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:s};case"tool":return{tools:c,toolChoice:{type:"tool",name:e.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:s};default:{let h=p;throw new tt({functionality:`tool choice type: ${h}`})}}}function Oh(t){var e,r;let n=t.input_tokens,o=t.output_tokens,a=(e=t.cache_creation_input_tokens)!=null?e:0,i=(r=t.cache_read_input_tokens)!=null?r:0;return{inputTokens:{total:n+a+i,noCache:n,cacheRead:i,cacheWrite:a},outputTokens:{total:o,text:void 0,reasoning:void 0},raw:t}}var jh=q(()=>H(zt.object({type:zt.literal("code_execution_result"),stdout:zt.string(),stderr:zt.string(),return_code:zt.number(),content:zt.array(zt.object({type:zt.literal("code_execution_output"),file_id:zt.string()})).optional().default([])}))),gT=q(()=>H(zt.object({code:zt.string()}))),yT=Ze({id:"anthropic.code_execution_20250522",inputSchema:gT,outputSchema:jh}),vT=(t={})=>yT(t),Lh=q(()=>H(ne.discriminatedUnion("type",[ne.object({type:ne.literal("code_execution_result"),stdout:ne.string(),stderr:ne.string(),return_code:ne.number(),content:ne.array(ne.object({type:ne.literal("code_execution_output"),file_id:ne.string()})).optional().default([])}),ne.object({type:ne.literal("bash_code_execution_result"),content:ne.array(ne.object({type:ne.literal("bash_code_execution_output"),file_id:ne.string()})),stdout:ne.string(),stderr:ne.string(),return_code:ne.number()}),ne.object({type:ne.literal("bash_code_execution_tool_result_error"),error_code:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution_tool_result_error"),error_code:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution_view_result"),content:ne.string(),file_type:ne.string(),num_lines:ne.number().nullable(),start_line:ne.number().nullable(),total_lines:ne.number().nullable()}),ne.object({type:ne.literal("text_editor_code_execution_create_result"),is_file_update:ne.boolean()}),ne.object({type:ne.literal("text_editor_code_execution_str_replace_result"),lines:ne.array(ne.string()).nullable(),new_lines:ne.number().nullable(),new_start:ne.number().nullable(),old_lines:ne.number().nullable(),old_start:ne.number().nullable()})]))),bT=q(()=>H(ne.discriminatedUnion("type",[ne.object({type:ne.literal("programmatic-tool-call"),code:ne.string()}),ne.object({type:ne.literal("bash_code_execution"),command:ne.string()}),ne.discriminatedUnion("command",[ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("view"),path:ne.string()}),ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("create"),path:ne.string(),file_text:ne.string().nullish()}),ne.object({type:ne.literal("text_editor_code_execution"),command:ne.literal("str_replace"),path:ne.string(),old_str:ne.string(),new_str:ne.string()})])]))),_T=Ze({id:"anthropic.code_execution_20250825",inputSchema:bT,outputSchema:Lh,supportsDeferredResults:!0}),wT=(t={})=>_T(t),Fh=q(()=>H(Br.array(Br.object({type:Br.literal("tool_reference"),toolName:Br.string()})))),ET=q(()=>H(Br.object({pattern:Br.string(),limit:Br.number().optional()}))),TT=Ze({id:"anthropic.tool_search_regex_20251119",inputSchema:ET,outputSchema:Fh}),xT=(t={})=>TT(t);function ST(t){if(typeof t=="string")return Buffer.from(t,"base64").toString("utf-8");if(t instanceof Uint8Array)return new TextDecoder().decode(t);throw t instanceof URL?new tt({functionality:"URL-based text documents are not supported for citations"}):new tt({functionality:`unsupported data type for text documents: ${typeof t}`})}function tl(t){return t instanceof URL||CT(t)}function CT(t){return typeof t=="string"&&/^https?:\/\//i.test(t)}function rl(t){return t instanceof URL?t.toString():t}async function IT({prompt:t,sendReasoning:e,warnings:r,cacheControlValidator:n,toolNameMapping:o}){var a,i,s,l,c,p,h,g,y,S,f,b,_,M,B;let Z=new Set,N=AT(t),R=n||new il,O,ee=[];async function E(X){var W,ue;let V=await Ve({provider:"anthropic",providerOptions:X,schema:kh});return(ue=(W=V?.citations)==null?void 0:W.enabled)!=null?ue:!1}async function Q(X){let W=await Ve({provider:"anthropic",providerOptions:X,schema:kh});return{title:W?.title,context:W?.context}}for(let X=0;X<N.length;X++){let W=N[X],ue=X===N.length-1,V=W.type;switch(V){case"system":{if(O!=null)throw new tt({functionality:"Multiple system messages that are separated by user/assistant messages"});O=W.messages.map(({content:K,providerOptions:me})=>({type:"text",text:K,cache_control:R.getCacheControl(me,{type:"system message",canCache:!0})}));break}case"user":{let K=[];for(let me of W.messages){let{role:j,content:ve}=me;switch(j){case"user":{for(let Se=0;Se<ve.length;Se++){let fe=ve[Se],Fe=Se===ve.length-1,z=(a=R.getCacheControl(fe.providerOptions,{type:"user message part",canCache:!0}))!=null?a:Fe?R.getCacheControl(me.providerOptions,{type:"user message",canCache:!0}):void 0;switch(fe.type){case"text":{K.push({type:"text",text:fe.text,cache_control:z});break}case"file":{if(fe.mediaType.startsWith("image/"))K.push({type:"image",source:tl(fe.data)?{type:"url",url:rl(fe.data)}:{type:"base64",media_type:fe.mediaType==="image/*"?"image/jpeg":fe.mediaType,data:lr(fe.data)},cache_control:z});else if(fe.mediaType==="application/pdf"){Z.add("pdfs-2024-09-25");let U=await E(fe.providerOptions),be=await Q(fe.providerOptions);K.push({type:"document",source:tl(fe.data)?{type:"url",url:rl(fe.data)}:{type:"base64",media_type:"application/pdf",data:lr(fe.data)},title:(i=be.title)!=null?i:fe.filename,...be.context&&{context:be.context},...U&&{citations:{enabled:!0}},cache_control:z})}else if(fe.mediaType==="text/plain"){let U=await E(fe.providerOptions),be=await Q(fe.providerOptions);K.push({type:"document",source:tl(fe.data)?{type:"url",url:rl(fe.data)}:{type:"text",media_type:"text/plain",data:ST(fe.data)},title:(s=be.title)!=null?s:fe.filename,...be.context&&{context:be.context},...U&&{citations:{enabled:!0}},cache_control:z})}else throw new tt({functionality:`media type: ${fe.mediaType}`});break}}}break}case"tool":{for(let Se=0;Se<ve.length;Se++){let fe=ve[Se];if(fe.type==="tool-approval-response")continue;let Fe=Se===ve.length-1,z=(l=R.getCacheControl(fe.providerOptions,{type:"tool result part",canCache:!0}))!=null?l:Fe?R.getCacheControl(me.providerOptions,{type:"tool result message",canCache:!0}):void 0,U=fe.output,be;switch(U.type){case"content":be=U.value.map(we=>{switch(we.type){case"text":return{type:"text",text:we.text};case"image-data":return{type:"image",source:{type:"base64",media_type:we.mediaType,data:we.data}};case"image-url":return{type:"image",source:{type:"url",url:we.url}};case"file-url":return{type:"document",source:{type:"url",url:we.url}};case"file-data":{if(we.mediaType==="application/pdf")return Z.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:we.mediaType,data:we.data}};r.push({type:"other",message:`unsupported tool content part type: ${we.type} with media type: ${we.mediaType}`});return}default:{r.push({type:"other",message:`unsupported tool content part type: ${we.type}`});return}}}).filter(nu);break;case"text":case"error-text":be=U.value;break;case"execution-denied":be=(c=U.reason)!=null?c:"Tool execution denied.";break;case"json":case"error-json":default:be=JSON.stringify(U.value);break}K.push({type:"tool_result",tool_use_id:fe.toolCallId,content:be,is_error:U.type==="error-text"||U.type==="error-json"?!0:void 0,cache_control:z})}break}default:{let Se=j;throw new Error(`Unsupported role: ${Se}`)}}}ee.push({role:"user",content:K});break}case"assistant":{let K=[],me=new Set;for(let j=0;j<W.messages.length;j++){let ve=W.messages[j],Se=j===W.messages.length-1,{content:fe}=ve;for(let Fe=0;Fe<fe.length;Fe++){let z=fe[Fe],U=Fe===fe.length-1,be=(p=R.getCacheControl(z.providerOptions,{type:"assistant message part",canCache:!0}))!=null?p:U?R.getCacheControl(ve.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(z.type){case"text":{K.push({type:"text",text:ue&&Se&&U?z.text.trim():z.text,cache_control:be});break}case"reasoning":{if(e){let we=await Ve({provider:"anthropic",providerOptions:z.providerOptions,schema:eT});we!=null?we.signature!=null?(R.getCacheControl(z.providerOptions,{type:"thinking block",canCache:!1}),K.push({type:"thinking",thinking:z.text,signature:we.signature})):we.redactedData!=null?(R.getCacheControl(z.providerOptions,{type:"redacted thinking block",canCache:!1}),K.push({type:"redacted_thinking",data:we.redactedData})):r.push({type:"other",message:"unsupported reasoning metadata"}):r.push({type:"other",message:"unsupported reasoning metadata"})}else r.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(z.providerExecuted){let ae=o.toProviderToolName(z.toolName);if(((g=(h=z.providerOptions)==null?void 0:h.anthropic)==null?void 0:g.type)==="mcp-tool-use"){me.add(z.toolCallId);let d=(S=(y=z.providerOptions)==null?void 0:y.anthropic)==null?void 0:S.serverName;if(d==null||typeof d!="string"){r.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}K.push({type:"mcp_tool_use",id:z.toolCallId,name:z.toolName,input:z.input,server_name:d,cache_control:be})}else if(ae==="code_execution"&&z.input!=null&&typeof z.input=="object"&&"type"in z.input&&typeof z.input.type=="string"&&(z.input.type==="bash_code_execution"||z.input.type==="text_editor_code_execution"))K.push({type:"server_tool_use",id:z.toolCallId,name:z.input.type,input:z.input,cache_control:be});else if(ae==="code_execution"&&z.input!=null&&typeof z.input=="object"&&"type"in z.input&&z.input.type==="programmatic-tool-call"){let{type:d,...m}=z.input;K.push({type:"server_tool_use",id:z.toolCallId,name:"code_execution",input:m,cache_control:be})}else ae==="code_execution"||ae==="web_fetch"||ae==="web_search"?K.push({type:"server_tool_use",id:z.toolCallId,name:ae,input:z.input,cache_control:be}):ae==="tool_search_tool_regex"||ae==="tool_search_tool_bm25"?K.push({type:"server_tool_use",id:z.toolCallId,name:ae,input:z.input,cache_control:be}):r.push({type:"other",message:`provider executed tool call for tool ${z.toolName} is not supported`});break}let we=(f=z.providerOptions)==null?void 0:f.anthropic,de=we?.caller?we.caller.type==="code_execution_20250825"&&we.caller.toolId?{type:"code_execution_20250825",tool_id:we.caller.toolId}:we.caller.type==="direct"?{type:"direct"}:void 0:void 0;K.push({type:"tool_use",id:z.toolCallId,name:z.toolName,input:z.input,...de&&{caller:de},cache_control:be});break}case"tool-result":{let we=o.toProviderToolName(z.toolName);if(me.has(z.toolCallId)){let de=z.output;if(de.type!=="json"&&de.type!=="error-json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}K.push({type:"mcp_tool_result",tool_use_id:z.toolCallId,is_error:de.type==="error-json",content:de.value,cache_control:be})}else if(we==="code_execution"){let de=z.output;if(de.type==="error-text"||de.type==="error-json"){let ae={};try{typeof de.value=="string"?ae=JSON.parse(de.value):typeof de.value=="object"&&de.value!==null&&(ae=de.value)}catch{}ae.type==="code_execution_tool_result_error"?K.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(b=ae.errorCode)!=null?b:"unknown"},cache_control:be}):K.push({type:"bash_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:be,content:{type:"bash_code_execution_tool_result_error",error_code:(_=ae.errorCode)!=null?_:"unknown"}});break}if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}if(de.value==null||typeof de.value!="object"||!("type"in de.value)||typeof de.value.type!="string"){r.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${z.toolName}`});break}if(de.value.type==="code_execution_result"){let ae=await St({value:de.value,schema:jh});K.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:ae.type,stdout:ae.stdout,stderr:ae.stderr,return_code:ae.return_code,content:(M=ae.content)!=null?M:[]},cache_control:be})}else{let ae=await St({value:de.value,schema:Lh});ae.type==="code_execution_result"?K.push({type:"code_execution_tool_result",tool_use_id:z.toolCallId,content:{type:ae.type,stdout:ae.stdout,stderr:ae.stderr,return_code:ae.return_code,content:(B=ae.content)!=null?B:[]},cache_control:be}):ae.type==="bash_code_execution_result"||ae.type==="bash_code_execution_tool_result_error"?K.push({type:"bash_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:be,content:ae}):K.push({type:"text_editor_code_execution_tool_result",tool_use_id:z.toolCallId,cache_control:be,content:ae})}break}if(we==="web_fetch"){let de=z.output;if(de.type==="error-json"){let Y=JSON.parse(de.value);K.push({type:"web_fetch_tool_result",tool_use_id:z.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:Y.errorCode},cache_control:be});break}if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}let ae=await St({value:de.value,schema:Dh});K.push({type:"web_fetch_tool_result",tool_use_id:z.toolCallId,content:{type:"web_fetch_result",url:ae.url,retrieved_at:ae.retrievedAt,content:{type:"document",title:ae.content.title,citations:ae.content.citations,source:{type:ae.content.source.type,media_type:ae.content.source.mediaType,data:ae.content.source.data}}},cache_control:be});break}if(we==="web_search"){let de=z.output;if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}let ae=await St({value:de.value,schema:Ph});K.push({type:"web_search_tool_result",tool_use_id:z.toolCallId,content:ae.map(Y=>({url:Y.url,title:Y.title,page_age:Y.pageAge,encrypted_content:Y.encryptedContent,type:Y.type})),cache_control:be});break}if(we==="tool_search_tool_regex"||we==="tool_search_tool_bm25"){let de=z.output;if(de.type!=="json"){r.push({type:"other",message:`provider executed tool result output type ${de.type} for tool ${z.toolName} is not supported`});break}let Y=(await St({value:de.value,schema:Fh})).map(d=>({type:"tool_reference",tool_name:d.toolName}));K.push({type:"tool_search_tool_result",tool_use_id:z.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:Y},cache_control:be});break}r.push({type:"other",message:`provider executed tool result for tool ${z.toolName} is not supported`});break}}}}ee.push({role:"assistant",content:K});break}default:{let K=V;throw new Error(`content type: ${K}`)}}}return{prompt:{system:O,messages:ee},betas:Z}}function AT(t){let e=[],r;for(let n of t){let{role:o}=n;switch(o){case"system":{r?.type!=="system"&&(r={type:"system",messages:[]},e.push(r)),r.messages.push(n);break}case"assistant":{r?.type!=="assistant"&&(r={type:"assistant",messages:[]},e.push(r)),r.messages.push(n);break}case"user":{r?.type!=="user"&&(r={type:"user",messages:[]},e.push(r)),r.messages.push(n);break}case"tool":{r?.type!=="user"&&(r={type:"user",messages:[]},e.push(r)),r.messages.push(n);break}default:{let a=o;throw new Error(`Unsupported role: ${a}`)}}}return e}function nl({finishReason:t,isJsonResponseFromTool:e}){switch(t){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return e?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";default:return"other"}}function Nh(t,e,r){var n;if(t.type!=="page_location"&&t.type!=="char_location")return;let o=e[t.document_index];if(o)return{type:"source",sourceType:"document",id:r(),mediaType:o.mediaType,title:(n=t.document_title)!=null?n:o.title,filename:o.filename,providerMetadata:{anthropic:t.type==="page_location"?{citedText:t.cited_text,startPageNumber:t.start_page_number,endPageNumber:t.end_page_number}:{citedText:t.cited_text,startCharIndex:t.start_char_index,endCharIndex:t.end_char_index}}}}var kT=class{constructor(t,e){this.specificationVersion="v3";var r;this.modelId=t,this.config=e,this.generateId=(r=e.generateId)!=null?r:xt}supportsUrl(t){return t.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({userSuppliedBetas:t,prompt:e,maxOutputTokens:r,temperature:n,topP:o,topK:a,frequencyPenalty:i,presencePenalty:s,stopSequences:l,responseFormat:c,seed:p,tools:h,toolChoice:g,providerOptions:y,stream:S}){var f,b,_,M,B,Z;let N=[];i!=null&&N.push({type:"unsupported",feature:"frequencyPenalty"}),s!=null&&N.push({type:"unsupported",feature:"presencePenalty"}),p!=null&&N.push({type:"unsupported",feature:"seed"}),n!=null&&n>1?(N.push({type:"unsupported",feature:"temperature",details:`${n} exceeds anthropic maximum of 1.0. clamped to 1.0`}),n=1):n!=null&&n<0&&(N.push({type:"unsupported",feature:"temperature",details:`${n} is below anthropic minimum of 0. clamped to 0`}),n=0),c?.type==="json"&&c.schema==null&&N.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let R=await Ve({provider:"anthropic",providerOptions:y,schema:tT}),{maxOutputTokens:O,supportsStructuredOutput:ee,isKnownModel:E}=RT(this.modelId),Q=((f=this.config.supportsNativeStructuredOutput)!=null?f:!0)&&ee,X=(b=R?.structuredOutputMode)!=null?b:"auto",W=X==="outputFormat"||X==="auto"&&Q,ue=c?.type==="json"&&c.schema!=null&&!W?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:c.schema}:void 0,V=R?.contextManagement,K=new il,me=Xc({tools:h,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:j,betas:ve}=await IT({prompt:e,sendReasoning:(_=R?.sendReasoning)!=null?_:!0,warnings:N,cacheControlValidator:K,toolNameMapping:me}),Se=((M=R?.thinking)==null?void 0:M.type)==="enabled",fe=(B=R?.thinking)==null?void 0:B.budgetTokens,Fe=r??O,z={model:this.modelId,max_tokens:Fe,temperature:n,top_k:a,top_p:o,stop_sequences:l,...Se&&{thinking:{type:"enabled",budget_tokens:fe}},...R?.effort&&{output_config:{effort:R.effort}},...W&&c?.type==="json"&&c.schema!=null&&{output_format:{type:"json_schema",schema:c.schema}},...R?.mcpServers&&R.mcpServers.length>0&&{mcp_servers:R.mcpServers.map(d=>({type:d.type,name:d.name,url:d.url,authorization_token:d.authorizationToken,tool_configuration:d.toolConfiguration?{allowed_tools:d.toolConfiguration.allowedTools,enabled:d.toolConfiguration.enabled}:void 0}))},...R?.container&&{container:R.container.skills&&R.container.skills.length>0?{id:R.container.id,skills:R.container.skills.map(d=>({type:d.type,skill_id:d.skillId,version:d.version}))}:R.container.id},system:j.system,messages:j.messages,...V&&{context_management:{edits:V.edits.map(d=>{let m=d.type;switch(m){case"clear_tool_uses_20250919":return{type:d.type,...d.trigger!==void 0&&{trigger:d.trigger},...d.keep!==void 0&&{keep:d.keep},...d.clearAtLeast!==void 0&&{clear_at_least:d.clearAtLeast},...d.clearToolInputs!==void 0&&{clear_tool_inputs:d.clearToolInputs},...d.excludeTools!==void 0&&{exclude_tools:d.excludeTools}};case"clear_thinking_20251015":return{type:d.type,...d.keep!==void 0&&{keep:d.keep}};default:N.push({type:"other",message:`Unknown context management strategy: ${m}`});return}}).filter(d=>d!==void 0)}}};Se?(fe==null&&(N.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),z.thinking={type:"enabled",budget_tokens:1024},fe=1024),z.temperature!=null&&(z.temperature=void 0,N.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),a!=null&&(z.top_k=void 0,N.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(z.top_p=void 0,N.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),z.max_tokens=Fe+(fe??0)):o!=null&&n!=null&&(N.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),z.top_p=void 0),E&&z.max_tokens>O&&(r!=null&&N.push({type:"unsupported",feature:"maxOutputTokens",details:`${z.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${O} max output tokens. The max output tokens have been limited to ${O}.`}),z.max_tokens=O),R?.mcpServers&&R.mcpServers.length>0&&ve.add("mcp-client-2025-04-04"),V&&ve.add("context-management-2025-06-27"),R?.container&&R.container.skills&&R.container.skills.length>0&&(ve.add("code-execution-2025-08-25"),ve.add("skills-2025-10-02"),ve.add("files-api-2025-04-14"),h?.some(d=>d.type==="provider"&&d.id==="anthropic.code_execution_20250825")||N.push({type:"other",message:"code execution tool is required when using skills"})),R?.effort&&ve.add("effort-2025-11-24"),S&&((Z=R?.toolStreaming)==null||Z)&&ve.add("fine-grained-tool-streaming-2025-05-14"),W&&c?.type==="json"&&c.schema!=null&&ve.add("structured-outputs-2025-11-13");let{tools:be,toolChoice:we,toolWarnings:de,betas:ae}=await mT(ue!=null?{tools:[...h??[],ue],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:K,supportsStructuredOutput:Q}:{tools:h??[],toolChoice:g,disableParallelToolUse:R?.disableParallelToolUse,cacheControlValidator:K,supportsStructuredOutput:Q}),Y=K.getWarnings();return{args:{...z,tools:be,tool_choice:we,stream:S===!0?!0:void 0},warnings:[...N,...de,...Y],betas:new Set([...ve,...ae,...t]),usesJsonResponseTool:ue!=null,toolNameMapping:me}}async getHeaders({betas:t,headers:e}){return Ge(await Te(this.config.headers),e,t.size>0?{"anthropic-beta":Array.from(t).join(",")}:{})}async getBetasFromHeaders(t){var e,r;let o=(e=(await Te(this.config.headers))["anthropic-beta"])!=null?e:"",a=(r=t?.["anthropic-beta"])!=null?r:"";return new Set([...o.toLowerCase().split(","),...a.toLowerCase().split(",")].map(i=>i.trim()).filter(i=>i!==""))}buildRequestUrl(t){var e,r,n;return(n=(r=(e=this.config).buildRequestUrl)==null?void 0:r.call(e,this.config.baseURL,t))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(t){var e,r,n;return(n=(r=(e=this.config).transformRequestBody)==null?void 0:r.call(e,t))!=null?n:t}extractCitationDocuments(t){let e=r=>{var n,o;if(r.type!=="file"||r.mediaType!=="application/pdf"&&r.mediaType!=="text/plain")return!1;let a=(n=r.providerOptions)==null?void 0:n.anthropic,i=a?.citations;return(o=i?.enabled)!=null?o:!1};return t.filter(r=>r.role==="user").flatMap(r=>r.content).filter(e).map(r=>{var n;let o=r;return{title:(n=o.filename)!=null?n:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(t){var e,r,n,o,a,i,s,l,c,p,h;let{args:g,warnings:y,betas:S,usesJsonResponseTool:f,toolNameMapping:b}=await this.getArgs({...t,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),_=this.extractCitationDocuments(t.prompt),{responseHeaders:M,value:B,rawValue:Z}=await Ue({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:S,headers:t.headers}),body:this.transformRequestBody(g),failedResponseHandler:Ah,successfulResponseHandler:qe(ZE),abortSignal:t.abortSignal,fetch:this.config.fetch}),N=[],R={},O={},ee=!1;for(let E of B.content)switch(E.type){case"text":{if(!f&&(N.push({type:"text",text:E.text}),E.citations))for(let Q of E.citations){let X=Nh(Q,_,this.generateId);X&&N.push(X)}break}case"thinking":{N.push({type:"reasoning",text:E.thinking,providerMetadata:{anthropic:{signature:E.signature}}});break}case"redacted_thinking":{N.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:E.data}}});break}case"tool_use":{if(f&&E.name==="json")ee=!0,N.push({type:"text",text:JSON.stringify(E.input)});else{let X=E.caller,W=X?{type:X.type,toolId:"tool_id"in X?X.tool_id:void 0}:void 0;N.push({type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),...W&&{providerMetadata:{anthropic:{caller:W}}}})}break}case"server_tool_use":{if(E.name==="text_editor_code_execution"||E.name==="bash_code_execution")N.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName("code_execution"),input:JSON.stringify({type:E.name,...E.input}),providerExecuted:!0});else if(E.name==="web_search"||E.name==="code_execution"||E.name==="web_fetch"){let Q=E.name==="code_execution"&&E.input!=null&&typeof E.input=="object"&&"code"in E.input&&!("type"in E.input)?{type:"programmatic-tool-call",...E.input}:E.input;N.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName(E.name),input:JSON.stringify(Q),providerExecuted:!0})}else(E.name==="tool_search_tool_regex"||E.name==="tool_search_tool_bm25")&&(O[E.id]=E.name,N.push({type:"tool-call",toolCallId:E.id,toolName:b.toCustomToolName(E.name),input:JSON.stringify(E.input),providerExecuted:!0}));break}case"mcp_tool_use":{R[E.id]={type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify(E.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:E.server_name}}},N.push(R[E.id]);break}case"mcp_tool_result":{N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:R[E.tool_use_id].toolName,isError:E.is_error,result:E.content,dynamic:!0,providerMetadata:R[E.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{E.content.type==="web_fetch_result"?N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:E.content.url,retrievedAt:E.content.retrieved_at,content:{type:E.content.content.type,title:E.content.content.title,citations:E.content.content.citations,source:{type:E.content.content.source.type,mediaType:E.content.content.source.media_type,data:E.content.content.source.data}}}}):E.content.type==="web_fetch_tool_result_error"&&N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:E.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(E.content)){N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_search"),result:E.content.map(Q=>{var X;return{url:Q.url,title:Q.title,pageAge:(X=Q.page_age)!=null?X:null,encryptedContent:Q.encrypted_content,type:Q.type}})});for(let Q of E.content)N.push({type:"source",sourceType:"url",id:this.generateId(),url:Q.url,title:Q.title,providerMetadata:{anthropic:{pageAge:(e=Q.page_age)!=null?e:null}}})}else N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:E.content.error_code}});break}case"code_execution_tool_result":{E.content.type==="code_execution_result"?N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),result:{type:E.content.type,stdout:E.content.stdout,stderr:E.content.stderr,return_code:E.content.return_code,content:(r=E.content.content)!=null?r:[]}}):E.content.type==="code_execution_tool_result_error"&&N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:E.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName("code_execution"),result:E.content});break}case"tool_search_tool_result":{let Q=(n=O[E.tool_use_id])!=null?n:"tool_search_tool_regex";E.content.type==="tool_search_tool_search_result"?N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName(Q),result:E.content.tool_references.map(X=>({type:X.type,toolName:X.tool_name}))}):N.push({type:"tool-result",toolCallId:E.tool_use_id,toolName:b.toCustomToolName(Q),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:E.content.error_code}});break}}return{content:N,finishReason:{unified:nl({finishReason:B.stop_reason,isJsonResponseFromTool:ee}),raw:(o=B.stop_reason)!=null?o:void 0},usage:Oh(B.usage),request:{body:g},response:{id:(a=B.id)!=null?a:void 0,modelId:(i=B.model)!=null?i:void 0,headers:M,body:Z},warnings:y,providerMetadata:{anthropic:{usage:B.usage,cacheCreationInputTokens:(s=B.usage.cache_creation_input_tokens)!=null?s:null,stopSequence:(l=B.stop_sequence)!=null?l:null,container:B.container?{expiresAt:B.container.expires_at,id:B.container.id,skills:(p=(c=B.container.skills)==null?void 0:c.map(E=>({type:E.type,skillId:E.skill_id,version:E.version})))!=null?p:null}:null,contextManagement:(h=Mh(B.context_management))!=null?h:null}}}}async doStream(t){var e,r;let{args:n,warnings:o,betas:a,usesJsonResponseTool:i,toolNameMapping:s}=await this.getArgs({...t,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),l=this.extractCitationDocuments(t.prompt),c=this.buildRequestUrl(!0),{responseHeaders:p,value:h}=await Ue({url:c,headers:await this.getHeaders({betas:a,headers:t.headers}),body:this.transformRequestBody(n),failedResponseHandler:Ah,successfulResponseHandler:Sr(QE),abortSignal:t.abortSignal,fetch:this.config.fetch}),g={unified:"other",raw:void 0},y={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},S={},f={},b={},_=null,M,B=null,Z=null,N=null,R=!1,O,ee=this.generateId,E=h.pipeThrough(new TransformStream({start(ue){ue.enqueue({type:"stream-start",warnings:o})},transform(ue,V){var K,me,j,ve,Se,fe,Fe,z,U,be,we,de,ae;if(t.includeRawChunks&&V.enqueue({type:"raw",rawValue:ue.rawValue}),!ue.success){V.enqueue({type:"error",error:ue.error});return}let Y=ue.value;switch(Y.type){case"ping":return;case"content_block_start":{let d=Y.content_block,m=d.type;switch(O=m,m){case"text":{if(i)return;S[Y.index]={type:"text"},V.enqueue({type:"text-start",id:String(Y.index)});return}case"thinking":{S[Y.index]={type:"reasoning"},V.enqueue({type:"reasoning-start",id:String(Y.index)});return}case"redacted_thinking":{S[Y.index]={type:"reasoning"},V.enqueue({type:"reasoning-start",id:String(Y.index),providerMetadata:{anthropic:{redactedData:d.data}}});return}case"tool_use":{if(i&&d.name==="json")R=!0,S[Y.index]={type:"text"},V.enqueue({type:"text-start",id:String(Y.index)});else{let C=d.caller,x=C?{type:C.type,toolId:"tool_id"in C?C.tool_id:void 0}:void 0,D=d.input&&Object.keys(d.input).length>0?JSON.stringify(d.input):"";S[Y.index]={type:"tool-call",toolCallId:d.id,toolName:d.name,input:D,firstDelta:D.length===0,...x&&{caller:x}},V.enqueue({type:"tool-input-start",id:d.id,toolName:d.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(d.name)){let v=d.name==="text_editor_code_execution"||d.name==="bash_code_execution"?"code_execution":d.name,C=s.toCustomToolName(v);S[Y.index]={type:"tool-call",toolCallId:d.id,toolName:C,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:d.name},V.enqueue({type:"tool-input-start",id:d.id,toolName:C,providerExecuted:!0})}else if(d.name==="tool_search_tool_regex"||d.name==="tool_search_tool_bm25"){b[d.id]=d.name;let v=s.toCustomToolName(d.name);S[Y.index]={type:"tool-call",toolCallId:d.id,toolName:v,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:d.name},V.enqueue({type:"tool-input-start",id:d.id,toolName:v,providerExecuted:!0})}return}case"web_fetch_tool_result":{d.content.type==="web_fetch_result"?V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:d.content.url,retrievedAt:d.content.retrieved_at,content:{type:d.content.content.type,title:d.content.content.title,citations:d.content.content.citations,source:{type:d.content.content.source.type,mediaType:d.content.content.source.media_type,data:d.content.content.source.data}}}}):d.content.type==="web_fetch_tool_result_error"&&V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:d.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(d.content)){V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_search"),result:d.content.map(v=>{var C;return{url:v.url,title:v.title,pageAge:(C=v.page_age)!=null?C:null,encryptedContent:v.encrypted_content,type:v.type}})});for(let v of d.content)V.enqueue({type:"source",sourceType:"url",id:ee(),url:v.url,title:v.title,providerMetadata:{anthropic:{pageAge:(K=v.page_age)!=null?K:null}}})}else V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:d.content.error_code}});return}case"code_execution_tool_result":{d.content.type==="code_execution_result"?V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),result:{type:d.content.type,stdout:d.content.stdout,stderr:d.content.stderr,return_code:d.content.return_code,content:(me=d.content.content)!=null?me:[]}}):d.content.type==="code_execution_tool_result_error"&&V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:d.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName("code_execution"),result:d.content});return}case"tool_search_tool_result":{let v=(j=b[d.tool_use_id])!=null?j:"tool_search_tool_regex";d.content.type==="tool_search_tool_search_result"?V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName(v),result:d.content.tool_references.map(C=>({type:C.type,toolName:C.tool_name}))}):V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:s.toCustomToolName(v),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:d.content.error_code}});return}case"mcp_tool_use":{f[d.id]={type:"tool-call",toolCallId:d.id,toolName:d.name,input:JSON.stringify(d.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:d.server_name}}},V.enqueue(f[d.id]);return}case"mcp_tool_result":{V.enqueue({type:"tool-result",toolCallId:d.tool_use_id,toolName:f[d.tool_use_id].toolName,isError:d.is_error,result:d.content,dynamic:!0,providerMetadata:f[d.tool_use_id].providerMetadata});return}default:{let v=m;throw new Error(`Unsupported content block type: ${v}`)}}}case"content_block_stop":{if(S[Y.index]!=null){let d=S[Y.index];switch(d.type){case"text":{V.enqueue({type:"text-end",id:String(Y.index)});break}case"reasoning":{V.enqueue({type:"reasoning-end",id:String(Y.index)});break}case"tool-call":if(!(i&&d.toolName==="json")){V.enqueue({type:"tool-input-end",id:d.toolCallId});let v=d.input===""?"{}":d.input;if(d.providerToolName==="code_execution")try{let C=JSON.parse(v);C!=null&&typeof C=="object"&&"code"in C&&!("type"in C)&&(v=JSON.stringify({type:"programmatic-tool-call",...C}))}catch{}V.enqueue({type:"tool-call",toolCallId:d.toolCallId,toolName:d.toolName,input:v,providerExecuted:d.providerExecuted,...d.caller&&{providerMetadata:{anthropic:{caller:d.caller}}}})}break}delete S[Y.index]}O=void 0;return}case"content_block_delta":{let d=Y.delta.type;switch(d){case"text_delta":{if(i)return;V.enqueue({type:"text-delta",id:String(Y.index),delta:Y.delta.text});return}case"thinking_delta":{V.enqueue({type:"reasoning-delta",id:String(Y.index),delta:Y.delta.thinking});return}case"signature_delta":{O==="thinking"&&V.enqueue({type:"reasoning-delta",id:String(Y.index),delta:"",providerMetadata:{anthropic:{signature:Y.delta.signature}}});return}case"input_json_delta":{let m=S[Y.index],v=Y.delta.partial_json;if(v.length===0)return;if(R){if(m?.type!=="text")return;V.enqueue({type:"text-delta",id:String(Y.index),delta:v})}else{if(m?.type!=="tool-call")return;m.firstDelta&&(m.providerToolName==="bash_code_execution"||m.providerToolName==="text_editor_code_execution")&&(v=`{"type": "${m.providerToolName}",${v.substring(1)}`),V.enqueue({type:"tool-input-delta",id:m.toolCallId,delta:v}),m.input+=v,m.firstDelta=!1}return}case"citations_delta":{let m=Y.delta.citation,v=Nh(m,l,ee);v&&V.enqueue(v);return}default:{let m=d;throw new Error(`Unsupported delta type: ${m}`)}}}case"message_start":{if(y.input_tokens=Y.message.usage.input_tokens,y.cache_read_input_tokens=(ve=Y.message.usage.cache_read_input_tokens)!=null?ve:0,y.cache_creation_input_tokens=(Se=Y.message.usage.cache_creation_input_tokens)!=null?Se:0,M={...Y.message.usage},B=(fe=Y.message.usage.cache_creation_input_tokens)!=null?fe:null,Y.message.container!=null&&(N={expiresAt:Y.message.container.expires_at,id:Y.message.container.id,skills:null}),Y.message.stop_reason!=null&&(g={unified:nl({finishReason:Y.message.stop_reason,isJsonResponseFromTool:R}),raw:Y.message.stop_reason}),V.enqueue({type:"response-metadata",id:(Fe=Y.message.id)!=null?Fe:void 0,modelId:(z=Y.message.model)!=null?z:void 0}),Y.message.content!=null)for(let d=0;d<Y.message.content.length;d++){let m=Y.message.content[d];if(m.type==="tool_use"){let v=m.caller,C=v?{type:v.type,toolId:"tool_id"in v?v.tool_id:void 0}:void 0;V.enqueue({type:"tool-input-start",id:m.id,toolName:m.name});let x=JSON.stringify((U=m.input)!=null?U:{});V.enqueue({type:"tool-input-delta",id:m.id,delta:x}),V.enqueue({type:"tool-input-end",id:m.id}),V.enqueue({type:"tool-call",toolCallId:m.id,toolName:m.name,input:x,...C&&{providerMetadata:{anthropic:{caller:C}}}})}}return}case"message_delta":{Y.usage.input_tokens!=null&&y.input_tokens!==Y.usage.input_tokens&&(y.input_tokens=Y.usage.input_tokens),y.output_tokens=Y.usage.output_tokens,g={unified:nl({finishReason:Y.delta.stop_reason,isJsonResponseFromTool:R}),raw:(be=Y.delta.stop_reason)!=null?be:void 0},Z=(we=Y.delta.stop_sequence)!=null?we:null,N=Y.delta.container!=null?{expiresAt:Y.delta.container.expires_at,id:Y.delta.container.id,skills:(ae=(de=Y.delta.container.skills)==null?void 0:de.map(d=>({type:d.type,skillId:d.skill_id,version:d.version})))!=null?ae:null}:null,Y.delta.context_management&&(_=Mh(Y.delta.context_management)),M={...M,...Y.usage};return}case"message_stop":{V.enqueue({type:"finish",finishReason:g,usage:Oh(y),providerMetadata:{anthropic:{usage:M??null,cacheCreationInputTokens:B,stopSequence:Z,container:N,contextManagement:_}}});return}case"error":{V.enqueue({type:"error",error:Y.error});return}default:{let d=Y;throw new Error(`Unsupported chunk type: ${d}`)}}}})),[Q,X]=E.tee(),W=Q.getReader();try{await W.read();let ue=await W.read();if(((e=ue.value)==null?void 0:e.type)==="raw"&&(ue=await W.read()),((r=ue.value)==null?void 0:r.type)==="error"){let V=ue.value.error;throw new $e({message:V.message,url:c,requestBodyValues:n,statusCode:V.type==="overloaded_error"?529:500,responseHeaders:p,responseBody:JSON.stringify(V),isRetryable:V.type==="overloaded_error"})}}finally{W.cancel().catch(()=>{}),W.releaseLock()}return{stream:X,request:{body:n},response:{headers:p}}}};function RT(t){return t.includes("claude-sonnet-4-5")||t.includes("claude-opus-4-5")||t.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,isKnownModel:!0}:t.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,isKnownModel:!0}:t.includes("claude-sonnet-4-")||t.includes("claude-3-7-sonnet")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-3-5-haiku")?{maxOutputTokens:8192,supportsStructuredOutput:!1,isKnownModel:!0}:t.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!1}}function Mh(t){return t?{appliedEdits:t.applied_edits.map(e=>{switch(e.type){case"clear_tool_uses_20250919":return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case"clear_thinking_20251015":return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens}}}).filter(e=>e!==void 0)}:null}var OT=q(()=>H(ol.object({command:ol.string(),restart:ol.boolean().optional()}))),NT=Ee({id:"anthropic.bash_20241022",inputSchema:OT}),MT=q(()=>H(al.object({command:al.string(),restart:al.boolean().optional()}))),PT=Ee({id:"anthropic.bash_20250124",inputSchema:MT}),DT=q(()=>H(oo.object({action:oo.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:oo.array(oo.number().int()).optional(),text:oo.string().optional()}))),jT=Ee({id:"anthropic.computer_20241022",inputSchema:DT}),LT=q(()=>H(Ot.object({action:Ot.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:Ot.tuple([Ot.number().int(),Ot.number().int()]).optional(),duration:Ot.number().optional(),scroll_amount:Ot.number().optional(),scroll_direction:Ot.enum(["up","down","left","right"]).optional(),start_coordinate:Ot.tuple([Ot.number().int(),Ot.number().int()]).optional(),text:Ot.string().optional()}))),FT=Ee({id:"anthropic.computer_20250124",inputSchema:LT}),UT=q(()=>H(De.discriminatedUnion("command",[De.object({command:De.literal("view"),path:De.string(),view_range:De.tuple([De.number(),De.number()]).optional()}),De.object({command:De.literal("create"),path:De.string(),file_text:De.string()}),De.object({command:De.literal("str_replace"),path:De.string(),old_str:De.string(),new_str:De.string()}),De.object({command:De.literal("insert"),path:De.string(),insert_line:De.number(),insert_text:De.string()}),De.object({command:De.literal("delete"),path:De.string()}),De.object({command:De.literal("rename"),old_path:De.string(),new_path:De.string()})]))),HT=Ee({id:"anthropic.memory_20250818",inputSchema:UT}),qT=q(()=>H(yr.object({command:yr.enum(["view","create","str_replace","insert","undo_edit"]),path:yr.string(),file_text:yr.string().optional(),insert_line:yr.number().int().optional(),new_str:yr.string().optional(),old_str:yr.string().optional(),view_range:yr.array(yr.number().int()).optional()}))),$T=Ee({id:"anthropic.text_editor_20241022",inputSchema:qT}),GT=q(()=>H(vr.object({command:vr.enum(["view","create","str_replace","insert","undo_edit"]),path:vr.string(),file_text:vr.string().optional(),insert_line:vr.number().int().optional(),new_str:vr.string().optional(),old_str:vr.string().optional(),view_range:vr.array(vr.number().int()).optional()}))),BT=Ee({id:"anthropic.text_editor_20250124",inputSchema:GT}),VT=q(()=>H(br.object({command:br.enum(["view","create","str_replace","insert"]),path:br.string(),file_text:br.string().optional(),insert_line:br.number().int().optional(),new_str:br.string().optional(),old_str:br.string().optional(),view_range:br.array(br.number().int()).optional()}))),zT=Ee({id:"anthropic.text_editor_20250429",inputSchema:VT}),WT=q(()=>H(Vr.array(Vr.object({type:Vr.literal("tool_reference"),toolName:Vr.string()})))),JT=q(()=>H(Vr.object({query:Vr.string(),limit:Vr.number().optional()}))),KT=Ze({id:"anthropic.tool_search_bm25_20251119",inputSchema:JT,outputSchema:WT}),YT=(t={})=>KT(t),XT={bash_20241022:NT,bash_20250124:PT,codeExecution_20250522:vT,codeExecution_20250825:wT,computer_20241022:jT,computer_20250124:FT,memory_20250818:HT,textEditor_20241022:$T,textEditor_20250124:BT,textEditor_20250429:zT,textEditor_20250728:iT,webFetch_20250910:fT,webSearch_20250305:uT,toolSearchRegex_20251119:xT,toolSearchBm25_20251119:YT};function sl(t={}){var e,r;let n=(e=dr(Lt({settingValue:t.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?e:"https://api.anthropic.com/v1",o=(r=t.name)!=null?r:"anthropic.messages",a=()=>lt({"anthropic-version":"2023-06-01","x-api-key":wo({apiKey:t.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...t.headers},`ai-sdk/anthropic/${YE}`),i=l=>{var c;return new kT(l,{provider:o,baseURL:n,headers:a,fetch:t.fetch,generateId:(c=t.generateId)!=null?c:xt,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},s=function(l){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return i(l)};return s.specificationVersion="v3",s.languageModel=i,s.chat=i,s.messages=i,s.embeddingModel=l=>{throw new Ha({modelId:l,modelType:"embeddingModel"})},s.textEmbeddingModel=s.embeddingModel,s.imageModel=l=>{throw new Ha({modelId:l,modelType:"imageModel"})},s.tools=XT,s}var LR=sl();function Uh(t){let e=Sn().env?.ANTHROPIC_API_KEY;if(!e)throw new Error("ANTHROPIC_API_KEY not configured in SDK config");return ce.debug(`Using Anthropic provider: model=${t}`),sl({apiKey:e})(t)}function Hh(t){return{anthropic:{structuredOutputMode:"jsonTool"}}}function WR(t){if(t.startsWith("claude-"))return Uh(t);if(t.startsWith("gemini-"))return Ch(t);throw new Error(`Unsupported model: ${t}. Use 'claude-*' or 'gemini-*' models.`)}function JR(t,e){return t.startsWith("claude-")?Hh(t):Ih(e,t)}async function $h(){let{default:t}=await import("sharp");return t}var qh=768;async function ll(t,e){let r=await $h(),n=await r(t).metadata(),o=n.width||0,a=n.height||0;if(o===0||a===0)throw new Error("Invalid image dimensions");let i=a,s=0,l=Math.floor((o-i)/2),c=Math.max(0,o-i),p=(S,f)=>{let b=r(t).extract({left:S,top:0,width:f,height:i});return e?.resize&&(b=b.resize(qh,qh)),b.png().toBuffer()},[h,g,y]=await Promise.all([p(s,Math.min(i,o)),p(l,Math.min(i,o-l)),p(c,Math.min(i,o-c))]);return[h,g,y]}async function Gh(t){let e=(await $h())(t),r=await e.metadata(),n=r.width||0,o=r.height||0;if(n===0||o===0)throw new Error("Invalid image dimensions");let{data:a}=await e.grayscale().raw().toBuffer({resolveWithObject:!0}),i=[];for(let s=0;s<o;s++){i[s]=[];for(let l=0;l<n;l++)i[s][l]=a[s*n+l]}return{pixels:i,width:n,height:o}}function Bh(t,e){return t.length>e?t.slice(0,e)+"...":t}var Vh=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","data-id","data-testid","data-test-id","data-handlepos","data-item-id"],zh={"react-flow__(\\S+)":"$1"};var Wh=class{constructor(t,e=null){this.isVisible=t,this.parent=e}},ao=class extends Wh{constructor(t,e,r=null){super(e,r),this.text=t,this.type="TEXT_NODE"}hasParentWithHighlightIndex(){let t=this.parent;for(;t!==null;){if(t.highlightIndex!==null)return!0;t=t.parent}return!1}isParentInViewport(){return this.parent===null?!1:this.parent.isInViewport}isParentTopElement(){return this.parent===null?!1:this.parent.isTopElement}},ar=class Ta extends Wh{constructor(e,r,n,o,a,i=!1,s=!1,l=!1,c=!1,p=!1,h=!1,g=null,y=null,S=null,f=null,b=[],_=null){super(a,_),this.tagName=e,this.xpath=r,this.attributes=n,this.children=o,this.isInteractive=i,this.isScrollable=s,this.markAsClickable=l,this.isTopElement=c,this.isInViewport=p,this.shadowRoot=h,this.highlightIndex=g,this.viewportCoordinates=y,this.pageCoordinates=S,this.viewportInfo=f,this.isNew=null,this.shadowHostXPaths=b}getAllTextTillNextClickableElement(e=-1){let r=[],n=(o,a)=>{if(!(e!==-1&&a>e)&&!(o instanceof Ta&&o!==this&&o.highlightIndex!==null)){if(o instanceof ao)r.push(o.text);else if(o instanceof Ta)for(let i of o.children)n(i,a+1)}};return n(this,0),r.join(`
|
|
52
|
+
`).trim()}clickableElementsToString(e){let r=e?.includeAttributes??Vh,n=e?.includeClassesWithRename??zh,o=[],a=(i,s)=>{let l=s,c=" ".repeat(s);if(i instanceof Ta){if(i.highlightIndex!==null){l+=1;let p=i.isScrollable?"":i.getAllTextTillNextClickableElement(),h=null;if(r.length>0){let _={};for(let Z of Object.keys(i.attributes))if(r.includes(Z)){let N=i.attributes[Z].trim();N!==""&&(_[Z]=N)}let M=r.filter(Z=>Z in _);if(M.length>1){let Z=new Set,N={};for(let R of M){let O=_[R];O.length>5&&(O in N?Z.add(R):N[O]=R)}for(let R of Z)delete _[R]}i.tagName===_.role&&delete _.role;let B=["aria-label","placeholder","title"];for(let Z of B)_[Z]&&_[Z].trim().toLowerCase()===p.trim().toLowerCase()&&delete _[Z];Object.keys(_).length>0&&(h=Object.entries(_).map(([Z,N])=>`${Z}=${Bh(N,200)}`).join(" "))}let g=i.isNew?`*[${i.highlightIndex}]`:`[${i.highlightIndex}]`,y=[];if(Object.keys(n).length>0&&i.attributes.class){let _=i.attributes.class.split(/\s+/);for(let M of _)for(let[B,Z]of Object.entries(n))try{let N=new RegExp(`^${B}$`);if(M.match(N)){let R=M.replace(N,Z);R&&y.push(R);break}}catch{continue}}let S=i.isScrollable?" (SCROLLABLE)":"",f=i.markAsClickable?" (CLICKABLE)":"",b=`${c}${g}${S}${f}<${i.tagName}`;if(y.length>0&&(b+=` ${y.join(" ")}`),h&&(b+=` ${h}`),p){let _=p.trim();h||(b+=" "),b+=`>${_}`}else h||(b+=" ");b+=" />",o.push(b)}else{let p=["data-testid","data-test-id"].filter(h=>i.attributes[h]);p.length>0&&(l+=1,o.push(`${c}<${i.tagName} ${p.map(h=>`${h}="${i.attributes[h]}"`).join(" ")} />`))}for(let p of i.children)a(p,l)}else if(i instanceof ao){if(i.hasParentWithHighlightIndex())return;i.parent&&i.parent.isVisible&&i.parent.isTopElement&&o.push(`${c}${i.text}`)}};return a(this,0),o.join(`
|
|
53
|
+
`)}};var cl=new Set(["button","link","textbox","checkbox","radio","combobox","listbox","menuitem","menuitemcheckbox","menuitemradio","option","tab","switch","slider","spinbutton","searchbox","scrollbar","treeitem","gridcell"]),xa=new Set(["click","mousedown","mouseup","dblclick","pointerdown","pointerup","touchstart","touchend"]),Jh=["[onclick]","[onmousedown]","[ontouchstart]","div","span","li","tr","td","[role]",'[class*="btn"]','[class*="button"]','[class*="click"]',"[data-action]","[data-click]"],Kh=500;function oO(t){return t?cl.has(t):!1}function aO(t){return xa.has(t)}function iO(t){return t.filter(e=>xa.has(e.type))}var ZT=`(
|
|
54
54
|
args = {
|
|
55
55
|
doHighlightElements: true,
|
|
56
56
|
focusHighlightIndex: -1,
|
|
@@ -3950,7 +3950,7 @@ Error message: ${Tr(r)}`,cause:r}),this[dc]=!0,this.value=e}static isInstance(e)
|
|
|
3950
3950
|
} : null,
|
|
3951
3951
|
clientRects: clientRectsArray
|
|
3952
3952
|
};
|
|
3953
|
-
}`,returnByValue:!0});l.value&&r.push({axNode:i,...l.value})}catch(l){ce.debug(`Failed to resolve element: ${l}`)}}return r}async getElementsWithEventListeners(t,e=Vh){let r=[];try{let{root:n}=await t.send("DOM.getDocument",{depth:0}),o=Bh.join(","),{nodeIds:a}=await t.send("DOM.querySelectorAll",{nodeId:n.nodeId,selector:o});ce.debug(`\u{1F50D} Checking ${Math.min(a.length,e)} elements for event listeners`);for(let i of a.slice(0,e))try{let{object:s}=await t.send("DOM.resolveNode",{nodeId:i});if(!s.objectId)continue;let{listeners:l}=await t.send("DOMDebugger.getEventListeners",{objectId:s.objectId}),c=l.filter(p=>Ta.has(p.type));if(c.length>0){let{node:p}=await t.send("DOM.describeNode",{nodeId:i});r.push({backendNodeId:p.backendNodeId,eventTypes:c.map(h=>h.type)})}await t.send("Runtime.releaseObject",{objectId:s.objectId})}catch{}ce.debug(`\u2705 Found ${r.length} elements with interaction event listeners`)}catch(n){ce.warn("Failed to get elements with event listeners:",n)}return r}async buildDomStateFromAXTree(t){let e=new Map,r=new ar("body","/body",{},[],!0,!1,!1,!1,!0,!0,!1,null),n=0;for(let o of t){let a=o.axNode.role?.value||"",i=o.axNode.name?.value||"",s=["button","link","menuitem","tab","switch"].includes(a),l=new ar(o.tagName,o.xpath,o.attributes,[],o.isVisible,!0,a==="scrollbar",s,o.isTopElement,o.isInViewport,!1,n,o.boundingRect?{topLeft:{x:o.boundingRect.x,y:o.boundingRect.y},topRight:{x:o.boundingRect.x+o.boundingRect.width,y:o.boundingRect.y},bottomLeft:{x:o.boundingRect.x,y:o.boundingRect.y+o.boundingRect.height},bottomRight:{x:o.boundingRect.x+o.boundingRect.width,y:o.boundingRect.y+o.boundingRect.height},center:{x:o.boundingRect.x+o.boundingRect.width/2,y:o.boundingRect.y+o.boundingRect.height/2},width:o.boundingRect.width,height:o.boundingRect.height}:null,null,null,[],r);if(i){let c=new ao(i,!0,l);l.children.push(c)}r.children.push(l),e.set(n,l),n++}return{domState:{elementTree:r,selectorMap:e},highlightIndex:n}}async renderHighlightsForAXElements(t,e){let r=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];await t.evaluate(({elements:n,colors:o})=>{let a="playwright-highlight-container",i=document.getElementById(a);i||(i=document.createElement("div"),i.id=a,i.style.position="fixed",i.style.pointerEvents="none",i.style.top="0",i.style.left="0",i.style.width="100%",i.style.height="100%",i.style.zIndex="2147483647",i.style.backgroundColor="transparent",document.body.appendChild(i)),n.forEach((s,l)=>{if(!s.boundingRect)return;let c=o[l%o.length],p=s.boundingRect,h=document.createElement("div");h.style.position="fixed",h.style.border=`1px solid ${c}`,h.style.backgroundColor="transparent",h.style.pointerEvents="none",h.style.boxSizing="border-box",h.style.top=`${p.y}px`,h.style.left=`${p.x}px`,h.style.width=`${p.width}px`,h.style.height=`${p.height}px`,i.appendChild(h);let g=document.createElement("div");g.style.position="fixed",g.style.background=c,g.style.color="white",g.style.padding="1px 4px",g.style.borderRadius="4px",g.style.fontSize=l>=100?"8px":"12px",g.textContent=String(l);let y=Math.max(0,p.y-16),S=Math.max(0,Math.min(p.x+p.width-20,window.innerWidth-25));g.style.top=`${y}px`,g.style.left=`${S}px`,i.appendChild(g)})},{elements:e,colors:r})}async removeHighlights(t){let e=()=>{let r=document.getElementById("playwright-highlight-container");r&&r.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(n=>n()),window._highlightCleanupFunctions=[])};try{await t.evaluate(e),ce.debug("\u2705 Highlights removed from page")}catch(r){ce.warn("Failed to remove highlights:",r.message)}for(let r of t.frames())if(r.url().startsWith("chrome-extension://"))try{await r.evaluate(e)}catch{}}async getCrossOriginIframes(t){let e=await t.locator("iframe").filter({hasNot:t.locator(":visible")}).evaluateAll(s=>s.map(l=>l.src)),r=s=>{try{let l=new URL(s);return["doubleclick.net","adroll.com","googletagmanager.com"].some(c=>l.hostname.includes(c))}catch{return!1}},n=t.url(),o=new URL(n).hostname,a=t.frames(),i=[];for(let s of a){let l=s.url();try{let c=new URL(l).hostname;c&&c!==o&&!e.includes(l)&&!r(l)&&i.push(l)}catch{continue}}return i}async buildDomTree(t,e,r,n,o,a,i,s="all"){if(await t.evaluate("1+1")!==2)throw new Error("The page cannot evaluate javascript code properly");if(e0(t.url()))return[new ar("body","",{},[],!1,!1,!1,!1,!1,!1,!1,null),new Map];let l={doHighlightElements:e,focusHighlightIndex:r,viewportExpansion:n,debugMode:!1,interactiveClassNames:o,alwaysHighlightFileInput:a,sameRectIoUThreshold:i,actionIntent:s,domTreeRoot:this.domTreeRoot};ce.debug(`\u{1F527} Starting JavaScript DOM analysis for ${t.url().slice(0,50)}...`);let c,p=null;if(this.useDomTreeTs&&e)try{let f={...l,phase:"boxes",grayscaleImage:null},b=await t.evaluate(({code:R,argsObj:O})=>new Function("return "+R)()(O),{code:this.jsCode,argsObj:f});ce.debug(`\u{1F4E6} Phase 1: Drew ${b.elementData?.length||0} bounding boxes`);let _=await t.screenshot({type:"png",fullPage:!1});ce.debug("\u{1F4F8} Captured screenshot with bounding boxes");let M=performance.now(),B=await Gh(_);p=B.pixels;let Z=Math.round(performance.now()-M);ce.debug(`\u{1F5BC}\uFE0F Generated grayscale image (${B.width}x${B.height}) in ${Z}ms`);let N={...l,phase:"labels",grayscaleImage:p,elementData:b.elementData};c=await t.evaluate(({code:R,argsObj:O})=>new Function("return "+R)()(O),{code:this.jsCode,argsObj:N}),c.map=b.map,c.rootId=b.rootId,c.highlightCount=b.highlightCount,c.perfMetrics=b.perfMetrics,ce.debug("\u2705 Phase 2: Labels placed using grayscale-based positioning")}catch(f){ce.warn("Two-phase rendering failed, falling back to legacy mode:",f.message),p=null;let b={...l,grayscaleImage:null};c=await t.evaluate(({code:_,argsObj:M})=>new Function("return "+_)()(M),{code:this.jsCode,argsObj:b}),ce.debug("\u2705 JavaScript DOM analysis completed (legacy mode)")}else try{c=await t.evaluate(({code:f,argsObj:b})=>new Function("return "+f)()(b),{code:this.jsCode,argsObj:l}),ce.debug("\u2705 JavaScript DOM analysis completed")}catch(f){throw ce.error("Error evaluating JavaScript:",f.message),f}if(!c||typeof c!="object")throw ce.error("JavaScript returned invalid result:",c),new Error("JavaScript DOM analysis returned invalid result");if(!c.map||!c.rootId)throw ce.error("JavaScript result missing map or rootId:",JSON.stringify(c,null,2)),new Error("JavaScript result missing required fields (map or rootId)");if(s!=="all"&&c.highlightCount===0){ce.debug(`\u26A0\uFE0F No elements matched intent '${s}', falling back to 'all'`);let f={...l,actionIntent:"all"};c=await t.evaluate(({code:b,argsObj:_})=>new Function("return "+b)()(_),{code:this.jsCode,argsObj:f})}let h=Object.entries(c.map).filter(([,f])=>f.tagName==="iframe");ce.debug(`\u{1F50D} [ext-iframe] Total iframe nodes in map: ${h.length}`);for(let[f,b]of h){let _=b;ce.debug(`\u{1F50D} [ext-iframe] iframe node id=${f} src=${_.attributes?.src} inaccessibleFrame=${_.inaccessibleFrame}`)}let g=t.frames();ce.debug(`\u{1F50D} [ext-iframe] Playwright frames count: ${g.length}`);for(let f of g)ce.debug(`\u{1F50D} [ext-iframe] Playwright frame url=${f.url()}`);let y=[];for(let[f,b]of Object.entries(c.map)){let _=b;_.inaccessibleFrame&&_.attributes?.src?.startsWith("chrome-extension://")&&y.push({nodeId:f,src:_.attributes.src})}if(ce.debug(`\u{1F50D} [ext-iframe] Inaccessible extension iframes found: ${y.length}`),y.length>0){ce.debug(`\u{1F50C} Found ${y.length} inaccessible extension iframe(s), processing via Playwright frames`);let f=-1;for(let b of Object.values(c.map)){let _=b;_.highlightIndex!=null&&(f=Math.max(f,_.highlightIndex))}ce.debug(`\u{1F50D} [ext-iframe] Main page max highlight index: ${f}`);for(let b=0;b<y.length;b++){let{nodeId:_,src:M}=y[b];ce.debug(`\u{1F50D} [ext-iframe] Processing extension iframe [${b}]: ${M}`);let B=(()=>{try{return new URL(M).origin}catch{return null}})(),Z=t.frames().find(N=>{if(N.url()===M)return!0;if(B)try{return new URL(N.url()).origin===B}catch{return!1}return!1});if(!Z){ce.debug(`\u26A0\uFE0F [ext-iframe] No Playwright frame found for extension iframe: ${M}`),ce.debug(`\u26A0\uFE0F [ext-iframe] Available frame URLs: ${t.frames().map(N=>N.url()).join(", ")}`);continue}ce.debug(`\u{1F50D} [ext-iframe] Found matching Playwright frame for: ${M} (frame url: ${Z.url()})`);try{let N={...l,initialHighlightIndex:f+1,domTreeRoot:"body"};ce.debug(`\u{1F50D} [ext-iframe] Running dom-tree in extension frame with initialHighlightIndex=${N.initialHighlightIndex}`);let R=await Z.evaluate(({code:Q,argsObj:X})=>new Function("return "+Q)()(X),{code:this.jsCode,argsObj:N});if(ce.debug(`\u{1F50D} [ext-iframe] frameEval result: map size=${Object.keys(R?.map??{}).length} rootId=${R?.rootId}`),!R?.map||!R.rootId){ce.debug("\u26A0\uFE0F [ext-iframe] frameEval missing map or rootId, skipping");continue}let O=Object.values(R.map).filter(Q=>Q.highlightIndex!=null);ce.debug(`\u{1F50D} [ext-iframe] Interactive elements in extension frame: ${O.length}`);for(let Q of O){let X=Q;ce.debug(`\u{1F50D} [ext-iframe] - <${X.tagName}> highlightIndex=${X.highlightIndex} text="${X.children?.length?"...":""}"`)}for(let Q of Object.values(R.map)){let X=Q;X.highlightIndex!=null&&(f=Math.max(f,X.highlightIndex))}let ee=`ext_${b}_`;for(let[Q,X]of Object.entries(R.map)){let W={...X};W.children&&(W.children=W.children.map(ue=>`${ee}${ue}`)),c.map[`${ee}${Q}`]=W}let E=c.map[_];E?(E.children=[...E.children||[],`${ee}${R.rootId}`],ce.debug(`\u{1F50D} [ext-iframe] Attached frame root to iframe node ${_}`)):ce.debug(`\u26A0\uFE0F [ext-iframe] iframe node ${_} not found in map`),ce.debug(`\u2705 Merged extension iframe content from: ${M}`)}catch(N){ce.warn(`Failed to process extension iframe ${M}:`,N)}}}if(c&&c.perfMetrics){let f=c.perfMetrics.nodeMetrics?.totalNodes??0,b=0;if(c.map)for(let M of Object.values(c.map))typeof M=="object"&&M!==null&&M.isInteractive&&b++;let _=t.url().length>50?t.url().slice(0,50)+"...":t.url();ce.debug(`\u{1F50E} Ran buildDOMTree.js interactive element detection on: ${_} interactive=${b}/${f}`)}ce.debug("\u{1F504} Starting TypeScript DOM tree construction...");let S=await this.constructDomTree(c);return ce.debug("\u2705 TypeScript DOM tree construction completed"),S}async constructDomTree(t){let e=t.map,r=t.rootId,n=new Map,o=new Map,a=new Map;for(let[s,l]of Object.entries(e)){let[c,p]=this.parseNode(l);c!==null&&(o.set(s,c),a.set(s,p),c instanceof ar&&c.highlightIndex!==null&&n.set(c.highlightIndex,c))}for(let[s,l]of a){let c=o.get(s);if(c instanceof ar)for(let p of l){let h=o.get(p);h&&(h.parent=c,c.children.push(h))}}let i=o.get(r);if(!i||!(i instanceof ar))throw new Error("Failed to parse HTML to dictionary");return[i,n]}parseNode(t){if(!t)return[null,[]];if(t.type==="TEXT_NODE")return[new ao(t.text,t.isVisible,null),[]];let e=null;t.viewport&&(e={width:t.viewport.width,height:t.viewport.height,scrollX:t.viewport.scrollX,scrollY:t.viewport.scrollY});let r=t.shadowHostXPaths??[],n=new ar(t.tagName,t.xpath,t.attributes||{},[],t.isVisible??!1,t.isInteractive??!1,t.isScrollable??!1,t.markAsClickable??!1,t.isTopElement??!1,t.isInViewport??!1,t.shadowRoot??!1,t.highlightIndex??null,t.viewportCoordinates??null,t.pageCoordinates??null,e,r,null),o=t.children||[];return[n,o]}};import{createHash as ul}from"crypto";var yO=class{static convertDomElementToHistoryElement(t){let e=this.getParentBranchPath(t),r=this.generateCssSelector(t);return{tagName:t.tagName,xpath:t.xpath,highlightIndex:t.highlightIndex,entireParentBranchPath:e,attributes:t.attributes,shadowRoot:t.shadowRoot,cssSelector:r,pageCoordinates:t.pageCoordinates,viewportCoordinates:t.viewportCoordinates,viewportInfo:t.viewportInfo}}static findHistoryElementInTree(t,e){let r=this.hashDomHistoryElement(t),n=o=>{if(o.highlightIndex!==null){let a=this.hashDomElement(o);if(this.compareHashes(a,r))return o}for(let a of o.children)if(a instanceof ar){let i=n(a);if(i!==null)return i}return null};return n(e)}static compareHistoryElementAndDomElement(t,e){let r=this.hashDomHistoryElement(t),n=this.hashDomElement(e);return this.compareHashes(r,n)}static hashDomHistoryElement(t){let e=this.parentBranchPathHash(t.entireParentBranchPath),r=this.attributesHash(t.attributes),n=this.xpathHash(t.xpath);return{branchPathHash:e,attributesHash:r,xpathHash:n}}static hashDomElement(t){let e=this.getParentBranchPath(t),r=this.parentBranchPathHash(e),n=this.attributesHash(t.attributes),o=this.xpathHash(t.xpath);return{branchPathHash:r,attributesHash:n,xpathHash:o}}static getParentBranchPath(t){let e=[],r=t;for(;r!==null&&r.parent!==null;)e.push(r),r=r.parent;return e.reverse(),e.map(n=>n.tagName)}static parentBranchPathHash(t){let e=t.join("/");return ul("sha256").update(e).digest("hex")}static attributesHash(t){let e=Object.entries(t).map(([r,n])=>`${r}=${n}`).join("");return ul("sha256").update(e).digest("hex")}static xpathHash(t){return ul("sha256").update(t).digest("hex")}static compareHashes(t,e){return t.branchPathHash===e.branchPathHash&&t.attributesHash===e.attributesHash&&t.xpathHash===e.xpathHash}static generateCssSelector(t){let e=t.attributes.id;if(e)return`#${e}`;let r=t.attributes.class;if(r){let n=r.split(/\s+/).filter(o=>o.trim());if(n.length>0)return`${t.tagName}.${n.join(".")}`}return t.tagName}};import{z as Or}from"zod/v4";import{z as yf}from"zod/v4";import{z as vl}from"zod/v4";import{z as We}from"zod/v4";import{z as Sa}from"zod/v4";import{z as Nt}from"zod/v4";import{z as ht}from"zod/v4";var Hf=Fa(gl(),1),qf=Fa(gl(),1);import{z as Re}from"zod";var x0="vercel.ai.gateway.error",yl=Symbol.for(x0),af,sf,Tt=class Of extends(sf=Error,af=yl,sf){constructor({message:e,statusCode:r=500,cause:n}){super(e),this[af]=!0,this.statusCode=r,this.cause=n}static isInstance(e){return Of.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&yl in e&&e[yl]===!0}},Nf="GatewayAuthenticationError",S0=`vercel.ai.gateway.error.${Nf}`,lf=Symbol.for(S0),cf,uf,Ca=class Mf extends(uf=Tt,cf=lf,uf){constructor({message:e="Authentication failed",statusCode:r=401,cause:n}={}){super({message:e,statusCode:r,cause:n}),this[cf]=!0,this.name=Nf,this.type="authentication_error"}static isInstance(e){return Tt.hasMarker(e)&&lf in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:a}){let i;return e?i=`AI Gateway authentication failed: Invalid API key.
|
|
3953
|
+
}`,returnByValue:!0});l.value&&r.push({axNode:i,...l.value})}catch(l){ce.debug(`Failed to resolve element: ${l}`)}}return r}async getElementsWithEventListeners(t,e=Kh){let r=[];try{let{root:n}=await t.send("DOM.getDocument",{depth:0}),o=Jh.join(","),{nodeIds:a}=await t.send("DOM.querySelectorAll",{nodeId:n.nodeId,selector:o});ce.debug(`\u{1F50D} Checking ${Math.min(a.length,e)} elements for event listeners`);for(let i of a.slice(0,e))try{let{object:s}=await t.send("DOM.resolveNode",{nodeId:i});if(!s.objectId)continue;let{listeners:l}=await t.send("DOMDebugger.getEventListeners",{objectId:s.objectId}),c=l.filter(p=>xa.has(p.type));if(c.length>0){let{node:p}=await t.send("DOM.describeNode",{nodeId:i});r.push({backendNodeId:p.backendNodeId,eventTypes:c.map(h=>h.type)})}await t.send("Runtime.releaseObject",{objectId:s.objectId})}catch{}ce.debug(`\u2705 Found ${r.length} elements with interaction event listeners`)}catch(n){ce.warn("Failed to get elements with event listeners:",n)}return r}async buildDomStateFromAXTree(t){let e=new Map,r=new ar("body","/body",{},[],!0,!1,!1,!1,!0,!0,!1,null),n=0;for(let o of t){let a=o.axNode.role?.value||"",i=o.axNode.name?.value||"",s=["button","link","menuitem","tab","switch"].includes(a),l=new ar(o.tagName,o.xpath,o.attributes,[],o.isVisible,!0,a==="scrollbar",s,o.isTopElement,o.isInViewport,!1,n,o.boundingRect?{topLeft:{x:o.boundingRect.x,y:o.boundingRect.y},topRight:{x:o.boundingRect.x+o.boundingRect.width,y:o.boundingRect.y},bottomLeft:{x:o.boundingRect.x,y:o.boundingRect.y+o.boundingRect.height},bottomRight:{x:o.boundingRect.x+o.boundingRect.width,y:o.boundingRect.y+o.boundingRect.height},center:{x:o.boundingRect.x+o.boundingRect.width/2,y:o.boundingRect.y+o.boundingRect.height/2},width:o.boundingRect.width,height:o.boundingRect.height}:null,null,null,[],r);if(i){let c=new ao(i,!0,l);l.children.push(c)}r.children.push(l),e.set(n,l),n++}return{domState:{elementTree:r,selectorMap:e},highlightIndex:n}}async renderHighlightsForAXElements(t,e){let r=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];await t.evaluate(({elements:n,colors:o})=>{let a="playwright-highlight-container",i=document.getElementById(a);i||(i=document.createElement("div"),i.id=a,i.style.position="fixed",i.style.pointerEvents="none",i.style.top="0",i.style.left="0",i.style.width="100%",i.style.height="100%",i.style.zIndex="2147483647",i.style.backgroundColor="transparent",document.body.appendChild(i)),n.forEach((s,l)=>{if(!s.boundingRect)return;let c=o[l%o.length],p=s.boundingRect,h=document.createElement("div");h.style.position="fixed",h.style.border=`1px solid ${c}`,h.style.backgroundColor="transparent",h.style.pointerEvents="none",h.style.boxSizing="border-box",h.style.top=`${p.y}px`,h.style.left=`${p.x}px`,h.style.width=`${p.width}px`,h.style.height=`${p.height}px`,i.appendChild(h);let g=document.createElement("div");g.style.position="fixed",g.style.background=c,g.style.color="white",g.style.padding="1px 4px",g.style.borderRadius="4px",g.style.fontSize=l>=100?"8px":"12px",g.textContent=String(l);let y=Math.max(0,p.y-16),S=Math.max(0,Math.min(p.x+p.width-20,window.innerWidth-25));g.style.top=`${y}px`,g.style.left=`${S}px`,i.appendChild(g)})},{elements:e,colors:r})}async removeHighlights(t){let e=()=>{let r=document.getElementById("playwright-highlight-container");r&&r.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(n=>n()),window._highlightCleanupFunctions=[])};try{await t.evaluate(e),ce.debug("\u2705 Highlights removed from page")}catch(r){ce.warn("Failed to remove highlights:",r.message)}for(let r of t.frames())if(r.url().startsWith("chrome-extension://"))try{await r.evaluate(e)}catch{}}async getCrossOriginIframes(t){let e=await t.locator("iframe").filter({hasNot:t.locator(":visible")}).evaluateAll(s=>s.map(l=>l.src)),r=s=>{try{let l=new URL(s);return["doubleclick.net","adroll.com","googletagmanager.com"].some(c=>l.hostname.includes(c))}catch{return!1}},n=t.url(),o=new URL(n).hostname,a=t.frames(),i=[];for(let s of a){let l=s.url();try{let c=new URL(l).hostname;c&&c!==o&&!e.includes(l)&&!r(l)&&i.push(l)}catch{continue}}return i}async buildDomTree(t,e,r,n,o,a,i,s="all"){if(await t.evaluate("1+1")!==2)throw new Error("The page cannot evaluate javascript code properly");if(e0(t.url()))return[new ar("body","",{},[],!1,!1,!1,!1,!1,!1,!1,null),new Map];let l={doHighlightElements:e,focusHighlightIndex:r,viewportExpansion:n,debugMode:!1,interactiveClassNames:o,alwaysHighlightFileInput:a,sameRectIoUThreshold:i,actionIntent:s,domTreeRoot:this.domTreeRoot};ce.debug(`\u{1F527} Starting JavaScript DOM analysis for ${t.url().slice(0,50)}...`);let c,p=null;if(this.useDomTreeTs&&e)try{let f={...l,phase:"boxes",grayscaleImage:null},b=await t.evaluate(({code:R,argsObj:O})=>new Function("return "+R)()(O),{code:this.jsCode,argsObj:f});ce.debug(`\u{1F4E6} Phase 1: Drew ${b.elementData?.length||0} bounding boxes`);let _=await t.screenshot({type:"png",fullPage:!1});ce.debug("\u{1F4F8} Captured screenshot with bounding boxes");let M=performance.now(),B=await Gh(_);p=B.pixels;let Z=Math.round(performance.now()-M);ce.debug(`\u{1F5BC}\uFE0F Generated grayscale image (${B.width}x${B.height}) in ${Z}ms`);let N={...l,phase:"labels",grayscaleImage:p,elementData:b.elementData};c=await t.evaluate(({code:R,argsObj:O})=>new Function("return "+R)()(O),{code:this.jsCode,argsObj:N}),c.map=b.map,c.rootId=b.rootId,c.highlightCount=b.highlightCount,c.perfMetrics=b.perfMetrics,ce.debug("\u2705 Phase 2: Labels placed using grayscale-based positioning")}catch(f){ce.warn("Two-phase rendering failed, falling back to legacy mode:",f.message),p=null;let b={...l,grayscaleImage:null};c=await t.evaluate(({code:_,argsObj:M})=>new Function("return "+_)()(M),{code:this.jsCode,argsObj:b}),ce.debug("\u2705 JavaScript DOM analysis completed (legacy mode)")}else try{c=await t.evaluate(({code:f,argsObj:b})=>new Function("return "+f)()(b),{code:this.jsCode,argsObj:l}),ce.debug("\u2705 JavaScript DOM analysis completed")}catch(f){throw ce.error("Error evaluating JavaScript:",f.message),f}if(!c||typeof c!="object")throw ce.error("JavaScript returned invalid result:",c),new Error("JavaScript DOM analysis returned invalid result");if(!c.map||!c.rootId)throw ce.error("JavaScript result missing map or rootId:",JSON.stringify(c,null,2)),new Error("JavaScript result missing required fields (map or rootId)");if(s!=="all"&&c.highlightCount===0){ce.debug(`\u26A0\uFE0F No elements matched intent '${s}', falling back to 'all'`);let f={...l,actionIntent:"all"};c=await t.evaluate(({code:b,argsObj:_})=>new Function("return "+b)()(_),{code:this.jsCode,argsObj:f})}let h=Object.entries(c.map).filter(([,f])=>f.tagName==="iframe");ce.debug(`\u{1F50D} [ext-iframe] Total iframe nodes in map: ${h.length}`);for(let[f,b]of h){let _=b;ce.debug(`\u{1F50D} [ext-iframe] iframe node id=${f} src=${_.attributes?.src} inaccessibleFrame=${_.inaccessibleFrame}`)}let g=t.frames();ce.debug(`\u{1F50D} [ext-iframe] Playwright frames count: ${g.length}`);for(let f of g)ce.debug(`\u{1F50D} [ext-iframe] Playwright frame url=${f.url()}`);let y=[];for(let[f,b]of Object.entries(c.map)){let _=b;_.inaccessibleFrame&&_.attributes?.src?.startsWith("chrome-extension://")&&y.push({nodeId:f,src:_.attributes.src})}if(ce.debug(`\u{1F50D} [ext-iframe] Inaccessible extension iframes found: ${y.length}`),y.length>0){ce.debug(`\u{1F50C} Found ${y.length} inaccessible extension iframe(s), processing via Playwright frames`);let f=-1;for(let b of Object.values(c.map)){let _=b;_.highlightIndex!=null&&(f=Math.max(f,_.highlightIndex))}ce.debug(`\u{1F50D} [ext-iframe] Main page max highlight index: ${f}`);for(let b=0;b<y.length;b++){let{nodeId:_,src:M}=y[b];ce.debug(`\u{1F50D} [ext-iframe] Processing extension iframe [${b}]: ${M}`);let B=(()=>{try{return new URL(M).origin}catch{return null}})(),Z=t.frames().find(N=>{if(N.url()===M)return!0;if(B)try{return new URL(N.url()).origin===B}catch{return!1}return!1});if(!Z){ce.debug(`\u26A0\uFE0F [ext-iframe] No Playwright frame found for extension iframe: ${M}`),ce.debug(`\u26A0\uFE0F [ext-iframe] Available frame URLs: ${t.frames().map(N=>N.url()).join(", ")}`);continue}ce.debug(`\u{1F50D} [ext-iframe] Found matching Playwright frame for: ${M} (frame url: ${Z.url()})`);try{let N={...l,initialHighlightIndex:f+1,domTreeRoot:"body"};ce.debug(`\u{1F50D} [ext-iframe] Running dom-tree in extension frame with initialHighlightIndex=${N.initialHighlightIndex}`);let R=await Z.evaluate(({code:Q,argsObj:X})=>new Function("return "+Q)()(X),{code:this.jsCode,argsObj:N});if(ce.debug(`\u{1F50D} [ext-iframe] frameEval result: map size=${Object.keys(R?.map??{}).length} rootId=${R?.rootId}`),!R?.map||!R.rootId){ce.debug("\u26A0\uFE0F [ext-iframe] frameEval missing map or rootId, skipping");continue}let O=Object.values(R.map).filter(Q=>Q.highlightIndex!=null);ce.debug(`\u{1F50D} [ext-iframe] Interactive elements in extension frame: ${O.length}`);for(let Q of O){let X=Q;ce.debug(`\u{1F50D} [ext-iframe] - <${X.tagName}> highlightIndex=${X.highlightIndex} text="${X.children?.length?"...":""}"`)}for(let Q of Object.values(R.map)){let X=Q;X.highlightIndex!=null&&(f=Math.max(f,X.highlightIndex))}let ee=`ext_${b}_`;for(let[Q,X]of Object.entries(R.map)){let W={...X};W.children&&(W.children=W.children.map(ue=>`${ee}${ue}`)),c.map[`${ee}${Q}`]=W}let E=c.map[_];E?(E.children=[...E.children||[],`${ee}${R.rootId}`],ce.debug(`\u{1F50D} [ext-iframe] Attached frame root to iframe node ${_}`)):ce.debug(`\u26A0\uFE0F [ext-iframe] iframe node ${_} not found in map`),ce.debug(`\u2705 Merged extension iframe content from: ${M}`)}catch(N){ce.warn(`Failed to process extension iframe ${M}:`,N)}}}if(c&&c.perfMetrics){let f=c.perfMetrics.nodeMetrics?.totalNodes??0,b=0;if(c.map)for(let M of Object.values(c.map))typeof M=="object"&&M!==null&&M.isInteractive&&b++;let _=t.url().length>50?t.url().slice(0,50)+"...":t.url();ce.debug(`\u{1F50E} Ran buildDOMTree.js interactive element detection on: ${_} interactive=${b}/${f}`)}ce.debug("\u{1F504} Starting TypeScript DOM tree construction...");let S=await this.constructDomTree(c);return ce.debug("\u2705 TypeScript DOM tree construction completed"),S}async constructDomTree(t){let e=t.map,r=t.rootId,n=new Map,o=new Map,a=new Map;for(let[s,l]of Object.entries(e)){let[c,p]=this.parseNode(l);c!==null&&(o.set(s,c),a.set(s,p),c instanceof ar&&c.highlightIndex!==null&&n.set(c.highlightIndex,c))}for(let[s,l]of a){let c=o.get(s);if(c instanceof ar)for(let p of l){let h=o.get(p);h&&(h.parent=c,c.children.push(h))}}let i=o.get(r);if(!i||!(i instanceof ar))throw new Error("Failed to parse HTML to dictionary");return[i,n]}parseNode(t){if(!t)return[null,[]];if(t.type==="TEXT_NODE")return[new ao(t.text,t.isVisible,null),[]];let e=null;t.viewport&&(e={width:t.viewport.width,height:t.viewport.height,scrollX:t.viewport.scrollX,scrollY:t.viewport.scrollY});let r=t.shadowHostXPaths??[],n=new ar(t.tagName,t.xpath,t.attributes||{},[],t.isVisible??!1,t.isInteractive??!1,t.isScrollable??!1,t.markAsClickable??!1,t.isTopElement??!1,t.isInViewport??!1,t.shadowRoot??!1,t.highlightIndex??null,t.viewportCoordinates??null,t.pageCoordinates??null,e,r,null),o=t.children||[];return[n,o]}};import{createHash as ul}from"crypto";var yO=class{static convertDomElementToHistoryElement(t){let e=this.getParentBranchPath(t),r=this.generateCssSelector(t);return{tagName:t.tagName,xpath:t.xpath,highlightIndex:t.highlightIndex,entireParentBranchPath:e,attributes:t.attributes,shadowRoot:t.shadowRoot,cssSelector:r,pageCoordinates:t.pageCoordinates,viewportCoordinates:t.viewportCoordinates,viewportInfo:t.viewportInfo}}static findHistoryElementInTree(t,e){let r=this.hashDomHistoryElement(t),n=o=>{if(o.highlightIndex!==null){let a=this.hashDomElement(o);if(this.compareHashes(a,r))return o}for(let a of o.children)if(a instanceof ar){let i=n(a);if(i!==null)return i}return null};return n(e)}static compareHistoryElementAndDomElement(t,e){let r=this.hashDomHistoryElement(t),n=this.hashDomElement(e);return this.compareHashes(r,n)}static hashDomHistoryElement(t){let e=this.parentBranchPathHash(t.entireParentBranchPath),r=this.attributesHash(t.attributes),n=this.xpathHash(t.xpath);return{branchPathHash:e,attributesHash:r,xpathHash:n}}static hashDomElement(t){let e=this.getParentBranchPath(t),r=this.parentBranchPathHash(e),n=this.attributesHash(t.attributes),o=this.xpathHash(t.xpath);return{branchPathHash:r,attributesHash:n,xpathHash:o}}static getParentBranchPath(t){let e=[],r=t;for(;r!==null&&r.parent!==null;)e.push(r),r=r.parent;return e.reverse(),e.map(n=>n.tagName)}static parentBranchPathHash(t){let e=t.join("/");return ul("sha256").update(e).digest("hex")}static attributesHash(t){let e=Object.entries(t).map(([r,n])=>`${r}=${n}`).join("");return ul("sha256").update(e).digest("hex")}static xpathHash(t){return ul("sha256").update(t).digest("hex")}static compareHashes(t,e){return t.branchPathHash===e.branchPathHash&&t.attributesHash===e.attributesHash&&t.xpathHash===e.xpathHash}static generateCssSelector(t){let e=t.attributes.id;if(e)return`#${e}`;let r=t.attributes.class;if(r){let n=r.split(/\s+/).filter(o=>o.trim());if(n.length>0)return`${t.tagName}.${n.join(".")}`}return t.tagName}};import{z as Or}from"zod/v4";import{z as yf}from"zod/v4";import{z as vl}from"zod/v4";import{z as We}from"zod/v4";import{z as Sa}from"zod/v4";import{z as Nt}from"zod/v4";import{z as ht}from"zod/v4";var Hf=Fa(gl(),1),qf=Fa(gl(),1);import{z as Re}from"zod";var x0="vercel.ai.gateway.error",yl=Symbol.for(x0),af,sf,Tt=class Of extends(sf=Error,af=yl,sf){constructor({message:e,statusCode:r=500,cause:n}){super(e),this[af]=!0,this.statusCode=r,this.cause=n}static isInstance(e){return Of.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&yl in e&&e[yl]===!0}},Nf="GatewayAuthenticationError",S0=`vercel.ai.gateway.error.${Nf}`,lf=Symbol.for(S0),cf,uf,Ca=class Mf extends(uf=Tt,cf=lf,uf){constructor({message:e="Authentication failed",statusCode:r=401,cause:n}={}){super({message:e,statusCode:r,cause:n}),this[cf]=!0,this.name=Nf,this.type="authentication_error"}static isInstance(e){return Tt.hasMarker(e)&&lf in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:a}){let i;return e?i=`AI Gateway authentication failed: Invalid API key.
|
|
3954
3954
|
|
|
3955
3955
|
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
3956
3956
|
|
|
@@ -3977,7 +3977,7 @@ Learn more: \x1B[34m${r}\x1B[0m
|
|
|
3977
3977
|
|
|
3978
3978
|
`)},flush(t){t.enqueue(`data: [DONE]
|
|
3979
3979
|
|
|
3980
|
-
`)}})}};var XM=q(()=>H(L.union([L.strictObject({type:L.literal("text-start"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("text-delta"),id:L.string(),delta:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("text-end"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("error"),errorText:L.string()}),L.strictObject({type:L.literal("tool-input-start"),toolCallId:L.string(),toolName:L.string(),providerExecuted:L.boolean().optional(),dynamic:L.boolean().optional(),title:L.string().optional()}),L.strictObject({type:L.literal("tool-input-delta"),toolCallId:L.string(),inputTextDelta:L.string()}),L.strictObject({type:L.literal("tool-input-available"),toolCallId:L.string(),toolName:L.string(),input:L.unknown(),providerExecuted:L.boolean().optional(),providerMetadata:he.optional(),dynamic:L.boolean().optional(),title:L.string().optional()}),L.strictObject({type:L.literal("tool-input-error"),toolCallId:L.string(),toolName:L.string(),input:L.unknown(),providerExecuted:L.boolean().optional(),providerMetadata:he.optional(),dynamic:L.boolean().optional(),errorText:L.string(),title:L.string().optional()}),L.strictObject({type:L.literal("tool-approval-request"),approvalId:L.string(),toolCallId:L.string()}),L.strictObject({type:L.literal("tool-output-available"),toolCallId:L.string(),output:L.unknown(),providerExecuted:L.boolean().optional(),dynamic:L.boolean().optional(),preliminary:L.boolean().optional()}),L.strictObject({type:L.literal("tool-output-error"),toolCallId:L.string(),errorText:L.string(),providerExecuted:L.boolean().optional(),dynamic:L.boolean().optional()}),L.strictObject({type:L.literal("tool-output-denied"),toolCallId:L.string()}),L.strictObject({type:L.literal("reasoning-start"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("reasoning-delta"),id:L.string(),delta:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("reasoning-end"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("source-url"),sourceId:L.string(),url:L.string(),title:L.string().optional(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("source-document"),sourceId:L.string(),mediaType:L.string(),title:L.string(),filename:L.string().optional(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("file"),url:L.string(),mediaType:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.custom(t=>typeof t=="string"&&t.startsWith("data-"),{message:'Type must start with "data-"'}),id:L.string().optional(),data:L.unknown(),transient:L.boolean().optional()}),L.strictObject({type:L.literal("start-step")}),L.strictObject({type:L.literal("finish-step")}),L.strictObject({type:L.literal("start"),messageId:L.string().optional(),messageMetadata:L.unknown().optional()}),L.strictObject({type:L.literal("finish"),finishReason:L.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:L.unknown().optional()}),L.strictObject({type:L.literal("abort"),reason:L.string().optional()}),L.strictObject({type:L.literal("message-metadata"),messageMetadata:L.unknown()})])));var ZM=cr({prefix:"aitxt",size:24});var t1=q(()=>H(w.array(w.object({id:w.string(),role:w.enum(["system","user","assistant"]),metadata:w.unknown().optional(),parts:w.array(w.union([w.object({type:w.literal("text"),text:w.string(),state:w.enum(["streaming","done"]).optional(),providerMetadata:he.optional()}),w.object({type:w.literal("reasoning"),text:w.string(),state:w.enum(["streaming","done"]).optional(),providerMetadata:he.optional()}),w.object({type:w.literal("source-url"),sourceId:w.string(),url:w.string(),title:w.string().optional(),providerMetadata:he.optional()}),w.object({type:w.literal("source-document"),sourceId:w.string(),mediaType:w.string(),title:w.string(),filename:w.string().optional(),providerMetadata:he.optional()}),w.object({type:w.literal("file"),mediaType:w.string(),filename:w.string().optional(),url:w.string(),providerMetadata:he.optional()}),w.object({type:w.literal("step-start")}),w.object({type:w.string().startsWith("data-"),id:w.string().optional(),data:w.unknown()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("input-streaming"),input:w.unknown().optional(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),approval:w.never().optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("input-available"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.never().optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("approval-requested"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.never().optional(),reason:w.never().optional()})}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("approval-responded"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.boolean(),reason:w.string().optional()})}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("output-available"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.unknown(),errorText:w.never().optional(),callProviderMetadata:he.optional(),preliminary:w.boolean().optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("output-error"),input:w.unknown(),rawInput:w.unknown().optional(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.string(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("output-denied"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!1),reason:w.string().optional()})}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("input-streaming"),providerExecuted:w.boolean().optional(),input:w.unknown().optional(),output:w.never().optional(),errorText:w.never().optional(),approval:w.never().optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("input-available"),providerExecuted:w.boolean().optional(),input:w.unknown(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.never().optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("approval-requested"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.never().optional(),reason:w.never().optional()})}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("approval-responded"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.boolean(),reason:w.string().optional()})}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("output-available"),providerExecuted:w.boolean().optional(),input:w.unknown(),output:w.unknown(),errorText:w.never().optional(),callProviderMetadata:he.optional(),preliminary:w.boolean().optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("output-error"),providerExecuted:w.boolean().optional(),input:w.unknown(),rawInput:w.unknown().optional(),output:w.never().optional(),errorText:w.string(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("output-denied"),providerExecuted:w.boolean().optional(),input:w.unknown(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!1),reason:w.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var n1=cr({prefix:"aiobj",size:24});var a1=cr({prefix:"aiobj",size:24});var yC="AI_NoSuchProviderError",vC=`vercel.ai.error.${yC}`,bC=Symbol.for(vC),_C;_C=bC;export{cg as a,EC as b,WR as c,JR as d,rC as e,zM as f,cl as g,
|
|
3980
|
+
`)}})}};var XM=q(()=>H(L.union([L.strictObject({type:L.literal("text-start"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("text-delta"),id:L.string(),delta:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("text-end"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("error"),errorText:L.string()}),L.strictObject({type:L.literal("tool-input-start"),toolCallId:L.string(),toolName:L.string(),providerExecuted:L.boolean().optional(),dynamic:L.boolean().optional(),title:L.string().optional()}),L.strictObject({type:L.literal("tool-input-delta"),toolCallId:L.string(),inputTextDelta:L.string()}),L.strictObject({type:L.literal("tool-input-available"),toolCallId:L.string(),toolName:L.string(),input:L.unknown(),providerExecuted:L.boolean().optional(),providerMetadata:he.optional(),dynamic:L.boolean().optional(),title:L.string().optional()}),L.strictObject({type:L.literal("tool-input-error"),toolCallId:L.string(),toolName:L.string(),input:L.unknown(),providerExecuted:L.boolean().optional(),providerMetadata:he.optional(),dynamic:L.boolean().optional(),errorText:L.string(),title:L.string().optional()}),L.strictObject({type:L.literal("tool-approval-request"),approvalId:L.string(),toolCallId:L.string()}),L.strictObject({type:L.literal("tool-output-available"),toolCallId:L.string(),output:L.unknown(),providerExecuted:L.boolean().optional(),dynamic:L.boolean().optional(),preliminary:L.boolean().optional()}),L.strictObject({type:L.literal("tool-output-error"),toolCallId:L.string(),errorText:L.string(),providerExecuted:L.boolean().optional(),dynamic:L.boolean().optional()}),L.strictObject({type:L.literal("tool-output-denied"),toolCallId:L.string()}),L.strictObject({type:L.literal("reasoning-start"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("reasoning-delta"),id:L.string(),delta:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("reasoning-end"),id:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("source-url"),sourceId:L.string(),url:L.string(),title:L.string().optional(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("source-document"),sourceId:L.string(),mediaType:L.string(),title:L.string(),filename:L.string().optional(),providerMetadata:he.optional()}),L.strictObject({type:L.literal("file"),url:L.string(),mediaType:L.string(),providerMetadata:he.optional()}),L.strictObject({type:L.custom(t=>typeof t=="string"&&t.startsWith("data-"),{message:'Type must start with "data-"'}),id:L.string().optional(),data:L.unknown(),transient:L.boolean().optional()}),L.strictObject({type:L.literal("start-step")}),L.strictObject({type:L.literal("finish-step")}),L.strictObject({type:L.literal("start"),messageId:L.string().optional(),messageMetadata:L.unknown().optional()}),L.strictObject({type:L.literal("finish"),finishReason:L.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:L.unknown().optional()}),L.strictObject({type:L.literal("abort"),reason:L.string().optional()}),L.strictObject({type:L.literal("message-metadata"),messageMetadata:L.unknown()})])));var ZM=cr({prefix:"aitxt",size:24});var t1=q(()=>H(w.array(w.object({id:w.string(),role:w.enum(["system","user","assistant"]),metadata:w.unknown().optional(),parts:w.array(w.union([w.object({type:w.literal("text"),text:w.string(),state:w.enum(["streaming","done"]).optional(),providerMetadata:he.optional()}),w.object({type:w.literal("reasoning"),text:w.string(),state:w.enum(["streaming","done"]).optional(),providerMetadata:he.optional()}),w.object({type:w.literal("source-url"),sourceId:w.string(),url:w.string(),title:w.string().optional(),providerMetadata:he.optional()}),w.object({type:w.literal("source-document"),sourceId:w.string(),mediaType:w.string(),title:w.string(),filename:w.string().optional(),providerMetadata:he.optional()}),w.object({type:w.literal("file"),mediaType:w.string(),filename:w.string().optional(),url:w.string(),providerMetadata:he.optional()}),w.object({type:w.literal("step-start")}),w.object({type:w.string().startsWith("data-"),id:w.string().optional(),data:w.unknown()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("input-streaming"),input:w.unknown().optional(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),approval:w.never().optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("input-available"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.never().optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("approval-requested"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.never().optional(),reason:w.never().optional()})}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("approval-responded"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.boolean(),reason:w.string().optional()})}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("output-available"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.unknown(),errorText:w.never().optional(),callProviderMetadata:he.optional(),preliminary:w.boolean().optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("output-error"),input:w.unknown(),rawInput:w.unknown().optional(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.string(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.literal("dynamic-tool"),toolName:w.string(),toolCallId:w.string(),state:w.literal("output-denied"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!1),reason:w.string().optional()})}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("input-streaming"),providerExecuted:w.boolean().optional(),input:w.unknown().optional(),output:w.never().optional(),errorText:w.never().optional(),approval:w.never().optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("input-available"),providerExecuted:w.boolean().optional(),input:w.unknown(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.never().optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("approval-requested"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.never().optional(),reason:w.never().optional()})}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("approval-responded"),input:w.unknown(),providerExecuted:w.boolean().optional(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.boolean(),reason:w.string().optional()})}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("output-available"),providerExecuted:w.boolean().optional(),input:w.unknown(),output:w.unknown(),errorText:w.never().optional(),callProviderMetadata:he.optional(),preliminary:w.boolean().optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("output-error"),providerExecuted:w.boolean().optional(),input:w.unknown(),rawInput:w.unknown().optional(),output:w.never().optional(),errorText:w.string(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!0),reason:w.string().optional()}).optional()}),w.object({type:w.string().startsWith("tool-"),toolCallId:w.string(),state:w.literal("output-denied"),providerExecuted:w.boolean().optional(),input:w.unknown(),output:w.never().optional(),errorText:w.never().optional(),callProviderMetadata:he.optional(),approval:w.object({id:w.string(),approved:w.literal(!1),reason:w.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var n1=cr({prefix:"aiobj",size:24});var a1=cr({prefix:"aiobj",size:24});var yC="AI_NoSuchProviderError",vC=`vercel.ai.error.${yC}`,bC=Symbol.for(vC),_C;_C=bC;export{cg as a,EC as b,WR as c,JR as d,rC as e,zM as f,cl as g,xa as h,Jh as i,Kh as j,oO as k,aO as l,iO as m,pO as n,yO as o};
|
|
3981
3981
|
/*! Bundled license information:
|
|
3982
3982
|
|
|
3983
3983
|
safe-buffer/index.js:
|