@github/copilot 0.0.339-11 → 0.0.339-13

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/sdk/index.js CHANGED
@@ -1237,7 +1237,7 @@ ${uOe()}
1237
1237
 
1238
1238
  <reminder>
1239
1239
  The user may have mentioned images, if so these will have been attached to this message, in the order they were mentioned
1240
- </reminder>`),I.trim()},I6={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."},NOe=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${Fbe(t)}. Commit changes by using the **report_progress** tool.</reminder>`;G();var Mbe="/tmp/playwright-logs",c9I="0.0.40",Tbe=[`@playwright/mcp@${c9I}`,"--viewport-size","1280, 720","--output-dir",Mbe],XMl=[...Tbe,"--isolated"];var Dbe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},jbe=2e3;async function s9I(t,e,I,l){let n={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},c=`${Gue(l)}/${t}`;I.info(`Downloading image from ${c}`);try{let a=await fetch(c,{method:"GET",headers:n});if(I.info(`Response status: ${a.status} ${a.statusText}`),I.debug(`Download Response URL: ${a.url}`),!a.ok){I.info(`Failed to download image, status: ${a.status}, statusText: ${a.statusText}`);try{let h=await a.text();I.info(`Error response body: ${h}`)}catch(h){I.info(`Could not read error response body: ${h}`)}return{size:0}}let r=(await a.json()).url;if(!r)return I.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let o=await fetch(r,{method:"GET"});if(!o.ok)return I.error(`Failed to download image: ${o.status} ${o.statusText}`),{size:0};let d=await o.arrayBuffer(),i=d.byteLength;return I.info(`Downloaded content size: ${im(i)}`),{size:i,buffer:Buffer.from(d),mimeType:o.headers.get("content-type")||void 0}}catch(a){return I.error("Network error downloading image"),a instanceof Error&&(I.info(`Error message: ${a.message}`),I.info(`Error stack: ${a.stack}`)),{size:0}}}function Kbe(t,e,I,l){let n=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,c=/!\[.*?\]\((.*?)\)/g,a=[];return a.push(...YOe(t,e,n,I,l)),a.push(...YOe(t,e,c,I,l)),a}function YOe(t,e,I,l,n){let c=t.matchAll(I),a=[],s=/\/([a-f0-9-]+)$/;for(let r of c){let o=d9I(r[1],e),d=i9I(r[1],e,n);if(o||d){let i=r[1].match(s),h={url:r[1],guid:"",kind:d?"legacy_attachment":"attachment"};i&&i.length>1&&(h.guid=i[1]),a.push(h)}else if(l){let i={url:r[1],guid:"",kind:"committed_attachment"};a.push(i)}}return a}function r9I(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&_be(t)}function _be(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function G9I(t){try{let e=/Here are relevant code snippets from the repository that might help with this task:\s*(\[[\s\S]*?\])(?=\n|$)/,I=t.match(e);if(!I?.[1]||I[1].length<=1)return null;let l=I[1].trim();return JSON.parse(l)}catch{return null}}function o9I(t,e,I){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 l=t.url.split("/").slice(3,5).join("/"),n=t.ref.split("/")[2],c;if(e.startsWith("/"))c=e.slice(1);else{let s=t.path,r=y9.dirname(s);c=y9.resolve("/",r,e).slice(1)}return`${I}/${l}/blob/${n}/${c}`}function d9I(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function i9I(t,e,I){return e&&new RegExp(`^${e}/[\\w.-]+/[\\w.-]+/assets/\\d+/[^.]+$`).test(t)?(I.debug(`Legacy GitHub asset URL detected: ${t}`),!0):!1}async function $be(t){let{width:e,height:I}=oSe(t);if(e===void 0||I===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:I}}async function VOe(t,e,I,l,n,c){t.debug(`Checking if image is valid size and dimensions. Max size: ${I}, Max dimension: ${l}`);let{exceedsSizeLimit:a,exceedsDimensionLimit:s}=await F9(I,l,c);if(!s&&!a)return t.debug("Image is within size and dimension limits."),c;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${l}, attempting to resize`);let[r,o]=await h9I(t,c,l,I,n);if(!r){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,o==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:d}=await F9(I,l,r);if(d){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),r}if(a){t.debug(`Image size ${im(c.length)} is larger than the maximum size of ${im(I)}, attempting to reduce image quality`);let r=await p9I(t,c,l,I,n);if(!r){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."),r}}async function F9(t,e,I){let l=await $be(I),n=I.length;return!l.width||!l.height?{exceedsSizeLimit:n>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await m9I(t,I),exceedsDimensionLimit:await b9I(e,I)}}async function b9I(t,e){let I=await $be(e);return!I.width||!I.height?!1:I.width>t||I.height>t}async function m9I(t,e){return e.length>t}async function h9I(t,e,I,l,n){try{if(!yOe(t,n))return[void 0,"unsupported_mime_type"];let c=await $be(e);if(!c.width||!c.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let a=async(N,Y)=>{let y=ROe(e).resize(N,Y,{fit:"inside",withoutEnlargement:!0});return Pbe(t,await y.toBuffer(),void 0,n)},s=Math.min(I,c.width),r=Math.min(I,c.height),o=await a(s,r);if(o&&o.length<=l)return[o,void 0];let d=Math.max(s,r),i=1,h=d-1,p,Z=0,u=10;for(;i<=h&&Z<u;){let N=Math.floor((i+h)/2),Y=await a(N,N);if(!Y)break;let{exceedsSizeLimit:y,exceedsDimensionLimit:Q}=await F9(l,I,Y);!y&&!Q?(p=Y,i=N+1):h=N-1,Z++}return[p,void 0]}catch(c){return t.error(`Failed to resize image for upload: ${c instanceof Error?c.message:String(c)}`),[void 0,"unknown"]}}async function p9I(t,e,I,l,n){try{let c=n==="image/png"?80:100,a=n==="image/png"?Math.floor(c*.4):20,s=await Pbe(t,e,a,n);if(!s||s.length>l)return;let r=a,o=c,d,i=0,h=10,p=r,Z=o-1;for(;p<=Z&&i<h;){let u=Math.floor((p+Z)/2),N=await Pbe(t,e,u,n);if(!N)return d;let{exceedsSizeLimit:Y,exceedsDimensionLimit:y}=await F9(l,I,N);!Y&&!y?(d=N,p=u+1):Z=u-1,i++}return d}catch(c){t.error(`Failed to reduce image quality: ${c instanceof Error?c.message:String(c)}`);return}}async function Pbe(t,e,I,l){let n=ROe(e);switch(l){case"image/png":return I?n.png({quality:I}).toBuffer():n.png().toBuffer();case"image/jpeg":return I?n.jpeg({quality:I}).toBuffer():n.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${l}`);return}}var qbe=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function Z9I(t,e,I,l){if(e<=0)return[];let n=[];for(let c of t){if(c.role!=="user"||n.length>=e)continue;let a=typeof c.content=="string"?c.content:JSON.stringify(c.content),s=G9I(a);if(s)for(let r in s){if(n.length>=e)break;let o=s[r].contents,d=Kbe(o,I,!0,l);for(let i of d){if(n.length>=e)break;let h=i.url,p="",Z=!1;if(i.kind==="attachment"||i.kind==="legacy_attachment"?n.push(i):r9I(h)?(Z=!0,p=o9I(s[r],h,I),n.push({url:p,guid:i.guid,kind:"committed_attachment"})):_be(h)&&h.startsWith(I)&&(Z=!0,n.push({...i,kind:"committed_attachment"})),Z){let u=n[n.length-1],N=new RegExp(`^${I}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),Y=u.url.match(N);if(l.info(`Blob match for ${u.url}: ${JSON.stringify(Y)}`),Y&&Y.length===5){let[,y,Q,A,w]=Y;u.owner=y,u.repo=Q,u.branch=A,u.path=w,l.info(`Repository metadata extracted: owner=${y}, repo=${Q}, branch=${A}, path=${w}`)}else l.info(`Failed to extract repository metadata from URL: ${u.url}`)}}}}return n}function u9I(t,e){let I=e.flatMap(n=>$R(n)?n.content.flatMap(c=>c.type==="image_url"?c.image_url.url:[]):[]),l=new Set(I);return t.filter(n=>!l.has(n.url))}var t6=class{async resolveRepositoryImages(e,I,l,n,c,a){if(I<=0)return[];let s=Z9I(e,I,l,n);this.logger.debug(`Found ${s.length} repository image URLs to process`);let r=u9I(s,e),o=await this.processImageReferences(r,c,a);return this.logger.debug(`Processed ${o.addedImages.length} repository image URLs`),o.addedImages}async*preRequest(e){let I=e.modelInfo;if(!I.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!I.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 i of this.messagesToInsertOnNextPreRequest)e.messages.push(i),yield{kind:"message",message:i,turn:e.turn};this.messagesToInsertOnNextPreRequest.splice(0);let l=[],n=I.capabilities.limits.vision?.max_prompt_images??1,c=I.capabilities.limits.vision?.max_prompt_image_size??3145728,a=0,s=[],r=new qbe,o=new Map;for(let i of e.messages)if(i.role=="user")if(typeof i.content=="string"){let h=Kbe(i.content,this.gitHubServerUrl,!1,this.logger).filter(Z=>!this.processedImageUrls.has(Z.url)),p=await this.processImageReferences(h,c,r);s.push(...p.addedImages)}else{let h=[];for(let[p,Z]of i.content.entries()){if(Z.type==="text"){let u=Kbe(Z.text,this.gitHubServerUrl,!1,this.logger).filter(Y=>!this.processedImageUrls.has(Y.url)),N=await this.processImageReferences(u,c,r);s.push(...N.addedImages)}else if(Z.type==="image_url"){if(Z.image_url.url.startsWith("data:")){let[u,N]=await this.extractAndUploadImageData(Z,c,r);if(u===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(u),p>=1&&h.length>0){let Y=h.at(-1);Y&&Y.type==="text"&&Y.text&&Y.text.includes("screenshot")&&o.set(u,ZOe(u))}h.pop();continue}a++}h.push(Z)}i.content=h}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${n}`);a<n&&s.length>0;){let i=s.shift();if(!i){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(i)){this.logger.debug(`Skipping already processed image url: ${i}`);continue}this.processedImageUrls.add(i);let h=`Here is the image url: ${i}`;o.has(i)&&(h=o.get(i)||h),this.logger.debug(`Adding image url: ${i}`),l.push({role:"user",content:[{type:"text",text:h},{type:"image_url",image_url:{url:i}}]}),a++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),a<n)){let i=await this.resolveRepositoryImages(e.messages,n-a,this.settings.github?.serverUrl||"",this.logger,c,r);this.logger.debug(`Resolved ${i.length} repository image URLs`);for(let h of i){if(a>=n)break;if(this.processedImageUrls.has(h)){this.logger.debug(`Skipping already processed repository image url: ${h}`);continue}l.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:h}}]}),this.processedImageUrls.add(h),a++}}let d={imagesExtractedCount:r.extractedImagesSize.length,base64ImagesCount:r.base64ImagesSize.length,imagesRemovedDueToSize:r.imagesRemovedDueToSize,imagesRemovedDueToDimensions:r.imagesRemovedDueToDimensions,imagesResized:r.imagesResized,imagesResolvedFromGitHubMCPCount:r.imagesResolvedFromGitHubMCPSize.length};for(let i=0;i<r.base64ImagesSize.length;i++)d[`base64ImageSize_${i}`]=r.base64ImagesSize[i];for(let i=0;i<r.resizedBase64ImagesSize.length;i++)d[`resizedBase64ImageSize_${i}`]=r.resizedBase64ImagesSize[i];for(let i=0;i<r.extractedImagesSize.length;i++)d[`extractedImageSize_${i}`]=r.extractedImagesSize[i];for(let i=0;i<r.imagesResolvedFromGitHubMCPSize.length;i++)d[`imagesResolvedFromGitHubMCPSize_${i}`]=r.imagesResolvedFromGitHubMCPSize[i];l.length>0&&this.logger.debug(`Using ${l.length} image messages`);for(let i of l)yield{kind:"message",message:i,turn:e.turn},e.messages.push(i);d.allImagesSendToLlm=e.messages.filter($R).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:d},e.messages.some(i=>$R(i))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,I,l){let n=G1(this.settings);if(!n)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let c=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!c||c.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let a=c[1];if(!yOe(this.logger,a))return[""];let s=c[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let r=Buffer.from(s,"base64");if(l.base64ImagesSize.push(r.length),r=await VOe(this.logger,l,I,jbe,a,r),l.resizedBase64ImagesSize.push(r?.length??-1),!r)return["",new Dbe(`Image size exceeds maximum size of ${im(I)}`)];s=r.toString("base64");try{let o=await this.uploadBase64ImageData(s,a,n);return o?(this.logger.debug(`Uploaded image url: ${o}`),e.image_url.url=o,[o]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(o){let d=o instanceof Error?o.message:String(o);return this.logger.debug(`Error during image upload: ${d}`),[""]}}async uploadBase64ImageData(e,I,l){try{let n=rue(this.settings),c=I.split("/").at(1),a=`image-${Date.now()}.${c}`;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 r=this.settings.github?.repo?.id;if(!r)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let o=`${n}?name=${encodeURIComponent(a)}&content_type=${encodeURIComponent(I)}&repository_id=${r}`;this.logger.debug(`Uploading image data (${im(s.length)}) to ${n} with name ${encodeURIComponent(a)} and content type ${encodeURIComponent(I)}`);let d={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+l},i=await fetch(o,{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(!i.ok){let p=await i.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${i.status} ${i.statusText} - ${p}`),null}let h=await i.json();return this.logger.debug(`Upload result: ${JSON.stringify(h,null,2)}`),h.url||null}catch(n){return this.logger.error(`Error handling image upload: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&this.logger.debug(`Stack trace: ${n.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 I=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof I}`),this.logger.debug(`GitHub tool call result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`),typeof I=="object"&&I!==null&&"binaryResultForLlm"in I&&Array.isArray(I.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${I.binaryResultForLlm.length} items`);try{for(let l of I.binaryResultForLlm)if(l.data&&l.mimeType){let n=Buffer.from(l.data,"base64"),c=l.mimeType;return{buffer:n,mimeType:c}}}catch(l){this.logger.error(`Failed to parse GitHub tool response: ${l}`),this.logger.debug(`binaryResultForLlm length: ${I.binaryResultForLlm?.length||0}`)}}else typeof I=="string"?this.logger.debug(`GitHub tool returned string result: ${I}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`)}catch(I){this.logger.error(`Error calling GitHub MCP tool: ${I}`)}}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,I,l){let n=[],c=await Promise.all(e);for(let{imgRef:a,attachment:s}of c)if(this.logger.debug(`Processing attachment for ${a.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(I.extractedImagesSize.push(s.buffer.length),vl(this.settings,"copilot_swe_agent_resize_image_references")){if(!await VOe(this.logger,I,l,jbe,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}n.push(a.url)}else{let r=await F9(l,jbe,s.buffer);if(this.logger.debug(`Image size check for ${a.url}: size=${s.buffer.length}, maxSize=${l}, exceedsSize=${r.exceedsSizeLimit}, exceedsDimensions=${r.exceedsDimensionLimit}`),r.exceedsSizeLimit?(I.imagesRemovedDueToSize++,this.logger.debug(`Image ${a.url} removed due to size (${s.buffer.length} > ${l})`)):r.exceedsDimensionLimit&&(I.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${a.url} removed due to dimensions`)),r.exceedsSizeLimit||r.exceedsDimensionLimit){this.processedImageUrls.add(a.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${im(l)}.`);continue}n.push(a.url),this.logger.debug(`Image ${a.url} passed size checks and added to results`)}else this.processedImageUrls.add(a.url),this.logger.debug(`Skipping image ${a.url} - could not fetch image data`);return n}async processImageReferences(e,I,l){let n=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${n}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let c=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 r=await this.getRepositoryImageViaTools(s);return r?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${r.buffer.length} bytes`),l.imagesResolvedFromGitHubMCPSize.push(r.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:r?.buffer?.length||0,mimeType:r?.mimeType||"",buffer:r?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await s9I(s.guid,G1(this.settings),this.logger,this.settings)}}),a=await this.getImgRefsSmallerThanMaxSize(c,l,I);return this.logger.debug(`Processed image references, found ${a.length} attachments smaller than max size of ${im(I)}`),{addedImages:a}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,I,l){this.logger=e,this.settings=I,this.gitHubServerUrl=I.github?.serverUrl,this.githubGetFileContentsTool=l,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 I=e.modelInfo,l=e.toolCall.function.name,n=e.toolResult;if(I?.capabilities?.supports?.vision){let c=Array.from(W9I(n,l));if(c.length===0){let a=await V9I(e.toolCall,this.logger);a&&c.push(a)}this.insertImageUrlMessages(c)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let I of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:I.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:I.url}}]})}};function*W9I(t,e){for(let I of t.binaryResultForLlm??[])I.type==="image"&&(yield{url:`data:${I.mimeType};base64,${I.data}`,isScreenshot:e.toLowerCase().includes("screenshot")})}var N9I="playwright-browser_take_screenshot";function Y9I(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function V9I(t,e){if(t.function.name!==N9I)return;e.debug("Adding images using Playwright params fallback strategy");let I=JSON.parse(t.function.arguments);if(Y9I(I)){let l=y9.isAbsolute(I.filename)?I.filename:y9.join(Mbe,I.filename);e.debug(`Image from Playwright params: ${I.filename}. Updated to ${l}.`);let n=await y9I(l,e);if(n){let c=n.buffer.toString("base64");return{url:`data:${n.mimeType};base64,${c}`,isScreenshot:!0}}}}function R9I(t){switch(y9.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function yOe(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 y9I(t,e){try{if(!_be(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let I=R9I(t);return I?{buffer:await a9I.readFile(t),mimeType:I}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(I){return e.error(`Failed to read image from disk: ${I instanceof Error?I.message:String(I)}`),null}}G();var YE=class{latestUserPromptMessage;logger;constructor(e,I){this.latestUserPromptMessage=e,this.logger=I}toJSON(){return"BasicTruncator"}async*preRequest(e){let I=this.latestUserPromptMessage?mGe(this.latestUserPromptMessage,e.messages):-1,l=[()=>gOe(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit),I===-1?void 0:()=>g9I(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit,I)].filter(a=>a!==void 0),n=0,c;for(;(!c||c.postTruncationTokensInMessages>e.tokenLimit)&&n<l.length;){let a=l[n]();c=F9I(c,a),n++}return c=c??Q9I(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit),c.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(c)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:c},c}},l6=class{truncateOnNextRequest=!1;userMessageToTruncateUpTo;logger;constructor(e,I){this.userMessageToTruncateUpTo=e,this.logger=I,this.logger.debug(`AnthropicTokenLimitErrorTruncator will truncate up to message: ${JSON.stringify(e)}`)}async*preRequest(e){if(this.truncateOnNextRequest){this.truncateOnNextRequest=!1;let I=mGe(this.userMessageToTruncateUpTo,e.messages);if(I===-1){this.logger.debug(`Failed to find user message to truncate up to: ${JSON.stringify(this.userMessageToTruncateUpTo)}`),this.logger.debug(`Current messages: ${JSON.stringify(e.messages)}`);return}let l=gOe(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit,I);l.tokensRemovedDuringTruncation>0&&this.logger.debug(`AnthropicTokenLimitErrorTruncator truncated: ${JSON.stringify(l)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"AnthropicTokenLimitErrorTruncator",truncateResult:l}}}async preErrorThrow(e){}async onRequestError(e){if(e){if(typeof e=="object"&&"code"in e&&e.code==="model_max_prompt_tokens_exceeded"){this.truncateOnNextRequest=!0;return}let I=[JSON.stringify(e)];e instanceof Error&&(I.push(e.message),e.cause instanceof Error?I.push(e.cause.message):e.cause&&I.push(JSON.stringify(e.cause)));let l="Input length and `max_tokens` exceed context limit";this.logger.debug(`Looking for error amongst: ${I.join(", ")}`),I.some(n=>n.includes(l))&&(this.truncateOnNextRequest=!0)}}toJSON(){return"AnthropicTokenLimitErrorTruncator"}};function F9I(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 FOe=.95;function gOe(t,e,I,l,n){let c=t.length;if(c===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:c,postTruncationTokensInMessages:0,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(p=>VF(p,I)),s=ui(JSON.stringify(e),I),r=l*FOe,o=a.reduce((p,Z)=>p+Z,0)+s;if(o<=r)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,i=0,h=Math.min(n??t.length,t.length);for(let p=0;p<h;p++){let Z=t[p];if(Z.role!=="system"&&Z.role!=="tool"&&Z.role!=="user"){if(Z.role==="assistant"){let u=Z.tool_calls||[],N=u.filter(Io).filter(A=>A.function.name===mC),Y=u.filter(Io).filter(A=>A.function.name!==mC),y=N.length===0,Q=new Set(Y.map(A=>A.id));if(Y.length>0&&(Z.tool_calls=N,a[p]=VF(Z,I)),y&&(d.add(p),i+=a[p]),Q.size>0)for(let A=p+1;A<t.length;A++){let w=t[A];if(w.role==="tool"&&Q.has(w.tool_call_id)&&(d.add(A),i+=a[A],Q.delete(w.tool_call_id),Q.size===0))break}}if(o-i<r)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function g9I(t,e,I,l,n){let c=t.length;if(c===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:c,postTruncationTokensInMessages:0,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(p=>VF(p,I)),s=ui(JSON.stringify(e),I),r=l*FOe,o=a.reduce((p,Z)=>p+Z,0)+s;if(o<=r)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,i=0,h=Math.min(n??t.length,t.length);for(let p=0;p<h;p++){let Z=t[p];if(Z.role!=="system"&&Z.role!=="tool"){if(Z.role==="user")d.add(p),i+=a[p];else if(Z.role==="assistant"){let u=Z.tool_calls||[],N=new Set(u.map(Y=>Y.id));if(d.add(p),i+=a[p],N.size>0)for(let Y=p+1;Y<t.length;Y++){let y=t[Y];if(y.role==="tool"&&N.has(y.tool_call_id)&&(d.add(Y),i+=a[Y],N.delete(y.tool_call_id),N.size===0))break}}if(o-i<r)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function Q9I(t,e,I,l){let n=t.length;if(n===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:n,postTruncationTokensInMessages:0,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let c=t.map(r=>VF(r,I)),a=ui(JSON.stringify(e),I),s=c.reduce((r,o)=>r+o,0)+a;return{tokenLimit:l,preTruncationTokensInMessages:s,preTruncationMessagesLength:n,postTruncationTokensInMessages:s,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}G();var ai=class extends Gp{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,I){}endGroup(e){}};G();G();var QOe={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"}]},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 n6(t,e,I){let l=(I||QOe)[t.toLowerCase()],n=new Set;for(;typeof l=="string";){if(n.has(l))return!1;n.add(l),l=QOe[l]}if(!l)return!1;let c=e.toLowerCase();return l.tools.some(a=>a.toolName===c)}var A9I="image";var w9I="resource",X9I=60*1e3*2,H9I={timeout:X9I};var eme=class{constructor(e,I,l){this.settings=e;this.logger=I;this.permissions=l}async invokeTool(e,I,l="hidden_characters"){let n=await this.doInvokeTool(e,I);return this.invokeToolResponseToToolResult(n,l)}invokeToolResponseToToolResult(e,I){let l=e.content||[],n="",c=[];for(let o of l)if(o.type==="text")n+=o.text||"";else if(o.type==="resource"){let d=o.resource;d&&d.blob?c.push({type:w9I,data:d.blob,mimeType:d.mimeType||"application/octet-stream"}):d&&d.text&&(n+=d.text)}else o.type==="image"&&c.push({type:A9I,data:o.data,mimeType:o.mimeType});let a=n;if(n==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),a=n;else try{let o=JSON.parse(n),d=lbe(o,I);a=JSON.stringify(d)}catch(o){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${o}`),a=Ibe(n,I)}this.logger.debug(`Tool invocation result: ${a}`);let s={},r=a?Pn(a,"output"):"";return e.isToolError?{textResultForLlm:a,resultType:"failure",error:a,sessionLog:r,toolTelemetry:s}:{textResultForLlm:a,binaryResultForLlm:c,resultType:"success",sessionLog:r,toolTelemetry:s}}async loadTools(e){let I=await this.loadToolsFromProvider(e),l={};for(let[n,c]of Object.entries(I)){let a=c.filterMode||"hidden_characters";l[n]={name:c.name,title:c.title||c.name,description:c.description,input_schema:c.input_schema,callback:async s=>{let r=I[n].serverName,o=I[n].name,d=I[n].title;if(!this.permissions.requestRequired)return this.invokeTool(n,s,a);let i=await this.permissions.request({kind:"mcp",serverName:r,toolName:o,toolTitle:d,args:s,readOnly:!!c.readOnly});switch(i.kind){case"approved":return this.invokeTool(n,s,a);case"denied-by-rules":return mO(i.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return hO;case"denied-interactively-by-user":return bO;default:FV(i,`Unhandled permission result kind: ${i}`)}},safeForTelemetry:c.safeForTelemetry}}return Object.values(l)}};var g9=class t extends eme{toolIdToClientInfo=new Map;constructor(e,I,l={requestRequired:!1}){super(e,I,l)}async doInvokeTool(e,I){let l=this.toolIdToClientInfo.get(e);if(!l)throw new Error(`No MCP client found for tool ID: ${e}`);let n=l.mcpClient,c=t.getToolNameFromIdAndClientName(e,l.clientName),a=await n.callTool({name:c,arguments:I},void 0,{...H9I,onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(a.content))throw new Error("Expected array of results");return{content:a.content,isToolError:a.error!==void 0&&a.error!==null||a.isError===!0}}async loadToolsFromProvider(e){let I={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let l of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(l.name)){this.logger.debug(`Skipping tool ${l.name} for client ${e.clientName}`);continue}let n=t.getToolIdFromClientAndToolName(e.clientName,l.name);this.toolIdToClientInfo.set(n,e);let c;e.safeForTelemetry===!0?c={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?c=e.safeForTelemetry:c={name:n6(e.clientName,l.name),inputsNames:!1},this.logger.debug(`Adding tool: ${n}`);let a;e.filterMapping===void 0?a="hidden_characters":typeof e.filterMapping=="object"?a=e.filterMapping[l.name]||"hidden_characters":a=e.filterMapping,I[n]={serverName:e.clientName,name:n,title:l.title||l.annotations?.title||l.name,description:l.description||"",input_schema:l.inputSchema,readOnly:l.annotations?.readOnlyHint,safeForTelemetry:c,filterMode:a}}return I}static getToolIdFromClientAndToolName(e,I){return`${e}-${I}`}static getToolNameFromIdAndClientName(e,I){return e.substring(I.length+1)}};G();var c6=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,I,l,n,c,a){this.settings=e,this.logger=I,this.gitHandler=l,this.location=n,this.commitPriorToCompletionWithTools=c,this.jitInstructions=a||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let I,l=async()=>{if(I===void 0)try{I=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(a){this.logger.error(`Failed to get changed paths, err: ${a}`),I=1}return I},n;for(let[a,s]of Object.entries(this.jitInstructions)){let r=VZe(this.settings,s.percentRemainingOfTimeout);r.isWithin&&(!s.whenNoPathsChanged||await l()===0)&&(!n||r.withinMs<n[0])&&(n=[r.withinMs,s.instruction])}let c=n?.[1];if(typeof c=="function"&&(c=c(this.location)),c&&!this.emittedJitInstructions.has(c)){this.logger.debug(`Adding JIT instructions to the history: ${c}`),this.emittedJitInstructions.add(c);let a={role:"user",content:c};e.messages.push(a),yield{kind:"message",message:a,turn:e.turn,source:"jit-instruction"}}}}},tme={remindWhereToDoWork:{instruction:NOe,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:I6.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:I6.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:I6.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};G();G();function lme(t){if(!t)return Vke;let[e,...I]=t?.split(":")??[t,void 0],l=I.join(":")||void 0;return{agent:e||void 0,model:l||void 0}}G();G();function a6(t){return t.kind==="message"&&t.message.role==="assistant"}function AOe(t){return t.kind==="message"&&t.message.role==="user"}function wOe(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function XOe(t){return t.kind==="message"&&t.message.role==="tool"}function E9I(t,e){return t.toolCalls.find(I=>I.toolCallId===e)}function v9I(t,e){let I=e.function.name;try{let l=JSON.parse(e.function.arguments||"{}"),c=t.find(a=>a.name===I)?.safeForTelemetry||{name:!1,inputsNames:!1};return{toolCallId:e.id,toolName:I,arguments:e.function.arguments,safeForTelemetryToolName:c===!0||c.name?I:F2(I),safeForTelemetryArguments:c===!0||c.inputsNames?Wke(l):""}}catch{return{toolCallId:e.id,toolName:I,arguments:e.function.arguments,safeForTelemetryToolName:F2(I),safeForTelemetryArguments:""}}}var s6=class{forAgent;turnDataCache;emittedTurns=new Set;callback;settings;toolsInUse;constructor(e,I,l,n){this.forAgent=e,this.turnDataCache=new Map,this.emittedTurns=new Set,this.callback=I,this.settings=l,this.toolsInUse=n}getTurnData(){return this.turnDataCache}async ingestEvent(e){let I,l;if("turn"in e&&typeof e.turn=="number"){if(I=e.turn+1,this.emittedTurns.has(I))return;this.turnDataCache.has(I)||this.turnDataCache.set(I,{featureFlagsAsString:Pq(this.settings),toolCalls:[],toolCallExecutions:[],turn:I}),l=this.turnDataCache.get(I)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(l,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(l={...l,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?l={...l,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?l={...l,endTimeMs:e.timestampMs,retriesUsed:(l.retriesUsed??0)+1}:e.kind==="turn_failed"?l={...l,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(l={...l,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?l={...l,truncateEvent:e}:e.kind==="image_processing"?l={...l,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?l={...l,largeImagesRemoved:(l.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(l.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(l={...l,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:Nke(e.requestMessages)},e.kind==="model_call_success"&&(l={...l,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):AOe(e)&&e.source==="jit-instruction"?l={...l,jitInstructionsAdded:(l?.jitInstructionsAdded??0)+1}:a6(e)&&e.message.tool_calls?l={...l,toolCalls:l.toolCalls.concat(e.message.tool_calls.map(n=>({...v9I(this.toolsInUse,n)})))}:XOe(e)&&(l={...l,toolCallExecutions:l.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(I,l),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(I),this.emittedTurns.add(I),this.turnDataCache.delete(I))}async emitTurnTelemetry(e){let I=this.turnDataCache.get(e);if(I){let l={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{model:I.model||"default",modelInfo:I.modelInfo||"{}",api_call_id:I.api_call_id,provider_call_id:I.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(I.toolCalls.map(n=>({toolCallId:n.toolCallId,toolName:n.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(I.toolCallExecutions),error:I.error,featureFlags:Pq(this.settings),conversationStructureSummary:I.conversationStructureSummary,truncationPerformedBy:I.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:I.endTimeMs!==void 0&&I.startTimeMs!==void 0?I.endTimeMs-I.startTimeMs:0,modelCallDurationMs:I.modelCallDurationMs,retriesUsed:I.retriesUsed??0,numToolCalls:I.toolCalls.length,numToolExecutions:I.toolCallExecutions.length,largeImagesRemoved:I.largeImagesRemoved,imagesRemoved:I.imagesRemoved,responsePromptTokens:I.responsePromptTokens,responseCompletionTokens:I.responseCompletionTokens,responseTotalTokens:I.responseTotalTokens,jitInstructionsAdded:I.jitInstructionsAdded,...I.truncateEvent?.truncateResult,...I.imageProcessingMetrics},restrictedProperties:{}}};await this.callback.progress(l)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,I){let l=I.toolCallId,n=E9I(e,l);if(n){let c=I.toolResult,a={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...c.toolTelemetry.properties,resultType:c.resultType,toolCallId:l,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id},restrictedProperties:{...c.toolTelemetry.restrictedProperties,arguments:n.arguments,result:c.textResultForLlm,toolName:n.toolName,error:c.error},metrics:{...c.toolTelemetry.metrics,durationMs:I.durationMs}}};await this.callback.progress(a)}}};G();G();var Q9=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var r6=class{constructor(e,I){this.runtimeContext=e;this.customAgentName=I;this.gitHandlers={silent:new Pr(new ai,this.runtimeContext.exec),logging:new Pr(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,I,l,n,c,a,s=new Q9,r){let o=async(p,Z,u)=>{let N={role:"user",content:p};return await this.runtimeContext.callback?.progress({kind:"message",message:N,turn:0}),await this.runCompletionWithTools(e,I,[...Z??[],N],a,c,{executeToolsInParallel:vl(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:u},r,s)},d=n,i=l??[],h;for(;d;){let p=await o(d,i,h);h=p.finalTurnCount,i=p.messages,d=await r?.onResult(p.postCompletionWithToolsCommitHash)}for(let p of a)if(p.shutdown){let Z=await p.shutdown();Z&&await this.runtimeContext.callback?.progress(Z)}return{finalTurnCount:h||0,messages:i}}async runCompletionWithTools(e,I,l,n,c,a,s,r=new Q9){let o=this.runtimeContext.callback?new s6("sweagent-capi",this.runtimeContext.callback,this.runtimeContext.settings,n):void 0,d=this.gitHandlers.logging,i=await d.getCurrentCommitHash(e),h=l.filter(Q=>Q.role==="user").at(-1),p=this.createCompletionWithToolsProcessors(e,i,n,r,c,s,h),Z=this.runtimeContext.client.getCompletionWithTools(I,l,n,{...a,processors:p}),u=0,N=[...l],Y=[];for await(let Q of Z){if(vl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let A=await this.runtimeContext.callback?.progress(Q,{accepts_user_messages:r.canProcessUserMessages()});r.handleCallbackResponse(A)}else Q.kind==="response"||Q.kind==="message"?await this.runtimeContext.callback?.progress({...Q,customAgentName:this.customAgentName}):await this.runtimeContext.callback?.progress(Q);o&&await o.ingestEvent(Q),(Q.kind==="message"||Q.kind==="response")&&(Q.kind==="message"&&N.push(Q.message),Q.kind==="response"&&Y.push(Q.response),u=Math.max(u,Q.turn??0))}let y=await d.getCurrentCommitHash(e);return{finalTurnCount:u,messages:N,resultMessages:Y,preCompletionWithToolsCommitHash:i,postCompletionWithToolsCommitHash:y}}createCompletionWithToolsProcessors(e,I,l,n,c,a,s){let r=new t6(this.runtimeContext.logger,this.runtimeContext.settings,l.find(p=>p.name==="github-mcp-server-get_file_contents")),o=new c6(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,I,c),d=new YE(s,this.runtimeContext.logger),i=s?new l6(s,this.runtimeContext.logger):void 0,h=[o,r,d,i];return vl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&h.push(n),{preRequest:h.filter(p=>p!==void 0),preToolsExecution:[a].filter(p=>p!==void 0),postToolExecution:[r,a].filter(p=>p!==void 0),onRequestError:[r,i].filter(p=>p!==void 0)}}};G();async function nme(t,e,I,l,n){try{return(await l.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:I,numSnippets:10},"hidden_characters")).textResultForLlm}catch(c){return n.error(`Error during Blackbird search: ${c}`),""}}var EOe=t=>vl(t,"copilot_swe_agent_search")||YZe(t,"SearchAgentExperiment")==="enabled",HOe="search";function cme(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var C9I=(t,e,I)=>`
1240
+ </reminder>`),I.trim()},I6={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."},NOe=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${Fbe(t)}. Commit changes by using the **report_progress** tool.</reminder>`;G();var Mbe="/tmp/playwright-logs",c9I="0.0.40",Tbe=[`@playwright/mcp@${c9I}`,"--viewport-size","1280, 720","--output-dir",Mbe],XMl=[...Tbe,"--isolated"];var Dbe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},jbe=2e3;async function s9I(t,e,I,l){let n={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},c=`${Gue(l)}/${t}`;I.info(`Downloading image from ${c}`);try{let a=await fetch(c,{method:"GET",headers:n});if(I.info(`Response status: ${a.status} ${a.statusText}`),I.debug(`Download Response URL: ${a.url}`),!a.ok){I.info(`Failed to download image, status: ${a.status}, statusText: ${a.statusText}`);try{let h=await a.text();I.info(`Error response body: ${h}`)}catch(h){I.info(`Could not read error response body: ${h}`)}return{size:0}}let r=(await a.json()).url;if(!r)return I.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let o=await fetch(r,{method:"GET"});if(!o.ok)return I.error(`Failed to download image: ${o.status} ${o.statusText}`),{size:0};let d=await o.arrayBuffer(),i=d.byteLength;return I.info(`Downloaded content size: ${im(i)}`),{size:i,buffer:Buffer.from(d),mimeType:o.headers.get("content-type")||void 0}}catch(a){return I.error("Network error downloading image"),a instanceof Error&&(I.info(`Error message: ${a.message}`),I.info(`Error stack: ${a.stack}`)),{size:0}}}function Kbe(t,e,I,l){let n=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,c=/!\[.*?\]\((.*?)\)/g,a=[];return a.push(...YOe(t,e,n,I,l)),a.push(...YOe(t,e,c,I,l)),a}function YOe(t,e,I,l,n){let c=t.matchAll(I),a=[],s=/\/([a-f0-9-]+)$/;for(let r of c){let o=d9I(r[1],e),d=i9I(r[1],e,n);if(o||d){let i=r[1].match(s),h={url:r[1],guid:"",kind:d?"legacy_attachment":"attachment"};i&&i.length>1&&(h.guid=i[1]),a.push(h)}else if(l){let i={url:r[1],guid:"",kind:"committed_attachment"};a.push(i)}}return a}function r9I(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&_be(t)}function _be(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function G9I(t){try{let e=/Here are relevant code snippets from the repository that might help with this task:\s*(\[[\s\S]*?\])(?=\n|$)/,I=t.match(e);if(!I?.[1]||I[1].length<=1)return null;let l=I[1].trim();return JSON.parse(l)}catch{return null}}function o9I(t,e,I){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 l=t.url.split("/").slice(3,5).join("/"),n=t.ref.split("/")[2],c;if(e.startsWith("/"))c=e.slice(1);else{let s=t.path,r=y9.dirname(s);c=y9.resolve("/",r,e).slice(1)}return`${I}/${l}/blob/${n}/${c}`}function d9I(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function i9I(t,e,I){return e&&new RegExp(`^${e}/[\\w.-]+/[\\w.-]+/assets/\\d+/[^.]+$`).test(t)?(I.debug(`Legacy GitHub asset URL detected: ${t}`),!0):!1}async function $be(t){let{width:e,height:I}=oSe(t);if(e===void 0||I===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:I}}async function VOe(t,e,I,l,n,c){t.debug(`Checking if image is valid size and dimensions. Max size: ${I}, Max dimension: ${l}`);let{exceedsSizeLimit:a,exceedsDimensionLimit:s}=await F9(I,l,c);if(!s&&!a)return t.debug("Image is within size and dimension limits."),c;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${l}, attempting to resize`);let[r,o]=await h9I(t,c,l,I,n);if(!r){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,o==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:d}=await F9(I,l,r);if(d){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),r}if(a){t.debug(`Image size ${im(c.length)} is larger than the maximum size of ${im(I)}, attempting to reduce image quality`);let r=await p9I(t,c,l,I,n);if(!r){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."),r}}async function F9(t,e,I){let l=await $be(I),n=I.length;return!l.width||!l.height?{exceedsSizeLimit:n>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await m9I(t,I),exceedsDimensionLimit:await b9I(e,I)}}async function b9I(t,e){let I=await $be(e);return!I.width||!I.height?!1:I.width>t||I.height>t}async function m9I(t,e){return e.length>t}async function h9I(t,e,I,l,n){try{if(!yOe(t,n))return[void 0,"unsupported_mime_type"];let c=await $be(e);if(!c.width||!c.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let a=async(N,Y)=>{let y=ROe(e).resize(N,Y,{fit:"inside",withoutEnlargement:!0});return Pbe(t,await y.toBuffer(),void 0,n)},s=Math.min(I,c.width),r=Math.min(I,c.height),o=await a(s,r);if(o&&o.length<=l)return[o,void 0];let d=Math.max(s,r),i=1,h=d-1,p,Z=0,u=10;for(;i<=h&&Z<u;){let N=Math.floor((i+h)/2),Y=await a(N,N);if(!Y)break;let{exceedsSizeLimit:y,exceedsDimensionLimit:Q}=await F9(l,I,Y);!y&&!Q?(p=Y,i=N+1):h=N-1,Z++}return[p,void 0]}catch(c){return t.error(`Failed to resize image for upload: ${c instanceof Error?c.message:String(c)}`),[void 0,"unknown"]}}async function p9I(t,e,I,l,n){try{let c=n==="image/png"?80:100,a=n==="image/png"?Math.floor(c*.4):20,s=await Pbe(t,e,a,n);if(!s||s.length>l)return;let r=a,o=c,d,i=0,h=10,p=r,Z=o-1;for(;p<=Z&&i<h;){let u=Math.floor((p+Z)/2),N=await Pbe(t,e,u,n);if(!N)return d;let{exceedsSizeLimit:Y,exceedsDimensionLimit:y}=await F9(l,I,N);!Y&&!y?(d=N,p=u+1):Z=u-1,i++}return d}catch(c){t.error(`Failed to reduce image quality: ${c instanceof Error?c.message:String(c)}`);return}}async function Pbe(t,e,I,l){let n=ROe(e);switch(l){case"image/png":return I?n.png({quality:I}).toBuffer():n.png().toBuffer();case"image/jpeg":return I?n.jpeg({quality:I}).toBuffer():n.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${l}`);return}}var qbe=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function Z9I(t,e,I,l){if(e<=0)return[];let n=[];for(let c of t){if(c.role!=="user"||n.length>=e)continue;let a=typeof c.content=="string"?c.content:JSON.stringify(c.content),s=G9I(a);if(s)for(let r in s){if(n.length>=e)break;let o=s[r].contents,d=Kbe(o,I,!0,l);for(let i of d){if(n.length>=e)break;let h=i.url,p="",Z=!1;if(i.kind==="attachment"||i.kind==="legacy_attachment"?n.push(i):r9I(h)?(Z=!0,p=o9I(s[r],h,I),n.push({url:p,guid:i.guid,kind:"committed_attachment"})):_be(h)&&h.startsWith(I)&&(Z=!0,n.push({...i,kind:"committed_attachment"})),Z){let u=n[n.length-1],N=new RegExp(`^${I}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),Y=u.url.match(N);if(l.info(`Blob match for ${u.url}: ${JSON.stringify(Y)}`),Y&&Y.length===5){let[,y,Q,A,w]=Y;u.owner=y,u.repo=Q,u.branch=A,u.path=w,l.info(`Repository metadata extracted: owner=${y}, repo=${Q}, branch=${A}, path=${w}`)}else l.info(`Failed to extract repository metadata from URL: ${u.url}`)}}}}return n}function u9I(t,e){let I=e.flatMap(n=>$R(n)?n.content.flatMap(c=>c.type==="image_url"?c.image_url.url:[]):[]),l=new Set(I);return t.filter(n=>!l.has(n.url))}var t6=class{async resolveRepositoryImages(e,I,l,n,c,a){if(I<=0)return[];let s=Z9I(e,I,l,n);this.logger.debug(`Found ${s.length} repository image URLs to process`);let r=u9I(s,e),o=await this.processImageReferences(r,c,a);return this.logger.debug(`Processed ${o.addedImages.length} repository image URLs`),o.addedImages}async*preRequest(e){let I=e.modelInfo;if(!I.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!I.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 i of this.messagesToInsertOnNextPreRequest)e.messages.push(i),yield{kind:"message",message:i,turn:e.turn};this.messagesToInsertOnNextPreRequest.splice(0);let l=[],n=I.capabilities.limits.vision?.max_prompt_images??1,c=I.capabilities.limits.vision?.max_prompt_image_size??3145728,a=0,s=[],r=new qbe,o=new Map;for(let i of e.messages)if(i.role=="user")if(typeof i.content=="string"){let h=Kbe(i.content,this.gitHubServerUrl,!1,this.logger).filter(Z=>!this.processedImageUrls.has(Z.url)),p=await this.processImageReferences(h,c,r);s.push(...p.addedImages)}else{let h=[];for(let[p,Z]of i.content.entries()){if(Z.type==="text"){let u=Kbe(Z.text,this.gitHubServerUrl,!1,this.logger).filter(Y=>!this.processedImageUrls.has(Y.url)),N=await this.processImageReferences(u,c,r);s.push(...N.addedImages)}else if(Z.type==="image_url"){if(Z.image_url.url.startsWith("data:")){let[u,N]=await this.extractAndUploadImageData(Z,c,r);if(u===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(u),p>=1&&h.length>0){let Y=h.at(-1);Y&&Y.type==="text"&&Y.text&&Y.text.includes("screenshot")&&o.set(u,ZOe(u))}h.pop();continue}a++}h.push(Z)}i.content=h}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${n}`);a<n&&s.length>0;){let i=s.shift();if(!i){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(i)){this.logger.debug(`Skipping already processed image url: ${i}`);continue}this.processedImageUrls.add(i);let h=`Here is the image url: ${i}`;o.has(i)&&(h=o.get(i)||h),this.logger.debug(`Adding image url: ${i}`),l.push({role:"user",content:[{type:"text",text:h},{type:"image_url",image_url:{url:i}}]}),a++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),a<n)){let i=await this.resolveRepositoryImages(e.messages,n-a,this.settings.github?.serverUrl||"",this.logger,c,r);this.logger.debug(`Resolved ${i.length} repository image URLs`);for(let h of i){if(a>=n)break;if(this.processedImageUrls.has(h)){this.logger.debug(`Skipping already processed repository image url: ${h}`);continue}l.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:h}}]}),this.processedImageUrls.add(h),a++}}let d={imagesExtractedCount:r.extractedImagesSize.length,base64ImagesCount:r.base64ImagesSize.length,imagesRemovedDueToSize:r.imagesRemovedDueToSize,imagesRemovedDueToDimensions:r.imagesRemovedDueToDimensions,imagesResized:r.imagesResized,imagesResolvedFromGitHubMCPCount:r.imagesResolvedFromGitHubMCPSize.length};for(let i=0;i<r.base64ImagesSize.length;i++)d[`base64ImageSize_${i}`]=r.base64ImagesSize[i];for(let i=0;i<r.resizedBase64ImagesSize.length;i++)d[`resizedBase64ImageSize_${i}`]=r.resizedBase64ImagesSize[i];for(let i=0;i<r.extractedImagesSize.length;i++)d[`extractedImageSize_${i}`]=r.extractedImagesSize[i];for(let i=0;i<r.imagesResolvedFromGitHubMCPSize.length;i++)d[`imagesResolvedFromGitHubMCPSize_${i}`]=r.imagesResolvedFromGitHubMCPSize[i];l.length>0&&this.logger.debug(`Using ${l.length} image messages`);for(let i of l)yield{kind:"message",message:i,turn:e.turn},e.messages.push(i);d.allImagesSendToLlm=e.messages.filter($R).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:d},e.messages.some(i=>$R(i))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,I,l){let n=G1(this.settings);if(!n)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let c=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!c||c.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let a=c[1];if(!yOe(this.logger,a))return[""];let s=c[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let r=Buffer.from(s,"base64");if(l.base64ImagesSize.push(r.length),r=await VOe(this.logger,l,I,jbe,a,r),l.resizedBase64ImagesSize.push(r?.length??-1),!r)return["",new Dbe(`Image size exceeds maximum size of ${im(I)}`)];s=r.toString("base64");try{let o=await this.uploadBase64ImageData(s,a,n);return o?(this.logger.debug(`Uploaded image url: ${o}`),e.image_url.url=o,[o]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(o){let d=o instanceof Error?o.message:String(o);return this.logger.debug(`Error during image upload: ${d}`),[""]}}async uploadBase64ImageData(e,I,l){try{let n=rue(this.settings),c=I.split("/").at(1),a=`image-${Date.now()}.${c}`;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 r=this.settings.github?.repo?.id;if(!r)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let o=`${n}?name=${encodeURIComponent(a)}&content_type=${encodeURIComponent(I)}&repository_id=${r}`;this.logger.debug(`Uploading image data (${im(s.length)}) to ${n} with name ${encodeURIComponent(a)} and content type ${encodeURIComponent(I)}`);let d={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+l},i=await fetch(o,{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(!i.ok){let p=await i.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${i.status} ${i.statusText} - ${p}`),null}let h=await i.json();return this.logger.debug(`Upload result: ${JSON.stringify(h,null,2)}`),h.url||null}catch(n){return this.logger.error(`Error handling image upload: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&this.logger.debug(`Stack trace: ${n.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 I=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof I}`),this.logger.debug(`GitHub tool call result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`),typeof I=="object"&&I!==null&&"binaryResultForLlm"in I&&Array.isArray(I.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${I.binaryResultForLlm.length} items`);try{for(let l of I.binaryResultForLlm)if(l.data&&l.mimeType){let n=Buffer.from(l.data,"base64"),c=l.mimeType;return{buffer:n,mimeType:c}}}catch(l){this.logger.error(`Failed to parse GitHub tool response: ${l}`),this.logger.debug(`binaryResultForLlm length: ${I.binaryResultForLlm?.length||0}`)}}else typeof I=="string"?this.logger.debug(`GitHub tool returned string result: ${I}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`)}catch(I){this.logger.error(`Error calling GitHub MCP tool: ${I}`)}}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,I,l){let n=[],c=await Promise.all(e);for(let{imgRef:a,attachment:s}of c)if(this.logger.debug(`Processing attachment for ${a.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(I.extractedImagesSize.push(s.buffer.length),vl(this.settings,"copilot_swe_agent_resize_image_references")){if(!await VOe(this.logger,I,l,jbe,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}n.push(a.url)}else{let r=await F9(l,jbe,s.buffer);if(this.logger.debug(`Image size check for ${a.url}: size=${s.buffer.length}, maxSize=${l}, exceedsSize=${r.exceedsSizeLimit}, exceedsDimensions=${r.exceedsDimensionLimit}`),r.exceedsSizeLimit?(I.imagesRemovedDueToSize++,this.logger.debug(`Image ${a.url} removed due to size (${s.buffer.length} > ${l})`)):r.exceedsDimensionLimit&&(I.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${a.url} removed due to dimensions`)),r.exceedsSizeLimit||r.exceedsDimensionLimit){this.processedImageUrls.add(a.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${im(l)}.`);continue}n.push(a.url),this.logger.debug(`Image ${a.url} passed size checks and added to results`)}else this.processedImageUrls.add(a.url),this.logger.debug(`Skipping image ${a.url} - could not fetch image data`);return n}async processImageReferences(e,I,l){let n=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${n}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let c=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 r=await this.getRepositoryImageViaTools(s);return r?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${r.buffer.length} bytes`),l.imagesResolvedFromGitHubMCPSize.push(r.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:r?.buffer?.length||0,mimeType:r?.mimeType||"",buffer:r?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await s9I(s.guid,G1(this.settings),this.logger,this.settings)}}),a=await this.getImgRefsSmallerThanMaxSize(c,l,I);return this.logger.debug(`Processed image references, found ${a.length} attachments smaller than max size of ${im(I)}`),{addedImages:a}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,I,l){this.logger=e,this.settings=I,this.gitHubServerUrl=I.github?.serverUrl,this.githubGetFileContentsTool=l,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 I=e.modelInfo,l=e.toolCall.function.name,n=e.toolResult;if(I?.capabilities?.supports?.vision){let c=Array.from(W9I(n,l));if(c.length===0){let a=await V9I(e.toolCall,this.logger);a&&c.push(a)}this.insertImageUrlMessages(c)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let I of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:I.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:I.url}}]})}};function*W9I(t,e){for(let I of t.binaryResultForLlm??[])I.type==="image"&&(yield{url:`data:${I.mimeType};base64,${I.data}`,isScreenshot:e.toLowerCase().includes("screenshot")})}var N9I="playwright-browser_take_screenshot";function Y9I(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function V9I(t,e){if(t.function.name!==N9I)return;e.debug("Adding images using Playwright params fallback strategy");let I=JSON.parse(t.function.arguments);if(Y9I(I)){let l=y9.isAbsolute(I.filename)?I.filename:y9.join(Mbe,I.filename);e.debug(`Image from Playwright params: ${I.filename}. Updated to ${l}.`);let n=await y9I(l,e);if(n){let c=n.buffer.toString("base64");return{url:`data:${n.mimeType};base64,${c}`,isScreenshot:!0}}}}function R9I(t){switch(y9.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function yOe(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 y9I(t,e){try{if(!_be(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let I=R9I(t);return I?{buffer:await a9I.readFile(t),mimeType:I}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(I){return e.error(`Failed to read image from disk: ${I instanceof Error?I.message:String(I)}`),null}}G();var YE=class{latestUserPromptMessage;logger;constructor(e,I){this.latestUserPromptMessage=e,this.logger=I}toJSON(){return"BasicTruncator"}async*preRequest(e){let I=this.latestUserPromptMessage?mGe(this.latestUserPromptMessage,e.messages):-1,l=[()=>gOe(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit),I===-1?void 0:()=>g9I(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit,I)].filter(a=>a!==void 0),n=0,c;for(;(!c||c.postTruncationTokensInMessages>e.tokenLimit)&&n<l.length;){let a=l[n]();c=F9I(c,a),n++}return c=c??Q9I(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit),c.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(c)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:c},c}},l6=class{truncateOnNextRequest=!1;userMessageToTruncateUpTo;logger;constructor(e,I){this.userMessageToTruncateUpTo=e,this.logger=I,this.logger.debug(`AnthropicTokenLimitErrorTruncator will truncate up to message: ${JSON.stringify(e)}`)}async*preRequest(e){if(this.truncateOnNextRequest){this.truncateOnNextRequest=!1;let I=mGe(this.userMessageToTruncateUpTo,e.messages);if(I===-1){this.logger.debug(`Failed to find user message to truncate up to: ${JSON.stringify(this.userMessageToTruncateUpTo)}`),this.logger.debug(`Current messages: ${JSON.stringify(e.messages)}`);return}let l=gOe(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit,I);l.tokensRemovedDuringTruncation>0&&this.logger.debug(`AnthropicTokenLimitErrorTruncator truncated: ${JSON.stringify(l)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"AnthropicTokenLimitErrorTruncator",truncateResult:l}}}async preErrorThrow(e){}async onRequestError(e){if(e){if(typeof e=="object"&&"code"in e&&e.code==="model_max_prompt_tokens_exceeded"){this.truncateOnNextRequest=!0;return}let I=[JSON.stringify(e)];e instanceof Error&&(I.push(e.message),e.cause instanceof Error?I.push(e.cause.message):e.cause&&I.push(JSON.stringify(e.cause)));let l="Input length and `max_tokens` exceed context limit";this.logger.debug(`Looking for error amongst: ${I.join(", ")}`),I.some(n=>n.includes(l))&&(this.truncateOnNextRequest=!0)}}toJSON(){return"AnthropicTokenLimitErrorTruncator"}};function F9I(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 FOe=.95;function gOe(t,e,I,l,n){let c=t.length;if(c===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:c,postTruncationTokensInMessages:0,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(p=>VF(p,I)),s=ui(JSON.stringify(e),I),r=l*FOe,o=a.reduce((p,Z)=>p+Z,0)+s;if(o<=r)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,i=0,h=Math.min(n??t.length,t.length);for(let p=0;p<h;p++){let Z=t[p];if(Z.role!=="system"&&Z.role!=="tool"&&Z.role!=="user"){if(Z.role==="assistant"){let u=Z.tool_calls||[],N=u.filter(Io).filter(A=>A.function.name===mC),Y=u.filter(Io).filter(A=>A.function.name!==mC),y=N.length===0,Q=new Set(Y.map(A=>A.id));if(Y.length>0&&(Z.tool_calls=N,a[p]=VF(Z,I)),y&&(d.add(p),i+=a[p]),Q.size>0)for(let A=p+1;A<t.length;A++){let w=t[A];if(w.role==="tool"&&Q.has(w.tool_call_id)&&(d.add(A),i+=a[A],Q.delete(w.tool_call_id),Q.size===0))break}}if(o-i<r)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function g9I(t,e,I,l,n){let c=t.length;if(c===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:c,postTruncationTokensInMessages:0,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(p=>VF(p,I)),s=ui(JSON.stringify(e),I),r=l*FOe,o=a.reduce((p,Z)=>p+Z,0)+s;if(o<=r)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,i=0,h=Math.min(n??t.length,t.length);for(let p=0;p<h;p++){let Z=t[p];if(Z.role!=="system"&&Z.role!=="tool"){if(Z.role==="user")d.add(p),i+=a[p];else if(Z.role==="assistant"){let u=Z.tool_calls||[],N=new Set(u.map(Y=>Y.id));if(d.add(p),i+=a[p],N.size>0)for(let Y=p+1;Y<t.length;Y++){let y=t[Y];if(y.role==="tool"&&N.has(y.tool_call_id)&&(d.add(Y),i+=a[Y],N.delete(y.tool_call_id),N.size===0))break}}if(o-i<r)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function Q9I(t,e,I,l){let n=t.length;if(n===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:n,postTruncationTokensInMessages:0,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let c=t.map(r=>VF(r,I)),a=ui(JSON.stringify(e),I),s=c.reduce((r,o)=>r+o,0)+a;return{tokenLimit:l,preTruncationTokensInMessages:s,preTruncationMessagesLength:n,postTruncationTokensInMessages:s,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}G();var ai=class extends Gp{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,I){}endGroup(e){}};G();G();var QOe={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"}]},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 n6(t,e,I){let l=(I||QOe)[t.toLowerCase()],n=new Set;for(;typeof l=="string";){if(n.has(l))return!1;n.add(l),l=QOe[l]}if(!l)return!1;let c=e.toLowerCase();return l.tools.some(a=>a.toolName===c)}var A9I="image";var w9I="resource",X9I=60*1e3*2,H9I={timeout:X9I};var eme=class{constructor(e,I,l){this.settings=e;this.logger=I;this.permissions=l}async invokeTool(e,I,l="hidden_characters"){let n=await this.doInvokeTool(e,I);return this.invokeToolResponseToToolResult(n,l)}invokeToolResponseToToolResult(e,I){let l=e.content||[],n="",c=[];for(let o of l)if(o.type==="text")n+=o.text||"";else if(o.type==="resource"){let d=o.resource;d&&d.blob?c.push({type:w9I,data:d.blob,mimeType:d.mimeType||"application/octet-stream"}):d&&d.text&&(n+=d.text)}else o.type==="image"&&c.push({type:A9I,data:o.data,mimeType:o.mimeType});let a=n;if(n==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),a=n;else try{let o=JSON.parse(n),d=lbe(o,I);a=JSON.stringify(d)}catch(o){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${o}`),a=Ibe(n,I)}this.logger.debug(`Tool invocation result: ${a}`);let s={},r=a?Pn(a,"output"):"";return e.isToolError?{textResultForLlm:a,resultType:"failure",error:a,sessionLog:r,toolTelemetry:s}:{textResultForLlm:a,binaryResultForLlm:c,resultType:"success",sessionLog:r,toolTelemetry:s}}async loadTools(e){let I=await this.loadToolsFromProvider(e),l={};for(let[n,c]of Object.entries(I)){let a=c.filterMode||"hidden_characters";l[n]={name:c.name,namespacedName:c.namespacedName,title:c.title||c.name,description:c.description,input_schema:c.input_schema,callback:async s=>{let r=I[n].serverName,o=I[n].name,d=I[n].title;if(!this.permissions.requestRequired)return this.invokeTool(n,s,a);let i=await this.permissions.request({kind:"mcp",serverName:r,toolName:o,toolTitle:d,args:s,readOnly:!!c.readOnly});switch(i.kind){case"approved":return this.invokeTool(n,s,a);case"denied-by-rules":return mO(i.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return hO;case"denied-interactively-by-user":return bO;default:FV(i,`Unhandled permission result kind: ${i}`)}},safeForTelemetry:c.safeForTelemetry}}return Object.values(l)}};var g9=class t extends eme{toolIdToClientInfo=new Map;constructor(e,I,l={requestRequired:!1}){super(e,I,l)}async doInvokeTool(e,I){let l=this.toolIdToClientInfo.get(e);if(!l)throw new Error(`No MCP client found for tool ID: ${e}`);let n=l.mcpClient,c=t.getToolNameFromIdAndClientName(e,l.clientName),a=await n.callTool({name:c,arguments:I},void 0,{...H9I,onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(a.content))throw new Error("Expected array of results");return{content:a.content,isToolError:a.error!==void 0&&a.error!==null||a.isError===!0}}async loadToolsFromProvider(e){let I={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let l of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(l.name)){this.logger.debug(`Skipping tool ${l.name} for client ${e.clientName}`);continue}let n=t.getToolIdFromClientAndToolName(e.clientName,l.name);this.toolIdToClientInfo.set(n,e);let c;e.safeForTelemetry===!0?c={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?c=e.safeForTelemetry:c={name:n6(e.clientName,l.name),inputsNames:!1},this.logger.debug(`Adding tool: ${n}`);let a;e.filterMapping===void 0?a="hidden_characters":typeof e.filterMapping=="object"?a=e.filterMapping[l.name]||"hidden_characters":a=e.filterMapping,I[n]={serverName:e.clientName,name:n,namespacedName:`${e.clientName}/${l.name}`,title:l.title||l.annotations?.title||l.name,description:l.description||"",input_schema:l.inputSchema,readOnly:l.annotations?.readOnlyHint,safeForTelemetry:c,filterMode:a}}return I}static getToolIdFromClientAndToolName(e,I){return`${e}-${I}`}static getToolNameFromIdAndClientName(e,I){return e.substring(I.length+1)}};G();var c6=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,I,l,n,c,a){this.settings=e,this.logger=I,this.gitHandler=l,this.location=n,this.commitPriorToCompletionWithTools=c,this.jitInstructions=a||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let I,l=async()=>{if(I===void 0)try{I=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(a){this.logger.error(`Failed to get changed paths, err: ${a}`),I=1}return I},n;for(let[a,s]of Object.entries(this.jitInstructions)){let r=VZe(this.settings,s.percentRemainingOfTimeout);r.isWithin&&(!s.whenNoPathsChanged||await l()===0)&&(!n||r.withinMs<n[0])&&(n=[r.withinMs,s.instruction])}let c=n?.[1];if(typeof c=="function"&&(c=c(this.location)),c&&!this.emittedJitInstructions.has(c)){this.logger.debug(`Adding JIT instructions to the history: ${c}`),this.emittedJitInstructions.add(c);let a={role:"user",content:c};e.messages.push(a),yield{kind:"message",message:a,turn:e.turn,source:"jit-instruction"}}}}},tme={remindWhereToDoWork:{instruction:NOe,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:I6.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:I6.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:I6.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};G();G();function lme(t){if(!t)return Vke;let[e,...I]=t?.split(":")??[t,void 0],l=I.join(":")||void 0;return{agent:e||void 0,model:l||void 0}}G();G();function a6(t){return t.kind==="message"&&t.message.role==="assistant"}function AOe(t){return t.kind==="message"&&t.message.role==="user"}function wOe(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function XOe(t){return t.kind==="message"&&t.message.role==="tool"}function E9I(t,e){return t.toolCalls.find(I=>I.toolCallId===e)}function v9I(t,e){let I=e.function.name;try{let l=JSON.parse(e.function.arguments||"{}"),c=t.find(a=>a.name===I)?.safeForTelemetry||{name:!1,inputsNames:!1};return{toolCallId:e.id,toolName:I,arguments:e.function.arguments,safeForTelemetryToolName:c===!0||c.name?I:F2(I),safeForTelemetryArguments:c===!0||c.inputsNames?Wke(l):""}}catch{return{toolCallId:e.id,toolName:I,arguments:e.function.arguments,safeForTelemetryToolName:F2(I),safeForTelemetryArguments:""}}}var s6=class{forAgent;turnDataCache;emittedTurns=new Set;callback;settings;toolsInUse;constructor(e,I,l,n){this.forAgent=e,this.turnDataCache=new Map,this.emittedTurns=new Set,this.callback=I,this.settings=l,this.toolsInUse=n}getTurnData(){return this.turnDataCache}async ingestEvent(e){let I,l;if("turn"in e&&typeof e.turn=="number"){if(I=e.turn+1,this.emittedTurns.has(I))return;this.turnDataCache.has(I)||this.turnDataCache.set(I,{featureFlagsAsString:Pq(this.settings),toolCalls:[],toolCallExecutions:[],turn:I}),l=this.turnDataCache.get(I)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(l,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(l={...l,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?l={...l,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?l={...l,endTimeMs:e.timestampMs,retriesUsed:(l.retriesUsed??0)+1}:e.kind==="turn_failed"?l={...l,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(l={...l,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?l={...l,truncateEvent:e}:e.kind==="image_processing"?l={...l,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?l={...l,largeImagesRemoved:(l.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(l.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(l={...l,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:Nke(e.requestMessages)},e.kind==="model_call_success"&&(l={...l,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):AOe(e)&&e.source==="jit-instruction"?l={...l,jitInstructionsAdded:(l?.jitInstructionsAdded??0)+1}:a6(e)&&e.message.tool_calls?l={...l,toolCalls:l.toolCalls.concat(e.message.tool_calls.map(n=>({...v9I(this.toolsInUse,n)})))}:XOe(e)&&(l={...l,toolCallExecutions:l.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(I,l),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(I),this.emittedTurns.add(I),this.turnDataCache.delete(I))}async emitTurnTelemetry(e){let I=this.turnDataCache.get(e);if(I){let l={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{model:I.model||"default",modelInfo:I.modelInfo||"{}",api_call_id:I.api_call_id,provider_call_id:I.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(I.toolCalls.map(n=>({toolCallId:n.toolCallId,toolName:n.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(I.toolCallExecutions),error:I.error,featureFlags:Pq(this.settings),conversationStructureSummary:I.conversationStructureSummary,truncationPerformedBy:I.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:I.endTimeMs!==void 0&&I.startTimeMs!==void 0?I.endTimeMs-I.startTimeMs:0,modelCallDurationMs:I.modelCallDurationMs,retriesUsed:I.retriesUsed??0,numToolCalls:I.toolCalls.length,numToolExecutions:I.toolCallExecutions.length,largeImagesRemoved:I.largeImagesRemoved,imagesRemoved:I.imagesRemoved,responsePromptTokens:I.responsePromptTokens,responseCompletionTokens:I.responseCompletionTokens,responseTotalTokens:I.responseTotalTokens,jitInstructionsAdded:I.jitInstructionsAdded,...I.truncateEvent?.truncateResult,...I.imageProcessingMetrics},restrictedProperties:{}}};await this.callback.progress(l)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,I){let l=I.toolCallId,n=E9I(e,l);if(n){let c=I.toolResult,a={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...c.toolTelemetry.properties,resultType:c.resultType,toolCallId:l,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id},restrictedProperties:{...c.toolTelemetry.restrictedProperties,arguments:n.arguments,result:c.textResultForLlm,toolName:n.toolName,error:c.error},metrics:{...c.toolTelemetry.metrics,durationMs:I.durationMs}}};await this.callback.progress(a)}}};G();G();var Q9=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var r6=class{constructor(e,I){this.runtimeContext=e;this.customAgentName=I;this.gitHandlers={silent:new Pr(new ai,this.runtimeContext.exec),logging:new Pr(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,I,l,n,c,a,s=new Q9,r){let o=async(p,Z,u)=>{let N={role:"user",content:p};return await this.runtimeContext.callback?.progress({kind:"message",message:N,turn:0}),await this.runCompletionWithTools(e,I,[...Z??[],N],a,c,{executeToolsInParallel:vl(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:u},r,s)},d=n,i=l??[],h;for(;d;){let p=await o(d,i,h);h=p.finalTurnCount,i=p.messages,d=await r?.onResult(p.postCompletionWithToolsCommitHash)}for(let p of a)if(p.shutdown){let Z=await p.shutdown();Z&&await this.runtimeContext.callback?.progress(Z)}return{finalTurnCount:h||0,messages:i}}async runCompletionWithTools(e,I,l,n,c,a,s,r=new Q9){let o=this.runtimeContext.callback?new s6("sweagent-capi",this.runtimeContext.callback,this.runtimeContext.settings,n):void 0,d=this.gitHandlers.logging,i=await d.getCurrentCommitHash(e),h=l.filter(Q=>Q.role==="user").at(-1),p=this.createCompletionWithToolsProcessors(e,i,n,r,c,s,h),Z=this.runtimeContext.client.getCompletionWithTools(I,l,n,{...a,processors:p}),u=0,N=[...l],Y=[];for await(let Q of Z){if(vl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let A=await this.runtimeContext.callback?.progress(Q,{accepts_user_messages:r.canProcessUserMessages()});r.handleCallbackResponse(A)}else Q.kind==="response"||Q.kind==="message"?await this.runtimeContext.callback?.progress({...Q,customAgentName:this.customAgentName}):await this.runtimeContext.callback?.progress(Q);o&&await o.ingestEvent(Q),(Q.kind==="message"||Q.kind==="response")&&(Q.kind==="message"&&N.push(Q.message),Q.kind==="response"&&Y.push(Q.response),u=Math.max(u,Q.turn??0))}let y=await d.getCurrentCommitHash(e);return{finalTurnCount:u,messages:N,resultMessages:Y,preCompletionWithToolsCommitHash:i,postCompletionWithToolsCommitHash:y}}createCompletionWithToolsProcessors(e,I,l,n,c,a,s){let r=new t6(this.runtimeContext.logger,this.runtimeContext.settings,l.find(p=>p.name==="github-mcp-server-get_file_contents")),o=new c6(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,I,c),d=new YE(s,this.runtimeContext.logger),i=s?new l6(s,this.runtimeContext.logger):void 0,h=[o,r,d,i];return vl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&h.push(n),{preRequest:h.filter(p=>p!==void 0),preToolsExecution:[a].filter(p=>p!==void 0),postToolExecution:[r,a].filter(p=>p!==void 0),onRequestError:[r,i].filter(p=>p!==void 0)}}};G();async function nme(t,e,I,l,n){try{return(await l.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:I,numSnippets:10},"hidden_characters")).textResultForLlm}catch(c){return n.error(`Error during Blackbird search: ${c}`),""}}var EOe=t=>vl(t,"copilot_swe_agent_search")||YZe(t,"SearchAgentExperiment")==="enabled",HOe="search";function cme(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var C9I=(t,e,I)=>`
1241
1241
  You are a question answering agent that is a component of GitHub Copilot coding agent. Your task is to take the given question
1242
1242
  and answer it using the given facts.
1243
1243
 
@@ -1347,10 +1347,10 @@ Pay attention to the following when using it:
1347
1347
  `,l),a=-1;if(n!==-1&&c!==-1?a=Math.min(n,c):n!==-1?a=n:c!==-1&&(a=c),a===-1){I=t.slice(l);break}else{let s=t.slice(l,a);e.push(s),l=a+1,t[l-1]==="\r"&&t[l]===`
1348
1348
  `&&l++}}return[e,I]}var dq=class extends Event{constructor(e,I){var l,n;super(e),this.code=(l=I?.code)!=null?l:void 0,this.message=(n=I?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,I,l){return l(Kje(this),I)}[Symbol.for("Deno.customInspect")](e,I){return e(Kje(this),I)}};function hTI(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function ape(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(ape).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${ape(t.cause)}`:t.message:`${t}`}function Kje(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var qje=t=>{throw TypeError(t)},mpe=(t,e,I)=>e.has(t)||qje("Cannot "+I),Bt=(t,e,I)=>(mpe(t,e,"read from private field"),I?I.call(t):e.get(t)),Ga=(t,e,I)=>e.has(t)?qje("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,I),Jn=(t,e,I,l)=>(mpe(t,e,"write to private field"),e.set(t,I),I),Cu=(t,e,I)=>(mpe(t,e,"access private method"),I),$G,lF,ME,oq,iq,ox,DE,dx,WV,TE,KE,jE,rx,Jb,spe,rpe,Gpe,Pje,ope,dpe,Gx,ipe,bpe,nF=class extends EventTarget{constructor(e,I){var l,n;super(),Ga(this,Jb),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ga(this,$G),Ga(this,lF),Ga(this,ME),Ga(this,oq),Ga(this,iq),Ga(this,ox),Ga(this,DE),Ga(this,dx,null),Ga(this,WV),Ga(this,TE),Ga(this,KE,null),Ga(this,jE,null),Ga(this,rx,null),Ga(this,rpe,async c=>{var a;Bt(this,TE).reset();let{body:s,redirected:r,status:o,headers:d}=c;if(o===204){Cu(this,Jb,Gx).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(r?Jn(this,ME,new URL(c.url)):Jn(this,ME,void 0),o!==200){Cu(this,Jb,Gx).call(this,`Non-200 status code (${o})`,o);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){Cu(this,Jb,Gx).call(this,'Invalid content type, expected "text/event-stream"',o);return}if(Bt(this,$G)===this.CLOSED)return;Jn(this,$G,this.OPEN);let i=new Event("open");if((a=Bt(this,rx))==null||a.call(this,i),this.dispatchEvent(i),typeof s!="object"||!s||!("getReader"in s)){Cu(this,Jb,Gx).call(this,"Invalid response body, expected a web ReadableStream",o),this.close();return}let h=new TextDecoder,p=s.getReader(),Z=!0;do{let{done:u,value:N}=await p.read();N&&Bt(this,TE).feed(h.decode(N,{stream:!u})),u&&(Z=!1,Bt(this,TE).reset(),Cu(this,Jb,ipe).call(this))}while(Z)}),Ga(this,Gpe,c=>{Jn(this,WV,void 0),!(c.name==="AbortError"||c.type==="aborted")&&Cu(this,Jb,ipe).call(this,ape(c))}),Ga(this,ope,c=>{typeof c.id=="string"&&Jn(this,dx,c.id);let a=new MessageEvent(c.event||"message",{data:c.data,origin:Bt(this,ME)?Bt(this,ME).origin:Bt(this,lF).origin,lastEventId:c.id||""});Bt(this,jE)&&(!c.event||c.event==="message")&&Bt(this,jE).call(this,a),this.dispatchEvent(a)}),Ga(this,dpe,c=>{Jn(this,ox,c)}),Ga(this,bpe,()=>{Jn(this,DE,void 0),Bt(this,$G)===this.CONNECTING&&Cu(this,Jb,spe).call(this)});try{if(e instanceof URL)Jn(this,lF,e);else if(typeof e=="string")Jn(this,lF,new URL(e,pTI()));else throw new Error("Invalid URL")}catch{throw hTI("An invalid or illegal string was specified")}Jn(this,TE,Gq({onEvent:Bt(this,ope),onRetry:Bt(this,dpe)})),Jn(this,$G,this.CONNECTING),Jn(this,ox,3e3),Jn(this,iq,(l=I?.fetch)!=null?l:globalThis.fetch),Jn(this,oq,(n=I?.withCredentials)!=null?n:!1),Cu(this,Jb,spe).call(this)}get readyState(){return Bt(this,$G)}get url(){return Bt(this,lF).href}get withCredentials(){return Bt(this,oq)}get onerror(){return Bt(this,KE)}set onerror(e){Jn(this,KE,e)}get onmessage(){return Bt(this,jE)}set onmessage(e){Jn(this,jE,e)}get onopen(){return Bt(this,rx)}set onopen(e){Jn(this,rx,e)}addEventListener(e,I,l){let n=I;super.addEventListener(e,n,l)}removeEventListener(e,I,l){let n=I;super.removeEventListener(e,n,l)}close(){Bt(this,DE)&&clearTimeout(Bt(this,DE)),Bt(this,$G)!==this.CLOSED&&(Bt(this,WV)&&Bt(this,WV).abort(),Jn(this,$G,this.CLOSED),Jn(this,WV,void 0))}};$G=new WeakMap,lF=new WeakMap,ME=new WeakMap,oq=new WeakMap,iq=new WeakMap,ox=new WeakMap,DE=new WeakMap,dx=new WeakMap,WV=new WeakMap,TE=new WeakMap,KE=new WeakMap,jE=new WeakMap,rx=new WeakMap,Jb=new WeakSet,spe=function(){Jn(this,$G,this.CONNECTING),Jn(this,WV,new AbortController),Bt(this,iq)(Bt(this,lF),Cu(this,Jb,Pje).call(this)).then(Bt(this,rpe)).catch(Bt(this,Gpe))},rpe=new WeakMap,Gpe=new WeakMap,Pje=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Bt(this,dx)?{"Last-Event-ID":Bt(this,dx)}:void 0},cache:"no-store",signal:(t=Bt(this,WV))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},ope=new WeakMap,dpe=new WeakMap,Gx=function(t,e){var I;Bt(this,$G)!==this.CLOSED&&Jn(this,$G,this.CLOSED);let l=new dq("error",{code:e,message:t});(I=Bt(this,KE))==null||I.call(this,l),this.dispatchEvent(l)},ipe=function(t,e){var I;if(Bt(this,$G)===this.CLOSED)return;Jn(this,$G,this.CONNECTING);let l=new dq("error",{code:e,message:t});(I=Bt(this,KE))==null||I.call(this,l),this.dispatchEvent(l),Jn(this,DE,setTimeout(Bt(this,bpe),Bt(this,ox)))},bpe=new WeakMap,nF.CONNECTING=0,nF.OPEN=1,nF.CLOSED=2;function pTI(){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}G();G();var hpe;hpe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function ZTI(t){return(await hpe).getRandomValues(new Uint8Array(t))}async function uTI(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",I="",l=await ZTI(t);for(let n=0;n<t;n++){let c=l[n]%e.length;I+=e[c]}return I}async function WTI(t){return await uTI(t)}async function NTI(t){let e=await(await hpe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function ppe(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await WTI(t),I=await NTI(e);return{code_verifier:e,code_challenge:I}}G();var za=R.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:R.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),R.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"}),_je=R.object({resource:R.string().url(),authorization_servers:R.array(za).optional(),jwks_uri:R.string().url().optional(),scopes_supported:R.array(R.string()).optional(),bearer_methods_supported:R.array(R.string()).optional(),resource_signing_alg_values_supported:R.array(R.string()).optional(),resource_name:R.string().optional(),resource_documentation:R.string().optional(),resource_policy_uri:R.string().url().optional(),resource_tos_uri:R.string().url().optional(),tls_client_certificate_bound_access_tokens:R.boolean().optional(),authorization_details_types_supported:R.array(R.string()).optional(),dpop_signing_alg_values_supported:R.array(R.string()).optional(),dpop_bound_access_tokens_required:R.boolean().optional()}).passthrough(),Zpe=R.object({issuer:R.string(),authorization_endpoint:za,token_endpoint:za,registration_endpoint:za.optional(),scopes_supported:R.array(R.string()).optional(),response_types_supported:R.array(R.string()),response_modes_supported:R.array(R.string()).optional(),grant_types_supported:R.array(R.string()).optional(),token_endpoint_auth_methods_supported:R.array(R.string()).optional(),token_endpoint_auth_signing_alg_values_supported:R.array(R.string()).optional(),service_documentation:za.optional(),revocation_endpoint:za.optional(),revocation_endpoint_auth_methods_supported:R.array(R.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:R.array(R.string()).optional(),introspection_endpoint:R.string().optional(),introspection_endpoint_auth_methods_supported:R.array(R.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:R.array(R.string()).optional(),code_challenge_methods_supported:R.array(R.string()).optional()}).passthrough(),YTI=R.object({issuer:R.string(),authorization_endpoint:za,token_endpoint:za,userinfo_endpoint:za.optional(),jwks_uri:za,registration_endpoint:za.optional(),scopes_supported:R.array(R.string()).optional(),response_types_supported:R.array(R.string()),response_modes_supported:R.array(R.string()).optional(),grant_types_supported:R.array(R.string()).optional(),acr_values_supported:R.array(R.string()).optional(),subject_types_supported:R.array(R.string()),id_token_signing_alg_values_supported:R.array(R.string()),id_token_encryption_alg_values_supported:R.array(R.string()).optional(),id_token_encryption_enc_values_supported:R.array(R.string()).optional(),userinfo_signing_alg_values_supported:R.array(R.string()).optional(),userinfo_encryption_alg_values_supported:R.array(R.string()).optional(),userinfo_encryption_enc_values_supported:R.array(R.string()).optional(),request_object_signing_alg_values_supported:R.array(R.string()).optional(),request_object_encryption_alg_values_supported:R.array(R.string()).optional(),request_object_encryption_enc_values_supported:R.array(R.string()).optional(),token_endpoint_auth_methods_supported:R.array(R.string()).optional(),token_endpoint_auth_signing_alg_values_supported:R.array(R.string()).optional(),display_values_supported:R.array(R.string()).optional(),claim_types_supported:R.array(R.string()).optional(),claims_supported:R.array(R.string()).optional(),service_documentation:R.string().optional(),claims_locales_supported:R.array(R.string()).optional(),ui_locales_supported:R.array(R.string()).optional(),claims_parameter_supported:R.boolean().optional(),request_parameter_supported:R.boolean().optional(),request_uri_parameter_supported:R.boolean().optional(),require_request_uri_registration:R.boolean().optional(),op_policy_uri:za.optional(),op_tos_uri:za.optional()}).passthrough(),$je=YTI.merge(Zpe.pick({code_challenge_methods_supported:!0})),upe=R.object({access_token:R.string(),id_token:R.string().optional(),token_type:R.string(),expires_in:R.number().optional(),scope:R.string().optional(),refresh_token:R.string().optional()}).strip(),eDe=R.object({error:R.string(),error_description:R.string().optional(),error_uri:R.string().optional()}),VTI=R.object({redirect_uris:R.array(za),token_endpoint_auth_method:R.string().optional(),grant_types:R.array(R.string()).optional(),response_types:R.array(R.string()).optional(),client_name:R.string().optional(),client_uri:za.optional(),logo_uri:za.optional(),scope:R.string().optional(),contacts:R.array(R.string()).optional(),tos_uri:za.optional(),policy_uri:R.string().optional(),jwks_uri:za.optional(),jwks:R.any().optional(),software_id:R.string().optional(),software_version:R.string().optional(),software_statement:R.string().optional()}).strip(),RTI=R.object({client_id:R.string(),client_secret:R.string().optional(),client_id_issued_at:R.number().optional(),client_secret_expires_at:R.number().optional()}).strip(),IDe=VTI.merge(RTI),j6l=R.object({error:R.string(),error_description:R.string().optional()}).strip(),D6l=R.object({token:R.string(),token_type_hint:R.string().optional()}).strip();G();function tDe(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function lDe({requestedResource:t,configuredResource:e}){let I=typeof t=="string"?new URL(t):new URL(t.href),l=typeof e=="string"?new URL(e):new URL(e.href);if(I.origin!==l.origin||I.pathname.length<l.pathname.length)return!1;let n=I.pathname.endsWith("/")?I.pathname:I.pathname+"/",c=l.pathname.endsWith("/")?l.pathname:l.pathname+"/";return n.startsWith(c)}G();var Sc=class extends Error{constructor(e,I){super(e),this.errorUri=I,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}},ix=class extends Sc{};ix.errorCode="invalid_request";var cF=class extends Sc{};cF.errorCode="invalid_client";var aF=class extends Sc{};aF.errorCode="invalid_grant";var sF=class extends Sc{};sF.errorCode="unauthorized_client";var bx=class extends Sc{};bx.errorCode="unsupported_grant_type";var mx=class extends Sc{};mx.errorCode="invalid_scope";var hx=class extends Sc{};hx.errorCode="access_denied";var Ju=class extends Sc{};Ju.errorCode="server_error";var px=class extends Sc{};px.errorCode="temporarily_unavailable";var Zx=class extends Sc{};Zx.errorCode="unsupported_response_type";var ux=class extends Sc{};ux.errorCode="unsupported_token_type";var Wx=class extends Sc{};Wx.errorCode="invalid_token";var Nx=class extends Sc{};Nx.errorCode="method_not_allowed";var Yx=class extends Sc{};Yx.errorCode="too_many_requests";var Vx=class extends Sc{};Vx.errorCode="invalid_client_metadata";var Rx=class extends Sc{};Rx.errorCode="insufficient_scope";var nDe={[ix.errorCode]:ix,[cF.errorCode]:cF,[aF.errorCode]:aF,[sF.errorCode]:sF,[bx.errorCode]:bx,[mx.errorCode]:mx,[hx.errorCode]:hx,[Ju.errorCode]:Ju,[px.errorCode]:px,[Zx.errorCode]:Zx,[ux.errorCode]:ux,[Wx.errorCode]:Wx,[Nx.errorCode]:Nx,[Yx.errorCode]:Yx,[Vx.errorCode]:Vx,[Rx.errorCode]:Rx};var eo=class extends Error{constructor(e){super(e??"Unauthorized")}};function aDe(t,e){let I=t.client_secret!==void 0;return e.length===0?I?"client_secret_post":"none":I&&e.includes("client_secret_basic")?"client_secret_basic":I&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":I?"client_secret_post":"none"}function sDe(t,e,I,l){let{client_id:n,client_secret:c}=e;switch(t){case"client_secret_basic":yTI(n,c,I);return;case"client_secret_post":FTI(n,c,l);return;case"none":gTI(n,l);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function yTI(t,e,I){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let l=btoa(`${t}:${e}`);I.set("Authorization",`Basic ${l}`)}function FTI(t,e,I){I.set("client_id",t),e&&I.set("client_secret",e)}function gTI(t,e){e.set("client_id",t)}async function Npe(t){let e=t instanceof Response?t.status:void 0,I=t instanceof Response?await t.text():t;try{let l=eDe.parse(JSON.parse(I)),{error:n,error_description:c,error_uri:a}=l,s=nDe[n]||Ju;return new s(c||"",a)}catch(l){let n=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${l}. Raw body: ${I}`;return new Ju(n)}}async function NV(t,e){var I,l;try{return await Wpe(t,e)}catch(n){if(n instanceof cF||n instanceof sF)return await((I=t.invalidateCredentials)===null||I===void 0?void 0:I.call(t,"all")),await Wpe(t,e);if(n instanceof aF)return await((l=t.invalidateCredentials)===null||l===void 0?void 0:l.call(t,"tokens")),await Wpe(t,e);throw n}}async function Wpe(t,{serverUrl:e,authorizationCode:I,scope:l,resourceMetadataUrl:n,fetchFn:c}){let a,s;try{a=await ATI(e,{resourceMetadataUrl:n},c),a.authorization_servers&&a.authorization_servers.length>0&&(s=a.authorization_servers[0])}catch{}s||(s=e);let r=await QTI(e,t,a),o=await vTI(s,{fetchFn:c}),d=await Promise.resolve(t.clientInformation());if(!d){if(I!==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 u=await kTI(s,{metadata:o,clientMetadata:t.clientMetadata,fetchFn:c});await t.saveClientInformation(u),d=u}if(I!==void 0){let u=await t.codeVerifier(),N=await JTI(s,{metadata:o,clientInformation:d,authorizationCode:I,codeVerifier:u,redirectUri:t.redirectUrl,resource:r,addClientAuthentication:t.addClientAuthentication,fetchFn:c});return await t.saveTokens(N),"AUTHORIZED"}let i=await t.tokens();if(i?.refresh_token)try{let u=await LTI(s,{metadata:o,clientInformation:d,refreshToken:i.refresh_token,resource:r,addClientAuthentication:t.addClientAuthentication,fetchFn:c});return await t.saveTokens(u),"AUTHORIZED"}catch(u){if(!(!(u instanceof Sc)||u instanceof Ju))throw u}let h=t.state?await t.state():void 0,{authorizationUrl:p,codeVerifier:Z}=await CTI(s,{metadata:o,clientInformation:d,state:h,redirectUrl:t.redirectUrl,scope:l||t.clientMetadata.scope,resource:r});return await t.saveCodeVerifier(Z),await t.redirectToAuthorization(p),"REDIRECT"}async function QTI(t,e,I){let l=tDe(t);if(e.validateResourceURL)return await e.validateResourceURL(l,I?.resource);if(I){if(!lDe({requestedResource:l,configuredResource:I.resource}))throw new Error(`Protected resource ${I.resource} does not match expected ${l} (or origin)`);return new URL(I.resource)}}function yx(t){let e=t.headers.get("WWW-Authenticate");if(!e)return;let[I,l]=e.split(" ");if(I.toLowerCase()!=="bearer"||!l)return;let c=/resource_metadata="([^"]*)"/.exec(e);if(c)try{return new URL(c[1])}catch{return}}async function ATI(t,e,I=fetch){let l=await HTI(t,"oauth-protected-resource",I,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!l||l.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!l.ok)throw new Error(`HTTP ${l.status} trying to load well-known OAuth protected resource metadata.`);return _je.parse(await l.json())}async function Ype(t,e,I=fetch){try{return await I(t,{headers:e})}catch(l){if(l instanceof TypeError)return e?Ype(t,void 0,I):void 0;throw l}}function wTI(t,e="",I={}){return e.endsWith("/")&&(e=e.slice(0,-1)),I.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function cDe(t,e,I=fetch){return await Ype(t,{"MCP-Protocol-Version":e},I)}function XTI(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function HTI(t,e,I,l){var n,c;let a=new URL(t),s=(n=l?.protocolVersion)!==null&&n!==void 0?n:XE,r;if(l?.metadataUrl)r=new URL(l.metadataUrl);else{let d=wTI(e,a.pathname);r=new URL(d,(c=l?.metadataServerUrl)!==null&&c!==void 0?c:a),r.search=a.search}let o=await cDe(r,s,I);if(!l?.metadataUrl&&XTI(o,a.pathname)){let d=new URL(`/.well-known/${e}`,a);o=await cDe(d,s,I)}return o}function ETI(t){let e=typeof t=="string"?new URL(t):t,I=e.pathname!=="/",l=[];if(!I)return l.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),l.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),l;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),l.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),l.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),l.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),l.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),l}async function vTI(t,{fetchFn:e=fetch,protocolVersion:I=XE}={}){var l;let n={"MCP-Protocol-Version":I},c=ETI(t);for(let{url:a,type:s}of c){let r=await Ype(a,n,e);if(r){if(!r.ok){if(r.status>=400&&r.status<500)continue;throw new Error(`HTTP ${r.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(s==="oauth")return Zpe.parse(await r.json());{let o=$je.parse(await r.json());if(!(!((l=o.code_challenge_methods_supported)===null||l===void 0)&&l.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return o}}}}async function CTI(t,{metadata:e,clientInformation:I,redirectUrl:l,scope:n,state:c,resource:a}){let s="code",r="S256",o;if(e){if(o=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(r))throw new Error(`Incompatible auth server: does not support code challenge method ${r}`)}else o=new URL("/authorize",t);let d=await ppe(),i=d.code_verifier,h=d.code_challenge;return o.searchParams.set("response_type",s),o.searchParams.set("client_id",I.client_id),o.searchParams.set("code_challenge",h),o.searchParams.set("code_challenge_method",r),o.searchParams.set("redirect_uri",String(l)),c&&o.searchParams.set("state",c),n&&o.searchParams.set("scope",n),n?.includes("offline_access")&&o.searchParams.append("prompt","consent"),a&&o.searchParams.set("resource",a.href),{authorizationUrl:o,codeVerifier:i}}async function JTI(t,{metadata:e,clientInformation:I,authorizationCode:l,codeVerifier:n,redirectUri:c,resource:a,addClientAuthentication:s,fetchFn:r}){var o;let d="authorization_code",i=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 h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:d,code:l,code_verifier:n,redirect_uri:String(c)});if(s)s(h,p,t,e);else{let u=(o=e?.token_endpoint_auth_methods_supported)!==null&&o!==void 0?o:[],N=aDe(I,u);sDe(N,I,h,p)}a&&p.set("resource",a.href);let Z=await(r??fetch)(i,{method:"POST",headers:h,body:p});if(!Z.ok)throw await Npe(Z);return upe.parse(await Z.json())}async function LTI(t,{metadata:e,clientInformation:I,refreshToken:l,resource:n,addClientAuthentication:c,fetchFn:a}){var s;let r="refresh_token",o;if(e){if(o=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(r))throw new Error(`Incompatible auth server: does not support grant type ${r}`)}else o=new URL("/token",t);let d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),i=new URLSearchParams({grant_type:r,refresh_token:l});if(c)c(d,i,t,e);else{let p=(s=e?.token_endpoint_auth_methods_supported)!==null&&s!==void 0?s:[],Z=aDe(I,p);sDe(Z,I,d,i)}n&&i.set("resource",n.href);let h=await(a??fetch)(o,{method:"POST",headers:d,body:i});if(!h.ok)throw await Npe(h);return upe.parse({refresh_token:l,...await h.json()})}async function kTI(t,{metadata:e,clientMetadata:I,fetchFn:l}){let n;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(e.registration_endpoint)}else n=new URL("/register",t);let c=await(l??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!c.ok)throw await Npe(c);return IDe.parse(await c.json())}var Vpe=class extends Error{constructor(e,I,l){super(`SSE error: ${I}`),this.code=e,this.event=l}},bq=class{constructor(e,I){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=I?.eventSourceInit,this._requestInit=I?.requestInit,this._authProvider=I?.authProvider,this._fetch=I?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new eo("No auth provider");let I;try{I=await NV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(e=this.onerror)===null||e===void 0||e.call(this,l),l}if(I!=="AUTHORIZED")throw new eo;return await this._startOrAuth()}async _commonHeaders(){var e;let I={};if(this._authProvider){let l=await this._authProvider.tokens();l&&(I.Authorization=`Bearer ${l.access_token}`)}return this._protocolVersion&&(I["mcp-protocol-version"]=this._protocolVersion),new Headers({...I,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,I,l;let n=(l=(I=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&I!==void 0?I:this._fetch)!==null&&l!==void 0?l:fetch;return new Promise((c,a)=>{this._eventSource=new nF(this._url.href,{...this._eventSourceInit,fetch:async(s,r)=>{let o=await this._commonHeaders();o.set("Accept","text/event-stream");let d=await n(s,{...r,headers:o});return d.status===401&&d.headers.has("www-authenticate")&&(this._resourceMetadataUrl=yx(d)),d}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{var r;if(s.code===401&&this._authProvider){this._authThenStart().then(c,a);return}let o=new Vpe(s.code,s.message,s);a(o),(r=this.onerror)===null||r===void 0||r.call(this,o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{var r;let o=s;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(d){a(d),(r=this.onerror)===null||r===void 0||r.call(this,d),this.close();return}c()}),this._eventSource.onmessage=s=>{var r,o;let d=s,i;try{i=dV.parse(JSON.parse(d.data))}catch(h){(r=this.onerror)===null||r===void 0||r.call(this,h);return}(o=this.onmessage)===null||o===void 0||o.call(this,i)}})}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 eo("No auth provider");if(await NV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo("Failed to authorize")}async close(){var e,I,l;(e=this._abortController)===null||e===void 0||e.abort(),(I=this._eventSource)===null||I===void 0||I.close(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e){var I,l,n;if(!this._endpoint)throw new Error("Not connected");try{let c=await this._commonHeaders();c.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:(I=this._abortController)===null||I===void 0?void 0:I.signal},s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._endpoint,a);if(!s.ok){if(s.status===401&&this._authProvider){if(this._resourceMetadataUrl=yx(s),await NV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo;return this.send(e)}let r=await s.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${r}`)}}catch(c){throw(n=this.onerror)===null||n===void 0||n.call(this,c),c}}setProtocolVersion(e){this._protocolVersion=e}};G();var qDe=rn(KDe(),1);import Zq from"node:process";import{PassThrough as djI}from"node:stream";G();var hq=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
1349
1349
  `);if(e===-1)return null;let I=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),ojI(I)}clear(){this._buffer=void 0}};function ojI(t){return dV.parse(JSON.parse(t))}function PDe(t){return JSON.stringify(t)+`
1350
- `}var ijI=Zq.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function bjI(){let t={};for(let e of ijI){let I=Zq.env[e];I!==void 0&&(I.startsWith("()")||(t[e]=I))}return t}var pq=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new hq,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new djI)}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,I)=>{var l,n,c,a,s;this._process=(0,qDe.default)(this._serverParams.command,(l=this._serverParams.args)!==null&&l!==void 0?l:[],{env:{...bjI(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!==null&&n!==void 0?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:Zq.platform==="win32"&&mjI(),cwd:this._serverParams.cwd}),this._process.on("error",r=>{var o,d;if(r.name==="AbortError"){(o=this.onclose)===null||o===void 0||o.call(this);return}I(r),(d=this.onerror)===null||d===void 0||d.call(this,r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{var o;this._process=void 0,(o=this.onclose)===null||o===void 0||o.call(this)}),(c=this._process.stdin)===null||c===void 0||c.on("error",r=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,r)}),(a=this._process.stdout)===null||a===void 0||a.on("data",r=>{this._readBuffer.append(r),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",r=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,r)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,I;return this._stderrStream?this._stderrStream:(I=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&I!==void 0?I:null}get pid(){var e,I;return(I=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&I!==void 0?I:null}processReadBuffer(){for(var e,I;;)try{let l=this._readBuffer.readMessage();if(l===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,l)}catch(l){(I=this.onerror)===null||I===void 0||I.call(this,l)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(I=>{var l;if(!(!((l=this._process)===null||l===void 0)&&l.stdin))throw new Error("Not connected");let n=PDe(e);this._process.stdin.write(n)?I():this._process.stdin.once("drain",I)})}};function mjI(){return"type"in Zq}G();G();var uq=class extends TransformStream{constructor({onError:e,onRetry:I,onComment:l}={}){let n;super({start(c){n=Gq({onEvent:a=>{c.enqueue(a)},onError(a){e==="terminate"?c.error(a):typeof e=="function"&&e(a)},onRetry:I,onComment:l})},transform(c){n.feed(c)}})}};var hjI={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Fx=class extends Error{constructor(e,I){super(`Streamable HTTP error: ${I}`),this.code=e}},Wq=class{constructor(e,I){var l;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=I?.requestInit,this._authProvider=I?.authProvider,this._fetch=I?.fetch,this._sessionId=I?.sessionId,this._reconnectionOptions=(l=I?.reconnectionOptions)!==null&&l!==void 0?l:hjI}async _authThenStart(){var e;if(!this._authProvider)throw new eo("No auth provider");let I;try{I=await NV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(e=this.onerror)===null||e===void 0||e.call(this,l),l}if(I!=="AUTHORIZED")throw new eo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let I={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(I.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(I["mcp-session-id"]=this._sessionId),this._protocolVersion&&(I["mcp-protocol-version"]=this._protocolVersion);let l=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...I,...l})}async _startOrAuthSse(e){var I,l,n;let{resumptionToken:c}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),c&&a.set("last-event-id",c);let s=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,{method:"GET",headers:a,signal:(l=this._abortController)===null||l===void 0?void 0:l.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Fx(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(n=this.onerror)===null||n===void 0||n.call(this,a),a}}_getNextReconnectionDelay(e){let I=this._reconnectionOptions.initialReconnectionDelay,l=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(I*Math.pow(l,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,I=0){var l;let n=this._reconnectionOptions.maxRetries;if(n>0&&I>=n){(l=this.onerror)===null||l===void 0||l.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let c=this._getNextReconnectionDelay(I);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,I+1)})},c)}_handleSseStream(e,I,l){if(!e)return;let{onresumptiontoken:n,replayMessageId:c}=I,a;(async()=>{var r,o,d,i;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new uq).getReader();for(;;){let{value:p,done:Z}=await h.read();if(Z)break;if(p.id&&(a=p.id,n?.(p.id)),!p.event||p.event==="message")try{let u=dV.parse(JSON.parse(p.data));c!==void 0&&E9(u)&&(u.id=c),(r=this.onmessage)===null||r===void 0||r.call(this,u)}catch(u){(o=this.onerror)===null||o===void 0||o.call(this,u)}}}catch(h){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${h}`)),l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:c},0)}catch(p){(i=this.onerror)===null||i===void 0||i.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 eo("No auth provider");if(await NV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo("Failed to authorize")}async close(){var e,I;(e=this._abortController)===null||e===void 0||e.abort(),(I=this.onclose)===null||I===void 0||I.call(this)}async send(e,I){var l,n,c,a;try{let{resumptionToken:s,onresumptiontoken:r}=I||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:Z6(e)?e.id:void 0}).catch(N=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,N)});return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,d),h=i.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=yx(i),await NV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo;return this.send(e)}let N=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${N}`)}if(i.status===202){sMe(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(N=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,N)});return}let Z=(Array.isArray(e)?e:[e]).filter(N=>"method"in N&&"id"in N&&N.id!==void 0).length>0,u=i.headers.get("content-type");if(Z)if(u?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:r},!1);else if(u?.includes("application/json")){let N=await i.json(),Y=Array.isArray(N)?N.map(y=>dV.parse(y)):[dV.parse(N)];for(let y of Y)(c=this.onmessage)===null||c===void 0||c.call(this,y)}else throw new Fx(-1,`Unexpected content type: ${u}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,I,l;if(this._sessionId)try{let n=await this._commonHeaders(),c={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,c);if(!a.ok&&a.status!==405)throw new Fx(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(n){throw(l=this.onerror)===null||l===void 0||l.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};G();var Nq=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 Epe(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(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},Epe=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(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var Yq=class{createTransport(e){switch(e.type){case"stdio":{let I=new pq({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0});return I.stderr?.pipe(e.stderr),I}case"http":return new Wq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new bq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new Nq(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};G();var rF="blackbird-mcp-server",_E="github-mcp-server",vpe="playwright";function $E(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function Vq(t){return t.type?.toLowerCase()==="http"}function Rq(t){return t.type?.toLowerCase()==="sse"}function gx(t){return t.type?.toLowerCase()==="memory"}var Cpe=class extends pjI{constructor(I,l){super({decodeStrings:!1});this.serverName=I;this.logger=l}_write(I,l,n){try{let c=I.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${c}`),n()}catch(c){n(c instanceof Error?c:new Error(String(c)))}}},yq=class{constructor(e,I=new sq,l=new Yq){this.logger=e;this.clientFactory=I;this.transportFactory=l}clients={};transports={};async startLocalMcpClient(e,I,l,n){this.logger.log(`Starting MCP client for ${e} with command: ${l} and args: ${n}`);let c=new Cpe(e,this.logger),a={type:"stdio",command:l,args:n,env:{...I,PATH:process.env.PATH},stderr:c},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"http",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startSseMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"sse",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startInMemoryMcpClient(e,I){this.logger.log(`Starting in-memory MCP client for ${e}`);let l={type:"memory",server:I},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async setupAndConnectClient(e,I){this.transports[e]=I,I.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let l=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),n=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await l.connect(I),l.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},l.onerror=c=>{this.logger.error(`MCP client for ${e} errored ${c}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-n}ms`),this.clients[e]=l}async getTools(e,I){let l={};for(let[n,c]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${n}`);let s=await c.listTools(),r=e?.mcpServers[n].tools,o=e?.mcpServers[n].filterMapping;for(let i of s.tools){if(i.name==="get_copilot_space")continue;if(!(r?.includes("*")||r?.includes(i.name))){this.logger.log(`Tool ${i.name} is not in the allowed list for client: ${n}`);continue}let p=n6(n,i.name),Z=`${n}-${i.name}`,u;typeof o=="string"?u=tbe(o):u=tbe(o?.[i.name]??"hidden_characters"),l[`${n}/${i.name}`]={name:Z,title:i.title??i.annotations?.title??i.name,description:i.description??Z,input_schema:i.inputSchema,readOnly:i.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[n].isDefaultServer||p),inputsNames:!!e?.mcpServers[n].isDefaultServer},filterMode:u},a.push(i.name),this.logger.log(`Tool ${i.name} added to tools list for client: ${n}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${n}`);let d=c.getServerVersion();await this.logServerSuccessWithTools(n,a,d,I)}catch(s){this.logger.error(`Failed to get tools from client: ${n} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(l,null,2)}`),l}async logServerSuccessWithTools(e,I,l,n){if(e!=rF&&n)try{let c=I.map(r=>`- ${r}`).join(`
1350
+ `}var ijI=Zq.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function bjI(){let t={};for(let e of ijI){let I=Zq.env[e];I!==void 0&&(I.startsWith("()")||(t[e]=I))}return t}var pq=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new hq,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new djI)}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,I)=>{var l,n,c,a,s;this._process=(0,qDe.default)(this._serverParams.command,(l=this._serverParams.args)!==null&&l!==void 0?l:[],{env:{...bjI(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!==null&&n!==void 0?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:Zq.platform==="win32"&&mjI(),cwd:this._serverParams.cwd}),this._process.on("error",r=>{var o,d;if(r.name==="AbortError"){(o=this.onclose)===null||o===void 0||o.call(this);return}I(r),(d=this.onerror)===null||d===void 0||d.call(this,r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{var o;this._process=void 0,(o=this.onclose)===null||o===void 0||o.call(this)}),(c=this._process.stdin)===null||c===void 0||c.on("error",r=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,r)}),(a=this._process.stdout)===null||a===void 0||a.on("data",r=>{this._readBuffer.append(r),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",r=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,r)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,I;return this._stderrStream?this._stderrStream:(I=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&I!==void 0?I:null}get pid(){var e,I;return(I=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&I!==void 0?I:null}processReadBuffer(){for(var e,I;;)try{let l=this._readBuffer.readMessage();if(l===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,l)}catch(l){(I=this.onerror)===null||I===void 0||I.call(this,l)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(I=>{var l;if(!(!((l=this._process)===null||l===void 0)&&l.stdin))throw new Error("Not connected");let n=PDe(e);this._process.stdin.write(n)?I():this._process.stdin.once("drain",I)})}};function mjI(){return"type"in Zq}G();G();var uq=class extends TransformStream{constructor({onError:e,onRetry:I,onComment:l}={}){let n;super({start(c){n=Gq({onEvent:a=>{c.enqueue(a)},onError(a){e==="terminate"?c.error(a):typeof e=="function"&&e(a)},onRetry:I,onComment:l})},transform(c){n.feed(c)}})}};var hjI={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Fx=class extends Error{constructor(e,I){super(`Streamable HTTP error: ${I}`),this.code=e}},Wq=class{constructor(e,I){var l;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=I?.requestInit,this._authProvider=I?.authProvider,this._fetch=I?.fetch,this._sessionId=I?.sessionId,this._reconnectionOptions=(l=I?.reconnectionOptions)!==null&&l!==void 0?l:hjI}async _authThenStart(){var e;if(!this._authProvider)throw new eo("No auth provider");let I;try{I=await NV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(e=this.onerror)===null||e===void 0||e.call(this,l),l}if(I!=="AUTHORIZED")throw new eo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let I={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(I.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(I["mcp-session-id"]=this._sessionId),this._protocolVersion&&(I["mcp-protocol-version"]=this._protocolVersion);let l=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...I,...l})}async _startOrAuthSse(e){var I,l,n;let{resumptionToken:c}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),c&&a.set("last-event-id",c);let s=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,{method:"GET",headers:a,signal:(l=this._abortController)===null||l===void 0?void 0:l.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new Fx(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(n=this.onerror)===null||n===void 0||n.call(this,a),a}}_getNextReconnectionDelay(e){let I=this._reconnectionOptions.initialReconnectionDelay,l=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(I*Math.pow(l,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,I=0){var l;let n=this._reconnectionOptions.maxRetries;if(n>0&&I>=n){(l=this.onerror)===null||l===void 0||l.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let c=this._getNextReconnectionDelay(I);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,I+1)})},c)}_handleSseStream(e,I,l){if(!e)return;let{onresumptiontoken:n,replayMessageId:c}=I,a;(async()=>{var r,o,d,i;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new uq).getReader();for(;;){let{value:p,done:Z}=await h.read();if(Z)break;if(p.id&&(a=p.id,n?.(p.id)),!p.event||p.event==="message")try{let u=dV.parse(JSON.parse(p.data));c!==void 0&&E9(u)&&(u.id=c),(r=this.onmessage)===null||r===void 0||r.call(this,u)}catch(u){(o=this.onerror)===null||o===void 0||o.call(this,u)}}}catch(h){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${h}`)),l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:c},0)}catch(p){(i=this.onerror)===null||i===void 0||i.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 eo("No auth provider");if(await NV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo("Failed to authorize")}async close(){var e,I;(e=this._abortController)===null||e===void 0||e.abort(),(I=this.onclose)===null||I===void 0||I.call(this)}async send(e,I){var l,n,c,a;try{let{resumptionToken:s,onresumptiontoken:r}=I||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:Z6(e)?e.id:void 0}).catch(N=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,N)});return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,d),h=i.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=yx(i),await NV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo;return this.send(e)}let N=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${N}`)}if(i.status===202){sMe(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(N=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,N)});return}let Z=(Array.isArray(e)?e:[e]).filter(N=>"method"in N&&"id"in N&&N.id!==void 0).length>0,u=i.headers.get("content-type");if(Z)if(u?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:r},!1);else if(u?.includes("application/json")){let N=await i.json(),Y=Array.isArray(N)?N.map(y=>dV.parse(y)):[dV.parse(N)];for(let y of Y)(c=this.onmessage)===null||c===void 0||c.call(this,y)}else throw new Fx(-1,`Unexpected content type: ${u}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,I,l;if(this._sessionId)try{let n=await this._commonHeaders(),c={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,c);if(!a.ok&&a.status!==405)throw new Fx(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(n){throw(l=this.onerror)===null||l===void 0||l.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};G();var Nq=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 Epe(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(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},Epe=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(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var Yq=class{createTransport(e){switch(e.type){case"stdio":{let I=new pq({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0});return I.stderr?.pipe(e.stderr),I}case"http":return new Wq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new bq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new Nq(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};G();var rF="blackbird-mcp-server",_E="github-mcp-server",vpe="playwright";function $E(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function Vq(t){return t.type?.toLowerCase()==="http"}function Rq(t){return t.type?.toLowerCase()==="sse"}function gx(t){return t.type?.toLowerCase()==="memory"}var Cpe=class extends pjI{constructor(I,l){super({decodeStrings:!1});this.serverName=I;this.logger=l}_write(I,l,n){try{let c=I.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${c}`),n()}catch(c){n(c instanceof Error?c:new Error(String(c)))}}},yq=class{constructor(e,I=new sq,l=new Yq){this.logger=e;this.clientFactory=I;this.transportFactory=l}clients={};transports={};async startLocalMcpClient(e,I,l,n){this.logger.log(`Starting MCP client for ${e} with command: ${l} and args: ${n}`);let c=new Cpe(e,this.logger),a={type:"stdio",command:l,args:n,env:{...I,PATH:process.env.PATH},stderr:c},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"http",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startSseMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"sse",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startInMemoryMcpClient(e,I){this.logger.log(`Starting in-memory MCP client for ${e}`);let l={type:"memory",server:I},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async setupAndConnectClient(e,I){this.transports[e]=I,I.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let l=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),n=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await l.connect(I),l.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},l.onerror=c=>{this.logger.error(`MCP client for ${e} errored ${c}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-n}ms`),this.clients[e]=l}async getTools(e,I){let l={};for(let[n,c]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${n}`);let s=await c.listTools(),r=e?.mcpServers[n].tools,o=e?.mcpServers[n].filterMapping;for(let i of s.tools){if(i.name==="get_copilot_space")continue;if(!(r?.includes("*")||r?.includes(i.name))){this.logger.log(`Tool ${i.name} is not in the allowed list for client: ${n}`);continue}let p=n6(n,i.name),Z=`${n}-${i.name}`,u;typeof o=="string"?u=tbe(o):u=tbe(o?.[i.name]??"hidden_characters"),l[`${n}/${i.name}`]={name:Z,namespacedName:`${n}/${i.name}`,title:i.title??i.annotations?.title??i.name,description:i.description??Z,input_schema:i.inputSchema,readOnly:i.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[n].isDefaultServer||p),inputsNames:!!e?.mcpServers[n].isDefaultServer},filterMode:u},a.push(i.name),this.logger.log(`Tool ${i.name} added to tools list for client: ${n}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${n}`);let d=c.getServerVersion();await this.logServerSuccessWithTools(n,a,d,I)}catch(s){this.logger.error(`Failed to get tools from client: ${n} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(l,null,2)}`),l}async logServerSuccessWithTools(e,I,l,n){if(e!=rF&&n)try{let c=I.map(r=>`- ${r}`).join(`
1351
1351
  `),s=`MCP server started successfully${l?` (version ${l.version})`:""} with ${I.length} ${I.length===1?"tool":"tools"} - for the full output, see the verbose logs
1352
1352
 
1353
- ${c}`;await n.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};G();var Jpe={mcpServers:{}},Fq=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;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 I=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(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),Jpe;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"),Jpe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let I in e.mcpServers)e.mcpServers[I].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),Jpe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){this.logger.log("Using default remote GitHub MCP server configuration");let l="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"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[_E]=c}configureLocalGitHubMcp(e){if(e.mcpServers[_E]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[_E]??{};$E(I)&&!I.command&&(e.mcpServers[_E]={...I,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 I={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[_E]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[vpe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(l=>l.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 I={command:"npx",args:[...Tbe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[vpe]=I}}configureBlackbirdMcp(e,I){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,I):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,I){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${I.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let n=[];I.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${I.blackbird?.mode}`);let c={command:`${l}/blackbird/mcp`,args:["serve","--index",`${l}/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:n,isDefaultServer:!0};e.mcpServers[rF]=c}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={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:I,isDefaultServer:!0};e.mcpServers[rF]=l}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={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&&(l["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:I,isDefaultServer:!0};e.mcpServers[rF]=n}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 $E(e)||Vq(e)||Rq(e)||gx(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,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!$E(I)&&!gx(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?$E(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Vq(I)||Rq(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):gx(I)&&!this.isValidInMemoryServerConfig(I)?(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,I){try{let l=this.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=this.resolveRemoteServerConfig(I);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let n=this.buildEnvironment(l),c=this.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args,l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let a=l+2;a<I.length;a++)c.push(I[a]);for(let a=0;a<l;a++)c.push(I[a]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)for(let[l,n]of Object.entries(e.env)){let c=n.trim();process.env[c]!==void 0&&(I[l]=process.env[c])}return I}resolveLocalServerConfig(e,I){let l=this.resolveString(e.command,I),n=this.resolveArray(e.args,I);return{...e,command:l,args:n}}resolveString(e,I){return I?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(l,n,c,a)=>{let r=I[n||a];return r!==void 0?r:c!==void 0?c:l}):e}resolveArray(e,I){return e?I?e.map(l=>this.resolveString(l,I)):e:[]}resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let a=this.resolveArray([c],I);l[n]=a[0]}return l}async processServers(e){if(!e)throw new Error("No servers to process");let I=Object.entries(e.mcpServers).map(([l,n])=>this.processServer(l,n));await Promise.all(I)}async processServer(e,I){if(!this.validateServerConfig(e,I)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{$E(I)?await this.processLocalServer(e,I):Vq(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Rq(I)&&this.remoteEnabled?await this.processSseServer(e,I):gx(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==rF&&await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var gq=class{constructor(e,I,l){this.logger=e;let n;if(typeof I=="string"){if(n=JSON.parse(I),typeof n!="object")throw new Error("Invalid MCP configuration: must be an object");if(n===null||!("mcpServers"in n)||typeof n.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=n}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new yq(this.logger),this.processor=new Fq(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=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 I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,I,l){if(!this.allTools){await this.startServers();let n=new g9(e,I,l),c=[];for(let a of Object.keys(this.registry.clients)){let s=await n.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});c.push(...s)}this.allTools=c}return this.allTools}getConfig(){return this.config}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.allTools=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}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.allTools=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 I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};G();var QKe=rn(gKe(),1);async function GKI(t={}){let e=await NZe();return ZZe((0,QKe.default)({},e,t))}async function AKe(t={}){if(zx())throw new Error("Settings have already been initialized");return GKI(t)}G();async function YV(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let a=await c(e);a&&(l=!0,n={...n,...a})}catch(a){I.error(`Hook execution failed: ${a}`)}return l?n:void 0}G();var l1=class{sessionId;startTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];constructor({sessionId:e,startTime:I,logger:l}={}){this.sessionId=e||kb(),this.startTime=I||new Date,this.logger=l||new ai}static fromEvents({events:e,logger:I}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({sessionId:l.data.sessionId,startTime:new Date(l.data.startTime),logger:I||new ai});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let a=e[c];n.events.push(a),n.processEventForState(a)}return n}addEvent(e){let I=e.id||kb(),l=e.timestamp||new Date().toISOString(),n=e.parentId!==void 0?e.parentId:this.getLastEventId(),c={...e,id:I,timestamp:l,parentId:n};return this.events.push(c),this.processEventForState(c),this.notifyEventCallbacks(c),c}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let I=this.eventCallbacks.indexOf(e);I>-1&&this.eventCallbacks.splice(I,1)}}get chatMessages(){return this._chatMessages}get selectedModel(){return this._selectedModel}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getChatContextMessages(){return this._chatMessages.filter(e=>e.role!=="system")}getSystemContextMessages(){return this._chatMessages.filter(e=>e.role==="system")}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":this._chatMessages.push({role:"user",content:e.data.content});break;case"assistant.message":{let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.resume":case"session.error":case"session.info":case"session.import_legacy":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"abort":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}notifyEventCallbacks(e){for(let I of this.eventCallbacks)try{I(e)}catch(l){this.logger.error(`Error in event callback: ${l instanceof Error?l.message:String(l)}`)}}};var Jq=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new ai,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new l1,gbe(this.workingDir).then(I=>{if(I.found)return KUe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e){let I=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new gq(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(Ze){this.logger.error(`Failed to initialize MCP host: ${Ze}`)}let n={timestamp:Date.now(),cwd:this.workingDir,prompt:e},a=(await YV(this.options.hooks?.userPromptSubmitted,n,this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:a}});let r=new WF().setProblemStatement(a).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-developer-cli").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();uZe();let o=await AKe(r),d=o.service?.agent?.model,i=lme(d),h=i.agent,p=i.model?{model:i.model}:void 0,Z=soe(o,this.logger,h,p),u={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:void 0,permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:process.platform==="win32"?Ci.powerShell:Ci.bash},N=await JOe(u,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,u.permissions)}catch(Ze){this.logger.error(`Failed to get MCP tools: ${Ze}`)}let y=[...N,...Y],Q=this.applyToolFiltering(y,this.options.allowedTools,this.options.disabledTools),A=await gbe(this.workingDir),E={...(kOe()["sweagent-capi"]?.["claude-sonnet-4"]??LOe()).supports,reasoning:!0},C=await pOe(A.found?A.gitRoot:"",Ife(),this.workingDir,{},E,u,Q,void 0),ce=this.session.chatMessages.slice(0,-1),ye={role:"user",content:WOe(a,E)},Xe=[...ce,ye],He={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e};await YV(this.options.hooks?.sessionStart,He,this.logger);let ie=Z.getCompletionWithTools(C,Xe,Q,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new YE(ye,this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let Ze of ie){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let II=await this.translateEvent(Ze,I);for(let Je of II)Je.type==="message"&&Je.role==="assistant"&&this.session.addEvent({type:"assistant.message",data:{messageId:`msg-${Date.now()}`,content:Je.content}}),yield Je}yield{type:"complete"}}catch(n){let c={timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:n instanceof Error?n:new Error(String(n))};await YV(this.options.hooks?.sessionEnd,c,this.logger),yield{type:"error",error:n instanceof Error?n:new Error(String(n))}}finally{let n={timestamp:Date.now(),cwd:this.workingDir,reason:"complete"};if(await YV(this.options.hooks?.sessionEnd,n,this.logger),l)try{await l.stopServers(),this.logger.log("MCP host stopped successfully")}catch(c){this.logger.error(`Error stopping MCP host: ${c}`)}}}buildAgentModelString(){switch(this.options.modelProvider.type){case"openai":return`openai:${this.options.modelProvider.model}`;case"anthropic":return`anthropic:${this.options.modelProvider.model}`;case"copilot":return`capi:${this.options.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.options.modelProvider.type}`)}}applyToolFiltering(e,I,l){let n=e;return I&&I.length>0&&(n=n.filter(c=>I.includes(c.name))),l&&l.length>0&&(n=n.filter(c=>!l.includes(c.name))),n}async translateEvent(e,I){switch(e.kind){case"message":{if(a6(e)&&e.message.content)return[{type:"message",content:typeof e.message.content=="string"?e.message.content:"",role:"assistant"}];if(wOe(e)){let l=[];for(let n of e.message.tool_calls){let c=jA(n.function.arguments);I.set(n.id,n.function.name);let a={timestamp:Date.now(),cwd:this.workingDir,toolName:n.function.name,toolArgs:c},r=(await YV(this.options.hooks?.preToolUse,a,this.logger))?.modifiedArgs??c;l.push({type:"tool_use",toolName:n.function.name,args:r,toolCallId:n.id})}return l}return[]}case"response":return[];case"model_call_failure":{let l=new Error(e.modelCall?.error||"Model call failed"),n={timestamp:Date.now(),cwd:this.workingDir,error:l,errorContext:"model_call",recoverable:!0};return await YV(this.options.hooks?.errorOccurred,n,this.logger),[{type:"error",error:l}]}case"tool_execution":{let l=I.get(e.toolCallId)||"unknown",n={timestamp:Date.now(),cwd:this.workingDir,toolName:l,toolArgs:{},toolResult:e.toolResult},a=(await YV(this.options.hooks?.postToolUse,n,this.logger))?.modifiedResult??e.toolResult;return[{type:"tool_result",toolName:l,result:a,toolCallId:e.toolCallId}]}default:return[]}}};G();G();var Tpe=class{loggers;constructor(e){this.loggers=e}isDebug(){return this.loggers.some(e=>e.isDebug())}debug(e){this.loggers.forEach(I=>I.debug(e))}log(e){this.loggers.forEach(I=>I.log(e))}info(e){this.loggers.forEach(I=>I.info(e))}notice(e){this.loggers.forEach(I=>I.notice(e))}warning(e){this.loggers.forEach(I=>I.warning(e))}error(e){this.loggers.forEach(I=>I.error(e))}startGroup(e,I){this.loggers.forEach(l=>l.startGroup(e,I))}endGroup(e){this.loggers.forEach(I=>I.endGroup(e))}};G();import{appendFile as oKI,access as dKI,mkdir as iKI}from"fs/promises";import{constants as bKI}from"fs";import{dirname as mKI}from"path";var jpe=class extends Gp{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=hKI(mKI(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(I).toString())}notice(I){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(I).toString())}warning(I){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(I).toString())}error(I){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(I).toString())}startGroup(I,l){super.shouldLog(l||4)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||4)&&this.write("END-GROUP","")}write(I,l){let c=`${new Date().toISOString()} [${I}] ${l}
1353
+ ${c}`;await n.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};G();var Jpe={mcpServers:{}},Fq=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;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 I=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(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),Jpe;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"),Jpe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let I in e.mcpServers)e.mcpServers[I].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),Jpe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){this.logger.log("Using default remote GitHub MCP server configuration");let l="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"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[_E]=c}configureLocalGitHubMcp(e){if(e.mcpServers[_E]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[_E]??{};$E(I)&&!I.command&&(e.mcpServers[_E]={...I,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 I={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[_E]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[vpe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(l=>l.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 I={command:"npx",args:[...Tbe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[vpe]=I}}configureBlackbirdMcp(e,I){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,I):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,I){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${I.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let n=[];I.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${I.blackbird?.mode}`);let c={command:`${l}/blackbird/mcp`,args:["serve","--index",`${l}/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:n,isDefaultServer:!0};e.mcpServers[rF]=c}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={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:I,isDefaultServer:!0};e.mcpServers[rF]=l}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={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&&(l["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:I,isDefaultServer:!0};e.mcpServers[rF]=n}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 $E(e)||Vq(e)||Rq(e)||gx(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,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!$E(I)&&!gx(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?$E(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(Vq(I)||Rq(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):gx(I)&&!this.isValidInMemoryServerConfig(I)?(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,I){try{let l=this.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=this.resolveRemoteServerConfig(I);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let n=this.buildEnvironment(l),c=this.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args,l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let a=l+2;a<I.length;a++)c.push(I[a]);for(let a=0;a<l;a++)c.push(I[a]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)for(let[l,n]of Object.entries(e.env)){let c=n.trim(),a=c;if(c.includes("$")&&(a=this.resolveString(c,process.env)),a!==c){I[l]=a;continue}process.env[c]!==void 0&&(I[l]=process.env[c])}return I}resolveLocalServerConfig(e,I){let l=this.resolveString(e.command,I),n=this.resolveArray(e.args,I);return{...e,command:l,args:n}}resolveString(e,I){return I?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(l,n,c,a)=>{let r=I[n||a];return r!==void 0?r:c!==void 0?c:l}):e}resolveArray(e,I){return e?I?e.map(l=>this.resolveString(l,I)):e:[]}resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let a=this.resolveArray([c],I);l[n]=a[0]}return l}async processServers(e){if(!e)throw new Error("No servers to process");let I=Object.entries(e.mcpServers).map(([l,n])=>this.processServer(l,n));await Promise.all(I)}async processServer(e,I){if(!this.validateServerConfig(e,I)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{$E(I)?await this.processLocalServer(e,I):Vq(I)&&this.remoteEnabled?await this.processHttpServer(e,I):Rq(I)&&this.remoteEnabled?await this.processSseServer(e,I):gx(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==rF&&await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var gq=class{constructor(e,I,l){this.logger=e;let n;if(typeof I=="string"){if(n=JSON.parse(I),typeof n!="object")throw new Error("Invalid MCP configuration: must be an object");if(n===null||!("mcpServers"in n)||typeof n.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=n}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new yq(this.logger),this.processor=new Fq(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=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 I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,I,l){if(!this.allTools){await this.startServers();let n=new g9(e,I,l),c=[];for(let a of Object.keys(this.registry.clients)){let s=await n.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});c.push(...s)}this.allTools=c}return this.allTools}getConfig(){return this.config}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.allTools=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}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.allTools=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 I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};G();var QKe=rn(gKe(),1);async function GKI(t={}){let e=await NZe();return ZZe((0,QKe.default)({},e,t))}async function AKe(t={}){if(zx())throw new Error("Settings have already been initialized");return GKI(t)}G();async function YV(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let a=await c(e);a&&(l=!0,n={...n,...a})}catch(a){I.error(`Hook execution failed: ${a}`)}return l?n:void 0}G();var l1=class{sessionId;startTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];constructor({sessionId:e,startTime:I,logger:l}={}){this.sessionId=e||kb(),this.startTime=I||new Date,this.logger=l||new ai}static fromEvents({events:e,logger:I}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({sessionId:l.data.sessionId,startTime:new Date(l.data.startTime),logger:I||new ai});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let a=e[c];n.events.push(a),n.processEventForState(a)}return n}addEvent(e){let I=e.id||kb(),l=e.timestamp||new Date().toISOString(),n=e.parentId!==void 0?e.parentId:this.getLastEventId(),c={...e,id:I,timestamp:l,parentId:n};return this.events.push(c),this.processEventForState(c),this.notifyEventCallbacks(c),c}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let I=this.eventCallbacks.indexOf(e);I>-1&&this.eventCallbacks.splice(I,1)}}get chatMessages(){return this._chatMessages}get selectedModel(){return this._selectedModel}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getChatContextMessages(){return this._chatMessages.filter(e=>e.role!=="system")}getSystemContextMessages(){return this._chatMessages.filter(e=>e.role==="system")}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":this._chatMessages.push({role:"user",content:e.data.content});break;case"assistant.message":{let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.resume":case"session.error":case"session.info":case"session.import_legacy":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"abort":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}notifyEventCallbacks(e){for(let I of this.eventCallbacks)try{I(e)}catch(l){this.logger.error(`Error in event callback: ${l instanceof Error?l.message:String(l)}`)}}};var Jq=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new ai,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new l1,gbe(this.workingDir).then(I=>{if(I.found)return KUe(I.gitRoot,!0,this.workingDir)}).catch(I=>{this.logger.debug(`Failed to initialize custom instructions cache: ${I}`)})}async*query(e){let I=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new gq(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(Ze){this.logger.error(`Failed to initialize MCP host: ${Ze}`)}let n={timestamp:Date.now(),cwd:this.workingDir,prompt:e},a=(await YV(this.options.hooks?.userPromptSubmitted,n,this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:a}});let r=new WF().setProblemStatement(a).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-developer-cli").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();uZe();let o=await AKe(r),d=o.service?.agent?.model,i=lme(d),h=i.agent,p=i.model?{model:i.model}:void 0,Z=soe(o,this.logger,h,p),u={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:void 0,permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:process.platform==="win32"?Ci.powerShell:Ci.bash},N=await JOe(u,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,u.permissions)}catch(Ze){this.logger.error(`Failed to get MCP tools: ${Ze}`)}let y=[...N,...Y],Q=this.applyToolFiltering(y,this.options.allowedTools,this.options.disabledTools),A=await gbe(this.workingDir),E={...(kOe()["sweagent-capi"]?.["claude-sonnet-4"]??LOe()).supports,reasoning:!0},C=await pOe(A.found?A.gitRoot:"",Ife(),this.workingDir,{},E,u,Q,void 0),ce=this.session.chatMessages.slice(0,-1),ye={role:"user",content:WOe(a,E)},Xe=[...ce,ye],He={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e};await YV(this.options.hooks?.sessionStart,He,this.logger);let ie=Z.getCompletionWithTools(C,Xe,Q,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new YE(ye,this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let Ze of ie){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let II=await this.translateEvent(Ze,I);for(let Je of II)Je.type==="message"&&Je.role==="assistant"&&this.session.addEvent({type:"assistant.message",data:{messageId:`msg-${Date.now()}`,content:Je.content}}),yield Je}yield{type:"complete"}}catch(n){let c={timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:n instanceof Error?n:new Error(String(n))};await YV(this.options.hooks?.sessionEnd,c,this.logger),yield{type:"error",error:n instanceof Error?n:new Error(String(n))}}finally{let n={timestamp:Date.now(),cwd:this.workingDir,reason:"complete"};if(await YV(this.options.hooks?.sessionEnd,n,this.logger),l)try{await l.stopServers(),this.logger.log("MCP host stopped successfully")}catch(c){this.logger.error(`Error stopping MCP host: ${c}`)}}}buildAgentModelString(){switch(this.options.modelProvider.type){case"openai":return`openai:${this.options.modelProvider.model}`;case"anthropic":return`anthropic:${this.options.modelProvider.model}`;case"copilot":return`capi:${this.options.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.options.modelProvider.type}`)}}applyToolFiltering(e,I,l){let n=e;return I&&I.length>0&&(n=n.filter(c=>I.includes(c.name))),l&&l.length>0&&(n=n.filter(c=>!l.includes(c.name))),n}async translateEvent(e,I){switch(e.kind){case"message":{if(a6(e)&&e.message.content)return[{type:"message",content:typeof e.message.content=="string"?e.message.content:"",role:"assistant"}];if(wOe(e)){let l=[];for(let n of e.message.tool_calls){let c=jA(n.function.arguments);I.set(n.id,n.function.name);let a={timestamp:Date.now(),cwd:this.workingDir,toolName:n.function.name,toolArgs:c},r=(await YV(this.options.hooks?.preToolUse,a,this.logger))?.modifiedArgs??c;l.push({type:"tool_use",toolName:n.function.name,args:r,toolCallId:n.id})}return l}return[]}case"response":return[];case"model_call_failure":{let l=new Error(e.modelCall?.error||"Model call failed"),n={timestamp:Date.now(),cwd:this.workingDir,error:l,errorContext:"model_call",recoverable:!0};return await YV(this.options.hooks?.errorOccurred,n,this.logger),[{type:"error",error:l}]}case"tool_execution":{let l=I.get(e.toolCallId)||"unknown",n={timestamp:Date.now(),cwd:this.workingDir,toolName:l,toolArgs:{},toolResult:e.toolResult},a=(await YV(this.options.hooks?.postToolUse,n,this.logger))?.modifiedResult??e.toolResult;return[{type:"tool_result",toolName:l,result:a,toolCallId:e.toolCallId}]}default:return[]}}};G();G();var Tpe=class{loggers;constructor(e){this.loggers=e}isDebug(){return this.loggers.some(e=>e.isDebug())}debug(e){this.loggers.forEach(I=>I.debug(e))}log(e){this.loggers.forEach(I=>I.log(e))}info(e){this.loggers.forEach(I=>I.info(e))}notice(e){this.loggers.forEach(I=>I.notice(e))}warning(e){this.loggers.forEach(I=>I.warning(e))}error(e){this.loggers.forEach(I=>I.error(e))}startGroup(e,I){this.loggers.forEach(l=>l.startGroup(e,I))}endGroup(e){this.loggers.forEach(I=>I.endGroup(e))}};G();import{appendFile as oKI,access as dKI,mkdir as iKI}from"fs/promises";import{constants as bKI}from"fs";import{dirname as mKI}from"path";var jpe=class extends Gp{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=hKI(mKI(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(I).toString())}notice(I){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(I).toString())}warning(I){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(I).toString())}error(I){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(I).toString())}startGroup(I,l){super.shouldLog(l||4)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||4)&&this.write("END-GROUP","")}write(I,l){let c=`${new Date().toISOString()} [${I}] ${l}
1354
1354
  `;this.writeQueue=this.writeQueue.then(()=>this.performWrite(c)).catch(()=>{})}async performWrite(I){await oKI(this.filePath,I)}};async function hKI(t){try{await dKI(t,bKI.F_OK)}catch{await iKI(t,{recursive:!0})}}G();async function*D7l(t){let{prompt:e,...I}=t;yield*new Jq(I).query(e)}G();var wKe=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new ai}async createSession(){let e=new l1({logger:this.logger});return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let I=this.sessions.get(e);return I&&(this.lastAccessedSessionId=e),I}async getLastSession(){if(this.lastAccessedSessionId){let l=this.sessions.get(this.lastAccessedSessionId);if(l)return l}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((l,n)=>n.startTime.getTime()-l.startTime.getTime());let I=e[0];return this.lastAccessedSessionId=I.sessionId,I}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}};export{Jq as Agent,Gp as BaseLogger,Tpe as CompoundLogger,qV as ConsoleLogger,jpe as FileLogger,ai as NoopLogger,l1 as Session,wKe as SessionManager,YV as executeHooks,s1 as isDebugEnvironment,D7l as query};
1355
1355
  /*! Bundled license information:
1356
1356