@github/copilot 0.0.354-25 → 0.0.354-27
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/index.js +4 -4
- package/package.json +2 -2
- package/sdk/index.js +3 -3
package/index.js
CHANGED
|
@@ -1756,7 +1756,7 @@ ${t}
|
|
|
1756
1756
|
<reminder>
|
|
1757
1757
|
The user may have mentioned images, if so these will have been attached to this message, in the order they were mentioned
|
|
1758
1758
|
</reminder>`),n.trim()},PEe={completeAsSoonAsPossible:"You will soon run out of iterations. Begin making your final code changes. Complete any code changes that are still pending instead of performing validations.",commitNow:"You are imminently out of iterations. Call **report_progress** detailing your current progress. After doing so, provide a final answer as soon as possible.",finalAnswerNeeded:"You have reached the maximum number of iterations. Consider your work completed. I no longer need more changes. Please provide a final answer."},wvt=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${Use(t)}. Commit changes by using the **report_progress** tool.</reminder>`;function Qvt(t){try{if(t)typeof t=="string"&&(t=JSON.parse(t));else return"no_messages";let e=t.map(l=>{let n="?";switch(l.role){case"system":n="s";break;case"assistant":n="a";break;case"user":n="u";break;case"tool":n="t";break}return{type:n,tool_call_id:l.role!=="tool"?void 0:l.tool_call_id,reasoning_text:l.role!=="assistant"?void 0:!!l.reasoning_text,content:typeof l.content=="string"?["text"]:l.content?.map(r=>r.type),tool_calls:l.role!=="assistant"?void 0:l.tool_calls?l.tool_calls.map(r=>r.id):[]}});return JSON.stringify(e,null,2)}catch{return"failed_to_summarize"}}function Z6(t){let e=t.reasoning_text?.replace(/<\|im_sep\|>(\*\*.*?\*\*)?/g,`
|
|
1759
|
-
`)?.trim();return{...t,reasoning_text:e}}function _se(t){return structuredClone(t)}function Fvt(t){return{...t,choices:t.choices.map(e=>{let l=Z6(e.message);return{delta:{role:l.role,content:l.content,reasoning_opaque:l.reasoning_opaque,reasoning_text:l.reasoning_text,tool_calls:e.message.tool_calls?.map(n=>({...n,index:0}))},finish_reason:e.finish_reason,index:e.index}}),object:"chat.completion.chunk"}}function _4(t){return t.role==="user"&&Array.isArray(t.content)&&t.content.some(e=>e.type==="image_url")}function Cvt(t,e){let l=e.indexOf(t);if(l!==-1)return l;let n=s=>(typeof s.content=="string"?[{type:"text",text:s.content}]:s.content).filter(o=>o.type==="text").map(o=>o.text).join("").trim(),r=n(t),a=e.map((s,o)=>s.role==="user"&&n(s)===r?o:-1).filter(s=>s!==-1),I=a.at(0)??-1;return a.length===1?I:-1}var JUe="/tmp/playwright-logs",qrn="0.0.40",xUe=[`@playwright/mcp@${qrn}`,"--viewport-size","1280, 720","--output-dir",JUe],pma=[...xUe,"--isolated"];var hMe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},p0e;async function PXt(){if(p0e)return p0e;try{return p0e=(await Promise.resolve().then(()=>$e(DXt(),1))).default,p0e}catch{}}var noe=2e3;async function cin(t,e,l,n){let r={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},a=`${NZt(n)}/${t}`;l.info(`Downloading image from ${a}`);try{let I=await fetch(a,{method:"GET",headers:r});if(l.info(`Response status: ${I.status} ${I.statusText}`),l.debug(`Download Response URL: ${I.url}`),!I.ok){l.info(`Failed to download image, status: ${I.status}, statusText: ${I.statusText}`);try{let b=await I.text();l.info(`Error response body: ${b}`)}catch(b){l.info(`Could not read error response body: ${b}`)}return{size:0}}let o=(await I.json()).url;if(!o)return l.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let c=await fetch(o,{method:"GET"});if(!c.ok)return l.error(`Failed to download image: ${c.status} ${c.statusText}`),{size:0};let d=await c.arrayBuffer(),m=d.byteLength;return l.info(`Downloaded content size: ${YE(m)}`),{size:m,buffer:Buffer.from(d),mimeType:c.headers.get("content-type")||void 0}}catch(I){return l.error("Network error downloading image"),I instanceof Error&&(l.info(`Error message: ${I.message}`),l.info(`Error stack: ${I.stack}`)),{size:0}}}function AMe(t,e,l,n){let r=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,a=/!\[.*?\]\((.*?)\)/g,I=[];return I.push(...zXt(t,e,r,l,n)),I.push(...zXt(t,e,a,l,n)),I}function zXt(t,e,l,n,r){let a=t.matchAll(l),I=[],s=/\/([a-f0-9-]+)$/;for(let o of a){let c=bin(o[1],e),d=Gin(o[1],e,r);if(c||d){let m=o[1].match(s),b={url:o[1],guid:"",kind:d?"legacy_attachment":"attachment"};m&&m.length>1&&(b.guid=m[1]),I.push(b)}else if(n){let m={url:o[1],guid:"",kind:"committed_attachment"};I.push(m)}}return I}function din(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&soe(t)}function soe(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function uin(t){try{let e=/Here are relevant code snippets from the repository that might help with this task:\s*(\[[\s\S]*?\])(?=\n|$)/,l=t.match(e);if(!l?.[1]||l[1].length<=1)return null;let n=l[1].trim();return JSON.parse(n)}catch{return null}}function min(t,e,l){if(!t?.url||!t?.ref||!t?.path)throw new Error("Invalid repository insight: missing required fields");if(!e||e.trim()==="")throw new Error("Invalid image path: path cannot be empty");let n=t.url.split("/").slice(3,5).join("/"),r=t.ref.split("/")[2],a;if(e.startsWith("/"))a=e.slice(1);else{let s=t.path,o=roe.dirname(s);a=roe.resolve("/",o,e).slice(1)}return`${l}/${n}/blob/${r}/${a}`}function bin(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function Gin(t,e,l){return e&&new RegExp(`^${e}/[\\w.-]+/[\\w.-]+/assets/\\d+/[^.]+$`).test(t)?(l.debug(`Legacy GitHub asset URL detected: ${t}`),!0):!1}async function ZMe(t){let{width:e,height:l}=Wft(t);if(e===void 0||l===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:l}}async function h0e(t,e,l,n,r,a){t.debug(`Checking if image is valid size and dimensions. Max size: ${l}, Max dimension: ${n}`);let{exceedsSizeLimit:I,exceedsDimensionLimit:s}=await aoe(l,n,a);if(!s&&!I)return t.debug("Image is within size and dimension limits."),a;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${n}, attempting to resize`);let[o,c]=await Ain(t,a,n,l,r);if(!o){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,c==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:d}=await aoe(l,n,o);if(d){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),o}if(I){t.debug(`Image size ${YE(a.length)} is larger than the maximum size of ${YE(l)}, attempting to reduce image quality`);let o=await gin(t,a,n,l,r);if(!o){t.debug("Failed to reduce image quality to fit within the maximum size, skipping"),e.imagesFailedToReduceQuality++,e.imagesRemovedDueToSize++;return}return e.imagesWithLoweredQuality++,t.debug("Image quality successfully reduced."),o}}async function aoe(t,e,l){let n=await ZMe(l),r=l.length;return!n.width||!n.height?{exceedsSizeLimit:r>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await hin(t,l),exceedsDimensionLimit:await pin(e,l)}}async function pin(t,e){let l=await ZMe(e);return!l.width||!l.height?!1:l.width>t||l.height>t}async function hin(t,e){return e.length>t}async function Ain(t,e,l,n,r){try{if(!jXt(t,r))return[void 0,"unsupported_mime_type"];let a=await ZMe(e);if(!a.width||!a.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let I=async(W,R)=>{let V=await PXt();if(!V)return;let f=V(e).resize(W,R,{fit:"inside",withoutEnlargement:!0});return gMe(t,await f.toBuffer(),void 0,r)},s=Math.min(l,a.width),o=Math.min(l,a.height),c=await I(s,o);if(c&&c.length<=n)return[c,void 0];let d=Math.max(s,o),m=1,b=d-1,p,A=0,Z=10;for(;m<=b&&A<Z;){let W=Math.floor((m+b)/2),R=await I(W,W);if(!R)break;let{exceedsSizeLimit:V,exceedsDimensionLimit:f}=await aoe(n,l,R);!V&&!f?(p=R,m=W+1):b=W-1,A++}return[p,void 0]}catch(a){return t.error(`Failed to resize image for upload: ${a instanceof Error?a.message:String(a)}`),[void 0,"unknown"]}}async function gin(t,e,l,n,r){try{let a=r==="image/png"?80:100,I=r==="image/png"?Math.floor(a*.4):20,s=await gMe(t,e,I,r);if(!s||s.length>n)return;let o=I,c=a,d,m=0,b=10,p=o,A=c-1;for(;p<=A&&m<b;){let Z=Math.floor((p+A)/2),W=await gMe(t,e,Z,r);if(!W)return d;let{exceedsSizeLimit:R,exceedsDimensionLimit:V}=await aoe(n,l,W);!R&&!V?(d=W,p=Z+1):A=Z-1,m++}return d}catch(a){t.error(`Failed to reduce image quality: ${a instanceof Error?a.message:String(a)}`);return}}async function gMe(t,e,l,n){let r=await PXt();if(!r)return;let a=r(e);switch(n){case"image/png":return l?a.png({quality:l}).toBuffer():a.png().toBuffer();case"image/jpeg":return l?a.jpeg({quality:l}).toBuffer():a.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${n}`);return}}var Ioe=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function Zin(t,e,l,n){if(e<=0)return[];let r=[];for(let a of t){if(a.role!=="user"||r.length>=e)continue;let I=typeof a.content=="string"?a.content:JSON.stringify(a.content),s=uin(I);if(s)for(let o in s){if(r.length>=e)break;let c=s[o].contents,d=AMe(c,l,!0,n);for(let m of d){if(r.length>=e)break;let b=m.url,p="",A=!1;if(m.kind==="attachment"||m.kind==="legacy_attachment"?r.push(m):din(b)?(A=!0,p=min(s[o],b,l),r.push({url:p,guid:m.guid,kind:"committed_attachment"})):soe(b)&&b.startsWith(l)&&(A=!0,r.push({...m,kind:"committed_attachment"})),A){let Z=r[r.length-1],W=new RegExp(`^${l}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),R=Z.url.match(W);if(n.info(`Blob match for ${Z.url}: ${JSON.stringify(R)}`),R&&R.length===5){let[,V,f,X,S]=R;Z.owner=V,Z.repo=f,Z.branch=X,Z.path=S,n.info(`Repository metadata extracted: owner=${V}, repo=${f}, branch=${X}, path=${S}`)}else n.info(`Failed to extract repository metadata from URL: ${Z.url}`)}}}}return r}function Nin(t,e){let l=e.flatMap(r=>_4(r)?r.content.flatMap(a=>a.type==="image_url"?a.image_url.url:[]):[]),n=new Set(l);return t.filter(r=>!n.has(r.url))}var A0e=class{async resolveRepositoryImages(e,l,n,r,a,I){if(l<=0)return[];let s=Zin(e,l,n,r);this.logger.debug(`Found ${s.length} repository image URLs to process`);let o=Nin(s,e),c=await this.processImageReferences(o,a,I);return this.logger.debug(`Processed ${c.addedImages.length} repository image URLs`),c.addedImages}async*preRequest(e){let l=e.modelInfo;if(!l.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!l.capabilities?.supports?.vision||!this.settings.featureFlags?.copilot_swe_agent_vision){this.logger.debug("Vision not supported or enabled, skipping image processing");return}if(!this.gitHubServerUrl){this.logger.debug("GitHub server URL is not set, skipping image processing");return}for(let m of this.messagesToInsertOnNextPreRequest)e.messages.push(m),yield{kind:"message",turn:e.turn,callId:e.callId,message:m};this.messagesToInsertOnNextPreRequest.splice(0);let n=[],r=l.capabilities.limits.vision?.max_prompt_images??1,a=l.capabilities.limits.vision?.max_prompt_image_size??3145728,I=0,s=[],o=new Ioe,c=new Map;for(let m of e.messages)if(m.role=="user")if(typeof m.content=="string"){let b=AMe(m.content,this.gitHubServerUrl,!1,this.logger).filter(A=>!this.processedImageUrls.has(A.url)),p=await this.processImageReferences(b,a,o);s.push(...p.addedImages)}else{let b=[];for(let[p,A]of m.content.entries()){if(A.type==="text"){let Z=AMe(A.text,this.gitHubServerUrl,!1,this.logger).filter(R=>!this.processedImageUrls.has(R.url)),W=await this.processImageReferences(Z,a,o);s.push(...W.addedImages)}else if(A.type==="image_url"){if(A.image_url.url.startsWith("data:")){let[Z,W]=await this.extractAndUploadImageData(A,a,o);if(Z===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(Z),p>=1&&b.length>0){let R=b.at(-1);R&&R.type==="text"&&R.text&&R.text.includes("screenshot")&&c.set(Z,Vvt(Z))}b.pop();continue}I++}b.push(A)}m.content=b}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${r}`);I<r&&s.length>0;){let m=s.shift();if(!m){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(m)){this.logger.debug(`Skipping already processed image url: ${m}`);continue}this.processedImageUrls.add(m);let b=`Here is the image url: ${m}`;c.has(m)&&(b=c.get(m)||b),this.logger.debug(`Adding image url: ${m}`),n.push({role:"user",content:[{type:"text",text:b},{type:"image_url",image_url:{url:m}}]}),I++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),I<r)){let m=await this.resolveRepositoryImages(e.messages,r-I,this.settings.github?.serverUrl||"",this.logger,a,o);this.logger.debug(`Resolved ${m.length} repository image URLs`);for(let b of m){if(I>=r)break;if(this.processedImageUrls.has(b)){this.logger.debug(`Skipping already processed repository image url: ${b}`);continue}n.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:b}}]}),this.processedImageUrls.add(b),I++}}let d={imagesExtractedCount:o.extractedImagesSize.length,base64ImagesCount:o.base64ImagesSize.length,imagesRemovedDueToSize:o.imagesRemovedDueToSize,imagesRemovedDueToDimensions:o.imagesRemovedDueToDimensions,imagesResized:o.imagesResized,imagesResolvedFromGitHubMCPCount:o.imagesResolvedFromGitHubMCPSize.length};for(let m=0;m<o.base64ImagesSize.length;m++)d[`base64ImageSize_${m}`]=o.base64ImagesSize[m];for(let m=0;m<o.resizedBase64ImagesSize.length;m++)d[`resizedBase64ImageSize_${m}`]=o.resizedBase64ImagesSize[m];for(let m=0;m<o.extractedImagesSize.length;m++)d[`extractedImageSize_${m}`]=o.extractedImagesSize[m];for(let m=0;m<o.imagesResolvedFromGitHubMCPSize.length;m++)d[`imagesResolvedFromGitHubMCPSize_${m}`]=o.imagesResolvedFromGitHubMCPSize[m];n.length>0&&this.logger.debug(`Using ${n.length} image messages`);for(let m of n)yield{kind:"message",turn:e.turn,callId:e.callId,message:m},e.messages.push(m);d.allImagesSendToLlm=e.messages.filter(_4).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:d},e.messages.some(m=>_4(m))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,l,n){let r=Pte(this.settings);if(!r)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let a=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!a||a.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let I=a[1];if(!jXt(this.logger,I))return[""];let s=a[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let o=Buffer.from(s,"base64");if(n.base64ImagesSize.push(o.length),o=await h0e(this.logger,n,l,noe,I,o),n.resizedBase64ImagesSize.push(o?.length??-1),!o)return["",new hMe(`Image size exceeds maximum size of ${YE(l)}`)];s=o.toString("base64");try{let c=await this.uploadBase64ImageData(s,I,r);return c?(this.logger.debug(`Uploaded image url: ${c}`),e.image_url.url=c,[c]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(c){let d=c instanceof Error?c.message:String(c);return this.logger.debug(`Error during image upload: ${d}`),[""]}}async uploadBase64ImageData(e,l,n){try{let r=ZZt(this.settings),a=l.split("/").at(1),I=`image-${Date.now()}.${a}`;if(!e||e.trim()==="")return this.logger.error("Empty image data provided for upload"),null;let s=Buffer.from(e,"base64");if(s.length===0)return this.logger.error("Converted image data has zero length"),null;let o=this.settings.github?.repo?.id;if(!o)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let c=`${r}?name=${encodeURIComponent(I)}&content_type=${encodeURIComponent(l)}&repository_id=${o}`;this.logger.debug(`Uploading image data (${YE(s.length)}) to ${r} with name ${encodeURIComponent(I)} and content type ${encodeURIComponent(l)}`);let d={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+n},m=await fetch(c,{method:"POST",headers:d,body:s}).catch(p=>{throw p instanceof Error?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof p=="object"&&p!==null&&"code"in p&&"message"in p?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):this.logger.error(`Failed to upload image: ${String(p)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:p?.code,message:p?.message,stack:p?.stack,name:p?.name,cause:p?.cause},null,2)}`),p});if(!m.ok){let p=await m.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${m.status} ${m.statusText} - ${p}`),null}let b=await m.json();return this.logger.debug(`Upload result: ${JSON.stringify(b,null,2)}`),b.url||null}catch(r){return this.logger.error(`Error handling image upload: ${r instanceof Error?r.message:String(r)}`),r instanceof Error&&r.stack&&this.logger.debug(`Stack trace: ${r.stack}`),null}}async getRepositoryImageViaTools(e){if(this.logger.debug(`Attempting to retrieve repository image: ${e.owner}/${e.repo}/${e.path}@${e.branch}`),this.githubGetFileContentsTool){this.logger.debug(`GitHub MCP tool found, calling with image reference: ${JSON.stringify(e)}`);try{let l=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{toolCallId:crypto.randomUUID(),settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof l}`),this.logger.debug(`GitHub tool call result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`),typeof l=="object"&&l!==null&&"binaryResultForLlm"in l&&Array.isArray(l.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${l.binaryResultForLlm.length} items`);try{for(let n of l.binaryResultForLlm)if(n.data&&n.mimeType){let r=Buffer.from(n.data,"base64"),a=n.mimeType;return{buffer:r,mimeType:a}}}catch(n){this.logger.error(`Failed to parse GitHub tool response: ${n}`),this.logger.debug(`binaryResultForLlm length: ${l.binaryResultForLlm?.length||0}`)}}else typeof l=="string"?this.logger.debug(`GitHub tool returned string result: ${l}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`)}catch(l){this.logger.error(`Error calling GitHub MCP tool: ${l}`)}}else this.logger.debug("GitHub MCP tool 'github-mcp-server-get_file_contents' not available");return this.logger.debug("Failed to retrieve repository image, returning null"),null}async getImgRefsSmallerThanMaxSize(e,l,n){let r=[],a=await Promise.all(e);for(let{imgRef:I,attachment:s}of a)if(this.logger.debug(`Processing attachment for ${I.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(l.extractedImagesSize.push(s.buffer.length),to(this.settings,"copilot_swe_agent_resize_image_references")){if(!await h0e(this.logger,l,n,noe,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}r.push(I.url)}else{let o=await aoe(n,noe,s.buffer);if(this.logger.debug(`Image size check for ${I.url}: size=${s.buffer.length}, maxSize=${n}, exceedsSize=${o.exceedsSizeLimit}, exceedsDimensions=${o.exceedsDimensionLimit}`),o.exceedsSizeLimit?(l.imagesRemovedDueToSize++,this.logger.debug(`Image ${I.url} removed due to size (${s.buffer.length} > ${n})`)):o.exceedsDimensionLimit&&(l.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${I.url} removed due to dimensions`)),o.exceedsSizeLimit||o.exceedsDimensionLimit){this.processedImageUrls.add(I.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${YE(n)}.`);continue}r.push(I.url),this.logger.debug(`Image ${I.url} passed size checks and added to results`)}else this.processedImageUrls.add(I.url),this.logger.debug(`Skipping image ${I.url} - could not fetch image data`);return r}async processImageReferences(e,l,n){let r=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${r}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let a=e.filter(s=>!this.processedImageUrls.has(s.url)).map(async s=>{if(this.logger.debug(`Processing image reference: ${JSON.stringify(s,null,2)}`),s.kind==="committed_attachment"){this.logger.debug(`Detected repository image - Owner: ${s.owner}, Repo: ${s.repo}, Branch: ${s.branch}, Path: ${s.path}`);let o=await this.getRepositoryImageViaTools(s);return o?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${o.buffer.length} bytes`),n.imagesResolvedFromGitHubMCPSize.push(o.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:o?.buffer?.length||0,mimeType:o?.mimeType||"",buffer:o?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await cin(s.guid,Pte(this.settings),this.logger,this.settings)}}),I=await this.getImgRefsSmallerThanMaxSize(a,n,l);return this.logger.debug(`Processed image references, found ${I.length} attachments smaller than max size of ${YE(l)}`),{addedImages:I}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,l,n){this.logger=e,this.settings=l,this.gitHubServerUrl=l.github?.serverUrl,this.githubGetFileContentsTool=n,this.processedImageUrls=new Set,this.messagesToInsertOnNextPreRequest=[]}toJSON(){return"CAPIImageProcessor"}async onRequestError(e){}async preErrorThrow(e){this.processedImageUrls.size>0&&(e.isVisionFlow=!0)}async postToolExecution(e){let l=e.modelInfo,n=e.toolCall.function.name,r=e.toolResult;if(l?.capabilities?.supports?.vision){let a=Array.from(Win(r,n));if(a.length===0){let I=await Rin(e.toolCall,this.logger);I&&a.push(I)}this.insertImageUrlMessages(a)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let l of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:l.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:l.url}}]})}},g0e=class{async*preRequest(e){e.messages.some(l=>_4(l))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}toJSON(){return"VisionEnabledProcessor"}};function*Win(t,e){for(let l of t.binaryResultForLlm??[])l.type==="image"&&(yield{url:`data:${l.mimeType};base64,${l.data}`,isScreenshot:e.toLowerCase().includes("screenshot")})}var yin="playwright-browser_take_screenshot";function Ein(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function Rin(t,e){if(t.function.name!==yin)return;e.debug("Adding images using Playwright params fallback strategy");let l=JSON.parse(t.function.arguments);if(Ein(l)){let n=roe.isAbsolute(l.filename)?l.filename:roe.join(JUe,l.filename);e.debug(`Image from Playwright params: ${l.filename}. Updated to ${n}.`);let r=await Vin(n,e);if(r){let a=r.buffer.toString("base64");return{url:`data:${r.mimeType};base64,${a}`,isScreenshot:!0}}}}function Yin(t){switch(roe.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function jXt(t,e){return e!=="image/png"&&e!=="image/jpeg"?(t.debug(`Unsupported content type: ${e}, only image / png and image / jpeg are supported`),!1):!0}async function Vin(t,e){try{if(!soe(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let l=Yin(t);return l?{buffer:await iin.readFile(t),mimeType:l}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(l){return e.error(`Failed to read image from disk: ${l instanceof Error?l.message:String(l)}`),null}}var q4=class t{static DEFAULT_TOKEN_LIMIT=128e3;static DEFAULT_TOKEN_LIMIT_BUFFER=0;static MAX_TOKEN_LIMIT_BUFFER=.5;latestUserPromptMessage;logger;modelToTokenLimit;constructor(e,l){this.latestUserPromptMessage=e,this.logger=l,this.modelToTokenLimit=new Map}toJSON(){return"BasicTruncator"}async*preRequest(e){this.initializeStateForModelOnFirstRequest(e);let l=this.modelToTokenLimit.get(e.modelInfo.name),n=l?.tokenLimit??t.DEFAULT_TOKEN_LIMIT;e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong&&this.throwIfOverTokenLimitOnFirstTurn(e,n);let r=l?.tokenLimitBuffer??t.DEFAULT_TOKEN_LIMIT_BUFFER,a=n*(1-r),I=this.latestUserPromptMessage?Cvt(this.latestUserPromptMessage,e.messages):-1,s=[()=>Fin(e.messages,e.toolDefinitions,e.modelInfo.name,a),I===-1?void 0:()=>Cin(e.messages,e.toolDefinitions,e.modelInfo.name,a,I)].filter(d=>d!==void 0),o=0,c;for(;(!c||c.postTruncationTokensInMessages>a)&&o<s.length;){let d=s[o]();c=Qin(c,d),o++}return c=c??fin(e.messages,e.toolDefinitions,e.modelInfo.name,a),c.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(c)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:c},c}async preErrorThrow(){}async onRequestError(e){let l=this.modelToTokenLimit.get(e.modelInfo.name);if(l===void 0){this.logger.warning("Unable to determine if error relates to token limits due to missing information.");return}let{tokenLimit:n,tokenLimitBuffer:r}=l,a=win(e.error,n);if(a!==void 0){if(a<n)this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:a,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER}),this.logger.debug(`Adjusted model token limit to ${a}`);else{let I=Math.min(r+t.MAX_TOKEN_LIMIT_BUFFER/e.maxRetries,t.MAX_TOKEN_LIMIT_BUFFER);this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:n,tokenLimitBuffer:I}),this.logger.debug(`Adjusted model token limit to ${n}, token limit retry buffer to ${I}`)}return{retryAfter:1}}}getTokenLimitForModel(e){let l=this.modelToTokenLimit.get(e),n=l?l.tokenLimit*(1-l.tokenLimitBuffer):void 0;return{tokenLimit:l?.tokenLimit,tokenLimitBuffer:l?.tokenLimitBuffer,effectiveTokenLimit:n}}initializeStateForModelOnFirstRequest(e){e.turn===0&&e.retry===0&&this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:e.modelInfo.capabilities?.limits?.max_prompt_tokens||e.modelInfo.capabilities?.limits?.max_context_window_tokens||t.DEFAULT_TOKEN_LIMIT,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER})}throwIfOverTokenLimitOnFirstTurn(e,l){if(e.turn===0){let n=Kte(e.messages,e.modelInfo.name),r=XZt(e.toolDefinitions,e.modelInfo.name);if(n+r>l){if(e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong)throw new Error(`Initial inputs exceed the model token limit of ${l} tokens.`);this.logger.warning(`Initial inputs exceed the model token limit of ${l} tokens. The model may not be able to process the inputs correctly.`)}}}};function win(t,e){if(t&&typeof t=="object"){let l="message"in t&&typeof t.message=="string"?t.message.match(/prompt token count of (\d+) exceeds the limit of (\d+)/):null;if(l){let I=parseInt(l[2],10);return isNaN(I)?e:I}if("code"in t&&t.code==="model_max_prompt_tokens_exceeded")return e;let r=[JSON.stringify(t)];t instanceof Error&&(r.push(t.message),t.cause instanceof Error?r.push(t.cause.message):t.cause&&r.push(JSON.stringify(t.cause)));let a="Input length and `max_tokens` exceed context limit";if(r.some(I=>I.includes(a)))return e}}function Qin(t,e){return t?{preTruncationMessagesLength:t.preTruncationMessagesLength,preTruncationTokensInMessages:t.preTruncationTokensInMessages,tokensRemovedDuringTruncation:t.tokensRemovedDuringTruncation+e.tokensRemovedDuringTruncation,messagesRemovedDuringTruncation:t.messagesRemovedDuringTruncation+e.messagesRemovedDuringTruncation,tokenLimit:t.tokenLimit,postTruncationMessagesLength:e.postTruncationMessagesLength,postTruncationTokensInMessages:e.postTruncationTokensInMessages}:e}var KXt=.95;function Fin(t,e,l,n,r){let a=t.length;if(a===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:a,postTruncationTokensInMessages:0,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let I=t.map(p=>AD(p,l)),s=jR(JSON.stringify(e),l),o=n*KXt,c=I.reduce((p,A)=>p+A,0)+s;if(c<=o)return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,m=0,b=Math.min(r??t.length,t.length);for(let p=0;p<b;p++){let A=t[p];if(A.role!=="system"&&A.role!=="tool"&&A.role!=="user"){if(A.role==="assistant"){let Z=A.tool_calls||[],W=Z.filter(kA).filter(X=>X.function.name===cS),R=Z.filter(kA).filter(X=>X.function.name!==cS),V=W.length===0,f=new Set(R.map(X=>X.id));if(R.length>0&&(A.tool_calls=W,I[p]=AD(A,l)),V&&(d.add(p),m+=I[p]),f.size>0)for(let X=p+1;X<t.length;X++){let S=t[X];if(S.role==="tool"&&f.has(S.tool_call_id)&&(d.add(X),m+=I[X],f.delete(S.tool_call_id),f.size===0))break}}if(c-m<o)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c-m,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:m,messagesRemovedDuringTruncation:a-t.length}}function Cin(t,e,l,n,r){let a=t.length;if(a===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:a,postTruncationTokensInMessages:0,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let I=t.map(p=>AD(p,l)),s=jR(JSON.stringify(e),l),o=n*KXt,c=I.reduce((p,A)=>p+A,0)+s;if(c<=o)return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,m=0,b=Math.min(r??t.length,t.length);for(let p=0;p<b;p++){let A=t[p];if(A.role!=="system"&&A.role!=="tool"){if(A.role==="user")d.add(p),m+=I[p];else if(A.role==="assistant"){let Z=A.tool_calls||[],W=new Set(Z.map(R=>R.id));if(d.add(p),m+=I[p],W.size>0)for(let R=p+1;R<t.length;R++){let V=t[R];if(V.role==="tool"&&W.has(V.tool_call_id)&&(d.add(R),m+=I[R],W.delete(V.tool_call_id),W.size===0))break}}if(c-m<o)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c-m,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:m,messagesRemovedDuringTruncation:a-t.length}}function fin(t,e,l,n){let r=t.length;if(r===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:r,postTruncationTokensInMessages:0,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(o=>AD(o,l)),I=jR(JSON.stringify(e),l),s=a.reduce((o,c)=>o+c,0)+I;return{tokenLimit:n,preTruncationTokensInMessages:s,preTruncationMessagesLength:r,postTruncationTokensInMessages:s,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}var xd=class extends $F{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,l){}endGroup(e){}};var qXt={fetch:{tools:[{toolName:"fetch"}]},time:{tools:[{toolName:"get_current_time"},{toolName:"convert_time"}]},sequentialthinking:{tools:[{toolName:"sequentialthinking"}]},"github-mcp-server":{tools:[{toolName:"get_code_scanning_alert"},{toolName:"get_commit"},{toolName:"get_file_contents"},{toolName:"get_issue"},{toolName:"get_issue_comments"},{toolName:"get_me"},{toolName:"get_copilot_space"},{toolName:"get_pull_request"},{toolName:"get_pull_request_comments"},{toolName:"get_pull_request_files"},{toolName:"get_pull_request_reviews"},{toolName:"get_pull_request_status"},{toolName:"get_secret_scanning_alert"},{toolName:"get_tag"},{toolName:"list_branches"},{toolName:"list_code_scanning_alerts"},{toolName:"list_commits"},{toolName:"list_issues"},{toolName:"list_pull_requests"},{toolName:"list_secret_scanning_alerts"},{toolName:"list_tags"},{toolName:"search_code"},{toolName:"search_issues"},{toolName:"search_repositories"},{toolName:"search_users"},{toolName:"get_job_logs"},{toolName:"get_workflow_run"},{toolName:"get_workflow_run_logs"},{toolName:"list_workflow_jobs"},{toolName:"list_workflow_runs"},{toolName:"list_workflow_run_artifacts"},{toolName:"list_workflows"},{toolName:"summarize_job_log_failures"}]},playwright:{tools:[{toolName:"browser_close"},{toolName:"browser_resize"},{toolName:"browser_console_messages"},{toolName:"browser_handle_dialog"},{toolName:"browser_file_upload"},{toolName:"browser_install"},{toolName:"browser_press_key"},{toolName:"browser_navigate"},{toolName:"browser_navigate_back"},{toolName:"browser_navigate_forward"},{toolName:"browser_network_requests"},{toolName:"browser_pdf_save"},{toolName:"browser_take_screenshot"},{toolName:"browser_snapshot"},{toolName:"browser_click"},{toolName:"browser_drag"},{toolName:"browser_hover"},{toolName:"browser_type"},{toolName:"browser_select_option"},{toolName:"browser_tab_list"},{toolName:"browser_tab_new"},{toolName:"browser_tab_select"},{toolName:"browser_tab_close"},{toolName:"browser_generate_playwright_test"},{toolName:"browser_wait_for"}]},primer:{tools:[{toolName:"init"},{toolName:"list_components"},{toolName:"get_component"},{toolName:"get_component_examples"},{toolName:"get_component_usage_guidelines"},{toolName:"get_component_accessibility_guidelines"},{toolName:"list_patterns"},{toolName:"get_pattern"},{toolName:"list_tokens"},{toolName:"get_color_usage"},{toolName:"get_typography_usage"},{toolName:"list_icons"},{toolName:"get_icon"},{toolName:"review_alt_text"}]},azure:"azure-mcp-server","azure-azmcp":"azure-mcp-server","azure-mcp-server-azmcp":"azure-mcp-server","azure-mcp-server":{tools:[{toolName:"aks"},{toolName:"appconfig"},{toolName:"azureterraformbestpractices"},{toolName:"bestpractices"},{toolName:"bicepschema"},{toolName:"cosmos"},{toolName:"datadog"},{toolName:"documentation"},{toolName:"extension_az"},{toolName:"extension_azd"},{toolName:"extension_azqr"},{toolName:"foundry"},{toolName:"grafana"},{toolName:"group"},{toolName:"keyvault"},{toolName:"kusto"},{toolName:"loadtesting"},{toolName:"marketplace"},{toolName:"monitor"},{toolName:"postgres"},{toolName:"redis"},{toolName:"role"},{toolName:"search"},{toolName:"servicebus"},{toolName:"sql"},{toolName:"storage"},{toolName:"subscription"},{toolName:"workbooks"}]}};function Z0e(t,e,l){let n=(l||qXt)[t.toLowerCase()],r=new Set;for(;typeof n=="string";){if(r.has(n))return!1;r.add(n),n=qXt[n]}if(!n)return!1;let a=e.toLowerCase();return n.tools.some(I=>I.toolName===a)}var vin="image";var Hin="resource",Xin=180*1e3,kin={timeout:Xin};var NMe=class{constructor(e,l,n){this.settings=e;this.logger=l;this.cacheProviderTools=n}cachedTools=new Map;async invokeTool(e,l,n="hidden_characters"){let r=await this.doInvokeTool(e,l);return this.invokeToolResponseToToolResult(r,n)}invokeToolResponseToToolResult(e,l){let n=e.content||[],r="",a=[];for(let c of n)if(c.type==="text")r+=c.text||"";else if(c.type==="resource"){let d=c.resource;d&&d.blob?a.push({type:Hin,data:d.blob,mimeType:d.mimeType||"application/octet-stream"}):d&&d.text&&(r+=d.text)}else c.type==="image"&&a.push({type:vin,data:c.data,mimeType:c.mimeType});let I=r;if(r==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),I=r;else try{let c=JSON.parse(r),d=HOe(c,l);I=JSON.stringify(d)}catch(c){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${c}`),I=fOe(r,l)}this.logger.debug(`Tool invocation result: ${I}`);let s={},o=I?uc(I,"output"):"";return e.isToolError?{textResultForLlm:I,resultType:"failure",error:I,sessionLog:o,toolTelemetry:s}:{textResultForLlm:I,binaryResultForLlm:a,resultType:"success",sessionLog:o,toolTelemetry:s}}async loadTools(e,l={requestRequired:!1}){let n=this.getProviderCacheKey(e),r=this.cachedTools.get(n),a=r??await this.loadToolsFromProvider(e);this.cacheProviderTools&&!r&&this.cachedTools.set(n,a);let I={};for(let[s,o]of Object.entries(a)){let c=o.filterMode||"hidden_characters";I[s]={name:o.name,namespacedName:o.namespacedName,title:o.title||o.name,description:o.description,input_schema:o.input_schema,callback:async d=>{let m=a[s].serverName,b=a[s].name,p=a[s].title;if(!l.requestRequired)return this.invokeTool(s,d,c);let A=await l.request({kind:"mcp",serverName:m,toolName:b,toolTitle:p,args:d,readOnly:!!o.readOnly});switch(A.kind){case"approved":return this.invokeTool(s,d,c);case"denied-by-rules":return CWe(A.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return fWe;case"denied-interactively-by-user":return FWe;default:wo(A,`Unhandled permission result kind: ${A}`)}},safeForTelemetry:o.safeForTelemetry}}return Object.values(I)}};var ooe=class t extends NMe{toolIdToClientInfo=new Map;constructor(e,l,n=!1){super(e,l,n)}async doInvokeTool(e,l){let n=this.toolIdToClientInfo.get(e);if(!n)throw new Error(`No MCP client found for tool ID: ${e}`);let r=n.mcpClient,a=t.getToolNameFromIdAndClientName(e,n.clientName),I=await r.callTool({name:a,arguments:l},void 0,{...kin,...n.timeout!==void 0?{timeout:n.timeout}:{},onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(I.content))throw new Error("Expected array of results");return{content:I.content,isToolError:I.error!==void 0&&I.error!==null||I.isError===!0}}getProviderCacheKey(e){return[e.clientName,...e.tools,JSON.stringify(e.filterMapping),e.timeout?.toString()??"default"].join("+")}async loadToolsFromProvider(e){let l={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let n of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(n.name)){this.logger.debug(`Skipping tool ${n.name} for client ${e.clientName}`);continue}let r=t.getToolIdFromClientAndToolName(e.clientName,n.name);this.toolIdToClientInfo.set(r,e);let a;e.safeForTelemetry===!0?a={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?a=e.safeForTelemetry:a={name:Z0e(e.clientName,n.name),inputsNames:!1},this.logger.debug(`Adding tool: ${r}`);let I;e.filterMapping===void 0?I="hidden_characters":typeof e.filterMapping=="object"?I=e.filterMapping[n.name]||"hidden_characters":I=e.filterMapping,l[r]={serverName:e.clientName,name:r,namespacedName:`${e.clientName}/${n.name}`,title:n.title||n.annotations?.title||n.name,description:n.description||"",input_schema:n.inputSchema,readOnly:n.annotations?.readOnlyHint,safeForTelemetry:a,filterMode:I}}return l}static getToolIdFromClientAndToolName(e,l){return`${e}-${l}`}static getToolNameFromIdAndClientName(e,l){return e.substring(l.length+1)}};var N0e=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,l,n,r,a,I){this.settings=e,this.logger=l,this.gitHandler=n,this.location=r,this.commitPriorToCompletionWithTools=a,this.jitInstructions=I||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let l,n=async()=>{if(l===void 0)try{l=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(s){this.logger.error(`Failed to get changed paths, err: ${s}`),l=1}return l},r=[];for(let[s,o]of Object.entries(this.jitInstructions)){let c=IZt(this.settings,o.percentRemainingOfTimeout);c.isWithin&&r.push({config:o,withinMs:c.withinMs})}let a=r.map(({config:s,withinMs:o})=>{let c=typeof s.instruction=="function"?s.instruction(this.location):s.instruction;return{config:s,withinMs:o,instruction:c}}).filter(({instruction:s})=>!this.emittedJitInstructions.has(s)),I;for(let{config:s,withinMs:o,instruction:c}of a)(s.whenNoPathsChanged?await n()===0:!0)&&(!I||o<I.withinMs)&&(I={withinMs:o,instruction:c});if(I){this.logger.debug(`Adding JIT instructions to the history: ${I.instruction}`),this.emittedJitInstructions.add(I.instruction);let s={role:"user",content:I.instruction};e.messages.push(s),yield{kind:"message",turn:e.turn,callId:e.callId,message:s,source:"jit-instruction"}}}}},WMe={remindWhereToDoWork:{instruction:wvt,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:PEe.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:PEe.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:PEe.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};var yMe={agent:"sweagent-capi",model:"claude-sonnet-4"},$Xt=yMe;function SB(t){if(!t)return $Xt;let[e,...l]=t?.split(":")??[t,void 0],n=l.join(":")||void 0;return{agent:e||void 0,model:n||void 0}}function W0e(t,e){return e?.thinkingMode||to(t,"copilot_swe_agent_enable_responses_api")}import Kxt from"path";var E0e="4.12.0",BB="04b07795-8ddb-461a-bbee-02f9e1bf7b46",e5t="common",y0e;(function(t){t.AzureChina="https://login.chinacloudapi.cn",t.AzureGermany="https://login.microsoftonline.de",t.AzureGovernment="https://login.microsoftonline.us",t.AzurePublicCloud="https://login.microsoftonline.com"})(y0e||(y0e={}));var coe=y0e.AzurePublicCloud,t5t="login.microsoftonline.com",l5t=["*"],n5t="cae",r5t="nocae",a5t="msal.cache";var EMe;var Lin,R0e,s5t;function o5t(){return R0e!==void 0&&s5t!==void 0}function Jin(t){let e={cache:{},broker:{...t.brokerOptions,isEnabled:t.brokerOptions?.enabled??!1,enableMsaPassthrough:t.brokerOptions?.legacyEnableMsaPassthrough??!1}};if(t.tokenCachePersistenceOptions?.enabled){if(EMe===void 0)throw new Error(["Persistent token caching was requested, but no persistence provider was configured.","You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)","and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling","`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`."].join(" "));let l=t.tokenCachePersistenceOptions.name||a5t;e.cache.cachePlugin=EMe({name:`${l}.${r5t}`,...t.tokenCachePersistenceOptions}),e.cache.cachePluginCae=EMe({name:`${l}.${n5t}`,...t.tokenCachePersistenceOptions})}return t.brokerOptions?.enabled&&(e.broker.nativeBrokerPlugin=Sin(t.isVSCodeCredential||!1)),e}var I5t={missing:(t,e,l)=>[`${t} was requested, but no plugin was configured or no authentication record was found.`,`You must install the ${e} plugin package (npm install --save ${e})`,"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",`useIdentityPlugin(${l}) before using enableBroker.`].join(" "),unavailable:(t,e)=>[`${t} was requested, and the plugin is configured, but the broker is unavailable.`,`Ensure the ${t} plugin is properly installed and configured.`,"Check for missing native dependencies and ensure the package is properly installed.",`See the README for prerequisites on installing and using ${e}.`].join(" ")},xin={vsCode:{credentialName:"Visual Studio Code Credential",packageName:"@azure/identity-vscode",pluginVar:"vsCodePlugin",get brokerInfo(){return s5t}},native:{credentialName:"Broker for WAM",packageName:"@azure/identity-broker",pluginVar:"nativeBrokerPlugin",get brokerInfo(){return Lin}}};function Sin(t){let{credentialName:e,packageName:l,pluginVar:n,brokerInfo:r}=xin[t?"vsCode":"native"];if(r===void 0)throw new Error(I5t.missing(e,l,n));if(r.broker.isBrokerAvailable===!1)throw new Error(I5t.unavailable(e,l));return r.broker}var i5t={generatePluginConfiguration:Jin};function Bin(t){return t&&typeof t.error=="string"&&typeof t.error_description=="string"}var d5t="CredentialUnavailableError",tr=class extends Error{constructor(e,l){super(e,l),this.name=d5t}},Y0e="AuthenticationError",$4=class extends Error{statusCode;errorResponse;constructor(e,l,n){let r={error:"unknown",errorDescription:"An unknown error occurred and no additional details are available."};if(Bin(l))r=c5t(l);else if(typeof l=="string")try{let a=JSON.parse(l);r=c5t(a)}catch{e===400?r={error:"invalid_request",errorDescription:`The service indicated that the request was invalid.
|
|
1759
|
+
`)?.trim();return{...t,reasoning_text:e}}function _se(t){return structuredClone(t)}function Fvt(t){return{...t,choices:t.choices.map(e=>{let l=Z6(e.message);return{delta:{role:l.role,content:l.content,reasoning_opaque:l.reasoning_opaque,reasoning_text:l.reasoning_text,tool_calls:e.message.tool_calls?.map(n=>({...n,index:0}))},finish_reason:e.finish_reason,index:e.index}}),object:"chat.completion.chunk"}}function _4(t){return t.role==="user"&&Array.isArray(t.content)&&t.content.some(e=>e.type==="image_url")}function Cvt(t,e){let l=e.indexOf(t);if(l!==-1)return l;let n=s=>(typeof s.content=="string"?[{type:"text",text:s.content}]:s.content).filter(o=>o.type==="text").map(o=>o.text).join("").trim(),r=n(t),a=e.map((s,o)=>s.role==="user"&&n(s)===r?o:-1).filter(s=>s!==-1),I=a.at(0)??-1;return a.length===1?I:-1}var JUe="/tmp/playwright-logs",qrn="0.0.40",xUe=[`@playwright/mcp@${qrn}`,"--viewport-size","1280, 720","--output-dir",JUe],pma=[...xUe,"--isolated"];var hMe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},p0e;async function PXt(){if(p0e)return p0e;try{return p0e=(await Promise.resolve().then(()=>$e(DXt(),1))).default,p0e}catch{}}var noe=2e3;async function cin(t,e,l,n){let r={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},a=`${NZt(n)}/${t}`;l.info(`Downloading image from ${a}`);try{let I=await fetch(a,{method:"GET",headers:r});if(l.info(`Response status: ${I.status} ${I.statusText}`),l.debug(`Download Response URL: ${I.url}`),!I.ok){l.info(`Failed to download image, status: ${I.status}, statusText: ${I.statusText}`);try{let b=await I.text();l.info(`Error response body: ${b}`)}catch(b){l.info(`Could not read error response body: ${b}`)}return{size:0}}let o=(await I.json()).url;if(!o)return l.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let c=await fetch(o,{method:"GET"});if(!c.ok)return l.error(`Failed to download image: ${c.status} ${c.statusText}`),{size:0};let d=await c.arrayBuffer(),m=d.byteLength;return l.info(`Downloaded content size: ${YE(m)}`),{size:m,buffer:Buffer.from(d),mimeType:c.headers.get("content-type")||void 0}}catch(I){return l.error("Network error downloading image"),I instanceof Error&&(l.info(`Error message: ${I.message}`),l.info(`Error stack: ${I.stack}`)),{size:0}}}function AMe(t,e,l,n){let r=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,a=/!\[.*?\]\((.*?)\)/g,I=[];return I.push(...zXt(t,e,r,l,n)),I.push(...zXt(t,e,a,l,n)),I}function zXt(t,e,l,n,r){let a=t.matchAll(l),I=[],s=/\/([a-f0-9-]+)$/;for(let o of a){let c=bin(o[1],e),d=Gin(o[1],e,r);if(c||d){let m=o[1].match(s),b={url:o[1],guid:"",kind:d?"legacy_attachment":"attachment"};m&&m.length>1&&(b.guid=m[1]),I.push(b)}else if(n){let m={url:o[1],guid:"",kind:"committed_attachment"};I.push(m)}}return I}function din(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&soe(t)}function soe(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function uin(t){try{let e=/Here are relevant code snippets from the repository that might help with this task:\s*(\[[\s\S]*?\])(?=\n|$)/,l=t.match(e);if(!l?.[1]||l[1].length<=1)return null;let n=l[1].trim();return JSON.parse(n)}catch{return null}}function min(t,e,l){if(!t?.url||!t?.ref||!t?.path)throw new Error("Invalid repository insight: missing required fields");if(!e||e.trim()==="")throw new Error("Invalid image path: path cannot be empty");let n=t.url.split("/").slice(3,5).join("/"),r=t.ref.split("/")[2],a;if(e.startsWith("/"))a=e.slice(1);else{let s=t.path,o=roe.dirname(s);a=roe.resolve("/",o,e).slice(1)}return`${l}/${n}/blob/${r}/${a}`}function bin(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function Gin(t,e,l){return e&&new RegExp(`^${e}/[\\w.-]+/[\\w.-]+/assets/\\d+/[^.]+$`).test(t)?(l.debug(`Legacy GitHub asset URL detected: ${t}`),!0):!1}async function ZMe(t){let{width:e,height:l}=Wft(t);if(e===void 0||l===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:l}}async function h0e(t,e,l,n,r,a){t.debug(`Checking if image is valid size and dimensions. Max size: ${l}, Max dimension: ${n}`);let{exceedsSizeLimit:I,exceedsDimensionLimit:s}=await aoe(l,n,a);if(!s&&!I)return t.debug("Image is within size and dimension limits."),a;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${n}, attempting to resize`);let[o,c]=await Ain(t,a,n,l,r);if(!o){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,c==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:d}=await aoe(l,n,o);if(d){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),o}if(I){t.debug(`Image size ${YE(a.length)} is larger than the maximum size of ${YE(l)}, attempting to reduce image quality`);let o=await gin(t,a,n,l,r);if(!o){t.debug("Failed to reduce image quality to fit within the maximum size, skipping"),e.imagesFailedToReduceQuality++,e.imagesRemovedDueToSize++;return}return e.imagesWithLoweredQuality++,t.debug("Image quality successfully reduced."),o}}async function aoe(t,e,l){let n=await ZMe(l),r=l.length;return!n.width||!n.height?{exceedsSizeLimit:r>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await hin(t,l),exceedsDimensionLimit:await pin(e,l)}}async function pin(t,e){let l=await ZMe(e);return!l.width||!l.height?!1:l.width>t||l.height>t}async function hin(t,e){return e.length>t}async function Ain(t,e,l,n,r){try{if(!jXt(t,r))return[void 0,"unsupported_mime_type"];let a=await ZMe(e);if(!a.width||!a.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let I=async(W,R)=>{let V=await PXt();if(!V)return;let f=V(e).resize(W,R,{fit:"inside",withoutEnlargement:!0});return gMe(t,await f.toBuffer(),void 0,r)},s=Math.min(l,a.width),o=Math.min(l,a.height),c=await I(s,o);if(c&&c.length<=n)return[c,void 0];let d=Math.max(s,o),m=1,b=d-1,p,A=0,Z=10;for(;m<=b&&A<Z;){let W=Math.floor((m+b)/2),R=await I(W,W);if(!R)break;let{exceedsSizeLimit:V,exceedsDimensionLimit:f}=await aoe(n,l,R);!V&&!f?(p=R,m=W+1):b=W-1,A++}return[p,void 0]}catch(a){return t.error(`Failed to resize image for upload: ${a instanceof Error?a.message:String(a)}`),[void 0,"unknown"]}}async function gin(t,e,l,n,r){try{let a=r==="image/png"?80:100,I=r==="image/png"?Math.floor(a*.4):20,s=await gMe(t,e,I,r);if(!s||s.length>n)return;let o=I,c=a,d,m=0,b=10,p=o,A=c-1;for(;p<=A&&m<b;){let Z=Math.floor((p+A)/2),W=await gMe(t,e,Z,r);if(!W)return d;let{exceedsSizeLimit:R,exceedsDimensionLimit:V}=await aoe(n,l,W);!R&&!V?(d=W,p=Z+1):A=Z-1,m++}return d}catch(a){t.error(`Failed to reduce image quality: ${a instanceof Error?a.message:String(a)}`);return}}async function gMe(t,e,l,n){let r=await PXt();if(!r)return;let a=r(e);switch(n){case"image/png":return l?a.png({quality:l}).toBuffer():a.png().toBuffer();case"image/jpeg":return l?a.jpeg({quality:l}).toBuffer():a.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${n}`);return}}var Ioe=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function Zin(t,e,l,n){if(e<=0)return[];let r=[];for(let a of t){if(a.role!=="user"||r.length>=e)continue;let I=typeof a.content=="string"?a.content:JSON.stringify(a.content),s=uin(I);if(s)for(let o in s){if(r.length>=e)break;let c=s[o].contents,d=AMe(c,l,!0,n);for(let m of d){if(r.length>=e)break;let b=m.url,p="",A=!1;if(m.kind==="attachment"||m.kind==="legacy_attachment"?r.push(m):din(b)?(A=!0,p=min(s[o],b,l),r.push({url:p,guid:m.guid,kind:"committed_attachment"})):soe(b)&&b.startsWith(l)&&(A=!0,r.push({...m,kind:"committed_attachment"})),A){let Z=r[r.length-1],W=new RegExp(`^${l}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),R=Z.url.match(W);if(n.info(`Blob match for ${Z.url}: ${JSON.stringify(R)}`),R&&R.length===5){let[,V,f,X,S]=R;Z.owner=V,Z.repo=f,Z.branch=X,Z.path=S,n.info(`Repository metadata extracted: owner=${V}, repo=${f}, branch=${X}, path=${S}`)}else n.info(`Failed to extract repository metadata from URL: ${Z.url}`)}}}}return r}function Nin(t,e){let l=e.flatMap(r=>_4(r)?r.content.flatMap(a=>a.type==="image_url"?a.image_url.url:[]):[]),n=new Set(l);return t.filter(r=>!n.has(r.url))}var A0e=class{async resolveRepositoryImages(e,l,n,r,a,I){if(l<=0)return[];let s=Zin(e,l,n,r);this.logger.debug(`Found ${s.length} repository image URLs to process`);let o=Nin(s,e),c=await this.processImageReferences(o,a,I);return this.logger.debug(`Processed ${c.addedImages.length} repository image URLs`),c.addedImages}async*preRequest(e){let l=e.modelInfo;if(!l.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!l.capabilities?.supports?.vision||!this.settings.featureFlags?.copilot_swe_agent_vision){this.logger.debug("Vision not supported or enabled, skipping image processing");return}if(!this.gitHubServerUrl){this.logger.debug("GitHub server URL is not set, skipping image processing");return}for(let m of this.messagesToInsertOnNextPreRequest)e.messages.push(m),yield{kind:"message",turn:e.turn,callId:e.callId,message:m};this.messagesToInsertOnNextPreRequest.splice(0);let n=[],r=l.capabilities.limits.vision?.max_prompt_images??1,a=l.capabilities.limits.vision?.max_prompt_image_size??3145728,I=0,s=[],o=new Ioe,c=new Map;for(let m of e.messages)if(m.role=="user")if(typeof m.content=="string"){let b=AMe(m.content,this.gitHubServerUrl,!1,this.logger).filter(A=>!this.processedImageUrls.has(A.url)),p=await this.processImageReferences(b,a,o);s.push(...p.addedImages)}else{let b=[];for(let[p,A]of m.content.entries()){if(A.type==="text"){let Z=AMe(A.text,this.gitHubServerUrl,!1,this.logger).filter(R=>!this.processedImageUrls.has(R.url)),W=await this.processImageReferences(Z,a,o);s.push(...W.addedImages)}else if(A.type==="image_url"){if(A.image_url.url.startsWith("data:")){let[Z,W]=await this.extractAndUploadImageData(A,a,o);if(Z===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(Z),p>=1&&b.length>0){let R=b.at(-1);R&&R.type==="text"&&R.text&&R.text.includes("screenshot")&&c.set(Z,Vvt(Z))}b.pop();continue}I++}b.push(A)}m.content=b}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${r}`);I<r&&s.length>0;){let m=s.shift();if(!m){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(m)){this.logger.debug(`Skipping already processed image url: ${m}`);continue}this.processedImageUrls.add(m);let b=`Here is the image url: ${m}`;c.has(m)&&(b=c.get(m)||b),this.logger.debug(`Adding image url: ${m}`),n.push({role:"user",content:[{type:"text",text:b},{type:"image_url",image_url:{url:m}}]}),I++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),I<r)){let m=await this.resolveRepositoryImages(e.messages,r-I,this.settings.github?.serverUrl||"",this.logger,a,o);this.logger.debug(`Resolved ${m.length} repository image URLs`);for(let b of m){if(I>=r)break;if(this.processedImageUrls.has(b)){this.logger.debug(`Skipping already processed repository image url: ${b}`);continue}n.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:b}}]}),this.processedImageUrls.add(b),I++}}let d={imagesExtractedCount:o.extractedImagesSize.length,base64ImagesCount:o.base64ImagesSize.length,imagesRemovedDueToSize:o.imagesRemovedDueToSize,imagesRemovedDueToDimensions:o.imagesRemovedDueToDimensions,imagesResized:o.imagesResized,imagesResolvedFromGitHubMCPCount:o.imagesResolvedFromGitHubMCPSize.length};for(let m=0;m<o.base64ImagesSize.length;m++)d[`base64ImageSize_${m}`]=o.base64ImagesSize[m];for(let m=0;m<o.resizedBase64ImagesSize.length;m++)d[`resizedBase64ImageSize_${m}`]=o.resizedBase64ImagesSize[m];for(let m=0;m<o.extractedImagesSize.length;m++)d[`extractedImageSize_${m}`]=o.extractedImagesSize[m];for(let m=0;m<o.imagesResolvedFromGitHubMCPSize.length;m++)d[`imagesResolvedFromGitHubMCPSize_${m}`]=o.imagesResolvedFromGitHubMCPSize[m];n.length>0&&this.logger.debug(`Using ${n.length} image messages`);for(let m of n)yield{kind:"message",turn:e.turn,callId:e.callId,message:m},e.messages.push(m);d.allImagesSendToLlm=e.messages.filter(_4).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:d},e.messages.some(m=>_4(m))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,l,n){let r=Pte(this.settings);if(!r)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let a=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!a||a.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let I=a[1];if(!jXt(this.logger,I))return[""];let s=a[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let o=Buffer.from(s,"base64");if(n.base64ImagesSize.push(o.length),o=await h0e(this.logger,n,l,noe,I,o),n.resizedBase64ImagesSize.push(o?.length??-1),!o)return["",new hMe(`Image size exceeds maximum size of ${YE(l)}`)];s=o.toString("base64");try{let c=await this.uploadBase64ImageData(s,I,r);return c?(this.logger.debug(`Uploaded image url: ${c}`),e.image_url.url=c,[c]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(c){let d=c instanceof Error?c.message:String(c);return this.logger.debug(`Error during image upload: ${d}`),[""]}}async uploadBase64ImageData(e,l,n){try{let r=ZZt(this.settings),a=l.split("/").at(1),I=`image-${Date.now()}.${a}`;if(!e||e.trim()==="")return this.logger.error("Empty image data provided for upload"),null;let s=Buffer.from(e,"base64");if(s.length===0)return this.logger.error("Converted image data has zero length"),null;let o=this.settings.github?.repo?.id;if(!o)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let c=`${r}?name=${encodeURIComponent(I)}&content_type=${encodeURIComponent(l)}&repository_id=${o}`;this.logger.debug(`Uploading image data (${YE(s.length)}) to ${r} with name ${encodeURIComponent(I)} and content type ${encodeURIComponent(l)}`);let d={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+n},m=await fetch(c,{method:"POST",headers:d,body:s}).catch(p=>{throw p instanceof Error?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof p=="object"&&p!==null&&"code"in p&&"message"in p?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):this.logger.error(`Failed to upload image: ${String(p)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:p?.code,message:p?.message,stack:p?.stack,name:p?.name,cause:p?.cause},null,2)}`),p});if(!m.ok){let p=await m.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${m.status} ${m.statusText} - ${p}`),null}let b=await m.json();return this.logger.debug(`Upload result: ${JSON.stringify(b,null,2)}`),b.url||null}catch(r){return this.logger.error(`Error handling image upload: ${r instanceof Error?r.message:String(r)}`),r instanceof Error&&r.stack&&this.logger.debug(`Stack trace: ${r.stack}`),null}}async getRepositoryImageViaTools(e){if(this.logger.debug(`Attempting to retrieve repository image: ${e.owner}/${e.repo}/${e.path}@${e.branch}`),this.githubGetFileContentsTool){this.logger.debug(`GitHub MCP tool found, calling with image reference: ${JSON.stringify(e)}`);try{let l=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{toolCallId:crypto.randomUUID(),settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof l}`),this.logger.debug(`GitHub tool call result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`),typeof l=="object"&&l!==null&&"binaryResultForLlm"in l&&Array.isArray(l.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${l.binaryResultForLlm.length} items`);try{for(let n of l.binaryResultForLlm)if(n.data&&n.mimeType){let r=Buffer.from(n.data,"base64"),a=n.mimeType;return{buffer:r,mimeType:a}}}catch(n){this.logger.error(`Failed to parse GitHub tool response: ${n}`),this.logger.debug(`binaryResultForLlm length: ${l.binaryResultForLlm?.length||0}`)}}else typeof l=="string"?this.logger.debug(`GitHub tool returned string result: ${l}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`)}catch(l){this.logger.error(`Error calling GitHub MCP tool: ${l}`)}}else this.logger.debug("GitHub MCP tool 'github-mcp-server-get_file_contents' not available");return this.logger.debug("Failed to retrieve repository image, returning null"),null}async getImgRefsSmallerThanMaxSize(e,l,n){let r=[],a=await Promise.all(e);for(let{imgRef:I,attachment:s}of a)if(this.logger.debug(`Processing attachment for ${I.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(l.extractedImagesSize.push(s.buffer.length),to(this.settings,"copilot_swe_agent_resize_image_references")){if(!await h0e(this.logger,l,n,noe,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}r.push(I.url)}else{let o=await aoe(n,noe,s.buffer);if(this.logger.debug(`Image size check for ${I.url}: size=${s.buffer.length}, maxSize=${n}, exceedsSize=${o.exceedsSizeLimit}, exceedsDimensions=${o.exceedsDimensionLimit}`),o.exceedsSizeLimit?(l.imagesRemovedDueToSize++,this.logger.debug(`Image ${I.url} removed due to size (${s.buffer.length} > ${n})`)):o.exceedsDimensionLimit&&(l.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${I.url} removed due to dimensions`)),o.exceedsSizeLimit||o.exceedsDimensionLimit){this.processedImageUrls.add(I.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${YE(n)}.`);continue}r.push(I.url),this.logger.debug(`Image ${I.url} passed size checks and added to results`)}else this.processedImageUrls.add(I.url),this.logger.debug(`Skipping image ${I.url} - could not fetch image data`);return r}async processImageReferences(e,l,n){let r=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${r}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let a=e.filter(s=>!this.processedImageUrls.has(s.url)).map(async s=>{if(this.logger.debug(`Processing image reference: ${JSON.stringify(s,null,2)}`),s.kind==="committed_attachment"){this.logger.debug(`Detected repository image - Owner: ${s.owner}, Repo: ${s.repo}, Branch: ${s.branch}, Path: ${s.path}`);let o=await this.getRepositoryImageViaTools(s);return o?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${o.buffer.length} bytes`),n.imagesResolvedFromGitHubMCPSize.push(o.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:o?.buffer?.length||0,mimeType:o?.mimeType||"",buffer:o?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await cin(s.guid,Pte(this.settings),this.logger,this.settings)}}),I=await this.getImgRefsSmallerThanMaxSize(a,n,l);return this.logger.debug(`Processed image references, found ${I.length} attachments smaller than max size of ${YE(l)}`),{addedImages:I}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,l,n){this.logger=e,this.settings=l,this.gitHubServerUrl=l.github?.serverUrl,this.githubGetFileContentsTool=n,this.processedImageUrls=new Set,this.messagesToInsertOnNextPreRequest=[]}toJSON(){return"CAPIImageProcessor"}async onRequestError(e){}async preErrorThrow(e){this.processedImageUrls.size>0&&(e.isVisionFlow=!0)}async postToolExecution(e){let l=e.modelInfo,n=e.toolCall.function.name,r=e.toolResult;if(l?.capabilities?.supports?.vision){let a=Array.from(Win(r,n));if(a.length===0){let I=await Rin(e.toolCall,this.logger);I&&a.push(I)}this.insertImageUrlMessages(a)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let l of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:l.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:l.url}}]})}},g0e=class{async*preRequest(e){e.messages.some(l=>_4(l))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}toJSON(){return"VisionEnabledProcessor"}};function*Win(t,e){for(let l of t.binaryResultForLlm??[])l.type==="image"&&(yield{url:`data:${l.mimeType};base64,${l.data}`,isScreenshot:e.toLowerCase().includes("screenshot")})}var yin="playwright-browser_take_screenshot";function Ein(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function Rin(t,e){if(t.function.name!==yin)return;e.debug("Adding images using Playwright params fallback strategy");let l=JSON.parse(t.function.arguments);if(Ein(l)){let n=roe.isAbsolute(l.filename)?l.filename:roe.join(JUe,l.filename);e.debug(`Image from Playwright params: ${l.filename}. Updated to ${n}.`);let r=await Vin(n,e);if(r){let a=r.buffer.toString("base64");return{url:`data:${r.mimeType};base64,${a}`,isScreenshot:!0}}}}function Yin(t){switch(roe.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function jXt(t,e){return e!=="image/png"&&e!=="image/jpeg"?(t.debug(`Unsupported content type: ${e}, only image / png and image / jpeg are supported`),!1):!0}async function Vin(t,e){try{if(!soe(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let l=Yin(t);return l?{buffer:await iin.readFile(t),mimeType:l}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(l){return e.error(`Failed to read image from disk: ${l instanceof Error?l.message:String(l)}`),null}}var q4=class t{static DEFAULT_TOKEN_LIMIT=128e3;static DEFAULT_TOKEN_LIMIT_BUFFER=0;static MAX_TOKEN_LIMIT_BUFFER=.5;latestUserPromptMessage;logger;modelToTokenLimit;constructor(e,l){this.latestUserPromptMessage=e,this.logger=l,this.modelToTokenLimit=new Map}toJSON(){return"BasicTruncator"}async*preRequest(e){this.initializeStateForModelOnFirstRequest(e);let l=this.modelToTokenLimit.get(e.modelInfo.name),n=l?.tokenLimit??t.DEFAULT_TOKEN_LIMIT;e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong&&this.throwIfOverTokenLimitOnFirstTurn(e,n);let r=l?.tokenLimitBuffer??t.DEFAULT_TOKEN_LIMIT_BUFFER,a=n*(1-r),I=this.latestUserPromptMessage?Cvt(this.latestUserPromptMessage,e.messages):-1,s=[()=>Fin(e.messages,e.toolDefinitions,e.modelInfo.name,a),I===-1?void 0:()=>Cin(e.messages,e.toolDefinitions,e.modelInfo.name,a,I)].filter(d=>d!==void 0),o=0,c;for(;(!c||c.postTruncationTokensInMessages>a)&&o<s.length;){let d=s[o]();c=Qin(c,d),o++}return c=c??fin(e.messages,e.toolDefinitions,e.modelInfo.name,a),c.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(c)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:c},c}async preErrorThrow(){}async onRequestError(e){let l=this.modelToTokenLimit.get(e.modelInfo.name);if(l===void 0){this.logger.warning("Unable to determine if error relates to token limits due to missing information.");return}let{tokenLimit:n,tokenLimitBuffer:r}=l,a=win(e.error,n);if(a!==void 0){if(a<n)this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:a,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER}),this.logger.debug(`Adjusted model token limit to ${a}`);else{let I=Math.min(r+t.MAX_TOKEN_LIMIT_BUFFER/e.maxRetries,t.MAX_TOKEN_LIMIT_BUFFER);this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:n,tokenLimitBuffer:I}),this.logger.debug(`Adjusted model token limit to ${n}, token limit retry buffer to ${I}`)}return{retryAfter:1}}}getTokenLimitForModel(e){let l=this.modelToTokenLimit.get(e),n=l?l.tokenLimit*(1-l.tokenLimitBuffer):void 0;return{tokenLimit:l?.tokenLimit,tokenLimitBuffer:l?.tokenLimitBuffer,effectiveTokenLimit:n}}initializeStateForModelOnFirstRequest(e){e.turn===0&&e.retry===0&&this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:e.modelInfo.capabilities?.limits?.max_prompt_tokens||e.modelInfo.capabilities?.limits?.max_context_window_tokens||t.DEFAULT_TOKEN_LIMIT,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER})}throwIfOverTokenLimitOnFirstTurn(e,l){if(e.turn===0){let n=Kte(e.messages,e.modelInfo.name),r=XZt(e.toolDefinitions,e.modelInfo.name);if(n+r>l){if(e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong)throw new Error(`Initial inputs exceed the model token limit of ${l} tokens.`);this.logger.warning(`Initial inputs exceed the model token limit of ${l} tokens. The model may not be able to process the inputs correctly.`)}}}};function win(t,e){if(t&&typeof t=="object"){let l="message"in t&&typeof t.message=="string"?t.message.match(/prompt token count of (\d+) exceeds the limit of (\d+)/):null;if(l){let I=parseInt(l[2],10);return isNaN(I)?e:I}if("code"in t&&t.code==="model_max_prompt_tokens_exceeded")return e;let r=[JSON.stringify(t)];t instanceof Error&&(r.push(t.message),t.cause instanceof Error?r.push(t.cause.message):t.cause&&r.push(JSON.stringify(t.cause)));let a="Input length and `max_tokens` exceed context limit";if(r.some(I=>I.includes(a)))return e}}function Qin(t,e){return t?{preTruncationMessagesLength:t.preTruncationMessagesLength,preTruncationTokensInMessages:t.preTruncationTokensInMessages,tokensRemovedDuringTruncation:t.tokensRemovedDuringTruncation+e.tokensRemovedDuringTruncation,messagesRemovedDuringTruncation:t.messagesRemovedDuringTruncation+e.messagesRemovedDuringTruncation,tokenLimit:t.tokenLimit,postTruncationMessagesLength:e.postTruncationMessagesLength,postTruncationTokensInMessages:e.postTruncationTokensInMessages}:e}var KXt=.95;function Fin(t,e,l,n,r){let a=t.length;if(a===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:a,postTruncationTokensInMessages:0,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let I=t.map(p=>AD(p,l)),s=jR(JSON.stringify(e),l),o=n*KXt,c=I.reduce((p,A)=>p+A,0)+s;if(c<=o)return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,m=0,b=Math.min(r??t.length,t.length);for(let p=0;p<b;p++){let A=t[p];if(A.role!=="system"&&A.role!=="tool"&&A.role!=="user"){if(A.role==="assistant"){let Z=A.tool_calls||[],W=Z.filter(kA).filter(X=>X.function.name===cS),R=Z.filter(kA).filter(X=>X.function.name!==cS),V=W.length===0,f=new Set(R.map(X=>X.id));if(R.length>0&&(A.tool_calls=W,I[p]=AD(A,l)),V&&(d.add(p),m+=I[p]),f.size>0)for(let X=p+1;X<t.length;X++){let S=t[X];if(S.role==="tool"&&f.has(S.tool_call_id)&&(d.add(X),m+=I[X],f.delete(S.tool_call_id),f.size===0))break}}if(c-m<o)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c-m,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:m,messagesRemovedDuringTruncation:a-t.length}}function Cin(t,e,l,n,r){let a=t.length;if(a===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:a,postTruncationTokensInMessages:0,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let I=t.map(p=>AD(p,l)),s=jR(JSON.stringify(e),l),o=n*KXt,c=I.reduce((p,A)=>p+A,0)+s;if(c<=o)return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,m=0,b=Math.min(r??t.length,t.length);for(let p=0;p<b;p++){let A=t[p];if(A.role!=="system"&&A.role!=="tool"){if(A.role==="user")d.add(p),m+=I[p];else if(A.role==="assistant"){let Z=A.tool_calls||[],W=new Set(Z.map(R=>R.id));if(d.add(p),m+=I[p],W.size>0)for(let R=p+1;R<t.length;R++){let V=t[R];if(V.role==="tool"&&W.has(V.tool_call_id)&&(d.add(R),m+=I[R],W.delete(V.tool_call_id),W.size===0))break}}if(c-m<o)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c-m,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:m,messagesRemovedDuringTruncation:a-t.length}}function fin(t,e,l,n){let r=t.length;if(r===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:r,postTruncationTokensInMessages:0,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(o=>AD(o,l)),I=jR(JSON.stringify(e),l),s=a.reduce((o,c)=>o+c,0)+I;return{tokenLimit:n,preTruncationTokensInMessages:s,preTruncationMessagesLength:r,postTruncationTokensInMessages:s,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}var xd=class extends $F{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,l){}endGroup(e){}};var qXt={fetch:{tools:[{toolName:"fetch"}]},time:{tools:[{toolName:"get_current_time"},{toolName:"convert_time"}]},sequentialthinking:{tools:[{toolName:"sequentialthinking"}]},"github-mcp-server":{tools:[{toolName:"get_code_scanning_alert"},{toolName:"get_commit"},{toolName:"get_file_contents"},{toolName:"get_issue"},{toolName:"get_issue_comments"},{toolName:"get_me"},{toolName:"get_copilot_space"},{toolName:"get_pull_request"},{toolName:"get_pull_request_comments"},{toolName:"get_pull_request_files"},{toolName:"get_pull_request_reviews"},{toolName:"get_pull_request_status"},{toolName:"get_secret_scanning_alert"},{toolName:"get_tag"},{toolName:"list_branches"},{toolName:"list_code_scanning_alerts"},{toolName:"list_commits"},{toolName:"list_issues"},{toolName:"list_pull_requests"},{toolName:"list_secret_scanning_alerts"},{toolName:"list_tags"},{toolName:"search_code"},{toolName:"search_issues"},{toolName:"search_repositories"},{toolName:"search_users"},{toolName:"get_job_logs"},{toolName:"get_workflow_run"},{toolName:"get_workflow_run_logs"},{toolName:"list_workflow_jobs"},{toolName:"list_workflow_runs"},{toolName:"list_workflow_run_artifacts"},{toolName:"list_workflows"},{toolName:"summarize_job_log_failures"}]},playwright:{tools:[{toolName:"browser_close"},{toolName:"browser_resize"},{toolName:"browser_console_messages"},{toolName:"browser_handle_dialog"},{toolName:"browser_file_upload"},{toolName:"browser_install"},{toolName:"browser_press_key"},{toolName:"browser_navigate"},{toolName:"browser_navigate_back"},{toolName:"browser_navigate_forward"},{toolName:"browser_network_requests"},{toolName:"browser_pdf_save"},{toolName:"browser_take_screenshot"},{toolName:"browser_snapshot"},{toolName:"browser_click"},{toolName:"browser_drag"},{toolName:"browser_hover"},{toolName:"browser_type"},{toolName:"browser_select_option"},{toolName:"browser_tab_list"},{toolName:"browser_tab_new"},{toolName:"browser_tab_select"},{toolName:"browser_tab_close"},{toolName:"browser_generate_playwright_test"},{toolName:"browser_wait_for"}]},primer:{tools:[{toolName:"init"},{toolName:"list_components"},{toolName:"get_component"},{toolName:"get_component_examples"},{toolName:"get_component_usage_guidelines"},{toolName:"get_component_accessibility_guidelines"},{toolName:"list_patterns"},{toolName:"get_pattern"},{toolName:"list_tokens"},{toolName:"get_color_usage"},{toolName:"get_typography_usage"},{toolName:"list_icons"},{toolName:"get_icon"},{toolName:"review_alt_text"}]},azure:"azure-mcp-server","azure-azmcp":"azure-mcp-server","azure-mcp-server-azmcp":"azure-mcp-server","azure-mcp-server":{tools:[{toolName:"aks"},{toolName:"appconfig"},{toolName:"azureterraformbestpractices"},{toolName:"bestpractices"},{toolName:"bicepschema"},{toolName:"cosmos"},{toolName:"datadog"},{toolName:"documentation"},{toolName:"extension_az"},{toolName:"extension_azd"},{toolName:"extension_azqr"},{toolName:"foundry"},{toolName:"grafana"},{toolName:"group"},{toolName:"keyvault"},{toolName:"kusto"},{toolName:"loadtesting"},{toolName:"marketplace"},{toolName:"monitor"},{toolName:"postgres"},{toolName:"redis"},{toolName:"role"},{toolName:"search"},{toolName:"servicebus"},{toolName:"sql"},{toolName:"storage"},{toolName:"subscription"},{toolName:"workbooks"}]}};function Z0e(t,e,l){let n=(l||qXt)[t.toLowerCase()],r=new Set;for(;typeof n=="string";){if(r.has(n))return!1;r.add(n),n=qXt[n]}if(!n)return!1;let a=e.toLowerCase();return n.tools.some(I=>I.toolName===a)}var vin="image";var Hin="resource",Xin=180*1e3,kin={timeout:Xin};var NMe=class{constructor(e,l,n){this.settings=e;this.logger=l;this.cacheProviderTools=n}cachedTools=new Map;async refreshProvider(e){let l=this.getProviderCacheKey(e);this.logger.log(`Refreshing tools for provider: ${l}`),this.cachedTools.has(l)&&(this.cachedTools.delete(l),this.logger.log(`Cleared cache entry: ${l}`)),await this.onProviderRefresh(e);let n=await this.loadToolsFromProvider(e);this.cacheProviderTools&&this.cachedTools.set(l,n),this.logger.log(`Completed refresh for provider: ${l}, loaded ${Object.keys(n).length} tools`)}async onProviderRefresh(e){}async invokeTool(e,l,n="hidden_characters"){let r=await this.doInvokeTool(e,l);return this.invokeToolResponseToToolResult(r,n)}invokeToolResponseToToolResult(e,l){let n=e.content||[],r="",a=[];for(let c of n)if(c.type==="text")r+=c.text||"";else if(c.type==="resource"){let d=c.resource;d&&d.blob?a.push({type:Hin,data:d.blob,mimeType:d.mimeType||"application/octet-stream"}):d&&d.text&&(r+=d.text)}else c.type==="image"&&a.push({type:vin,data:c.data,mimeType:c.mimeType});let I=r;if(r==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),I=r;else try{let c=JSON.parse(r),d=HOe(c,l);I=JSON.stringify(d)}catch(c){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${c}`),I=fOe(r,l)}this.logger.debug(`Tool invocation result: ${I}`);let s={},o=I?uc(I,"output"):"";return e.isToolError?{textResultForLlm:I,resultType:"failure",error:I,sessionLog:o,toolTelemetry:s}:{textResultForLlm:I,binaryResultForLlm:a,resultType:"success",sessionLog:o,toolTelemetry:s}}async loadTools(e,l={requestRequired:!1}){let n=this.getProviderCacheKey(e),r=this.cachedTools.get(n),a=r??await this.loadToolsFromProvider(e);this.cacheProviderTools&&!r&&this.cachedTools.set(n,a);let I={};for(let[s,o]of Object.entries(a)){let c=o.filterMode||"hidden_characters";I[s]={name:o.name,namespacedName:o.namespacedName,title:o.title||o.name,description:o.description,input_schema:o.input_schema,callback:async d=>{let m=a[s].serverName,b=a[s].name,p=a[s].title;if(!l.requestRequired)return this.invokeTool(s,d,c);let A=await l.request({kind:"mcp",serverName:m,toolName:b,toolTitle:p,args:d,readOnly:!!o.readOnly});switch(A.kind){case"approved":return this.invokeTool(s,d,c);case"denied-by-rules":return CWe(A.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return fWe;case"denied-interactively-by-user":return FWe;default:wo(A,`Unhandled permission result kind: ${A}`)}},safeForTelemetry:o.safeForTelemetry}}return Object.values(I)}};var ooe=class t extends NMe{toolIdToClientInfo=new Map;constructor(e,l,n=!1){super(e,l,n)}async onProviderRefresh(e){let l=e.clientName,n=[];for(let[r,a]of this.toolIdToClientInfo.entries())a.clientName===l&&n.push(r);for(let r of n)this.toolIdToClientInfo.delete(r);this.logger.log(`Cleared ${n.length} tool ID mappings for ${l}`)}async doInvokeTool(e,l){let n=this.toolIdToClientInfo.get(e);if(!n)throw new Error(`No MCP client found for tool ID: ${e}`);let r=n.mcpClient,a=t.getToolNameFromIdAndClientName(e,n.clientName),I=await r.callTool({name:a,arguments:l},void 0,{...kin,...n.timeout!==void 0?{timeout:n.timeout}:{},onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(I.content))throw new Error("Expected array of results");return{content:I.content,isToolError:I.error!==void 0&&I.error!==null||I.isError===!0}}getProviderCacheKey(e){return[e.clientName,...e.tools,JSON.stringify(e.filterMapping),e.timeout?.toString()??"default"].join("+")}async loadToolsFromProvider(e){let l={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let n of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(n.name)){this.logger.debug(`Skipping tool ${n.name} for client ${e.clientName}`);continue}let r=t.getToolIdFromClientAndToolName(e.clientName,n.name);this.toolIdToClientInfo.set(r,e);let a;e.safeForTelemetry===!0?a={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?a=e.safeForTelemetry:a={name:Z0e(e.clientName,n.name),inputsNames:!1},this.logger.debug(`Adding tool: ${r}`);let I;e.filterMapping===void 0?I="hidden_characters":typeof e.filterMapping=="object"?I=e.filterMapping[n.name]||"hidden_characters":I=e.filterMapping,l[r]={serverName:e.clientName,name:r,namespacedName:`${e.clientName}/${n.name}`,title:n.title||n.annotations?.title||n.name,description:n.description||"",input_schema:n.inputSchema,readOnly:n.annotations?.readOnlyHint,safeForTelemetry:a,filterMode:I}}return l}static getToolIdFromClientAndToolName(e,l){return`${e}-${l}`}static getToolNameFromIdAndClientName(e,l){return e.substring(l.length+1)}};var N0e=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,l,n,r,a,I){this.settings=e,this.logger=l,this.gitHandler=n,this.location=r,this.commitPriorToCompletionWithTools=a,this.jitInstructions=I||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let l,n=async()=>{if(l===void 0)try{l=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(s){this.logger.error(`Failed to get changed paths, err: ${s}`),l=1}return l},r=[];for(let[s,o]of Object.entries(this.jitInstructions)){let c=IZt(this.settings,o.percentRemainingOfTimeout);c.isWithin&&r.push({config:o,withinMs:c.withinMs})}let a=r.map(({config:s,withinMs:o})=>{let c=typeof s.instruction=="function"?s.instruction(this.location):s.instruction;return{config:s,withinMs:o,instruction:c}}).filter(({instruction:s})=>!this.emittedJitInstructions.has(s)),I;for(let{config:s,withinMs:o,instruction:c}of a)(s.whenNoPathsChanged?await n()===0:!0)&&(!I||o<I.withinMs)&&(I={withinMs:o,instruction:c});if(I){this.logger.debug(`Adding JIT instructions to the history: ${I.instruction}`),this.emittedJitInstructions.add(I.instruction);let s={role:"user",content:I.instruction};e.messages.push(s),yield{kind:"message",turn:e.turn,callId:e.callId,message:s,source:"jit-instruction"}}}}},WMe={remindWhereToDoWork:{instruction:wvt,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:PEe.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:PEe.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:PEe.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};var yMe={agent:"sweagent-capi",model:"claude-sonnet-4"},$Xt=yMe;function SB(t){if(!t)return $Xt;let[e,...l]=t?.split(":")??[t,void 0],n=l.join(":")||void 0;return{agent:e||void 0,model:n||void 0}}function W0e(t,e){return e?.thinkingMode||to(t,"copilot_swe_agent_enable_responses_api")}import Kxt from"path";var E0e="4.12.0",BB="04b07795-8ddb-461a-bbee-02f9e1bf7b46",e5t="common",y0e;(function(t){t.AzureChina="https://login.chinacloudapi.cn",t.AzureGermany="https://login.microsoftonline.de",t.AzureGovernment="https://login.microsoftonline.us",t.AzurePublicCloud="https://login.microsoftonline.com"})(y0e||(y0e={}));var coe=y0e.AzurePublicCloud,t5t="login.microsoftonline.com",l5t=["*"],n5t="cae",r5t="nocae",a5t="msal.cache";var EMe;var Lin,R0e,s5t;function o5t(){return R0e!==void 0&&s5t!==void 0}function Jin(t){let e={cache:{},broker:{...t.brokerOptions,isEnabled:t.brokerOptions?.enabled??!1,enableMsaPassthrough:t.brokerOptions?.legacyEnableMsaPassthrough??!1}};if(t.tokenCachePersistenceOptions?.enabled){if(EMe===void 0)throw new Error(["Persistent token caching was requested, but no persistence provider was configured.","You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)","and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling","`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`."].join(" "));let l=t.tokenCachePersistenceOptions.name||a5t;e.cache.cachePlugin=EMe({name:`${l}.${r5t}`,...t.tokenCachePersistenceOptions}),e.cache.cachePluginCae=EMe({name:`${l}.${n5t}`,...t.tokenCachePersistenceOptions})}return t.brokerOptions?.enabled&&(e.broker.nativeBrokerPlugin=Sin(t.isVSCodeCredential||!1)),e}var I5t={missing:(t,e,l)=>[`${t} was requested, but no plugin was configured or no authentication record was found.`,`You must install the ${e} plugin package (npm install --save ${e})`,"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",`useIdentityPlugin(${l}) before using enableBroker.`].join(" "),unavailable:(t,e)=>[`${t} was requested, and the plugin is configured, but the broker is unavailable.`,`Ensure the ${t} plugin is properly installed and configured.`,"Check for missing native dependencies and ensure the package is properly installed.",`See the README for prerequisites on installing and using ${e}.`].join(" ")},xin={vsCode:{credentialName:"Visual Studio Code Credential",packageName:"@azure/identity-vscode",pluginVar:"vsCodePlugin",get brokerInfo(){return s5t}},native:{credentialName:"Broker for WAM",packageName:"@azure/identity-broker",pluginVar:"nativeBrokerPlugin",get brokerInfo(){return Lin}}};function Sin(t){let{credentialName:e,packageName:l,pluginVar:n,brokerInfo:r}=xin[t?"vsCode":"native"];if(r===void 0)throw new Error(I5t.missing(e,l,n));if(r.broker.isBrokerAvailable===!1)throw new Error(I5t.unavailable(e,l));return r.broker}var i5t={generatePluginConfiguration:Jin};function Bin(t){return t&&typeof t.error=="string"&&typeof t.error_description=="string"}var d5t="CredentialUnavailableError",tr=class extends Error{constructor(e,l){super(e,l),this.name=d5t}},Y0e="AuthenticationError",$4=class extends Error{statusCode;errorResponse;constructor(e,l,n){let r={error:"unknown",errorDescription:"An unknown error occurred and no additional details are available."};if(Bin(l))r=c5t(l);else if(typeof l=="string")try{let a=JSON.parse(l);r=c5t(a)}catch{e===400?r={error:"invalid_request",errorDescription:`The service indicated that the request was invalid.
|
|
1760
1760
|
|
|
1761
1761
|
${l}`}:r={error:"unknown_error",errorDescription:`An unknown error has occurred. Response body:
|
|
1762
1762
|
|
|
@@ -2018,19 +2018,19 @@ Pay attention to the following when using it:
|
|
|
2018
2018
|
This tool is used to perform a semantic search of the codebase to find relevant information based on the question asked.
|
|
2019
2019
|
* It leverages advanced AI techniques to understand the context and semantics of the codebase.
|
|
2020
2020
|
* Use this tool when you need to find information that is not easily accessible through traditional search methods.
|
|
2021
|
-
`,input_schema:{type:"object",properties:{question:{type:"string",description:"A question about the codebase. It should reference by name any topics, specific file names, and concepts that are relevant to the question and specify the desired output format."}},required:["question"]},callback:async n=>{let r,a=lZe(t),I="",s="",o=a.split("/");if(o.length===2){[I,s]=o,l.info("Searching for repository insights");try{r=await aKe(n.question,I,s,e,l),l.info(`Blackbird results: ${r}`)}catch(c){l.error(`Error occurred while searching for repository insights: ${c}`)}}return{resultType:"success",textResultForLlm:r??"No results found.",toolTelemetry:{}}}}}async function IUt(t,e,l,n,r,a){let I=await sUt(t),s=await yRn(t,e,l),o=rUt(e)?[new rVe(l,e,n,r,t,t.location,RWe(),a).getSearch()]:[],c=t.splitEditingTools?EBe(t,l,e):[RBe(t,l,e)];return[I.shellTool,...I.otherTools??[],...s,...o,...c,vRt(t,e,l,n),to(e,qte)?await oNt(t,l,n,e):void 0,t?.requireReasoning?VBe(t):void 0,to(e,VRt)?wRt:void 0,await ERn(t,e,l,n)].filter(d=>d!==void 0)}async function aVe(t,e){let l=await sUt(t),n=EBe(t,e);return[l.shellTool,...l.otherTools??[],...n,t?.requireReasoning?VBe(t):void 0,RE].filter(r=>r!==void 0)}async function WRn(t,e,l,n,r,a){return[...await IUt(t,e,l,n,r,a),QRt(t,l)]}var M8=t=>({...lY,supports:{...lY.supports,reasoning:t?.thinkingMode?!0:lY.supports?.reasoning}}),lY={supports:{tool_choice:!1,reasoning:!0,parallel_tool_calls:!1},createPR:{toolInit:IUt,jitInstructions:WMe},prDetails:{},respondToPRComment:{toolInit:WRn,jitInstructions:WMe}},_8=t=>({"sweagent-capi":{"claude-3.5-sonnet":{...lY,supports:{tool_choice:!1,reasoning:!1}},"claude-3.7-sonnet":{...lY,supports:{tool_choice:!1,reasoning:!1,vision:!0}},"claude-sonnet-4":{...lY,supports:{tool_choice:!1,reasoning:!0,parallel_tool_calls:!0,vision:!0},toolConfigOverrides:{splitEditingTools:!0}},"claude-sonnet-4.5":{...lY,supports:{tool_choice:!1,reasoning:!0,parallel_tool_calls:!0,vision:!0},toolConfigOverrides:{splitEditingTools:!0}},oswe:{...lY,supports:{tool_choice:!0,reasoning:!0,vision:!0,steering:!0}},"oswe-agent-a":{...lY,supports:{tool_choice:!0,reasoning:!0,vision:!0,steering:!0}},"gpt-5":{...lY,supports:{tool_choice:!0,reasoning:!0,parallel_tool_calls:!0,vision:!0,steering:!0},toolConfigOverrides:{splitEditingTools:!0}},"gpt-5-codex":{...lY,supports:{tool_choice:!0,reasoning:!0,parallel_tool_calls:!0,vision:!0,steering:!0},toolConfigOverrides:{splitEditingTools:!0}}}});async function sUt(t){let e=new kWe(t);return{shellTool:e.getShellTool(),otherTools:[e.getWriteShellTool(),e.getReadShellTool(),e.getStopShellTool()]}}async function yRn(t,e,l){if($9e(e,"cloud"))return[new Bne(new pye(e,l,void 0)).getStoreMemory()];if($9e(e,"local")){let n=new Bne(new Gye(t.location));return[n.getStoreMemory(),n.getReadMemory()]}return[]}async function ERn(t,e,l,n){if(t.includeCodeQLTool){let r=new hZ(l,n),a=e.swebench_base_commit&&e.swebench_base_commit!=="undefined"?e.swebench_base_commit:await r.getCurrentCommitHash(t.location);return new kx(t,r,a,e,l).getCodeQLCheckerTool()}}async function oUt(t,e){switch(t.kind){case"image_processing":return e.onImageProcessingEvent(t);case"images_removed":return e.onImageRemovalEvent(t);case"message":return e.onMessage(t);case"model_call_failure":return e.onModelCallFailure(t);case"model_call_success":return await e.onModelCallSuccess(t);case"response":return e.onResponse(t);case"tool_execution":return e.onToolExecution(t);case"history_truncated":return e.onTruncationEvent(t);case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":return e.onTurnEvent(t);default:wo(t,`Unknown event kind: ${JSON.stringify(t)}`)}}import{Writable as UCn}from"stream";var D={};fm(D,{BRAND:()=>jRn,DIRTY:()=>CT,EMPTY_PATH:()=>wRn,INVALID:()=>zr,NEVER:()=>y2n,OK:()=>Th,ParseStatus:()=>vp,Schema:()=>VI,ZodAny:()=>ZL,ZodArray:()=>mv,ZodBigInt:()=>vT,ZodBoolean:()=>HT,ZodBranded:()=>Kde,ZodCatch:()=>MT,ZodDate:()=>XT,ZodDefault:()=>UT,ZodDiscriminatedUnion:()=>oVe,ZodEffects:()=>p0,ZodEnum:()=>TT,ZodError:()=>Bh,ZodFirstPartyTypeKind:()=>ta,ZodFunction:()=>cVe,ZodIntersection:()=>xT,ZodIssueCode:()=>Hl,ZodLazy:()=>ST,ZodLiteral:()=>BT,ZodMap:()=>q8,ZodNaN:()=>eq,ZodNativeEnum:()=>OT,ZodNever:()=>nY,ZodNull:()=>LT,ZodNullable:()=>Sw,ZodNumber:()=>fT,ZodObject:()=>nN,ZodOptional:()=>b0,ZodParsedType:()=>Xn,ZodPipeline:()=>qde,ZodPromise:()=>NL,ZodReadonly:()=>_T,ZodRecord:()=>iVe,ZodSchema:()=>VI,ZodSet:()=>$8,ZodString:()=>gL,ZodSymbol:()=>j8,ZodTransformer:()=>p0,ZodTuple:()=>xw,ZodType:()=>VI,ZodUndefined:()=>kT,ZodUnion:()=>JT,ZodUnknown:()=>uv,ZodVoid:()=>K8,addIssueToContext:()=>Nn,any:()=>dKe,array:()=>Od,bigint:()=>e2n,boolean:()=>ro,coerce:()=>uVe,custom:()=>pUt,date:()=>t2n,datetimeRegex:()=>bUt,defaultErrorMap:()=>cv,discriminatedUnion:()=>$de,effect:()=>G2n,enum:()=>h0,function:()=>d2n,getErrorMap:()=>D8,getParsedType:()=>Jw,instanceof:()=>qRn,intersection:()=>o2n,isAborted:()=>IVe,isAsync:()=>z8,isDirty:()=>sVe,isValid:()=>AL,late:()=>KRn,lazy:()=>u2n,literal:()=>pr,makeIssue:()=>jde,map:()=>i2n,nan:()=>$Rn,nativeEnum:()=>m2n,never:()=>a2n,null:()=>r2n,nullable:()=>h2n,number:()=>Pm,object:()=>zl,objectUtil:()=>oKe,oboolean:()=>W2n,onumber:()=>N2n,optional:()=>p2n,ostring:()=>Z2n,pipeline:()=>g2n,preprocess:()=>A2n,promise:()=>b2n,quotelessJson:()=>RRn,record:()=>rY,set:()=>c2n,setErrorMap:()=>VRn,strictObject:()=>s2n,string:()=>Qt,symbol:()=>l2n,transformer:()=>G2n,tuple:()=>dVe,undefined:()=>n2n,union:()=>Oh,unknown:()=>Bw,util:()=>ds,void:()=>I2n});var ds;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function l(r){throw new Error}t.assertNever=l,t.arrayToEnum=r=>{let a={};for(let I of r)a[I]=I;return a},t.getValidEnumValues=r=>{let a=t.objectKeys(r).filter(s=>typeof r[r[s]]!="number"),I={};for(let s of a)I[s]=r[s];return t.objectValues(I)},t.objectValues=r=>t.objectKeys(r).map(function(a){return r[a]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{let a=[];for(let I in r)Object.prototype.hasOwnProperty.call(r,I)&&a.push(I);return a},t.find=(r,a)=>{for(let I of r)if(a(I))return I},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function n(r,a=" | "){return r.map(I=>typeof I=="string"?`'${I}'`:I).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(r,a)=>typeof a=="bigint"?a.toString():a})(ds||(ds={}));var oKe;(function(t){t.mergeShapes=(e,l)=>({...e,...l})})(oKe||(oKe={}));var Xn=ds.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Jw=t=>{switch(typeof t){case"undefined":return Xn.undefined;case"string":return Xn.string;case"number":return Number.isNaN(t)?Xn.nan:Xn.number;case"boolean":return Xn.boolean;case"function":return Xn.function;case"bigint":return Xn.bigint;case"symbol":return Xn.symbol;case"object":return Array.isArray(t)?Xn.array:t===null?Xn.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Xn.promise:typeof Map<"u"&&t instanceof Map?Xn.map:typeof Set<"u"&&t instanceof Set?Xn.set:typeof Date<"u"&&t instanceof Date?Xn.date:Xn.object;default:return Xn.unknown}};var Hl=ds.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),RRn=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Bh=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let l=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,l):this.__proto__=l,this.name="ZodError",this.issues=e}format(e){let l=e||function(a){return a.message},n={_errors:[]},r=a=>{for(let I of a.issues)if(I.code==="invalid_union")I.unionErrors.map(r);else if(I.code==="invalid_return_type")r(I.returnTypeError);else if(I.code==="invalid_arguments")r(I.argumentsError);else if(I.path.length===0)n._errors.push(l(I));else{let s=n,o=0;for(;o<I.path.length;){let c=I.path[o];o===I.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(l(I))):s[c]=s[c]||{_errors:[]},s=s[c],o++}}};return r(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ds.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=l=>l.message){let l={},n=[];for(let r of this.issues)if(r.path.length>0){let a=r.path[0];l[a]=l[a]||[],l[a].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:l}}get formErrors(){return this.flatten()}};Bh.create=t=>new Bh(t);var YRn=(t,e)=>{let l;switch(t.code){case Hl.invalid_type:t.received===Xn.undefined?l="Required":l=`Expected ${t.expected}, received ${t.received}`;break;case Hl.invalid_literal:l=`Invalid literal value, expected ${JSON.stringify(t.expected,ds.jsonStringifyReplacer)}`;break;case Hl.unrecognized_keys:l=`Unrecognized key(s) in object: ${ds.joinValues(t.keys,", ")}`;break;case Hl.invalid_union:l="Invalid input";break;case Hl.invalid_union_discriminator:l=`Invalid discriminator value. Expected ${ds.joinValues(t.options)}`;break;case Hl.invalid_enum_value:l=`Invalid enum value. Expected ${ds.joinValues(t.options)}, received '${t.received}'`;break;case Hl.invalid_arguments:l="Invalid function arguments";break;case Hl.invalid_return_type:l="Invalid function return type";break;case Hl.invalid_date:l="Invalid date";break;case Hl.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(l=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(l=`${l} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?l=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?l=`Invalid input: must end with "${t.validation.endsWith}"`:ds.assertNever(t.validation):t.validation!=="regex"?l=`Invalid ${t.validation}`:l="Invalid";break;case Hl.too_small:t.type==="array"?l=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?l=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?l=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?l=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?l=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:l="Invalid input";break;case Hl.too_big:t.type==="array"?l=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?l=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?l=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?l=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?l=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:l="Invalid input";break;case Hl.custom:l="Invalid input";break;case Hl.invalid_intersection_types:l="Intersection results could not be merged";break;case Hl.not_multiple_of:l=`Number must be a multiple of ${t.multipleOf}`;break;case Hl.not_finite:l="Number must be finite";break;default:l=e.defaultError,ds.assertNever(t)}return{message:l}},cv=YRn;var iUt=cv;function VRn(t){iUt=t}function D8(){return iUt}var jde=t=>{let{data:e,path:l,errorMaps:n,issueData:r}=t,a=[...l,...r.path||[]],I={...r,path:a};if(r.message!==void 0)return{...r,path:a,message:r.message};let s="",o=n.filter(c=>!!c).slice().reverse();for(let c of o)s=c(I,{data:e,defaultError:s}).message;return{...r,path:a,message:s}},wRn=[];function Nn(t,e){let l=D8(),n=jde({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,l,l===cv?void 0:cv].filter(r=>!!r)});t.common.issues.push(n)}var vp=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,l){let n=[];for(let r of l){if(r.status==="aborted")return zr;r.status==="dirty"&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,l){let n=[];for(let r of l){let a=await r.key,I=await r.value;n.push({key:a,value:I})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,l){let n={};for(let r of l){let{key:a,value:I}=r;if(a.status==="aborted"||I.status==="aborted")return zr;a.status==="dirty"&&e.dirty(),I.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof I.value<"u"||r.alwaysSet)&&(n[a.value]=I.value)}return{status:e.value,value:n}}},zr=Object.freeze({status:"aborted"}),CT=t=>({status:"dirty",value:t}),Th=t=>({status:"valid",value:t}),IVe=t=>t.status==="aborted",sVe=t=>t.status==="dirty",AL=t=>t.status==="valid",z8=t=>typeof Promise<"u"&&t instanceof Promise;var dr;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(dr||(dr={}));var G0=class{constructor(e,l,n,r){this._cachedPath=[],this.parent=e,this.data=l,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},cUt=(t,e)=>{if(AL(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let l=new Bh(t.common.issues);return this._error=l,this._error}}};function aI(t){if(!t)return{};let{errorMap:e,invalid_type_error:l,required_error:n,description:r}=t;if(e&&(l||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(I,s)=>{let{message:o}=t;return I.code==="invalid_enum_value"?{message:o??s.defaultError}:typeof s.data>"u"?{message:o??n??s.defaultError}:I.code!=="invalid_type"?{message:s.defaultError}:{message:o??l??s.defaultError}},description:r}}var VI=class{get description(){return this._def.description}_getType(e){return Jw(e.data)}_getOrReturnCtx(e,l){return l||{common:e.parent.common,data:e.data,parsedType:Jw(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new vp,ctx:{common:e.parent.common,data:e.data,parsedType:Jw(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let l=this._parse(e);if(z8(l))throw new Error("Synchronous parse encountered promise.");return l}_parseAsync(e){let l=this._parse(e);return Promise.resolve(l)}parse(e,l){let n=this.safeParse(e,l);if(n.success)return n.data;throw n.error}safeParse(e,l){let n={common:{issues:[],async:l?.async??!1,contextualErrorMap:l?.errorMap},path:l?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jw(e)},r=this._parseSync({data:e,path:n.path,parent:n});return cUt(n,r)}"~validate"(e){let l={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jw(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:l});return AL(n)?{value:n.value}:{issues:l.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),l.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:l}).then(n=>AL(n)?{value:n.value}:{issues:l.common.issues})}async parseAsync(e,l){let n=await this.safeParseAsync(e,l);if(n.success)return n.data;throw n.error}async safeParseAsync(e,l){let n={common:{issues:[],contextualErrorMap:l?.errorMap,async:!0},path:l?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jw(e)},r=this._parse({data:e,path:n.path,parent:n}),a=await(z8(r)?r:Promise.resolve(r));return cUt(n,a)}refine(e,l){let n=r=>typeof l=="string"||typeof l>"u"?{message:l}:typeof l=="function"?l(r):l;return this._refinement((r,a)=>{let I=e(r),s=()=>a.addIssue({code:Hl.custom,...n(r)});return typeof Promise<"u"&&I instanceof Promise?I.then(o=>o?!0:(s(),!1)):I?!0:(s(),!1)})}refinement(e,l){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof l=="function"?l(n,r):l),!1))}_refinement(e){return new p0({schema:this,typeName:ta.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:l=>this["~validate"](l)}}optional(){return b0.create(this,this._def)}nullable(){return Sw.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mv.create(this)}promise(){return NL.create(this,this._def)}or(e){return JT.create([this,e],this._def)}and(e){return xT.create(this,e,this._def)}transform(e){return new p0({...aI(this._def),schema:this,typeName:ta.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let l=typeof e=="function"?e:()=>e;return new UT({...aI(this._def),innerType:this,defaultValue:l,typeName:ta.ZodDefault})}brand(){return new Kde({typeName:ta.ZodBranded,type:this,...aI(this._def)})}catch(e){let l=typeof e=="function"?e:()=>e;return new MT({...aI(this._def),innerType:this,catchValue:l,typeName:ta.ZodCatch})}describe(e){let l=this.constructor;return new l({...this._def,description:e})}pipe(e){return qde.create(this,e)}readonly(){return _T.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},QRn=/^c[^\s-]{8,}$/i,FRn=/^[0-9a-z]+$/,CRn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fRn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,vRn=/^[a-z0-9_-]{21}$/i,HRn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,XRn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,kRn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,LRn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",iKe,JRn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xRn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,SRn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,BRn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,TRn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ORn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,uUt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",URn=new RegExp(`^${uUt}$`);function mUt(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let l=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${l}`}function MRn(t){return new RegExp(`^${mUt(t)}$`)}function bUt(t){let e=`${uUt}T${mUt(t)}`,l=[];return l.push(t.local?"Z?":"Z"),t.offset&&l.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${l.join("|")})`,new RegExp(`^${e}$`)}function _Rn(t,e){return!!((e==="v4"||!e)&&JRn.test(t)||(e==="v6"||!e)&&SRn.test(t))}function DRn(t,e){if(!HRn.test(t))return!1;try{let[l]=t.split(".");if(!l)return!1;let n=l.replace(/-/g,"+").replace(/_/g,"/").padEnd(l.length+(4-l.length%4)%4,"="),r=JSON.parse(atob(n));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function zRn(t,e){return!!((e==="v4"||!e)&&xRn.test(t)||(e==="v6"||!e)&&BRn.test(t))}var gL=class t extends VI{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Xn.string){let a=this._getOrReturnCtx(e);return Nn(a,{code:Hl.invalid_type,expected:Xn.string,received:a.parsedType}),zr}let n=new vp,r;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let I=e.data.length>a.value,s=e.data.length<a.value;(I||s)&&(r=this._getOrReturnCtx(e,r),I?Nn(r,{code:Hl.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&Nn(r,{code:Hl.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")kRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"email",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")iKe||(iKe=new RegExp(LRn,"u")),iKe.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"emoji",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")fRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"uuid",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")vRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"nanoid",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")QRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"cuid",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")FRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"cuid2",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")CRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"ulid",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Nn(r,{validation:"url",code:Hl.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"regex",code:Hl.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?bUt(a).test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?URn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?MRn(a).test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?XRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"duration",code:Hl.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?_Rn(e.data,a.version)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"ip",code:Hl.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?DRn(e.data,a.alg)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"jwt",code:Hl.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?zRn(e.data,a.version)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"cidr",code:Hl.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?TRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"base64",code:Hl.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?ORn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"base64url",code:Hl.invalid_string,message:a.message}),n.dirty()):ds.assertNever(a);return{status:n.value,value:e.data}}_regex(e,l,n){return this.refinement(r=>e.test(r),{validation:l,code:Hl.invalid_string,...dr.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...dr.errToObj(e)})}url(e){return this._addCheck({kind:"url",...dr.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...dr.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...dr.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...dr.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...dr.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...dr.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...dr.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...dr.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...dr.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...dr.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...dr.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...dr.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...dr.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...dr.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...dr.errToObj(e)})}regex(e,l){return this._addCheck({kind:"regex",regex:e,...dr.errToObj(l)})}includes(e,l){return this._addCheck({kind:"includes",value:e,position:l?.position,...dr.errToObj(l?.message)})}startsWith(e,l){return this._addCheck({kind:"startsWith",value:e,...dr.errToObj(l)})}endsWith(e,l){return this._addCheck({kind:"endsWith",value:e,...dr.errToObj(l)})}min(e,l){return this._addCheck({kind:"min",value:e,...dr.errToObj(l)})}max(e,l){return this._addCheck({kind:"max",value:e,...dr.errToObj(l)})}length(e,l){return this._addCheck({kind:"length",value:e,...dr.errToObj(l)})}nonempty(e){return this.min(1,dr.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let l of this._def.checks)l.kind==="min"&&(e===null||l.value>e)&&(e=l.value);return e}get maxLength(){let e=null;for(let l of this._def.checks)l.kind==="max"&&(e===null||l.value<e)&&(e=l.value);return e}};gL.create=t=>new gL({checks:[],typeName:ta.ZodString,coerce:t?.coerce??!1,...aI(t)});function PRn(t,e){let l=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,r=l>n?l:n,a=Number.parseInt(t.toFixed(r).replace(".","")),I=Number.parseInt(e.toFixed(r).replace(".",""));return a%I/10**r}var fT=class t extends VI{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Xn.number){let a=this._getOrReturnCtx(e);return Nn(a,{code:Hl.invalid_type,expected:Xn.number,received:a.parsedType}),zr}let n,r=new vp;for(let a of this._def.checks)a.kind==="int"?ds.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):a.kind==="multipleOf"?PRn(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.not_finite,message:a.message}),r.dirty()):ds.assertNever(a);return{status:r.value,value:e.data}}gte(e,l){return this.setLimit("min",e,!0,dr.toString(l))}gt(e,l){return this.setLimit("min",e,!1,dr.toString(l))}lte(e,l){return this.setLimit("max",e,!0,dr.toString(l))}lt(e,l){return this.setLimit("max",e,!1,dr.toString(l))}setLimit(e,l,n,r){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:l,inclusive:n,message:dr.toString(r)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:dr.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:dr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:dr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:dr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:dr.toString(e)})}multipleOf(e,l){return this._addCheck({kind:"multipleOf",value:e,message:dr.toString(l)})}finite(e){return this._addCheck({kind:"finite",message:dr.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:dr.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:dr.toString(e)})}get minValue(){let e=null;for(let l of this._def.checks)l.kind==="min"&&(e===null||l.value>e)&&(e=l.value);return e}get maxValue(){let e=null;for(let l of this._def.checks)l.kind==="max"&&(e===null||l.value<e)&&(e=l.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ds.isInteger(e.value))}get isFinite(){let e=null,l=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(l===null||n.value>l)&&(l=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(l)&&Number.isFinite(e)}};fT.create=t=>new fT({checks:[],typeName:ta.ZodNumber,coerce:t?.coerce||!1,...aI(t)});var vT=class t extends VI{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Xn.bigint)return this._getInvalidInput(e);let n,r=new vp;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):ds.assertNever(a);return{status:r.value,value:e.data}}_getInvalidInput(e){let l=this._getOrReturnCtx(e);return Nn(l,{code:Hl.invalid_type,expected:Xn.bigint,received:l.parsedType}),zr}gte(e,l){return this.setLimit("min",e,!0,dr.toString(l))}gt(e,l){return this.setLimit("min",e,!1,dr.toString(l))}lte(e,l){return this.setLimit("max",e,!0,dr.toString(l))}lt(e,l){return this.setLimit("max",e,!1,dr.toString(l))}setLimit(e,l,n,r){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:l,inclusive:n,message:dr.toString(r)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:dr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:dr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:dr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:dr.toString(e)})}multipleOf(e,l){return this._addCheck({kind:"multipleOf",value:e,message:dr.toString(l)})}get minValue(){let e=null;for(let l of this._def.checks)l.kind==="min"&&(e===null||l.value>e)&&(e=l.value);return e}get maxValue(){let e=null;for(let l of this._def.checks)l.kind==="max"&&(e===null||l.value<e)&&(e=l.value);return e}};vT.create=t=>new vT({checks:[],typeName:ta.ZodBigInt,coerce:t?.coerce??!1,...aI(t)});var HT=class extends VI{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Xn.boolean){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.boolean,received:n.parsedType}),zr}return Th(e.data)}};HT.create=t=>new HT({typeName:ta.ZodBoolean,coerce:t?.coerce||!1,...aI(t)});var XT=class t extends VI{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Xn.date){let a=this._getOrReturnCtx(e);return Nn(a,{code:Hl.invalid_type,expected:Xn.date,received:a.parsedType}),zr}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return Nn(a,{code:Hl.invalid_date}),zr}let n=new vp,r;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):ds.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,l){return this._addCheck({kind:"min",value:e.getTime(),message:dr.toString(l)})}max(e,l){return this._addCheck({kind:"max",value:e.getTime(),message:dr.toString(l)})}get minDate(){let e=null;for(let l of this._def.checks)l.kind==="min"&&(e===null||l.value>e)&&(e=l.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let l of this._def.checks)l.kind==="max"&&(e===null||l.value<e)&&(e=l.value);return e!=null?new Date(e):null}};XT.create=t=>new XT({checks:[],coerce:t?.coerce||!1,typeName:ta.ZodDate,...aI(t)});var j8=class extends VI{_parse(e){if(this._getType(e)!==Xn.symbol){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.symbol,received:n.parsedType}),zr}return Th(e.data)}};j8.create=t=>new j8({typeName:ta.ZodSymbol,...aI(t)});var kT=class extends VI{_parse(e){if(this._getType(e)!==Xn.undefined){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.undefined,received:n.parsedType}),zr}return Th(e.data)}};kT.create=t=>new kT({typeName:ta.ZodUndefined,...aI(t)});var LT=class extends VI{_parse(e){if(this._getType(e)!==Xn.null){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.null,received:n.parsedType}),zr}return Th(e.data)}};LT.create=t=>new LT({typeName:ta.ZodNull,...aI(t)});var ZL=class extends VI{constructor(){super(...arguments),this._any=!0}_parse(e){return Th(e.data)}};ZL.create=t=>new ZL({typeName:ta.ZodAny,...aI(t)});var uv=class extends VI{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Th(e.data)}};uv.create=t=>new uv({typeName:ta.ZodUnknown,...aI(t)});var nY=class extends VI{_parse(e){let l=this._getOrReturnCtx(e);return Nn(l,{code:Hl.invalid_type,expected:Xn.never,received:l.parsedType}),zr}};nY.create=t=>new nY({typeName:ta.ZodNever,...aI(t)});var K8=class extends VI{_parse(e){if(this._getType(e)!==Xn.undefined){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.void,received:n.parsedType}),zr}return Th(e.data)}};K8.create=t=>new K8({typeName:ta.ZodVoid,...aI(t)});var mv=class t extends VI{_parse(e){let{ctx:l,status:n}=this._processInputParams(e),r=this._def;if(l.parsedType!==Xn.array)return Nn(l,{code:Hl.invalid_type,expected:Xn.array,received:l.parsedType}),zr;if(r.exactLength!==null){let I=l.data.length>r.exactLength.value,s=l.data.length<r.exactLength.value;(I||s)&&(Nn(l,{code:I?Hl.too_big:Hl.too_small,minimum:s?r.exactLength.value:void 0,maximum:I?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&l.data.length<r.minLength.value&&(Nn(l,{code:Hl.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&l.data.length>r.maxLength.value&&(Nn(l,{code:Hl.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),l.common.async)return Promise.all([...l.data].map((I,s)=>r.type._parseAsync(new G0(l,I,l.path,s)))).then(I=>vp.mergeArray(n,I));let a=[...l.data].map((I,s)=>r.type._parseSync(new G0(l,I,l.path,s)));return vp.mergeArray(n,a)}get element(){return this._def.type}min(e,l){return new t({...this._def,minLength:{value:e,message:dr.toString(l)}})}max(e,l){return new t({...this._def,maxLength:{value:e,message:dr.toString(l)}})}length(e,l){return new t({...this._def,exactLength:{value:e,message:dr.toString(l)}})}nonempty(e){return this.min(1,e)}};mv.create=(t,e)=>new mv({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ta.ZodArray,...aI(e)});function P8(t){if(t instanceof nN){let e={};for(let l in t.shape){let n=t.shape[l];e[l]=b0.create(P8(n))}return new nN({...t._def,shape:()=>e})}else return t instanceof mv?new mv({...t._def,type:P8(t.element)}):t instanceof b0?b0.create(P8(t.unwrap())):t instanceof Sw?Sw.create(P8(t.unwrap())):t instanceof xw?xw.create(t.items.map(e=>P8(e))):t}var nN=class t extends VI{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),l=ds.objectKeys(e);return this._cached={shape:e,keys:l},this._cached}_parse(e){if(this._getType(e)!==Xn.object){let c=this._getOrReturnCtx(e);return Nn(c,{code:Hl.invalid_type,expected:Xn.object,received:c.parsedType}),zr}let{status:n,ctx:r}=this._processInputParams(e),{shape:a,keys:I}=this._getCached(),s=[];if(!(this._def.catchall instanceof nY&&this._def.unknownKeys==="strip"))for(let c in r.data)I.includes(c)||s.push(c);let o=[];for(let c of I){let d=a[c],m=r.data[c];o.push({key:{status:"valid",value:c},value:d._parse(new G0(r,m,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof nY){let c=this._def.unknownKeys;if(c==="passthrough")for(let d of s)o.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(c==="strict")s.length>0&&(Nn(r,{code:Hl.unrecognized_keys,keys:s}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let d of s){let m=r.data[d];o.push({key:{status:"valid",value:d},value:c._parse(new G0(r,m,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let c=[];for(let d of o){let m=await d.key,b=await d.value;c.push({key:m,value:b,alwaysSet:d.alwaysSet})}return c}).then(c=>vp.mergeObjectSync(n,c)):vp.mergeObjectSync(n,o)}get shape(){return this._def.shape()}strict(e){return dr.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(l,n)=>{let r=this._def.errorMap?.(l,n).message??n.defaultError;return l.code==="unrecognized_keys"?{message:dr.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ta.ZodObject})}setKey(e,l){return this.augment({[e]:l})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let l={};for(let n of ds.objectKeys(e))e[n]&&this.shape[n]&&(l[n]=this.shape[n]);return new t({...this._def,shape:()=>l})}omit(e){let l={};for(let n of ds.objectKeys(this.shape))e[n]||(l[n]=this.shape[n]);return new t({...this._def,shape:()=>l})}deepPartial(){return P8(this)}partial(e){let l={};for(let n of ds.objectKeys(this.shape)){let r=this.shape[n];e&&!e[n]?l[n]=r:l[n]=r.optional()}return new t({...this._def,shape:()=>l})}required(e){let l={};for(let n of ds.objectKeys(this.shape))if(e&&!e[n])l[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof b0;)a=a._def.innerType;l[n]=a}return new t({...this._def,shape:()=>l})}keyof(){return GUt(ds.objectKeys(this.shape))}};nN.create=(t,e)=>new nN({shape:()=>t,unknownKeys:"strip",catchall:nY.create(),typeName:ta.ZodObject,...aI(e)});nN.strictCreate=(t,e)=>new nN({shape:()=>t,unknownKeys:"strict",catchall:nY.create(),typeName:ta.ZodObject,...aI(e)});nN.lazycreate=(t,e)=>new nN({shape:t,unknownKeys:"strip",catchall:nY.create(),typeName:ta.ZodObject,...aI(e)});var JT=class extends VI{_parse(e){let{ctx:l}=this._processInputParams(e),n=this._def.options;function r(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return l.common.issues.push(...s.ctx.common.issues),s.result;let I=a.map(s=>new Bh(s.ctx.common.issues));return Nn(l,{code:Hl.invalid_union,unionErrors:I}),zr}if(l.common.async)return Promise.all(n.map(async a=>{let I={...l,common:{...l.common,issues:[]},parent:null};return{result:await a._parseAsync({data:l.data,path:l.path,parent:I}),ctx:I}})).then(r);{let a,I=[];for(let o of n){let c={...l,common:{...l.common,issues:[]},parent:null},d=o._parseSync({data:l.data,path:l.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!a&&(a={result:d,ctx:c}),c.common.issues.length&&I.push(c.common.issues)}if(a)return l.common.issues.push(...a.ctx.common.issues),a.result;let s=I.map(o=>new Bh(o));return Nn(l,{code:Hl.invalid_union,unionErrors:s}),zr}}get options(){return this._def.options}};JT.create=(t,e)=>new JT({options:t,typeName:ta.ZodUnion,...aI(e)});var dv=t=>t instanceof ST?dv(t.schema):t instanceof p0?dv(t.innerType()):t instanceof BT?[t.value]:t instanceof TT?t.options:t instanceof OT?ds.objectValues(t.enum):t instanceof UT?dv(t._def.innerType):t instanceof kT?[void 0]:t instanceof LT?[null]:t instanceof b0?[void 0,...dv(t.unwrap())]:t instanceof Sw?[null,...dv(t.unwrap())]:t instanceof Kde||t instanceof _T?dv(t.unwrap()):t instanceof MT?dv(t._def.innerType):[],oVe=class t extends VI{_parse(e){let{ctx:l}=this._processInputParams(e);if(l.parsedType!==Xn.object)return Nn(l,{code:Hl.invalid_type,expected:Xn.object,received:l.parsedType}),zr;let n=this.discriminator,r=l.data[n],a=this.optionsMap.get(r);return a?l.common.async?a._parseAsync({data:l.data,path:l.path,parent:l}):a._parseSync({data:l.data,path:l.path,parent:l}):(Nn(l,{code:Hl.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),zr)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,l,n){let r=new Map;for(let a of l){let I=dv(a.shape[e]);if(!I.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of I){if(r.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);r.set(s,a)}}return new t({typeName:ta.ZodDiscriminatedUnion,discriminator:e,options:l,optionsMap:r,...aI(n)})}};function cKe(t,e){let l=Jw(t),n=Jw(e);if(t===e)return{valid:!0,data:t};if(l===Xn.object&&n===Xn.object){let r=ds.objectKeys(e),a=ds.objectKeys(t).filter(s=>r.indexOf(s)!==-1),I={...t,...e};for(let s of a){let o=cKe(t[s],e[s]);if(!o.valid)return{valid:!1};I[s]=o.data}return{valid:!0,data:I}}else if(l===Xn.array&&n===Xn.array){if(t.length!==e.length)return{valid:!1};let r=[];for(let a=0;a<t.length;a++){let I=t[a],s=e[a],o=cKe(I,s);if(!o.valid)return{valid:!1};r.push(o.data)}return{valid:!0,data:r}}else return l===Xn.date&&n===Xn.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var xT=class extends VI{_parse(e){let{status:l,ctx:n}=this._processInputParams(e),r=(a,I)=>{if(IVe(a)||IVe(I))return zr;let s=cKe(a.value,I.value);return s.valid?((sVe(a)||sVe(I))&&l.dirty(),{status:l.value,value:s.data}):(Nn(n,{code:Hl.invalid_intersection_types}),zr)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,I])=>r(a,I)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};xT.create=(t,e,l)=>new xT({left:t,right:e,typeName:ta.ZodIntersection,...aI(l)});var xw=class t extends VI{_parse(e){let{status:l,ctx:n}=this._processInputParams(e);if(n.parsedType!==Xn.array)return Nn(n,{code:Hl.invalid_type,expected:Xn.array,received:n.parsedType}),zr;if(n.data.length<this._def.items.length)return Nn(n,{code:Hl.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),zr;!this._def.rest&&n.data.length>this._def.items.length&&(Nn(n,{code:Hl.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),l.dirty());let a=[...n.data].map((I,s)=>{let o=this._def.items[s]||this._def.rest;return o?o._parse(new G0(n,I,n.path,s)):null}).filter(I=>!!I);return n.common.async?Promise.all(a).then(I=>vp.mergeArray(l,I)):vp.mergeArray(l,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};xw.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xw({items:t,typeName:ta.ZodTuple,rest:null,...aI(e)})};var iVe=class t extends VI{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:l,ctx:n}=this._processInputParams(e);if(n.parsedType!==Xn.object)return Nn(n,{code:Hl.invalid_type,expected:Xn.object,received:n.parsedType}),zr;let r=[],a=this._def.keyType,I=this._def.valueType;for(let s in n.data)r.push({key:a._parse(new G0(n,s,n.path,s)),value:I._parse(new G0(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?vp.mergeObjectAsync(l,r):vp.mergeObjectSync(l,r)}get element(){return this._def.valueType}static create(e,l,n){return l instanceof VI?new t({keyType:e,valueType:l,typeName:ta.ZodRecord,...aI(n)}):new t({keyType:gL.create(),valueType:e,typeName:ta.ZodRecord,...aI(l)})}},q8=class extends VI{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:l,ctx:n}=this._processInputParams(e);if(n.parsedType!==Xn.map)return Nn(n,{code:Hl.invalid_type,expected:Xn.map,received:n.parsedType}),zr;let r=this._def.keyType,a=this._def.valueType,I=[...n.data.entries()].map(([s,o],c)=>({key:r._parse(new G0(n,s,n.path,[c,"key"])),value:a._parse(new G0(n,o,n.path,[c,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let o of I){let c=await o.key,d=await o.value;if(c.status==="aborted"||d.status==="aborted")return zr;(c.status==="dirty"||d.status==="dirty")&&l.dirty(),s.set(c.value,d.value)}return{status:l.value,value:s}})}else{let s=new Map;for(let o of I){let c=o.key,d=o.value;if(c.status==="aborted"||d.status==="aborted")return zr;(c.status==="dirty"||d.status==="dirty")&&l.dirty(),s.set(c.value,d.value)}return{status:l.value,value:s}}}};q8.create=(t,e,l)=>new q8({valueType:e,keyType:t,typeName:ta.ZodMap,...aI(l)});var $8=class t extends VI{_parse(e){let{status:l,ctx:n}=this._processInputParams(e);if(n.parsedType!==Xn.set)return Nn(n,{code:Hl.invalid_type,expected:Xn.set,received:n.parsedType}),zr;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(Nn(n,{code:Hl.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),l.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(Nn(n,{code:Hl.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),l.dirty());let a=this._def.valueType;function I(o){let c=new Set;for(let d of o){if(d.status==="aborted")return zr;d.status==="dirty"&&l.dirty(),c.add(d.value)}return{status:l.value,value:c}}let s=[...n.data.values()].map((o,c)=>a._parse(new G0(n,o,n.path,c)));return n.common.async?Promise.all(s).then(o=>I(o)):I(s)}min(e,l){return new t({...this._def,minSize:{value:e,message:dr.toString(l)}})}max(e,l){return new t({...this._def,maxSize:{value:e,message:dr.toString(l)}})}size(e,l){return this.min(e,l).max(e,l)}nonempty(e){return this.min(1,e)}};$8.create=(t,e)=>new $8({valueType:t,minSize:null,maxSize:null,typeName:ta.ZodSet,...aI(e)});var cVe=class t extends VI{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:l}=this._processInputParams(e);if(l.parsedType!==Xn.function)return Nn(l,{code:Hl.invalid_type,expected:Xn.function,received:l.parsedType}),zr;function n(s,o){return jde({data:s,path:l.path,errorMaps:[l.common.contextualErrorMap,l.schemaErrorMap,D8(),cv].filter(c=>!!c),issueData:{code:Hl.invalid_arguments,argumentsError:o}})}function r(s,o){return jde({data:s,path:l.path,errorMaps:[l.common.contextualErrorMap,l.schemaErrorMap,D8(),cv].filter(c=>!!c),issueData:{code:Hl.invalid_return_type,returnTypeError:o}})}let a={errorMap:l.common.contextualErrorMap},I=l.data;if(this._def.returns instanceof NL){let s=this;return Th(async function(...o){let c=new Bh([]),d=await s._def.args.parseAsync(o,a).catch(p=>{throw c.addIssue(n(o,p)),c}),m=await Reflect.apply(I,this,d);return await s._def.returns._def.type.parseAsync(m,a).catch(p=>{throw c.addIssue(r(m,p)),c})})}else{let s=this;return Th(function(...o){let c=s._def.args.safeParse(o,a);if(!c.success)throw new Bh([n(o,c.error)]);let d=Reflect.apply(I,this,c.data),m=s._def.returns.safeParse(d,a);if(!m.success)throw new Bh([r(d,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:xw.create(e).rest(uv.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,l,n){return new t({args:e||xw.create([]).rest(uv.create()),returns:l||uv.create(),typeName:ta.ZodFunction,...aI(n)})}},ST=class extends VI{get schema(){return this._def.getter()}_parse(e){let{ctx:l}=this._processInputParams(e);return this._def.getter()._parse({data:l.data,path:l.path,parent:l})}};ST.create=(t,e)=>new ST({getter:t,typeName:ta.ZodLazy,...aI(e)});var BT=class extends VI{_parse(e){if(e.data!==this._def.value){let l=this._getOrReturnCtx(e);return Nn(l,{received:l.data,code:Hl.invalid_literal,expected:this._def.value}),zr}return{status:"valid",value:e.data}}get value(){return this._def.value}};BT.create=(t,e)=>new BT({value:t,typeName:ta.ZodLiteral,...aI(e)});function GUt(t,e){return new TT({values:t,typeName:ta.ZodEnum,...aI(e)})}var TT=class t extends VI{_parse(e){if(typeof e.data!="string"){let l=this._getOrReturnCtx(e),n=this._def.values;return Nn(l,{expected:ds.joinValues(n),received:l.parsedType,code:Hl.invalid_type}),zr}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let l=this._getOrReturnCtx(e),n=this._def.values;return Nn(l,{received:l.data,code:Hl.invalid_enum_value,options:n}),zr}return Th(e.data)}get options(){return this._def.values}get enum(){let e={};for(let l of this._def.values)e[l]=l;return e}get Values(){let e={};for(let l of this._def.values)e[l]=l;return e}get Enum(){let e={};for(let l of this._def.values)e[l]=l;return e}extract(e,l=this._def){return t.create(e,{...this._def,...l})}exclude(e,l=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...l})}};TT.create=GUt;var OT=class extends VI{_parse(e){let l=ds.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Xn.string&&n.parsedType!==Xn.number){let r=ds.objectValues(l);return Nn(n,{expected:ds.joinValues(r),received:n.parsedType,code:Hl.invalid_type}),zr}if(this._cache||(this._cache=new Set(ds.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let r=ds.objectValues(l);return Nn(n,{received:n.data,code:Hl.invalid_enum_value,options:r}),zr}return Th(e.data)}get enum(){return this._def.values}};OT.create=(t,e)=>new OT({values:t,typeName:ta.ZodNativeEnum,...aI(e)});var NL=class extends VI{unwrap(){return this._def.type}_parse(e){let{ctx:l}=this._processInputParams(e);if(l.parsedType!==Xn.promise&&l.common.async===!1)return Nn(l,{code:Hl.invalid_type,expected:Xn.promise,received:l.parsedType}),zr;let n=l.parsedType===Xn.promise?l.data:Promise.resolve(l.data);return Th(n.then(r=>this._def.type.parseAsync(r,{path:l.path,errorMap:l.common.contextualErrorMap})))}};NL.create=(t,e)=>new NL({type:t,typeName:ta.ZodPromise,...aI(e)});var p0=class extends VI{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ta.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:l,ctx:n}=this._processInputParams(e),r=this._def.effect||null,a={addIssue:I=>{Nn(n,I),I.fatal?l.abort():l.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),r.type==="preprocess"){let I=r.transform(n.data,a);if(n.common.async)return Promise.resolve(I).then(async s=>{if(l.value==="aborted")return zr;let o=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return o.status==="aborted"?zr:o.status==="dirty"?CT(o.value):l.value==="dirty"?CT(o.value):o});{if(l.value==="aborted")return zr;let s=this._def.schema._parseSync({data:I,path:n.path,parent:n});return s.status==="aborted"?zr:s.status==="dirty"?CT(s.value):l.value==="dirty"?CT(s.value):s}}if(r.type==="refinement"){let I=s=>{let o=r.refinement(s,a);if(n.common.async)return Promise.resolve(o);if(o instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?zr:(s.status==="dirty"&&l.dirty(),I(s.value),{status:l.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?zr:(s.status==="dirty"&&l.dirty(),I(s.value).then(()=>({status:l.value,value:s.value}))))}if(r.type==="transform")if(n.common.async===!1){let I=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!AL(I))return zr;let s=r.transform(I.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:l.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(I=>AL(I)?Promise.resolve(r.transform(I.value,a)).then(s=>({status:l.value,value:s})):zr);ds.assertNever(r)}};p0.create=(t,e,l)=>new p0({schema:t,typeName:ta.ZodEffects,effect:e,...aI(l)});p0.createWithPreprocess=(t,e,l)=>new p0({schema:e,effect:{type:"preprocess",transform:t},typeName:ta.ZodEffects,...aI(l)});var b0=class extends VI{_parse(e){return this._getType(e)===Xn.undefined?Th(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};b0.create=(t,e)=>new b0({innerType:t,typeName:ta.ZodOptional,...aI(e)});var Sw=class extends VI{_parse(e){return this._getType(e)===Xn.null?Th(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Sw.create=(t,e)=>new Sw({innerType:t,typeName:ta.ZodNullable,...aI(e)});var UT=class extends VI{_parse(e){let{ctx:l}=this._processInputParams(e),n=l.data;return l.parsedType===Xn.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:l.path,parent:l})}removeDefault(){return this._def.innerType}};UT.create=(t,e)=>new UT({innerType:t,typeName:ta.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...aI(e)});var MT=class extends VI{_parse(e){let{ctx:l}=this._processInputParams(e),n={...l,common:{...l.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return z8(r)?r.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Bh(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Bh(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};MT.create=(t,e)=>new MT({innerType:t,typeName:ta.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...aI(e)});var eq=class extends VI{_parse(e){if(this._getType(e)!==Xn.nan){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.nan,received:n.parsedType}),zr}return{status:"valid",value:e.data}}};eq.create=t=>new eq({typeName:ta.ZodNaN,...aI(t)});var jRn=Symbol("zod_brand"),Kde=class extends VI{_parse(e){let{ctx:l}=this._processInputParams(e),n=l.data;return this._def.type._parse({data:n,path:l.path,parent:l})}unwrap(){return this._def.type}},qde=class t extends VI{_parse(e){let{status:l,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?zr:a.status==="dirty"?(l.dirty(),CT(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return r.status==="aborted"?zr:r.status==="dirty"?(l.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,l){return new t({in:e,out:l,typeName:ta.ZodPipeline})}},_T=class extends VI{_parse(e){let l=this._def.innerType._parse(e),n=r=>(AL(r)&&(r.value=Object.freeze(r.value)),r);return z8(l)?l.then(r=>n(r)):n(l)}unwrap(){return this._def.innerType}};_T.create=(t,e)=>new _T({innerType:t,typeName:ta.ZodReadonly,...aI(e)});function dUt(t,e){let l=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof l=="string"?{message:l}:l}function pUt(t,e={},l){return t?ZL.create().superRefine((n,r)=>{let a=t(n);if(a instanceof Promise)return a.then(I=>{if(!I){let s=dUt(e,n),o=s.fatal??l??!0;r.addIssue({code:"custom",...s,fatal:o})}});if(!a){let I=dUt(e,n),s=I.fatal??l??!0;r.addIssue({code:"custom",...I,fatal:s})}}):ZL.create()}var KRn={object:nN.lazycreate},ta;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ta||(ta={}));var qRn=(t,e={message:`Input not instance of ${t.name}`})=>pUt(l=>l instanceof t,e),Qt=gL.create,Pm=fT.create,$Rn=eq.create,e2n=vT.create,ro=HT.create,t2n=XT.create,l2n=j8.create,n2n=kT.create,r2n=LT.create,dKe=ZL.create,Bw=uv.create,a2n=nY.create,I2n=K8.create,Od=mv.create,zl=nN.create,s2n=nN.strictCreate,Oh=JT.create,$de=oVe.create,o2n=xT.create,dVe=xw.create,rY=iVe.create,i2n=q8.create,c2n=$8.create,d2n=cVe.create,u2n=ST.create,pr=BT.create,h0=TT.create,m2n=OT.create,b2n=NL.create,G2n=p0.create,p2n=b0.create,h2n=Sw.create,A2n=p0.createWithPreprocess,g2n=qde.create,Z2n=()=>Qt().optional(),N2n=()=>Pm().optional(),W2n=()=>ro().optional(),uVe={string:t=>gL.create({...t,coerce:!0}),number:t=>fT.create({...t,coerce:!0}),boolean:t=>HT.create({...t,coerce:!0}),bigint:t=>vT.create({...t,coerce:!0}),date:t=>XT.create({...t,coerce:!0})};var y2n=zr;var OI=D;var tq="2025-06-18";var hUt=[tq,"2025-03-26","2024-11-05","2024-10-07"],mVe="2.0",AUt=D.union([D.string(),D.number().int()]),gUt=D.string(),E2n=D.object({progressToken:D.optional(AUt)}).passthrough(),Z0=D.object({_meta:D.optional(E2n)}).passthrough(),rN=D.object({method:D.string(),params:D.optional(Z0)}),eue=D.object({_meta:D.optional(D.object({}).passthrough())}).passthrough(),Tw=D.object({method:D.string(),params:D.optional(eue)}),N0=D.object({_meta:D.optional(D.object({}).passthrough())}).passthrough(),bVe=D.union([D.string(),D.number().int()]),ZUt=D.object({jsonrpc:D.literal(mVe),id:bVe}).merge(rN).strict(),GVe=t=>ZUt.safeParse(t).success,NUt=D.object({jsonrpc:D.literal(mVe)}).merge(Tw).strict(),WUt=t=>NUt.safeParse(t).success,yUt=D.object({jsonrpc:D.literal(mVe),id:bVe,result:N0}).strict(),tue=t=>yUt.safeParse(t).success,A0;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(A0||(A0={}));var EUt=D.object({jsonrpc:D.literal(mVe),id:bVe,error:D.object({code:D.number().int(),message:D.string(),data:D.optional(D.unknown())})}).strict(),RUt=t=>EUt.safeParse(t).success,yL=D.union([ZUt,NUt,yUt,EUt]),DT=N0.strict(),pVe=Tw.extend({method:D.literal("notifications/cancelled"),params:eue.extend({requestId:bVe,reason:D.string().optional()})}),hVe=D.object({src:D.string(),mimeType:D.optional(D.string()),sizes:D.optional(D.string())}).passthrough(),lue=D.object({name:D.string(),title:D.optional(D.string())}).passthrough(),YUt=lue.extend({version:D.string(),websiteUrl:D.optional(D.string()),icons:D.optional(D.array(hVe))}),R2n=D.object({experimental:D.optional(D.object({}).passthrough()),sampling:D.optional(D.object({}).passthrough()),elicitation:D.optional(D.object({}).passthrough()),roots:D.optional(D.object({listChanged:D.optional(D.boolean())}).passthrough())}).passthrough(),Y2n=rN.extend({method:D.literal("initialize"),params:Z0.extend({protocolVersion:D.string(),capabilities:R2n,clientInfo:YUt})});var V2n=D.object({experimental:D.optional(D.object({}).passthrough()),logging:D.optional(D.object({}).passthrough()),completions:D.optional(D.object({}).passthrough()),prompts:D.optional(D.object({listChanged:D.optional(D.boolean())}).passthrough()),resources:D.optional(D.object({subscribe:D.optional(D.boolean()),listChanged:D.optional(D.boolean())}).passthrough()),tools:D.optional(D.object({listChanged:D.optional(D.boolean())}).passthrough())}).passthrough(),uKe=N0.extend({protocolVersion:D.string(),capabilities:V2n,serverInfo:YUt,instructions:D.optional(D.string())}),VUt=Tw.extend({method:D.literal("notifications/initialized")}),wUt=t=>VUt.safeParse(t).success,AVe=rN.extend({method:D.literal("ping")}),w2n=D.object({progress:D.number(),total:D.optional(D.number()),message:D.optional(D.string())}).passthrough(),gVe=Tw.extend({method:D.literal("notifications/progress"),params:eue.merge(w2n).extend({progressToken:AUt})}),ZVe=rN.extend({params:Z0.extend({cursor:D.optional(gUt)}).optional()}),NVe=N0.extend({nextCursor:D.optional(gUt)}),QUt=D.object({uri:D.string(),mimeType:D.optional(D.string()),_meta:D.optional(D.object({}).passthrough())}).passthrough(),FUt=QUt.extend({text:D.string()}),mKe=D.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),CUt=QUt.extend({blob:mKe}),fUt=lue.extend({uri:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),icons:D.optional(D.array(hVe)),_meta:D.optional(D.object({}).passthrough())}),Q2n=lue.extend({uriTemplate:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),_meta:D.optional(D.object({}).passthrough())}),F2n=ZVe.extend({method:D.literal("resources/list")}),bKe=NVe.extend({resources:D.array(fUt)}),C2n=ZVe.extend({method:D.literal("resources/templates/list")}),GKe=NVe.extend({resourceTemplates:D.array(Q2n)}),f2n=rN.extend({method:D.literal("resources/read"),params:Z0.extend({uri:D.string()})}),pKe=N0.extend({contents:D.array(D.union([FUt,CUt]))}),v2n=Tw.extend({method:D.literal("notifications/resources/list_changed")}),H2n=rN.extend({method:D.literal("resources/subscribe"),params:Z0.extend({uri:D.string()})}),X2n=rN.extend({method:D.literal("resources/unsubscribe"),params:Z0.extend({uri:D.string()})}),k2n=Tw.extend({method:D.literal("notifications/resources/updated"),params:eue.extend({uri:D.string()})}),L2n=D.object({name:D.string(),description:D.optional(D.string()),required:D.optional(D.boolean())}).passthrough(),J2n=lue.extend({description:D.optional(D.string()),arguments:D.optional(D.array(L2n)),icons:D.optional(D.array(hVe)),_meta:D.optional(D.object({}).passthrough())}),x2n=ZVe.extend({method:D.literal("prompts/list")}),hKe=NVe.extend({prompts:D.array(J2n)}),S2n=rN.extend({method:D.literal("prompts/get"),params:Z0.extend({name:D.string(),arguments:D.optional(D.record(D.string()))})}),AKe=D.object({type:D.literal("text"),text:D.string(),_meta:D.optional(D.object({}).passthrough())}).passthrough(),gKe=D.object({type:D.literal("image"),data:mKe,mimeType:D.string(),_meta:D.optional(D.object({}).passthrough())}).passthrough(),ZKe=D.object({type:D.literal("audio"),data:mKe,mimeType:D.string(),_meta:D.optional(D.object({}).passthrough())}).passthrough(),B2n=D.object({type:D.literal("resource"),resource:D.union([FUt,CUt]),_meta:D.optional(D.object({}).passthrough())}).passthrough(),T2n=fUt.extend({type:D.literal("resource_link")}),vUt=D.union([AKe,gKe,ZKe,T2n,B2n]),O2n=D.object({role:D.enum(["user","assistant"]),content:vUt}).passthrough(),NKe=N0.extend({description:D.optional(D.string()),messages:D.array(O2n)}),U2n=Tw.extend({method:D.literal("notifications/prompts/list_changed")}),M2n=D.object({title:D.optional(D.string()),readOnlyHint:D.optional(D.boolean()),destructiveHint:D.optional(D.boolean()),idempotentHint:D.optional(D.boolean()),openWorldHint:D.optional(D.boolean())}).passthrough(),_2n=lue.extend({description:D.optional(D.string()),inputSchema:D.object({type:D.literal("object"),properties:D.optional(D.object({}).passthrough()),required:D.optional(D.array(D.string()))}).passthrough(),outputSchema:D.optional(D.object({type:D.literal("object"),properties:D.optional(D.object({}).passthrough()),required:D.optional(D.array(D.string()))}).passthrough()),annotations:D.optional(M2n),icons:D.optional(D.array(hVe)),_meta:D.optional(D.object({}).passthrough())}),D2n=ZVe.extend({method:D.literal("tools/list")}),WKe=NVe.extend({tools:D.array(_2n)}),WVe=N0.extend({content:D.array(vUt).default([]),structuredContent:D.object({}).passthrough().optional(),isError:D.optional(D.boolean())}),bja=WVe.or(N0.extend({toolResult:D.unknown()})),z2n=rN.extend({method:D.literal("tools/call"),params:Z0.extend({name:D.string(),arguments:D.optional(D.record(D.unknown()))})}),P2n=Tw.extend({method:D.literal("notifications/tools/list_changed")}),HUt=D.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),j2n=rN.extend({method:D.literal("logging/setLevel"),params:Z0.extend({level:HUt})}),K2n=Tw.extend({method:D.literal("notifications/message"),params:eue.extend({level:HUt,logger:D.optional(D.string()),data:D.unknown()})}),q2n=D.object({name:D.string().optional()}).passthrough(),$2n=D.object({hints:D.optional(D.array(q2n)),costPriority:D.optional(D.number().min(0).max(1)),speedPriority:D.optional(D.number().min(0).max(1)),intelligencePriority:D.optional(D.number().min(0).max(1))}).passthrough(),eYn=D.object({role:D.enum(["user","assistant"]),content:D.union([AKe,gKe,ZKe])}).passthrough(),tYn=rN.extend({method:D.literal("sampling/createMessage"),params:Z0.extend({messages:D.array(eYn),systemPrompt:D.optional(D.string()),includeContext:D.optional(D.enum(["none","thisServer","allServers"])),temperature:D.optional(D.number()),maxTokens:D.number().int(),stopSequences:D.optional(D.array(D.string())),metadata:D.optional(D.object({}).passthrough()),modelPreferences:D.optional($2n)})}),lYn=N0.extend({model:D.string(),stopReason:D.optional(D.enum(["endTurn","stopSequence","maxTokens"]).or(D.string())),role:D.enum(["user","assistant"]),content:D.discriminatedUnion("type",[AKe,gKe,ZKe])}),nYn=D.object({type:D.literal("boolean"),title:D.optional(D.string()),description:D.optional(D.string()),default:D.optional(D.boolean())}).passthrough(),rYn=D.object({type:D.literal("string"),title:D.optional(D.string()),description:D.optional(D.string()),minLength:D.optional(D.number()),maxLength:D.optional(D.number()),format:D.optional(D.enum(["email","uri","date","date-time"]))}).passthrough(),aYn=D.object({type:D.enum(["number","integer"]),title:D.optional(D.string()),description:D.optional(D.string()),minimum:D.optional(D.number()),maximum:D.optional(D.number())}).passthrough(),IYn=D.object({type:D.literal("string"),title:D.optional(D.string()),description:D.optional(D.string()),enum:D.array(D.string()),enumNames:D.optional(D.array(D.string()))}).passthrough(),sYn=D.union([nYn,rYn,aYn,IYn]),oYn=rN.extend({method:D.literal("elicitation/create"),params:Z0.extend({message:D.string(),requestedSchema:D.object({type:D.literal("object"),properties:D.record(D.string(),sYn),required:D.optional(D.array(D.string()))}).passthrough()})}),iYn=N0.extend({action:D.enum(["accept","decline","cancel"]),content:D.optional(D.record(D.string(),D.unknown()))}),cYn=D.object({type:D.literal("ref/resource"),uri:D.string()}).passthrough();var dYn=D.object({type:D.literal("ref/prompt"),name:D.string()}).passthrough(),uYn=rN.extend({method:D.literal("completion/complete"),params:Z0.extend({ref:D.union([dYn,cYn]),argument:D.object({name:D.string(),value:D.string()}).passthrough(),context:D.optional(D.object({arguments:D.optional(D.record(D.string(),D.string()))}))})}),yKe=N0.extend({completion:D.object({values:D.array(D.string()).max(100),total:D.optional(D.number().int()),hasMore:D.optional(D.boolean())}).passthrough()}),mYn=D.object({uri:D.string().startsWith("file://"),name:D.optional(D.string()),_meta:D.optional(D.object({}).passthrough())}).passthrough(),bYn=rN.extend({method:D.literal("roots/list")}),GYn=N0.extend({roots:D.array(mYn)}),pYn=Tw.extend({method:D.literal("notifications/roots/list_changed")}),Gja=D.union([AVe,Y2n,uYn,j2n,S2n,x2n,F2n,C2n,f2n,H2n,X2n,z2n,D2n]),pja=D.union([pVe,gVe,VUt,pYn]),hja=D.union([DT,lYn,iYn,GYn]),Aja=D.union([AVe,tYn,oYn,bYn]),gja=D.union([pVe,gVe,K2n,k2n,v2n,P2n,U2n]),Zja=D.union([DT,uKe,yKe,NKe,hKe,bKe,GKe,pKe,WVe,WKe]),g0=class extends Error{constructor(e,l,n){super(`MCP error ${e}: ${l}`),this.code=e,this.data=n,this.name="McpError"}};var hYn=6e4,yVe=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(pVe,l=>{let n=this._requestHandlerAbortControllers.get(l.params.requestId);n?.abort(l.params.reason)}),this.setNotificationHandler(gVe,l=>{this._onprogress(l)}),this.setRequestHandler(AVe,l=>({}))}_setupTimeout(e,l,n,r,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,l),startTime:Date.now(),timeout:l,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:r})}_resetTimeout(e){let l=this._timeoutInfo.get(e);if(!l)return!1;let n=Date.now()-l.startTime;if(l.maxTotalTimeout&&n>=l.maxTotalTimeout)throw this._timeoutInfo.delete(e),new g0(A0.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:l.maxTotalTimeout,totalElapsed:n});return clearTimeout(l.timeoutId),l.timeoutId=setTimeout(l.onTimeout,l.timeout),!0}_cleanupTimeout(e){let l=this._timeoutInfo.get(e);l&&(clearTimeout(l.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var l,n,r;this._transport=e;let a=(l=this.transport)===null||l===void 0?void 0:l.onclose;this._transport.onclose=()=>{a?.(),this._onclose()};let I=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=o=>{I?.(o),this._onerror(o)};let s=(r=this._transport)===null||r===void 0?void 0:r.onmessage;this._transport.onmessage=(o,c)=>{s?.(o,c),tue(o)||RUt(o)?this._onresponse(o):GVe(o)?this._onrequest(o,c):WUt(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){var e;let l=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=new g0(A0.ConnectionClosed,"Connection closed");for(let r of l.values())r(n)}_onerror(e){var l;(l=this.onerror)===null||l===void 0||l.call(this,e)}_onnotification(e){var l;let n=(l=this._notificationHandlers.get(e.method))!==null&&l!==void 0?l:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,l){var n,r;let a=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,I=this._transport;if(a===void 0){I?.send({jsonrpc:"2.0",id:e.id,error:{code:A0.MethodNotFound,message:"Method not found"}}).catch(c=>this._onerror(new Error(`Failed to send an error response: ${c}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let o={signal:s.signal,sessionId:I?.sessionId,_meta:(r=e.params)===null||r===void 0?void 0:r._meta,sendNotification:c=>this.notification(c,{relatedRequestId:e.id}),sendRequest:(c,d,m)=>this.request(c,d,{...m,relatedRequestId:e.id}),authInfo:l?.authInfo,requestId:e.id,requestInfo:l?.requestInfo};Promise.resolve().then(()=>a(e,o)).then(c=>{if(!s.signal.aborted)return I?.send({result:c,jsonrpc:"2.0",id:e.id})},c=>{var d;if(!s.signal.aborted)return I?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(c.code)?c.code:A0.InternalError,message:(d=c.message)!==null&&d!==void 0?d:"Internal error"}})}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:l,...n}=e.params,r=Number(l),a=this._progressHandlers.get(r);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let I=this._responseHandlers.get(r),s=this._timeoutInfo.get(r);if(s&&I&&s.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(o){I(o);return}a(n)}_onresponse(e){let l=Number(e.id),n=this._responseHandlers.get(l);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(l),this._progressHandlers.delete(l),this._cleanupTimeout(l),tue(e))n(e);else{let r=new g0(e.error.code,e.error.message,e.error.data);n(r)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,l,n){let{relatedRequestId:r,resumptionToken:a,onresumptiontoken:I}=n??{};return new Promise((s,o)=>{var c,d,m,b,p,A;if(!this._transport){o(new Error("Not connected"));return}((c=this._options)===null||c===void 0?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(d=n?.signal)===null||d===void 0||d.throwIfAborted();let Z=this._requestMessageId++,W={...e,jsonrpc:"2.0",id:Z};n?.onprogress&&(this._progressHandlers.set(Z,n.onprogress),W.params={...e.params,_meta:{...((m=e.params)===null||m===void 0?void 0:m._meta)||{},progressToken:Z}});let R=X=>{var S;this._responseHandlers.delete(Z),this._progressHandlers.delete(Z),this._cleanupTimeout(Z),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:Z,reason:String(X)}},{relatedRequestId:r,resumptionToken:a,onresumptiontoken:I}).catch(U=>this._onerror(new Error(`Failed to send cancellation: ${U}`))),o(X)};this._responseHandlers.set(Z,X=>{var S;if(!(!((S=n?.signal)===null||S===void 0)&&S.aborted)){if(X instanceof Error)return o(X);try{let U=l.parse(X.result);s(U)}catch(U){o(U)}}}),(b=n?.signal)===null||b===void 0||b.addEventListener("abort",()=>{var X;R((X=n?.signal)===null||X===void 0?void 0:X.reason)});let V=(p=n?.timeout)!==null&&p!==void 0?p:hYn,f=()=>R(new g0(A0.RequestTimeout,"Request timed out",{timeout:V}));this._setupTimeout(Z,V,n?.maxTotalTimeout,f,(A=n?.resetTimeoutOnProgress)!==null&&A!==void 0?A:!1),this._transport.send(W,{relatedRequestId:r,resumptionToken:a,onresumptiontoken:I}).catch(X=>{this._cleanupTimeout(Z),o(X)})})}async notification(e,l){var n,r;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((r=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&r!==void 0?r:[]).includes(e.method)&&!e.params&&!l?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var o;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let c={...e,jsonrpc:"2.0"};(o=this._transport)===null||o===void 0||o.send(c,l).catch(d=>this._onerror(d))});return}let s={...e,jsonrpc:"2.0"};await this._transport.send(s,l)}setRequestHandler(e,l){let n=e.shape.method.value;this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(r,a)=>Promise.resolve(l(e.parse(r),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,l){this._notificationHandlers.set(e.shape.method.value,n=>Promise.resolve(l(e.parse(n))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function XUt(t,e){return Object.entries(e).reduce((l,[n,r])=>(r&&typeof r=="object"?l[n]=l[n]?{...l[n],...r}:r:l[n]=r,l),{...t})}var GDt=$e(bDt(),1),rwe=class extends yVe{constructor(e,l){var n;super(l),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=l?.capabilities)!==null&&n!==void 0?n:{},this._ajv=new GDt.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=XUt(this._capabilities,e)}assertCapability(e,l){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${l})`)}async connect(e,l){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:tq,capabilities:this._capabilities,clientInfo:this._clientInfo}},uKe,l);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!hUt.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var l,n,r,a,I;switch(e){case"logging/setLevel":if(!(!((l=this._serverCapabilities)===null||l===void 0)&&l.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((I=this._serverCapabilities)===null||I===void 0)&&I.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var l;switch(e){case"notifications/roots/list_changed":if(!(!((l=this._capabilities.roots)===null||l===void 0)&&l.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},DT,e)}async complete(e,l){return this.request({method:"completion/complete",params:e},yKe,l)}async setLoggingLevel(e,l){return this.request({method:"logging/setLevel",params:{level:e}},DT,l)}async getPrompt(e,l){return this.request({method:"prompts/get",params:e},NKe,l)}async listPrompts(e,l){return this.request({method:"prompts/list",params:e},hKe,l)}async listResources(e,l){return this.request({method:"resources/list",params:e},bKe,l)}async listResourceTemplates(e,l){return this.request({method:"resources/templates/list",params:e},GKe,l)}async readResource(e,l){return this.request({method:"resources/read",params:e},pKe,l)}async subscribeResource(e,l){return this.request({method:"resources/subscribe",params:e},DT,l)}async unsubscribeResource(e,l){return this.request({method:"resources/unsubscribe",params:e},DT,l)}async callTool(e,l=WVe,n){let r=await this.request({method:"tools/call",params:e},l,n),a=this.getToolOutputValidator(e.name);if(a){if(!r.structuredContent&&!r.isError)throw new g0(A0.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{if(!a(r.structuredContent))throw new g0(A0.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(a.errors)}`)}catch(I){throw I instanceof g0?I:new g0(A0.InvalidParams,`Failed to validate structured content: ${I instanceof Error?I.message:String(I)}`)}}return r}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let l of e)if(l.outputSchema)try{let n=this._ajv.compile(l.outputSchema);this._cachedToolOutputValidators.set(l.name,n)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,l){let n=await this.request({method:"tools/list",params:e},WKe,l);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var awe=class{createClient(e,l){return new rwe(e,l)}};var Iwe=class extends Error{constructor(e,l){super(e),this.name="ParseError",this.type=l.type,this.field=l.field,this.value=l.value,this.line=l.line}};function sqe(t){}function swe(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=sqe,onError:l=sqe,onRetry:n=sqe,onComment:r}=t,a="",I=!0,s,o="",c="";function d(Z){let W=I?Z.replace(/^\xEF\xBB\xBF/,""):Z,[R,V]=TFn(`${a}${W}`);for(let f of R)m(f);a=V,I=!1}function m(Z){if(Z===""){p();return}if(Z.startsWith(":")){r&&r(Z.slice(Z.startsWith(": ")?2:1));return}let W=Z.indexOf(":");if(W!==-1){let R=Z.slice(0,W),V=Z[W+1]===" "?2:1,f=Z.slice(W+V);b(R,f,Z);return}b(Z,"",Z)}function b(Z,W,R){switch(Z){case"event":c=W;break;case"data":o=`${o}${W}
|
|
2021
|
+
`,input_schema:{type:"object",properties:{question:{type:"string",description:"A question about the codebase. It should reference by name any topics, specific file names, and concepts that are relevant to the question and specify the desired output format."}},required:["question"]},callback:async n=>{let r,a=lZe(t),I="",s="",o=a.split("/");if(o.length===2){[I,s]=o,l.info("Searching for repository insights");try{r=await aKe(n.question,I,s,e,l),l.info(`Blackbird results: ${r}`)}catch(c){l.error(`Error occurred while searching for repository insights: ${c}`)}}return{resultType:"success",textResultForLlm:r??"No results found.",toolTelemetry:{}}}}}async function IUt(t,e,l,n,r,a){let I=await sUt(t),s=await yRn(t,e,l),o=rUt(e)?[new rVe(l,e,n,r,t,t.location,RWe(),a).getSearch()]:[],c=t.splitEditingTools?EBe(t,l,e):[RBe(t,l,e)];return[I.shellTool,...I.otherTools??[],...s,...o,...c,vRt(t,e,l,n),to(e,qte)?await oNt(t,l,n,e):void 0,t?.requireReasoning?VBe(t):void 0,to(e,VRt)?wRt:void 0,await ERn(t,e,l,n)].filter(d=>d!==void 0)}async function aVe(t,e){let l=await sUt(t),n=EBe(t,e);return[l.shellTool,...l.otherTools??[],...n,t?.requireReasoning?VBe(t):void 0,RE].filter(r=>r!==void 0)}async function WRn(t,e,l,n,r,a){return[...await IUt(t,e,l,n,r,a),QRt(t,l)]}var M8=t=>({...lY,supports:{...lY.supports,reasoning:t?.thinkingMode?!0:lY.supports?.reasoning}}),lY={supports:{tool_choice:!1,reasoning:!0,parallel_tool_calls:!1},createPR:{toolInit:IUt,jitInstructions:WMe},prDetails:{},respondToPRComment:{toolInit:WRn,jitInstructions:WMe}},_8=t=>({"sweagent-capi":{"claude-3.5-sonnet":{...lY,supports:{tool_choice:!1,reasoning:!1}},"claude-3.7-sonnet":{...lY,supports:{tool_choice:!1,reasoning:!1,vision:!0}},"claude-sonnet-4":{...lY,supports:{tool_choice:!1,reasoning:!0,parallel_tool_calls:!0,vision:!0},toolConfigOverrides:{splitEditingTools:!0}},"claude-sonnet-4.5":{...lY,supports:{tool_choice:!1,reasoning:!0,parallel_tool_calls:!0,vision:!0},toolConfigOverrides:{splitEditingTools:!0}},oswe:{...lY,supports:{tool_choice:!0,reasoning:!0,vision:!0,steering:!0}},"oswe-agent-a":{...lY,supports:{tool_choice:!0,reasoning:!0,vision:!0,steering:!0}},"gpt-5":{...lY,supports:{tool_choice:!0,reasoning:!0,parallel_tool_calls:!0,vision:!0,steering:!0},toolConfigOverrides:{splitEditingTools:!0}},"gpt-5-codex":{...lY,supports:{tool_choice:!0,reasoning:!0,parallel_tool_calls:!0,vision:!0,steering:!0},toolConfigOverrides:{splitEditingTools:!0}}}});async function sUt(t){let e=new kWe(t);return{shellTool:e.getShellTool(),otherTools:[e.getWriteShellTool(),e.getReadShellTool(),e.getStopShellTool()]}}async function yRn(t,e,l){if($9e(e,"cloud"))return[new Bne(new pye(e,l,void 0)).getStoreMemory()];if($9e(e,"local")){let n=new Bne(new Gye(t.location));return[n.getStoreMemory(),n.getReadMemory()]}return[]}async function ERn(t,e,l,n){if(t.includeCodeQLTool){let r=new hZ(l,n),a=e.swebench_base_commit&&e.swebench_base_commit!=="undefined"?e.swebench_base_commit:await r.getCurrentCommitHash(t.location);return new kx(t,r,a,e,l).getCodeQLCheckerTool()}}async function oUt(t,e){switch(t.kind){case"image_processing":return e.onImageProcessingEvent(t);case"images_removed":return e.onImageRemovalEvent(t);case"message":return e.onMessage(t);case"model_call_failure":return e.onModelCallFailure(t);case"model_call_success":return await e.onModelCallSuccess(t);case"response":return e.onResponse(t);case"tool_execution":return e.onToolExecution(t);case"history_truncated":return e.onTruncationEvent(t);case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":return e.onTurnEvent(t);default:wo(t,`Unknown event kind: ${JSON.stringify(t)}`)}}var D={};fm(D,{BRAND:()=>jRn,DIRTY:()=>CT,EMPTY_PATH:()=>wRn,INVALID:()=>zr,NEVER:()=>y2n,OK:()=>Th,ParseStatus:()=>vp,Schema:()=>VI,ZodAny:()=>ZL,ZodArray:()=>mv,ZodBigInt:()=>vT,ZodBoolean:()=>HT,ZodBranded:()=>Kde,ZodCatch:()=>MT,ZodDate:()=>XT,ZodDefault:()=>UT,ZodDiscriminatedUnion:()=>oVe,ZodEffects:()=>p0,ZodEnum:()=>TT,ZodError:()=>Bh,ZodFirstPartyTypeKind:()=>ta,ZodFunction:()=>cVe,ZodIntersection:()=>xT,ZodIssueCode:()=>Hl,ZodLazy:()=>ST,ZodLiteral:()=>BT,ZodMap:()=>q8,ZodNaN:()=>eq,ZodNativeEnum:()=>OT,ZodNever:()=>nY,ZodNull:()=>LT,ZodNullable:()=>Sw,ZodNumber:()=>fT,ZodObject:()=>nN,ZodOptional:()=>b0,ZodParsedType:()=>Xn,ZodPipeline:()=>qde,ZodPromise:()=>NL,ZodReadonly:()=>_T,ZodRecord:()=>iVe,ZodSchema:()=>VI,ZodSet:()=>$8,ZodString:()=>gL,ZodSymbol:()=>j8,ZodTransformer:()=>p0,ZodTuple:()=>xw,ZodType:()=>VI,ZodUndefined:()=>kT,ZodUnion:()=>JT,ZodUnknown:()=>uv,ZodVoid:()=>K8,addIssueToContext:()=>Nn,any:()=>dKe,array:()=>Od,bigint:()=>e2n,boolean:()=>ro,coerce:()=>uVe,custom:()=>pUt,date:()=>t2n,datetimeRegex:()=>bUt,defaultErrorMap:()=>cv,discriminatedUnion:()=>$de,effect:()=>G2n,enum:()=>h0,function:()=>d2n,getErrorMap:()=>D8,getParsedType:()=>Jw,instanceof:()=>qRn,intersection:()=>o2n,isAborted:()=>IVe,isAsync:()=>z8,isDirty:()=>sVe,isValid:()=>AL,late:()=>KRn,lazy:()=>u2n,literal:()=>pr,makeIssue:()=>jde,map:()=>i2n,nan:()=>$Rn,nativeEnum:()=>m2n,never:()=>a2n,null:()=>r2n,nullable:()=>h2n,number:()=>Pm,object:()=>zl,objectUtil:()=>oKe,oboolean:()=>W2n,onumber:()=>N2n,optional:()=>p2n,ostring:()=>Z2n,pipeline:()=>g2n,preprocess:()=>A2n,promise:()=>b2n,quotelessJson:()=>RRn,record:()=>rY,set:()=>c2n,setErrorMap:()=>VRn,strictObject:()=>s2n,string:()=>Qt,symbol:()=>l2n,transformer:()=>G2n,tuple:()=>dVe,undefined:()=>n2n,union:()=>Oh,unknown:()=>Bw,util:()=>ds,void:()=>I2n});var ds;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function l(r){throw new Error}t.assertNever=l,t.arrayToEnum=r=>{let a={};for(let I of r)a[I]=I;return a},t.getValidEnumValues=r=>{let a=t.objectKeys(r).filter(s=>typeof r[r[s]]!="number"),I={};for(let s of a)I[s]=r[s];return t.objectValues(I)},t.objectValues=r=>t.objectKeys(r).map(function(a){return r[a]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{let a=[];for(let I in r)Object.prototype.hasOwnProperty.call(r,I)&&a.push(I);return a},t.find=(r,a)=>{for(let I of r)if(a(I))return I},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function n(r,a=" | "){return r.map(I=>typeof I=="string"?`'${I}'`:I).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(r,a)=>typeof a=="bigint"?a.toString():a})(ds||(ds={}));var oKe;(function(t){t.mergeShapes=(e,l)=>({...e,...l})})(oKe||(oKe={}));var Xn=ds.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Jw=t=>{switch(typeof t){case"undefined":return Xn.undefined;case"string":return Xn.string;case"number":return Number.isNaN(t)?Xn.nan:Xn.number;case"boolean":return Xn.boolean;case"function":return Xn.function;case"bigint":return Xn.bigint;case"symbol":return Xn.symbol;case"object":return Array.isArray(t)?Xn.array:t===null?Xn.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Xn.promise:typeof Map<"u"&&t instanceof Map?Xn.map:typeof Set<"u"&&t instanceof Set?Xn.set:typeof Date<"u"&&t instanceof Date?Xn.date:Xn.object;default:return Xn.unknown}};var Hl=ds.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),RRn=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Bh=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let l=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,l):this.__proto__=l,this.name="ZodError",this.issues=e}format(e){let l=e||function(a){return a.message},n={_errors:[]},r=a=>{for(let I of a.issues)if(I.code==="invalid_union")I.unionErrors.map(r);else if(I.code==="invalid_return_type")r(I.returnTypeError);else if(I.code==="invalid_arguments")r(I.argumentsError);else if(I.path.length===0)n._errors.push(l(I));else{let s=n,o=0;for(;o<I.path.length;){let c=I.path[o];o===I.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(l(I))):s[c]=s[c]||{_errors:[]},s=s[c],o++}}};return r(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ds.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=l=>l.message){let l={},n=[];for(let r of this.issues)if(r.path.length>0){let a=r.path[0];l[a]=l[a]||[],l[a].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:l}}get formErrors(){return this.flatten()}};Bh.create=t=>new Bh(t);var YRn=(t,e)=>{let l;switch(t.code){case Hl.invalid_type:t.received===Xn.undefined?l="Required":l=`Expected ${t.expected}, received ${t.received}`;break;case Hl.invalid_literal:l=`Invalid literal value, expected ${JSON.stringify(t.expected,ds.jsonStringifyReplacer)}`;break;case Hl.unrecognized_keys:l=`Unrecognized key(s) in object: ${ds.joinValues(t.keys,", ")}`;break;case Hl.invalid_union:l="Invalid input";break;case Hl.invalid_union_discriminator:l=`Invalid discriminator value. Expected ${ds.joinValues(t.options)}`;break;case Hl.invalid_enum_value:l=`Invalid enum value. Expected ${ds.joinValues(t.options)}, received '${t.received}'`;break;case Hl.invalid_arguments:l="Invalid function arguments";break;case Hl.invalid_return_type:l="Invalid function return type";break;case Hl.invalid_date:l="Invalid date";break;case Hl.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(l=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(l=`${l} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?l=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?l=`Invalid input: must end with "${t.validation.endsWith}"`:ds.assertNever(t.validation):t.validation!=="regex"?l=`Invalid ${t.validation}`:l="Invalid";break;case Hl.too_small:t.type==="array"?l=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?l=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?l=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?l=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?l=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:l="Invalid input";break;case Hl.too_big:t.type==="array"?l=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?l=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?l=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?l=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?l=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:l="Invalid input";break;case Hl.custom:l="Invalid input";break;case Hl.invalid_intersection_types:l="Intersection results could not be merged";break;case Hl.not_multiple_of:l=`Number must be a multiple of ${t.multipleOf}`;break;case Hl.not_finite:l="Number must be finite";break;default:l=e.defaultError,ds.assertNever(t)}return{message:l}},cv=YRn;var iUt=cv;function VRn(t){iUt=t}function D8(){return iUt}var jde=t=>{let{data:e,path:l,errorMaps:n,issueData:r}=t,a=[...l,...r.path||[]],I={...r,path:a};if(r.message!==void 0)return{...r,path:a,message:r.message};let s="",o=n.filter(c=>!!c).slice().reverse();for(let c of o)s=c(I,{data:e,defaultError:s}).message;return{...r,path:a,message:s}},wRn=[];function Nn(t,e){let l=D8(),n=jde({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,l,l===cv?void 0:cv].filter(r=>!!r)});t.common.issues.push(n)}var vp=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,l){let n=[];for(let r of l){if(r.status==="aborted")return zr;r.status==="dirty"&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,l){let n=[];for(let r of l){let a=await r.key,I=await r.value;n.push({key:a,value:I})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,l){let n={};for(let r of l){let{key:a,value:I}=r;if(a.status==="aborted"||I.status==="aborted")return zr;a.status==="dirty"&&e.dirty(),I.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof I.value<"u"||r.alwaysSet)&&(n[a.value]=I.value)}return{status:e.value,value:n}}},zr=Object.freeze({status:"aborted"}),CT=t=>({status:"dirty",value:t}),Th=t=>({status:"valid",value:t}),IVe=t=>t.status==="aborted",sVe=t=>t.status==="dirty",AL=t=>t.status==="valid",z8=t=>typeof Promise<"u"&&t instanceof Promise;var dr;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(dr||(dr={}));var G0=class{constructor(e,l,n,r){this._cachedPath=[],this.parent=e,this.data=l,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},cUt=(t,e)=>{if(AL(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let l=new Bh(t.common.issues);return this._error=l,this._error}}};function aI(t){if(!t)return{};let{errorMap:e,invalid_type_error:l,required_error:n,description:r}=t;if(e&&(l||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(I,s)=>{let{message:o}=t;return I.code==="invalid_enum_value"?{message:o??s.defaultError}:typeof s.data>"u"?{message:o??n??s.defaultError}:I.code!=="invalid_type"?{message:s.defaultError}:{message:o??l??s.defaultError}},description:r}}var VI=class{get description(){return this._def.description}_getType(e){return Jw(e.data)}_getOrReturnCtx(e,l){return l||{common:e.parent.common,data:e.data,parsedType:Jw(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new vp,ctx:{common:e.parent.common,data:e.data,parsedType:Jw(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let l=this._parse(e);if(z8(l))throw new Error("Synchronous parse encountered promise.");return l}_parseAsync(e){let l=this._parse(e);return Promise.resolve(l)}parse(e,l){let n=this.safeParse(e,l);if(n.success)return n.data;throw n.error}safeParse(e,l){let n={common:{issues:[],async:l?.async??!1,contextualErrorMap:l?.errorMap},path:l?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jw(e)},r=this._parseSync({data:e,path:n.path,parent:n});return cUt(n,r)}"~validate"(e){let l={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jw(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:l});return AL(n)?{value:n.value}:{issues:l.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),l.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:l}).then(n=>AL(n)?{value:n.value}:{issues:l.common.issues})}async parseAsync(e,l){let n=await this.safeParseAsync(e,l);if(n.success)return n.data;throw n.error}async safeParseAsync(e,l){let n={common:{issues:[],contextualErrorMap:l?.errorMap,async:!0},path:l?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jw(e)},r=this._parse({data:e,path:n.path,parent:n}),a=await(z8(r)?r:Promise.resolve(r));return cUt(n,a)}refine(e,l){let n=r=>typeof l=="string"||typeof l>"u"?{message:l}:typeof l=="function"?l(r):l;return this._refinement((r,a)=>{let I=e(r),s=()=>a.addIssue({code:Hl.custom,...n(r)});return typeof Promise<"u"&&I instanceof Promise?I.then(o=>o?!0:(s(),!1)):I?!0:(s(),!1)})}refinement(e,l){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof l=="function"?l(n,r):l),!1))}_refinement(e){return new p0({schema:this,typeName:ta.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:l=>this["~validate"](l)}}optional(){return b0.create(this,this._def)}nullable(){return Sw.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mv.create(this)}promise(){return NL.create(this,this._def)}or(e){return JT.create([this,e],this._def)}and(e){return xT.create(this,e,this._def)}transform(e){return new p0({...aI(this._def),schema:this,typeName:ta.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let l=typeof e=="function"?e:()=>e;return new UT({...aI(this._def),innerType:this,defaultValue:l,typeName:ta.ZodDefault})}brand(){return new Kde({typeName:ta.ZodBranded,type:this,...aI(this._def)})}catch(e){let l=typeof e=="function"?e:()=>e;return new MT({...aI(this._def),innerType:this,catchValue:l,typeName:ta.ZodCatch})}describe(e){let l=this.constructor;return new l({...this._def,description:e})}pipe(e){return qde.create(this,e)}readonly(){return _T.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},QRn=/^c[^\s-]{8,}$/i,FRn=/^[0-9a-z]+$/,CRn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fRn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,vRn=/^[a-z0-9_-]{21}$/i,HRn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,XRn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,kRn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,LRn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",iKe,JRn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xRn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,SRn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,BRn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,TRn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ORn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,uUt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",URn=new RegExp(`^${uUt}$`);function mUt(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let l=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${l}`}function MRn(t){return new RegExp(`^${mUt(t)}$`)}function bUt(t){let e=`${uUt}T${mUt(t)}`,l=[];return l.push(t.local?"Z?":"Z"),t.offset&&l.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${l.join("|")})`,new RegExp(`^${e}$`)}function _Rn(t,e){return!!((e==="v4"||!e)&&JRn.test(t)||(e==="v6"||!e)&&SRn.test(t))}function DRn(t,e){if(!HRn.test(t))return!1;try{let[l]=t.split(".");if(!l)return!1;let n=l.replace(/-/g,"+").replace(/_/g,"/").padEnd(l.length+(4-l.length%4)%4,"="),r=JSON.parse(atob(n));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function zRn(t,e){return!!((e==="v4"||!e)&&xRn.test(t)||(e==="v6"||!e)&&BRn.test(t))}var gL=class t extends VI{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Xn.string){let a=this._getOrReturnCtx(e);return Nn(a,{code:Hl.invalid_type,expected:Xn.string,received:a.parsedType}),zr}let n=new vp,r;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let I=e.data.length>a.value,s=e.data.length<a.value;(I||s)&&(r=this._getOrReturnCtx(e,r),I?Nn(r,{code:Hl.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&Nn(r,{code:Hl.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")kRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"email",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")iKe||(iKe=new RegExp(LRn,"u")),iKe.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"emoji",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")fRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"uuid",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")vRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"nanoid",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")QRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"cuid",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")FRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"cuid2",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")CRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"ulid",code:Hl.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Nn(r,{validation:"url",code:Hl.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"regex",code:Hl.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?bUt(a).test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?URn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?MRn(a).test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?XRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"duration",code:Hl.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?_Rn(e.data,a.version)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"ip",code:Hl.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?DRn(e.data,a.alg)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"jwt",code:Hl.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?zRn(e.data,a.version)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"cidr",code:Hl.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?TRn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"base64",code:Hl.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?ORn.test(e.data)||(r=this._getOrReturnCtx(e,r),Nn(r,{validation:"base64url",code:Hl.invalid_string,message:a.message}),n.dirty()):ds.assertNever(a);return{status:n.value,value:e.data}}_regex(e,l,n){return this.refinement(r=>e.test(r),{validation:l,code:Hl.invalid_string,...dr.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...dr.errToObj(e)})}url(e){return this._addCheck({kind:"url",...dr.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...dr.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...dr.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...dr.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...dr.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...dr.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...dr.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...dr.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...dr.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...dr.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...dr.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...dr.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...dr.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...dr.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...dr.errToObj(e)})}regex(e,l){return this._addCheck({kind:"regex",regex:e,...dr.errToObj(l)})}includes(e,l){return this._addCheck({kind:"includes",value:e,position:l?.position,...dr.errToObj(l?.message)})}startsWith(e,l){return this._addCheck({kind:"startsWith",value:e,...dr.errToObj(l)})}endsWith(e,l){return this._addCheck({kind:"endsWith",value:e,...dr.errToObj(l)})}min(e,l){return this._addCheck({kind:"min",value:e,...dr.errToObj(l)})}max(e,l){return this._addCheck({kind:"max",value:e,...dr.errToObj(l)})}length(e,l){return this._addCheck({kind:"length",value:e,...dr.errToObj(l)})}nonempty(e){return this.min(1,dr.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let l of this._def.checks)l.kind==="min"&&(e===null||l.value>e)&&(e=l.value);return e}get maxLength(){let e=null;for(let l of this._def.checks)l.kind==="max"&&(e===null||l.value<e)&&(e=l.value);return e}};gL.create=t=>new gL({checks:[],typeName:ta.ZodString,coerce:t?.coerce??!1,...aI(t)});function PRn(t,e){let l=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,r=l>n?l:n,a=Number.parseInt(t.toFixed(r).replace(".","")),I=Number.parseInt(e.toFixed(r).replace(".",""));return a%I/10**r}var fT=class t extends VI{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Xn.number){let a=this._getOrReturnCtx(e);return Nn(a,{code:Hl.invalid_type,expected:Xn.number,received:a.parsedType}),zr}let n,r=new vp;for(let a of this._def.checks)a.kind==="int"?ds.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):a.kind==="multipleOf"?PRn(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.not_finite,message:a.message}),r.dirty()):ds.assertNever(a);return{status:r.value,value:e.data}}gte(e,l){return this.setLimit("min",e,!0,dr.toString(l))}gt(e,l){return this.setLimit("min",e,!1,dr.toString(l))}lte(e,l){return this.setLimit("max",e,!0,dr.toString(l))}lt(e,l){return this.setLimit("max",e,!1,dr.toString(l))}setLimit(e,l,n,r){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:l,inclusive:n,message:dr.toString(r)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:dr.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:dr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:dr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:dr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:dr.toString(e)})}multipleOf(e,l){return this._addCheck({kind:"multipleOf",value:e,message:dr.toString(l)})}finite(e){return this._addCheck({kind:"finite",message:dr.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:dr.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:dr.toString(e)})}get minValue(){let e=null;for(let l of this._def.checks)l.kind==="min"&&(e===null||l.value>e)&&(e=l.value);return e}get maxValue(){let e=null;for(let l of this._def.checks)l.kind==="max"&&(e===null||l.value<e)&&(e=l.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ds.isInteger(e.value))}get isFinite(){let e=null,l=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(l===null||n.value>l)&&(l=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(l)&&Number.isFinite(e)}};fT.create=t=>new fT({checks:[],typeName:ta.ZodNumber,coerce:t?.coerce||!1,...aI(t)});var vT=class t extends VI{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Xn.bigint)return this._getInvalidInput(e);let n,r=new vp;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Nn(n,{code:Hl.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):ds.assertNever(a);return{status:r.value,value:e.data}}_getInvalidInput(e){let l=this._getOrReturnCtx(e);return Nn(l,{code:Hl.invalid_type,expected:Xn.bigint,received:l.parsedType}),zr}gte(e,l){return this.setLimit("min",e,!0,dr.toString(l))}gt(e,l){return this.setLimit("min",e,!1,dr.toString(l))}lte(e,l){return this.setLimit("max",e,!0,dr.toString(l))}lt(e,l){return this.setLimit("max",e,!1,dr.toString(l))}setLimit(e,l,n,r){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:l,inclusive:n,message:dr.toString(r)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:dr.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:dr.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:dr.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:dr.toString(e)})}multipleOf(e,l){return this._addCheck({kind:"multipleOf",value:e,message:dr.toString(l)})}get minValue(){let e=null;for(let l of this._def.checks)l.kind==="min"&&(e===null||l.value>e)&&(e=l.value);return e}get maxValue(){let e=null;for(let l of this._def.checks)l.kind==="max"&&(e===null||l.value<e)&&(e=l.value);return e}};vT.create=t=>new vT({checks:[],typeName:ta.ZodBigInt,coerce:t?.coerce??!1,...aI(t)});var HT=class extends VI{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Xn.boolean){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.boolean,received:n.parsedType}),zr}return Th(e.data)}};HT.create=t=>new HT({typeName:ta.ZodBoolean,coerce:t?.coerce||!1,...aI(t)});var XT=class t extends VI{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Xn.date){let a=this._getOrReturnCtx(e);return Nn(a,{code:Hl.invalid_type,expected:Xn.date,received:a.parsedType}),zr}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return Nn(a,{code:Hl.invalid_date}),zr}let n=new vp,r;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(r=this._getOrReturnCtx(e,r),Nn(r,{code:Hl.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):ds.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,l){return this._addCheck({kind:"min",value:e.getTime(),message:dr.toString(l)})}max(e,l){return this._addCheck({kind:"max",value:e.getTime(),message:dr.toString(l)})}get minDate(){let e=null;for(let l of this._def.checks)l.kind==="min"&&(e===null||l.value>e)&&(e=l.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let l of this._def.checks)l.kind==="max"&&(e===null||l.value<e)&&(e=l.value);return e!=null?new Date(e):null}};XT.create=t=>new XT({checks:[],coerce:t?.coerce||!1,typeName:ta.ZodDate,...aI(t)});var j8=class extends VI{_parse(e){if(this._getType(e)!==Xn.symbol){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.symbol,received:n.parsedType}),zr}return Th(e.data)}};j8.create=t=>new j8({typeName:ta.ZodSymbol,...aI(t)});var kT=class extends VI{_parse(e){if(this._getType(e)!==Xn.undefined){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.undefined,received:n.parsedType}),zr}return Th(e.data)}};kT.create=t=>new kT({typeName:ta.ZodUndefined,...aI(t)});var LT=class extends VI{_parse(e){if(this._getType(e)!==Xn.null){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.null,received:n.parsedType}),zr}return Th(e.data)}};LT.create=t=>new LT({typeName:ta.ZodNull,...aI(t)});var ZL=class extends VI{constructor(){super(...arguments),this._any=!0}_parse(e){return Th(e.data)}};ZL.create=t=>new ZL({typeName:ta.ZodAny,...aI(t)});var uv=class extends VI{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Th(e.data)}};uv.create=t=>new uv({typeName:ta.ZodUnknown,...aI(t)});var nY=class extends VI{_parse(e){let l=this._getOrReturnCtx(e);return Nn(l,{code:Hl.invalid_type,expected:Xn.never,received:l.parsedType}),zr}};nY.create=t=>new nY({typeName:ta.ZodNever,...aI(t)});var K8=class extends VI{_parse(e){if(this._getType(e)!==Xn.undefined){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.void,received:n.parsedType}),zr}return Th(e.data)}};K8.create=t=>new K8({typeName:ta.ZodVoid,...aI(t)});var mv=class t extends VI{_parse(e){let{ctx:l,status:n}=this._processInputParams(e),r=this._def;if(l.parsedType!==Xn.array)return Nn(l,{code:Hl.invalid_type,expected:Xn.array,received:l.parsedType}),zr;if(r.exactLength!==null){let I=l.data.length>r.exactLength.value,s=l.data.length<r.exactLength.value;(I||s)&&(Nn(l,{code:I?Hl.too_big:Hl.too_small,minimum:s?r.exactLength.value:void 0,maximum:I?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&l.data.length<r.minLength.value&&(Nn(l,{code:Hl.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&l.data.length>r.maxLength.value&&(Nn(l,{code:Hl.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),l.common.async)return Promise.all([...l.data].map((I,s)=>r.type._parseAsync(new G0(l,I,l.path,s)))).then(I=>vp.mergeArray(n,I));let a=[...l.data].map((I,s)=>r.type._parseSync(new G0(l,I,l.path,s)));return vp.mergeArray(n,a)}get element(){return this._def.type}min(e,l){return new t({...this._def,minLength:{value:e,message:dr.toString(l)}})}max(e,l){return new t({...this._def,maxLength:{value:e,message:dr.toString(l)}})}length(e,l){return new t({...this._def,exactLength:{value:e,message:dr.toString(l)}})}nonempty(e){return this.min(1,e)}};mv.create=(t,e)=>new mv({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ta.ZodArray,...aI(e)});function P8(t){if(t instanceof nN){let e={};for(let l in t.shape){let n=t.shape[l];e[l]=b0.create(P8(n))}return new nN({...t._def,shape:()=>e})}else return t instanceof mv?new mv({...t._def,type:P8(t.element)}):t instanceof b0?b0.create(P8(t.unwrap())):t instanceof Sw?Sw.create(P8(t.unwrap())):t instanceof xw?xw.create(t.items.map(e=>P8(e))):t}var nN=class t extends VI{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),l=ds.objectKeys(e);return this._cached={shape:e,keys:l},this._cached}_parse(e){if(this._getType(e)!==Xn.object){let c=this._getOrReturnCtx(e);return Nn(c,{code:Hl.invalid_type,expected:Xn.object,received:c.parsedType}),zr}let{status:n,ctx:r}=this._processInputParams(e),{shape:a,keys:I}=this._getCached(),s=[];if(!(this._def.catchall instanceof nY&&this._def.unknownKeys==="strip"))for(let c in r.data)I.includes(c)||s.push(c);let o=[];for(let c of I){let d=a[c],m=r.data[c];o.push({key:{status:"valid",value:c},value:d._parse(new G0(r,m,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof nY){let c=this._def.unknownKeys;if(c==="passthrough")for(let d of s)o.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(c==="strict")s.length>0&&(Nn(r,{code:Hl.unrecognized_keys,keys:s}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let d of s){let m=r.data[d];o.push({key:{status:"valid",value:d},value:c._parse(new G0(r,m,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let c=[];for(let d of o){let m=await d.key,b=await d.value;c.push({key:m,value:b,alwaysSet:d.alwaysSet})}return c}).then(c=>vp.mergeObjectSync(n,c)):vp.mergeObjectSync(n,o)}get shape(){return this._def.shape()}strict(e){return dr.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(l,n)=>{let r=this._def.errorMap?.(l,n).message??n.defaultError;return l.code==="unrecognized_keys"?{message:dr.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ta.ZodObject})}setKey(e,l){return this.augment({[e]:l})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let l={};for(let n of ds.objectKeys(e))e[n]&&this.shape[n]&&(l[n]=this.shape[n]);return new t({...this._def,shape:()=>l})}omit(e){let l={};for(let n of ds.objectKeys(this.shape))e[n]||(l[n]=this.shape[n]);return new t({...this._def,shape:()=>l})}deepPartial(){return P8(this)}partial(e){let l={};for(let n of ds.objectKeys(this.shape)){let r=this.shape[n];e&&!e[n]?l[n]=r:l[n]=r.optional()}return new t({...this._def,shape:()=>l})}required(e){let l={};for(let n of ds.objectKeys(this.shape))if(e&&!e[n])l[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof b0;)a=a._def.innerType;l[n]=a}return new t({...this._def,shape:()=>l})}keyof(){return GUt(ds.objectKeys(this.shape))}};nN.create=(t,e)=>new nN({shape:()=>t,unknownKeys:"strip",catchall:nY.create(),typeName:ta.ZodObject,...aI(e)});nN.strictCreate=(t,e)=>new nN({shape:()=>t,unknownKeys:"strict",catchall:nY.create(),typeName:ta.ZodObject,...aI(e)});nN.lazycreate=(t,e)=>new nN({shape:t,unknownKeys:"strip",catchall:nY.create(),typeName:ta.ZodObject,...aI(e)});var JT=class extends VI{_parse(e){let{ctx:l}=this._processInputParams(e),n=this._def.options;function r(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return l.common.issues.push(...s.ctx.common.issues),s.result;let I=a.map(s=>new Bh(s.ctx.common.issues));return Nn(l,{code:Hl.invalid_union,unionErrors:I}),zr}if(l.common.async)return Promise.all(n.map(async a=>{let I={...l,common:{...l.common,issues:[]},parent:null};return{result:await a._parseAsync({data:l.data,path:l.path,parent:I}),ctx:I}})).then(r);{let a,I=[];for(let o of n){let c={...l,common:{...l.common,issues:[]},parent:null},d=o._parseSync({data:l.data,path:l.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!a&&(a={result:d,ctx:c}),c.common.issues.length&&I.push(c.common.issues)}if(a)return l.common.issues.push(...a.ctx.common.issues),a.result;let s=I.map(o=>new Bh(o));return Nn(l,{code:Hl.invalid_union,unionErrors:s}),zr}}get options(){return this._def.options}};JT.create=(t,e)=>new JT({options:t,typeName:ta.ZodUnion,...aI(e)});var dv=t=>t instanceof ST?dv(t.schema):t instanceof p0?dv(t.innerType()):t instanceof BT?[t.value]:t instanceof TT?t.options:t instanceof OT?ds.objectValues(t.enum):t instanceof UT?dv(t._def.innerType):t instanceof kT?[void 0]:t instanceof LT?[null]:t instanceof b0?[void 0,...dv(t.unwrap())]:t instanceof Sw?[null,...dv(t.unwrap())]:t instanceof Kde||t instanceof _T?dv(t.unwrap()):t instanceof MT?dv(t._def.innerType):[],oVe=class t extends VI{_parse(e){let{ctx:l}=this._processInputParams(e);if(l.parsedType!==Xn.object)return Nn(l,{code:Hl.invalid_type,expected:Xn.object,received:l.parsedType}),zr;let n=this.discriminator,r=l.data[n],a=this.optionsMap.get(r);return a?l.common.async?a._parseAsync({data:l.data,path:l.path,parent:l}):a._parseSync({data:l.data,path:l.path,parent:l}):(Nn(l,{code:Hl.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),zr)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,l,n){let r=new Map;for(let a of l){let I=dv(a.shape[e]);if(!I.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of I){if(r.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);r.set(s,a)}}return new t({typeName:ta.ZodDiscriminatedUnion,discriminator:e,options:l,optionsMap:r,...aI(n)})}};function cKe(t,e){let l=Jw(t),n=Jw(e);if(t===e)return{valid:!0,data:t};if(l===Xn.object&&n===Xn.object){let r=ds.objectKeys(e),a=ds.objectKeys(t).filter(s=>r.indexOf(s)!==-1),I={...t,...e};for(let s of a){let o=cKe(t[s],e[s]);if(!o.valid)return{valid:!1};I[s]=o.data}return{valid:!0,data:I}}else if(l===Xn.array&&n===Xn.array){if(t.length!==e.length)return{valid:!1};let r=[];for(let a=0;a<t.length;a++){let I=t[a],s=e[a],o=cKe(I,s);if(!o.valid)return{valid:!1};r.push(o.data)}return{valid:!0,data:r}}else return l===Xn.date&&n===Xn.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var xT=class extends VI{_parse(e){let{status:l,ctx:n}=this._processInputParams(e),r=(a,I)=>{if(IVe(a)||IVe(I))return zr;let s=cKe(a.value,I.value);return s.valid?((sVe(a)||sVe(I))&&l.dirty(),{status:l.value,value:s.data}):(Nn(n,{code:Hl.invalid_intersection_types}),zr)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,I])=>r(a,I)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};xT.create=(t,e,l)=>new xT({left:t,right:e,typeName:ta.ZodIntersection,...aI(l)});var xw=class t extends VI{_parse(e){let{status:l,ctx:n}=this._processInputParams(e);if(n.parsedType!==Xn.array)return Nn(n,{code:Hl.invalid_type,expected:Xn.array,received:n.parsedType}),zr;if(n.data.length<this._def.items.length)return Nn(n,{code:Hl.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),zr;!this._def.rest&&n.data.length>this._def.items.length&&(Nn(n,{code:Hl.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),l.dirty());let a=[...n.data].map((I,s)=>{let o=this._def.items[s]||this._def.rest;return o?o._parse(new G0(n,I,n.path,s)):null}).filter(I=>!!I);return n.common.async?Promise.all(a).then(I=>vp.mergeArray(l,I)):vp.mergeArray(l,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};xw.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xw({items:t,typeName:ta.ZodTuple,rest:null,...aI(e)})};var iVe=class t extends VI{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:l,ctx:n}=this._processInputParams(e);if(n.parsedType!==Xn.object)return Nn(n,{code:Hl.invalid_type,expected:Xn.object,received:n.parsedType}),zr;let r=[],a=this._def.keyType,I=this._def.valueType;for(let s in n.data)r.push({key:a._parse(new G0(n,s,n.path,s)),value:I._parse(new G0(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?vp.mergeObjectAsync(l,r):vp.mergeObjectSync(l,r)}get element(){return this._def.valueType}static create(e,l,n){return l instanceof VI?new t({keyType:e,valueType:l,typeName:ta.ZodRecord,...aI(n)}):new t({keyType:gL.create(),valueType:e,typeName:ta.ZodRecord,...aI(l)})}},q8=class extends VI{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:l,ctx:n}=this._processInputParams(e);if(n.parsedType!==Xn.map)return Nn(n,{code:Hl.invalid_type,expected:Xn.map,received:n.parsedType}),zr;let r=this._def.keyType,a=this._def.valueType,I=[...n.data.entries()].map(([s,o],c)=>({key:r._parse(new G0(n,s,n.path,[c,"key"])),value:a._parse(new G0(n,o,n.path,[c,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let o of I){let c=await o.key,d=await o.value;if(c.status==="aborted"||d.status==="aborted")return zr;(c.status==="dirty"||d.status==="dirty")&&l.dirty(),s.set(c.value,d.value)}return{status:l.value,value:s}})}else{let s=new Map;for(let o of I){let c=o.key,d=o.value;if(c.status==="aborted"||d.status==="aborted")return zr;(c.status==="dirty"||d.status==="dirty")&&l.dirty(),s.set(c.value,d.value)}return{status:l.value,value:s}}}};q8.create=(t,e,l)=>new q8({valueType:e,keyType:t,typeName:ta.ZodMap,...aI(l)});var $8=class t extends VI{_parse(e){let{status:l,ctx:n}=this._processInputParams(e);if(n.parsedType!==Xn.set)return Nn(n,{code:Hl.invalid_type,expected:Xn.set,received:n.parsedType}),zr;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(Nn(n,{code:Hl.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),l.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(Nn(n,{code:Hl.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),l.dirty());let a=this._def.valueType;function I(o){let c=new Set;for(let d of o){if(d.status==="aborted")return zr;d.status==="dirty"&&l.dirty(),c.add(d.value)}return{status:l.value,value:c}}let s=[...n.data.values()].map((o,c)=>a._parse(new G0(n,o,n.path,c)));return n.common.async?Promise.all(s).then(o=>I(o)):I(s)}min(e,l){return new t({...this._def,minSize:{value:e,message:dr.toString(l)}})}max(e,l){return new t({...this._def,maxSize:{value:e,message:dr.toString(l)}})}size(e,l){return this.min(e,l).max(e,l)}nonempty(e){return this.min(1,e)}};$8.create=(t,e)=>new $8({valueType:t,minSize:null,maxSize:null,typeName:ta.ZodSet,...aI(e)});var cVe=class t extends VI{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:l}=this._processInputParams(e);if(l.parsedType!==Xn.function)return Nn(l,{code:Hl.invalid_type,expected:Xn.function,received:l.parsedType}),zr;function n(s,o){return jde({data:s,path:l.path,errorMaps:[l.common.contextualErrorMap,l.schemaErrorMap,D8(),cv].filter(c=>!!c),issueData:{code:Hl.invalid_arguments,argumentsError:o}})}function r(s,o){return jde({data:s,path:l.path,errorMaps:[l.common.contextualErrorMap,l.schemaErrorMap,D8(),cv].filter(c=>!!c),issueData:{code:Hl.invalid_return_type,returnTypeError:o}})}let a={errorMap:l.common.contextualErrorMap},I=l.data;if(this._def.returns instanceof NL){let s=this;return Th(async function(...o){let c=new Bh([]),d=await s._def.args.parseAsync(o,a).catch(p=>{throw c.addIssue(n(o,p)),c}),m=await Reflect.apply(I,this,d);return await s._def.returns._def.type.parseAsync(m,a).catch(p=>{throw c.addIssue(r(m,p)),c})})}else{let s=this;return Th(function(...o){let c=s._def.args.safeParse(o,a);if(!c.success)throw new Bh([n(o,c.error)]);let d=Reflect.apply(I,this,c.data),m=s._def.returns.safeParse(d,a);if(!m.success)throw new Bh([r(d,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:xw.create(e).rest(uv.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,l,n){return new t({args:e||xw.create([]).rest(uv.create()),returns:l||uv.create(),typeName:ta.ZodFunction,...aI(n)})}},ST=class extends VI{get schema(){return this._def.getter()}_parse(e){let{ctx:l}=this._processInputParams(e);return this._def.getter()._parse({data:l.data,path:l.path,parent:l})}};ST.create=(t,e)=>new ST({getter:t,typeName:ta.ZodLazy,...aI(e)});var BT=class extends VI{_parse(e){if(e.data!==this._def.value){let l=this._getOrReturnCtx(e);return Nn(l,{received:l.data,code:Hl.invalid_literal,expected:this._def.value}),zr}return{status:"valid",value:e.data}}get value(){return this._def.value}};BT.create=(t,e)=>new BT({value:t,typeName:ta.ZodLiteral,...aI(e)});function GUt(t,e){return new TT({values:t,typeName:ta.ZodEnum,...aI(e)})}var TT=class t extends VI{_parse(e){if(typeof e.data!="string"){let l=this._getOrReturnCtx(e),n=this._def.values;return Nn(l,{expected:ds.joinValues(n),received:l.parsedType,code:Hl.invalid_type}),zr}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let l=this._getOrReturnCtx(e),n=this._def.values;return Nn(l,{received:l.data,code:Hl.invalid_enum_value,options:n}),zr}return Th(e.data)}get options(){return this._def.values}get enum(){let e={};for(let l of this._def.values)e[l]=l;return e}get Values(){let e={};for(let l of this._def.values)e[l]=l;return e}get Enum(){let e={};for(let l of this._def.values)e[l]=l;return e}extract(e,l=this._def){return t.create(e,{...this._def,...l})}exclude(e,l=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...l})}};TT.create=GUt;var OT=class extends VI{_parse(e){let l=ds.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Xn.string&&n.parsedType!==Xn.number){let r=ds.objectValues(l);return Nn(n,{expected:ds.joinValues(r),received:n.parsedType,code:Hl.invalid_type}),zr}if(this._cache||(this._cache=new Set(ds.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let r=ds.objectValues(l);return Nn(n,{received:n.data,code:Hl.invalid_enum_value,options:r}),zr}return Th(e.data)}get enum(){return this._def.values}};OT.create=(t,e)=>new OT({values:t,typeName:ta.ZodNativeEnum,...aI(e)});var NL=class extends VI{unwrap(){return this._def.type}_parse(e){let{ctx:l}=this._processInputParams(e);if(l.parsedType!==Xn.promise&&l.common.async===!1)return Nn(l,{code:Hl.invalid_type,expected:Xn.promise,received:l.parsedType}),zr;let n=l.parsedType===Xn.promise?l.data:Promise.resolve(l.data);return Th(n.then(r=>this._def.type.parseAsync(r,{path:l.path,errorMap:l.common.contextualErrorMap})))}};NL.create=(t,e)=>new NL({type:t,typeName:ta.ZodPromise,...aI(e)});var p0=class extends VI{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ta.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:l,ctx:n}=this._processInputParams(e),r=this._def.effect||null,a={addIssue:I=>{Nn(n,I),I.fatal?l.abort():l.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),r.type==="preprocess"){let I=r.transform(n.data,a);if(n.common.async)return Promise.resolve(I).then(async s=>{if(l.value==="aborted")return zr;let o=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return o.status==="aborted"?zr:o.status==="dirty"?CT(o.value):l.value==="dirty"?CT(o.value):o});{if(l.value==="aborted")return zr;let s=this._def.schema._parseSync({data:I,path:n.path,parent:n});return s.status==="aborted"?zr:s.status==="dirty"?CT(s.value):l.value==="dirty"?CT(s.value):s}}if(r.type==="refinement"){let I=s=>{let o=r.refinement(s,a);if(n.common.async)return Promise.resolve(o);if(o instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?zr:(s.status==="dirty"&&l.dirty(),I(s.value),{status:l.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?zr:(s.status==="dirty"&&l.dirty(),I(s.value).then(()=>({status:l.value,value:s.value}))))}if(r.type==="transform")if(n.common.async===!1){let I=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!AL(I))return zr;let s=r.transform(I.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:l.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(I=>AL(I)?Promise.resolve(r.transform(I.value,a)).then(s=>({status:l.value,value:s})):zr);ds.assertNever(r)}};p0.create=(t,e,l)=>new p0({schema:t,typeName:ta.ZodEffects,effect:e,...aI(l)});p0.createWithPreprocess=(t,e,l)=>new p0({schema:e,effect:{type:"preprocess",transform:t},typeName:ta.ZodEffects,...aI(l)});var b0=class extends VI{_parse(e){return this._getType(e)===Xn.undefined?Th(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};b0.create=(t,e)=>new b0({innerType:t,typeName:ta.ZodOptional,...aI(e)});var Sw=class extends VI{_parse(e){return this._getType(e)===Xn.null?Th(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Sw.create=(t,e)=>new Sw({innerType:t,typeName:ta.ZodNullable,...aI(e)});var UT=class extends VI{_parse(e){let{ctx:l}=this._processInputParams(e),n=l.data;return l.parsedType===Xn.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:l.path,parent:l})}removeDefault(){return this._def.innerType}};UT.create=(t,e)=>new UT({innerType:t,typeName:ta.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...aI(e)});var MT=class extends VI{_parse(e){let{ctx:l}=this._processInputParams(e),n={...l,common:{...l.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return z8(r)?r.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Bh(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Bh(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};MT.create=(t,e)=>new MT({innerType:t,typeName:ta.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...aI(e)});var eq=class extends VI{_parse(e){if(this._getType(e)!==Xn.nan){let n=this._getOrReturnCtx(e);return Nn(n,{code:Hl.invalid_type,expected:Xn.nan,received:n.parsedType}),zr}return{status:"valid",value:e.data}}};eq.create=t=>new eq({typeName:ta.ZodNaN,...aI(t)});var jRn=Symbol("zod_brand"),Kde=class extends VI{_parse(e){let{ctx:l}=this._processInputParams(e),n=l.data;return this._def.type._parse({data:n,path:l.path,parent:l})}unwrap(){return this._def.type}},qde=class t extends VI{_parse(e){let{status:l,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?zr:a.status==="dirty"?(l.dirty(),CT(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return r.status==="aborted"?zr:r.status==="dirty"?(l.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,l){return new t({in:e,out:l,typeName:ta.ZodPipeline})}},_T=class extends VI{_parse(e){let l=this._def.innerType._parse(e),n=r=>(AL(r)&&(r.value=Object.freeze(r.value)),r);return z8(l)?l.then(r=>n(r)):n(l)}unwrap(){return this._def.innerType}};_T.create=(t,e)=>new _T({innerType:t,typeName:ta.ZodReadonly,...aI(e)});function dUt(t,e){let l=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof l=="string"?{message:l}:l}function pUt(t,e={},l){return t?ZL.create().superRefine((n,r)=>{let a=t(n);if(a instanceof Promise)return a.then(I=>{if(!I){let s=dUt(e,n),o=s.fatal??l??!0;r.addIssue({code:"custom",...s,fatal:o})}});if(!a){let I=dUt(e,n),s=I.fatal??l??!0;r.addIssue({code:"custom",...I,fatal:s})}}):ZL.create()}var KRn={object:nN.lazycreate},ta;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ta||(ta={}));var qRn=(t,e={message:`Input not instance of ${t.name}`})=>pUt(l=>l instanceof t,e),Qt=gL.create,Pm=fT.create,$Rn=eq.create,e2n=vT.create,ro=HT.create,t2n=XT.create,l2n=j8.create,n2n=kT.create,r2n=LT.create,dKe=ZL.create,Bw=uv.create,a2n=nY.create,I2n=K8.create,Od=mv.create,zl=nN.create,s2n=nN.strictCreate,Oh=JT.create,$de=oVe.create,o2n=xT.create,dVe=xw.create,rY=iVe.create,i2n=q8.create,c2n=$8.create,d2n=cVe.create,u2n=ST.create,pr=BT.create,h0=TT.create,m2n=OT.create,b2n=NL.create,G2n=p0.create,p2n=b0.create,h2n=Sw.create,A2n=p0.createWithPreprocess,g2n=qde.create,Z2n=()=>Qt().optional(),N2n=()=>Pm().optional(),W2n=()=>ro().optional(),uVe={string:t=>gL.create({...t,coerce:!0}),number:t=>fT.create({...t,coerce:!0}),boolean:t=>HT.create({...t,coerce:!0}),bigint:t=>vT.create({...t,coerce:!0}),date:t=>XT.create({...t,coerce:!0})};var y2n=zr;var OI=D;import{Writable as UCn}from"stream";var tq="2025-06-18";var hUt=[tq,"2025-03-26","2024-11-05","2024-10-07"],mVe="2.0",AUt=D.union([D.string(),D.number().int()]),gUt=D.string(),E2n=D.object({progressToken:D.optional(AUt)}).passthrough(),Z0=D.object({_meta:D.optional(E2n)}).passthrough(),rN=D.object({method:D.string(),params:D.optional(Z0)}),eue=D.object({_meta:D.optional(D.object({}).passthrough())}).passthrough(),Tw=D.object({method:D.string(),params:D.optional(eue)}),N0=D.object({_meta:D.optional(D.object({}).passthrough())}).passthrough(),bVe=D.union([D.string(),D.number().int()]),ZUt=D.object({jsonrpc:D.literal(mVe),id:bVe}).merge(rN).strict(),GVe=t=>ZUt.safeParse(t).success,NUt=D.object({jsonrpc:D.literal(mVe)}).merge(Tw).strict(),WUt=t=>NUt.safeParse(t).success,yUt=D.object({jsonrpc:D.literal(mVe),id:bVe,result:N0}).strict(),tue=t=>yUt.safeParse(t).success,A0;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(A0||(A0={}));var EUt=D.object({jsonrpc:D.literal(mVe),id:bVe,error:D.object({code:D.number().int(),message:D.string(),data:D.optional(D.unknown())})}).strict(),RUt=t=>EUt.safeParse(t).success,yL=D.union([ZUt,NUt,yUt,EUt]),DT=N0.strict(),pVe=Tw.extend({method:D.literal("notifications/cancelled"),params:eue.extend({requestId:bVe,reason:D.string().optional()})}),hVe=D.object({src:D.string(),mimeType:D.optional(D.string()),sizes:D.optional(D.string())}).passthrough(),lue=D.object({name:D.string(),title:D.optional(D.string())}).passthrough(),YUt=lue.extend({version:D.string(),websiteUrl:D.optional(D.string()),icons:D.optional(D.array(hVe))}),R2n=D.object({experimental:D.optional(D.object({}).passthrough()),sampling:D.optional(D.object({}).passthrough()),elicitation:D.optional(D.object({}).passthrough()),roots:D.optional(D.object({listChanged:D.optional(D.boolean())}).passthrough())}).passthrough(),Y2n=rN.extend({method:D.literal("initialize"),params:Z0.extend({protocolVersion:D.string(),capabilities:R2n,clientInfo:YUt})});var V2n=D.object({experimental:D.optional(D.object({}).passthrough()),logging:D.optional(D.object({}).passthrough()),completions:D.optional(D.object({}).passthrough()),prompts:D.optional(D.object({listChanged:D.optional(D.boolean())}).passthrough()),resources:D.optional(D.object({subscribe:D.optional(D.boolean()),listChanged:D.optional(D.boolean())}).passthrough()),tools:D.optional(D.object({listChanged:D.optional(D.boolean())}).passthrough())}).passthrough(),uKe=N0.extend({protocolVersion:D.string(),capabilities:V2n,serverInfo:YUt,instructions:D.optional(D.string())}),VUt=Tw.extend({method:D.literal("notifications/initialized")}),wUt=t=>VUt.safeParse(t).success,AVe=rN.extend({method:D.literal("ping")}),w2n=D.object({progress:D.number(),total:D.optional(D.number()),message:D.optional(D.string())}).passthrough(),gVe=Tw.extend({method:D.literal("notifications/progress"),params:eue.merge(w2n).extend({progressToken:AUt})}),ZVe=rN.extend({params:Z0.extend({cursor:D.optional(gUt)}).optional()}),NVe=N0.extend({nextCursor:D.optional(gUt)}),QUt=D.object({uri:D.string(),mimeType:D.optional(D.string()),_meta:D.optional(D.object({}).passthrough())}).passthrough(),FUt=QUt.extend({text:D.string()}),mKe=D.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),CUt=QUt.extend({blob:mKe}),fUt=lue.extend({uri:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),icons:D.optional(D.array(hVe)),_meta:D.optional(D.object({}).passthrough())}),Q2n=lue.extend({uriTemplate:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),_meta:D.optional(D.object({}).passthrough())}),F2n=ZVe.extend({method:D.literal("resources/list")}),bKe=NVe.extend({resources:D.array(fUt)}),C2n=ZVe.extend({method:D.literal("resources/templates/list")}),GKe=NVe.extend({resourceTemplates:D.array(Q2n)}),f2n=rN.extend({method:D.literal("resources/read"),params:Z0.extend({uri:D.string()})}),pKe=N0.extend({contents:D.array(D.union([FUt,CUt]))}),v2n=Tw.extend({method:D.literal("notifications/resources/list_changed")}),H2n=rN.extend({method:D.literal("resources/subscribe"),params:Z0.extend({uri:D.string()})}),X2n=rN.extend({method:D.literal("resources/unsubscribe"),params:Z0.extend({uri:D.string()})}),k2n=Tw.extend({method:D.literal("notifications/resources/updated"),params:eue.extend({uri:D.string()})}),L2n=D.object({name:D.string(),description:D.optional(D.string()),required:D.optional(D.boolean())}).passthrough(),J2n=lue.extend({description:D.optional(D.string()),arguments:D.optional(D.array(L2n)),icons:D.optional(D.array(hVe)),_meta:D.optional(D.object({}).passthrough())}),x2n=ZVe.extend({method:D.literal("prompts/list")}),hKe=NVe.extend({prompts:D.array(J2n)}),S2n=rN.extend({method:D.literal("prompts/get"),params:Z0.extend({name:D.string(),arguments:D.optional(D.record(D.string()))})}),AKe=D.object({type:D.literal("text"),text:D.string(),_meta:D.optional(D.object({}).passthrough())}).passthrough(),gKe=D.object({type:D.literal("image"),data:mKe,mimeType:D.string(),_meta:D.optional(D.object({}).passthrough())}).passthrough(),ZKe=D.object({type:D.literal("audio"),data:mKe,mimeType:D.string(),_meta:D.optional(D.object({}).passthrough())}).passthrough(),B2n=D.object({type:D.literal("resource"),resource:D.union([FUt,CUt]),_meta:D.optional(D.object({}).passthrough())}).passthrough(),T2n=fUt.extend({type:D.literal("resource_link")}),vUt=D.union([AKe,gKe,ZKe,T2n,B2n]),O2n=D.object({role:D.enum(["user","assistant"]),content:vUt}).passthrough(),NKe=N0.extend({description:D.optional(D.string()),messages:D.array(O2n)}),U2n=Tw.extend({method:D.literal("notifications/prompts/list_changed")}),M2n=D.object({title:D.optional(D.string()),readOnlyHint:D.optional(D.boolean()),destructiveHint:D.optional(D.boolean()),idempotentHint:D.optional(D.boolean()),openWorldHint:D.optional(D.boolean())}).passthrough(),_2n=lue.extend({description:D.optional(D.string()),inputSchema:D.object({type:D.literal("object"),properties:D.optional(D.object({}).passthrough()),required:D.optional(D.array(D.string()))}).passthrough(),outputSchema:D.optional(D.object({type:D.literal("object"),properties:D.optional(D.object({}).passthrough()),required:D.optional(D.array(D.string()))}).passthrough()),annotations:D.optional(M2n),icons:D.optional(D.array(hVe)),_meta:D.optional(D.object({}).passthrough())}),D2n=ZVe.extend({method:D.literal("tools/list")}),WKe=NVe.extend({tools:D.array(_2n)}),WVe=N0.extend({content:D.array(vUt).default([]),structuredContent:D.object({}).passthrough().optional(),isError:D.optional(D.boolean())}),bja=WVe.or(N0.extend({toolResult:D.unknown()})),z2n=rN.extend({method:D.literal("tools/call"),params:Z0.extend({name:D.string(),arguments:D.optional(D.record(D.unknown()))})}),P2n=Tw.extend({method:D.literal("notifications/tools/list_changed")}),HUt=D.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),j2n=rN.extend({method:D.literal("logging/setLevel"),params:Z0.extend({level:HUt})}),K2n=Tw.extend({method:D.literal("notifications/message"),params:eue.extend({level:HUt,logger:D.optional(D.string()),data:D.unknown()})}),q2n=D.object({name:D.string().optional()}).passthrough(),$2n=D.object({hints:D.optional(D.array(q2n)),costPriority:D.optional(D.number().min(0).max(1)),speedPriority:D.optional(D.number().min(0).max(1)),intelligencePriority:D.optional(D.number().min(0).max(1))}).passthrough(),eYn=D.object({role:D.enum(["user","assistant"]),content:D.union([AKe,gKe,ZKe])}).passthrough(),tYn=rN.extend({method:D.literal("sampling/createMessage"),params:Z0.extend({messages:D.array(eYn),systemPrompt:D.optional(D.string()),includeContext:D.optional(D.enum(["none","thisServer","allServers"])),temperature:D.optional(D.number()),maxTokens:D.number().int(),stopSequences:D.optional(D.array(D.string())),metadata:D.optional(D.object({}).passthrough()),modelPreferences:D.optional($2n)})}),lYn=N0.extend({model:D.string(),stopReason:D.optional(D.enum(["endTurn","stopSequence","maxTokens"]).or(D.string())),role:D.enum(["user","assistant"]),content:D.discriminatedUnion("type",[AKe,gKe,ZKe])}),nYn=D.object({type:D.literal("boolean"),title:D.optional(D.string()),description:D.optional(D.string()),default:D.optional(D.boolean())}).passthrough(),rYn=D.object({type:D.literal("string"),title:D.optional(D.string()),description:D.optional(D.string()),minLength:D.optional(D.number()),maxLength:D.optional(D.number()),format:D.optional(D.enum(["email","uri","date","date-time"]))}).passthrough(),aYn=D.object({type:D.enum(["number","integer"]),title:D.optional(D.string()),description:D.optional(D.string()),minimum:D.optional(D.number()),maximum:D.optional(D.number())}).passthrough(),IYn=D.object({type:D.literal("string"),title:D.optional(D.string()),description:D.optional(D.string()),enum:D.array(D.string()),enumNames:D.optional(D.array(D.string()))}).passthrough(),sYn=D.union([nYn,rYn,aYn,IYn]),oYn=rN.extend({method:D.literal("elicitation/create"),params:Z0.extend({message:D.string(),requestedSchema:D.object({type:D.literal("object"),properties:D.record(D.string(),sYn),required:D.optional(D.array(D.string()))}).passthrough()})}),iYn=N0.extend({action:D.enum(["accept","decline","cancel"]),content:D.optional(D.record(D.string(),D.unknown()))}),cYn=D.object({type:D.literal("ref/resource"),uri:D.string()}).passthrough();var dYn=D.object({type:D.literal("ref/prompt"),name:D.string()}).passthrough(),uYn=rN.extend({method:D.literal("completion/complete"),params:Z0.extend({ref:D.union([dYn,cYn]),argument:D.object({name:D.string(),value:D.string()}).passthrough(),context:D.optional(D.object({arguments:D.optional(D.record(D.string(),D.string()))}))})}),yKe=N0.extend({completion:D.object({values:D.array(D.string()).max(100),total:D.optional(D.number().int()),hasMore:D.optional(D.boolean())}).passthrough()}),mYn=D.object({uri:D.string().startsWith("file://"),name:D.optional(D.string()),_meta:D.optional(D.object({}).passthrough())}).passthrough(),bYn=rN.extend({method:D.literal("roots/list")}),GYn=N0.extend({roots:D.array(mYn)}),pYn=Tw.extend({method:D.literal("notifications/roots/list_changed")}),Gja=D.union([AVe,Y2n,uYn,j2n,S2n,x2n,F2n,C2n,f2n,H2n,X2n,z2n,D2n]),pja=D.union([pVe,gVe,VUt,pYn]),hja=D.union([DT,lYn,iYn,GYn]),Aja=D.union([AVe,tYn,oYn,bYn]),gja=D.union([pVe,gVe,K2n,k2n,v2n,P2n,U2n]),Zja=D.union([DT,uKe,yKe,NKe,hKe,bKe,GKe,pKe,WVe,WKe]),g0=class extends Error{constructor(e,l,n){super(`MCP error ${e}: ${l}`),this.code=e,this.data=n,this.name="McpError"}};var hYn=6e4,yVe=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(pVe,l=>{let n=this._requestHandlerAbortControllers.get(l.params.requestId);n?.abort(l.params.reason)}),this.setNotificationHandler(gVe,l=>{this._onprogress(l)}),this.setRequestHandler(AVe,l=>({}))}_setupTimeout(e,l,n,r,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,l),startTime:Date.now(),timeout:l,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:r})}_resetTimeout(e){let l=this._timeoutInfo.get(e);if(!l)return!1;let n=Date.now()-l.startTime;if(l.maxTotalTimeout&&n>=l.maxTotalTimeout)throw this._timeoutInfo.delete(e),new g0(A0.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:l.maxTotalTimeout,totalElapsed:n});return clearTimeout(l.timeoutId),l.timeoutId=setTimeout(l.onTimeout,l.timeout),!0}_cleanupTimeout(e){let l=this._timeoutInfo.get(e);l&&(clearTimeout(l.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var l,n,r;this._transport=e;let a=(l=this.transport)===null||l===void 0?void 0:l.onclose;this._transport.onclose=()=>{a?.(),this._onclose()};let I=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=o=>{I?.(o),this._onerror(o)};let s=(r=this._transport)===null||r===void 0?void 0:r.onmessage;this._transport.onmessage=(o,c)=>{s?.(o,c),tue(o)||RUt(o)?this._onresponse(o):GVe(o)?this._onrequest(o,c):WUt(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){var e;let l=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=new g0(A0.ConnectionClosed,"Connection closed");for(let r of l.values())r(n)}_onerror(e){var l;(l=this.onerror)===null||l===void 0||l.call(this,e)}_onnotification(e){var l;let n=(l=this._notificationHandlers.get(e.method))!==null&&l!==void 0?l:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,l){var n,r;let a=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,I=this._transport;if(a===void 0){I?.send({jsonrpc:"2.0",id:e.id,error:{code:A0.MethodNotFound,message:"Method not found"}}).catch(c=>this._onerror(new Error(`Failed to send an error response: ${c}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let o={signal:s.signal,sessionId:I?.sessionId,_meta:(r=e.params)===null||r===void 0?void 0:r._meta,sendNotification:c=>this.notification(c,{relatedRequestId:e.id}),sendRequest:(c,d,m)=>this.request(c,d,{...m,relatedRequestId:e.id}),authInfo:l?.authInfo,requestId:e.id,requestInfo:l?.requestInfo};Promise.resolve().then(()=>a(e,o)).then(c=>{if(!s.signal.aborted)return I?.send({result:c,jsonrpc:"2.0",id:e.id})},c=>{var d;if(!s.signal.aborted)return I?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(c.code)?c.code:A0.InternalError,message:(d=c.message)!==null&&d!==void 0?d:"Internal error"}})}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:l,...n}=e.params,r=Number(l),a=this._progressHandlers.get(r);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let I=this._responseHandlers.get(r),s=this._timeoutInfo.get(r);if(s&&I&&s.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(o){I(o);return}a(n)}_onresponse(e){let l=Number(e.id),n=this._responseHandlers.get(l);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(l),this._progressHandlers.delete(l),this._cleanupTimeout(l),tue(e))n(e);else{let r=new g0(e.error.code,e.error.message,e.error.data);n(r)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,l,n){let{relatedRequestId:r,resumptionToken:a,onresumptiontoken:I}=n??{};return new Promise((s,o)=>{var c,d,m,b,p,A;if(!this._transport){o(new Error("Not connected"));return}((c=this._options)===null||c===void 0?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(d=n?.signal)===null||d===void 0||d.throwIfAborted();let Z=this._requestMessageId++,W={...e,jsonrpc:"2.0",id:Z};n?.onprogress&&(this._progressHandlers.set(Z,n.onprogress),W.params={...e.params,_meta:{...((m=e.params)===null||m===void 0?void 0:m._meta)||{},progressToken:Z}});let R=X=>{var S;this._responseHandlers.delete(Z),this._progressHandlers.delete(Z),this._cleanupTimeout(Z),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:Z,reason:String(X)}},{relatedRequestId:r,resumptionToken:a,onresumptiontoken:I}).catch(U=>this._onerror(new Error(`Failed to send cancellation: ${U}`))),o(X)};this._responseHandlers.set(Z,X=>{var S;if(!(!((S=n?.signal)===null||S===void 0)&&S.aborted)){if(X instanceof Error)return o(X);try{let U=l.parse(X.result);s(U)}catch(U){o(U)}}}),(b=n?.signal)===null||b===void 0||b.addEventListener("abort",()=>{var X;R((X=n?.signal)===null||X===void 0?void 0:X.reason)});let V=(p=n?.timeout)!==null&&p!==void 0?p:hYn,f=()=>R(new g0(A0.RequestTimeout,"Request timed out",{timeout:V}));this._setupTimeout(Z,V,n?.maxTotalTimeout,f,(A=n?.resetTimeoutOnProgress)!==null&&A!==void 0?A:!1),this._transport.send(W,{relatedRequestId:r,resumptionToken:a,onresumptiontoken:I}).catch(X=>{this._cleanupTimeout(Z),o(X)})})}async notification(e,l){var n,r;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((r=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&r!==void 0?r:[]).includes(e.method)&&!e.params&&!l?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var o;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let c={...e,jsonrpc:"2.0"};(o=this._transport)===null||o===void 0||o.send(c,l).catch(d=>this._onerror(d))});return}let s={...e,jsonrpc:"2.0"};await this._transport.send(s,l)}setRequestHandler(e,l){let n=e.shape.method.value;this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(r,a)=>Promise.resolve(l(e.parse(r),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,l){this._notificationHandlers.set(e.shape.method.value,n=>Promise.resolve(l(e.parse(n))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function XUt(t,e){return Object.entries(e).reduce((l,[n,r])=>(r&&typeof r=="object"?l[n]=l[n]?{...l[n],...r}:r:l[n]=r,l),{...t})}var GDt=$e(bDt(),1),rwe=class extends yVe{constructor(e,l){var n;super(l),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=l?.capabilities)!==null&&n!==void 0?n:{},this._ajv=new GDt.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=XUt(this._capabilities,e)}assertCapability(e,l){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${l})`)}async connect(e,l){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:tq,capabilities:this._capabilities,clientInfo:this._clientInfo}},uKe,l);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!hUt.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var l,n,r,a,I;switch(e){case"logging/setLevel":if(!(!((l=this._serverCapabilities)===null||l===void 0)&&l.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((I=this._serverCapabilities)===null||I===void 0)&&I.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var l;switch(e){case"notifications/roots/list_changed":if(!(!((l=this._capabilities.roots)===null||l===void 0)&&l.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},DT,e)}async complete(e,l){return this.request({method:"completion/complete",params:e},yKe,l)}async setLoggingLevel(e,l){return this.request({method:"logging/setLevel",params:{level:e}},DT,l)}async getPrompt(e,l){return this.request({method:"prompts/get",params:e},NKe,l)}async listPrompts(e,l){return this.request({method:"prompts/list",params:e},hKe,l)}async listResources(e,l){return this.request({method:"resources/list",params:e},bKe,l)}async listResourceTemplates(e,l){return this.request({method:"resources/templates/list",params:e},GKe,l)}async readResource(e,l){return this.request({method:"resources/read",params:e},pKe,l)}async subscribeResource(e,l){return this.request({method:"resources/subscribe",params:e},DT,l)}async unsubscribeResource(e,l){return this.request({method:"resources/unsubscribe",params:e},DT,l)}async callTool(e,l=WVe,n){let r=await this.request({method:"tools/call",params:e},l,n),a=this.getToolOutputValidator(e.name);if(a){if(!r.structuredContent&&!r.isError)throw new g0(A0.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{if(!a(r.structuredContent))throw new g0(A0.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(a.errors)}`)}catch(I){throw I instanceof g0?I:new g0(A0.InvalidParams,`Failed to validate structured content: ${I instanceof Error?I.message:String(I)}`)}}return r}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let l of e)if(l.outputSchema)try{let n=this._ajv.compile(l.outputSchema);this._cachedToolOutputValidators.set(l.name,n)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,l){let n=await this.request({method:"tools/list",params:e},WKe,l);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var awe=class{createClient(e,l){return new rwe(e,l)}};var Iwe=class extends Error{constructor(e,l){super(e),this.name="ParseError",this.type=l.type,this.field=l.field,this.value=l.value,this.line=l.line}};function sqe(t){}function swe(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=sqe,onError:l=sqe,onRetry:n=sqe,onComment:r}=t,a="",I=!0,s,o="",c="";function d(Z){let W=I?Z.replace(/^\xEF\xBB\xBF/,""):Z,[R,V]=TFn(`${a}${W}`);for(let f of R)m(f);a=V,I=!1}function m(Z){if(Z===""){p();return}if(Z.startsWith(":")){r&&r(Z.slice(Z.startsWith(": ")?2:1));return}let W=Z.indexOf(":");if(W!==-1){let R=Z.slice(0,W),V=Z[W+1]===" "?2:1,f=Z.slice(W+V);b(R,f,Z);return}b(Z,"",Z)}function b(Z,W,R){switch(Z){case"event":c=W;break;case"data":o=`${o}${W}
|
|
2022
2022
|
`;break;case"id":s=W.includes("\0")?void 0:W;break;case"retry":/^\d+$/.test(W)?n(parseInt(W,10)):l(new Iwe(`Invalid \`retry\` value: "${W}"`,{type:"invalid-retry",value:W,line:R}));break;default:l(new Iwe(`Unknown field "${Z.length>20?`${Z.slice(0,20)}\u2026`:Z}"`,{type:"unknown-field",field:Z,value:W,line:R}));break}}function p(){o.length>0&&e({id:s,event:c||void 0,data:o.endsWith(`
|
|
2023
2023
|
`)?o.slice(0,-1):o}),s=void 0,o="",c=""}function A(Z={}){a&&Z.consume&&m(a),I=!0,s=void 0,o="",c="",a=""}return{feed:d,reset:A}}function TFn(t){let e=[],l="",n=0;for(;n<t.length;){let r=t.indexOf("\r",n),a=t.indexOf(`
|
|
2024
2024
|
`,n),I=-1;if(r!==-1&&a!==-1?I=Math.min(r,a):r!==-1?I=r:a!==-1&&(I=a),I===-1){l=t.slice(n);break}else{let s=t.slice(n,I);e.push(s),n=I+1,t[n-1]==="\r"&&t[n]===`
|
|
2025
2025
|
`&&n++}}return[e,l]}var iwe=class extends Event{constructor(e,l){var n,r;super(e),this.code=(n=l?.code)!=null?n:void 0,this.message=(r=l?.message)!=null?r:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,l,n){return n(pDt(this),l)}[Symbol.for("Deno.customInspect")](e,l){return e(pDt(this),l)}};function OFn(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function oqe(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(oqe).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${oqe(t.cause)}`:t.message:`${t}`}function pDt(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var ADt=t=>{throw TypeError(t)},pqe=(t,e,l)=>e.has(t)||ADt("Cannot "+l),us=(t,e,l)=>(pqe(t,e,"read from private field"),l?l.call(t):e.get(t)),Hb=(t,e,l)=>e.has(t)?ADt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,l),hd=(t,e,l,n)=>(pqe(t,e,"write to private field"),e.set(t,l),l),gv=(t,e,l)=>(pqe(t,e,"access private method"),l),iN,rO,pq,owe,cwe,vue,gq,Hue,CL,hq,Zq,Aq,Cue,iY,iqe,cqe,dqe,hDt,uqe,mqe,fue,bqe,Gqe,aO=class extends EventTarget{constructor(e,l){var n,r;super(),Hb(this,iY),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Hb(this,iN),Hb(this,rO),Hb(this,pq),Hb(this,owe),Hb(this,cwe),Hb(this,vue),Hb(this,gq),Hb(this,Hue,null),Hb(this,CL),Hb(this,hq),Hb(this,Zq,null),Hb(this,Aq,null),Hb(this,Cue,null),Hb(this,cqe,async a=>{var I;us(this,hq).reset();let{body:s,redirected:o,status:c,headers:d}=a;if(c===204){gv(this,iY,fue).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(o?hd(this,pq,new URL(a.url)):hd(this,pq,void 0),c!==200){gv(this,iY,fue).call(this,`Non-200 status code (${c})`,c);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){gv(this,iY,fue).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(us(this,iN)===this.CLOSED)return;hd(this,iN,this.OPEN);let m=new Event("open");if((I=us(this,Cue))==null||I.call(this,m),this.dispatchEvent(m),typeof s!="object"||!s||!("getReader"in s)){gv(this,iY,fue).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let b=new TextDecoder,p=s.getReader(),A=!0;do{let{done:Z,value:W}=await p.read();W&&us(this,hq).feed(b.decode(W,{stream:!Z})),Z&&(A=!1,us(this,hq).reset(),gv(this,iY,bqe).call(this))}while(A)}),Hb(this,dqe,a=>{hd(this,CL,void 0),!(a.name==="AbortError"||a.type==="aborted")&&gv(this,iY,bqe).call(this,oqe(a))}),Hb(this,uqe,a=>{typeof a.id=="string"&&hd(this,Hue,a.id);let I=new MessageEvent(a.event||"message",{data:a.data,origin:us(this,pq)?us(this,pq).origin:us(this,rO).origin,lastEventId:a.id||""});us(this,Aq)&&(!a.event||a.event==="message")&&us(this,Aq).call(this,I),this.dispatchEvent(I)}),Hb(this,mqe,a=>{hd(this,vue,a)}),Hb(this,Gqe,()=>{hd(this,gq,void 0),us(this,iN)===this.CONNECTING&&gv(this,iY,iqe).call(this)});try{if(e instanceof URL)hd(this,rO,e);else if(typeof e=="string")hd(this,rO,new URL(e,UFn()));else throw new Error("Invalid URL")}catch{throw OFn("An invalid or illegal string was specified")}hd(this,hq,swe({onEvent:us(this,uqe),onRetry:us(this,mqe)})),hd(this,iN,this.CONNECTING),hd(this,vue,3e3),hd(this,cwe,(n=l?.fetch)!=null?n:globalThis.fetch),hd(this,owe,(r=l?.withCredentials)!=null?r:!1),gv(this,iY,iqe).call(this)}get readyState(){return us(this,iN)}get url(){return us(this,rO).href}get withCredentials(){return us(this,owe)}get onerror(){return us(this,Zq)}set onerror(e){hd(this,Zq,e)}get onmessage(){return us(this,Aq)}set onmessage(e){hd(this,Aq,e)}get onopen(){return us(this,Cue)}set onopen(e){hd(this,Cue,e)}addEventListener(e,l,n){let r=l;super.addEventListener(e,r,n)}removeEventListener(e,l,n){let r=l;super.removeEventListener(e,r,n)}close(){us(this,gq)&&clearTimeout(us(this,gq)),us(this,iN)!==this.CLOSED&&(us(this,CL)&&us(this,CL).abort(),hd(this,iN,this.CLOSED),hd(this,CL,void 0))}};iN=new WeakMap,rO=new WeakMap,pq=new WeakMap,owe=new WeakMap,cwe=new WeakMap,vue=new WeakMap,gq=new WeakMap,Hue=new WeakMap,CL=new WeakMap,hq=new WeakMap,Zq=new WeakMap,Aq=new WeakMap,Cue=new WeakMap,iY=new WeakSet,iqe=function(){hd(this,iN,this.CONNECTING),hd(this,CL,new AbortController),us(this,cwe)(us(this,rO),gv(this,iY,hDt).call(this)).then(us(this,cqe)).catch(us(this,dqe))},cqe=new WeakMap,dqe=new WeakMap,hDt=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...us(this,Hue)?{"Last-Event-ID":us(this,Hue)}:void 0},cache:"no-store",signal:(t=us(this,CL))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},uqe=new WeakMap,mqe=new WeakMap,fue=function(t,e){var l;us(this,iN)!==this.CLOSED&&hd(this,iN,this.CLOSED);let n=new iwe("error",{code:e,message:t});(l=us(this,Zq))==null||l.call(this,n),this.dispatchEvent(n)},bqe=function(t,e){var l;if(us(this,iN)===this.CLOSED)return;hd(this,iN,this.CONNECTING);let n=new iwe("error",{code:e,message:t});(l=us(this,Zq))==null||l.call(this,n),this.dispatchEvent(n),hd(this,gq,setTimeout(us(this,Gqe),us(this,vue)))},Gqe=new WeakMap,aO.CONNECTING=0,aO.OPEN=1,aO.CLOSED=2;function UFn(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var hqe;hqe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function MFn(t){return(await hqe).getRandomValues(new Uint8Array(t))}async function _Fn(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",l="",n=await MFn(t);for(let r=0;r<t;r++){let a=n[r]%e.length;l+=e[a]}return l}async function DFn(t){return await _Fn(t)}async function zFn(t){let e=await(await hqe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Aqe(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await DFn(t),l=await zFn(e);return{code_verifier:e,code_challenge:l}}var xG=D.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:D.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),D.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),gDt=D.object({resource:D.string().url(),authorization_servers:D.array(xG).optional(),jwks_uri:D.string().url().optional(),scopes_supported:D.array(D.string()).optional(),bearer_methods_supported:D.array(D.string()).optional(),resource_signing_alg_values_supported:D.array(D.string()).optional(),resource_name:D.string().optional(),resource_documentation:D.string().optional(),resource_policy_uri:D.string().url().optional(),resource_tos_uri:D.string().url().optional(),tls_client_certificate_bound_access_tokens:D.boolean().optional(),authorization_details_types_supported:D.array(D.string()).optional(),dpop_signing_alg_values_supported:D.array(D.string()).optional(),dpop_bound_access_tokens_required:D.boolean().optional()}).passthrough(),gqe=D.object({issuer:D.string(),authorization_endpoint:xG,token_endpoint:xG,registration_endpoint:xG.optional(),scopes_supported:D.array(D.string()).optional(),response_types_supported:D.array(D.string()),response_modes_supported:D.array(D.string()).optional(),grant_types_supported:D.array(D.string()).optional(),token_endpoint_auth_methods_supported:D.array(D.string()).optional(),token_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),service_documentation:xG.optional(),revocation_endpoint:xG.optional(),revocation_endpoint_auth_methods_supported:D.array(D.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),introspection_endpoint:D.string().optional(),introspection_endpoint_auth_methods_supported:D.array(D.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),code_challenge_methods_supported:D.array(D.string()).optional()}).passthrough(),PFn=D.object({issuer:D.string(),authorization_endpoint:xG,token_endpoint:xG,userinfo_endpoint:xG.optional(),jwks_uri:xG,registration_endpoint:xG.optional(),scopes_supported:D.array(D.string()).optional(),response_types_supported:D.array(D.string()),response_modes_supported:D.array(D.string()).optional(),grant_types_supported:D.array(D.string()).optional(),acr_values_supported:D.array(D.string()).optional(),subject_types_supported:D.array(D.string()),id_token_signing_alg_values_supported:D.array(D.string()),id_token_encryption_alg_values_supported:D.array(D.string()).optional(),id_token_encryption_enc_values_supported:D.array(D.string()).optional(),userinfo_signing_alg_values_supported:D.array(D.string()).optional(),userinfo_encryption_alg_values_supported:D.array(D.string()).optional(),userinfo_encryption_enc_values_supported:D.array(D.string()).optional(),request_object_signing_alg_values_supported:D.array(D.string()).optional(),request_object_encryption_alg_values_supported:D.array(D.string()).optional(),request_object_encryption_enc_values_supported:D.array(D.string()).optional(),token_endpoint_auth_methods_supported:D.array(D.string()).optional(),token_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),display_values_supported:D.array(D.string()).optional(),claim_types_supported:D.array(D.string()).optional(),claims_supported:D.array(D.string()).optional(),service_documentation:D.string().optional(),claims_locales_supported:D.array(D.string()).optional(),ui_locales_supported:D.array(D.string()).optional(),claims_parameter_supported:D.boolean().optional(),request_parameter_supported:D.boolean().optional(),request_uri_parameter_supported:D.boolean().optional(),require_request_uri_registration:D.boolean().optional(),op_policy_uri:xG.optional(),op_tos_uri:xG.optional()}).passthrough(),ZDt=PFn.merge(gqe.pick({code_challenge_methods_supported:!0})),Zqe=D.object({access_token:D.string(),id_token:D.string().optional(),token_type:D.string(),expires_in:D.number().optional(),scope:D.string().optional(),refresh_token:D.string().optional()}).strip(),NDt=D.object({error:D.string(),error_description:D.string().optional(),error_uri:D.string().optional()}),jFn=D.object({redirect_uris:D.array(xG),token_endpoint_auth_method:D.string().optional(),grant_types:D.array(D.string()).optional(),response_types:D.array(D.string()).optional(),client_name:D.string().optional(),client_uri:xG.optional(),logo_uri:xG.optional(),scope:D.string().optional(),contacts:D.array(D.string()).optional(),tos_uri:xG.optional(),policy_uri:D.string().optional(),jwks_uri:xG.optional(),jwks:D.any().optional(),software_id:D.string().optional(),software_version:D.string().optional(),software_statement:D.string().optional()}).strip(),KFn=D.object({client_id:D.string(),client_secret:D.string().optional(),client_id_issued_at:D.number().optional(),client_secret_expires_at:D.number().optional()}).strip(),WDt=jFn.merge(KFn),z6a=D.object({error:D.string(),error_description:D.string().optional()}).strip(),P6a=D.object({token:D.string(),token_type_hint:D.string().optional()}).strip();function yDt(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function EDt({requestedResource:t,configuredResource:e}){let l=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(l.origin!==n.origin||l.pathname.length<n.pathname.length)return!1;let r=l.pathname.endsWith("/")?l.pathname:l.pathname+"/",a=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return r.startsWith(a)}var jm=class extends Error{constructor(e,l){super(e),this.errorUri=l,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Xue=class extends jm{};Xue.errorCode="invalid_request";var IO=class extends jm{};IO.errorCode="invalid_client";var sO=class extends jm{};sO.errorCode="invalid_grant";var oO=class extends jm{};oO.errorCode="unauthorized_client";var kue=class extends jm{};kue.errorCode="unsupported_grant_type";var Lue=class extends jm{};Lue.errorCode="invalid_scope";var Jue=class extends jm{};Jue.errorCode="access_denied";var Zv=class extends jm{};Zv.errorCode="server_error";var xue=class extends jm{};xue.errorCode="temporarily_unavailable";var Sue=class extends jm{};Sue.errorCode="unsupported_response_type";var Bue=class extends jm{};Bue.errorCode="unsupported_token_type";var Tue=class extends jm{};Tue.errorCode="invalid_token";var Oue=class extends jm{};Oue.errorCode="method_not_allowed";var Uue=class extends jm{};Uue.errorCode="too_many_requests";var Mue=class extends jm{};Mue.errorCode="invalid_client_metadata";var _ue=class extends jm{};_ue.errorCode="insufficient_scope";var RDt={[Xue.errorCode]:Xue,[IO.errorCode]:IO,[sO.errorCode]:sO,[oO.errorCode]:oO,[kue.errorCode]:kue,[Lue.errorCode]:Lue,[Jue.errorCode]:Jue,[Zv.errorCode]:Zv,[xue.errorCode]:xue,[Sue.errorCode]:Sue,[Bue.errorCode]:Bue,[Tue.errorCode]:Tue,[Oue.errorCode]:Oue,[Uue.errorCode]:Uue,[Mue.errorCode]:Mue,[_ue.errorCode]:_ue};var cN=class extends Error{constructor(e){super(e??"Unauthorized")}};function VDt(t,e){let l=t.client_secret!==void 0;return e.length===0?l?"client_secret_post":"none":l&&e.includes("client_secret_basic")?"client_secret_basic":l&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":l?"client_secret_post":"none"}function wDt(t,e,l,n){let{client_id:r,client_secret:a}=e;switch(t){case"client_secret_basic":qFn(r,a,l);return;case"client_secret_post":$Fn(r,a,n);return;case"none":eCn(r,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function qFn(t,e,l){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);l.set("Authorization",`Basic ${n}`)}function $Fn(t,e,l){l.set("client_id",t),e&&l.set("client_secret",e)}function eCn(t,e){e.set("client_id",t)}async function Wqe(t){let e=t instanceof Response?t.status:void 0,l=t instanceof Response?await t.text():t;try{let n=NDt.parse(JSON.parse(l)),{error:r,error_description:a,error_uri:I}=n,s=RDt[r]||Zv;return new s(a||"",I)}catch(n){let r=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${l}`;return new Zv(r)}}async function fL(t,e){var l,n;try{return await Nqe(t,e)}catch(r){if(r instanceof IO||r instanceof oO)return await((l=t.invalidateCredentials)===null||l===void 0?void 0:l.call(t,"all")),await Nqe(t,e);if(r instanceof sO)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await Nqe(t,e);throw r}}async function Nqe(t,{serverUrl:e,authorizationCode:l,scope:n,resourceMetadataUrl:r,fetchFn:a}){let I,s;try{I=await lCn(e,{resourceMetadataUrl:r},a),I.authorization_servers&&I.authorization_servers.length>0&&(s=I.authorization_servers[0])}catch{}s||(s=e);let o=await tCn(e,t,I),c=await sCn(s,{fetchFn:a}),d=await Promise.resolve(t.clientInformation());if(!d){if(l!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Z=await dCn(s,{metadata:c,clientMetadata:t.clientMetadata,fetchFn:a});await t.saveClientInformation(Z),d=Z}if(l!==void 0){let Z=await t.codeVerifier(),W=await iCn(s,{metadata:c,clientInformation:d,authorizationCode:l,codeVerifier:Z,redirectUri:t.redirectUrl,resource:o,addClientAuthentication:t.addClientAuthentication,fetchFn:a});return await t.saveTokens(W),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let Z=await cCn(s,{metadata:c,clientInformation:d,refreshToken:m.refresh_token,resource:o,addClientAuthentication:t.addClientAuthentication,fetchFn:a});return await t.saveTokens(Z),"AUTHORIZED"}catch(Z){if(!(!(Z instanceof jm)||Z instanceof Zv))throw Z}let b=t.state?await t.state():void 0,{authorizationUrl:p,codeVerifier:A}=await oCn(s,{metadata:c,clientInformation:d,state:b,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:o});return await t.saveCodeVerifier(A),await t.redirectToAuthorization(p),"REDIRECT"}async function tCn(t,e,l){let n=yDt(t);if(e.validateResourceURL)return await e.validateResourceURL(n,l?.resource);if(l){if(!EDt({requestedResource:n,configuredResource:l.resource}))throw new Error(`Protected resource ${l.resource} does not match expected ${n} (or origin)`);return new URL(l.resource)}}function Due(t){let e=t.headers.get("WWW-Authenticate");if(!e)return;let[l,n]=e.split(" ");if(l.toLowerCase()!=="bearer"||!n)return;let a=/resource_metadata="([^"]*)"/.exec(e);if(a)try{return new URL(a[1])}catch{return}}async function lCn(t,e,l=fetch){let n=await aCn(t,"oauth-protected-resource",l,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return gDt.parse(await n.json())}async function yqe(t,e,l=fetch){try{return await l(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?yqe(t,void 0,l):void 0;throw n}}function nCn(t,e="",l={}){return e.endsWith("/")&&(e=e.slice(0,-1)),l.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function YDt(t,e,l=fetch){return await yqe(t,{"MCP-Protocol-Version":e},l)}function rCn(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function aCn(t,e,l,n){var r,a;let I=new URL(t),s=(r=n?.protocolVersion)!==null&&r!==void 0?r:tq,o;if(n?.metadataUrl)o=new URL(n.metadataUrl);else{let d=nCn(e,I.pathname);o=new URL(d,(a=n?.metadataServerUrl)!==null&&a!==void 0?a:I),o.search=I.search}let c=await YDt(o,s,l);if(!n?.metadataUrl&&rCn(c,I.pathname)){let d=new URL(`/.well-known/${e}`,I);c=await YDt(d,s,l)}return c}function ICn(t){let e=typeof t=="string"?new URL(t):t,l=e.pathname!=="/",n=[];if(!l)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let r=e.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${r}`,e.origin),type:"oidc"}),n.push({url:new URL(`${r}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function sCn(t,{fetchFn:e=fetch,protocolVersion:l=tq}={}){var n;let r={"MCP-Protocol-Version":l},a=ICn(t);for(let{url:I,type:s}of a){let o=await yqe(I,r,e);if(o){if(!o.ok){if(o.status>=400&&o.status<500)continue;throw new Error(`HTTP ${o.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${I}`)}if(s==="oauth")return gqe.parse(await o.json());{let c=ZDt.parse(await o.json());if(!(!((n=c.code_challenge_methods_supported)===null||n===void 0)&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${I}: does not support S256 code challenge method required by MCP specification`);return c}}}}async function oCn(t,{metadata:e,clientInformation:l,redirectUrl:n,scope:r,state:a,resource:I}){let s="code",o="S256",c;if(e){if(c=new URL(e.authorization_endpoint),!e.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(o))throw new Error(`Incompatible auth server: does not support code challenge method ${o}`)}else c=new URL("/authorize",t);let d=await Aqe(),m=d.code_verifier,b=d.code_challenge;return c.searchParams.set("response_type",s),c.searchParams.set("client_id",l.client_id),c.searchParams.set("code_challenge",b),c.searchParams.set("code_challenge_method",o),c.searchParams.set("redirect_uri",String(n)),a&&c.searchParams.set("state",a),r&&c.searchParams.set("scope",r),r?.includes("offline_access")&&c.searchParams.append("prompt","consent"),I&&c.searchParams.set("resource",I.href),{authorizationUrl:c,codeVerifier:m}}async function iCn(t,{metadata:e,clientInformation:l,authorizationCode:n,codeVerifier:r,redirectUri:a,resource:I,addClientAuthentication:s,fetchFn:o}){var c;let d="authorization_code",m=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);let b=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:d,code:n,code_verifier:r,redirect_uri:String(a)});if(s)s(b,p,t,e);else{let Z=(c=e?.token_endpoint_auth_methods_supported)!==null&&c!==void 0?c:[],W=VDt(l,Z);wDt(W,l,b,p)}I&&p.set("resource",I.href);let A=await(o??fetch)(m,{method:"POST",headers:b,body:p});if(!A.ok)throw await Wqe(A);return Zqe.parse(await A.json())}async function cCn(t,{metadata:e,clientInformation:l,refreshToken:n,resource:r,addClientAuthentication:a,fetchFn:I}){var s;let o="refresh_token",c;if(e){if(c=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(o))throw new Error(`Incompatible auth server: does not support grant type ${o}`)}else c=new URL("/token",t);let d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),m=new URLSearchParams({grant_type:o,refresh_token:n});if(a)a(d,m,t,e);else{let p=(s=e?.token_endpoint_auth_methods_supported)!==null&&s!==void 0?s:[],A=VDt(l,p);wDt(A,l,d,m)}r&&m.set("resource",r.href);let b=await(I??fetch)(c,{method:"POST",headers:d,body:m});if(!b.ok)throw await Wqe(b);return Zqe.parse({refresh_token:n,...await b.json()})}async function dCn(t,{metadata:e,clientMetadata:l,fetchFn:n}){let r;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");r=new URL(e.registration_endpoint)}else r=new URL("/register",t);let a=await(n??fetch)(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!a.ok)throw await Wqe(a);return WDt.parse(await a.json())}var Eqe=class extends Error{constructor(e,l,n){super(`SSE error: ${l}`),this.code=e,this.event=n}},dwe=class{constructor(e,l){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=l?.eventSourceInit,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new cN("No auth provider");let l;try{l=await fL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new cN;return await this._startOrAuth()}async _commonHeaders(){var e;let l={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(l.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion),new Headers({...l,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,l,n;let r=(n=(l=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&l!==void 0?l:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((a,I)=>{this._eventSource=new aO(this._url.href,{...this._eventSourceInit,fetch:async(s,o)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let d=await r(s,{...o,headers:c});return d.status===401&&d.headers.has("www-authenticate")&&(this._resourceMetadataUrl=Due(d)),d}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{var o;if(s.code===401&&this._authProvider){this._authThenStart().then(a,I);return}let c=new Eqe(s.code,s.message,s);I(c),(o=this.onerror)===null||o===void 0||o.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{var o;let c=s;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(d){I(d),(o=this.onerror)===null||o===void 0||o.call(this,d),this.close();return}a()}),this._eventSource.onmessage=s=>{var o,c;let d=s,m;try{m=yL.parse(JSON.parse(d.data))}catch(b){(o=this.onerror)===null||o===void 0||o.call(this,b);return}(c=this.onmessage)===null||c===void 0||c.call(this,m)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new cN("No auth provider");if(await fL(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new cN("Failed to authorize")}async close(){var e,l,n;(e=this._abortController)===null||e===void 0||e.abort(),(l=this._eventSource)===null||l===void 0||l.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var l,n,r;if(!this._endpoint)throw new Error("Not connected");try{let a=await this._commonHeaders();a.set("content-type","application/json");let I={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},s=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,I);if(!s.ok){if(s.status===401&&this._authProvider){if(this._resourceMetadataUrl=Due(s),await fL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new cN;return this.send(e)}let o=await s.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${o}`)}}catch(a){throw(r=this.onerror)===null||r===void 0||r.call(this,a),a}}setProtocolVersion(e){this._protocolVersion=e}};var Azt=$e(pzt(),1);import Gwe from"node:process";import{PassThrough as xCn}from"node:stream";var mwe=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
2026
2026
|
`);if(e===-1)return null;let l=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),JCn(l)}clear(){this._buffer=void 0}};function JCn(t){return yL.parse(JSON.parse(t))}function hzt(t){return JSON.stringify(t)+`
|
|
2027
|
-
`}var SCn=Gwe.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function BCn(){let t={};for(let e of SCn){let l=Gwe.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var bwe=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new mwe,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new xCn)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,l)=>{var n,r,a,I,s;this._process=(0,Azt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...BCn(),...this._serverParams.env},stdio:["pipe","pipe",(r=this._serverParams.stderr)!==null&&r!==void 0?r:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:Gwe.platform==="win32"&&TCn(),cwd:this._serverParams.cwd}),this._process.on("error",o=>{var c,d;if(o.name==="AbortError"){(c=this.onclose)===null||c===void 0||c.call(this);return}l(o),(d=this.onerror)===null||d===void 0||d.call(this,o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{var c;this._process=void 0,(c=this.onclose)===null||c===void 0||c.call(this)}),(a=this._process.stdin)===null||a===void 0||a.on("error",o=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,o)}),(I=this._process.stdout)===null||I===void 0||I.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",o=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,l;return this._stderrStream?this._stderrStream:(l=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&l!==void 0?l:null}get pid(){var e,l;return(l=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&l!==void 0?l:null}processReadBuffer(){for(var e,l;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(l=this.onerror)===null||l===void 0||l.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(l=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let r=hzt(e);this._process.stdin.write(r)?l():this._process.stdin.once("drain",l)})}};function TCn(){return"type"in Gwe}var pwe=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let r;super({start(a){r=swe({onEvent:I=>{a.enqueue(I)},onError(I){e==="terminate"?a.error(I):typeof e=="function"&&e(I)},onRetry:l,onComment:n})},transform(a){r.feed(a)}})}};var OCn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},zue=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},hwe=class{constructor(e,l){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch,this._sessionId=l?.sessionId,this._reconnectionOptions=(n=l?.reconnectionOptions)!==null&&n!==void 0?n:OCn}async _authThenStart(){var e;if(!this._authProvider)throw new cN("No auth provider");let l;try{l=await fL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new cN;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let l={};if(this._authProvider){let r=await this._authProvider.tokens();r&&(l.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(l["mcp-session-id"]=this._sessionId),this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...l,...n})}async _startOrAuthSse(e){var l,n,r;let{resumptionToken:a}=e;try{let I=await this._commonHeaders();I.set("Accept","text/event-stream"),a&&I.set("last-event-id",a);let s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,{method:"GET",headers:I,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new zue(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(I){throw(r=this.onerror)===null||r===void 0||r.call(this,I),I}}_getNextReconnectionDelay(e){let l=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(n,e),r)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,l=0){var n;let r=this._reconnectionOptions.maxRetries;if(r>0&&l>=r){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}let a=this._getNextReconnectionDelay(l);setTimeout(()=>{this._startOrAuthSse(e).catch(I=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${I instanceof Error?I.message:String(I)}`)),this._scheduleReconnection(e,l+1)})},a)}_handleSseStream(e,l,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:a}=l,I;(async()=>{var o,c,d,m;try{let b=e.pipeThrough(new TextDecoderStream).pipeThrough(new pwe).getReader();for(;;){let{value:p,done:A}=await b.read();if(A)break;if(p.id&&(I=p.id,r?.(p.id)),!p.event||p.event==="message")try{let Z=yL.parse(JSON.parse(p.data));a!==void 0&&tue(Z)&&(Z.id=a),(o=this.onmessage)===null||o===void 0||o.call(this,Z)}catch(Z){(c=this.onerror)===null||c===void 0||c.call(this,Z)}}}catch(b){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${b}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:I,onresumptiontoken:r,replayMessageId:a},0)}catch(p){(m=this.onerror)===null||m===void 0||m.call(this,new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new cN("No auth provider");if(await fL(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new cN("Failed to authorize")}async close(){var e,l;(e=this._abortController)===null||e===void 0||e.abort(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e,l){var n,r,a,I;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:GVe(e)?e.id:void 0}).catch(W=>{var R;return(R=this.onerror)===null||R===void 0?void 0:R.call(this,W)});return}let c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,d),b=m.headers.get("mcp-session-id");if(b&&(this._sessionId=b),!m.ok){if(m.status===401&&this._authProvider){if(this._resourceMetadataUrl=Due(m),await fL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new cN;return this.send(e)}let W=await m.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${m.status}): ${W}`)}if(m.status===202){wUt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(W=>{var R;return(R=this.onerror)===null||R===void 0?void 0:R.call(this,W)});return}let A=(Array.isArray(e)?e:[e]).filter(W=>"method"in W&&"id"in W&&W.id!==void 0).length>0,Z=m.headers.get("content-type");if(A)if(Z?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:o},!1);else if(Z?.includes("application/json")){let W=await m.json(),R=Array.isArray(W)?W.map(V=>yL.parse(V)):[yL.parse(W)];for(let V of R)(a=this.onmessage)===null||a===void 0||a.call(this,V)}else throw new zue(-1,`Unexpected content type: ${Z}`)}catch(s){throw(I=this.onerror)===null||I===void 0||I.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,l,n;if(this._sessionId)try{let r=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:r,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},I=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,a);if(!I.ok&&I.status!==405)throw new zue(I.status,`Failed to terminate session: ${I.statusText}`);this._sessionId=void 0}catch(r){throw(n=this.onerror)===null||n===void 0||n.call(this,r),r}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};var Awe=class{constructor(e){this.server=e}onmessage;onerror;onclose;serverTransport;closed=!1;async start(){if(this.closed)throw new Error("Transport is closed");this.serverTransport=new Hqe(this),await this.server.connect(this.serverTransport)}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},Hqe=class{constructor(e){this.clientTransport=e}onmessage;onerror;onclose;closed=!1;async start(){}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var gwe=class{createTransport(e){switch(e.type){case"stdio":{let l=new bwe({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0,cwd:e.cwd});return l.stderr?.pipe(e.stderr),l}case"http":return new hwe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new dwe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new Awe(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};var Pue="blackbird-mcp-server",vL="github-mcp-server",Xqe="playwright",jue=[Pue];function yq(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function HL(t){return Kue(t)||que(t)}function Kue(t){return t.type?.toLowerCase()==="http"}function que(t){return t.type?.toLowerCase()==="sse"}function $ue(t){return t.type?.toLowerCase()==="memory"}var kqe=class extends UCn{constructor(l,n){super({decodeStrings:!1});this.serverName=l;this.logger=n}_write(l,n,r){try{let a=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${a}`),r()}catch(a){r(a instanceof Error?a:new Error(String(a)))}}},Zwe=class{constructor(e,l=new awe,n=new gwe,r="indirect"){this.logger=e;this.clientFactory=l;this.transportFactory=n;this.envValueMode=r}clients={};transports={};configs={};async startLocalMcpClient(e,l){this.logger.log(`Starting MCP client for ${e} with command: ${l.command} and args: ${l.args}`);let n=new kqe(e,this.logger),r={type:"stdio",command:l.command,args:l.args,env:{...l.env||{},PATH:process.env.PATH},stderr:n,cwd:l.cwd},a=this.transportFactory.createTransport(r);await this.setupAndConnectClient(e,l,a)}async startHttpMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"http",url:l.url,headers:l.headers},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,l,r)}async startSseMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"sse",url:l.url,headers:l.headers},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,l,r)}async startInMemoryMcpClient(e,l,n){this.logger.log(`Starting in-memory MCP client for ${e}`);let r={type:"memory",server:n},a=this.transportFactory.createTransport(r);await this.setupAndConnectClient(e,l,a)}async setupAndConnectClient(e,l,n){this.transports[e]=n,n.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e],delete this.configs[e]},this.configs[e]=l,l.timeout!==void 0&&this.logger.log(`MCP client for ${e} configured with timeout: ${l.timeout}ms`),this.logger.log(`Creating MCP client for ${e}...`);let r=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),a=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await r.connect(n),r.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},r.onerror=I=>{this.logger.error(`MCP client for ${e} errored ${I}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-a}ms`),this.clients[e]=r}async getTools(e,l){let n={};for(let[r,a]of Object.entries(this.clients))(await this.getServerTools(r,a,e,l)).forEach(s=>{n[s.namespacedName]=s});return this.logger.log(`All tools retrieved: ${JSON.stringify(n,null,2)}`),n}async getServerTools(e,l,n,r){let a=[];try{this.logger.log(`Fetching tools from client: ${e}`);let I=await l.listTools(),s=n?.mcpServers[e].tools,o=n?.mcpServers[e].filterMapping;for(let d of I.tools){if(d.name==="get_copilot_space")continue;if(!(s?.includes("*")||s?.includes(d.name))){this.logger.log(`Tool ${d.name} is not in the allowed list for client: ${e}`);continue}let b=Z0e(e,d.name),p=`${e}-${d.name}`,A;typeof o=="string"?A=vOe(o):A=vOe(o?.[d.name]??"hidden_characters");let Z=`${e}/${d.name}`,W={name:p,namespacedName:Z,title:d.title||d.annotations?.title||Z||d.name,description:d.description??p,input_schema:d.inputSchema,readOnly:d.annotations?.readOnlyHint,safeForTelemetry:{name:!!(n?.mcpServers[e].isDefaultServer||b),inputsNames:!!n?.mcpServers[e].isDefaultServer},filterMode:A};a.push(W),this.logger.log(`Tool ${d.name} added to tools list for client: ${e}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${e}`);let c=l.getServerVersion();await this.logServerSuccessWithTools(e,a,c,r)}catch(I){this.logger.error(`Failed to get tools from client: ${e} ${I}`)}return a}async logServerSuccessWithTools(e,l,n,r){if(!jue.includes(e)&&r)try{let a=l.map(c=>`- ${c.namespacedName}`).join(`
|
|
2027
|
+
`}var SCn=Gwe.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function BCn(){let t={};for(let e of SCn){let l=Gwe.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var bwe=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new mwe,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new xCn)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,l)=>{var n,r,a,I,s;this._process=(0,Azt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...BCn(),...this._serverParams.env},stdio:["pipe","pipe",(r=this._serverParams.stderr)!==null&&r!==void 0?r:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:Gwe.platform==="win32"&&TCn(),cwd:this._serverParams.cwd}),this._process.on("error",o=>{var c,d;if(o.name==="AbortError"){(c=this.onclose)===null||c===void 0||c.call(this);return}l(o),(d=this.onerror)===null||d===void 0||d.call(this,o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{var c;this._process=void 0,(c=this.onclose)===null||c===void 0||c.call(this)}),(a=this._process.stdin)===null||a===void 0||a.on("error",o=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,o)}),(I=this._process.stdout)===null||I===void 0||I.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",o=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,l;return this._stderrStream?this._stderrStream:(l=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&l!==void 0?l:null}get pid(){var e,l;return(l=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&l!==void 0?l:null}processReadBuffer(){for(var e,l;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(l=this.onerror)===null||l===void 0||l.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(l=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let r=hzt(e);this._process.stdin.write(r)?l():this._process.stdin.once("drain",l)})}};function TCn(){return"type"in Gwe}var pwe=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let r;super({start(a){r=swe({onEvent:I=>{a.enqueue(I)},onError(I){e==="terminate"?a.error(I):typeof e=="function"&&e(I)},onRetry:l,onComment:n})},transform(a){r.feed(a)}})}};var OCn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},zue=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},hwe=class{constructor(e,l){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch,this._sessionId=l?.sessionId,this._reconnectionOptions=(n=l?.reconnectionOptions)!==null&&n!==void 0?n:OCn}async _authThenStart(){var e;if(!this._authProvider)throw new cN("No auth provider");let l;try{l=await fL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new cN;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let l={};if(this._authProvider){let r=await this._authProvider.tokens();r&&(l.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(l["mcp-session-id"]=this._sessionId),this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...l,...n})}async _startOrAuthSse(e){var l,n,r;let{resumptionToken:a}=e;try{let I=await this._commonHeaders();I.set("Accept","text/event-stream"),a&&I.set("last-event-id",a);let s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,{method:"GET",headers:I,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new zue(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(I){throw(r=this.onerror)===null||r===void 0||r.call(this,I),I}}_getNextReconnectionDelay(e){let l=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(n,e),r)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,l=0){var n;let r=this._reconnectionOptions.maxRetries;if(r>0&&l>=r){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}let a=this._getNextReconnectionDelay(l);setTimeout(()=>{this._startOrAuthSse(e).catch(I=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${I instanceof Error?I.message:String(I)}`)),this._scheduleReconnection(e,l+1)})},a)}_handleSseStream(e,l,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:a}=l,I;(async()=>{var o,c,d,m;try{let b=e.pipeThrough(new TextDecoderStream).pipeThrough(new pwe).getReader();for(;;){let{value:p,done:A}=await b.read();if(A)break;if(p.id&&(I=p.id,r?.(p.id)),!p.event||p.event==="message")try{let Z=yL.parse(JSON.parse(p.data));a!==void 0&&tue(Z)&&(Z.id=a),(o=this.onmessage)===null||o===void 0||o.call(this,Z)}catch(Z){(c=this.onerror)===null||c===void 0||c.call(this,Z)}}}catch(b){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${b}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:I,onresumptiontoken:r,replayMessageId:a},0)}catch(p){(m=this.onerror)===null||m===void 0||m.call(this,new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new cN("No auth provider");if(await fL(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new cN("Failed to authorize")}async close(){var e,l;(e=this._abortController)===null||e===void 0||e.abort(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e,l){var n,r,a,I;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:GVe(e)?e.id:void 0}).catch(W=>{var R;return(R=this.onerror)===null||R===void 0?void 0:R.call(this,W)});return}let c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,d),b=m.headers.get("mcp-session-id");if(b&&(this._sessionId=b),!m.ok){if(m.status===401&&this._authProvider){if(this._resourceMetadataUrl=Due(m),await fL(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new cN;return this.send(e)}let W=await m.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${m.status}): ${W}`)}if(m.status===202){wUt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(W=>{var R;return(R=this.onerror)===null||R===void 0?void 0:R.call(this,W)});return}let A=(Array.isArray(e)?e:[e]).filter(W=>"method"in W&&"id"in W&&W.id!==void 0).length>0,Z=m.headers.get("content-type");if(A)if(Z?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:o},!1);else if(Z?.includes("application/json")){let W=await m.json(),R=Array.isArray(W)?W.map(V=>yL.parse(V)):[yL.parse(W)];for(let V of R)(a=this.onmessage)===null||a===void 0||a.call(this,V)}else throw new zue(-1,`Unexpected content type: ${Z}`)}catch(s){throw(I=this.onerror)===null||I===void 0||I.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,l,n;if(this._sessionId)try{let r=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:r,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},I=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,a);if(!I.ok&&I.status!==405)throw new zue(I.status,`Failed to terminate session: ${I.statusText}`);this._sessionId=void 0}catch(r){throw(n=this.onerror)===null||n===void 0||n.call(this,r),r}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};var Awe=class{constructor(e){this.server=e}onmessage;onerror;onclose;serverTransport;closed=!1;async start(){if(this.closed)throw new Error("Transport is closed");this.serverTransport=new Hqe(this),await this.server.connect(this.serverTransport)}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},Hqe=class{constructor(e){this.clientTransport=e}onmessage;onerror;onclose;closed=!1;async start(){}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var gwe=class{createTransport(e){switch(e.type){case"stdio":{let l=new bwe({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0,cwd:e.cwd});return l.stderr?.pipe(e.stderr),l}case"http":return new hwe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new dwe(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new Awe(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};var Pue="blackbird-mcp-server",vL="github-mcp-server",Xqe="playwright",jue=[Pue];function yq(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function HL(t){return Kue(t)||que(t)}function Kue(t){return t.type?.toLowerCase()==="http"}function que(t){return t.type?.toLowerCase()==="sse"}function $ue(t){return t.type?.toLowerCase()==="memory"}var kqe=class extends UCn{constructor(l,n){super({decodeStrings:!1});this.serverName=l;this.logger=n}_write(l,n,r){try{let a=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${a}`),r()}catch(a){r(a instanceof Error?a:new Error(String(a)))}}},Zwe=class{constructor(e,l=new awe,n=new gwe,r="indirect"){this.logger=e;this.clientFactory=l;this.transportFactory=n;this.envValueMode=r}clients={};transports={};configs={};toolsChangedCallback;setToolsChangedCallback(e){this.toolsChangedCallback=e}async startLocalMcpClient(e,l){this.logger.log(`Starting MCP client for ${e} with command: ${l.command} and args: ${l.args}`);let n=new kqe(e,this.logger),r={type:"stdio",command:l.command,args:l.args,env:{...l.env||{},PATH:process.env.PATH},stderr:n,cwd:l.cwd},a=this.transportFactory.createTransport(r);await this.setupAndConnectClient(e,l,a)}async startHttpMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"http",url:l.url,headers:l.headers},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,l,r)}async startSseMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"sse",url:l.url,headers:l.headers},r=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,l,r)}async startInMemoryMcpClient(e,l,n){this.logger.log(`Starting in-memory MCP client for ${e}`);let r={type:"memory",server:n},a=this.transportFactory.createTransport(r);await this.setupAndConnectClient(e,l,a)}async setupAndConnectClient(e,l,n){this.transports[e]=n,n.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e],delete this.configs[e]},this.configs[e]=l,l.timeout!==void 0&&this.logger.log(`MCP client for ${e} configured with timeout: ${l.timeout}ms`),this.logger.log(`Creating MCP client for ${e}...`);let r=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),a=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await r.connect(n),r.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},r.onerror=s=>{this.logger.error(`MCP client for ${e} errored ${s}`)};let I=D.object({method:D.literal("notifications/tools/list_changed")});r.setNotificationHandler(I,()=>{if(this.logger.log(`Received tools/list_changed notification from ${e}`),this.toolsChangedCallback){let s=this.toolsChangedCallback(e);s instanceof Promise&&s.catch(o=>{this.logger.error(`Error in tools changed callback for ${e}: ${o}`)})}}),this.logger.log(`MCP client for ${e} connected, took ${Date.now()-a}ms`),this.clients[e]=r}async getTools(e,l){let n={};for(let[r,a]of Object.entries(this.clients))(await this.getServerTools(r,a,e,l)).forEach(s=>{n[s.namespacedName]=s});return this.logger.log(`All tools retrieved: ${JSON.stringify(n,null,2)}`),n}async getServerTools(e,l,n,r){let a=[];try{this.logger.log(`Fetching tools from client: ${e}`);let I=await l.listTools(),s=n?.mcpServers[e].tools,o=n?.mcpServers[e].filterMapping;for(let d of I.tools){if(d.name==="get_copilot_space")continue;if(!(s?.includes("*")||s?.includes(d.name))){this.logger.log(`Tool ${d.name} is not in the allowed list for client: ${e}`);continue}let b=Z0e(e,d.name),p=`${e}-${d.name}`,A;typeof o=="string"?A=vOe(o):A=vOe(o?.[d.name]??"hidden_characters");let Z=`${e}/${d.name}`,W={name:p,namespacedName:Z,title:d.title||d.annotations?.title||Z||d.name,description:d.description??p,input_schema:d.inputSchema,readOnly:d.annotations?.readOnlyHint,safeForTelemetry:{name:!!(n?.mcpServers[e].isDefaultServer||b),inputsNames:!!n?.mcpServers[e].isDefaultServer},filterMode:A};a.push(W),this.logger.log(`Tool ${d.name} added to tools list for client: ${e}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${e}`);let c=l.getServerVersion();await this.logServerSuccessWithTools(e,a,c,r)}catch(I){this.logger.error(`Failed to get tools from client: ${e} ${I}`)}return a}async logServerSuccessWithTools(e,l,n,r){if(!jue.includes(e)&&r)try{let a=l.map(c=>`- ${c.namespacedName}`).join(`
|
|
2028
2028
|
`),I=l.reduce((c,d)=>(c[d.name]=d.title||d.namespacedName,c),{}),o=`MCP server started successfully${n?` (version ${n.version})`:""} with ${l.length} ${l.length===1?"tool":"tools"} - for the full output, see the verbose logs
|
|
2029
2029
|
|
|
2030
2030
|
${a}`;await r.createOrUpdateMCPStartupToolCall({serverName:e,content:o,toolNamesToDisplayNames:I}),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(a){this.logger.error(`Failed to update session log for ${e}: ${a}`)}}};var XL=class t{static resolveString(e,l){return!l||e.length>1e3?e:e.replace(/\$\{([A-Z0-9_]+)(?::-([^}]*))?\}|\$([A-Z0-9_]+)(?![A-Z0-9_])/g,(n,r,a,I)=>{let o=l[r||I];return o!==void 0?o:a!==void 0?a:n})}static resolveArray(e,l){return e?l?e.map(n=>t.resolveString(n,l)):e:[]}static resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[r,a]of Object.entries(e)){let I=t.resolveArray([a],l);n[r]=I[0]}return n}static resolveLocalServerConfig(e,l){let n=t.resolveString(e.command,l),r=t.resolveArray(e.args,l),a;return e.cwd&&(a=t.resolveString(e.cwd,l)),{...e,command:n,args:r,cwd:a}}static resolveRemoteServerConfig(e,l=process.env){let n=t.resolveString(e.url,l),r=t.resolveHeaders(e.headers,l);return{...e,url:n,headers:r}}};var Lqe={mcpServers:{}},Nwe=class{constructor(e,l,n){this.logger=e;this.registry=l;this.remoteEnabled=n?.remoteEnabled??!1,this.mcp3pEnabled=n?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=n?.blackbirdMetisIndexEnabled??!1,this.sessionClient=n?.sessionClient,this.mcpEnvConfig=void 0,this.envValueMode=n?.envValueMode??this.registry.envValueMode}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;envValueMode;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let l=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(l,e),this.configureGitHubMcp(l,e),this.configurePlaywrightMcp(l)),l}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),Lqe;if(this.logger.log("User-provided MCPs are enabled, checking for environment variable"),!this.mcpEnvConfig)return this.logger.log("No user-provided MCP servers found"),Lqe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let l in e.mcpServers){if(l.indexOf("/")===-1)continue;let n=l.replace(/\//g,"__");e.mcpServers[n]=e.mcpServers[l],delete e.mcpServers[l]}for(let l in e.mcpServers)e.mcpServers[l].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),Lqe}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){let n="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),n=n+",copilot_spaces");let r={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":n,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(r["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(r["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let a={type:"http",url:this.getCapiMcpUrl(),headers:r,tools:["*"],isDefaultServer:!0};this.setDefaultGitHubFilterMapping(a);let I=e.mcpServers[vL]??void 0;if(I&&HL(I)){let s=structuredClone(I);this.logger.log("GitHub MCP server configuration already provided by user, skipping default remote configuration"),I.headers===void 0&&(I.headers={}),s.headers={...r,...I.headers},s.isDefaultServer=!0,this.setDefaultGitHubFilterMapping(s),e.mcpServers[vL]=s}else this.logger.log("Using default remote GitHub MCP server configuration"),e.mcpServers[vL]=a}configureLocalGitHubMcp(e){if(e.mcpServers[vL]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[vL]??{};yq(l)&&!l.command&&(e.mcpServers[vL]={...l,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let l={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[vL]=l}}setDefaultGitHubFilterMapping(e){e.filterMapping??={get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}}configurePlaywrightMcp(e){if(!e.mcpServers[Xqe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(n=>n.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let l={command:"npx",args:[...xUe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[Xqe]=l}}configureBlackbirdMcp(e,l){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,l):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,l){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${l.blackbird?.mode}`);let n=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${n}`);let r=[];l.blackbird?.mode==="tool"&&(r=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let a={command:`${n}/blackbird/mcp`,args:["serve","--index",`${n}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:r,isDefaultServer:!0};e.mcpServers[Pue]=a}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:l,isDefaultServer:!0};e.mcpServers[Pue]=n}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:l,isDefaultServer:!0};e.mcpServers[Pue]=r}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return yq(e)||Kue(e)||que(e)||$ue(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,l){return this.remoteEnabled&&!this.isValidServerType(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!yq(l)&&!$ue(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?yq(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Kue(l)||que(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):$ue(l)&&!this.isValidInMemoryServerConfig(l)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,l){try{let n=XL.resolveHeaders(l.headers,process.env),r={...l,headers:n};await this.registry.startHttpMcpClient(e,r),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processSseServer(e,l){try{let n=XL.resolveRemoteServerConfig(l,process.env);await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processInMemoryServer(e,l){try{await this.registry.startInMemoryMcpClient(e,l,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(n){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${n}`),n}}async processLocalServer(e,l){let n={...l};if(l.command==="python")try{n=await this.convertPythonToPipx(n)}catch(I){this.logger.error(`Failed to handle Python module for ${e}: ${I}`)}let r=this.buildEnvironment(n),a=XL.resolveLocalServerConfig(n,r);process.env.GITHUB_WORKSPACE&&a.cwd===void 0&&(a.cwd=process.env.GITHUB_WORKSPACE),this.logger.log(`Starting MCP client for ${e} with
|
|
2031
2031
|
command: ${a.command}
|
|
2032
2032
|
args: ${a.args}
|
|
2033
|
-
cwd: ${a.cwd}`);try{let I={...a,env:r};await this.registry.startLocalMcpClient(e,I),this.logger.log(`Started MCP client for ${e}`)}catch(I){throw this.logger.error(`Failed to start MCP client for ${e}: ${I}`),I}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let l=e.args;if(l.length>1e3)throw new Error("Too many arguments provided to Python command");let n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let r=l[n+1];this.logger.log(`Converting Python module: ${r} to pipx command`);let a=["run",r];for(let I=n+2;I<l.length;I++)a.push(l[I]);for(let I=0;I<n;I++)a.push(l[I]);return{...e,command:"pipx",args:a}}buildEnvironment(e){let l={};if(e.env)if(this.envValueMode==="direct")for(let[n,r]of Object.entries(e.env))l[n]=XL.resolveString(r,process.env);else for(let[n,r]of Object.entries(e.env)){let a=r.trim(),I=a;if(a.includes("$")&&(I=XL.resolveString(a,process.env)),I!==a){l[n]=I;continue}process.env[a]!==void 0&&(l[n]=process.env[a])}return l}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,r])=>this.processServer(n,r));await Promise.all(l)}async processServer(e,l){if(e=e.replace(/\//g,"__"),!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}jue.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{yq(l)?await this.processLocalServer(e,l):Kue(l)&&this.remoteEnabled?await this.processHttpServer(e,l):que(l)&&this.remoteEnabled?await this.processSseServer(e,l):$ue(l)&&await this.processInMemoryServer(e,l)}catch(n){jue.includes(e)||await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.createOrUpdateMCPStartupToolCall({serverName:e,content:`<error>MCP server failed to start: ${l.message} - for the full output, see the verbose logs</error>`})}catch(n){this.logger.error(`Failed to log failure for MCP Server '${e}': '${n}'`)}}};var kL=class{constructor(e,l,n,r="indirect"){this.logger=e;let a;if(typeof l=="string"){if(a=JSON.parse(l),typeof a!="object")throw new Error("Invalid MCP configuration: must be an object");if(a===null||!("mcpServers"in a)||typeof a.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=a}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new Zwe(this.logger,void 0,void 0,r),this.processor=new Nwe(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let l={};for(let[n,r]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=r;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.transport=null}async getTools(e,l,n){await this.startServers(),this.transport
|
|
2033
|
+
cwd: ${a.cwd}`);try{let I={...a,env:r};await this.registry.startLocalMcpClient(e,I),this.logger.log(`Started MCP client for ${e}`)}catch(I){throw this.logger.error(`Failed to start MCP client for ${e}: ${I}`),I}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let l=e.args;if(l.length>1e3)throw new Error("Too many arguments provided to Python command");let n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let r=l[n+1];this.logger.log(`Converting Python module: ${r} to pipx command`);let a=["run",r];for(let I=n+2;I<l.length;I++)a.push(l[I]);for(let I=0;I<n;I++)a.push(l[I]);return{...e,command:"pipx",args:a}}buildEnvironment(e){let l={};if(e.env)if(this.envValueMode==="direct")for(let[n,r]of Object.entries(e.env))l[n]=XL.resolveString(r,process.env);else for(let[n,r]of Object.entries(e.env)){let a=r.trim(),I=a;if(a.includes("$")&&(I=XL.resolveString(a,process.env)),I!==a){l[n]=I;continue}process.env[a]!==void 0&&(l[n]=process.env[a])}return l}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,r])=>this.processServer(n,r));await Promise.all(l)}async processServer(e,l){if(e=e.replace(/\//g,"__"),!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}jue.includes(e)||await this.sessionClient?.createOrUpdateMCPStartupToolCall({serverName:e});try{yq(l)?await this.processLocalServer(e,l):Kue(l)&&this.remoteEnabled?await this.processHttpServer(e,l):que(l)&&this.remoteEnabled?await this.processSseServer(e,l):$ue(l)&&await this.processInMemoryServer(e,l)}catch(n){jue.includes(e)||await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.createOrUpdateMCPStartupToolCall({serverName:e,content:`<error>MCP server failed to start: ${l.message} - for the full output, see the verbose logs</error>`})}catch(n){this.logger.error(`Failed to log failure for MCP Server '${e}': '${n}'`)}}};var kL=class{constructor(e,l,n,r="indirect"){this.logger=e;let a;if(typeof l=="string"){if(a=JSON.parse(l),typeof a!="object")throw new Error("Invalid MCP configuration: must be an object");if(a===null||!("mcpServers"in a)||typeof a.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=a}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new Zwe(this.logger,void 0,void 0,r),this.registry.setToolsChangedCallback(I=>{this.handleToolsChanged(I)}),this.processor=new Nwe(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;transport=null;disabledServers;async handleToolsChanged(e){if(this.logger.log(`Handling tools changed notification for ${e}`),this.transport){let l=this.registry.clients[e];l?await this.transport.refreshProvider({mcpClient:l,clientName:e,tools:this.config.mcpServers[e]?.tools||["*"],filterMapping:this.config.mcpServers[e]?.filterMapping||"hidden_characters"}):this.logger.log(`No client found for ${e}, cannot refresh`)}}async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let l={};for(let[n,r]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=r;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.transport=null}async getTools(e,l,n){await this.startServers(),this.transport||(this.transport=new ooe(e,l,!0));let r=[];for(let a of Object.keys(this.registry.clients)){let I=await this.transport.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters",timeout:this.config.mcpServers[a]?.timeout},n);r.push(...I)}return r}getConfig(){return this.config}getClients(){return this.registry.clients}async startServer(e,l){await this.startServers(),this.config.mcpServers[e]=l,await this.processor.processServer(e,l),this.transport=null}async stopServer(e){let l=this.registry.transports[e];if(l)try{await l.close(),delete this.registry.transports[e]}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.transport=null}async restartServer(e,l){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,l)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.transport=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let l=this.getServerConfig(e);l?await this.startServer(e,l):await this.startBuiltInServer(e),this.transport=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};var MCn="/login/device/code",_Cn="/login/oauth/access_token",gzt="Ov23ctDVkRmgkPke0Mmm",JL="https://github.com",LL=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function iO(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function Zzt(t){let e=new URL(MCn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:gzt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new LL(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function Nzt(t,e){let l=new URL(_Cn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:gzt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new LL(n.status,`Failed to authorize: ${n.statusText}`);let r=await n.json();if(typeof r.access_token=="string")return r.access_token;if(r.error!=="authorization_pending"&&r.error!=="slow_down")throw new Error(r.error_description||`Unexpected error: ${r.error}`)}async function Eq(t,e){let l=new URL("/user",iO(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new LL(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function dN(t,e,l){let n=`
|
|
2034
2034
|
{
|
|
2035
2035
|
viewer {
|
|
2036
2036
|
login
|