@github/copilot 0.0.339-12 → 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/index.js CHANGED
@@ -1624,7 +1624,7 @@ ${QYt()}
1624
1624
  <reminder>
1625
1625
  The user may have mentioned images, if so these will have been attached to this message, in the order they were mentioned
1626
1626
  </reminder>`),l.trim()},fNe={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."},wYt=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${ire(t)}. Commit changes by using the **report_progress** tool.</reminder>`;c();function FYt(t){try{if(t)typeof t=="string"&&(t=JSON.parse(t));else return"no_messages";let e=t.map(l=>{let n="?";switch(l.role){case"system":n="s";break;case"assistant":n="a";break;case"user":n="u";break;case"tool":n="t";break}return{type:n,tool_call_id:l.role!=="tool"?void 0:l.tool_call_id,reasoning_text:l.role!=="assistant"?void 0:!!l.reasoning_text,content:typeof l.content=="string"?["text"]:l.content?.map(I=>I.type),tool_calls:l.role!=="assistant"?void 0:l.tool_calls?l.tool_calls.map(I=>I.id):[]}});return JSON.stringify(e,null,2)}catch{return"failed_to_summarize"}}function uP(t){let e=t.reasoning_text?.replace(/<\|im_sep\|>(\*\*.*?\*\*)?/g,`
1627
- `)?.trim();return{...t,reasoning_text:e}}function dre(t){return structuredClone(t)}function CYt(t){return{...t,choices:t.choices.map(e=>{let l=uP(e.message);return{delta:{role:l.role,content:l.content,reasoning_opaque:l.reasoning_opaque,reasoning_text:l.reasoning_text,tool_calls:e.message.tool_calls?.map(n=>({...n,index:0}))},finish_reason:e.finish_reason,index:e.index}}),object:"chat.completion.chunk"}}function ex(t){return t.role==="user"&&Array.isArray(t.content)&&t.content.some(e=>e.type==="image_url")}function ZSe(t,e){let l=e.indexOf(t);if(l!==-1)return l;let n=s=>(typeof s.content=="string"?[{type:"text",text:s.content}]:s.content).filter(o=>o.type==="text").map(o=>o.text).join("").trim(),I=n(t),r=e.map((s,o)=>s.role==="user"&&n(s)===I?o:-1).filter(s=>s!==-1),a=r.at(0)??-1;return r.length===1?a:-1}c();var gSe="/tmp/playwright-logs",X_l="0.0.40",NSe=[`@playwright/mcp@${X_l}`,"--viewport-size","1280, 720","--output-dir",gSe],zcr=[...NSe,"--isolated"];var WSe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},ure=2e3;async function L_l(t,e,l,n){let I={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},r=`${Ibt(n)}/${t}`;l.info(`Downloading image from ${r}`);try{let a=await fetch(r,{method:"GET",headers:I});if(l.info(`Response status: ${a.status} ${a.statusText}`),l.debug(`Download Response URL: ${a.url}`),!a.ok){l.info(`Failed to download image, status: ${a.status}, statusText: ${a.statusText}`);try{let p=await a.text();l.info(`Error response body: ${p}`)}catch(p){l.info(`Could not read error response body: ${p}`)}return{size:0}}let o=(await a.json()).url;if(!o)return l.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let d=await fetch(o,{method:"GET"});if(!d.ok)return l.error(`Failed to download image: ${d.status} ${d.statusText}`),{size:0};let u=await d.arrayBuffer(),G=u.byteLength;return l.info(`Downloaded content size: ${By(G)}`),{size:G,buffer:Buffer.from(u),mimeType:d.headers.get("content-type")||void 0}}catch(a){return l.error("Network error downloading image"),a instanceof Error&&(l.info(`Error message: ${a.message}`),l.info(`Error stack: ${a.stack}`)),{size:0}}}function ySe(t,e,l,n){let I=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,r=/!\[.*?\]\((.*?)\)/g,a=[];return a.push(...vYt(t,e,I,l,n)),a.push(...vYt(t,e,r,l,n)),a}function vYt(t,e,l,n,I){let r=t.matchAll(l),a=[],s=/\/([a-f0-9-]+)$/;for(let o of r){let d=S_l(o[1],e),u=O_l(o[1],e,I);if(d||u){let G=o[1].match(s),p={url:o[1],guid:"",kind:u?"legacy_attachment":"attachment"};G&&G.length>1&&(p.guid=G[1]),a.push(p)}else if(n){let G={url:o[1],guid:"",kind:"committed_attachment"};a.push(G)}}return a}function J_l(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&pre(t)}function pre(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function B_l(t){try{let e=/Here are relevant code snippets from the repository that might help with this task:\s*(\[[\s\S]*?\])(?=\n|$)/,l=t.match(e);if(!l?.[1]||l[1].length<=1)return null;let n=l[1].trim();return JSON.parse(n)}catch{return null}}function x_l(t,e,l){if(!t?.url||!t?.ref||!t?.path)throw new Error("Invalid repository insight: missing required fields");if(!e||e.trim()==="")throw new Error("Invalid image path: path cannot be empty");let n=t.url.split("/").slice(3,5).join("/"),I=t.ref.split("/")[2],r;if(e.startsWith("/"))r=e.slice(1);else{let s=t.path,o=mre.dirname(s);r=mre.resolve("/",o,e).slice(1)}return`${l}/${n}/blob/${I}/${r}`}function S_l(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function O_l(t,e,l){return e&&new RegExp(`^${e}/[\\w.-]+/[\\w.-]+/assets/\\d+/[^.]+$`).test(t)?(l.debug(`Legacy GitHub asset URL detected: ${t}`),!0):!1}async function RSe(t){let{width:e,height:l}=g2t(t);if(e===void 0||l===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:l}}async function HNe(t,e,l,n,I,r){t.debug(`Checking if image is valid size and dimensions. Max size: ${l}, Max dimension: ${n}`);let{exceedsSizeLimit:a,exceedsDimensionLimit:s}=await Gre(l,n,r);if(!s&&!a)return t.debug("Image is within size and dimension limits."),r;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${n}, attempting to resize`);let[o,d]=await M_l(t,r,n,l,I);if(!o){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,d==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:u}=await Gre(l,n,o);if(u){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),o}if(a){t.debug(`Image size ${By(r.length)} is larger than the maximum size of ${By(l)}, attempting to reduce image quality`);let o=await __l(t,r,n,l,I);if(!o){t.debug("Failed to reduce image quality to fit within the maximum size, skipping"),e.imagesFailedToReduceQuality++,e.imagesRemovedDueToSize++;return}return e.imagesWithLoweredQuality++,t.debug("Image quality successfully reduced."),o}}async function Gre(t,e,l){let n=await RSe(l),I=l.length;return!n.width||!n.height?{exceedsSizeLimit:I>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await U_l(t,l),exceedsDimensionLimit:await T_l(e,l)}}async function T_l(t,e){let l=await RSe(e);return!l.width||!l.height?!1:l.width>t||l.height>t}async function U_l(t,e){return e.length>t}async function M_l(t,e,l,n,I){try{if(!HYt(t,I))return[void 0,"unsupported_mime_type"];let r=await RSe(e);if(!r.width||!r.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let a=async(R,w)=>{let C=fYt(e).resize(R,w,{fit:"inside",withoutEnlargement:!0});return ESe(t,await C.toBuffer(),void 0,I)},s=Math.min(l,r.width),o=Math.min(l,r.height),d=await a(s,o);if(d&&d.length<=n)return[d,void 0];let u=Math.max(s,o),G=1,p=u-1,h,W=0,E=10;for(;G<=p&&W<E;){let R=Math.floor((G+p)/2),w=await a(R,R);if(!w)break;let{exceedsSizeLimit:C,exceedsDimensionLimit:k}=await Gre(n,l,w);!C&&!k?(h=w,G=R+1):p=R-1,W++}return[h,void 0]}catch(r){return t.error(`Failed to resize image for upload: ${r instanceof Error?r.message:String(r)}`),[void 0,"unknown"]}}async function __l(t,e,l,n,I){try{let r=I==="image/png"?80:100,a=I==="image/png"?Math.floor(r*.4):20,s=await ESe(t,e,a,I);if(!s||s.length>n)return;let o=a,d=r,u,G=0,p=10,h=o,W=d-1;for(;h<=W&&G<p;){let E=Math.floor((h+W)/2),R=await ESe(t,e,E,I);if(!R)return u;let{exceedsSizeLimit:w,exceedsDimensionLimit:C}=await Gre(n,l,R);!w&&!C?(u=R,h=E+1):W=E-1,G++}return u}catch(r){t.error(`Failed to reduce image quality: ${r instanceof Error?r.message:String(r)}`);return}}async function ESe(t,e,l,n){let I=fYt(e);switch(n){case"image/png":return l?I.png({quality:l}).toBuffer():I.png().toBuffer();case"image/jpeg":return l?I.jpeg({quality:l}).toBuffer():I.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${n}`);return}}var bre=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function D_l(t,e,l,n){if(e<=0)return[];let I=[];for(let r of t){if(r.role!=="user"||I.length>=e)continue;let a=typeof r.content=="string"?r.content:JSON.stringify(r.content),s=B_l(a);if(s)for(let o in s){if(I.length>=e)break;let d=s[o].contents,u=ySe(d,l,!0,n);for(let G of u){if(I.length>=e)break;let p=G.url,h="",W=!1;if(G.kind==="attachment"||G.kind==="legacy_attachment"?I.push(G):J_l(p)?(W=!0,h=x_l(s[o],p,l),I.push({url:h,guid:G.guid,kind:"committed_attachment"})):pre(p)&&p.startsWith(l)&&(W=!0,I.push({...G,kind:"committed_attachment"})),W){let E=I[I.length-1],R=new RegExp(`^${l}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),w=E.url.match(R);if(n.info(`Blob match for ${E.url}: ${JSON.stringify(w)}`),w&&w.length===5){let[,C,k,x,U]=w;E.owner=C,E.repo=k,E.branch=x,E.path=U,n.info(`Repository metadata extracted: owner=${C}, repo=${k}, branch=${x}, path=${U}`)}else n.info(`Failed to extract repository metadata from URL: ${E.url}`)}}}}return I}function z_l(t,e){let l=e.flatMap(I=>ex(I)?I.content.flatMap(r=>r.type==="image_url"?r.image_url.url:[]):[]),n=new Set(l);return t.filter(I=>!n.has(I.url))}var XNe=class{async resolveRepositoryImages(e,l,n,I,r,a){if(l<=0)return[];let s=D_l(e,l,n,I);this.logger.debug(`Found ${s.length} repository image URLs to process`);let o=z_l(s,e),d=await this.processImageReferences(o,r,a);return this.logger.debug(`Processed ${d.addedImages.length} repository image URLs`),d.addedImages}async*preRequest(e){let l=e.modelInfo;if(!l.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!l.capabilities?.supports?.vision||!this.settings.featureFlags?.copilot_swe_agent_vision){this.logger.debug("Vision not supported or enabled, skipping image processing");return}if(!this.gitHubServerUrl){this.logger.debug("GitHub server URL is not set, skipping image processing");return}for(let G of this.messagesToInsertOnNextPreRequest)e.messages.push(G),yield{kind:"message",message:G,turn:e.turn};this.messagesToInsertOnNextPreRequest.splice(0);let n=[],I=l.capabilities.limits.vision?.max_prompt_images??1,r=l.capabilities.limits.vision?.max_prompt_image_size??3145728,a=0,s=[],o=new bre,d=new Map;for(let G of e.messages)if(G.role=="user")if(typeof G.content=="string"){let p=ySe(G.content,this.gitHubServerUrl,!1,this.logger).filter(W=>!this.processedImageUrls.has(W.url)),h=await this.processImageReferences(p,r,o);s.push(...h.addedImages)}else{let p=[];for(let[h,W]of G.content.entries()){if(W.type==="text"){let E=ySe(W.text,this.gitHubServerUrl,!1,this.logger).filter(w=>!this.processedImageUrls.has(w.url)),R=await this.processImageReferences(E,r,o);s.push(...R.addedImages)}else if(W.type==="image_url"){if(W.image_url.url.startsWith("data:")){let[E,R]=await this.extractAndUploadImageData(W,r,o);if(E===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(E),h>=1&&p.length>0){let w=p.at(-1);w&&w.type==="text"&&w.text&&w.text.includes("screenshot")&&d.set(E,VYt(E))}p.pop();continue}a++}p.push(W)}G.content=p}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${I}`);a<I&&s.length>0;){let G=s.shift();if(!G){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(G)){this.logger.debug(`Skipping already processed image url: ${G}`);continue}this.processedImageUrls.add(G);let p=`Here is the image url: ${G}`;d.has(G)&&(p=d.get(G)||p),this.logger.debug(`Adding image url: ${G}`),n.push({role:"user",content:[{type:"text",text:p},{type:"image_url",image_url:{url:G}}]}),a++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),a<I)){let G=await this.resolveRepositoryImages(e.messages,I-a,this.settings.github?.serverUrl||"",this.logger,r,o);this.logger.debug(`Resolved ${G.length} repository image URLs`);for(let p of G){if(a>=I)break;if(this.processedImageUrls.has(p)){this.logger.debug(`Skipping already processed repository image url: ${p}`);continue}n.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:p}}]}),this.processedImageUrls.add(p),a++}}let u={imagesExtractedCount:o.extractedImagesSize.length,base64ImagesCount:o.base64ImagesSize.length,imagesRemovedDueToSize:o.imagesRemovedDueToSize,imagesRemovedDueToDimensions:o.imagesRemovedDueToDimensions,imagesResized:o.imagesResized,imagesResolvedFromGitHubMCPCount:o.imagesResolvedFromGitHubMCPSize.length};for(let G=0;G<o.base64ImagesSize.length;G++)u[`base64ImageSize_${G}`]=o.base64ImagesSize[G];for(let G=0;G<o.resizedBase64ImagesSize.length;G++)u[`resizedBase64ImageSize_${G}`]=o.resizedBase64ImagesSize[G];for(let G=0;G<o.extractedImagesSize.length;G++)u[`extractedImageSize_${G}`]=o.extractedImagesSize[G];for(let G=0;G<o.imagesResolvedFromGitHubMCPSize.length;G++)u[`imagesResolvedFromGitHubMCPSize_${G}`]=o.imagesResolvedFromGitHubMCPSize[G];n.length>0&&this.logger.debug(`Using ${n.length} image messages`);for(let G of n)yield{kind:"message",message:G,turn:e.turn},e.messages.push(G);u.allImagesSendToLlm=e.messages.filter(ex).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:u},e.messages.some(G=>ex(G))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,l,n){let I=R$(this.settings);if(!I)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let r=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!r||r.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let a=r[1];if(!HYt(this.logger,a))return[""];let s=r[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let o=Buffer.from(s,"base64");if(n.base64ImagesSize.push(o.length),o=await HNe(this.logger,n,l,ure,a,o),n.resizedBase64ImagesSize.push(o?.length??-1),!o)return["",new WSe(`Image size exceeds maximum size of ${By(l)}`)];s=o.toString("base64");try{let d=await this.uploadBase64ImageData(s,a,I);return d?(this.logger.debug(`Uploaded image url: ${d}`),e.image_url.url=d,[d]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(d){let u=d instanceof Error?d.message:String(d);return this.logger.debug(`Error during image upload: ${u}`),[""]}}async uploadBase64ImageData(e,l,n){try{let I=nbt(this.settings),r=l.split("/").at(1),a=`image-${Date.now()}.${r}`;if(!e||e.trim()==="")return this.logger.error("Empty image data provided for upload"),null;let s=Buffer.from(e,"base64");if(s.length===0)return this.logger.error("Converted image data has zero length"),null;let o=this.settings.github?.repo?.id;if(!o)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let d=`${I}?name=${encodeURIComponent(a)}&content_type=${encodeURIComponent(l)}&repository_id=${o}`;this.logger.debug(`Uploading image data (${By(s.length)}) to ${I} with name ${encodeURIComponent(a)} and content type ${encodeURIComponent(l)}`);let u={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+n},G=await fetch(d,{method:"POST",headers:u,body:s}).catch(h=>{throw h instanceof Error?(this.logger.error(`Failed to upload image: ${h.message}`),h.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):h.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(h.message.includes("request entity too large")||h.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof h=="object"&&h!==null&&"code"in h&&"message"in h?(this.logger.error(`Failed to upload image: ${h.message}`),h.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):h.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(h.message.includes("request entity too large")||h.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(h)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:h?.code,message:h?.message,stack:h?.stack,name:h?.name,cause:h?.cause},null,2)}`),h});if(!G.ok){let h=await G.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${G.status} ${G.statusText} - ${h}`),null}let p=await G.json();return this.logger.debug(`Upload result: ${JSON.stringify(p,null,2)}`),p.url||null}catch(I){return this.logger.error(`Error handling image upload: ${I instanceof Error?I.message:String(I)}`),I instanceof Error&&I.stack&&this.logger.debug(`Stack trace: ${I.stack}`),null}}async getRepositoryImageViaTools(e){if(this.logger.debug(`Attempting to retrieve repository image: ${e.owner}/${e.repo}/${e.path}@${e.branch}`),this.githubGetFileContentsTool){this.logger.debug(`GitHub MCP tool found, calling with image reference: ${JSON.stringify(e)}`);try{let l=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof l}`),this.logger.debug(`GitHub tool call result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`),typeof l=="object"&&l!==null&&"binaryResultForLlm"in l&&Array.isArray(l.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${l.binaryResultForLlm.length} items`);try{for(let n of l.binaryResultForLlm)if(n.data&&n.mimeType){let I=Buffer.from(n.data,"base64"),r=n.mimeType;return{buffer:I,mimeType:r}}}catch(n){this.logger.error(`Failed to parse GitHub tool response: ${n}`),this.logger.debug(`binaryResultForLlm length: ${l.binaryResultForLlm?.length||0}`)}}else typeof l=="string"?this.logger.debug(`GitHub tool returned string result: ${l}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`)}catch(l){this.logger.error(`Error calling GitHub MCP tool: ${l}`)}}else this.logger.debug("GitHub MCP tool 'github-mcp-server-get_file_contents' not available");return this.logger.debug("Failed to retrieve repository image, returning null"),null}async getImgRefsSmallerThanMaxSize(e,l,n){let I=[],r=await Promise.all(e);for(let{imgRef:a,attachment:s}of r)if(this.logger.debug(`Processing attachment for ${a.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(l.extractedImagesSize.push(s.buffer.length),ri(this.settings,"copilot_swe_agent_resize_image_references")){if(!await HNe(this.logger,l,n,ure,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}I.push(a.url)}else{let o=await Gre(n,ure,s.buffer);if(this.logger.debug(`Image size check for ${a.url}: size=${s.buffer.length}, maxSize=${n}, exceedsSize=${o.exceedsSizeLimit}, exceedsDimensions=${o.exceedsDimensionLimit}`),o.exceedsSizeLimit?(l.imagesRemovedDueToSize++,this.logger.debug(`Image ${a.url} removed due to size (${s.buffer.length} > ${n})`)):o.exceedsDimensionLimit&&(l.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${a.url} removed due to dimensions`)),o.exceedsSizeLimit||o.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 ${By(n)}.`);continue}I.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 I}async processImageReferences(e,l,n){let I=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${I}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let r=e.filter(s=>!this.processedImageUrls.has(s.url)).map(async s=>{if(this.logger.debug(`Processing image reference: ${JSON.stringify(s,null,2)}`),s.kind==="committed_attachment"){this.logger.debug(`Detected repository image - Owner: ${s.owner}, Repo: ${s.repo}, Branch: ${s.branch}, Path: ${s.path}`);let o=await this.getRepositoryImageViaTools(s);return o?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${o.buffer.length} bytes`),n.imagesResolvedFromGitHubMCPSize.push(o.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:o?.buffer?.length||0,mimeType:o?.mimeType||"",buffer:o?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await L_l(s.guid,R$(this.settings),this.logger,this.settings)}}),a=await this.getImgRefsSmallerThanMaxSize(r,n,l);return this.logger.debug(`Processed image references, found ${a.length} attachments smaller than max size of ${By(l)}`),{addedImages:a}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,l,n){this.logger=e,this.settings=l,this.gitHubServerUrl=l.github?.serverUrl,this.githubGetFileContentsTool=n,this.processedImageUrls=new Set,this.messagesToInsertOnNextPreRequest=[]}toJSON(){return"CAPIImageProcessor"}async onRequestError(e){}async preErrorThrow(e){this.processedImageUrls.size>0&&(e.isVisionFlow=!0)}async postToolExecution(e){let l=e.modelInfo,n=e.toolCall.function.name,I=e.toolResult;if(l?.capabilities?.supports?.vision){let r=Array.from(P_l(I,n));if(r.length===0){let a=await q_l(e.toolCall,this.logger);a&&r.push(a)}this.insertImageUrlMessages(r)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let l of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:l.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:l.url}}]})}};function*P_l(t,e){for(let l of t.binaryResultForLlm??[])l.type==="image"&&(yield{url:`data:${l.mimeType};base64,${l.data}`,isScreenshot:e.toLowerCase().includes("screenshot")})}var j_l="playwright-browser_take_screenshot";function K_l(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function q_l(t,e){if(t.function.name!==j_l)return;e.debug("Adding images using Playwright params fallback strategy");let l=JSON.parse(t.function.arguments);if(K_l(l)){let n=mre.isAbsolute(l.filename)?l.filename:mre.join(gSe,l.filename);e.debug(`Image from Playwright params: ${l.filename}. Updated to ${n}.`);let I=await eDl(n,e);if(I){let r=I.buffer.toString("base64");return{url:`data:${I.mimeType};base64,${r}`,isScreenshot:!0}}}}function $_l(t){switch(mre.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function HYt(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 eDl(t,e){try{if(!pre(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let l=$_l(t);return l?{buffer:await k_l.readFile(t),mimeType:l}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(l){return e.error(`Failed to read image from disk: ${l instanceof Error?l.message:String(l)}`),null}}c();var mP=class{latestUserPromptMessage;logger;constructor(e,l){this.latestUserPromptMessage=e,this.logger=l}toJSON(){return"BasicTruncator"}async*preRequest(e){let l=this.latestUserPromptMessage?ZSe(this.latestUserPromptMessage,e.messages):-1,n=[()=>kYt(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit),l===-1?void 0:()=>lDl(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit,l)].filter(a=>a!==void 0),I=0,r;for(;(!r||r.postTruncationTokensInMessages>e.tokenLimit)&&I<n.length;){let a=n[I]();r=tDl(r,a),I++}return r=r??nDl(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit),r.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(r)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:r},r}},GP=class{truncateOnNextRequest=!1;userMessageToTruncateUpTo;logger;constructor(e,l){this.userMessageToTruncateUpTo=e,this.logger=l,this.logger.debug(`AnthropicTokenLimitErrorTruncator will truncate up to message: ${JSON.stringify(e)}`)}async*preRequest(e){if(this.truncateOnNextRequest){this.truncateOnNextRequest=!1;let l=ZSe(this.userMessageToTruncateUpTo,e.messages);if(l===-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 n=kYt(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit,l);n.tokensRemovedDuringTruncation>0&&this.logger.debug(`AnthropicTokenLimitErrorTruncator truncated: ${JSON.stringify(n)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"AnthropicTokenLimitErrorTruncator",truncateResult:n}}}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 l=[JSON.stringify(e)];e instanceof Error&&(l.push(e.message),e.cause instanceof Error?l.push(e.cause.message):e.cause&&l.push(JSON.stringify(e.cause)));let n="Input length and `max_tokens` exceed context limit";this.logger.debug(`Looking for error amongst: ${l.join(", ")}`),l.some(I=>I.includes(n))&&(this.truncateOnNextRequest=!0)}}toJSON(){return"AnthropicTokenLimitErrorTruncator"}};function tDl(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 XYt=.95;function kYt(t,e,l,n,I){let r=t.length;if(r===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:r,postTruncationTokensInMessages:0,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(h=>VM(h,l)),s=aR(JSON.stringify(e),l),o=n*XYt,d=a.reduce((h,W)=>h+W,0)+s;if(d<=o)return{tokenLimit:n,preTruncationTokensInMessages:d,preTruncationMessagesLength:r,postTruncationTokensInMessages:d,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let u=new Set,G=0,p=Math.min(I??t.length,t.length);for(let h=0;h<p;h++){let W=t[h];if(W.role!=="system"&&W.role!=="tool"&&W.role!=="user"){if(W.role==="assistant"){let E=W.tool_calls||[],R=E.filter(oA).filter(x=>x.function.name===Tee),w=E.filter(oA).filter(x=>x.function.name!==Tee),C=R.length===0,k=new Set(w.map(x=>x.id));if(w.length>0&&(W.tool_calls=R,a[h]=VM(W,l)),C&&(u.add(h),G+=a[h]),k.size>0)for(let x=h+1;x<t.length;x++){let U=t[x];if(U.role==="tool"&&k.has(U.tool_call_id)&&(u.add(x),G+=a[x],k.delete(U.tool_call_id),k.size===0))break}}if(d-G<o)break}}for(let h=t.length-1;h>=0;h--)u.has(h)&&t.splice(h,1);return{tokenLimit:n,preTruncationTokensInMessages:d,preTruncationMessagesLength:r,postTruncationTokensInMessages:d-G,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:G,messagesRemovedDuringTruncation:r-t.length}}function lDl(t,e,l,n,I){let r=t.length;if(r===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:r,postTruncationTokensInMessages:0,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(h=>VM(h,l)),s=aR(JSON.stringify(e),l),o=n*XYt,d=a.reduce((h,W)=>h+W,0)+s;if(d<=o)return{tokenLimit:n,preTruncationTokensInMessages:d,preTruncationMessagesLength:r,postTruncationTokensInMessages:d,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let u=new Set,G=0,p=Math.min(I??t.length,t.length);for(let h=0;h<p;h++){let W=t[h];if(W.role!=="system"&&W.role!=="tool"){if(W.role==="user")u.add(h),G+=a[h];else if(W.role==="assistant"){let E=W.tool_calls||[],R=new Set(E.map(w=>w.id));if(u.add(h),G+=a[h],R.size>0)for(let w=h+1;w<t.length;w++){let C=t[w];if(C.role==="tool"&&R.has(C.tool_call_id)&&(u.add(w),G+=a[w],R.delete(C.tool_call_id),R.size===0))break}}if(d-G<o)break}}for(let h=t.length-1;h>=0;h--)u.has(h)&&t.splice(h,1);return{tokenLimit:n,preTruncationTokensInMessages:d,preTruncationMessagesLength:r,postTruncationTokensInMessages:d-G,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:G,messagesRemovedDuringTruncation:r-t.length}}function nDl(t,e,l,n){let I=t.length;if(I===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:I,postTruncationTokensInMessages:0,postTruncationMessagesLength:I,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let r=t.map(o=>VM(o,l)),a=aR(JSON.stringify(e),l),s=r.reduce((o,d)=>o+d,0)+a;return{tokenLimit:n,preTruncationTokensInMessages:s,preTruncationMessagesLength:I,postTruncationTokensInMessages:s,postTruncationMessagesLength:I,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}c();var BA=class extends zH{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,l){}endGroup(e){}};c();c();var LYt={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 kNe(t,e,l){let n=(l||LYt)[t.toLowerCase()],I=new Set;for(;typeof n=="string";){if(I.has(n))return!1;I.add(n),n=LYt[n]}if(!n)return!1;let r=e.toLowerCase();return n.tools.some(a=>a.toolName===r)}var IDl="image";var rDl="resource",aDl=60*1e3*2,sDl={timeout:aDl};var YSe=class{constructor(e,l,n){this.settings=e;this.logger=l;this.permissions=n}async invokeTool(e,l,n="hidden_characters"){let I=await this.doInvokeTool(e,l);return this.invokeToolResponseToToolResult(I,n)}invokeToolResponseToToolResult(e,l){let n=e.content||[],I="",r=[];for(let d of n)if(d.type==="text")I+=d.text||"";else if(d.type==="resource"){let u=d.resource;u&&u.blob?r.push({type:rDl,data:u.blob,mimeType:u.mimeType||"application/octet-stream"}):u&&u.text&&(I+=u.text)}else d.type==="image"&&r.push({type:IDl,data:d.data,mimeType:d.mimeType});let a=I;if(I==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),a=I;else try{let d=JSON.parse(I),u=fxe(d,l);a=JSON.stringify(u)}catch(d){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${d}`),a=Cxe(I,l)}this.logger.debug(`Tool invocation result: ${a}`);let s={},o=a?Rc(a,"output"):"";return e.isToolError?{textResultForLlm:a,resultType:"failure",error:a,sessionLog:o,toolTelemetry:s}:{textResultForLlm:a,binaryResultForLlm:r,resultType:"success",sessionLog:o,toolTelemetry:s}}async loadTools(e){let l=await this.loadToolsFromProvider(e),n={};for(let[I,r]of Object.entries(l)){let a=r.filterMode||"hidden_characters";n[I]={name:r.name,title:r.title||r.name,description:r.description,input_schema:r.input_schema,callback:async s=>{let o=l[I].serverName,d=l[I].name,u=l[I].title;if(!this.permissions.requestRequired)return this.invokeTool(I,s,a);let G=await this.permissions.request({kind:"mcp",serverName:o,toolName:d,toolTitle:u,args:s,readOnly:!!r.readOnly});switch(G.kind){case"approved":return this.invokeTool(I,s,a);case"denied-by-rules":return RZe(G.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return YZe;case"denied-interactively-by-user":return EZe;default:zp(G,`Unhandled permission result kind: ${G}`)}},safeForTelemetry:r.safeForTelemetry}}return Object.values(n)}};var hre=class t extends YSe{toolIdToClientInfo=new Map;constructor(e,l,n={requestRequired:!1}){super(e,l,n)}async doInvokeTool(e,l){let n=this.toolIdToClientInfo.get(e);if(!n)throw new Error(`No MCP client found for tool ID: ${e}`);let I=n.mcpClient,r=t.getToolNameFromIdAndClientName(e,n.clientName),a=await I.callTool({name:r,arguments:l},void 0,{...sDl,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 l={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let n of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(n.name)){this.logger.debug(`Skipping tool ${n.name} for client ${e.clientName}`);continue}let I=t.getToolIdFromClientAndToolName(e.clientName,n.name);this.toolIdToClientInfo.set(I,e);let r;e.safeForTelemetry===!0?r={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?r=e.safeForTelemetry:r={name:kNe(e.clientName,n.name),inputsNames:!1},this.logger.debug(`Adding tool: ${I}`);let a;e.filterMapping===void 0?a="hidden_characters":typeof e.filterMapping=="object"?a=e.filterMapping[n.name]||"hidden_characters":a=e.filterMapping,l[I]={serverName:e.clientName,name:I,title:n.title||n.annotations?.title||n.name,description:n.description||"",input_schema:n.inputSchema,readOnly:n.annotations?.readOnlyHint,safeForTelemetry:r,filterMode:a}}return l}static getToolIdFromClientAndToolName(e,l){return`${e}-${l}`}static getToolNameFromIdAndClientName(e,l){return e.substring(l.length+1)}};c();var LNe=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,l,n,I,r,a){this.settings=e,this.logger=l,this.gitHandler=n,this.location=I,this.commitPriorToCompletionWithTools=r,this.jitInstructions=a||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let l,n=async()=>{if(l===void 0)try{l=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(a){this.logger.error(`Failed to get changed paths, err: ${a}`),l=1}return l},I;for(let[a,s]of Object.entries(this.jitInstructions)){let o=SGt(this.settings,s.percentRemainingOfTimeout);o.isWithin&&(!s.whenNoPathsChanged||await n()===0)&&(!I||o.withinMs<I[0])&&(I=[o.withinMs,s.instruction])}let r=I?.[1];if(typeof r=="function"&&(r=r(this.location)),r&&!this.emittedJitInstructions.has(r)){this.logger.debug(`Adding JIT instructions to the history: ${r}`),this.emittedJitInstructions.add(r);let a={role:"user",content:r};e.messages.push(a),yield{kind:"message",message:a,turn:e.turn,source:"jit-instruction"}}}}},VSe={remindWhereToDoWork:{instruction:wYt,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:fNe.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:fNe.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:fNe.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};c();c();c();var QSe={agent:"sweagent-capi",model:"claude-sonnet-4"},JYt=QSe;function Zre(t){if(!t)return JYt;let[e,...l]=t?.split(":")??[t,void 0],n=l.join(":")||void 0;return{agent:e||void 0,model:n||void 0}}c();c();c();import hft from"path";c();c();c();c();var BNe="4.12.0",tx="04b07795-8ddb-461a-bbee-02f9e1bf7b46",BYt="common",JNe;(function(t){t.AzureChina="https://login.chinacloudapi.cn",t.AzureGermany="https://login.microsoftonline.de",t.AzureGovernment="https://login.microsoftonline.us",t.AzurePublicCloud="https://login.microsoftonline.com"})(JNe||(JNe={}));var gre=JNe.AzurePublicCloud,xYt="login.microsoftonline.com",SYt=["*"],OYt="cae",TYt="nocae",UYt="msal.cache";var wSe;var oDl,xNe,_Yt;function DYt(){return xNe!==void 0&&_Yt!==void 0}function iDl(t){let e={cache:{},broker:{...t.brokerOptions,isEnabled:t.brokerOptions?.enabled??!1,enableMsaPassthrough:t.brokerOptions?.legacyEnableMsaPassthrough??!1}};if(t.tokenCachePersistenceOptions?.enabled){if(wSe===void 0)throw new Error(["Persistent token caching was requested, but no persistence provider was configured.","You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)","and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling","`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`."].join(" "));let l=t.tokenCachePersistenceOptions.name||UYt;e.cache.cachePlugin=wSe({name:`${l}.${TYt}`,...t.tokenCachePersistenceOptions}),e.cache.cachePluginCae=wSe({name:`${l}.${OYt}`,...t.tokenCachePersistenceOptions})}return t.brokerOptions?.enabled&&(e.broker.nativeBrokerPlugin=dDl(t.isVSCodeCredential||!1)),e}var MYt={missing:(t,e,l)=>[`${t} was requested, but no plugin was configured or no authentication record was found.`,`You must install the ${e} plugin package (npm install --save ${e})`,"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",`useIdentityPlugin(${l}) before using enableBroker.`].join(" "),unavailable:(t,e)=>[`${t} was requested, and the plugin is configured, but the broker is unavailable.`,`Ensure the ${t} plugin is properly installed and configured.`,"Check for missing native dependencies and ensure the package is properly installed.",`See the README for prerequisites on installing and using ${e}.`].join(" ")},cDl={vsCode:{credentialName:"Visual Studio Code Credential",packageName:"@azure/identity-vscode",pluginVar:"vsCodePlugin",get brokerInfo(){return _Yt}},native:{credentialName:"Broker for WAM",packageName:"@azure/identity-broker",pluginVar:"nativeBrokerPlugin",get brokerInfo(){return oDl}}};function dDl(t){let{credentialName:e,packageName:l,pluginVar:n,brokerInfo:I}=cDl[t?"vsCode":"native"];if(I===void 0)throw new Error(MYt.missing(e,l,n));if(I.broker.isBrokerAvailable===!1)throw new Error(MYt.unavailable(e,l));return I.broker}var zYt={generatePluginConfiguration:iDl};c();c();c();function uDl(t){return t&&typeof t.error=="string"&&typeof t.error_description=="string"}var jYt="CredentialUnavailableError",Pn=class extends Error{constructor(e,l){super(e,l),this.name=jYt}},SNe="AuthenticationError",T5=class extends Error{statusCode;errorResponse;constructor(e,l,n){let I={error:"unknown",errorDescription:"An unknown error occurred and no additional details are available."};if(uDl(l))I=PYt(l);else if(typeof l=="string")try{let r=JSON.parse(l);I=PYt(r)}catch{e===400?I={error:"invalid_request",errorDescription:`The service indicated that the request was invalid.
1627
+ `)?.trim();return{...t,reasoning_text:e}}function dre(t){return structuredClone(t)}function CYt(t){return{...t,choices:t.choices.map(e=>{let l=uP(e.message);return{delta:{role:l.role,content:l.content,reasoning_opaque:l.reasoning_opaque,reasoning_text:l.reasoning_text,tool_calls:e.message.tool_calls?.map(n=>({...n,index:0}))},finish_reason:e.finish_reason,index:e.index}}),object:"chat.completion.chunk"}}function ex(t){return t.role==="user"&&Array.isArray(t.content)&&t.content.some(e=>e.type==="image_url")}function ZSe(t,e){let l=e.indexOf(t);if(l!==-1)return l;let n=s=>(typeof s.content=="string"?[{type:"text",text:s.content}]:s.content).filter(o=>o.type==="text").map(o=>o.text).join("").trim(),I=n(t),r=e.map((s,o)=>s.role==="user"&&n(s)===I?o:-1).filter(s=>s!==-1),a=r.at(0)??-1;return r.length===1?a:-1}c();var gSe="/tmp/playwright-logs",X_l="0.0.40",NSe=[`@playwright/mcp@${X_l}`,"--viewport-size","1280, 720","--output-dir",gSe],zcr=[...NSe,"--isolated"];var WSe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},ure=2e3;async function L_l(t,e,l,n){let I={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},r=`${Ibt(n)}/${t}`;l.info(`Downloading image from ${r}`);try{let a=await fetch(r,{method:"GET",headers:I});if(l.info(`Response status: ${a.status} ${a.statusText}`),l.debug(`Download Response URL: ${a.url}`),!a.ok){l.info(`Failed to download image, status: ${a.status}, statusText: ${a.statusText}`);try{let p=await a.text();l.info(`Error response body: ${p}`)}catch(p){l.info(`Could not read error response body: ${p}`)}return{size:0}}let o=(await a.json()).url;if(!o)return l.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let d=await fetch(o,{method:"GET"});if(!d.ok)return l.error(`Failed to download image: ${d.status} ${d.statusText}`),{size:0};let u=await d.arrayBuffer(),G=u.byteLength;return l.info(`Downloaded content size: ${By(G)}`),{size:G,buffer:Buffer.from(u),mimeType:d.headers.get("content-type")||void 0}}catch(a){return l.error("Network error downloading image"),a instanceof Error&&(l.info(`Error message: ${a.message}`),l.info(`Error stack: ${a.stack}`)),{size:0}}}function ySe(t,e,l,n){let I=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,r=/!\[.*?\]\((.*?)\)/g,a=[];return a.push(...vYt(t,e,I,l,n)),a.push(...vYt(t,e,r,l,n)),a}function vYt(t,e,l,n,I){let r=t.matchAll(l),a=[],s=/\/([a-f0-9-]+)$/;for(let o of r){let d=S_l(o[1],e),u=O_l(o[1],e,I);if(d||u){let G=o[1].match(s),p={url:o[1],guid:"",kind:u?"legacy_attachment":"attachment"};G&&G.length>1&&(p.guid=G[1]),a.push(p)}else if(n){let G={url:o[1],guid:"",kind:"committed_attachment"};a.push(G)}}return a}function J_l(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&pre(t)}function pre(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function B_l(t){try{let e=/Here are relevant code snippets from the repository that might help with this task:\s*(\[[\s\S]*?\])(?=\n|$)/,l=t.match(e);if(!l?.[1]||l[1].length<=1)return null;let n=l[1].trim();return JSON.parse(n)}catch{return null}}function x_l(t,e,l){if(!t?.url||!t?.ref||!t?.path)throw new Error("Invalid repository insight: missing required fields");if(!e||e.trim()==="")throw new Error("Invalid image path: path cannot be empty");let n=t.url.split("/").slice(3,5).join("/"),I=t.ref.split("/")[2],r;if(e.startsWith("/"))r=e.slice(1);else{let s=t.path,o=mre.dirname(s);r=mre.resolve("/",o,e).slice(1)}return`${l}/${n}/blob/${I}/${r}`}function S_l(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function O_l(t,e,l){return e&&new RegExp(`^${e}/[\\w.-]+/[\\w.-]+/assets/\\d+/[^.]+$`).test(t)?(l.debug(`Legacy GitHub asset URL detected: ${t}`),!0):!1}async function RSe(t){let{width:e,height:l}=g2t(t);if(e===void 0||l===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:l}}async function HNe(t,e,l,n,I,r){t.debug(`Checking if image is valid size and dimensions. Max size: ${l}, Max dimension: ${n}`);let{exceedsSizeLimit:a,exceedsDimensionLimit:s}=await Gre(l,n,r);if(!s&&!a)return t.debug("Image is within size and dimension limits."),r;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${n}, attempting to resize`);let[o,d]=await M_l(t,r,n,l,I);if(!o){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,d==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:u}=await Gre(l,n,o);if(u){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),o}if(a){t.debug(`Image size ${By(r.length)} is larger than the maximum size of ${By(l)}, attempting to reduce image quality`);let o=await __l(t,r,n,l,I);if(!o){t.debug("Failed to reduce image quality to fit within the maximum size, skipping"),e.imagesFailedToReduceQuality++,e.imagesRemovedDueToSize++;return}return e.imagesWithLoweredQuality++,t.debug("Image quality successfully reduced."),o}}async function Gre(t,e,l){let n=await RSe(l),I=l.length;return!n.width||!n.height?{exceedsSizeLimit:I>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await U_l(t,l),exceedsDimensionLimit:await T_l(e,l)}}async function T_l(t,e){let l=await RSe(e);return!l.width||!l.height?!1:l.width>t||l.height>t}async function U_l(t,e){return e.length>t}async function M_l(t,e,l,n,I){try{if(!HYt(t,I))return[void 0,"unsupported_mime_type"];let r=await RSe(e);if(!r.width||!r.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let a=async(R,w)=>{let C=fYt(e).resize(R,w,{fit:"inside",withoutEnlargement:!0});return ESe(t,await C.toBuffer(),void 0,I)},s=Math.min(l,r.width),o=Math.min(l,r.height),d=await a(s,o);if(d&&d.length<=n)return[d,void 0];let u=Math.max(s,o),G=1,p=u-1,h,W=0,E=10;for(;G<=p&&W<E;){let R=Math.floor((G+p)/2),w=await a(R,R);if(!w)break;let{exceedsSizeLimit:C,exceedsDimensionLimit:k}=await Gre(n,l,w);!C&&!k?(h=w,G=R+1):p=R-1,W++}return[h,void 0]}catch(r){return t.error(`Failed to resize image for upload: ${r instanceof Error?r.message:String(r)}`),[void 0,"unknown"]}}async function __l(t,e,l,n,I){try{let r=I==="image/png"?80:100,a=I==="image/png"?Math.floor(r*.4):20,s=await ESe(t,e,a,I);if(!s||s.length>n)return;let o=a,d=r,u,G=0,p=10,h=o,W=d-1;for(;h<=W&&G<p;){let E=Math.floor((h+W)/2),R=await ESe(t,e,E,I);if(!R)return u;let{exceedsSizeLimit:w,exceedsDimensionLimit:C}=await Gre(n,l,R);!w&&!C?(u=R,h=E+1):W=E-1,G++}return u}catch(r){t.error(`Failed to reduce image quality: ${r instanceof Error?r.message:String(r)}`);return}}async function ESe(t,e,l,n){let I=fYt(e);switch(n){case"image/png":return l?I.png({quality:l}).toBuffer():I.png().toBuffer();case"image/jpeg":return l?I.jpeg({quality:l}).toBuffer():I.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${n}`);return}}var bre=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function D_l(t,e,l,n){if(e<=0)return[];let I=[];for(let r of t){if(r.role!=="user"||I.length>=e)continue;let a=typeof r.content=="string"?r.content:JSON.stringify(r.content),s=B_l(a);if(s)for(let o in s){if(I.length>=e)break;let d=s[o].contents,u=ySe(d,l,!0,n);for(let G of u){if(I.length>=e)break;let p=G.url,h="",W=!1;if(G.kind==="attachment"||G.kind==="legacy_attachment"?I.push(G):J_l(p)?(W=!0,h=x_l(s[o],p,l),I.push({url:h,guid:G.guid,kind:"committed_attachment"})):pre(p)&&p.startsWith(l)&&(W=!0,I.push({...G,kind:"committed_attachment"})),W){let E=I[I.length-1],R=new RegExp(`^${l}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),w=E.url.match(R);if(n.info(`Blob match for ${E.url}: ${JSON.stringify(w)}`),w&&w.length===5){let[,C,k,x,U]=w;E.owner=C,E.repo=k,E.branch=x,E.path=U,n.info(`Repository metadata extracted: owner=${C}, repo=${k}, branch=${x}, path=${U}`)}else n.info(`Failed to extract repository metadata from URL: ${E.url}`)}}}}return I}function z_l(t,e){let l=e.flatMap(I=>ex(I)?I.content.flatMap(r=>r.type==="image_url"?r.image_url.url:[]):[]),n=new Set(l);return t.filter(I=>!n.has(I.url))}var XNe=class{async resolveRepositoryImages(e,l,n,I,r,a){if(l<=0)return[];let s=D_l(e,l,n,I);this.logger.debug(`Found ${s.length} repository image URLs to process`);let o=z_l(s,e),d=await this.processImageReferences(o,r,a);return this.logger.debug(`Processed ${d.addedImages.length} repository image URLs`),d.addedImages}async*preRequest(e){let l=e.modelInfo;if(!l.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!l.capabilities?.supports?.vision||!this.settings.featureFlags?.copilot_swe_agent_vision){this.logger.debug("Vision not supported or enabled, skipping image processing");return}if(!this.gitHubServerUrl){this.logger.debug("GitHub server URL is not set, skipping image processing");return}for(let G of this.messagesToInsertOnNextPreRequest)e.messages.push(G),yield{kind:"message",message:G,turn:e.turn};this.messagesToInsertOnNextPreRequest.splice(0);let n=[],I=l.capabilities.limits.vision?.max_prompt_images??1,r=l.capabilities.limits.vision?.max_prompt_image_size??3145728,a=0,s=[],o=new bre,d=new Map;for(let G of e.messages)if(G.role=="user")if(typeof G.content=="string"){let p=ySe(G.content,this.gitHubServerUrl,!1,this.logger).filter(W=>!this.processedImageUrls.has(W.url)),h=await this.processImageReferences(p,r,o);s.push(...h.addedImages)}else{let p=[];for(let[h,W]of G.content.entries()){if(W.type==="text"){let E=ySe(W.text,this.gitHubServerUrl,!1,this.logger).filter(w=>!this.processedImageUrls.has(w.url)),R=await this.processImageReferences(E,r,o);s.push(...R.addedImages)}else if(W.type==="image_url"){if(W.image_url.url.startsWith("data:")){let[E,R]=await this.extractAndUploadImageData(W,r,o);if(E===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(E),h>=1&&p.length>0){let w=p.at(-1);w&&w.type==="text"&&w.text&&w.text.includes("screenshot")&&d.set(E,VYt(E))}p.pop();continue}a++}p.push(W)}G.content=p}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${I}`);a<I&&s.length>0;){let G=s.shift();if(!G){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(G)){this.logger.debug(`Skipping already processed image url: ${G}`);continue}this.processedImageUrls.add(G);let p=`Here is the image url: ${G}`;d.has(G)&&(p=d.get(G)||p),this.logger.debug(`Adding image url: ${G}`),n.push({role:"user",content:[{type:"text",text:p},{type:"image_url",image_url:{url:G}}]}),a++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),a<I)){let G=await this.resolveRepositoryImages(e.messages,I-a,this.settings.github?.serverUrl||"",this.logger,r,o);this.logger.debug(`Resolved ${G.length} repository image URLs`);for(let p of G){if(a>=I)break;if(this.processedImageUrls.has(p)){this.logger.debug(`Skipping already processed repository image url: ${p}`);continue}n.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:p}}]}),this.processedImageUrls.add(p),a++}}let u={imagesExtractedCount:o.extractedImagesSize.length,base64ImagesCount:o.base64ImagesSize.length,imagesRemovedDueToSize:o.imagesRemovedDueToSize,imagesRemovedDueToDimensions:o.imagesRemovedDueToDimensions,imagesResized:o.imagesResized,imagesResolvedFromGitHubMCPCount:o.imagesResolvedFromGitHubMCPSize.length};for(let G=0;G<o.base64ImagesSize.length;G++)u[`base64ImageSize_${G}`]=o.base64ImagesSize[G];for(let G=0;G<o.resizedBase64ImagesSize.length;G++)u[`resizedBase64ImageSize_${G}`]=o.resizedBase64ImagesSize[G];for(let G=0;G<o.extractedImagesSize.length;G++)u[`extractedImageSize_${G}`]=o.extractedImagesSize[G];for(let G=0;G<o.imagesResolvedFromGitHubMCPSize.length;G++)u[`imagesResolvedFromGitHubMCPSize_${G}`]=o.imagesResolvedFromGitHubMCPSize[G];n.length>0&&this.logger.debug(`Using ${n.length} image messages`);for(let G of n)yield{kind:"message",message:G,turn:e.turn},e.messages.push(G);u.allImagesSendToLlm=e.messages.filter(ex).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:u},e.messages.some(G=>ex(G))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,l,n){let I=R$(this.settings);if(!I)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let r=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!r||r.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let a=r[1];if(!HYt(this.logger,a))return[""];let s=r[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let o=Buffer.from(s,"base64");if(n.base64ImagesSize.push(o.length),o=await HNe(this.logger,n,l,ure,a,o),n.resizedBase64ImagesSize.push(o?.length??-1),!o)return["",new WSe(`Image size exceeds maximum size of ${By(l)}`)];s=o.toString("base64");try{let d=await this.uploadBase64ImageData(s,a,I);return d?(this.logger.debug(`Uploaded image url: ${d}`),e.image_url.url=d,[d]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(d){let u=d instanceof Error?d.message:String(d);return this.logger.debug(`Error during image upload: ${u}`),[""]}}async uploadBase64ImageData(e,l,n){try{let I=nbt(this.settings),r=l.split("/").at(1),a=`image-${Date.now()}.${r}`;if(!e||e.trim()==="")return this.logger.error("Empty image data provided for upload"),null;let s=Buffer.from(e,"base64");if(s.length===0)return this.logger.error("Converted image data has zero length"),null;let o=this.settings.github?.repo?.id;if(!o)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let d=`${I}?name=${encodeURIComponent(a)}&content_type=${encodeURIComponent(l)}&repository_id=${o}`;this.logger.debug(`Uploading image data (${By(s.length)}) to ${I} with name ${encodeURIComponent(a)} and content type ${encodeURIComponent(l)}`);let u={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+n},G=await fetch(d,{method:"POST",headers:u,body:s}).catch(h=>{throw h instanceof Error?(this.logger.error(`Failed to upload image: ${h.message}`),h.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):h.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(h.message.includes("request entity too large")||h.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof h=="object"&&h!==null&&"code"in h&&"message"in h?(this.logger.error(`Failed to upload image: ${h.message}`),h.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):h.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(h.message.includes("request entity too large")||h.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(h)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:h?.code,message:h?.message,stack:h?.stack,name:h?.name,cause:h?.cause},null,2)}`),h});if(!G.ok){let h=await G.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${G.status} ${G.statusText} - ${h}`),null}let p=await G.json();return this.logger.debug(`Upload result: ${JSON.stringify(p,null,2)}`),p.url||null}catch(I){return this.logger.error(`Error handling image upload: ${I instanceof Error?I.message:String(I)}`),I instanceof Error&&I.stack&&this.logger.debug(`Stack trace: ${I.stack}`),null}}async getRepositoryImageViaTools(e){if(this.logger.debug(`Attempting to retrieve repository image: ${e.owner}/${e.repo}/${e.path}@${e.branch}`),this.githubGetFileContentsTool){this.logger.debug(`GitHub MCP tool found, calling with image reference: ${JSON.stringify(e)}`);try{let l=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof l}`),this.logger.debug(`GitHub tool call result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`),typeof l=="object"&&l!==null&&"binaryResultForLlm"in l&&Array.isArray(l.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${l.binaryResultForLlm.length} items`);try{for(let n of l.binaryResultForLlm)if(n.data&&n.mimeType){let I=Buffer.from(n.data,"base64"),r=n.mimeType;return{buffer:I,mimeType:r}}}catch(n){this.logger.error(`Failed to parse GitHub tool response: ${n}`),this.logger.debug(`binaryResultForLlm length: ${l.binaryResultForLlm?.length||0}`)}}else typeof l=="string"?this.logger.debug(`GitHub tool returned string result: ${l}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`)}catch(l){this.logger.error(`Error calling GitHub MCP tool: ${l}`)}}else this.logger.debug("GitHub MCP tool 'github-mcp-server-get_file_contents' not available");return this.logger.debug("Failed to retrieve repository image, returning null"),null}async getImgRefsSmallerThanMaxSize(e,l,n){let I=[],r=await Promise.all(e);for(let{imgRef:a,attachment:s}of r)if(this.logger.debug(`Processing attachment for ${a.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(l.extractedImagesSize.push(s.buffer.length),ri(this.settings,"copilot_swe_agent_resize_image_references")){if(!await HNe(this.logger,l,n,ure,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}I.push(a.url)}else{let o=await Gre(n,ure,s.buffer);if(this.logger.debug(`Image size check for ${a.url}: size=${s.buffer.length}, maxSize=${n}, exceedsSize=${o.exceedsSizeLimit}, exceedsDimensions=${o.exceedsDimensionLimit}`),o.exceedsSizeLimit?(l.imagesRemovedDueToSize++,this.logger.debug(`Image ${a.url} removed due to size (${s.buffer.length} > ${n})`)):o.exceedsDimensionLimit&&(l.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${a.url} removed due to dimensions`)),o.exceedsSizeLimit||o.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 ${By(n)}.`);continue}I.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 I}async processImageReferences(e,l,n){let I=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${I}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let r=e.filter(s=>!this.processedImageUrls.has(s.url)).map(async s=>{if(this.logger.debug(`Processing image reference: ${JSON.stringify(s,null,2)}`),s.kind==="committed_attachment"){this.logger.debug(`Detected repository image - Owner: ${s.owner}, Repo: ${s.repo}, Branch: ${s.branch}, Path: ${s.path}`);let o=await this.getRepositoryImageViaTools(s);return o?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${o.buffer.length} bytes`),n.imagesResolvedFromGitHubMCPSize.push(o.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:o?.buffer?.length||0,mimeType:o?.mimeType||"",buffer:o?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await L_l(s.guid,R$(this.settings),this.logger,this.settings)}}),a=await this.getImgRefsSmallerThanMaxSize(r,n,l);return this.logger.debug(`Processed image references, found ${a.length} attachments smaller than max size of ${By(l)}`),{addedImages:a}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,l,n){this.logger=e,this.settings=l,this.gitHubServerUrl=l.github?.serverUrl,this.githubGetFileContentsTool=n,this.processedImageUrls=new Set,this.messagesToInsertOnNextPreRequest=[]}toJSON(){return"CAPIImageProcessor"}async onRequestError(e){}async preErrorThrow(e){this.processedImageUrls.size>0&&(e.isVisionFlow=!0)}async postToolExecution(e){let l=e.modelInfo,n=e.toolCall.function.name,I=e.toolResult;if(l?.capabilities?.supports?.vision){let r=Array.from(P_l(I,n));if(r.length===0){let a=await q_l(e.toolCall,this.logger);a&&r.push(a)}this.insertImageUrlMessages(r)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let l of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:l.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:l.url}}]})}};function*P_l(t,e){for(let l of t.binaryResultForLlm??[])l.type==="image"&&(yield{url:`data:${l.mimeType};base64,${l.data}`,isScreenshot:e.toLowerCase().includes("screenshot")})}var j_l="playwright-browser_take_screenshot";function K_l(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function q_l(t,e){if(t.function.name!==j_l)return;e.debug("Adding images using Playwright params fallback strategy");let l=JSON.parse(t.function.arguments);if(K_l(l)){let n=mre.isAbsolute(l.filename)?l.filename:mre.join(gSe,l.filename);e.debug(`Image from Playwright params: ${l.filename}. Updated to ${n}.`);let I=await eDl(n,e);if(I){let r=I.buffer.toString("base64");return{url:`data:${I.mimeType};base64,${r}`,isScreenshot:!0}}}}function $_l(t){switch(mre.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function HYt(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 eDl(t,e){try{if(!pre(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let l=$_l(t);return l?{buffer:await k_l.readFile(t),mimeType:l}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(l){return e.error(`Failed to read image from disk: ${l instanceof Error?l.message:String(l)}`),null}}c();var mP=class{latestUserPromptMessage;logger;constructor(e,l){this.latestUserPromptMessage=e,this.logger=l}toJSON(){return"BasicTruncator"}async*preRequest(e){let l=this.latestUserPromptMessage?ZSe(this.latestUserPromptMessage,e.messages):-1,n=[()=>kYt(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit),l===-1?void 0:()=>lDl(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit,l)].filter(a=>a!==void 0),I=0,r;for(;(!r||r.postTruncationTokensInMessages>e.tokenLimit)&&I<n.length;){let a=n[I]();r=tDl(r,a),I++}return r=r??nDl(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit),r.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(r)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:r},r}},GP=class{truncateOnNextRequest=!1;userMessageToTruncateUpTo;logger;constructor(e,l){this.userMessageToTruncateUpTo=e,this.logger=l,this.logger.debug(`AnthropicTokenLimitErrorTruncator will truncate up to message: ${JSON.stringify(e)}`)}async*preRequest(e){if(this.truncateOnNextRequest){this.truncateOnNextRequest=!1;let l=ZSe(this.userMessageToTruncateUpTo,e.messages);if(l===-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 n=kYt(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit,l);n.tokensRemovedDuringTruncation>0&&this.logger.debug(`AnthropicTokenLimitErrorTruncator truncated: ${JSON.stringify(n)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"AnthropicTokenLimitErrorTruncator",truncateResult:n}}}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 l=[JSON.stringify(e)];e instanceof Error&&(l.push(e.message),e.cause instanceof Error?l.push(e.cause.message):e.cause&&l.push(JSON.stringify(e.cause)));let n="Input length and `max_tokens` exceed context limit";this.logger.debug(`Looking for error amongst: ${l.join(", ")}`),l.some(I=>I.includes(n))&&(this.truncateOnNextRequest=!0)}}toJSON(){return"AnthropicTokenLimitErrorTruncator"}};function tDl(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 XYt=.95;function kYt(t,e,l,n,I){let r=t.length;if(r===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:r,postTruncationTokensInMessages:0,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(h=>VM(h,l)),s=aR(JSON.stringify(e),l),o=n*XYt,d=a.reduce((h,W)=>h+W,0)+s;if(d<=o)return{tokenLimit:n,preTruncationTokensInMessages:d,preTruncationMessagesLength:r,postTruncationTokensInMessages:d,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let u=new Set,G=0,p=Math.min(I??t.length,t.length);for(let h=0;h<p;h++){let W=t[h];if(W.role!=="system"&&W.role!=="tool"&&W.role!=="user"){if(W.role==="assistant"){let E=W.tool_calls||[],R=E.filter(oA).filter(x=>x.function.name===Tee),w=E.filter(oA).filter(x=>x.function.name!==Tee),C=R.length===0,k=new Set(w.map(x=>x.id));if(w.length>0&&(W.tool_calls=R,a[h]=VM(W,l)),C&&(u.add(h),G+=a[h]),k.size>0)for(let x=h+1;x<t.length;x++){let U=t[x];if(U.role==="tool"&&k.has(U.tool_call_id)&&(u.add(x),G+=a[x],k.delete(U.tool_call_id),k.size===0))break}}if(d-G<o)break}}for(let h=t.length-1;h>=0;h--)u.has(h)&&t.splice(h,1);return{tokenLimit:n,preTruncationTokensInMessages:d,preTruncationMessagesLength:r,postTruncationTokensInMessages:d-G,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:G,messagesRemovedDuringTruncation:r-t.length}}function lDl(t,e,l,n,I){let r=t.length;if(r===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:r,postTruncationTokensInMessages:0,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(h=>VM(h,l)),s=aR(JSON.stringify(e),l),o=n*XYt,d=a.reduce((h,W)=>h+W,0)+s;if(d<=o)return{tokenLimit:n,preTruncationTokensInMessages:d,preTruncationMessagesLength:r,postTruncationTokensInMessages:d,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let u=new Set,G=0,p=Math.min(I??t.length,t.length);for(let h=0;h<p;h++){let W=t[h];if(W.role!=="system"&&W.role!=="tool"){if(W.role==="user")u.add(h),G+=a[h];else if(W.role==="assistant"){let E=W.tool_calls||[],R=new Set(E.map(w=>w.id));if(u.add(h),G+=a[h],R.size>0)for(let w=h+1;w<t.length;w++){let C=t[w];if(C.role==="tool"&&R.has(C.tool_call_id)&&(u.add(w),G+=a[w],R.delete(C.tool_call_id),R.size===0))break}}if(d-G<o)break}}for(let h=t.length-1;h>=0;h--)u.has(h)&&t.splice(h,1);return{tokenLimit:n,preTruncationTokensInMessages:d,preTruncationMessagesLength:r,postTruncationTokensInMessages:d-G,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:G,messagesRemovedDuringTruncation:r-t.length}}function nDl(t,e,l,n){let I=t.length;if(I===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:I,postTruncationTokensInMessages:0,postTruncationMessagesLength:I,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let r=t.map(o=>VM(o,l)),a=aR(JSON.stringify(e),l),s=r.reduce((o,d)=>o+d,0)+a;return{tokenLimit:n,preTruncationTokensInMessages:s,preTruncationMessagesLength:I,postTruncationTokensInMessages:s,postTruncationMessagesLength:I,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}c();var BA=class extends zH{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,l){}endGroup(e){}};c();c();var LYt={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 kNe(t,e,l){let n=(l||LYt)[t.toLowerCase()],I=new Set;for(;typeof n=="string";){if(I.has(n))return!1;I.add(n),n=LYt[n]}if(!n)return!1;let r=e.toLowerCase();return n.tools.some(a=>a.toolName===r)}var IDl="image";var rDl="resource",aDl=60*1e3*2,sDl={timeout:aDl};var YSe=class{constructor(e,l,n){this.settings=e;this.logger=l;this.permissions=n}async invokeTool(e,l,n="hidden_characters"){let I=await this.doInvokeTool(e,l);return this.invokeToolResponseToToolResult(I,n)}invokeToolResponseToToolResult(e,l){let n=e.content||[],I="",r=[];for(let d of n)if(d.type==="text")I+=d.text||"";else if(d.type==="resource"){let u=d.resource;u&&u.blob?r.push({type:rDl,data:u.blob,mimeType:u.mimeType||"application/octet-stream"}):u&&u.text&&(I+=u.text)}else d.type==="image"&&r.push({type:IDl,data:d.data,mimeType:d.mimeType});let a=I;if(I==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),a=I;else try{let d=JSON.parse(I),u=fxe(d,l);a=JSON.stringify(u)}catch(d){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${d}`),a=Cxe(I,l)}this.logger.debug(`Tool invocation result: ${a}`);let s={},o=a?Rc(a,"output"):"";return e.isToolError?{textResultForLlm:a,resultType:"failure",error:a,sessionLog:o,toolTelemetry:s}:{textResultForLlm:a,binaryResultForLlm:r,resultType:"success",sessionLog:o,toolTelemetry:s}}async loadTools(e){let l=await this.loadToolsFromProvider(e),n={};for(let[I,r]of Object.entries(l)){let a=r.filterMode||"hidden_characters";n[I]={name:r.name,namespacedName:r.namespacedName,title:r.title||r.name,description:r.description,input_schema:r.input_schema,callback:async s=>{let o=l[I].serverName,d=l[I].name,u=l[I].title;if(!this.permissions.requestRequired)return this.invokeTool(I,s,a);let G=await this.permissions.request({kind:"mcp",serverName:o,toolName:d,toolTitle:u,args:s,readOnly:!!r.readOnly});switch(G.kind){case"approved":return this.invokeTool(I,s,a);case"denied-by-rules":return RZe(G.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return YZe;case"denied-interactively-by-user":return EZe;default:zp(G,`Unhandled permission result kind: ${G}`)}},safeForTelemetry:r.safeForTelemetry}}return Object.values(n)}};var hre=class t extends YSe{toolIdToClientInfo=new Map;constructor(e,l,n={requestRequired:!1}){super(e,l,n)}async doInvokeTool(e,l){let n=this.toolIdToClientInfo.get(e);if(!n)throw new Error(`No MCP client found for tool ID: ${e}`);let I=n.mcpClient,r=t.getToolNameFromIdAndClientName(e,n.clientName),a=await I.callTool({name:r,arguments:l},void 0,{...sDl,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 l={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let n of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(n.name)){this.logger.debug(`Skipping tool ${n.name} for client ${e.clientName}`);continue}let I=t.getToolIdFromClientAndToolName(e.clientName,n.name);this.toolIdToClientInfo.set(I,e);let r;e.safeForTelemetry===!0?r={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?r=e.safeForTelemetry:r={name:kNe(e.clientName,n.name),inputsNames:!1},this.logger.debug(`Adding tool: ${I}`);let a;e.filterMapping===void 0?a="hidden_characters":typeof e.filterMapping=="object"?a=e.filterMapping[n.name]||"hidden_characters":a=e.filterMapping,l[I]={serverName:e.clientName,name:I,namespacedName:`${e.clientName}/${n.name}`,title:n.title||n.annotations?.title||n.name,description:n.description||"",input_schema:n.inputSchema,readOnly:n.annotations?.readOnlyHint,safeForTelemetry:r,filterMode:a}}return l}static getToolIdFromClientAndToolName(e,l){return`${e}-${l}`}static getToolNameFromIdAndClientName(e,l){return e.substring(l.length+1)}};c();var LNe=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,l,n,I,r,a){this.settings=e,this.logger=l,this.gitHandler=n,this.location=I,this.commitPriorToCompletionWithTools=r,this.jitInstructions=a||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let l,n=async()=>{if(l===void 0)try{l=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(a){this.logger.error(`Failed to get changed paths, err: ${a}`),l=1}return l},I;for(let[a,s]of Object.entries(this.jitInstructions)){let o=SGt(this.settings,s.percentRemainingOfTimeout);o.isWithin&&(!s.whenNoPathsChanged||await n()===0)&&(!I||o.withinMs<I[0])&&(I=[o.withinMs,s.instruction])}let r=I?.[1];if(typeof r=="function"&&(r=r(this.location)),r&&!this.emittedJitInstructions.has(r)){this.logger.debug(`Adding JIT instructions to the history: ${r}`),this.emittedJitInstructions.add(r);let a={role:"user",content:r};e.messages.push(a),yield{kind:"message",message:a,turn:e.turn,source:"jit-instruction"}}}}},VSe={remindWhereToDoWork:{instruction:wYt,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:fNe.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:fNe.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:fNe.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};c();c();c();var QSe={agent:"sweagent-capi",model:"claude-sonnet-4"},JYt=QSe;function Zre(t){if(!t)return JYt;let[e,...l]=t?.split(":")??[t,void 0],n=l.join(":")||void 0;return{agent:e||void 0,model:n||void 0}}c();c();c();import hft from"path";c();c();c();c();var BNe="4.12.0",tx="04b07795-8ddb-461a-bbee-02f9e1bf7b46",BYt="common",JNe;(function(t){t.AzureChina="https://login.chinacloudapi.cn",t.AzureGermany="https://login.microsoftonline.de",t.AzureGovernment="https://login.microsoftonline.us",t.AzurePublicCloud="https://login.microsoftonline.com"})(JNe||(JNe={}));var gre=JNe.AzurePublicCloud,xYt="login.microsoftonline.com",SYt=["*"],OYt="cae",TYt="nocae",UYt="msal.cache";var wSe;var oDl,xNe,_Yt;function DYt(){return xNe!==void 0&&_Yt!==void 0}function iDl(t){let e={cache:{},broker:{...t.brokerOptions,isEnabled:t.brokerOptions?.enabled??!1,enableMsaPassthrough:t.brokerOptions?.legacyEnableMsaPassthrough??!1}};if(t.tokenCachePersistenceOptions?.enabled){if(wSe===void 0)throw new Error(["Persistent token caching was requested, but no persistence provider was configured.","You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)","and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling","`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`."].join(" "));let l=t.tokenCachePersistenceOptions.name||UYt;e.cache.cachePlugin=wSe({name:`${l}.${TYt}`,...t.tokenCachePersistenceOptions}),e.cache.cachePluginCae=wSe({name:`${l}.${OYt}`,...t.tokenCachePersistenceOptions})}return t.brokerOptions?.enabled&&(e.broker.nativeBrokerPlugin=dDl(t.isVSCodeCredential||!1)),e}var MYt={missing:(t,e,l)=>[`${t} was requested, but no plugin was configured or no authentication record was found.`,`You must install the ${e} plugin package (npm install --save ${e})`,"and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling",`useIdentityPlugin(${l}) before using enableBroker.`].join(" "),unavailable:(t,e)=>[`${t} was requested, and the plugin is configured, but the broker is unavailable.`,`Ensure the ${t} plugin is properly installed and configured.`,"Check for missing native dependencies and ensure the package is properly installed.",`See the README for prerequisites on installing and using ${e}.`].join(" ")},cDl={vsCode:{credentialName:"Visual Studio Code Credential",packageName:"@azure/identity-vscode",pluginVar:"vsCodePlugin",get brokerInfo(){return _Yt}},native:{credentialName:"Broker for WAM",packageName:"@azure/identity-broker",pluginVar:"nativeBrokerPlugin",get brokerInfo(){return oDl}}};function dDl(t){let{credentialName:e,packageName:l,pluginVar:n,brokerInfo:I}=cDl[t?"vsCode":"native"];if(I===void 0)throw new Error(MYt.missing(e,l,n));if(I.broker.isBrokerAvailable===!1)throw new Error(MYt.unavailable(e,l));return I.broker}var zYt={generatePluginConfiguration:iDl};c();c();c();function uDl(t){return t&&typeof t.error=="string"&&typeof t.error_description=="string"}var jYt="CredentialUnavailableError",Pn=class extends Error{constructor(e,l){super(e,l),this.name=jYt}},SNe="AuthenticationError",T5=class extends Error{statusCode;errorResponse;constructor(e,l,n){let I={error:"unknown",errorDescription:"An unknown error occurred and no additional details are available."};if(uDl(l))I=PYt(l);else if(typeof l=="string")try{let r=JSON.parse(l);I=PYt(r)}catch{e===400?I={error:"invalid_request",errorDescription:`The service indicated that the request was invalid.
1628
1628
 
1629
1629
  ${l}`}:I={error:"unknown_error",errorDescription:`An unknown error has occurred. Response body:
1630
1630
 
@@ -1891,7 +1891,7 @@ Pay attention to the following when using it:
1891
1891
  `,n),a=-1;if(I!==-1&&r!==-1?a=Math.min(I,r):I!==-1?a=I:r!==-1&&(a=r),a===-1){l=t.slice(n);break}else{let s=t.slice(n,a);e.push(s),n=a+1,t[n-1]==="\r"&&t[n]===`
1892
1892
  `&&n++}}return[e,l]}var w2e=class extends Event{constructor(e,l){var n,I;super(e),this.code=(n=l?.code)!=null?n:void 0,this.message=(I=l?.message)!=null?I:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,l,n){return n(L3t(this),l)}[Symbol.for("Deno.customInspect")](e,l){return e(L3t(this),l)}};function pbn(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function NPe(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(NPe).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${NPe(t.cause)}`:t.message:`${t}`}function L3t(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var B3t=t=>{throw TypeError(t)},wPe=(t,e,l)=>e.has(t)||B3t("Cannot "+l),is=(t,e,l)=>(wPe(t,e,"read from private field"),l?l.call(t):e.get(t)),pG=(t,e,l)=>e.has(t)?B3t("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,l),od=(t,e,l,n)=>(wPe(t,e,"write to private field"),e.set(t,l),l),Nv=(t,e,l)=>(wPe(t,e,"access private method"),l),xg,A9,lK,Q2e,F2e,Die,rK,zie,hk,nK,aK,IK,Mie,Z2,WPe,yPe,EPe,J3t,RPe,YPe,_ie,VPe,QPe,Z9=class extends EventTarget{constructor(e,l){var n,I;super(),pG(this,Z2),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,pG(this,xg),pG(this,A9),pG(this,lK),pG(this,Q2e),pG(this,F2e),pG(this,Die),pG(this,rK),pG(this,zie,null),pG(this,hk),pG(this,nK),pG(this,aK,null),pG(this,IK,null),pG(this,Mie,null),pG(this,yPe,async r=>{var a;is(this,nK).reset();let{body:s,redirected:o,status:d,headers:u}=r;if(d===204){Nv(this,Z2,_ie).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(o?od(this,lK,new URL(r.url)):od(this,lK,void 0),d!==200){Nv(this,Z2,_ie).call(this,`Non-200 status code (${d})`,d);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Nv(this,Z2,_ie).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(is(this,xg)===this.CLOSED)return;od(this,xg,this.OPEN);let G=new Event("open");if((a=is(this,Mie))==null||a.call(this,G),this.dispatchEvent(G),typeof s!="object"||!s||!("getReader"in s)){Nv(this,Z2,_ie).call(this,"Invalid response body, expected a web ReadableStream",d),this.close();return}let p=new TextDecoder,h=s.getReader(),W=!0;do{let{done:E,value:R}=await h.read();R&&is(this,nK).feed(p.decode(R,{stream:!E})),E&&(W=!1,is(this,nK).reset(),Nv(this,Z2,VPe).call(this))}while(W)}),pG(this,EPe,r=>{od(this,hk,void 0),!(r.name==="AbortError"||r.type==="aborted")&&Nv(this,Z2,VPe).call(this,NPe(r))}),pG(this,RPe,r=>{typeof r.id=="string"&&od(this,zie,r.id);let a=new MessageEvent(r.event||"message",{data:r.data,origin:is(this,lK)?is(this,lK).origin:is(this,A9).origin,lastEventId:r.id||""});is(this,IK)&&(!r.event||r.event==="message")&&is(this,IK).call(this,a),this.dispatchEvent(a)}),pG(this,YPe,r=>{od(this,Die,r)}),pG(this,QPe,()=>{od(this,rK,void 0),is(this,xg)===this.CONNECTING&&Nv(this,Z2,WPe).call(this)});try{if(e instanceof URL)od(this,A9,e);else if(typeof e=="string")od(this,A9,new URL(e,hbn()));else throw new Error("Invalid URL")}catch{throw pbn("An invalid or illegal string was specified")}od(this,nK,V2e({onEvent:is(this,RPe),onRetry:is(this,YPe)})),od(this,xg,this.CONNECTING),od(this,Die,3e3),od(this,F2e,(n=l?.fetch)!=null?n:globalThis.fetch),od(this,Q2e,(I=l?.withCredentials)!=null?I:!1),Nv(this,Z2,WPe).call(this)}get readyState(){return is(this,xg)}get url(){return is(this,A9).href}get withCredentials(){return is(this,Q2e)}get onerror(){return is(this,aK)}set onerror(e){od(this,aK,e)}get onmessage(){return is(this,IK)}set onmessage(e){od(this,IK,e)}get onopen(){return is(this,Mie)}set onopen(e){od(this,Mie,e)}addEventListener(e,l,n){let I=l;super.addEventListener(e,I,n)}removeEventListener(e,l,n){let I=l;super.removeEventListener(e,I,n)}close(){is(this,rK)&&clearTimeout(is(this,rK)),is(this,xg)!==this.CLOSED&&(is(this,hk)&&is(this,hk).abort(),od(this,xg,this.CLOSED),od(this,hk,void 0))}};xg=new WeakMap,A9=new WeakMap,lK=new WeakMap,Q2e=new WeakMap,F2e=new WeakMap,Die=new WeakMap,rK=new WeakMap,zie=new WeakMap,hk=new WeakMap,nK=new WeakMap,aK=new WeakMap,IK=new WeakMap,Mie=new WeakMap,Z2=new WeakSet,WPe=function(){od(this,xg,this.CONNECTING),od(this,hk,new AbortController),is(this,F2e)(is(this,A9),Nv(this,Z2,J3t).call(this)).then(is(this,yPe)).catch(is(this,EPe))},yPe=new WeakMap,EPe=new WeakMap,J3t=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...is(this,zie)?{"Last-Event-ID":is(this,zie)}:void 0},cache:"no-store",signal:(t=is(this,hk))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},RPe=new WeakMap,YPe=new WeakMap,_ie=function(t,e){var l;is(this,xg)!==this.CLOSED&&od(this,xg,this.CLOSED);let n=new w2e("error",{code:e,message:t});(l=is(this,aK))==null||l.call(this,n),this.dispatchEvent(n)},VPe=function(t,e){var l;if(is(this,xg)===this.CLOSED)return;od(this,xg,this.CONNECTING);let n=new w2e("error",{code:e,message:t});(l=is(this,aK))==null||l.call(this,n),this.dispatchEvent(n),od(this,rK,setTimeout(is(this,QPe),is(this,Die)))},QPe=new WeakMap,Z9.CONNECTING=0,Z9.OPEN=1,Z9.CLOSED=2;function hbn(){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}c();c();var FPe;FPe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function Abn(t){return(await FPe).getRandomValues(new Uint8Array(t))}async function Zbn(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",l="",n=await Abn(t);for(let I=0;I<t;I++){let r=n[I]%e.length;l+=e[r]}return l}async function gbn(t){return await Zbn(t)}async function Nbn(t){let e=await(await FPe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function CPe(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await gbn(t),l=await Nbn(e);return{code_verifier:e,code_challenge:l}}c();var yb=j.string().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:j.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),j.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"}),x3t=j.object({resource:j.string().url(),authorization_servers:j.array(yb).optional(),jwks_uri:j.string().url().optional(),scopes_supported:j.array(j.string()).optional(),bearer_methods_supported:j.array(j.string()).optional(),resource_signing_alg_values_supported:j.array(j.string()).optional(),resource_name:j.string().optional(),resource_documentation:j.string().optional(),resource_policy_uri:j.string().url().optional(),resource_tos_uri:j.string().url().optional(),tls_client_certificate_bound_access_tokens:j.boolean().optional(),authorization_details_types_supported:j.array(j.string()).optional(),dpop_signing_alg_values_supported:j.array(j.string()).optional(),dpop_bound_access_tokens_required:j.boolean().optional()}).passthrough(),vPe=j.object({issuer:j.string(),authorization_endpoint:yb,token_endpoint:yb,registration_endpoint:yb.optional(),scopes_supported:j.array(j.string()).optional(),response_types_supported:j.array(j.string()),response_modes_supported:j.array(j.string()).optional(),grant_types_supported:j.array(j.string()).optional(),token_endpoint_auth_methods_supported:j.array(j.string()).optional(),token_endpoint_auth_signing_alg_values_supported:j.array(j.string()).optional(),service_documentation:yb.optional(),revocation_endpoint:yb.optional(),revocation_endpoint_auth_methods_supported:j.array(j.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:j.array(j.string()).optional(),introspection_endpoint:j.string().optional(),introspection_endpoint_auth_methods_supported:j.array(j.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:j.array(j.string()).optional(),code_challenge_methods_supported:j.array(j.string()).optional()}).passthrough(),Wbn=j.object({issuer:j.string(),authorization_endpoint:yb,token_endpoint:yb,userinfo_endpoint:yb.optional(),jwks_uri:yb,registration_endpoint:yb.optional(),scopes_supported:j.array(j.string()).optional(),response_types_supported:j.array(j.string()),response_modes_supported:j.array(j.string()).optional(),grant_types_supported:j.array(j.string()).optional(),acr_values_supported:j.array(j.string()).optional(),subject_types_supported:j.array(j.string()),id_token_signing_alg_values_supported:j.array(j.string()),id_token_encryption_alg_values_supported:j.array(j.string()).optional(),id_token_encryption_enc_values_supported:j.array(j.string()).optional(),userinfo_signing_alg_values_supported:j.array(j.string()).optional(),userinfo_encryption_alg_values_supported:j.array(j.string()).optional(),userinfo_encryption_enc_values_supported:j.array(j.string()).optional(),request_object_signing_alg_values_supported:j.array(j.string()).optional(),request_object_encryption_alg_values_supported:j.array(j.string()).optional(),request_object_encryption_enc_values_supported:j.array(j.string()).optional(),token_endpoint_auth_methods_supported:j.array(j.string()).optional(),token_endpoint_auth_signing_alg_values_supported:j.array(j.string()).optional(),display_values_supported:j.array(j.string()).optional(),claim_types_supported:j.array(j.string()).optional(),claims_supported:j.array(j.string()).optional(),service_documentation:j.string().optional(),claims_locales_supported:j.array(j.string()).optional(),ui_locales_supported:j.array(j.string()).optional(),claims_parameter_supported:j.boolean().optional(),request_parameter_supported:j.boolean().optional(),request_uri_parameter_supported:j.boolean().optional(),require_request_uri_registration:j.boolean().optional(),op_policy_uri:yb.optional(),op_tos_uri:yb.optional()}).passthrough(),S3t=Wbn.merge(vPe.pick({code_challenge_methods_supported:!0})),fPe=j.object({access_token:j.string(),id_token:j.string().optional(),token_type:j.string(),expires_in:j.number().optional(),scope:j.string().optional(),refresh_token:j.string().optional()}).strip(),O3t=j.object({error:j.string(),error_description:j.string().optional(),error_uri:j.string().optional()}),ybn=j.object({redirect_uris:j.array(yb),token_endpoint_auth_method:j.string().optional(),grant_types:j.array(j.string()).optional(),response_types:j.array(j.string()).optional(),client_name:j.string().optional(),client_uri:yb.optional(),logo_uri:yb.optional(),scope:j.string().optional(),contacts:j.array(j.string()).optional(),tos_uri:yb.optional(),policy_uri:j.string().optional(),jwks_uri:yb.optional(),jwks:j.any().optional(),software_id:j.string().optional(),software_version:j.string().optional(),software_statement:j.string().optional()}).strip(),Ebn=j.object({client_id:j.string(),client_secret:j.string().optional(),client_id_issued_at:j.number().optional(),client_secret_expires_at:j.number().optional()}).strip(),T3t=ybn.merge(Ebn),jIa=j.object({error:j.string(),error_description:j.string().optional()}).strip(),KIa=j.object({token:j.string(),token_type_hint:j.string().optional()}).strip();c();function U3t(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function M3t({requestedResource:t,configuredResource:e}){let l=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(l.origin!==n.origin||l.pathname.length<n.pathname.length)return!1;let I=l.pathname.endsWith("/")?l.pathname:l.pathname+"/",r=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return I.startsWith(r)}c();var km=class extends Error{constructor(e,l){super(e),this.errorUri=l,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Pie=class extends km{};Pie.errorCode="invalid_request";var g9=class extends km{};g9.errorCode="invalid_client";var N9=class extends km{};N9.errorCode="invalid_grant";var W9=class extends km{};W9.errorCode="unauthorized_client";var jie=class extends km{};jie.errorCode="unsupported_grant_type";var Kie=class extends km{};Kie.errorCode="invalid_scope";var qie=class extends km{};qie.errorCode="access_denied";var Wv=class extends km{};Wv.errorCode="server_error";var $ie=class extends km{};$ie.errorCode="temporarily_unavailable";var ece=class extends km{};ece.errorCode="unsupported_response_type";var tce=class extends km{};tce.errorCode="unsupported_token_type";var lce=class extends km{};lce.errorCode="invalid_token";var nce=class extends km{};nce.errorCode="method_not_allowed";var Ice=class extends km{};Ice.errorCode="too_many_requests";var rce=class extends km{};rce.errorCode="invalid_client_metadata";var ace=class extends km{};ace.errorCode="insufficient_scope";var _3t={[Pie.errorCode]:Pie,[g9.errorCode]:g9,[N9.errorCode]:N9,[W9.errorCode]:W9,[jie.errorCode]:jie,[Kie.errorCode]:Kie,[qie.errorCode]:qie,[Wv.errorCode]:Wv,[$ie.errorCode]:$ie,[ece.errorCode]:ece,[tce.errorCode]:tce,[lce.errorCode]:lce,[nce.errorCode]:nce,[Ice.errorCode]:Ice,[rce.errorCode]:rce,[ace.errorCode]:ace};var Sg=class extends Error{constructor(e){super(e??"Unauthorized")}};function z3t(t,e){let l=t.client_secret!==void 0;return e.length===0?l?"client_secret_post":"none":l&&e.includes("client_secret_basic")?"client_secret_basic":l&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":l?"client_secret_post":"none"}function P3t(t,e,l,n){let{client_id:I,client_secret:r}=e;switch(t){case"client_secret_basic":Rbn(I,r,l);return;case"client_secret_post":Ybn(I,r,n);return;case"none":Vbn(I,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Rbn(t,e,l){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);l.set("Authorization",`Basic ${n}`)}function Ybn(t,e,l){l.set("client_id",t),e&&l.set("client_secret",e)}function Vbn(t,e){e.set("client_id",t)}async function XPe(t){let e=t instanceof Response?t.status:void 0,l=t instanceof Response?await t.text():t;try{let n=O3t.parse(JSON.parse(l)),{error:I,error_description:r,error_uri:a}=n,s=_3t[I]||Wv;return new s(r||"",a)}catch(n){let I=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${l}`;return new Wv(I)}}async function Ak(t,e){var l,n;try{return await HPe(t,e)}catch(I){if(I instanceof g9||I instanceof W9)return await((l=t.invalidateCredentials)===null||l===void 0?void 0:l.call(t,"all")),await HPe(t,e);if(I instanceof N9)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await HPe(t,e);throw I}}async function HPe(t,{serverUrl:e,authorizationCode:l,scope:n,resourceMetadataUrl:I,fetchFn:r}){let a,s;try{a=await wbn(e,{resourceMetadataUrl:I},r),a.authorization_servers&&a.authorization_servers.length>0&&(s=a.authorization_servers[0])}catch{}s||(s=e);let o=await Qbn(e,t,a),d=await Hbn(s,{fetchFn:r}),u=await Promise.resolve(t.clientInformation());if(!u){if(l!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let E=await Jbn(s,{metadata:d,clientMetadata:t.clientMetadata,fetchFn:r});await t.saveClientInformation(E),u=E}if(l!==void 0){let E=await t.codeVerifier(),R=await kbn(s,{metadata:d,clientInformation:u,authorizationCode:l,codeVerifier:E,redirectUri:t.redirectUrl,resource:o,addClientAuthentication:t.addClientAuthentication,fetchFn:r});return await t.saveTokens(R),"AUTHORIZED"}let G=await t.tokens();if(G?.refresh_token)try{let E=await Lbn(s,{metadata:d,clientInformation:u,refreshToken:G.refresh_token,resource:o,addClientAuthentication:t.addClientAuthentication,fetchFn:r});return await t.saveTokens(E),"AUTHORIZED"}catch(E){if(!(!(E instanceof km)||E instanceof Wv))throw E}let p=t.state?await t.state():void 0,{authorizationUrl:h,codeVerifier:W}=await Xbn(s,{metadata:d,clientInformation:u,state:p,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:o});return await t.saveCodeVerifier(W),await t.redirectToAuthorization(h),"REDIRECT"}async function Qbn(t,e,l){let n=U3t(t);if(e.validateResourceURL)return await e.validateResourceURL(n,l?.resource);if(l){if(!M3t({requestedResource:n,configuredResource:l.resource}))throw new Error(`Protected resource ${l.resource} does not match expected ${n} (or origin)`);return new URL(l.resource)}}function sce(t){let e=t.headers.get("WWW-Authenticate");if(!e)return;let[l,n]=e.split(" ");if(l.toLowerCase()!=="bearer"||!n)return;let r=/resource_metadata="([^"]*)"/.exec(e);if(r)try{return new URL(r[1])}catch{return}}async function wbn(t,e,l=fetch){let n=await vbn(t,"oauth-protected-resource",l,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return x3t.parse(await n.json())}async function kPe(t,e,l=fetch){try{return await l(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?kPe(t,void 0,l):void 0;throw n}}function Fbn(t,e="",l={}){return e.endsWith("/")&&(e=e.slice(0,-1)),l.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function D3t(t,e,l=fetch){return await kPe(t,{"MCP-Protocol-Version":e},l)}function Cbn(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function vbn(t,e,l,n){var I,r;let a=new URL(t),s=(I=n?.protocolVersion)!==null&&I!==void 0?I:S6,o;if(n?.metadataUrl)o=new URL(n.metadataUrl);else{let u=Fbn(e,a.pathname);o=new URL(u,(r=n?.metadataServerUrl)!==null&&r!==void 0?r:a),o.search=a.search}let d=await D3t(o,s,l);if(!n?.metadataUrl&&Cbn(d,a.pathname)){let u=new URL(`/.well-known/${e}`,a);d=await D3t(u,s,l)}return d}function fbn(t){let e=typeof t=="string"?new URL(t):t,l=e.pathname!=="/",n=[];if(!l)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let I=e.pathname;return I.endsWith("/")&&(I=I.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${I}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${I}`,e.origin),type:"oidc"}),n.push({url:new URL(`${I}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function Hbn(t,{fetchFn:e=fetch,protocolVersion:l=S6}={}){var n;let I={"MCP-Protocol-Version":l},r=fbn(t);for(let{url:a,type:s}of r){let o=await kPe(a,I,e);if(o){if(!o.ok){if(o.status>=400&&o.status<500)continue;throw new Error(`HTTP ${o.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(s==="oauth")return vPe.parse(await o.json());{let d=S3t.parse(await o.json());if(!(!((n=d.code_challenge_methods_supported)===null||n===void 0)&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return d}}}}async function Xbn(t,{metadata:e,clientInformation:l,redirectUrl:n,scope:I,state:r,resource:a}){let s="code",o="S256",d;if(e){if(d=new URL(e.authorization_endpoint),!e.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(o))throw new Error(`Incompatible auth server: does not support code challenge method ${o}`)}else d=new URL("/authorize",t);let u=await CPe(),G=u.code_verifier,p=u.code_challenge;return d.searchParams.set("response_type",s),d.searchParams.set("client_id",l.client_id),d.searchParams.set("code_challenge",p),d.searchParams.set("code_challenge_method",o),d.searchParams.set("redirect_uri",String(n)),r&&d.searchParams.set("state",r),I&&d.searchParams.set("scope",I),I?.includes("offline_access")&&d.searchParams.append("prompt","consent"),a&&d.searchParams.set("resource",a.href),{authorizationUrl:d,codeVerifier:G}}async function kbn(t,{metadata:e,clientInformation:l,authorizationCode:n,codeVerifier:I,redirectUri:r,resource:a,addClientAuthentication:s,fetchFn:o}){var d;let u="authorization_code",G=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:u,code:n,code_verifier:I,redirect_uri:String(r)});if(s)s(p,h,t,e);else{let E=(d=e?.token_endpoint_auth_methods_supported)!==null&&d!==void 0?d:[],R=z3t(l,E);P3t(R,l,p,h)}a&&h.set("resource",a.href);let W=await(o??fetch)(G,{method:"POST",headers:p,body:h});if(!W.ok)throw await XPe(W);return fPe.parse(await W.json())}async function Lbn(t,{metadata:e,clientInformation:l,refreshToken:n,resource:I,addClientAuthentication:r,fetchFn:a}){var s;let o="refresh_token",d;if(e){if(d=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(o))throw new Error(`Incompatible auth server: does not support grant type ${o}`)}else d=new URL("/token",t);let u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),G=new URLSearchParams({grant_type:o,refresh_token:n});if(r)r(u,G,t,e);else{let h=(s=e?.token_endpoint_auth_methods_supported)!==null&&s!==void 0?s:[],W=z3t(l,h);P3t(W,l,u,G)}I&&G.set("resource",I.href);let p=await(a??fetch)(d,{method:"POST",headers:u,body:G});if(!p.ok)throw await XPe(p);return fPe.parse({refresh_token:n,...await p.json()})}async function Jbn(t,{metadata:e,clientMetadata:l,fetchFn:n}){let I;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");I=new URL(e.registration_endpoint)}else I=new URL("/register",t);let r=await(n??fetch)(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!r.ok)throw await XPe(r);return T3t.parse(await r.json())}var LPe=class extends Error{constructor(e,l,n){super(`SSE error: ${l}`),this.code=e,this.event=n}},C2e=class{constructor(e,l){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=l?.eventSourceInit,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new Sg("No auth provider");let l;try{l=await Ak(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new Sg;return await this._startOrAuth()}async _commonHeaders(){var e;let l={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(l.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion),new Headers({...l,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,l,n;let I=(n=(l=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&l!==void 0?l:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((r,a)=>{this._eventSource=new Z9(this._url.href,{...this._eventSourceInit,fetch:async(s,o)=>{let d=await this._commonHeaders();d.set("Accept","text/event-stream");let u=await I(s,{...o,headers:d});return u.status===401&&u.headers.has("www-authenticate")&&(this._resourceMetadataUrl=sce(u)),u}}),this._abortController=new AbortController,this._eventSource.onerror=s=>{var o;if(s.code===401&&this._authProvider){this._authThenStart().then(r,a);return}let d=new LPe(s.code,s.message,s);a(d),(o=this.onerror)===null||o===void 0||o.call(this,d)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",s=>{var o;let d=s;try{if(this._endpoint=new URL(d.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){a(u),(o=this.onerror)===null||o===void 0||o.call(this,u),this.close();return}r()}),this._eventSource.onmessage=s=>{var o,d;let u=s,G;try{G=ik.parse(JSON.parse(u.data))}catch(p){(o=this.onerror)===null||o===void 0||o.call(this,p);return}(d=this.onmessage)===null||d===void 0||d.call(this,G)}})}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 Sg("No auth provider");if(await Ak(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Sg("Failed to authorize")}async close(){var e,l,n;(e=this._abortController)===null||e===void 0||e.abort(),(l=this._eventSource)===null||l===void 0||l.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var l,n,I;if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},s=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!s.ok){if(s.status===401&&this._authProvider){if(this._resourceMetadataUrl=sce(s),await Ak(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Sg;return this.send(e)}let o=await s.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${o}`)}}catch(r){throw(I=this.onerror)===null||I===void 0||I.call(this,r),r}}setProtocolVersion(e){this._protocolVersion=e}};c();var BBt=dt(LBt(),1);import X2e from"node:process";import{PassThrough as upn}from"node:stream";c();var f2e=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
1893
1893
  `);if(e===-1)return null;let l=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),dpn(l)}clear(){this._buffer=void 0}};function dpn(t){return ik.parse(JSON.parse(t))}function JBt(t){return JSON.stringify(t)+`
1894
- `}var mpn=X2e.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Gpn(){let t={};for(let e of mpn){let l=X2e.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var H2e=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new f2e,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new upn)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,l)=>{var n,I,r,a,s;this._process=(0,BBt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...Gpn(),...this._serverParams.env},stdio:["pipe","pipe",(I=this._serverParams.stderr)!==null&&I!==void 0?I:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:X2e.platform==="win32"&&bpn(),cwd:this._serverParams.cwd}),this._process.on("error",o=>{var d,u;if(o.name==="AbortError"){(d=this.onclose)===null||d===void 0||d.call(this);return}l(o),(u=this.onerror)===null||u===void 0||u.call(this,o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{var d;this._process=void 0,(d=this.onclose)===null||d===void 0||d.call(this)}),(r=this._process.stdin)===null||r===void 0||r.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),(a=this._process.stdout)===null||a===void 0||a.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,l;return this._stderrStream?this._stderrStream:(l=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&l!==void 0?l:null}get pid(){var e,l;return(l=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&l!==void 0?l:null}processReadBuffer(){for(var e,l;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(l=this.onerror)===null||l===void 0||l.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(l=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let I=JBt(e);this._process.stdin.write(I)?l():this._process.stdin.once("drain",l)})}};function bpn(){return"type"in X2e}c();c();var k2e=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let I;super({start(r){I=V2e({onEvent:a=>{r.enqueue(a)},onError(a){e==="terminate"?r.error(a):typeof e=="function"&&e(a)},onRetry:l,onComment:n})},transform(r){I.feed(r)}})}};var ppn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},oce=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},L2e=class{constructor(e,l){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch,this._sessionId=l?.sessionId,this._reconnectionOptions=(n=l?.reconnectionOptions)!==null&&n!==void 0?n:ppn}async _authThenStart(){var e;if(!this._authProvider)throw new Sg("No auth provider");let l;try{l=await Ak(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new Sg;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let l={};if(this._authProvider){let I=await this._authProvider.tokens();I&&(l.Authorization=`Bearer ${I.access_token}`)}this._sessionId&&(l["mcp-session-id"]=this._sessionId),this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...l,...n})}async _startOrAuthSse(e){var l,n,I;let{resumptionToken:r}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),r&&a.set("last-event-id",r);let s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new oce(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(I=this.onerror)===null||I===void 0||I.call(this,a),a}}_getNextReconnectionDelay(e){let l=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,I=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(n,e),I)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,l=0){var n;let I=this._reconnectionOptions.maxRetries;if(I>0&&l>=I){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${I}) exceeded.`));return}let r=this._getNextReconnectionDelay(l);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,l+1)})},r)}_handleSseStream(e,l,n){if(!e)return;let{onresumptiontoken:I,replayMessageId:r}=l,a;(async()=>{var o,d,u,G;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new k2e).getReader();for(;;){let{value:h,done:W}=await p.read();if(W)break;if(h.id&&(a=h.id,I?.(h.id)),!h.event||h.event==="message")try{let E=ik.parse(JSON.parse(h.data));r!==void 0&&bie(E)&&(E.id=r),(o=this.onmessage)===null||o===void 0||o.call(this,E)}catch(E){(d=this.onerror)===null||d===void 0||d.call(this,E)}}}catch(p){if((u=this.onerror)===null||u===void 0||u.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:I,replayMessageId:r},0)}catch(h){(G=this.onerror)===null||G===void 0||G.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}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 Sg("No auth provider");if(await Ak(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Sg("Failed to authorize")}async close(){var e,l;(e=this._abortController)===null||e===void 0||e.abort(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e,l){var n,I,r,a;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:XRe(e)?e.id:void 0}).catch(R=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,R)});return}let d=await this._commonHeaders();d.set("content-type","application/json"),d.set("accept","application/json, text/event-stream");let u={...this._requestInit,method:"POST",headers:d,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},G=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,u),p=G.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!G.ok){if(G.status===401&&this._authProvider){if(this._resourceMetadataUrl=sce(G),await Ak(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Sg;return this.send(e)}let R=await G.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${G.status}): ${R}`)}if(G.status===202){Pkt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(R=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,R)});return}let W=(Array.isArray(e)?e:[e]).filter(R=>"method"in R&&"id"in R&&R.id!==void 0).length>0,E=G.headers.get("content-type");if(W)if(E?.includes("text/event-stream"))this._handleSseStream(G.body,{onresumptiontoken:o},!1);else if(E?.includes("application/json")){let R=await G.json(),w=Array.isArray(R)?R.map(C=>ik.parse(C)):[ik.parse(R)];for(let C of w)(r=this.onmessage)===null||r===void 0||r.call(this,C)}else throw new oce(-1,`Unexpected content type: ${E}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,l,n;if(this._sessionId)try{let I=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:I,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,r);if(!a.ok&&a.status!==405)throw new oce(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(I){throw(n=this.onerror)===null||n===void 0||n.call(this,I),I}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};c();var J2e=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 DPe(this),await this.server.connect(this.serverTransport)}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},DPe=class{constructor(e){this.clientTransport=e}onmessage;onerror;onclose;closed=!1;async start(){}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var B2e=class{createTransport(e){switch(e.type){case"stdio":{let l=new H2e({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0});return l.stderr?.pipe(e.stderr),l}case"http":return new L2e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new C2e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new J2e(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};c();var y9="blackbird-mcp-server",iK="github-mcp-server",zPe="playwright";function cK(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function dK(t){return ice(t)||cce(t)}function ice(t){return t.type?.toLowerCase()==="http"}function cce(t){return t.type?.toLowerCase()==="sse"}function dce(t){return t.type?.toLowerCase()==="memory"}var PPe=class extends hpn{constructor(l,n){super({decodeStrings:!1});this.serverName=l;this.logger=n}_write(l,n,I){try{let r=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${r}`),I()}catch(r){I(r instanceof Error?r:new Error(String(r)))}}},x2e=class{constructor(e,l=new R2e,n=new B2e){this.logger=e;this.clientFactory=l;this.transportFactory=n}clients={};transports={};async startLocalMcpClient(e,l,n,I){this.logger.log(`Starting MCP client for ${e} with command: ${n} and args: ${I}`);let r=new PPe(e,this.logger),a={type:"stdio",command:n,args:I,env:{...l,PATH:process.env.PATH},stderr:r},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"http",url:l.url,headers:l.headers},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async startSseMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"sse",url:l.url,headers:l.headers},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async startInMemoryMcpClient(e,l){this.logger.log(`Starting in-memory MCP client for ${e}`);let n={type:"memory",server:l},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async setupAndConnectClient(e,l){this.transports[e]=l,l.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let n=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),I=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await n.connect(l),n.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},n.onerror=r=>{this.logger.error(`MCP client for ${e} errored ${r}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-I}ms`),this.clients[e]=n}async getTools(e,l){let n={};for(let[I,r]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${I}`);let s=await r.listTools(),o=e?.mcpServers[I].tools,d=e?.mcpServers[I].filterMapping;for(let G of s.tools){if(G.name==="get_copilot_space")continue;if(!(o?.includes("*")||o?.includes(G.name))){this.logger.log(`Tool ${G.name} is not in the allowed list for client: ${I}`);continue}let h=kNe(I,G.name),W=`${I}-${G.name}`,E;typeof d=="string"?E=vxe(d):E=vxe(d?.[G.name]??"hidden_characters"),n[`${I}/${G.name}`]={name:W,title:G.title??G.annotations?.title??G.name,description:G.description??W,input_schema:G.inputSchema,readOnly:G.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[I].isDefaultServer||h),inputsNames:!!e?.mcpServers[I].isDefaultServer},filterMode:E},a.push(G.name),this.logger.log(`Tool ${G.name} added to tools list for client: ${I}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${I}`);let u=r.getServerVersion();await this.logServerSuccessWithTools(I,a,u,l)}catch(s){this.logger.error(`Failed to get tools from client: ${I} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(n,null,2)}`),n}async logServerSuccessWithTools(e,l,n,I){if(e!=y9&&I)try{let r=l.map(o=>`- ${o}`).join(`
1894
+ `}var mpn=X2e.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Gpn(){let t={};for(let e of mpn){let l=X2e.env[e];l!==void 0&&(l.startsWith("()")||(t[e]=l))}return t}var H2e=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new f2e,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new upn)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,l)=>{var n,I,r,a,s;this._process=(0,BBt.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...Gpn(),...this._serverParams.env},stdio:["pipe","pipe",(I=this._serverParams.stderr)!==null&&I!==void 0?I:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:X2e.platform==="win32"&&bpn(),cwd:this._serverParams.cwd}),this._process.on("error",o=>{var d,u;if(o.name==="AbortError"){(d=this.onclose)===null||d===void 0||d.call(this);return}l(o),(u=this.onerror)===null||u===void 0||u.call(this,o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{var d;this._process=void 0,(d=this.onclose)===null||d===void 0||d.call(this)}),(r=this._process.stdin)===null||r===void 0||r.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),(a=this._process.stdout)===null||a===void 0||a.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",o=>{var d;(d=this.onerror)===null||d===void 0||d.call(this,o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,l;return this._stderrStream?this._stderrStream:(l=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&l!==void 0?l:null}get pid(){var e,l;return(l=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&l!==void 0?l:null}processReadBuffer(){for(var e,l;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(l=this.onerror)===null||l===void 0||l.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(l=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let I=JBt(e);this._process.stdin.write(I)?l():this._process.stdin.once("drain",l)})}};function bpn(){return"type"in X2e}c();c();var k2e=class extends TransformStream{constructor({onError:e,onRetry:l,onComment:n}={}){let I;super({start(r){I=V2e({onEvent:a=>{r.enqueue(a)},onError(a){e==="terminate"?r.error(a):typeof e=="function"&&e(a)},onRetry:l,onComment:n})},transform(r){I.feed(r)}})}};var ppn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},oce=class extends Error{constructor(e,l){super(`Streamable HTTP error: ${l}`),this.code=e}},L2e=class{constructor(e,l){var n;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=l?.requestInit,this._authProvider=l?.authProvider,this._fetch=l?.fetch,this._sessionId=l?.sessionId,this._reconnectionOptions=(n=l?.reconnectionOptions)!==null&&n!==void 0?n:ppn}async _authThenStart(){var e;if(!this._authProvider)throw new Sg("No auth provider");let l;try{l=await Ak(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(l!=="AUTHORIZED")throw new Sg;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let l={};if(this._authProvider){let I=await this._authProvider.tokens();I&&(l.Authorization=`Bearer ${I.access_token}`)}this._sessionId&&(l["mcp-session-id"]=this._sessionId),this._protocolVersion&&(l["mcp-protocol-version"]=this._protocolVersion);let n=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...l,...n})}async _startOrAuthSse(e){var l,n,I;let{resumptionToken:r}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),r&&a.set("last-event-id",r);let s=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new oce(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(I=this.onerror)===null||I===void 0||I.call(this,a),a}}_getNextReconnectionDelay(e){let l=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,I=this._reconnectionOptions.maxReconnectionDelay;return Math.min(l*Math.pow(n,e),I)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,l=0){var n;let I=this._reconnectionOptions.maxRetries;if(I>0&&l>=I){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${I}) exceeded.`));return}let r=this._getNextReconnectionDelay(l);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,l+1)})},r)}_handleSseStream(e,l,n){if(!e)return;let{onresumptiontoken:I,replayMessageId:r}=l,a;(async()=>{var o,d,u,G;try{let p=e.pipeThrough(new TextDecoderStream).pipeThrough(new k2e).getReader();for(;;){let{value:h,done:W}=await p.read();if(W)break;if(h.id&&(a=h.id,I?.(h.id)),!h.event||h.event==="message")try{let E=ik.parse(JSON.parse(h.data));r!==void 0&&bie(E)&&(E.id=r),(o=this.onmessage)===null||o===void 0||o.call(this,E)}catch(E){(d=this.onerror)===null||d===void 0||d.call(this,E)}}}catch(p){if((u=this.onerror)===null||u===void 0||u.call(this,new Error(`SSE stream disconnected: ${p}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:I,replayMessageId:r},0)}catch(h){(G=this.onerror)===null||G===void 0||G.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}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 Sg("No auth provider");if(await Ak(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Sg("Failed to authorize")}async close(){var e,l;(e=this._abortController)===null||e===void 0||e.abort(),(l=this.onclose)===null||l===void 0||l.call(this)}async send(e,l){var n,I,r,a;try{let{resumptionToken:s,onresumptiontoken:o}=l||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:XRe(e)?e.id:void 0}).catch(R=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,R)});return}let d=await this._commonHeaders();d.set("content-type","application/json"),d.set("accept","application/json, text/event-stream");let u={...this._requestInit,method:"POST",headers:d,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},G=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,u),p=G.headers.get("mcp-session-id");if(p&&(this._sessionId=p),!G.ok){if(G.status===401&&this._authProvider){if(this._resourceMetadataUrl=sce(G),await Ak(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Sg;return this.send(e)}let R=await G.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${G.status}): ${R}`)}if(G.status===202){Pkt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(R=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,R)});return}let W=(Array.isArray(e)?e:[e]).filter(R=>"method"in R&&"id"in R&&R.id!==void 0).length>0,E=G.headers.get("content-type");if(W)if(E?.includes("text/event-stream"))this._handleSseStream(G.body,{onresumptiontoken:o},!1);else if(E?.includes("application/json")){let R=await G.json(),w=Array.isArray(R)?R.map(C=>ik.parse(C)):[ik.parse(R)];for(let C of w)(r=this.onmessage)===null||r===void 0||r.call(this,C)}else throw new oce(-1,`Unexpected content type: ${E}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,l,n;if(this._sessionId)try{let I=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:I,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((l=this._fetch)!==null&&l!==void 0?l:fetch)(this._url,r);if(!a.ok&&a.status!==405)throw new oce(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(I){throw(n=this.onerror)===null||n===void 0||n.call(this,I),I}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};c();var J2e=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 DPe(this),await this.server.connect(this.serverTransport)}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},DPe=class{constructor(e){this.clientTransport=e}onmessage;onerror;onclose;closed=!1;async start(){}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(e)}catch(l){this.onerror?.(l instanceof Error?l:new Error(String(l)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var B2e=class{createTransport(e){switch(e.type){case"stdio":{let l=new H2e({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0});return l.stderr?.pipe(e.stderr),l}case"http":return new L2e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new C2e(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new J2e(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};c();var y9="blackbird-mcp-server",iK="github-mcp-server",zPe="playwright";function cK(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function dK(t){return ice(t)||cce(t)}function ice(t){return t.type?.toLowerCase()==="http"}function cce(t){return t.type?.toLowerCase()==="sse"}function dce(t){return t.type?.toLowerCase()==="memory"}var PPe=class extends hpn{constructor(l,n){super({decodeStrings:!1});this.serverName=l;this.logger=n}_write(l,n,I){try{let r=l.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${r}`),I()}catch(r){I(r instanceof Error?r:new Error(String(r)))}}},x2e=class{constructor(e,l=new R2e,n=new B2e){this.logger=e;this.clientFactory=l;this.transportFactory=n}clients={};transports={};async startLocalMcpClient(e,l,n,I){this.logger.log(`Starting MCP client for ${e} with command: ${n} and args: ${I}`);let r=new PPe(e,this.logger),a={type:"stdio",command:n,args:I,env:{...l,PATH:process.env.PATH},stderr:r},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"http",url:l.url,headers:l.headers},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async startSseMcpClient(e,l){this.logger.log(`Starting remote MCP client for ${e} with url: ${l.url}`);let n={type:"sse",url:l.url,headers:l.headers},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async startInMemoryMcpClient(e,l){this.logger.log(`Starting in-memory MCP client for ${e}`);let n={type:"memory",server:l},I=this.transportFactory.createTransport(n);await this.setupAndConnectClient(e,I)}async setupAndConnectClient(e,l){this.transports[e]=l,l.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let n=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),I=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await n.connect(l),n.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},n.onerror=r=>{this.logger.error(`MCP client for ${e} errored ${r}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-I}ms`),this.clients[e]=n}async getTools(e,l){let n={};for(let[I,r]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${I}`);let s=await r.listTools(),o=e?.mcpServers[I].tools,d=e?.mcpServers[I].filterMapping;for(let G of s.tools){if(G.name==="get_copilot_space")continue;if(!(o?.includes("*")||o?.includes(G.name))){this.logger.log(`Tool ${G.name} is not in the allowed list for client: ${I}`);continue}let h=kNe(I,G.name),W=`${I}-${G.name}`,E;typeof d=="string"?E=vxe(d):E=vxe(d?.[G.name]??"hidden_characters"),n[`${I}/${G.name}`]={name:W,namespacedName:`${I}/${G.name}`,title:G.title??G.annotations?.title??G.name,description:G.description??W,input_schema:G.inputSchema,readOnly:G.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[I].isDefaultServer||h),inputsNames:!!e?.mcpServers[I].isDefaultServer},filterMode:E},a.push(G.name),this.logger.log(`Tool ${G.name} added to tools list for client: ${I}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${I}`);let u=r.getServerVersion();await this.logServerSuccessWithTools(I,a,u,l)}catch(s){this.logger.error(`Failed to get tools from client: ${I} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(n,null,2)}`),n}async logServerSuccessWithTools(e,l,n,I){if(e!=y9&&I)try{let r=l.map(o=>`- ${o}`).join(`
1895
1895
  `),s=`MCP server started successfully${n?` (version ${n.version})`:""} with ${l.length} ${l.length===1?"tool":"tools"} - for the full output, see the verbose logs
1896
1896
 
1897
1897
  ${r}`;await I.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${l.length} tools`)}catch(r){this.logger.error(`Failed to update session log for ${e}: ${r}`)}}};c();var jPe={mcpServers:{}},S2e=class{constructor(e,l,n){this.logger=e;this.registry=l;this.remoteEnabled=n?.remoteEnabled??!1,this.mcp3pEnabled=n?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=n?.blackbirdMetisIndexEnabled??!1,this.sessionClient=n?.sessionClient,this.mcpEnvConfig=void 0}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 l=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(l,e),this.configureGitHubMcp(l,e),this.configurePlaywrightMcp(l)),l}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),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 l in e.mcpServers)e.mcpServers[l].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),jPe}}configureGitHubMcp(e,l){this.remoteEnabled?this.configureRemoteGitHubMcp(e,l):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,l){this.logger.log("Using default remote GitHub MCP server configuration");let n="repos,issues,users,pull_requests,code_security,secret_protection,actions,web_search";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),n=n+",copilot_spaces");let I={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":n,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};l&&l.api?.copilot?.integrationId&&(I["Copilot-Integration-Id"]=l.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(I["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let r={type:"http",url:this.getCapiMcpUrl(),headers:I,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[iK]=r}configureLocalGitHubMcp(e){if(e.mcpServers[iK]){this.logger.log("Using user-provided GitHub MCP server configuration");let l=e.mcpServers[iK]??{};cK(l)&&!l.command&&(e.mcpServers[iK]={...l,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let l={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[iK]=l}}configurePlaywrightMcp(e){if(!e.mcpServers[zPe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(n=>n.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let l={command:"npx",args:[...NSe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[zPe]=l}}configureBlackbirdMcp(e,l){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,l):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,l){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${l.blackbird?.mode}`);let n=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${n}`);let I=[];l.blackbird?.mode==="tool"&&(I=["*"]),this.logger.log(`Using blackbird Metis server: ${l.blackbird?.mode}`);let r={command:`${n}/blackbird/mcp`,args:["serve","--index",`${n}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:I,isDefaultServer:!0};e.mcpServers[y9]=r}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:l,isDefaultServer:!0};e.mcpServers[y9]=n}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let l=[];process.env.BLACKBIRD_MODE==="tool"&&(l=["*"]);let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let I={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:l,isDefaultServer:!0};e.mcpServers[y9]=I}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 cK(e)||ice(e)||cce(e)||dce(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,l){return this.remoteEnabled&&!this.isValidServerType(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!cK(l)&&!dce(l)?(this.logger.error(`Unsupported server type "${l.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):l.tools?cK(l)&&!this.isValidLocalServerConfig(l)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(ice(l)||cce(l))&&!this.isValidRemoteServerConfig(l)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):dce(l)&&!this.isValidInMemoryServerConfig(l)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,l){try{let n=this.resolveHeaders(l.headers,process.env),I={...l,headers:n};await this.registry.startHttpMcpClient(e,I),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}async processSseServer(e,l){try{let n=this.resolveRemoteServerConfig(l);await this.registry.startSseMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(n){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${n}`),n}}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,l){try{await this.registry.startInMemoryMcpClient(e,l.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(n){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${n}`),n}}async processLocalServer(e,l){let n={...l};if(l.command==="python")try{n=await this.convertPythonToPipx(n)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let I=this.buildEnvironment(n),r=this.resolveLocalServerConfig(n,I);this.logger.log(`Starting MCP client for ${e} with command: ${r.command} and args: ${r.args}`);try{await this.registry.startLocalMcpClient(e,I,r.command,r.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 l=e.args,n=l.indexOf("-m");if(n===-1||n===l.length-1)throw new Error("Python command with -m flag must specify a module");let I=l[n+1];this.logger.log(`Converting Python module: ${I} to pipx command`);let r=["run",I];for(let a=n+2;a<l.length;a++)r.push(l[a]);for(let a=0;a<n;a++)r.push(l[a]);return{...e,command:"pipx",args:r}}buildEnvironment(e){let l={};if(e.env)for(let[n,I]of Object.entries(e.env)){let r=I.trim(),a=r;if(r.includes("$")&&(a=this.resolveString(r,process.env)),a!==r){l[n]=a;continue}process.env[r]!==void 0&&(l[n]=process.env[r])}return l}resolveLocalServerConfig(e,l){let n=this.resolveString(e.command,l),I=this.resolveArray(e.args,l);return{...e,command:n,args:I}}resolveString(e,l){return l?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(n,I,r,a)=>{let o=l[I||a];return o!==void 0?o:r!==void 0?r:n}):e}resolveArray(e,l){return e?l?e.map(n=>this.resolveString(n,l)):e:[]}resolveHeaders(e,l){if(!e)return{};if(!l)return e;let n={};for(let[I,r]of Object.entries(e)){let a=this.resolveArray([r],l);n[I]=a[0]}return n}async processServers(e){if(!e)throw new Error("No servers to process");let l=Object.entries(e.mcpServers).map(([n,I])=>this.processServer(n,I));await Promise.all(l)}async processServer(e,l){if(!this.validateServerConfig(e,l)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{cK(l)?await this.processLocalServer(e,l):ice(l)&&this.remoteEnabled?await this.processHttpServer(e,l):cce(l)&&this.remoteEnabled?await this.processSseServer(e,l):dce(l)&&await this.processInMemoryServer(e,l)}catch(n){e!==y9&&await this.logServerFailure(e,n)}}async logServerFailure(e,l){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${l.message} - for the full output, see the verbose logs</error>`)}catch(n){this.logger.error(`Failed to log failure for MCP Server '${e}': '${n}'`)}}};var O2e=class{constructor(e,l,n){this.logger=e;let I;if(typeof l=="string"){if(I=JSON.parse(l),typeof I!="object")throw new Error("Invalid MCP configuration: must be an object");if(I===null||!("mcpServers"in I)||typeof I.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=I}else this.config=l;this.disabledServers=new Set(n||[]),this.registry=new x2e(this.logger),this.processor=new S2e(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 l={};for(let[n,I]of Object.entries(this.config.mcpServers))this.disabledServers.has(n)?this.logger.log(`Skipping disabled MCP server: ${n}`):l[n]=I;e={...this.config,mcpServers:l}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,l]of Object.entries(this.registry.transports))try{await l.close()}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,l,n){if(!this.allTools){await this.startServers();let I=new hre(e,l,n),r=[];for(let a of Object.keys(this.registry.clients)){let s=await I.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});r.push(...s)}this.allTools=r}return this.allTools}getConfig(){return this.config}async startServer(e,l){await this.startServers(),this.config.mcpServers[e]=l,await this.processor.processServer(e,l),this.allTools=null}async stopServer(e){let l=this.registry.transports[e];if(l)try{await l.close(),delete this.registry.transports[e]}catch(n){this.logger.error(`Error closing transport for ${e}: ${n}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,l){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,l)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.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 l=this.getServerConfig(e);l?await this.startServer(e,l):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};c();var Apn="/login/device/code",Zpn="/login/oauth/access_token",xBt="Ov23ctDVkRmgkPke0Mmm",g2="https://github.com",Zk=class extends Error{constructor(l,n){super(n);this.status=l;this.message=n;this.name="GitHubApiError"}};function SBt(t){let e=new URL(t);return e.hostname.startsWith("api.")||(e.hostname="api."+e.hostname),e.href}async function OBt(t){let e=new URL(Apn,t),l=await fetch(e.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:xBt,scope:"user:email,read:user,repo,workflow"})});if(!l.ok)throw new Zk(l.status,`Failed to request device code: ${l.statusText}`);return await l.json()}async function TBt(t,e){let l=new URL(Zpn,t),n=await fetch(l.href,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:xBt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!n.ok)throw new Zk(n.status,`Failed to authorize: ${n.statusText}`);let I=await n.json();if(typeof I.access_token=="string")return I.access_token;if(I.error!=="authorization_pending"&&I.error!=="slow_down")throw new Error(I.error_description||`Unexpected error: ${I.error}`)}async function uK(t,e){let l=new URL("/user",SBt(t)),n=await fetch(l.href,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!n.ok)throw new Zk(n.status,`Failed to fetch user info: ${n.statusText}`);return(await n.json()).login}async function mK(t,e){let l=`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@github/copilot",
3
3
  "description": "GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.",
4
- "version": "0.0.339-12",
4
+ "version": "0.0.339-13",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -33,7 +33,7 @@
33
33
  "sdk/**/*"
34
34
  ],
35
35
  "buildMetadata": {
36
- "gitCommit": "6812c15"
36
+ "gitCommit": "e2f735e"
37
37
  },
38
38
  "dependencies": {
39
39
  "node-pty": "npm:@devm33/node-pty@^1.0.8",