@github/copilot 0.0.337-10 → 0.0.337-11
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 +1 -1
- package/package.json +2 -2
- package/sdk/index.js +1 -1
- package/sdk/index.js.map +1 -1
package/index.js
CHANGED
|
@@ -1619,7 +1619,7 @@ ${IYt()}
|
|
|
1619
1619
|
<reminder>
|
|
1620
1620
|
The user may have mentioned images, if so these will have been attached to this message, in the order they were mentioned
|
|
1621
1621
|
</reminder>`),l.trim()},NNe={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."},rYt=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${rre(t)}. Commit changes by using the **report_progress** tool.</reminder>`;c();function aYt(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 aP(t){let e=t.reasoning_text?.replace(/<\|im_sep\|>(\*\*.*?\*\*)?/g,`
|
|
1622
|
-
`)?.trim();return{...t,reasoning_text:e}}function sre(t){return structuredClone(t)}function sYt(t){return{...t,choices:t.choices.map(e=>{let l=aP(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 jB(t){return t.role==="user"&&Array.isArray(t.content)&&t.content.some(e=>e.type==="image_url")}function oYt(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 eSe="/tmp/playwright-logs",kMl="0.0.40",tSe=[`@playwright/mcp@${kMl}`,"--viewport-size","1280, 720","--output-dir",eSe],Kir=[...tSe,"--isolated"];var lSe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},ore=2e3;async function JMl(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=`${_Gt(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: ${e1(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 nSe(t,e,l,n){let I=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,r=/!\[.*?\]\((.*?)\)/g,a=[];return a.push(...iYt(t,e,I,l,n)),a.push(...iYt(t,e,r,l,n)),a}function iYt(t,e,l,n,I){let r=t.matchAll(l),a=[],s=/\/([a-f0-9-]+)$/;for(let o of r){let d=OMl(o[1],e),u=TMl(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 BMl(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&ure(t)}function ure(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function xMl(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 SMl(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=ire.dirname(s);r=ire.resolve("/",o,e).slice(1)}return`${l}/${n}/blob/${I}/${r}`}function OMl(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function TMl(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}=jRt(t);if(e===void 0||l===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:l}}async function WNe(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 cre(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 _Ml(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 cre(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 ${e1(r.length)} is larger than the maximum size of ${e1(l)}, attempting to reduce image quality`);let o=await DMl(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 cre(t,e,l){let n=await rSe(l),I=l.length;return!n.width||!n.height?{exceedsSizeLimit:I>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await MMl(t,l),exceedsDimensionLimit:await UMl(e,l)}}async function UMl(t,e){let l=await rSe(e);return!l.width||!l.height?!1:l.width>t||l.height>t}async function MMl(t,e){return e.length>t}async function _Ml(t,e,l,n,I){try{if(!dYt(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=cYt(e).resize(R,w,{fit:"inside",withoutEnlargement:!0});return ISe(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:L}=await cre(n,l,w);!C&&!L?(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 DMl(t,e,l,n,I){try{let r=I==="image/png"?80:100,a=I==="image/png"?Math.floor(r*.4):20,s=await ISe(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 ISe(t,e,E,I);if(!R)return u;let{exceedsSizeLimit:w,exceedsDimensionLimit:C}=await cre(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 ISe(t,e,l,n){let I=cYt(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 dre=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function zMl(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=xMl(a);if(s)for(let o in s){if(I.length>=e)break;let d=s[o].contents,u=nSe(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):BMl(p)?(W=!0,h=SMl(s[o],p,l),I.push({url:h,guid:G.guid,kind:"committed_attachment"})):ure(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,L,S,U]=w;E.owner=C,E.repo=L,E.branch=S,E.path=U,n.info(`Repository metadata extracted: owner=${C}, repo=${L}, branch=${S}, path=${U}`)}else n.info(`Failed to extract repository metadata from URL: ${E.url}`)}}}}return I}function PMl(t,e){let l=e.flatMap(I=>jB(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 yNe=class{async resolveRepositoryImages(e,l,n,I,r,a){if(l<=0)return[];let s=zMl(e,l,n,I);this.logger.debug(`Found ${s.length} repository image URLs to process`);let o=PMl(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 dre,d=new Map;for(let G of e.messages)if(G.role=="user")if(typeof G.content=="string"){let p=nSe(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=nSe(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,nYt(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(jB).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:u},e.messages.some(G=>jB(G))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,l,n){let I=W$(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(!dYt(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 WNe(this.logger,n,l,ore,a,o),n.resizedBase64ImagesSize.push(o?.length??-1),!o)return["",new lSe(`Image size exceeds maximum size of ${e1(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=MGt(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 (${e1(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),Ii(this.settings,"copilot_swe_agent_resize_image_references")){if(!await WNe(this.logger,l,n,ore,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 cre(n,ore,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 ${e1(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 JMl(s.guid,W$(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 ${e1(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(jMl(I,n));if(r.length===0){let a=await $Ml(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*jMl(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 KMl="playwright-browser_take_screenshot";function qMl(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function $Ml(t,e){if(t.function.name!==KMl)return;e.debug("Adding images using Playwright params fallback strategy");let l=JSON.parse(t.function.arguments);if(qMl(l)){let n=ire.isAbsolute(l.filename)?l.filename:ire.join(eSe,l.filename);e.debug(`Image from Playwright params: ${l.filename}. Updated to ${n}.`);let I=await t_l(n,e);if(I){let r=I.buffer.toString("base64");return{url:`data:${I.mimeType};base64,${r}`,isScreenshot:!0}}}}function e_l(t){switch(ire.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function dYt(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 t_l(t,e){try{if(!ure(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let l=e_l(t);return l?{buffer:await LMl.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 sP=class{logger;constructor(e){this.logger=e}toJSON(){return"BasicTruncator"}async*preRequest(e){let l=await uYt(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit);l.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(l)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:l}}},oP=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=oYt(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=await uYt(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"}},l_l=.95;function uYt(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=>Dpe(h,l)),s=sF(JSON.stringify(e),l),o=n*l_l,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(nA).filter(S=>S.function.name===xee),w=E.filter(nA).filter(S=>S.function.name!==xee),C=R.length===0,L=new Set(w.map(S=>S.id));if(w.length>0&&(W.tool_calls=R,a[h]=Dpe(W,l)),C&&(u.add(h),G+=a[h]),L.size>0)for(let S=h+1;S<t.length;S++){let U=t[S];if(U.role==="tool"&&L.has(U.tool_call_id)&&(u.add(S),G+=a[S],L.delete(U.tool_call_id),L.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}}c();var HA=class extends UH{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,l){}endGroup(e){}};c();c();var mYt={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"}]},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 ENe(t,e,l){let n=(l||mYt)[t.toLowerCase()],I=new Set;for(;typeof n=="string";){if(I.has(n))return!1;I.add(n),n=mYt[n]}if(!n)return!1;let r=e.toLowerCase();return n.tools.some(a=>a.toolName===r)}var n_l="image";var I_l="resource",r_l=60*1e3*2,a_l={timeout:r_l};var aSe=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:I_l,data:u.blob,mimeType:u.mimeType||"application/octet-stream"}):u&&u.text&&(I+=u.text)}else d.type==="image"&&r.push({type:n_l,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=gxe(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=Axe(I,l)}this.logger.debug(`Tool invocation result: ${a}`);let s={},o=a?yc(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 AZe(G.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return ZZe;case"denied-interactively-by-user":return hZe;default:fN(G,`Unhandled permission result kind: ${G}`)}},safeForTelemetry:r.safeForTelemetry}}return Object.values(n)}};var mre=class t extends aSe{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,{...a_l,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:ENe(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 RNe=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=wGt(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"}}}}},sSe={remindWhereToDoWork:{instruction:rYt,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:NNe.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:NNe.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:NNe.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};c();c();c();var oSe={agent:"sweagent-capi",model:"claude-sonnet-4"},GYt=oSe;function iSe(t){if(!t)return GYt;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 Dvt from"path";c();c();c();c();var VNe="4.12.0",KB="04b07795-8ddb-461a-bbee-02f9e1bf7b46",bYt="common",YNe;(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"})(YNe||(YNe={}));var bre=YNe.AzurePublicCloud,pYt="login.microsoftonline.com",hYt=["*"],AYt="cae",ZYt="nocae",gYt="msal.cache";var cSe;var s_l,QNe,WYt;function yYt(){return QNe!==void 0&&WYt!==void 0}function o_l(t){let e={cache:{},broker:{...t.brokerOptions,isEnabled:t.brokerOptions?.enabled??!1,enableMsaPassthrough:t.brokerOptions?.legacyEnableMsaPassthrough??!1}};if(t.tokenCachePersistenceOptions?.enabled){if(cSe===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||gYt;e.cache.cachePlugin=cSe({name:`${l}.${ZYt}`,...t.tokenCachePersistenceOptions}),e.cache.cachePluginCae=cSe({name:`${l}.${AYt}`,...t.tokenCachePersistenceOptions})}return t.brokerOptions?.enabled&&(e.broker.nativeBrokerPlugin=c_l(t.isVSCodeCredential||!1)),e}var NYt={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(" ")},i_l={vsCode:{credentialName:"Visual Studio Code Credential",packageName:"@azure/identity-vscode",pluginVar:"vsCodePlugin",get brokerInfo(){return WYt}},native:{credentialName:"Broker for WAM",packageName:"@azure/identity-broker",pluginVar:"nativeBrokerPlugin",get brokerInfo(){return s_l}}};function c_l(t){let{credentialName:e,packageName:l,pluginVar:n,brokerInfo:I}=i_l[t?"vsCode":"native"];if(I===void 0)throw new Error(NYt.missing(e,l,n));if(I.broker.isBrokerAvailable===!1)throw new Error(NYt.unavailable(e,l));return I.broker}var EYt={generatePluginConfiguration:o_l};c();c();c();function d_l(t){return t&&typeof t.error=="string"&&typeof t.error_description=="string"}var YYt="CredentialUnavailableError",qn=class extends Error{constructor(e,l){super(e,l),this.name=YYt}},wNe="AuthenticationError",J5=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(d_l(l))I=RYt(l);else if(typeof l=="string")try{let r=JSON.parse(l);I=RYt(r)}catch{e===400?I={error:"invalid_request",errorDescription:`The service indicated that the request was invalid.
|
|
1622
|
+
`)?.trim();return{...t,reasoning_text:e}}function sre(t){return structuredClone(t)}function sYt(t){return{...t,choices:t.choices.map(e=>{let l=aP(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 jB(t){return t.role==="user"&&Array.isArray(t.content)&&t.content.some(e=>e.type==="image_url")}function oYt(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 eSe="/tmp/playwright-logs",kMl="0.0.40",tSe=[`@playwright/mcp@${kMl}`,"--viewport-size","1280, 720","--output-dir",eSe],Kir=[...tSe,"--isolated"];var lSe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},ore=2e3;async function JMl(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=`${_Gt(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: ${e1(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 nSe(t,e,l,n){let I=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,r=/!\[.*?\]\((.*?)\)/g,a=[];return a.push(...iYt(t,e,I,l,n)),a.push(...iYt(t,e,r,l,n)),a}function iYt(t,e,l,n,I){let r=t.matchAll(l),a=[],s=/\/([a-f0-9-]+)$/;for(let o of r){let d=OMl(o[1],e),u=TMl(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 BMl(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&ure(t)}function ure(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function xMl(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 SMl(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=ire.dirname(s);r=ire.resolve("/",o,e).slice(1)}return`${l}/${n}/blob/${I}/${r}`}function OMl(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function TMl(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}=jRt(t);if(e===void 0||l===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:l}}async function WNe(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 cre(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 _Ml(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 cre(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 ${e1(r.length)} is larger than the maximum size of ${e1(l)}, attempting to reduce image quality`);let o=await DMl(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 cre(t,e,l){let n=await rSe(l),I=l.length;return!n.width||!n.height?{exceedsSizeLimit:I>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await MMl(t,l),exceedsDimensionLimit:await UMl(e,l)}}async function UMl(t,e){let l=await rSe(e);return!l.width||!l.height?!1:l.width>t||l.height>t}async function MMl(t,e){return e.length>t}async function _Ml(t,e,l,n,I){try{if(!dYt(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=cYt(e).resize(R,w,{fit:"inside",withoutEnlargement:!0});return ISe(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:L}=await cre(n,l,w);!C&&!L?(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 DMl(t,e,l,n,I){try{let r=I==="image/png"?80:100,a=I==="image/png"?Math.floor(r*.4):20,s=await ISe(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 ISe(t,e,E,I);if(!R)return u;let{exceedsSizeLimit:w,exceedsDimensionLimit:C}=await cre(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 ISe(t,e,l,n){let I=cYt(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 dre=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function zMl(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=xMl(a);if(s)for(let o in s){if(I.length>=e)break;let d=s[o].contents,u=nSe(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):BMl(p)?(W=!0,h=SMl(s[o],p,l),I.push({url:h,guid:G.guid,kind:"committed_attachment"})):ure(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,L,S,U]=w;E.owner=C,E.repo=L,E.branch=S,E.path=U,n.info(`Repository metadata extracted: owner=${C}, repo=${L}, branch=${S}, path=${U}`)}else n.info(`Failed to extract repository metadata from URL: ${E.url}`)}}}}return I}function PMl(t,e){let l=e.flatMap(I=>jB(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 yNe=class{async resolveRepositoryImages(e,l,n,I,r,a){if(l<=0)return[];let s=zMl(e,l,n,I);this.logger.debug(`Found ${s.length} repository image URLs to process`);let o=PMl(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 dre,d=new Map;for(let G of e.messages)if(G.role=="user")if(typeof G.content=="string"){let p=nSe(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=nSe(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,nYt(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(jB).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:u},e.messages.some(G=>jB(G))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,l,n){let I=W$(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(!dYt(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 WNe(this.logger,n,l,ore,a,o),n.resizedBase64ImagesSize.push(o?.length??-1),!o)return["",new lSe(`Image size exceeds maximum size of ${e1(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=MGt(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 (${e1(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),Ii(this.settings,"copilot_swe_agent_resize_image_references")){if(!await WNe(this.logger,l,n,ore,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 cre(n,ore,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 ${e1(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 JMl(s.guid,W$(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 ${e1(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(jMl(I,n));if(r.length===0){let a=await $Ml(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*jMl(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 KMl="playwright-browser_take_screenshot";function qMl(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function $Ml(t,e){if(t.function.name!==KMl)return;e.debug("Adding images using Playwright params fallback strategy");let l=JSON.parse(t.function.arguments);if(qMl(l)){let n=ire.isAbsolute(l.filename)?l.filename:ire.join(eSe,l.filename);e.debug(`Image from Playwright params: ${l.filename}. Updated to ${n}.`);let I=await t_l(n,e);if(I){let r=I.buffer.toString("base64");return{url:`data:${I.mimeType};base64,${r}`,isScreenshot:!0}}}}function e_l(t){switch(ire.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function dYt(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 t_l(t,e){try{if(!ure(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let l=e_l(t);return l?{buffer:await LMl.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 sP=class{logger;constructor(e){this.logger=e}toJSON(){return"BasicTruncator"}async*preRequest(e){let l=await uYt(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit);l.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(l)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:l}}},oP=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=oYt(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=await uYt(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"}},l_l=.95;function uYt(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=>Dpe(h,l)),s=sF(JSON.stringify(e),l),o=n*l_l,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(nA).filter(S=>S.function.name===xee),w=E.filter(nA).filter(S=>S.function.name!==xee),C=R.length===0,L=new Set(w.map(S=>S.id));if(w.length>0&&(W.tool_calls=R,a[h]=Dpe(W,l)),C&&(u.add(h),G+=a[h]),L.size>0)for(let S=h+1;S<t.length;S++){let U=t[S];if(U.role==="tool"&&L.has(U.tool_call_id)&&(u.add(S),G+=a[S],L.delete(U.tool_call_id),L.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}}c();var HA=class extends UH{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,l){}endGroup(e){}};c();c();var mYt={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 ENe(t,e,l){let n=(l||mYt)[t.toLowerCase()],I=new Set;for(;typeof n=="string";){if(I.has(n))return!1;I.add(n),n=mYt[n]}if(!n)return!1;let r=e.toLowerCase();return n.tools.some(a=>a.toolName===r)}var n_l="image";var I_l="resource",r_l=60*1e3*2,a_l={timeout:r_l};var aSe=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:I_l,data:u.blob,mimeType:u.mimeType||"application/octet-stream"}):u&&u.text&&(I+=u.text)}else d.type==="image"&&r.push({type:n_l,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=gxe(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=Axe(I,l)}this.logger.debug(`Tool invocation result: ${a}`);let s={},o=a?yc(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 AZe(G.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return ZZe;case"denied-interactively-by-user":return hZe;default:fN(G,`Unhandled permission result kind: ${G}`)}},safeForTelemetry:r.safeForTelemetry}}return Object.values(n)}};var mre=class t extends aSe{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,{...a_l,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:ENe(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 RNe=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=wGt(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"}}}}},sSe={remindWhereToDoWork:{instruction:rYt,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:NNe.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:NNe.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:NNe.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};c();c();c();var oSe={agent:"sweagent-capi",model:"claude-sonnet-4"},GYt=oSe;function iSe(t){if(!t)return GYt;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 Dvt from"path";c();c();c();c();var VNe="4.12.0",KB="04b07795-8ddb-461a-bbee-02f9e1bf7b46",bYt="common",YNe;(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"})(YNe||(YNe={}));var bre=YNe.AzurePublicCloud,pYt="login.microsoftonline.com",hYt=["*"],AYt="cae",ZYt="nocae",gYt="msal.cache";var cSe;var s_l,QNe,WYt;function yYt(){return QNe!==void 0&&WYt!==void 0}function o_l(t){let e={cache:{},broker:{...t.brokerOptions,isEnabled:t.brokerOptions?.enabled??!1,enableMsaPassthrough:t.brokerOptions?.legacyEnableMsaPassthrough??!1}};if(t.tokenCachePersistenceOptions?.enabled){if(cSe===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||gYt;e.cache.cachePlugin=cSe({name:`${l}.${ZYt}`,...t.tokenCachePersistenceOptions}),e.cache.cachePluginCae=cSe({name:`${l}.${AYt}`,...t.tokenCachePersistenceOptions})}return t.brokerOptions?.enabled&&(e.broker.nativeBrokerPlugin=c_l(t.isVSCodeCredential||!1)),e}var NYt={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(" ")},i_l={vsCode:{credentialName:"Visual Studio Code Credential",packageName:"@azure/identity-vscode",pluginVar:"vsCodePlugin",get brokerInfo(){return WYt}},native:{credentialName:"Broker for WAM",packageName:"@azure/identity-broker",pluginVar:"nativeBrokerPlugin",get brokerInfo(){return s_l}}};function c_l(t){let{credentialName:e,packageName:l,pluginVar:n,brokerInfo:I}=i_l[t?"vsCode":"native"];if(I===void 0)throw new Error(NYt.missing(e,l,n));if(I.broker.isBrokerAvailable===!1)throw new Error(NYt.unavailable(e,l));return I.broker}var EYt={generatePluginConfiguration:o_l};c();c();c();function d_l(t){return t&&typeof t.error=="string"&&typeof t.error_description=="string"}var YYt="CredentialUnavailableError",qn=class extends Error{constructor(e,l){super(e,l),this.name=YYt}},wNe="AuthenticationError",J5=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(d_l(l))I=RYt(l);else if(typeof l=="string")try{let r=JSON.parse(l);I=RYt(r)}catch{e===400?I={error:"invalid_request",errorDescription:`The service indicated that the request was invalid.
|
|
1623
1623
|
|
|
1624
1624
|
${l}`}:I={error:"unknown_error",errorDescription:`An unknown error has occurred. Response body:
|
|
1625
1625
|
|
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.337-
|
|
4
|
+
"version": "0.0.337-11",
|
|
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": "
|
|
36
|
+
"gitCommit": "a06710d"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"node-pty": "npm:@devm33/node-pty@^1.0.8",
|
package/sdk/index.js
CHANGED
|
@@ -1232,7 +1232,7 @@ ${BSe()}
|
|
|
1232
1232
|
|
|
1233
1233
|
<reminder>
|
|
1234
1234
|
The user may have mentioned images, if so these will have been attached to this message, in the order they were mentioned
|
|
1235
|
-
</reminder>`),I.trim()},OP={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."},USe=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${nbe(t)}. Commit changes by using the **report_progress** tool.</reminder>`;G();var ybe="/tmp/playwright-logs",$kI="0.0.40",Fbe=[`@playwright/mcp@${$kI}`,"--viewport-size","1280, 720","--output-dir",ybe],oOl=[...Fbe,"--isolated"];var Qbe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},gbe=2e3;async function IfI(t,e,I,l){let n={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},c=`${UZe(l)}/${t}`;I.info(`Downloading image from ${c}`);try{let a=await fetch(c,{method:"GET",headers:n});if(I.info(`Response status: ${a.status} ${a.statusText}`),I.debug(`Download Response URL: ${a.url}`),!a.ok){I.info(`Failed to download image, status: ${a.status}, statusText: ${a.statusText}`);try{let h=await a.text();I.info(`Error response body: ${h}`)}catch(h){I.info(`Could not read error response body: ${h}`)}return{size:0}}let r=(await a.json()).url;if(!r)return I.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let o=await fetch(r,{method:"GET"});if(!o.ok)return I.error(`Failed to download image: ${o.status} ${o.statusText}`),{size:0};let d=await o.arrayBuffer(),i=d.byteLength;return I.info(`Downloaded content size: ${Gm(i)}`),{size:i,buffer:Buffer.from(d),mimeType:o.headers.get("content-type")||void 0}}catch(a){return I.error("Network error downloading image"),a instanceof Error&&(I.info(`Error message: ${a.message}`),I.info(`Error stack: ${a.stack}`)),{size:0}}}function Abe(t,e,I,l){let n=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,c=/!\[.*?\]\((.*?)\)/g,a=[];return a.push(...SSe(t,e,n,I,l)),a.push(...SSe(t,e,c,I,l)),a}function SSe(t,e,I,l,n){let c=t.matchAll(I),a=[],s=/\/([a-f0-9-]+)$/;for(let r of c){let o=cfI(r[1],e),d=afI(r[1],e,n);if(o||d){let i=r[1].match(s),h={url:r[1],guid:"",kind:d?"legacy_attachment":"attachment"};i&&i.length>1&&(h.guid=i[1]),a.push(h)}else if(l){let i={url:r[1],guid:"",kind:"committed_attachment"};a.push(i)}}return a}function tfI(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&Hbe(t)}function Hbe(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function lfI(t){try{let e=/Here are relevant code snippets from the repository that might help with this task:\s*(\[[\s\S]*?\])(?=\n|$)/,I=t.match(e);if(!I?.[1]||I[1].length<=1)return null;let l=I[1].trim();return JSON.parse(l)}catch{return null}}function nfI(t,e,I){if(!t?.url||!t?.ref||!t?.path)throw new Error("Invalid repository insight: missing required fields");if(!e||e.trim()==="")throw new Error("Invalid image path: path cannot be empty");let l=t.url.split("/").slice(3,5).join("/"),n=t.ref.split("/")[2],c;if(e.startsWith("/"))c=e.slice(1);else{let s=t.path,r=Z9.dirname(s);c=Z9.resolve("/",r,e).slice(1)}return`${I}/${l}/blob/${n}/${c}`}function cfI(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function afI(t,e,I){return e&&new RegExp(`^${e}/[\\w.-]+/[\\w.-]+/assets/\\d+/[^.]+$`).test(t)?(I.debug(`Legacy GitHub asset URL detected: ${t}`),!0):!1}async function Ebe(t){let{width:e,height:I}=EUe(t);if(e===void 0||I===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:I}}async function OSe(t,e,I,l,n,c){t.debug(`Checking if image is valid size and dimensions. Max size: ${I}, Max dimension: ${l}`);let{exceedsSizeLimit:a,exceedsDimensionLimit:s}=await u9(I,l,c);if(!s&&!a)return t.debug("Image is within size and dimension limits."),c;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${l}, attempting to resize`);let[r,o]=await GfI(t,c,l,I,n);if(!r){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,o==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:d}=await u9(I,l,r);if(d){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),r}if(a){t.debug(`Image size ${Gm(c.length)} is larger than the maximum size of ${Gm(I)}, attempting to reduce image quality`);let r=await ofI(t,c,l,I,n);if(!r){t.debug("Failed to reduce image quality to fit within the maximum size, skipping"),e.imagesFailedToReduceQuality++,e.imagesRemovedDueToSize++;return}return e.imagesWithLoweredQuality++,t.debug("Image quality successfully reduced."),r}}async function u9(t,e,I){let l=await Ebe(I),n=I.length;return!l.width||!l.height?{exceedsSizeLimit:n>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await rfI(t,I),exceedsDimensionLimit:await sfI(e,I)}}async function sfI(t,e){let I=await Ebe(e);return!I.width||!I.height?!1:I.width>t||I.height>t}async function rfI(t,e){return e.length>t}async function GfI(t,e,I,l,n){try{if(!TSe(t,n))return[void 0,"unsupported_mime_type"];let c=await Ebe(e);if(!c.width||!c.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let a=async(N,Y)=>{let y=MSe(e).resize(N,Y,{fit:"inside",withoutEnlargement:!0});return wbe(t,await y.toBuffer(),void 0,n)},s=Math.min(I,c.width),r=Math.min(I,c.height),o=await a(s,r);if(o&&o.length<=l)return[o,void 0];let d=Math.max(s,r),i=1,h=d-1,p,Z=0,u=10;for(;i<=h&&Z<u;){let N=Math.floor((i+h)/2),Y=await a(N,N);if(!Y)break;let{exceedsSizeLimit:y,exceedsDimensionLimit:Q}=await u9(l,I,Y);!y&&!Q?(p=Y,i=N+1):h=N-1,Z++}return[p,void 0]}catch(c){return t.error(`Failed to resize image for upload: ${c instanceof Error?c.message:String(c)}`),[void 0,"unknown"]}}async function ofI(t,e,I,l,n){try{let c=n==="image/png"?80:100,a=n==="image/png"?Math.floor(c*.4):20,s=await wbe(t,e,a,n);if(!s||s.length>l)return;let r=a,o=c,d,i=0,h=10,p=r,Z=o-1;for(;p<=Z&&i<h;){let u=Math.floor((p+Z)/2),N=await wbe(t,e,u,n);if(!N)return d;let{exceedsSizeLimit:Y,exceedsDimensionLimit:y}=await u9(l,I,N);!Y&&!y?(d=N,p=u+1):Z=u-1,i++}return d}catch(c){t.error(`Failed to reduce image quality: ${c instanceof Error?c.message:String(c)}`);return}}async function wbe(t,e,I,l){let n=MSe(e);switch(l){case"image/png":return I?n.png({quality:I}).toBuffer():n.png().toBuffer();case"image/jpeg":return I?n.jpeg({quality:I}).toBuffer():n.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${l}`);return}}var Xbe=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function dfI(t,e,I,l){if(e<=0)return[];let n=[];for(let c of t){if(c.role!=="user"||n.length>=e)continue;let a=typeof c.content=="string"?c.content:JSON.stringify(c.content),s=lfI(a);if(s)for(let r in s){if(n.length>=e)break;let o=s[r].contents,d=Abe(o,I,!0,l);for(let i of d){if(n.length>=e)break;let h=i.url,p="",Z=!1;if(i.kind==="attachment"||i.kind==="legacy_attachment"?n.push(i):tfI(h)?(Z=!0,p=nfI(s[r],h,I),n.push({url:p,guid:i.guid,kind:"committed_attachment"})):Hbe(h)&&h.startsWith(I)&&(Z=!0,n.push({...i,kind:"committed_attachment"})),Z){let u=n[n.length-1],N=new RegExp(`^${I}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),Y=u.url.match(N);if(l.info(`Blob match for ${u.url}: ${JSON.stringify(Y)}`),Y&&Y.length===5){let[,y,Q,A,w]=Y;u.owner=y,u.repo=Q,u.branch=A,u.path=w,l.info(`Repository metadata extracted: owner=${y}, repo=${Q}, branch=${A}, path=${w}`)}else l.info(`Failed to extract repository metadata from URL: ${u.url}`)}}}}return n}function ifI(t,e){let I=e.flatMap(n=>MR(n)?n.content.flatMap(c=>c.type==="image_url"?c.image_url.url:[]):[]),l=new Set(I);return t.filter(n=>!l.has(n.url))}var MP=class{async resolveRepositoryImages(e,I,l,n,c,a){if(I<=0)return[];let s=dfI(e,I,l,n);this.logger.debug(`Found ${s.length} repository image URLs to process`);let r=ifI(s,e),o=await this.processImageReferences(r,c,a);return this.logger.debug(`Processed ${o.addedImages.length} repository image URLs`),o.addedImages}async*preRequest(e){let I=e.modelInfo;if(!I.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!I.capabilities?.supports?.vision||!this.settings.featureFlags?.copilot_swe_agent_vision){this.logger.debug("Vision not supported or enabled, skipping image processing");return}if(!this.gitHubServerUrl){this.logger.debug("GitHub server URL is not set, skipping image processing");return}for(let i of this.messagesToInsertOnNextPreRequest)e.messages.push(i),yield{kind:"message",message:i,turn:e.turn};this.messagesToInsertOnNextPreRequest.splice(0);let l=[],n=I.capabilities.limits.vision?.max_prompt_images??1,c=I.capabilities.limits.vision?.max_prompt_image_size??3145728,a=0,s=[],r=new Xbe,o=new Map;for(let i of e.messages)if(i.role=="user")if(typeof i.content=="string"){let h=Abe(i.content,this.gitHubServerUrl,!1,this.logger).filter(Z=>!this.processedImageUrls.has(Z.url)),p=await this.processImageReferences(h,c,r);s.push(...p.addedImages)}else{let h=[];for(let[p,Z]of i.content.entries()){if(Z.type==="text"){let u=Abe(Z.text,this.gitHubServerUrl,!1,this.logger).filter(Y=>!this.processedImageUrls.has(Y.url)),N=await this.processImageReferences(u,c,r);s.push(...N.addedImages)}else if(Z.type==="image_url"){if(Z.image_url.url.startsWith("data:")){let[u,N]=await this.extractAndUploadImageData(Z,c,r);if(u===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(u),p>=1&&h.length>0){let Y=h.at(-1);Y&&Y.type==="text"&&Y.text&&Y.text.includes("screenshot")&&o.set(u,xSe(u))}h.pop();continue}a++}h.push(Z)}i.content=h}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${n}`);a<n&&s.length>0;){let i=s.shift();if(!i){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(i)){this.logger.debug(`Skipping already processed image url: ${i}`);continue}this.processedImageUrls.add(i);let h=`Here is the image url: ${i}`;o.has(i)&&(h=o.get(i)||h),this.logger.debug(`Adding image url: ${i}`),l.push({role:"user",content:[{type:"text",text:h},{type:"image_url",image_url:{url:i}}]}),a++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),a<n)){let i=await this.resolveRepositoryImages(e.messages,n-a,this.settings.github?.serverUrl||"",this.logger,c,r);this.logger.debug(`Resolved ${i.length} repository image URLs`);for(let h of i){if(a>=n)break;if(this.processedImageUrls.has(h)){this.logger.debug(`Skipping already processed repository image url: ${h}`);continue}l.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:h}}]}),this.processedImageUrls.add(h),a++}}let d={imagesExtractedCount:r.extractedImagesSize.length,base64ImagesCount:r.base64ImagesSize.length,imagesRemovedDueToSize:r.imagesRemovedDueToSize,imagesRemovedDueToDimensions:r.imagesRemovedDueToDimensions,imagesResized:r.imagesResized,imagesResolvedFromGitHubMCPCount:r.imagesResolvedFromGitHubMCPSize.length};for(let i=0;i<r.base64ImagesSize.length;i++)d[`base64ImageSize_${i}`]=r.base64ImagesSize[i];for(let i=0;i<r.resizedBase64ImagesSize.length;i++)d[`resizedBase64ImageSize_${i}`]=r.resizedBase64ImagesSize[i];for(let i=0;i<r.extractedImagesSize.length;i++)d[`extractedImageSize_${i}`]=r.extractedImagesSize[i];for(let i=0;i<r.imagesResolvedFromGitHubMCPSize.length;i++)d[`imagesResolvedFromGitHubMCPSize_${i}`]=r.imagesResolvedFromGitHubMCPSize[i];l.length>0&&this.logger.debug(`Using ${l.length} image messages`);for(let i of l)yield{kind:"message",message:i,turn:e.turn},e.messages.push(i);d.allImagesSendToLlm=e.messages.filter(MR).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:d},e.messages.some(i=>MR(i))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,I,l){let n=l1(this.settings);if(!n)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let c=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!c||c.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let a=c[1];if(!TSe(this.logger,a))return[""];let s=c[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let r=Buffer.from(s,"base64");if(l.base64ImagesSize.push(r.length),r=await OSe(this.logger,l,I,gbe,a,r),l.resizedBase64ImagesSize.push(r?.length??-1),!r)return["",new Qbe(`Image size exceeds maximum size of ${Gm(I)}`)];s=r.toString("base64");try{let o=await this.uploadBase64ImageData(s,a,n);return o?(this.logger.debug(`Uploaded image url: ${o}`),e.image_url.url=o,[o]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(o){let d=o instanceof Error?o.message:String(o);return this.logger.debug(`Error during image upload: ${d}`),[""]}}async uploadBase64ImageData(e,I,l){try{let n=zZe(this.settings),c=I.split("/").at(1),a=`image-${Date.now()}.${c}`;if(!e||e.trim()==="")return this.logger.error("Empty image data provided for upload"),null;let s=Buffer.from(e,"base64");if(s.length===0)return this.logger.error("Converted image data has zero length"),null;let r=this.settings.github?.repo?.id;if(!r)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let o=`${n}?name=${encodeURIComponent(a)}&content_type=${encodeURIComponent(I)}&repository_id=${r}`;this.logger.debug(`Uploading image data (${Gm(s.length)}) to ${n} with name ${encodeURIComponent(a)} and content type ${encodeURIComponent(I)}`);let d={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+l},i=await fetch(o,{method:"POST",headers:d,body:s}).catch(p=>{throw p instanceof Error?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof p=="object"&&p!==null&&"code"in p&&"message"in p?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):this.logger.error(`Failed to upload image: ${String(p)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:p?.code,message:p?.message,stack:p?.stack,name:p?.name,cause:p?.cause},null,2)}`),p});if(!i.ok){let p=await i.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${i.status} ${i.statusText} - ${p}`),null}let h=await i.json();return this.logger.debug(`Upload result: ${JSON.stringify(h,null,2)}`),h.url||null}catch(n){return this.logger.error(`Error handling image upload: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&this.logger.debug(`Stack trace: ${n.stack}`),null}}async getRepositoryImageViaTools(e){if(this.logger.debug(`Attempting to retrieve repository image: ${e.owner}/${e.repo}/${e.path}@${e.branch}`),this.githubGetFileContentsTool){this.logger.debug(`GitHub MCP tool found, calling with image reference: ${JSON.stringify(e)}`);try{let I=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof I}`),this.logger.debug(`GitHub tool call result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`),typeof I=="object"&&I!==null&&"binaryResultForLlm"in I&&Array.isArray(I.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${I.binaryResultForLlm.length} items`);try{for(let l of I.binaryResultForLlm)if(l.data&&l.mimeType){let n=Buffer.from(l.data,"base64"),c=l.mimeType;return{buffer:n,mimeType:c}}}catch(l){this.logger.error(`Failed to parse GitHub tool response: ${l}`),this.logger.debug(`binaryResultForLlm length: ${I.binaryResultForLlm?.length||0}`)}}else typeof I=="string"?this.logger.debug(`GitHub tool returned string result: ${I}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`)}catch(I){this.logger.error(`Error calling GitHub MCP tool: ${I}`)}}else this.logger.debug("GitHub MCP tool 'github-mcp-server-get_file_contents' not available");return this.logger.debug("Failed to retrieve repository image, returning null"),null}async getImgRefsSmallerThanMaxSize(e,I,l){let n=[],c=await Promise.all(e);for(let{imgRef:a,attachment:s}of c)if(this.logger.debug(`Processing attachment for ${a.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(I.extractedImagesSize.push(s.buffer.length),vl(this.settings,"copilot_swe_agent_resize_image_references")){if(!await OSe(this.logger,I,l,gbe,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}n.push(a.url)}else{let r=await u9(l,gbe,s.buffer);if(this.logger.debug(`Image size check for ${a.url}: size=${s.buffer.length}, maxSize=${l}, exceedsSize=${r.exceedsSizeLimit}, exceedsDimensions=${r.exceedsDimensionLimit}`),r.exceedsSizeLimit?(I.imagesRemovedDueToSize++,this.logger.debug(`Image ${a.url} removed due to size (${s.buffer.length} > ${l})`)):r.exceedsDimensionLimit&&(I.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${a.url} removed due to dimensions`)),r.exceedsSizeLimit||r.exceedsDimensionLimit){this.processedImageUrls.add(a.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${Gm(l)}.`);continue}n.push(a.url),this.logger.debug(`Image ${a.url} passed size checks and added to results`)}else this.processedImageUrls.add(a.url),this.logger.debug(`Skipping image ${a.url} - could not fetch image data`);return n}async processImageReferences(e,I,l){let n=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${n}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let c=e.filter(s=>!this.processedImageUrls.has(s.url)).map(async s=>{if(this.logger.debug(`Processing image reference: ${JSON.stringify(s,null,2)}`),s.kind==="committed_attachment"){this.logger.debug(`Detected repository image - Owner: ${s.owner}, Repo: ${s.repo}, Branch: ${s.branch}, Path: ${s.path}`);let r=await this.getRepositoryImageViaTools(s);return r?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${r.buffer.length} bytes`),l.imagesResolvedFromGitHubMCPSize.push(r.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:r?.buffer?.length||0,mimeType:r?.mimeType||"",buffer:r?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await IfI(s.guid,l1(this.settings),this.logger,this.settings)}}),a=await this.getImgRefsSmallerThanMaxSize(c,l,I);return this.logger.debug(`Processed image references, found ${a.length} attachments smaller than max size of ${Gm(I)}`),{addedImages:a}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,I,l){this.logger=e,this.settings=I,this.gitHubServerUrl=I.github?.serverUrl,this.githubGetFileContentsTool=l,this.processedImageUrls=new Set,this.messagesToInsertOnNextPreRequest=[]}toJSON(){return"CAPIImageProcessor"}async onRequestError(e){}async preErrorThrow(e){this.processedImageUrls.size>0&&(e.isVisionFlow=!0)}async postToolExecution(e){let I=e.modelInfo,l=e.toolCall.function.name,n=e.toolResult;if(I?.capabilities?.supports?.vision){let c=Array.from(bfI(n,l));if(c.length===0){let a=await pfI(e.toolCall,this.logger);a&&c.push(a)}this.insertImageUrlMessages(c)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let I of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:I.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:I.url}}]})}};function*bfI(t,e){for(let I of t.binaryResultForLlm??[])I.type==="image"&&(yield{url:`data:${I.mimeType};base64,${I.data}`,isScreenshot:e.toLowerCase().includes("screenshot")})}var mfI="playwright-browser_take_screenshot";function hfI(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function pfI(t,e){if(t.function.name!==mfI)return;e.debug("Adding images using Playwright params fallback strategy");let I=JSON.parse(t.function.arguments);if(hfI(I)){let l=Z9.isAbsolute(I.filename)?I.filename:Z9.join(ybe,I.filename);e.debug(`Image from Playwright params: ${I.filename}. Updated to ${l}.`);let n=await ufI(l,e);if(n){let c=n.buffer.toString("base64");return{url:`data:${n.mimeType};base64,${c}`,isScreenshot:!0}}}}function ZfI(t){switch(Z9.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function TSe(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 ufI(t,e){try{if(!Hbe(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let I=ZfI(t);return I?{buffer:await efI.readFile(t),mimeType:I}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(I){return e.error(`Failed to read image from disk: ${I instanceof Error?I.message:String(I)}`),null}}G();var hE=class{logger;constructor(e){this.logger=e}toJSON(){return"BasicTruncator"}async*preRequest(e){let I=await jSe(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit);I.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(I)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:I}}},TP=class{truncateOnNextRequest=!1;userMessageToTruncateUpTo;logger;constructor(e,I){this.userMessageToTruncateUpTo=e,this.logger=I,this.logger.debug(`AnthropicTokenLimitErrorTruncator will truncate up to message: ${JSON.stringify(e)}`)}async*preRequest(e){if(this.truncateOnNextRequest){this.truncateOnNextRequest=!1;let I=H3e(this.userMessageToTruncateUpTo,e.messages);if(I===-1){this.logger.debug(`Failed to find user message to truncate up to: ${JSON.stringify(this.userMessageToTruncateUpTo)}`),this.logger.debug(`Current messages: ${JSON.stringify(e.messages)}`);return}let l=await jSe(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit,I);l.tokensRemovedDuringTruncation>0&&this.logger.debug(`AnthropicTokenLimitErrorTruncator truncated: ${JSON.stringify(l)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"AnthropicTokenLimitErrorTruncator",truncateResult:l}}}async preErrorThrow(e){}async onRequestError(e){if(e){if(typeof e=="object"&&"code"in e&&e.code==="model_max_prompt_tokens_exceeded"){this.truncateOnNextRequest=!0;return}let I=[JSON.stringify(e)];e instanceof Error&&(I.push(e.message),e.cause instanceof Error?I.push(e.cause.message):e.cause&&I.push(JSON.stringify(e.cause)));let l="Input length and `max_tokens` exceed context limit";this.logger.debug(`Looking for error amongst: ${I.join(", ")}`),I.some(n=>n.includes(l))&&(this.truncateOnNextRequest=!0)}}toJSON(){return"AnthropicTokenLimitErrorTruncator"}},WfI=.95;function jSe(t,e,I,l,n){let c=t.length;if(c===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:c,postTruncationTokensInMessages:0,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(p=>xx(p,I)),s=rp(JSON.stringify(e),I),r=l*WfI,o=a.reduce((p,Z)=>p+Z,0)+s;if(o<=r)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,i=0,h=Math.min(n??t.length,t.length);for(let p=0;p<h;p++){let Z=t[p];if(Z.role!=="system"&&Z.role!=="tool"&&Z.role!=="user"){if(Z.role==="assistant"){let u=Z.tool_calls||[],N=u.filter(Io).filter(A=>A.function.name===rC),Y=u.filter(Io).filter(A=>A.function.name!==rC),y=N.length===0,Q=new Set(Y.map(A=>A.id));if(Y.length>0&&(Z.tool_calls=N,a[p]=xx(Z,I)),y&&(d.add(p),i+=a[p]),Q.size>0)for(let A=p+1;A<t.length;A++){let w=t[A];if(w.role==="tool"&&Q.has(w.tool_call_id)&&(d.add(A),i+=a[A],Q.delete(w.tool_call_id),Q.size===0))break}}if(o-i<r)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}G();var ni=class extends ap{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,I){}endGroup(e){}};G();G();var DSe={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"}]},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 jP(t,e,I){let l=(I||DSe)[t.toLowerCase()],n=new Set;for(;typeof l=="string";){if(n.has(l))return!1;n.add(l),l=DSe[l]}if(!l)return!1;let c=e.toLowerCase();return l.tools.some(a=>a.toolName===c)}var NfI="image";var YfI="resource",VfI=60*1e3*2,RfI={timeout:VfI};var vbe=class{constructor(e,I,l){this.settings=e;this.logger=I;this.permissions=l}async invokeTool(e,I,l="hidden_characters"){let n=await this.doInvokeTool(e,I);return this.invokeToolResponseToToolResult(n,l)}invokeToolResponseToToolResult(e,I){let l=e.content||[],n="",c=[];for(let o of l)if(o.type==="text")n+=o.text||"";else if(o.type==="resource"){let d=o.resource;d&&d.blob?c.push({type:YfI,data:d.blob,mimeType:d.mimeType||"application/octet-stream"}):d&&d.text&&(n+=d.text)}else o.type==="image"&&c.push({type:NfI,data:o.data,mimeType:o.mimeType});let a=n;if(n==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),a=n;else try{let o=JSON.parse(n),d=Uie(o,I);a=JSON.stringify(d)}catch(o){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${o}`),a=Bie(n,I)}this.logger.debug(`Tool invocation result: ${a}`);let s={},r=a?Pn(a,"output"):"";return e.isToolError?{textResultForLlm:a,resultType:"failure",error:a,sessionLog:r,toolTelemetry:s}:{textResultForLlm:a,binaryResultForLlm:c,resultType:"success",sessionLog:r,toolTelemetry:s}}async loadTools(e){let I=await this.loadToolsFromProvider(e),l={};for(let[n,c]of Object.entries(I)){let a=c.filterMode||"hidden_characters";l[n]={name:c.name,title:c.title||c.name,description:c.description,input_schema:c.input_schema,callback:async s=>{let r=I[n].serverName,o=I[n].name,d=I[n].title;if(!this.permissions.requestRequired)return this.invokeTool(n,s,a);let i=await this.permissions.request({kind:"mcp",serverName:r,toolName:o,toolTitle:d,args:s,readOnly:!!c.readOnly});switch(i.kind){case"approved":return this.invokeTool(n,s,a);case"denied-by-rules":return rO(i.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return GO;case"denied-interactively-by-user":return sO;default:NV(i,`Unhandled permission result kind: ${i}`)}},safeForTelemetry:c.safeForTelemetry}}return Object.values(l)}};var W9=class t extends vbe{toolIdToClientInfo=new Map;constructor(e,I,l={requestRequired:!1}){super(e,I,l)}async doInvokeTool(e,I){let l=this.toolIdToClientInfo.get(e);if(!l)throw new Error(`No MCP client found for tool ID: ${e}`);let n=l.mcpClient,c=t.getToolNameFromIdAndClientName(e,l.clientName),a=await n.callTool({name:c,arguments:I},void 0,{...RfI,onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(a.content))throw new Error("Expected array of results");return{content:a.content,isToolError:a.error!==void 0&&a.error!==null||a.isError===!0}}async loadToolsFromProvider(e){let I={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let l of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(l.name)){this.logger.debug(`Skipping tool ${l.name} for client ${e.clientName}`);continue}let n=t.getToolIdFromClientAndToolName(e.clientName,l.name);this.toolIdToClientInfo.set(n,e);let c;e.safeForTelemetry===!0?c={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?c=e.safeForTelemetry:c={name:jP(e.clientName,l.name),inputsNames:!1},this.logger.debug(`Adding tool: ${n}`);let a;e.filterMapping===void 0?a="hidden_characters":typeof e.filterMapping=="object"?a=e.filterMapping[l.name]||"hidden_characters":a=e.filterMapping,I[n]={serverName:e.clientName,name:n,title:l.title||l.annotations?.title||l.name,description:l.description||"",input_schema:l.inputSchema,readOnly:l.annotations?.readOnlyHint,safeForTelemetry:c,filterMode:a}}return I}static getToolIdFromClientAndToolName(e,I){return`${e}-${I}`}static getToolNameFromIdAndClientName(e,I){return e.substring(I.length+1)}};G();var DP=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,I,l,n,c,a){this.settings=e,this.logger=I,this.gitHandler=l,this.location=n,this.commitPriorToCompletionWithTools=c,this.jitInstructions=a||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let I,l=async()=>{if(I===void 0)try{I=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(a){this.logger.error(`Failed to get changed paths, err: ${a}`),I=1}return I},n;for(let[a,s]of Object.entries(this.jitInstructions)){let r=IZe(this.settings,s.percentRemainingOfTimeout);r.isWithin&&(!s.whenNoPathsChanged||await l()===0)&&(!n||r.withinMs<n[0])&&(n=[r.withinMs,s.instruction])}let c=n?.[1];if(typeof c=="function"&&(c=c(this.location)),c&&!this.emittedJitInstructions.has(c)){this.logger.debug(`Adding JIT instructions to the history: ${c}`),this.emittedJitInstructions.add(c);let a={role:"user",content:c};e.messages.push(a),yield{kind:"message",message:a,turn:e.turn,source:"jit-instruction"}}}}},Jbe={remindWhereToDoWork:{instruction:USe,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:OP.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:OP.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:OP.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};G();G();function Lbe(t){if(!t)return E3e;let[e,...I]=t?.split(":")??[t,void 0],l=I.join(":")||void 0;return{agent:e||void 0,model:l||void 0}}G();G();function KP(t){return t.kind==="message"&&t.message.role==="assistant"}function KSe(t){return t.kind==="message"&&t.message.role==="user"}function PSe(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function qSe(t){return t.kind==="message"&&t.message.role==="tool"}function yfI(t,e){return t.toolCalls.find(I=>I.toolCallId===e)}function FfI(t,e){let I=e.function.name;try{let l=JSON.parse(e.function.arguments||"{}"),c=t.find(a=>a.name===I)?.safeForTelemetry||{name:!1,inputsNames:!1};return{toolCallId:e.id,toolName:I,arguments:e.function.arguments,safeForTelemetryToolName:c===!0||c.name?I:Y2(I),safeForTelemetryArguments:c===!0||c.inputsNames?A3e(l):""}}catch{return{toolCallId:e.id,toolName:I,arguments:e.function.arguments,safeForTelemetryToolName:Y2(I),safeForTelemetryArguments:""}}}var PP=class{forAgent;turnDataCache;emittedTurns=new Set;callback;settings;toolsInUse;constructor(e,I,l,n){this.forAgent=e,this.turnDataCache=new Map,this.emittedTurns=new Set,this.callback=I,this.settings=l,this.toolsInUse=n}getTurnData(){return this.turnDataCache}async ingestEvent(e){let I,l;if("turn"in e&&typeof e.turn=="number"){if(I=e.turn+1,this.emittedTurns.has(I))return;this.turnDataCache.has(I)||this.turnDataCache.set(I,{featureFlagsAsString:xq(this.settings),toolCalls:[],toolCallExecutions:[],turn:I}),l=this.turnDataCache.get(I)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(l,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(l={...l,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?l={...l,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?l={...l,endTimeMs:e.timestampMs,retriesUsed:(l.retriesUsed??0)+1}:e.kind==="turn_failed"?l={...l,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(l={...l,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?l={...l,truncateEvent:e}:e.kind==="image_processing"?l={...l,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?l={...l,largeImagesRemoved:(l.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(l.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(l={...l,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:w3e(e.requestMessages)},e.kind==="model_call_success"&&(l={...l,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):KSe(e)&&e.source==="jit-instruction"?l={...l,jitInstructionsAdded:(l?.jitInstructionsAdded??0)+1}:KP(e)&&e.message.tool_calls?l={...l,toolCalls:l.toolCalls.concat(e.message.tool_calls.map(n=>({...FfI(this.toolsInUse,n)})))}:qSe(e)&&(l={...l,toolCallExecutions:l.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(I,l),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(I),this.emittedTurns.add(I),this.turnDataCache.delete(I))}async emitTurnTelemetry(e){let I=this.turnDataCache.get(e);if(I){let l={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{model:I.model||"default",modelInfo:I.modelInfo||"{}",api_call_id:I.api_call_id,provider_call_id:I.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(I.toolCalls.map(n=>({toolCallId:n.toolCallId,toolName:n.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(I.toolCallExecutions),error:I.error,featureFlags:xq(this.settings),conversationStructureSummary:I.conversationStructureSummary,truncationPerformedBy:I.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:I.endTimeMs!==void 0&&I.startTimeMs!==void 0?I.endTimeMs-I.startTimeMs:0,modelCallDurationMs:I.modelCallDurationMs,retriesUsed:I.retriesUsed??0,numToolCalls:I.toolCalls.length,numToolExecutions:I.toolCallExecutions.length,largeImagesRemoved:I.largeImagesRemoved,imagesRemoved:I.imagesRemoved,responsePromptTokens:I.responsePromptTokens,responseCompletionTokens:I.responseCompletionTokens,responseTotalTokens:I.responseTotalTokens,jitInstructionsAdded:I.jitInstructionsAdded,...I.truncateEvent?.truncateResult,...I.imageProcessingMetrics},restrictedProperties:{}}};await this.callback.progress(l)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,I){let l=I.toolCallId,n=yfI(e,l);if(n){let c=I.toolResult,a={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...c.toolTelemetry.properties,resultType:c.resultType,toolCallId:l,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id},restrictedProperties:{...c.toolTelemetry.restrictedProperties,arguments:n.arguments,result:c.textResultForLlm,toolName:n.toolName,error:c.error},metrics:{...c.toolTelemetry.metrics,durationMs:I.durationMs}}};await this.callback.progress(a)}}};G();G();var N9=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var qP=class{constructor(e,I){this.runtimeContext=e;this.customAgentName=I;this.gitHandlers={silent:new Pr(new ni,this.runtimeContext.exec),logging:new Pr(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,I,l,n,c,a,s=new N9,r){let o=async(p,Z,u)=>{let N={role:"user",content:p};return await this.runtimeContext.callback?.progress({kind:"message",message:N,turn:0}),await this.runCompletionWithTools(e,I,[...Z??[],N],a,c,{executeToolsInParallel:vl(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:u},r,s)},d=n,i=l??[],h;for(;d;){let p=await o(d,i,h);h=p.finalTurnCount,i=p.messages,d=await r?.onResult(p.postCompletionWithToolsCommitHash)}for(let p of a)if(p.shutdown){let Z=await p.shutdown();Z&&await this.runtimeContext.callback?.progress(Z)}return{finalTurnCount:h||0,messages:i}}async runCompletionWithTools(e,I,l,n,c,a,s,r=new N9){let o=this.runtimeContext.callback?new PP("sweagent-capi",this.runtimeContext.callback,this.runtimeContext.settings,n):void 0,d=this.gitHandlers.logging,i=await d.getCurrentCommitHash(e),h=l.filter(Q=>Q.role==="user").at(-1),p=this.createCompletionWithToolsProcessors(e,i,n,r,c,s,h),Z=this.runtimeContext.client.getCompletionWithTools(I,l,n,{...a,processors:p}),u=0,N=[...l],Y=[];for await(let Q of Z){if(vl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let A=await this.runtimeContext.callback?.progress(Q,{accepts_user_messages:r.canProcessUserMessages()});r.handleCallbackResponse(A)}else Q.kind==="response"||Q.kind==="message"?await this.runtimeContext.callback?.progress({...Q,customAgentName:this.customAgentName}):await this.runtimeContext.callback?.progress(Q);o&&await o.ingestEvent(Q),(Q.kind==="message"||Q.kind==="response")&&(Q.kind==="message"&&N.push(Q.message),Q.kind==="response"&&Y.push(Q.response),u=Math.max(u,Q.turn??0))}let y=await d.getCurrentCommitHash(e);return{finalTurnCount:u,messages:N,resultMessages:Y,preCompletionWithToolsCommitHash:i,postCompletionWithToolsCommitHash:y}}createCompletionWithToolsProcessors(e,I,l,n,c,a,s){let r=new MP(this.runtimeContext.logger,this.runtimeContext.settings,l.find(p=>p.name==="github-mcp-server-get_file_contents")),o=new DP(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,I,c),d=new hE(this.runtimeContext.logger),i=s?new TP(s,this.runtimeContext.logger):void 0,h=[o,r,d,i];return vl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&h.push(n),{preRequest:h.filter(p=>p!==void 0),preToolsExecution:[a].filter(p=>p!==void 0),postToolExecution:[r,a].filter(p=>p!==void 0),onRequestError:[r,i].filter(p=>p!==void 0)}}};G();async function kbe(t,e,I,l,n){try{return(await l.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:I,numSnippets:10},"hidden_characters")).textResultForLlm}catch(c){return n.error(`Error during Blackbird search: ${c}`),""}}var $Se=t=>vl(t,"copilot_swe_agent_search")||eZe(t,"SearchAgentExperiment")==="enabled",_Se="search";function fbe(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var gfI=(t,e,I)=>`
|
|
1235
|
+
</reminder>`),I.trim()},OP={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."},USe=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${nbe(t)}. Commit changes by using the **report_progress** tool.</reminder>`;G();var ybe="/tmp/playwright-logs",$kI="0.0.40",Fbe=[`@playwright/mcp@${$kI}`,"--viewport-size","1280, 720","--output-dir",ybe],oOl=[...Fbe,"--isolated"];var Qbe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},gbe=2e3;async function IfI(t,e,I,l){let n={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},c=`${UZe(l)}/${t}`;I.info(`Downloading image from ${c}`);try{let a=await fetch(c,{method:"GET",headers:n});if(I.info(`Response status: ${a.status} ${a.statusText}`),I.debug(`Download Response URL: ${a.url}`),!a.ok){I.info(`Failed to download image, status: ${a.status}, statusText: ${a.statusText}`);try{let h=await a.text();I.info(`Error response body: ${h}`)}catch(h){I.info(`Could not read error response body: ${h}`)}return{size:0}}let r=(await a.json()).url;if(!r)return I.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let o=await fetch(r,{method:"GET"});if(!o.ok)return I.error(`Failed to download image: ${o.status} ${o.statusText}`),{size:0};let d=await o.arrayBuffer(),i=d.byteLength;return I.info(`Downloaded content size: ${Gm(i)}`),{size:i,buffer:Buffer.from(d),mimeType:o.headers.get("content-type")||void 0}}catch(a){return I.error("Network error downloading image"),a instanceof Error&&(I.info(`Error message: ${a.message}`),I.info(`Error stack: ${a.stack}`)),{size:0}}}function Abe(t,e,I,l){let n=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,c=/!\[.*?\]\((.*?)\)/g,a=[];return a.push(...SSe(t,e,n,I,l)),a.push(...SSe(t,e,c,I,l)),a}function SSe(t,e,I,l,n){let c=t.matchAll(I),a=[],s=/\/([a-f0-9-]+)$/;for(let r of c){let o=cfI(r[1],e),d=afI(r[1],e,n);if(o||d){let i=r[1].match(s),h={url:r[1],guid:"",kind:d?"legacy_attachment":"attachment"};i&&i.length>1&&(h.guid=i[1]),a.push(h)}else if(l){let i={url:r[1],guid:"",kind:"committed_attachment"};a.push(i)}}return a}function tfI(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&Hbe(t)}function Hbe(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function lfI(t){try{let e=/Here are relevant code snippets from the repository that might help with this task:\s*(\[[\s\S]*?\])(?=\n|$)/,I=t.match(e);if(!I?.[1]||I[1].length<=1)return null;let l=I[1].trim();return JSON.parse(l)}catch{return null}}function nfI(t,e,I){if(!t?.url||!t?.ref||!t?.path)throw new Error("Invalid repository insight: missing required fields");if(!e||e.trim()==="")throw new Error("Invalid image path: path cannot be empty");let l=t.url.split("/").slice(3,5).join("/"),n=t.ref.split("/")[2],c;if(e.startsWith("/"))c=e.slice(1);else{let s=t.path,r=Z9.dirname(s);c=Z9.resolve("/",r,e).slice(1)}return`${I}/${l}/blob/${n}/${c}`}function cfI(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function afI(t,e,I){return e&&new RegExp(`^${e}/[\\w.-]+/[\\w.-]+/assets/\\d+/[^.]+$`).test(t)?(I.debug(`Legacy GitHub asset URL detected: ${t}`),!0):!1}async function Ebe(t){let{width:e,height:I}=EUe(t);if(e===void 0||I===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:I}}async function OSe(t,e,I,l,n,c){t.debug(`Checking if image is valid size and dimensions. Max size: ${I}, Max dimension: ${l}`);let{exceedsSizeLimit:a,exceedsDimensionLimit:s}=await u9(I,l,c);if(!s&&!a)return t.debug("Image is within size and dimension limits."),c;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${l}, attempting to resize`);let[r,o]=await GfI(t,c,l,I,n);if(!r){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,o==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:d}=await u9(I,l,r);if(d){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),r}if(a){t.debug(`Image size ${Gm(c.length)} is larger than the maximum size of ${Gm(I)}, attempting to reduce image quality`);let r=await ofI(t,c,l,I,n);if(!r){t.debug("Failed to reduce image quality to fit within the maximum size, skipping"),e.imagesFailedToReduceQuality++,e.imagesRemovedDueToSize++;return}return e.imagesWithLoweredQuality++,t.debug("Image quality successfully reduced."),r}}async function u9(t,e,I){let l=await Ebe(I),n=I.length;return!l.width||!l.height?{exceedsSizeLimit:n>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await rfI(t,I),exceedsDimensionLimit:await sfI(e,I)}}async function sfI(t,e){let I=await Ebe(e);return!I.width||!I.height?!1:I.width>t||I.height>t}async function rfI(t,e){return e.length>t}async function GfI(t,e,I,l,n){try{if(!TSe(t,n))return[void 0,"unsupported_mime_type"];let c=await Ebe(e);if(!c.width||!c.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let a=async(N,Y)=>{let y=MSe(e).resize(N,Y,{fit:"inside",withoutEnlargement:!0});return wbe(t,await y.toBuffer(),void 0,n)},s=Math.min(I,c.width),r=Math.min(I,c.height),o=await a(s,r);if(o&&o.length<=l)return[o,void 0];let d=Math.max(s,r),i=1,h=d-1,p,Z=0,u=10;for(;i<=h&&Z<u;){let N=Math.floor((i+h)/2),Y=await a(N,N);if(!Y)break;let{exceedsSizeLimit:y,exceedsDimensionLimit:Q}=await u9(l,I,Y);!y&&!Q?(p=Y,i=N+1):h=N-1,Z++}return[p,void 0]}catch(c){return t.error(`Failed to resize image for upload: ${c instanceof Error?c.message:String(c)}`),[void 0,"unknown"]}}async function ofI(t,e,I,l,n){try{let c=n==="image/png"?80:100,a=n==="image/png"?Math.floor(c*.4):20,s=await wbe(t,e,a,n);if(!s||s.length>l)return;let r=a,o=c,d,i=0,h=10,p=r,Z=o-1;for(;p<=Z&&i<h;){let u=Math.floor((p+Z)/2),N=await wbe(t,e,u,n);if(!N)return d;let{exceedsSizeLimit:Y,exceedsDimensionLimit:y}=await u9(l,I,N);!Y&&!y?(d=N,p=u+1):Z=u-1,i++}return d}catch(c){t.error(`Failed to reduce image quality: ${c instanceof Error?c.message:String(c)}`);return}}async function wbe(t,e,I,l){let n=MSe(e);switch(l){case"image/png":return I?n.png({quality:I}).toBuffer():n.png().toBuffer();case"image/jpeg":return I?n.jpeg({quality:I}).toBuffer():n.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${l}`);return}}var Xbe=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function dfI(t,e,I,l){if(e<=0)return[];let n=[];for(let c of t){if(c.role!=="user"||n.length>=e)continue;let a=typeof c.content=="string"?c.content:JSON.stringify(c.content),s=lfI(a);if(s)for(let r in s){if(n.length>=e)break;let o=s[r].contents,d=Abe(o,I,!0,l);for(let i of d){if(n.length>=e)break;let h=i.url,p="",Z=!1;if(i.kind==="attachment"||i.kind==="legacy_attachment"?n.push(i):tfI(h)?(Z=!0,p=nfI(s[r],h,I),n.push({url:p,guid:i.guid,kind:"committed_attachment"})):Hbe(h)&&h.startsWith(I)&&(Z=!0,n.push({...i,kind:"committed_attachment"})),Z){let u=n[n.length-1],N=new RegExp(`^${I}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),Y=u.url.match(N);if(l.info(`Blob match for ${u.url}: ${JSON.stringify(Y)}`),Y&&Y.length===5){let[,y,Q,A,w]=Y;u.owner=y,u.repo=Q,u.branch=A,u.path=w,l.info(`Repository metadata extracted: owner=${y}, repo=${Q}, branch=${A}, path=${w}`)}else l.info(`Failed to extract repository metadata from URL: ${u.url}`)}}}}return n}function ifI(t,e){let I=e.flatMap(n=>MR(n)?n.content.flatMap(c=>c.type==="image_url"?c.image_url.url:[]):[]),l=new Set(I);return t.filter(n=>!l.has(n.url))}var MP=class{async resolveRepositoryImages(e,I,l,n,c,a){if(I<=0)return[];let s=dfI(e,I,l,n);this.logger.debug(`Found ${s.length} repository image URLs to process`);let r=ifI(s,e),o=await this.processImageReferences(r,c,a);return this.logger.debug(`Processed ${o.addedImages.length} repository image URLs`),o.addedImages}async*preRequest(e){let I=e.modelInfo;if(!I.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!I.capabilities?.supports?.vision||!this.settings.featureFlags?.copilot_swe_agent_vision){this.logger.debug("Vision not supported or enabled, skipping image processing");return}if(!this.gitHubServerUrl){this.logger.debug("GitHub server URL is not set, skipping image processing");return}for(let i of this.messagesToInsertOnNextPreRequest)e.messages.push(i),yield{kind:"message",message:i,turn:e.turn};this.messagesToInsertOnNextPreRequest.splice(0);let l=[],n=I.capabilities.limits.vision?.max_prompt_images??1,c=I.capabilities.limits.vision?.max_prompt_image_size??3145728,a=0,s=[],r=new Xbe,o=new Map;for(let i of e.messages)if(i.role=="user")if(typeof i.content=="string"){let h=Abe(i.content,this.gitHubServerUrl,!1,this.logger).filter(Z=>!this.processedImageUrls.has(Z.url)),p=await this.processImageReferences(h,c,r);s.push(...p.addedImages)}else{let h=[];for(let[p,Z]of i.content.entries()){if(Z.type==="text"){let u=Abe(Z.text,this.gitHubServerUrl,!1,this.logger).filter(Y=>!this.processedImageUrls.has(Y.url)),N=await this.processImageReferences(u,c,r);s.push(...N.addedImages)}else if(Z.type==="image_url"){if(Z.image_url.url.startsWith("data:")){let[u,N]=await this.extractAndUploadImageData(Z,c,r);if(u===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(u),p>=1&&h.length>0){let Y=h.at(-1);Y&&Y.type==="text"&&Y.text&&Y.text.includes("screenshot")&&o.set(u,xSe(u))}h.pop();continue}a++}h.push(Z)}i.content=h}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${n}`);a<n&&s.length>0;){let i=s.shift();if(!i){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(i)){this.logger.debug(`Skipping already processed image url: ${i}`);continue}this.processedImageUrls.add(i);let h=`Here is the image url: ${i}`;o.has(i)&&(h=o.get(i)||h),this.logger.debug(`Adding image url: ${i}`),l.push({role:"user",content:[{type:"text",text:h},{type:"image_url",image_url:{url:i}}]}),a++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),a<n)){let i=await this.resolveRepositoryImages(e.messages,n-a,this.settings.github?.serverUrl||"",this.logger,c,r);this.logger.debug(`Resolved ${i.length} repository image URLs`);for(let h of i){if(a>=n)break;if(this.processedImageUrls.has(h)){this.logger.debug(`Skipping already processed repository image url: ${h}`);continue}l.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:h}}]}),this.processedImageUrls.add(h),a++}}let d={imagesExtractedCount:r.extractedImagesSize.length,base64ImagesCount:r.base64ImagesSize.length,imagesRemovedDueToSize:r.imagesRemovedDueToSize,imagesRemovedDueToDimensions:r.imagesRemovedDueToDimensions,imagesResized:r.imagesResized,imagesResolvedFromGitHubMCPCount:r.imagesResolvedFromGitHubMCPSize.length};for(let i=0;i<r.base64ImagesSize.length;i++)d[`base64ImageSize_${i}`]=r.base64ImagesSize[i];for(let i=0;i<r.resizedBase64ImagesSize.length;i++)d[`resizedBase64ImageSize_${i}`]=r.resizedBase64ImagesSize[i];for(let i=0;i<r.extractedImagesSize.length;i++)d[`extractedImageSize_${i}`]=r.extractedImagesSize[i];for(let i=0;i<r.imagesResolvedFromGitHubMCPSize.length;i++)d[`imagesResolvedFromGitHubMCPSize_${i}`]=r.imagesResolvedFromGitHubMCPSize[i];l.length>0&&this.logger.debug(`Using ${l.length} image messages`);for(let i of l)yield{kind:"message",message:i,turn:e.turn},e.messages.push(i);d.allImagesSendToLlm=e.messages.filter(MR).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:d},e.messages.some(i=>MR(i))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,I,l){let n=l1(this.settings);if(!n)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let c=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!c||c.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let a=c[1];if(!TSe(this.logger,a))return[""];let s=c[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let r=Buffer.from(s,"base64");if(l.base64ImagesSize.push(r.length),r=await OSe(this.logger,l,I,gbe,a,r),l.resizedBase64ImagesSize.push(r?.length??-1),!r)return["",new Qbe(`Image size exceeds maximum size of ${Gm(I)}`)];s=r.toString("base64");try{let o=await this.uploadBase64ImageData(s,a,n);return o?(this.logger.debug(`Uploaded image url: ${o}`),e.image_url.url=o,[o]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(o){let d=o instanceof Error?o.message:String(o);return this.logger.debug(`Error during image upload: ${d}`),[""]}}async uploadBase64ImageData(e,I,l){try{let n=zZe(this.settings),c=I.split("/").at(1),a=`image-${Date.now()}.${c}`;if(!e||e.trim()==="")return this.logger.error("Empty image data provided for upload"),null;let s=Buffer.from(e,"base64");if(s.length===0)return this.logger.error("Converted image data has zero length"),null;let r=this.settings.github?.repo?.id;if(!r)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let o=`${n}?name=${encodeURIComponent(a)}&content_type=${encodeURIComponent(I)}&repository_id=${r}`;this.logger.debug(`Uploading image data (${Gm(s.length)}) to ${n} with name ${encodeURIComponent(a)} and content type ${encodeURIComponent(I)}`);let d={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+l},i=await fetch(o,{method:"POST",headers:d,body:s}).catch(p=>{throw p instanceof Error?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof p=="object"&&p!==null&&"code"in p&&"message"in p?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):this.logger.error(`Failed to upload image: ${String(p)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:p?.code,message:p?.message,stack:p?.stack,name:p?.name,cause:p?.cause},null,2)}`),p});if(!i.ok){let p=await i.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${i.status} ${i.statusText} - ${p}`),null}let h=await i.json();return this.logger.debug(`Upload result: ${JSON.stringify(h,null,2)}`),h.url||null}catch(n){return this.logger.error(`Error handling image upload: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&this.logger.debug(`Stack trace: ${n.stack}`),null}}async getRepositoryImageViaTools(e){if(this.logger.debug(`Attempting to retrieve repository image: ${e.owner}/${e.repo}/${e.path}@${e.branch}`),this.githubGetFileContentsTool){this.logger.debug(`GitHub MCP tool found, calling with image reference: ${JSON.stringify(e)}`);try{let I=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof I}`),this.logger.debug(`GitHub tool call result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`),typeof I=="object"&&I!==null&&"binaryResultForLlm"in I&&Array.isArray(I.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${I.binaryResultForLlm.length} items`);try{for(let l of I.binaryResultForLlm)if(l.data&&l.mimeType){let n=Buffer.from(l.data,"base64"),c=l.mimeType;return{buffer:n,mimeType:c}}}catch(l){this.logger.error(`Failed to parse GitHub tool response: ${l}`),this.logger.debug(`binaryResultForLlm length: ${I.binaryResultForLlm?.length||0}`)}}else typeof I=="string"?this.logger.debug(`GitHub tool returned string result: ${I}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof I=="object"&&I!==null?Object.keys(I).join(", "):typeof I}`)}catch(I){this.logger.error(`Error calling GitHub MCP tool: ${I}`)}}else this.logger.debug("GitHub MCP tool 'github-mcp-server-get_file_contents' not available");return this.logger.debug("Failed to retrieve repository image, returning null"),null}async getImgRefsSmallerThanMaxSize(e,I,l){let n=[],c=await Promise.all(e);for(let{imgRef:a,attachment:s}of c)if(this.logger.debug(`Processing attachment for ${a.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(I.extractedImagesSize.push(s.buffer.length),vl(this.settings,"copilot_swe_agent_resize_image_references")){if(!await OSe(this.logger,I,l,gbe,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}n.push(a.url)}else{let r=await u9(l,gbe,s.buffer);if(this.logger.debug(`Image size check for ${a.url}: size=${s.buffer.length}, maxSize=${l}, exceedsSize=${r.exceedsSizeLimit}, exceedsDimensions=${r.exceedsDimensionLimit}`),r.exceedsSizeLimit?(I.imagesRemovedDueToSize++,this.logger.debug(`Image ${a.url} removed due to size (${s.buffer.length} > ${l})`)):r.exceedsDimensionLimit&&(I.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${a.url} removed due to dimensions`)),r.exceedsSizeLimit||r.exceedsDimensionLimit){this.processedImageUrls.add(a.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${Gm(l)}.`);continue}n.push(a.url),this.logger.debug(`Image ${a.url} passed size checks and added to results`)}else this.processedImageUrls.add(a.url),this.logger.debug(`Skipping image ${a.url} - could not fetch image data`);return n}async processImageReferences(e,I,l){let n=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${n}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let c=e.filter(s=>!this.processedImageUrls.has(s.url)).map(async s=>{if(this.logger.debug(`Processing image reference: ${JSON.stringify(s,null,2)}`),s.kind==="committed_attachment"){this.logger.debug(`Detected repository image - Owner: ${s.owner}, Repo: ${s.repo}, Branch: ${s.branch}, Path: ${s.path}`);let r=await this.getRepositoryImageViaTools(s);return r?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${r.buffer.length} bytes`),l.imagesResolvedFromGitHubMCPSize.push(r.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:r?.buffer?.length||0,mimeType:r?.mimeType||"",buffer:r?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await IfI(s.guid,l1(this.settings),this.logger,this.settings)}}),a=await this.getImgRefsSmallerThanMaxSize(c,l,I);return this.logger.debug(`Processed image references, found ${a.length} attachments smaller than max size of ${Gm(I)}`),{addedImages:a}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,I,l){this.logger=e,this.settings=I,this.gitHubServerUrl=I.github?.serverUrl,this.githubGetFileContentsTool=l,this.processedImageUrls=new Set,this.messagesToInsertOnNextPreRequest=[]}toJSON(){return"CAPIImageProcessor"}async onRequestError(e){}async preErrorThrow(e){this.processedImageUrls.size>0&&(e.isVisionFlow=!0)}async postToolExecution(e){let I=e.modelInfo,l=e.toolCall.function.name,n=e.toolResult;if(I?.capabilities?.supports?.vision){let c=Array.from(bfI(n,l));if(c.length===0){let a=await pfI(e.toolCall,this.logger);a&&c.push(a)}this.insertImageUrlMessages(c)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let I of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:I.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:I.url}}]})}};function*bfI(t,e){for(let I of t.binaryResultForLlm??[])I.type==="image"&&(yield{url:`data:${I.mimeType};base64,${I.data}`,isScreenshot:e.toLowerCase().includes("screenshot")})}var mfI="playwright-browser_take_screenshot";function hfI(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function pfI(t,e){if(t.function.name!==mfI)return;e.debug("Adding images using Playwright params fallback strategy");let I=JSON.parse(t.function.arguments);if(hfI(I)){let l=Z9.isAbsolute(I.filename)?I.filename:Z9.join(ybe,I.filename);e.debug(`Image from Playwright params: ${I.filename}. Updated to ${l}.`);let n=await ufI(l,e);if(n){let c=n.buffer.toString("base64");return{url:`data:${n.mimeType};base64,${c}`,isScreenshot:!0}}}}function ZfI(t){switch(Z9.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function TSe(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 ufI(t,e){try{if(!Hbe(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let I=ZfI(t);return I?{buffer:await efI.readFile(t),mimeType:I}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(I){return e.error(`Failed to read image from disk: ${I instanceof Error?I.message:String(I)}`),null}}G();var hE=class{logger;constructor(e){this.logger=e}toJSON(){return"BasicTruncator"}async*preRequest(e){let I=await jSe(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit);I.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(I)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:I}}},TP=class{truncateOnNextRequest=!1;userMessageToTruncateUpTo;logger;constructor(e,I){this.userMessageToTruncateUpTo=e,this.logger=I,this.logger.debug(`AnthropicTokenLimitErrorTruncator will truncate up to message: ${JSON.stringify(e)}`)}async*preRequest(e){if(this.truncateOnNextRequest){this.truncateOnNextRequest=!1;let I=H3e(this.userMessageToTruncateUpTo,e.messages);if(I===-1){this.logger.debug(`Failed to find user message to truncate up to: ${JSON.stringify(this.userMessageToTruncateUpTo)}`),this.logger.debug(`Current messages: ${JSON.stringify(e.messages)}`);return}let l=await jSe(e.messages,e.toolDefinitions,e.modelInfo.name,e.tokenLimit,I);l.tokensRemovedDuringTruncation>0&&this.logger.debug(`AnthropicTokenLimitErrorTruncator truncated: ${JSON.stringify(l)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"AnthropicTokenLimitErrorTruncator",truncateResult:l}}}async preErrorThrow(e){}async onRequestError(e){if(e){if(typeof e=="object"&&"code"in e&&e.code==="model_max_prompt_tokens_exceeded"){this.truncateOnNextRequest=!0;return}let I=[JSON.stringify(e)];e instanceof Error&&(I.push(e.message),e.cause instanceof Error?I.push(e.cause.message):e.cause&&I.push(JSON.stringify(e.cause)));let l="Input length and `max_tokens` exceed context limit";this.logger.debug(`Looking for error amongst: ${I.join(", ")}`),I.some(n=>n.includes(l))&&(this.truncateOnNextRequest=!0)}}toJSON(){return"AnthropicTokenLimitErrorTruncator"}},WfI=.95;function jSe(t,e,I,l,n){let c=t.length;if(c===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:c,postTruncationTokensInMessages:0,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(p=>xx(p,I)),s=rp(JSON.stringify(e),I),r=l*WfI,o=a.reduce((p,Z)=>p+Z,0)+s;if(o<=r)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,i=0,h=Math.min(n??t.length,t.length);for(let p=0;p<h;p++){let Z=t[p];if(Z.role!=="system"&&Z.role!=="tool"&&Z.role!=="user"){if(Z.role==="assistant"){let u=Z.tool_calls||[],N=u.filter(Io).filter(A=>A.function.name===rC),Y=u.filter(Io).filter(A=>A.function.name!==rC),y=N.length===0,Q=new Set(Y.map(A=>A.id));if(Y.length>0&&(Z.tool_calls=N,a[p]=xx(Z,I)),y&&(d.add(p),i+=a[p]),Q.size>0)for(let A=p+1;A<t.length;A++){let w=t[A];if(w.role==="tool"&&Q.has(w.tool_call_id)&&(d.add(A),i+=a[A],Q.delete(w.tool_call_id),Q.size===0))break}}if(o-i<r)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}G();var ni=class extends ap{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,I){}endGroup(e){}};G();G();var DSe={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 jP(t,e,I){let l=(I||DSe)[t.toLowerCase()],n=new Set;for(;typeof l=="string";){if(n.has(l))return!1;n.add(l),l=DSe[l]}if(!l)return!1;let c=e.toLowerCase();return l.tools.some(a=>a.toolName===c)}var NfI="image";var YfI="resource",VfI=60*1e3*2,RfI={timeout:VfI};var vbe=class{constructor(e,I,l){this.settings=e;this.logger=I;this.permissions=l}async invokeTool(e,I,l="hidden_characters"){let n=await this.doInvokeTool(e,I);return this.invokeToolResponseToToolResult(n,l)}invokeToolResponseToToolResult(e,I){let l=e.content||[],n="",c=[];for(let o of l)if(o.type==="text")n+=o.text||"";else if(o.type==="resource"){let d=o.resource;d&&d.blob?c.push({type:YfI,data:d.blob,mimeType:d.mimeType||"application/octet-stream"}):d&&d.text&&(n+=d.text)}else o.type==="image"&&c.push({type:NfI,data:o.data,mimeType:o.mimeType});let a=n;if(n==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),a=n;else try{let o=JSON.parse(n),d=Uie(o,I);a=JSON.stringify(d)}catch(o){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${o}`),a=Bie(n,I)}this.logger.debug(`Tool invocation result: ${a}`);let s={},r=a?Pn(a,"output"):"";return e.isToolError?{textResultForLlm:a,resultType:"failure",error:a,sessionLog:r,toolTelemetry:s}:{textResultForLlm:a,binaryResultForLlm:c,resultType:"success",sessionLog:r,toolTelemetry:s}}async loadTools(e){let I=await this.loadToolsFromProvider(e),l={};for(let[n,c]of Object.entries(I)){let a=c.filterMode||"hidden_characters";l[n]={name:c.name,title:c.title||c.name,description:c.description,input_schema:c.input_schema,callback:async s=>{let r=I[n].serverName,o=I[n].name,d=I[n].title;if(!this.permissions.requestRequired)return this.invokeTool(n,s,a);let i=await this.permissions.request({kind:"mcp",serverName:r,toolName:o,toolTitle:d,args:s,readOnly:!!c.readOnly});switch(i.kind){case"approved":return this.invokeTool(n,s,a);case"denied-by-rules":return rO(i.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return GO;case"denied-interactively-by-user":return sO;default:NV(i,`Unhandled permission result kind: ${i}`)}},safeForTelemetry:c.safeForTelemetry}}return Object.values(l)}};var W9=class t extends vbe{toolIdToClientInfo=new Map;constructor(e,I,l={requestRequired:!1}){super(e,I,l)}async doInvokeTool(e,I){let l=this.toolIdToClientInfo.get(e);if(!l)throw new Error(`No MCP client found for tool ID: ${e}`);let n=l.mcpClient,c=t.getToolNameFromIdAndClientName(e,l.clientName),a=await n.callTool({name:c,arguments:I},void 0,{...RfI,onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(a.content))throw new Error("Expected array of results");return{content:a.content,isToolError:a.error!==void 0&&a.error!==null||a.isError===!0}}async loadToolsFromProvider(e){let I={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let l of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(l.name)){this.logger.debug(`Skipping tool ${l.name} for client ${e.clientName}`);continue}let n=t.getToolIdFromClientAndToolName(e.clientName,l.name);this.toolIdToClientInfo.set(n,e);let c;e.safeForTelemetry===!0?c={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?c=e.safeForTelemetry:c={name:jP(e.clientName,l.name),inputsNames:!1},this.logger.debug(`Adding tool: ${n}`);let a;e.filterMapping===void 0?a="hidden_characters":typeof e.filterMapping=="object"?a=e.filterMapping[l.name]||"hidden_characters":a=e.filterMapping,I[n]={serverName:e.clientName,name:n,title:l.title||l.annotations?.title||l.name,description:l.description||"",input_schema:l.inputSchema,readOnly:l.annotations?.readOnlyHint,safeForTelemetry:c,filterMode:a}}return I}static getToolIdFromClientAndToolName(e,I){return`${e}-${I}`}static getToolNameFromIdAndClientName(e,I){return e.substring(I.length+1)}};G();var DP=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,I,l,n,c,a){this.settings=e,this.logger=I,this.gitHandler=l,this.location=n,this.commitPriorToCompletionWithTools=c,this.jitInstructions=a||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let I,l=async()=>{if(I===void 0)try{I=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(a){this.logger.error(`Failed to get changed paths, err: ${a}`),I=1}return I},n;for(let[a,s]of Object.entries(this.jitInstructions)){let r=IZe(this.settings,s.percentRemainingOfTimeout);r.isWithin&&(!s.whenNoPathsChanged||await l()===0)&&(!n||r.withinMs<n[0])&&(n=[r.withinMs,s.instruction])}let c=n?.[1];if(typeof c=="function"&&(c=c(this.location)),c&&!this.emittedJitInstructions.has(c)){this.logger.debug(`Adding JIT instructions to the history: ${c}`),this.emittedJitInstructions.add(c);let a={role:"user",content:c};e.messages.push(a),yield{kind:"message",message:a,turn:e.turn,source:"jit-instruction"}}}}},Jbe={remindWhereToDoWork:{instruction:USe,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:OP.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:OP.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:OP.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};G();G();function Lbe(t){if(!t)return E3e;let[e,...I]=t?.split(":")??[t,void 0],l=I.join(":")||void 0;return{agent:e||void 0,model:l||void 0}}G();G();function KP(t){return t.kind==="message"&&t.message.role==="assistant"}function KSe(t){return t.kind==="message"&&t.message.role==="user"}function PSe(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function qSe(t){return t.kind==="message"&&t.message.role==="tool"}function yfI(t,e){return t.toolCalls.find(I=>I.toolCallId===e)}function FfI(t,e){let I=e.function.name;try{let l=JSON.parse(e.function.arguments||"{}"),c=t.find(a=>a.name===I)?.safeForTelemetry||{name:!1,inputsNames:!1};return{toolCallId:e.id,toolName:I,arguments:e.function.arguments,safeForTelemetryToolName:c===!0||c.name?I:Y2(I),safeForTelemetryArguments:c===!0||c.inputsNames?A3e(l):""}}catch{return{toolCallId:e.id,toolName:I,arguments:e.function.arguments,safeForTelemetryToolName:Y2(I),safeForTelemetryArguments:""}}}var PP=class{forAgent;turnDataCache;emittedTurns=new Set;callback;settings;toolsInUse;constructor(e,I,l,n){this.forAgent=e,this.turnDataCache=new Map,this.emittedTurns=new Set,this.callback=I,this.settings=l,this.toolsInUse=n}getTurnData(){return this.turnDataCache}async ingestEvent(e){let I,l;if("turn"in e&&typeof e.turn=="number"){if(I=e.turn+1,this.emittedTurns.has(I))return;this.turnDataCache.has(I)||this.turnDataCache.set(I,{featureFlagsAsString:xq(this.settings),toolCalls:[],toolCallExecutions:[],turn:I}),l=this.turnDataCache.get(I)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(l,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(l={...l,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?l={...l,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?l={...l,endTimeMs:e.timestampMs,retriesUsed:(l.retriesUsed??0)+1}:e.kind==="turn_failed"?l={...l,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(l={...l,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?l={...l,truncateEvent:e}:e.kind==="image_processing"?l={...l,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?l={...l,largeImagesRemoved:(l.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(l.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(l={...l,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:w3e(e.requestMessages)},e.kind==="model_call_success"&&(l={...l,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):KSe(e)&&e.source==="jit-instruction"?l={...l,jitInstructionsAdded:(l?.jitInstructionsAdded??0)+1}:KP(e)&&e.message.tool_calls?l={...l,toolCalls:l.toolCalls.concat(e.message.tool_calls.map(n=>({...FfI(this.toolsInUse,n)})))}:qSe(e)&&(l={...l,toolCallExecutions:l.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(I,l),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(I),this.emittedTurns.add(I),this.turnDataCache.delete(I))}async emitTurnTelemetry(e){let I=this.turnDataCache.get(e);if(I){let l={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{model:I.model||"default",modelInfo:I.modelInfo||"{}",api_call_id:I.api_call_id,provider_call_id:I.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(I.toolCalls.map(n=>({toolCallId:n.toolCallId,toolName:n.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(I.toolCallExecutions),error:I.error,featureFlags:xq(this.settings),conversationStructureSummary:I.conversationStructureSummary,truncationPerformedBy:I.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:I.endTimeMs!==void 0&&I.startTimeMs!==void 0?I.endTimeMs-I.startTimeMs:0,modelCallDurationMs:I.modelCallDurationMs,retriesUsed:I.retriesUsed??0,numToolCalls:I.toolCalls.length,numToolExecutions:I.toolCallExecutions.length,largeImagesRemoved:I.largeImagesRemoved,imagesRemoved:I.imagesRemoved,responsePromptTokens:I.responsePromptTokens,responseCompletionTokens:I.responseCompletionTokens,responseTotalTokens:I.responseTotalTokens,jitInstructionsAdded:I.jitInstructionsAdded,...I.truncateEvent?.truncateResult,...I.imageProcessingMetrics},restrictedProperties:{}}};await this.callback.progress(l)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,I){let l=I.toolCallId,n=yfI(e,l);if(n){let c=I.toolResult,a={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...c.toolTelemetry.properties,resultType:c.resultType,toolCallId:l,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id},restrictedProperties:{...c.toolTelemetry.restrictedProperties,arguments:n.arguments,result:c.textResultForLlm,toolName:n.toolName,error:c.error},metrics:{...c.toolTelemetry.metrics,durationMs:I.durationMs}}};await this.callback.progress(a)}}};G();G();var N9=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var qP=class{constructor(e,I){this.runtimeContext=e;this.customAgentName=I;this.gitHandlers={silent:new Pr(new ni,this.runtimeContext.exec),logging:new Pr(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,I,l,n,c,a,s=new N9,r){let o=async(p,Z,u)=>{let N={role:"user",content:p};return await this.runtimeContext.callback?.progress({kind:"message",message:N,turn:0}),await this.runCompletionWithTools(e,I,[...Z??[],N],a,c,{executeToolsInParallel:vl(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:u},r,s)},d=n,i=l??[],h;for(;d;){let p=await o(d,i,h);h=p.finalTurnCount,i=p.messages,d=await r?.onResult(p.postCompletionWithToolsCommitHash)}for(let p of a)if(p.shutdown){let Z=await p.shutdown();Z&&await this.runtimeContext.callback?.progress(Z)}return{finalTurnCount:h||0,messages:i}}async runCompletionWithTools(e,I,l,n,c,a,s,r=new N9){let o=this.runtimeContext.callback?new PP("sweagent-capi",this.runtimeContext.callback,this.runtimeContext.settings,n):void 0,d=this.gitHandlers.logging,i=await d.getCurrentCommitHash(e),h=l.filter(Q=>Q.role==="user").at(-1),p=this.createCompletionWithToolsProcessors(e,i,n,r,c,s,h),Z=this.runtimeContext.client.getCompletionWithTools(I,l,n,{...a,processors:p}),u=0,N=[...l],Y=[];for await(let Q of Z){if(vl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let A=await this.runtimeContext.callback?.progress(Q,{accepts_user_messages:r.canProcessUserMessages()});r.handleCallbackResponse(A)}else Q.kind==="response"||Q.kind==="message"?await this.runtimeContext.callback?.progress({...Q,customAgentName:this.customAgentName}):await this.runtimeContext.callback?.progress(Q);o&&await o.ingestEvent(Q),(Q.kind==="message"||Q.kind==="response")&&(Q.kind==="message"&&N.push(Q.message),Q.kind==="response"&&Y.push(Q.response),u=Math.max(u,Q.turn??0))}let y=await d.getCurrentCommitHash(e);return{finalTurnCount:u,messages:N,resultMessages:Y,preCompletionWithToolsCommitHash:i,postCompletionWithToolsCommitHash:y}}createCompletionWithToolsProcessors(e,I,l,n,c,a,s){let r=new MP(this.runtimeContext.logger,this.runtimeContext.settings,l.find(p=>p.name==="github-mcp-server-get_file_contents")),o=new DP(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,I,c),d=new hE(this.runtimeContext.logger),i=s?new TP(s,this.runtimeContext.logger):void 0,h=[o,r,d,i];return vl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&h.push(n),{preRequest:h.filter(p=>p!==void 0),preToolsExecution:[a].filter(p=>p!==void 0),postToolExecution:[r,a].filter(p=>p!==void 0),onRequestError:[r,i].filter(p=>p!==void 0)}}};G();async function kbe(t,e,I,l,n){try{return(await l.invokeTool("blackbird-mcp-server/search_repository_with_agent",{task:t,depth:2,owner:e,repo:I,numSnippets:10},"hidden_characters")).textResultForLlm}catch(c){return n.error(`Error during Blackbird search: ${c}`),""}}var $Se=t=>vl(t,"copilot_swe_agent_search")||eZe(t,"SearchAgentExperiment")==="enabled",_Se="search";function fbe(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var gfI=(t,e,I)=>`
|
|
1236
1236
|
You are a question answering agent that is a component of GitHub Copilot coding agent. Your task is to take the given question
|
|
1237
1237
|
and answer it using the given facts.
|
|
1238
1238
|
|