@github/copilot 0.0.354-7 → 0.0.354-8
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/index.js
CHANGED
|
@@ -1743,7 +1743,7 @@ ${t}
|
|
|
1743
1743
|
<reminder>
|
|
1744
1744
|
The user may have mentioned images, if so these will have been attached to this message, in the order they were mentioned
|
|
1745
1745
|
</reminder>`),n.trim()},u0e={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."},HXt=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${Ose(t)}. Commit changes by using the **report_progress** tool.</reminder>`;function XXt(t){try{if(t)typeof t=="string"&&(t=JSON.parse(t));else return"no_messages";let e=t.map(l=>{let n="?";switch(l.role){case"system":n="s";break;case"assistant":n="a";break;case"user":n="u";break;case"tool":n="t";break}return{type:n,tool_call_id:l.role!=="tool"?void 0:l.tool_call_id,reasoning_text:l.role!=="assistant"?void 0:!!l.reasoning_text,content:typeof l.content=="string"?["text"]:l.content?.map(r=>r.type),tool_calls:l.role!=="assistant"?void 0:l.tool_calls?l.tool_calls.map(r=>r.id):[]}});return JSON.stringify(e,null,2)}catch{return"failed_to_summarize"}}function C6(t){let e=t.reasoning_text?.replace(/<\|im_sep\|>(\*\*.*?\*\*)?/g,`
|
|
1746
|
-
`)?.trim();return{...t,reasoning_text:e}}function toe(t){return structuredClone(t)}function kXt(t){return{...t,choices:t.choices.map(e=>{let l=C6(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 j4(t){return t.role==="user"&&Array.isArray(t.content)&&t.content.some(e=>e.type==="image_url")}function LXt(t,e){let l=e.indexOf(t);if(l!==-1)return l;let n=s=>(typeof s.content=="string"?[{type:"text",text:s.content}]:s.content).filter(o=>o.type==="text").map(o=>o.text).join("").trim(),r=n(t),a=e.map((s,o)=>s.role==="user"&&n(s)===r?o:-1).filter(s=>s!==-1),I=a.at(0)??-1;return a.length===1?I:-1}var iMe="/tmp/playwright-logs",Kon="0.0.40",cMe=[`@playwright/mcp@${Kon}`,"--viewport-size","1280, 720","--output-dir",iMe],Mma=[...cMe,"--isolated"];var dMe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},loe=2e3;async function $on(t,e,l,n){let r={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},a=`${GZt(n)}/${t}`;l.info(`Downloading image from ${a}`);try{let I=await fetch(a,{method:"GET",headers:r});if(l.info(`Response status: ${I.status} ${I.statusText}`),l.debug(`Download Response URL: ${I.url}`),!I.ok){l.info(`Failed to download image, status: ${I.status}, statusText: ${I.statusText}`);try{let G=await I.text();l.info(`Error response body: ${G}`)}catch(G){l.info(`Could not read error response body: ${G}`)}return{size:0}}let o=(await I.json()).url;if(!o)return l.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let c=await fetch(o,{method:"GET"});if(!c.ok)return l.error(`Failed to download image: ${c.status} ${c.statusText}`),{size:0};let d=await c.arrayBuffer(),m=d.byteLength;return l.info(`Downloaded content size: ${EE(m)}`),{size:m,buffer:Buffer.from(d),mimeType:c.headers.get("content-type")||void 0}}catch(I){return l.error("Network error downloading image"),I instanceof Error&&(l.info(`Error message: ${I.message}`),l.info(`Error stack: ${I.stack}`)),{size:0}}}function uMe(t,e,l,n){let r=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,a=/!\[.*?\]\((.*?)\)/g,I=[];return I.push(...JXt(t,e,r,l,n)),I.push(...JXt(t,e,a,l,n)),I}function JXt(t,e,l,n,r){let a=t.matchAll(l),I=[],s=/\/([a-f0-9-]+)$/;for(let o of a){let c=nin(o[1],e),d=rin(o[1],e,r);if(c||d){let m=o[1].match(s),G={url:o[1],guid:"",kind:d?"legacy_attachment":"attachment"};m&&m.length>1&&(G.guid=m[1]),I.push(G)}else if(n){let m={url:o[1],guid:"",kind:"committed_attachment"};I.push(m)}}return I}function ein(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&Ioe(t)}function Ioe(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function tin(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 lin(t,e,l){if(!t?.url||!t?.ref||!t?.path)throw new Error("Invalid repository insight: missing required fields");if(!e||e.trim()==="")throw new Error("Invalid image path: path cannot be empty");let n=t.url.split("/").slice(3,5).join("/"),r=t.ref.split("/")[2],a;if(e.startsWith("/"))a=e.slice(1);else{let s=t.path,o=noe.dirname(s);a=noe.resolve("/",o,e).slice(1)}return`${l}/${n}/blob/${r}/${a}`}function nin(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function rin(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 GMe(t){let{width:e,height:l}=uvt(t);if(e===void 0||l===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:l}}async function m0e(t,e,l,n,r,a){t.debug(`Checking if image is valid size and dimensions. Max size: ${l}, Max dimension: ${n}`);let{exceedsSizeLimit:I,exceedsDimensionLimit:s}=await roe(l,n,a);if(!s&&!I)return t.debug("Image is within size and dimension limits."),a;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${n}, attempting to resize`);let[o,c]=await sin(t,a,n,l,r);if(!o){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,c==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:d}=await roe(l,n,o);if(d){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),o}if(I){t.debug(`Image size ${EE(a.length)} is larger than the maximum size of ${EE(l)}, attempting to reduce image quality`);let o=await oin(t,a,n,l,r);if(!o){t.debug("Failed to reduce image quality to fit within the maximum size, skipping"),e.imagesFailedToReduceQuality++,e.imagesRemovedDueToSize++;return}return e.imagesWithLoweredQuality++,t.debug("Image quality successfully reduced."),o}}async function roe(t,e,l){let n=await GMe(l),r=l.length;return!n.width||!n.height?{exceedsSizeLimit:r>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await Iin(t,l),exceedsDimensionLimit:await ain(e,l)}}async function ain(t,e){let l=await GMe(e);return!l.width||!l.height?!1:l.width>t||l.height>t}async function Iin(t,e){return e.length>t}async function sin(t,e,l,n,r){try{if(!xXt(t,r))return[void 0,"unsupported_mime_type"];let a=await GMe(e);if(!a.width||!a.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let I=async(W,R)=>{let V=(0,bMe.default)(e).resize(W,R,{fit:"inside",withoutEnlargement:!0});return mMe(t,await V.toBuffer(),void 0,r)},s=Math.min(l,a.width),o=Math.min(l,a.height),c=await I(s,o);if(c&&c.length<=n)return[c,void 0];let d=Math.max(s,o),m=1,G=d-1,p,A=0,Z=10;for(;m<=G&&A<Z;){let W=Math.floor((m+G)/2),R=await I(W,W);if(!R)break;let{exceedsSizeLimit:V,exceedsDimensionLimit:v}=await roe(n,l,R);!V&&!v?(p=R,m=W+1):G=W-1,A++}return[p,void 0]}catch(a){return t.error(`Failed to resize image for upload: ${a instanceof Error?a.message:String(a)}`),[void 0,"unknown"]}}async function oin(t,e,l,n,r){try{let a=r==="image/png"?80:100,I=r==="image/png"?Math.floor(a*.4):20,s=await mMe(t,e,I,r);if(!s||s.length>n)return;let o=I,c=a,d,m=0,G=10,p=o,A=c-1;for(;p<=A&&m<G;){let Z=Math.floor((p+A)/2),W=await mMe(t,e,Z,r);if(!W)return d;let{exceedsSizeLimit:R,exceedsDimensionLimit:V}=await roe(n,l,W);!R&&!V?(d=W,p=Z+1):A=Z-1,m++}return d}catch(a){t.error(`Failed to reduce image quality: ${a instanceof Error?a.message:String(a)}`);return}}async function mMe(t,e,l,n){let r=(0,bMe.default)(e);switch(n){case"image/png":return l?r.png({quality:l}).toBuffer():r.png().toBuffer();case"image/jpeg":return l?r.jpeg({quality:l}).toBuffer():r.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${n}`);return}}var aoe=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function iin(t,e,l,n){if(e<=0)return[];let r=[];for(let a of t){if(a.role!=="user"||r.length>=e)continue;let I=typeof a.content=="string"?a.content:JSON.stringify(a.content),s=tin(I);if(s)for(let o in s){if(r.length>=e)break;let c=s[o].contents,d=uMe(c,l,!0,n);for(let m of d){if(r.length>=e)break;let G=m.url,p="",A=!1;if(m.kind==="attachment"||m.kind==="legacy_attachment"?r.push(m):ein(G)?(A=!0,p=lin(s[o],G,l),r.push({url:p,guid:m.guid,kind:"committed_attachment"})):Ioe(G)&&G.startsWith(l)&&(A=!0,r.push({...m,kind:"committed_attachment"})),A){let Z=r[r.length-1],W=new RegExp(`^${l}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),R=Z.url.match(W);if(n.info(`Blob match for ${Z.url}: ${JSON.stringify(R)}`),R&&R.length===5){let[,V,v,X,x]=R;Z.owner=V,Z.repo=v,Z.branch=X,Z.path=x,n.info(`Repository metadata extracted: owner=${V}, repo=${v}, branch=${X}, path=${x}`)}else n.info(`Failed to extract repository metadata from URL: ${Z.url}`)}}}}return r}function cin(t,e){let l=e.flatMap(r=>j4(r)?r.content.flatMap(a=>a.type==="image_url"?a.image_url.url:[]):[]),n=new Set(l);return t.filter(r=>!n.has(r.url))}var b0e=class{async resolveRepositoryImages(e,l,n,r,a,I){if(l<=0)return[];let s=iin(e,l,n,r);this.logger.debug(`Found ${s.length} repository image URLs to process`);let o=cin(s,e),c=await this.processImageReferences(o,a,I);return this.logger.debug(`Processed ${c.addedImages.length} repository image URLs`),c.addedImages}async*preRequest(e){let l=e.modelInfo;if(!l.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!l.capabilities?.supports?.vision||!this.settings.featureFlags?.copilot_swe_agent_vision){this.logger.debug("Vision not supported or enabled, skipping image processing");return}if(!this.gitHubServerUrl){this.logger.debug("GitHub server URL is not set, skipping image processing");return}for(let m of this.messagesToInsertOnNextPreRequest)e.messages.push(m),yield{kind:"message",turn:e.turn,callId:e.callId,message:m};this.messagesToInsertOnNextPreRequest.splice(0);let n=[],r=l.capabilities.limits.vision?.max_prompt_images??1,a=l.capabilities.limits.vision?.max_prompt_image_size??3145728,I=0,s=[],o=new aoe,c=new Map;for(let m of e.messages)if(m.role=="user")if(typeof m.content=="string"){let G=uMe(m.content,this.gitHubServerUrl,!1,this.logger).filter(A=>!this.processedImageUrls.has(A.url)),p=await this.processImageReferences(G,a,o);s.push(...p.addedImages)}else{let G=[];for(let[p,A]of m.content.entries()){if(A.type==="text"){let Z=uMe(A.text,this.gitHubServerUrl,!1,this.logger).filter(R=>!this.processedImageUrls.has(R.url)),W=await this.processImageReferences(Z,a,o);s.push(...W.addedImages)}else if(A.type==="image_url"){if(A.image_url.url.startsWith("data:")){let[Z,W]=await this.extractAndUploadImageData(A,a,o);if(Z===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(Z),p>=1&&G.length>0){let R=G.at(-1);R&&R.type==="text"&&R.text&&R.text.includes("screenshot")&&c.set(Z,fXt(Z))}G.pop();continue}I++}G.push(A)}m.content=G}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${r}`);I<r&&s.length>0;){let m=s.shift();if(!m){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(m)){this.logger.debug(`Skipping already processed image url: ${m}`);continue}this.processedImageUrls.add(m);let G=`Here is the image url: ${m}`;c.has(m)&&(G=c.get(m)||G),this.logger.debug(`Adding image url: ${m}`),n.push({role:"user",content:[{type:"text",text:G},{type:"image_url",image_url:{url:m}}]}),I++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),I<r)){let m=await this.resolveRepositoryImages(e.messages,r-I,this.settings.github?.serverUrl||"",this.logger,a,o);this.logger.debug(`Resolved ${m.length} repository image URLs`);for(let G of m){if(I>=r)break;if(this.processedImageUrls.has(G)){this.logger.debug(`Skipping already processed repository image url: ${G}`);continue}n.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:G}}]}),this.processedImageUrls.add(G),I++}}let d={imagesExtractedCount:o.extractedImagesSize.length,base64ImagesCount:o.base64ImagesSize.length,imagesRemovedDueToSize:o.imagesRemovedDueToSize,imagesRemovedDueToDimensions:o.imagesRemovedDueToDimensions,imagesResized:o.imagesResized,imagesResolvedFromGitHubMCPCount:o.imagesResolvedFromGitHubMCPSize.length};for(let m=0;m<o.base64ImagesSize.length;m++)d[`base64ImageSize_${m}`]=o.base64ImagesSize[m];for(let m=0;m<o.resizedBase64ImagesSize.length;m++)d[`resizedBase64ImageSize_${m}`]=o.resizedBase64ImagesSize[m];for(let m=0;m<o.extractedImagesSize.length;m++)d[`extractedImageSize_${m}`]=o.extractedImagesSize[m];for(let m=0;m<o.imagesResolvedFromGitHubMCPSize.length;m++)d[`imagesResolvedFromGitHubMCPSize_${m}`]=o.imagesResolvedFromGitHubMCPSize[m];n.length>0&&this.logger.debug(`Using ${n.length} image messages`);for(let m of n)yield{kind:"message",turn:e.turn,callId:e.callId,message:m},e.messages.push(m);d.allImagesSendToLlm=e.messages.filter(j4).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:d},e.messages.some(m=>j4(m))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,l,n){let r=zte(this.settings);if(!r)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let a=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!a||a.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let I=a[1];if(!xXt(this.logger,I))return[""];let s=a[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let o=Buffer.from(s,"base64");if(n.base64ImagesSize.push(o.length),o=await m0e(this.logger,n,l,loe,I,o),n.resizedBase64ImagesSize.push(o?.length??-1),!o)return["",new dMe(`Image size exceeds maximum size of ${EE(l)}`)];s=o.toString("base64");try{let c=await this.uploadBase64ImageData(s,I,r);return c?(this.logger.debug(`Uploaded image url: ${c}`),e.image_url.url=c,[c]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(c){let d=c instanceof Error?c.message:String(c);return this.logger.debug(`Error during image upload: ${d}`),[""]}}async uploadBase64ImageData(e,l,n){try{let r=bZt(this.settings),a=l.split("/").at(1),I=`image-${Date.now()}.${a}`;if(!e||e.trim()==="")return this.logger.error("Empty image data provided for upload"),null;let s=Buffer.from(e,"base64");if(s.length===0)return this.logger.error("Converted image data has zero length"),null;let o=this.settings.github?.repo?.id;if(!o)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let c=`${r}?name=${encodeURIComponent(I)}&content_type=${encodeURIComponent(l)}&repository_id=${o}`;this.logger.debug(`Uploading image data (${EE(s.length)}) to ${r} with name ${encodeURIComponent(I)} and content type ${encodeURIComponent(l)}`);let d={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+n},m=await fetch(c,{method:"POST",headers:d,body:s}).catch(p=>{throw p instanceof Error?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof p=="object"&&p!==null&&"code"in p&&"message"in p?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):this.logger.error(`Failed to upload image: ${String(p)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:p?.code,message:p?.message,stack:p?.stack,name:p?.name,cause:p?.cause},null,2)}`),p});if(!m.ok){let p=await m.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${m.status} ${m.statusText} - ${p}`),null}let G=await m.json();return this.logger.debug(`Upload result: ${JSON.stringify(G,null,2)}`),G.url||null}catch(r){return this.logger.error(`Error handling image upload: ${r instanceof Error?r.message:String(r)}`),r instanceof Error&&r.stack&&this.logger.debug(`Stack trace: ${r.stack}`),null}}async getRepositoryImageViaTools(e){if(this.logger.debug(`Attempting to retrieve repository image: ${e.owner}/${e.repo}/${e.path}@${e.branch}`),this.githubGetFileContentsTool){this.logger.debug(`GitHub MCP tool found, calling with image reference: ${JSON.stringify(e)}`);try{let l=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{toolCallId:crypto.randomUUID(),settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof l}`),this.logger.debug(`GitHub tool call result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`),typeof l=="object"&&l!==null&&"binaryResultForLlm"in l&&Array.isArray(l.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${l.binaryResultForLlm.length} items`);try{for(let n of l.binaryResultForLlm)if(n.data&&n.mimeType){let r=Buffer.from(n.data,"base64"),a=n.mimeType;return{buffer:r,mimeType:a}}}catch(n){this.logger.error(`Failed to parse GitHub tool response: ${n}`),this.logger.debug(`binaryResultForLlm length: ${l.binaryResultForLlm?.length||0}`)}}else typeof l=="string"?this.logger.debug(`GitHub tool returned string result: ${l}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`)}catch(l){this.logger.error(`Error calling GitHub MCP tool: ${l}`)}}else this.logger.debug("GitHub MCP tool 'github-mcp-server-get_file_contents' not available");return this.logger.debug("Failed to retrieve repository image, returning null"),null}async getImgRefsSmallerThanMaxSize(e,l,n){let r=[],a=await Promise.all(e);for(let{imgRef:I,attachment:s}of a)if(this.logger.debug(`Processing attachment for ${I.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(l.extractedImagesSize.push(s.buffer.length),to(this.settings,"copilot_swe_agent_resize_image_references")){if(!await m0e(this.logger,l,n,loe,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}r.push(I.url)}else{let o=await roe(n,loe,s.buffer);if(this.logger.debug(`Image size check for ${I.url}: size=${s.buffer.length}, maxSize=${n}, exceedsSize=${o.exceedsSizeLimit}, exceedsDimensions=${o.exceedsDimensionLimit}`),o.exceedsSizeLimit?(l.imagesRemovedDueToSize++,this.logger.debug(`Image ${I.url} removed due to size (${s.buffer.length} > ${n})`)):o.exceedsDimensionLimit&&(l.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${I.url} removed due to dimensions`)),o.exceedsSizeLimit||o.exceedsDimensionLimit){this.processedImageUrls.add(I.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${EE(n)}.`);continue}r.push(I.url),this.logger.debug(`Image ${I.url} passed size checks and added to results`)}else this.processedImageUrls.add(I.url),this.logger.debug(`Skipping image ${I.url} - could not fetch image data`);return r}async processImageReferences(e,l,n){let r=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${r}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let a=e.filter(s=>!this.processedImageUrls.has(s.url)).map(async s=>{if(this.logger.debug(`Processing image reference: ${JSON.stringify(s,null,2)}`),s.kind==="committed_attachment"){this.logger.debug(`Detected repository image - Owner: ${s.owner}, Repo: ${s.repo}, Branch: ${s.branch}, Path: ${s.path}`);let o=await this.getRepositoryImageViaTools(s);return o?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${o.buffer.length} bytes`),n.imagesResolvedFromGitHubMCPSize.push(o.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:o?.buffer?.length||0,mimeType:o?.mimeType||"",buffer:o?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await $on(s.guid,zte(this.settings),this.logger,this.settings)}}),I=await this.getImgRefsSmallerThanMaxSize(a,n,l);return this.logger.debug(`Processed image references, found ${I.length} attachments smaller than max size of ${EE(l)}`),{addedImages:I}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,l,n){this.logger=e,this.settings=l,this.gitHubServerUrl=l.github?.serverUrl,this.githubGetFileContentsTool=n,this.processedImageUrls=new Set,this.messagesToInsertOnNextPreRequest=[]}toJSON(){return"CAPIImageProcessor"}async onRequestError(e){}async preErrorThrow(e){this.processedImageUrls.size>0&&(e.isVisionFlow=!0)}async postToolExecution(e){let l=e.modelInfo,n=e.toolCall.function.name,r=e.toolResult;if(l?.capabilities?.supports?.vision){let a=Array.from(din(r,n));if(a.length===0){let I=await bin(e.toolCall,this.logger);I&&a.push(I)}this.insertImageUrlMessages(a)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let l of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:l.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:l.url}}]})}},G0e=class{async*preRequest(e){e.messages.some(l=>j4(l))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}toJSON(){return"VisionEnabledProcessor"}};function*din(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 uin="playwright-browser_take_screenshot";function min(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function bin(t,e){if(t.function.name!==uin)return;e.debug("Adding images using Playwright params fallback strategy");let l=JSON.parse(t.function.arguments);if(min(l)){let n=noe.isAbsolute(l.filename)?l.filename:noe.join(iMe,l.filename);e.debug(`Image from Playwright params: ${l.filename}. Updated to ${n}.`);let r=await pin(n,e);if(r){let a=r.buffer.toString("base64");return{url:`data:${r.mimeType};base64,${a}`,isScreenshot:!0}}}}function Gin(t){switch(noe.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function xXt(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 pin(t,e){try{if(!Ioe(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let l=Gin(t);return l?{buffer:await qon.readFile(t),mimeType:l}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(l){return e.error(`Failed to read image from disk: ${l instanceof Error?l.message:String(l)}`),null}}var K4=class t{static DEFAULT_TOKEN_LIMIT=128e3;static DEFAULT_TOKEN_LIMIT_BUFFER=0;static MAX_TOKEN_LIMIT_BUFFER=.5;latestUserPromptMessage;logger;modelToTokenLimit;constructor(e,l){this.latestUserPromptMessage=e,this.logger=l,this.modelToTokenLimit=new Map}toJSON(){return"BasicTruncator"}async*preRequest(e){this.initializeStateForModelOnFirstRequest(e);let l=this.modelToTokenLimit.get(e.modelInfo.name),n=l?.tokenLimit??t.DEFAULT_TOKEN_LIMIT;e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong&&this.throwIfOverTokenLimitOnFirstTurn(e,n);let r=l?.tokenLimitBuffer??t.DEFAULT_TOKEN_LIMIT_BUFFER,a=n*(1-r),I=this.latestUserPromptMessage?LXt(this.latestUserPromptMessage,e.messages):-1,s=[()=>gin(e.messages,e.toolDefinitions,e.modelInfo.name,a),I===-1?void 0:()=>Zin(e.messages,e.toolDefinitions,e.modelInfo.name,a,I)].filter(d=>d!==void 0),o=0,c;for(;(!c||c.postTruncationTokensInMessages>a)&&o<s.length;){let d=s[o]();c=Ain(c,d),o++}return c=c??Nin(e.messages,e.toolDefinitions,e.modelInfo.name,a),c.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(c)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:c},c}async preErrorThrow(){}async onRequestError(e){let l=this.modelToTokenLimit.get(e.modelInfo.name);if(l===void 0){this.logger.warning("Unable to determine if error relates to token limits due to missing information.");return}let{tokenLimit:n,tokenLimitBuffer:r}=l,a=hin(e.error,n);if(a!==void 0){if(a<n)this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:a,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER}),this.logger.debug(`Adjusted model token limit to ${a}`);else{let I=Math.min(r+t.MAX_TOKEN_LIMIT_BUFFER/e.maxRetries,t.MAX_TOKEN_LIMIT_BUFFER);this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:n,tokenLimitBuffer:I}),this.logger.debug(`Adjusted model token limit to ${n}, token limit retry buffer to ${I}`)}return{retryAfter:1}}}getTokenLimitForModel(e){let l=this.modelToTokenLimit.get(e),n=l?l.tokenLimit*(1-l.tokenLimitBuffer):void 0;return{tokenLimit:l?.tokenLimit,tokenLimitBuffer:l?.tokenLimitBuffer,effectiveTokenLimit:n}}initializeStateForModelOnFirstRequest(e){e.turn===0&&e.retry===0&&this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:e.modelInfo.capabilities?.limits?.max_prompt_tokens||e.modelInfo.capabilities?.limits?.max_context_window_tokens||t.DEFAULT_TOKEN_LIMIT,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER})}throwIfOverTokenLimitOnFirstTurn(e,l){if(e.turn===0){let n=jte(e.messages,e.modelInfo.name),r=FZt(e.toolDefinitions,e.modelInfo.name);if(n+r>l){if(e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong)throw new Error(`Initial inputs exceed the model token limit of ${l} tokens.`);this.logger.warning(`Initial inputs exceed the model token limit of ${l} tokens. The model may not be able to process the inputs correctly.`)}}}};function hin(t,e){if(t&&typeof t=="object"){let l="message"in t&&typeof t.message=="string"?t.message.match(/prompt token count of (\d+) exceeds the limit of (\d+)/):null;if(l){let I=parseInt(l[2],10);return isNaN(I)?e:I}if("code"in t&&t.code==="model_max_prompt_tokens_exceeded")return e;let r=[JSON.stringify(t)];t instanceof Error&&(r.push(t.message),t.cause instanceof Error?r.push(t.cause.message):t.cause&&r.push(JSON.stringify(t.cause)));let a="Input length and `max_tokens` exceed context limit";if(r.some(I=>I.includes(a)))return e}}function Ain(t,e){return t?{preTruncationMessagesLength:t.preTruncationMessagesLength,preTruncationTokensInMessages:t.preTruncationTokensInMessages,tokensRemovedDuringTruncation:t.tokensRemovedDuringTruncation+e.tokensRemovedDuringTruncation,messagesRemovedDuringTruncation:t.messagesRemovedDuringTruncation+e.messagesRemovedDuringTruncation,tokenLimit:t.tokenLimit,postTruncationMessagesLength:e.postTruncationMessagesLength,postTruncationTokensInMessages:e.postTruncationTokensInMessages}:e}var SXt=.95;function gin(t,e,l,n,r){let a=t.length;if(a===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:a,postTruncationTokensInMessages:0,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let I=t.map(p=>hD(p,l)),s=jR(JSON.stringify(e),l),o=n*SXt,c=I.reduce((p,A)=>p+A,0)+s;if(c<=o)return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,m=0,G=Math.min(r??t.length,t.length);for(let p=0;p<G;p++){let A=t[p];if(A.role!=="system"&&A.role!=="tool"&&A.role!=="user"){if(A.role==="assistant"){let Z=A.tool_calls||[],W=Z.filter(kA).filter(X=>X.function.name===oS),R=Z.filter(kA).filter(X=>X.function.name!==oS),V=W.length===0,v=new Set(R.map(X=>X.id));if(R.length>0&&(A.tool_calls=W,I[p]=hD(A,l)),V&&(d.add(p),m+=I[p]),v.size>0)for(let X=p+1;X<t.length;X++){let x=t[X];if(x.role==="tool"&&v.has(x.tool_call_id)&&(d.add(X),m+=I[X],v.delete(x.tool_call_id),v.size===0))break}}if(c-m<o)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c-m,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:m,messagesRemovedDuringTruncation:a-t.length}}function Zin(t,e,l,n,r){let a=t.length;if(a===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:a,postTruncationTokensInMessages:0,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let I=t.map(p=>hD(p,l)),s=jR(JSON.stringify(e),l),o=n*SXt,c=I.reduce((p,A)=>p+A,0)+s;if(c<=o)return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,m=0,G=Math.min(r??t.length,t.length);for(let p=0;p<G;p++){let A=t[p];if(A.role!=="system"&&A.role!=="tool"){if(A.role==="user")d.add(p),m+=I[p];else if(A.role==="assistant"){let Z=A.tool_calls||[],W=new Set(Z.map(R=>R.id));if(d.add(p),m+=I[p],W.size>0)for(let R=p+1;R<t.length;R++){let V=t[R];if(V.role==="tool"&&W.has(V.tool_call_id)&&(d.add(R),m+=I[R],W.delete(V.tool_call_id),W.size===0))break}}if(c-m<o)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c-m,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:m,messagesRemovedDuringTruncation:a-t.length}}function Nin(t,e,l,n){let r=t.length;if(r===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:r,postTruncationTokensInMessages:0,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(o=>hD(o,l)),I=jR(JSON.stringify(e),l),s=a.reduce((o,c)=>o+c,0)+I;return{tokenLimit:n,preTruncationTokensInMessages:s,preTruncationMessagesLength:r,postTruncationTokensInMessages:s,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}var xd=class extends qF{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,l){}endGroup(e){}};var BXt={fetch:{tools:[{toolName:"fetch"}]},time:{tools:[{toolName:"get_current_time"},{toolName:"convert_time"}]},sequentialthinking:{tools:[{toolName:"sequentialthinking"}]},"github-mcp-server":{tools:[{toolName:"get_code_scanning_alert"},{toolName:"get_commit"},{toolName:"get_file_contents"},{toolName:"get_issue"},{toolName:"get_issue_comments"},{toolName:"get_me"},{toolName:"get_copilot_space"},{toolName:"get_pull_request"},{toolName:"get_pull_request_comments"},{toolName:"get_pull_request_files"},{toolName:"get_pull_request_reviews"},{toolName:"get_pull_request_status"},{toolName:"get_secret_scanning_alert"},{toolName:"get_tag"},{toolName:"list_branches"},{toolName:"list_code_scanning_alerts"},{toolName:"list_commits"},{toolName:"list_issues"},{toolName:"list_pull_requests"},{toolName:"list_secret_scanning_alerts"},{toolName:"list_tags"},{toolName:"search_code"},{toolName:"search_issues"},{toolName:"search_repositories"},{toolName:"search_users"},{toolName:"get_job_logs"},{toolName:"get_workflow_run"},{toolName:"get_workflow_run_logs"},{toolName:"list_workflow_jobs"},{toolName:"list_workflow_runs"},{toolName:"list_workflow_run_artifacts"},{toolName:"list_workflows"},{toolName:"summarize_job_log_failures"}]},playwright:{tools:[{toolName:"browser_close"},{toolName:"browser_resize"},{toolName:"browser_console_messages"},{toolName:"browser_handle_dialog"},{toolName:"browser_file_upload"},{toolName:"browser_install"},{toolName:"browser_press_key"},{toolName:"browser_navigate"},{toolName:"browser_navigate_back"},{toolName:"browser_navigate_forward"},{toolName:"browser_network_requests"},{toolName:"browser_pdf_save"},{toolName:"browser_take_screenshot"},{toolName:"browser_snapshot"},{toolName:"browser_click"},{toolName:"browser_drag"},{toolName:"browser_hover"},{toolName:"browser_type"},{toolName:"browser_select_option"},{toolName:"browser_tab_list"},{toolName:"browser_tab_new"},{toolName:"browser_tab_select"},{toolName:"browser_tab_close"},{toolName:"browser_generate_playwright_test"},{toolName:"browser_wait_for"}]},primer:{tools:[{toolName:"init"},{toolName:"list_components"},{toolName:"get_component"},{toolName:"get_component_examples"},{toolName:"get_component_usage_guidelines"},{toolName:"get_component_accessibility_guidelines"},{toolName:"list_patterns"},{toolName:"get_pattern"},{toolName:"list_tokens"},{toolName:"get_color_usage"},{toolName:"get_typography_usage"},{toolName:"list_icons"},{toolName:"get_icon"},{toolName:"review_alt_text"}]},azure:"azure-mcp-server","azure-azmcp":"azure-mcp-server","azure-mcp-server-azmcp":"azure-mcp-server","azure-mcp-server":{tools:[{toolName:"aks"},{toolName:"appconfig"},{toolName:"azureterraformbestpractices"},{toolName:"bestpractices"},{toolName:"bicepschema"},{toolName:"cosmos"},{toolName:"datadog"},{toolName:"documentation"},{toolName:"extension_az"},{toolName:"extension_azd"},{toolName:"extension_azqr"},{toolName:"foundry"},{toolName:"grafana"},{toolName:"group"},{toolName:"keyvault"},{toolName:"kusto"},{toolName:"loadtesting"},{toolName:"marketplace"},{toolName:"monitor"},{toolName:"postgres"},{toolName:"redis"},{toolName:"role"},{toolName:"search"},{toolName:"servicebus"},{toolName:"sql"},{toolName:"storage"},{toolName:"subscription"},{toolName:"workbooks"}]}};function p0e(t,e,l){let n=(l||BXt)[t.toLowerCase()],r=new Set;for(;typeof n=="string";){if(r.has(n))return!1;r.add(n),n=BXt[n]}if(!n)return!1;let a=e.toLowerCase();return n.tools.some(I=>I.toolName===a)}var Win="image";var yin="resource",Ein=180*1e3,Rin={timeout:Ein};var pMe=class{constructor(e,l,n){this.settings=e;this.logger=l;this.cacheProviderTools=n}cachedTools=new Map;async invokeTool(e,l,n="hidden_characters"){let r=await this.doInvokeTool(e,l);return this.invokeToolResponseToToolResult(r,n)}invokeToolResponseToToolResult(e,l){let n=e.content||[],r="",a=[];for(let c of n)if(c.type==="text")r+=c.text||"";else if(c.type==="resource"){let d=c.resource;d&&d.blob?a.push({type:yin,data:d.blob,mimeType:d.mimeType||"application/octet-stream"}):d&&d.text&&(r+=d.text)}else c.type==="image"&&a.push({type:Win,data:c.data,mimeType:c.mimeType});let I=r;if(r==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),I=r;else try{let c=JSON.parse(r),d=wOe(c,l);I=JSON.stringify(d)}catch(c){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${c}`),I=YOe(r,l)}this.logger.debug(`Tool invocation result: ${I}`);let s={},o=I?uc(I,"output"):"";return e.isToolError?{textResultForLlm:I,resultType:"failure",error:I,sessionLog:o,toolTelemetry:s}:{textResultForLlm:I,binaryResultForLlm:a,resultType:"success",sessionLog:o,toolTelemetry:s}}async loadTools(e,l={requestRequired:!1}){let n=this.getProviderCacheKey(e),r=this.cachedTools.get(n),a=r??await this.loadToolsFromProvider(e);this.cacheProviderTools&&!r&&this.cachedTools.set(n,a);let I={};for(let[s,o]of Object.entries(a)){let c=o.filterMode||"hidden_characters";I[s]={name:o.name,namespacedName:o.namespacedName,title:o.title||o.name,description:o.description,input_schema:o.input_schema,callback:async d=>{let m=a[s].serverName,G=a[s].name,p=a[s].title;if(!l.requestRequired)return this.invokeTool(s,d,c);let A=await l.request({kind:"mcp",serverName:m,toolName:G,toolTitle:p,args:d,readOnly:!!o.readOnly});switch(A.kind){case"approved":return this.invokeTool(s,d,c);case"denied-by-rules":return wWe(A.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return QWe;case"denied-interactively-by-user":return VWe;default:wo(A,`Unhandled permission result kind: ${A}`)}},safeForTelemetry:o.safeForTelemetry}}return Object.values(I)}};var soe=class t extends pMe{toolIdToClientInfo=new Map;constructor(e,l,n=!1){super(e,l,n)}async doInvokeTool(e,l){let n=this.toolIdToClientInfo.get(e);if(!n)throw new Error(`No MCP client found for tool ID: ${e}`);let r=n.mcpClient,a=t.getToolNameFromIdAndClientName(e,n.clientName),I=await r.callTool({name:a,arguments:l},void 0,{...Rin,onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(I.content))throw new Error("Expected array of results");return{content:I.content,isToolError:I.error!==void 0&&I.error!==null||I.isError===!0}}getProviderCacheKey(e){return[e.clientName,...e.tools,JSON.stringify(e.filterMapping)].join("+")}async loadToolsFromProvider(e){let l={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let n of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(n.name)){this.logger.debug(`Skipping tool ${n.name} for client ${e.clientName}`);continue}let r=t.getToolIdFromClientAndToolName(e.clientName,n.name);this.toolIdToClientInfo.set(r,e);let a;e.safeForTelemetry===!0?a={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?a=e.safeForTelemetry:a={name:p0e(e.clientName,n.name),inputsNames:!1},this.logger.debug(`Adding tool: ${r}`);let I;e.filterMapping===void 0?I="hidden_characters":typeof e.filterMapping=="object"?I=e.filterMapping[n.name]||"hidden_characters":I=e.filterMapping,l[r]={serverName:e.clientName,name:r,namespacedName:`${e.clientName}/${n.name}`,title:n.title||n.annotations?.title||n.name,description:n.description||"",input_schema:n.inputSchema,readOnly:n.annotations?.readOnlyHint,safeForTelemetry:a,filterMode:I}}return l}static getToolIdFromClientAndToolName(e,l){return`${e}-${l}`}static getToolNameFromIdAndClientName(e,l){return e.substring(l.length+1)}};var h0e=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,l,n,r,a,I){this.settings=e,this.logger=l,this.gitHandler=n,this.location=r,this.commitPriorToCompletionWithTools=a,this.jitInstructions=I||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let l,n=async()=>{if(l===void 0)try{l=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(I){this.logger.error(`Failed to get changed paths, err: ${I}`),l=1}return l},r;for(let[I,s]of Object.entries(this.jitInstructions)){let o=eZt(this.settings,s.percentRemainingOfTimeout);o.isWithin&&(!s.whenNoPathsChanged||await n()===0)&&(!r||o.withinMs<r[0])&&(r=[o.withinMs,s.instruction])}let a=r?.[1];if(typeof a=="function"&&(a=a(this.location)),a&&!this.emittedJitInstructions.has(a)){this.logger.debug(`Adding JIT instructions to the history: ${a}`),this.emittedJitInstructions.add(a);let I={role:"user",content:a};e.messages.push(I),yield{kind:"message",turn:e.turn,callId:e.callId,message:I,source:"jit-instruction"}}}}},hMe={remindWhereToDoWork:{instruction:HXt,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:u0e.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:u0e.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:u0e.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};var AMe={agent:"sweagent-capi",model:"claude-sonnet-4"},TXt=AMe;function JB(t){if(!t)return TXt;let[e,...l]=t?.split(":")??[t,void 0],n=l.join(":")||void 0;return{agent:e||void 0,model:n||void 0}}import Sxt from"path";var g0e="4.12.0",xB="04b07795-8ddb-461a-bbee-02f9e1bf7b46",OXt="common",A0e;(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"})(A0e||(A0e={}));var ioe=A0e.AzurePublicCloud,UXt="login.microsoftonline.com",MXt=["*"],_Xt="cae",DXt="nocae",zXt="msal.cache";var gMe;var Yin,Z0e,jXt;function KXt(){return Z0e!==void 0&&jXt!==void 0}function Vin(t){let e={cache:{},broker:{...t.brokerOptions,isEnabled:t.brokerOptions?.enabled??!1,enableMsaPassthrough:t.brokerOptions?.legacyEnableMsaPassthrough??!1}};if(t.tokenCachePersistenceOptions?.enabled){if(gMe===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||zXt;e.cache.cachePlugin=gMe({name:`${l}.${DXt}`,...t.tokenCachePersistenceOptions}),e.cache.cachePluginCae=gMe({name:`${l}.${_Xt}`,...t.tokenCachePersistenceOptions})}return t.brokerOptions?.enabled&&(e.broker.nativeBrokerPlugin=Qin(t.isVSCodeCredential||!1)),e}var PXt={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(" ")},win={vsCode:{credentialName:"Visual Studio Code Credential",packageName:"@azure/identity-vscode",pluginVar:"vsCodePlugin",get brokerInfo(){return jXt}},native:{credentialName:"Broker for WAM",packageName:"@azure/identity-broker",pluginVar:"nativeBrokerPlugin",get brokerInfo(){return Yin}}};function Qin(t){let{credentialName:e,packageName:l,pluginVar:n,brokerInfo:r}=win[t?"vsCode":"native"];if(r===void 0)throw new Error(PXt.missing(e,l,n));if(r.broker.isBrokerAvailable===!1)throw new Error(PXt.unavailable(e,l));return r.broker}var qXt={generatePluginConfiguration:Vin};function Fin(t){return t&&typeof t.error=="string"&&typeof t.error_description=="string"}var e5t="CredentialUnavailableError",tr=class extends Error{constructor(e,l){super(e,l),this.name=e5t}},N0e="AuthenticationError",q4=class extends Error{statusCode;errorResponse;constructor(e,l,n){let r={error:"unknown",errorDescription:"An unknown error occurred and no additional details are available."};if(Fin(l))r=$Xt(l);else if(typeof l=="string")try{let a=JSON.parse(l);r=$Xt(a)}catch{e===400?r={error:"invalid_request",errorDescription:`The service indicated that the request was invalid.
|
|
1746
|
+
`)?.trim();return{...t,reasoning_text:e}}function toe(t){return structuredClone(t)}function kXt(t){return{...t,choices:t.choices.map(e=>{let l=C6(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 j4(t){return t.role==="user"&&Array.isArray(t.content)&&t.content.some(e=>e.type==="image_url")}function LXt(t,e){let l=e.indexOf(t);if(l!==-1)return l;let n=s=>(typeof s.content=="string"?[{type:"text",text:s.content}]:s.content).filter(o=>o.type==="text").map(o=>o.text).join("").trim(),r=n(t),a=e.map((s,o)=>s.role==="user"&&n(s)===r?o:-1).filter(s=>s!==-1),I=a.at(0)??-1;return a.length===1?I:-1}var iMe="/tmp/playwright-logs",Kon="0.0.40",cMe=[`@playwright/mcp@${Kon}`,"--viewport-size","1280, 720","--output-dir",iMe],Mma=[...cMe,"--isolated"];var dMe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},loe=2e3;async function $on(t,e,l,n){let r={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+e},a=`${GZt(n)}/${t}`;l.info(`Downloading image from ${a}`);try{let I=await fetch(a,{method:"GET",headers:r});if(l.info(`Response status: ${I.status} ${I.statusText}`),l.debug(`Download Response URL: ${I.url}`),!I.ok){l.info(`Failed to download image, status: ${I.status}, statusText: ${I.statusText}`);try{let G=await I.text();l.info(`Error response body: ${G}`)}catch(G){l.info(`Could not read error response body: ${G}`)}return{size:0}}let o=(await I.json()).url;if(!o)return l.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let c=await fetch(o,{method:"GET"});if(!c.ok)return l.error(`Failed to download image: ${c.status} ${c.statusText}`),{size:0};let d=await c.arrayBuffer(),m=d.byteLength;return l.info(`Downloaded content size: ${EE(m)}`),{size:m,buffer:Buffer.from(d),mimeType:c.headers.get("content-type")||void 0}}catch(I){return l.error("Network error downloading image"),I instanceof Error&&(l.info(`Error message: ${I.message}`),l.info(`Error stack: ${I.stack}`)),{size:0}}}function uMe(t,e,l,n){let r=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,a=/!\[.*?\]\((.*?)\)/g,I=[];return I.push(...JXt(t,e,r,l,n)),I.push(...JXt(t,e,a,l,n)),I}function JXt(t,e,l,n,r){let a=t.matchAll(l),I=[],s=/\/([a-f0-9-]+)$/;for(let o of a){let c=nin(o[1],e),d=rin(o[1],e,r);if(c||d){let m=o[1].match(s),G={url:o[1],guid:"",kind:d?"legacy_attachment":"attachment"};m&&m.length>1&&(G.guid=m[1]),I.push(G)}else if(n){let m={url:o[1],guid:"",kind:"committed_attachment"};I.push(m)}}return I}function ein(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&Ioe(t)}function Ioe(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function tin(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 lin(t,e,l){if(!t?.url||!t?.ref||!t?.path)throw new Error("Invalid repository insight: missing required fields");if(!e||e.trim()==="")throw new Error("Invalid image path: path cannot be empty");let n=t.url.split("/").slice(3,5).join("/"),r=t.ref.split("/")[2],a;if(e.startsWith("/"))a=e.slice(1);else{let s=t.path,o=noe.dirname(s);a=noe.resolve("/",o,e).slice(1)}return`${l}/${n}/blob/${r}/${a}`}function nin(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function rin(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 GMe(t){let{width:e,height:l}=uvt(t);if(e===void 0||l===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:l}}async function m0e(t,e,l,n,r,a){t.debug(`Checking if image is valid size and dimensions. Max size: ${l}, Max dimension: ${n}`);let{exceedsSizeLimit:I,exceedsDimensionLimit:s}=await roe(l,n,a);if(!s&&!I)return t.debug("Image is within size and dimension limits."),a;if(s){t.debug(`Image x or y dimension exceeds the maximum limit of ${n}, attempting to resize`);let[o,c]=await sin(t,a,n,l,r);if(!o){t.debug("Failed to resize image to fit within the maximum dimensions limits, skipping"),e.imagesRemovedDueToDimensions++,e.imagesFailedToResize++,c==="unsupported_mime_type"?e.resizeErrorsUnsupportedMimeType++:e.resizeErrorsUnknown++;return}let{exceedsDimensionLimit:d}=await roe(l,n,o);if(d){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),o}if(I){t.debug(`Image size ${EE(a.length)} is larger than the maximum size of ${EE(l)}, attempting to reduce image quality`);let o=await oin(t,a,n,l,r);if(!o){t.debug("Failed to reduce image quality to fit within the maximum size, skipping"),e.imagesFailedToReduceQuality++,e.imagesRemovedDueToSize++;return}return e.imagesWithLoweredQuality++,t.debug("Image quality successfully reduced."),o}}async function roe(t,e,l){let n=await GMe(l),r=l.length;return!n.width||!n.height?{exceedsSizeLimit:r>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await Iin(t,l),exceedsDimensionLimit:await ain(e,l)}}async function ain(t,e){let l=await GMe(e);return!l.width||!l.height?!1:l.width>t||l.height>t}async function Iin(t,e){return e.length>t}async function sin(t,e,l,n,r){try{if(!xXt(t,r))return[void 0,"unsupported_mime_type"];let a=await GMe(e);if(!a.width||!a.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let I=async(W,R)=>{let V=(0,bMe.default)(e).resize(W,R,{fit:"inside",withoutEnlargement:!0});return mMe(t,await V.toBuffer(),void 0,r)},s=Math.min(l,a.width),o=Math.min(l,a.height),c=await I(s,o);if(c&&c.length<=n)return[c,void 0];let d=Math.max(s,o),m=1,G=d-1,p,A=0,Z=10;for(;m<=G&&A<Z;){let W=Math.floor((m+G)/2),R=await I(W,W);if(!R)break;let{exceedsSizeLimit:V,exceedsDimensionLimit:v}=await roe(n,l,R);!V&&!v?(p=R,m=W+1):G=W-1,A++}return[p,void 0]}catch(a){return t.error(`Failed to resize image for upload: ${a instanceof Error?a.message:String(a)}`),[void 0,"unknown"]}}async function oin(t,e,l,n,r){try{let a=r==="image/png"?80:100,I=r==="image/png"?Math.floor(a*.4):20,s=await mMe(t,e,I,r);if(!s||s.length>n)return;let o=I,c=a,d,m=0,G=10,p=o,A=c-1;for(;p<=A&&m<G;){let Z=Math.floor((p+A)/2),W=await mMe(t,e,Z,r);if(!W)return d;let{exceedsSizeLimit:R,exceedsDimensionLimit:V}=await roe(n,l,W);!R&&!V?(d=W,p=Z+1):A=Z-1,m++}return d}catch(a){t.error(`Failed to reduce image quality: ${a instanceof Error?a.message:String(a)}`);return}}async function mMe(t,e,l,n){let r=(0,bMe.default)(e);switch(n){case"image/png":return l?r.png({quality:l}).toBuffer():r.png().toBuffer();case"image/jpeg":return l?r.jpeg({quality:l}).toBuffer():r.jpeg().toBuffer();default:t.debug(`Unsupported image format: ${n}`);return}}var aoe=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function iin(t,e,l,n){if(e<=0)return[];let r=[];for(let a of t){if(a.role!=="user"||r.length>=e)continue;let I=typeof a.content=="string"?a.content:JSON.stringify(a.content),s=tin(I);if(s)for(let o in s){if(r.length>=e)break;let c=s[o].contents,d=uMe(c,l,!0,n);for(let m of d){if(r.length>=e)break;let G=m.url,p="",A=!1;if(m.kind==="attachment"||m.kind==="legacy_attachment"?r.push(m):ein(G)?(A=!0,p=lin(s[o],G,l),r.push({url:p,guid:m.guid,kind:"committed_attachment"})):Ioe(G)&&G.startsWith(l)&&(A=!0,r.push({...m,kind:"committed_attachment"})),A){let Z=r[r.length-1],W=new RegExp(`^${l}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),R=Z.url.match(W);if(n.info(`Blob match for ${Z.url}: ${JSON.stringify(R)}`),R&&R.length===5){let[,V,v,X,x]=R;Z.owner=V,Z.repo=v,Z.branch=X,Z.path=x,n.info(`Repository metadata extracted: owner=${V}, repo=${v}, branch=${X}, path=${x}`)}else n.info(`Failed to extract repository metadata from URL: ${Z.url}`)}}}}return r}function cin(t,e){let l=e.flatMap(r=>j4(r)?r.content.flatMap(a=>a.type==="image_url"?a.image_url.url:[]):[]),n=new Set(l);return t.filter(r=>!n.has(r.url))}var b0e=class{async resolveRepositoryImages(e,l,n,r,a,I){if(l<=0)return[];let s=iin(e,l,n,r);this.logger.debug(`Found ${s.length} repository image URLs to process`);let o=cin(s,e),c=await this.processImageReferences(o,a,I);return this.logger.debug(`Processed ${c.addedImages.length} repository image URLs`),c.addedImages}async*preRequest(e){let l=e.modelInfo;if(!l.capabilities?.limits){this.logger.debug("Model limits not defined, skipping image processing");return}if(!l.capabilities?.supports?.vision||!this.settings.featureFlags?.copilot_swe_agent_vision){this.logger.debug("Vision not supported or enabled, skipping image processing");return}if(!this.gitHubServerUrl){this.logger.debug("GitHub server URL is not set, skipping image processing");return}for(let m of this.messagesToInsertOnNextPreRequest)e.messages.push(m),yield{kind:"message",turn:e.turn,callId:e.callId,message:m};this.messagesToInsertOnNextPreRequest.splice(0);let n=[],r=l.capabilities.limits.vision?.max_prompt_images??1,a=l.capabilities.limits.vision?.max_prompt_image_size??3145728,I=0,s=[],o=new aoe,c=new Map;for(let m of e.messages)if(m.role=="user")if(typeof m.content=="string"){let G=uMe(m.content,this.gitHubServerUrl,!1,this.logger).filter(A=>!this.processedImageUrls.has(A.url)),p=await this.processImageReferences(G,a,o);s.push(...p.addedImages)}else{let G=[];for(let[p,A]of m.content.entries()){if(A.type==="text"){let Z=uMe(A.text,this.gitHubServerUrl,!1,this.logger).filter(R=>!this.processedImageUrls.has(R.url)),W=await this.processImageReferences(Z,a,o);s.push(...W.addedImages)}else if(A.type==="image_url"){if(A.image_url.url.startsWith("data:")){let[Z,W]=await this.extractAndUploadImageData(A,a,o);if(Z===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(Z),p>=1&&G.length>0){let R=G.at(-1);R&&R.type==="text"&&R.text&&R.text.includes("screenshot")&&c.set(Z,fXt(Z))}G.pop();continue}I++}G.push(A)}m.content=G}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${r}`);I<r&&s.length>0;){let m=s.shift();if(!m){this.logger.debug("Skipping empty image url");continue}if(this.processedImageUrls.has(m)){this.logger.debug(`Skipping already processed image url: ${m}`);continue}this.processedImageUrls.add(m);let G=`Here is the image url: ${m}`;c.has(m)&&(G=c.get(m)||G),this.logger.debug(`Adding image url: ${m}`),n.push({role:"user",content:[{type:"text",text:G},{type:"image_url",image_url:{url:m}}]}),I++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),I<r)){let m=await this.resolveRepositoryImages(e.messages,r-I,this.settings.github?.serverUrl||"",this.logger,a,o);this.logger.debug(`Resolved ${m.length} repository image URLs`);for(let G of m){if(I>=r)break;if(this.processedImageUrls.has(G)){this.logger.debug(`Skipping already processed repository image url: ${G}`);continue}n.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:G}}]}),this.processedImageUrls.add(G),I++}}let d={imagesExtractedCount:o.extractedImagesSize.length,base64ImagesCount:o.base64ImagesSize.length,imagesRemovedDueToSize:o.imagesRemovedDueToSize,imagesRemovedDueToDimensions:o.imagesRemovedDueToDimensions,imagesResized:o.imagesResized,imagesResolvedFromGitHubMCPCount:o.imagesResolvedFromGitHubMCPSize.length};for(let m=0;m<o.base64ImagesSize.length;m++)d[`base64ImageSize_${m}`]=o.base64ImagesSize[m];for(let m=0;m<o.resizedBase64ImagesSize.length;m++)d[`resizedBase64ImageSize_${m}`]=o.resizedBase64ImagesSize[m];for(let m=0;m<o.extractedImagesSize.length;m++)d[`extractedImageSize_${m}`]=o.extractedImagesSize[m];for(let m=0;m<o.imagesResolvedFromGitHubMCPSize.length;m++)d[`imagesResolvedFromGitHubMCPSize_${m}`]=o.imagesResolvedFromGitHubMCPSize[m];n.length>0&&this.logger.debug(`Using ${n.length} image messages`);for(let m of n)yield{kind:"message",turn:e.turn,callId:e.callId,message:m},e.messages.push(m);d.allImagesSendToLlm=e.messages.filter(j4).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:d},e.messages.some(m=>j4(m))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,l,n){let r=zte(this.settings);if(!r)return this.logger.debug("No user token available, skipping image upload"),[""];this.logger.debug("Found base64 image data, uploading...");let a=e.image_url.url.match(/^data:(.*?);base64,(.*)$/);if(!a||a.length<3)return this.logger.debug("Invalid base64 image data format, skipping"),[""];let I=a[1];if(!xXt(this.logger,I))return[""];let s=a[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let o=Buffer.from(s,"base64");if(n.base64ImagesSize.push(o.length),o=await m0e(this.logger,n,l,loe,I,o),n.resizedBase64ImagesSize.push(o?.length??-1),!o)return["",new dMe(`Image size exceeds maximum size of ${EE(l)}`)];s=o.toString("base64");try{let c=await this.uploadBase64ImageData(s,I,r);return c?(this.logger.debug(`Uploaded image url: ${c}`),e.image_url.url=c,[c]):(this.logger.debug("Failed to upload image, skipping"),[""])}catch(c){let d=c instanceof Error?c.message:String(c);return this.logger.debug(`Error during image upload: ${d}`),[""]}}async uploadBase64ImageData(e,l,n){try{let r=bZt(this.settings),a=l.split("/").at(1),I=`image-${Date.now()}.${a}`;if(!e||e.trim()==="")return this.logger.error("Empty image data provided for upload"),null;let s=Buffer.from(e,"base64");if(s.length===0)return this.logger.error("Converted image data has zero length"),null;let o=this.settings.github?.repo?.id;if(!o)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let c=`${r}?name=${encodeURIComponent(I)}&content_type=${encodeURIComponent(l)}&repository_id=${o}`;this.logger.debug(`Uploading image data (${EE(s.length)}) to ${r} with name ${encodeURIComponent(I)} and content type ${encodeURIComponent(l)}`);let d={"Content-Type":"application/octet-stream",Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",Authorization:"Bearer "+n},m=await fetch(c,{method:"POST",headers:d,body:s}).catch(p=>{throw p instanceof Error?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof p=="object"&&p!==null&&"code"in p&&"message"in p?(this.logger.error(`Failed to upload image: ${p.message}`),p.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):p.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(p.message.includes("request entity too large")||p.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):this.logger.error(`Failed to upload image: ${String(p)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:p?.code,message:p?.message,stack:p?.stack,name:p?.name,cause:p?.cause},null,2)}`),p});if(!m.ok){let p=await m.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${m.status} ${m.statusText} - ${p}`),null}let G=await m.json();return this.logger.debug(`Upload result: ${JSON.stringify(G,null,2)}`),G.url||null}catch(r){return this.logger.error(`Error handling image upload: ${r instanceof Error?r.message:String(r)}`),r instanceof Error&&r.stack&&this.logger.debug(`Stack trace: ${r.stack}`),null}}async getRepositoryImageViaTools(e){if(this.logger.debug(`Attempting to retrieve repository image: ${e.owner}/${e.repo}/${e.path}@${e.branch}`),this.githubGetFileContentsTool){this.logger.debug(`GitHub MCP tool found, calling with image reference: ${JSON.stringify(e)}`);try{let l=await this.githubGetFileContentsTool.callback({owner:e.owner,repo:e.repo,path:e.path,branch:e.branch},{toolCallId:crypto.randomUUID(),settings:this.settings});if(this.logger.debug(`GitHub tool call completed. Result type: ${typeof l}`),this.logger.debug(`GitHub tool call result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`),typeof l=="object"&&l!==null&&"binaryResultForLlm"in l&&Array.isArray(l.binaryResultForLlm)){this.logger.debug(`Tool result has binaryResultForLlm array with ${l.binaryResultForLlm.length} items`);try{for(let n of l.binaryResultForLlm)if(n.data&&n.mimeType){let r=Buffer.from(n.data,"base64"),a=n.mimeType;return{buffer:r,mimeType:a}}}catch(n){this.logger.error(`Failed to parse GitHub tool response: ${n}`),this.logger.debug(`binaryResultForLlm length: ${l.binaryResultForLlm?.length||0}`)}}else typeof l=="string"?this.logger.debug(`GitHub tool returned string result: ${l}`):this.logger.debug(`GitHub tool call failed or returned unexpected format. Result structure: ${typeof l=="object"&&l!==null?Object.keys(l).join(", "):typeof l}`)}catch(l){this.logger.error(`Error calling GitHub MCP tool: ${l}`)}}else this.logger.debug("GitHub MCP tool 'github-mcp-server-get_file_contents' not available");return this.logger.debug("Failed to retrieve repository image, returning null"),null}async getImgRefsSmallerThanMaxSize(e,l,n){let r=[],a=await Promise.all(e);for(let{imgRef:I,attachment:s}of a)if(this.logger.debug(`Processing attachment for ${I.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(l.extractedImagesSize.push(s.buffer.length),to(this.settings,"copilot_swe_agent_resize_image_references")){if(!await m0e(this.logger,l,n,loe,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}r.push(I.url)}else{let o=await roe(n,loe,s.buffer);if(this.logger.debug(`Image size check for ${I.url}: size=${s.buffer.length}, maxSize=${n}, exceedsSize=${o.exceedsSizeLimit}, exceedsDimensions=${o.exceedsDimensionLimit}`),o.exceedsSizeLimit?(l.imagesRemovedDueToSize++,this.logger.debug(`Image ${I.url} removed due to size (${s.buffer.length} > ${n})`)):o.exceedsDimensionLimit&&(l.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${I.url} removed due to dimensions`)),o.exceedsSizeLimit||o.exceedsDimensionLimit){this.processedImageUrls.add(I.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${EE(n)}.`);continue}r.push(I.url),this.logger.debug(`Image ${I.url} passed size checks and added to results`)}else this.processedImageUrls.add(I.url),this.logger.debug(`Skipping image ${I.url} - could not fetch image data`);return r}async processImageReferences(e,l,n){let r=this.settings.github?.serverUrl||"";this.logger.debug(`Processing ${e.length} image references`),this.logger.debug(`GitHub server URL: ${r}`),this.logger.debug(`Image references: ${e.map(s=>s.url).join(", ")}`);let a=e.filter(s=>!this.processedImageUrls.has(s.url)).map(async s=>{if(this.logger.debug(`Processing image reference: ${JSON.stringify(s,null,2)}`),s.kind==="committed_attachment"){this.logger.debug(`Detected repository image - Owner: ${s.owner}, Repo: ${s.repo}, Branch: ${s.branch}, Path: ${s.path}`);let o=await this.getRepositoryImageViaTools(s);return o?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${o.buffer.length} bytes`),n.imagesResolvedFromGitHubMCPSize.push(o.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:o?.buffer?.length||0,mimeType:o?.mimeType||"",buffer:o?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await $on(s.guid,zte(this.settings),this.logger,this.settings)}}),I=await this.getImgRefsSmallerThanMaxSize(a,n,l);return this.logger.debug(`Processed image references, found ${I.length} attachments smaller than max size of ${EE(l)}`),{addedImages:I}}logger;settings;gitHubServerUrl;processedImageUrls;messagesToInsertOnNextPreRequest;githubGetFileContentsTool;constructor(e,l,n){this.logger=e,this.settings=l,this.gitHubServerUrl=l.github?.serverUrl,this.githubGetFileContentsTool=n,this.processedImageUrls=new Set,this.messagesToInsertOnNextPreRequest=[]}toJSON(){return"CAPIImageProcessor"}async onRequestError(e){}async preErrorThrow(e){this.processedImageUrls.size>0&&(e.isVisionFlow=!0)}async postToolExecution(e){let l=e.modelInfo,n=e.toolCall.function.name,r=e.toolResult;if(l?.capabilities?.supports?.vision){let a=Array.from(din(r,n));if(a.length===0){let I=await bin(e.toolCall,this.logger);I&&a.push(I)}this.insertImageUrlMessages(a)}}insertImageUrlMessages(e){this.logger.info(`Inserted ${e.length} image URLs from tools into chat history.`);for(let l of e)this.messagesToInsertOnNextPreRequest.push({role:"user",content:[{type:"text",text:l.isScreenshot?"Here is a screenshot:":"Here is an image:"},{type:"image_url",image_url:{url:l.url}}]})}},G0e=class{async*preRequest(e){e.messages.some(l=>j4(l))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}toJSON(){return"VisionEnabledProcessor"}};function*din(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 uin="playwright-browser_take_screenshot";function min(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function bin(t,e){if(t.function.name!==uin)return;e.debug("Adding images using Playwright params fallback strategy");let l=JSON.parse(t.function.arguments);if(min(l)){let n=noe.isAbsolute(l.filename)?l.filename:noe.join(iMe,l.filename);e.debug(`Image from Playwright params: ${l.filename}. Updated to ${n}.`);let r=await pin(n,e);if(r){let a=r.buffer.toString("base64");return{url:`data:${r.mimeType};base64,${a}`,isScreenshot:!0}}}}function Gin(t){switch(noe.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function xXt(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 pin(t,e){try{if(!Ioe(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let l=Gin(t);return l?{buffer:await qon.readFile(t),mimeType:l}:(e.debug(`Image ${t} is not a mime type supported for file -> data URI flow`),null)}catch(l){return e.error(`Failed to read image from disk: ${l instanceof Error?l.message:String(l)}`),null}}var K4=class t{static DEFAULT_TOKEN_LIMIT=128e3;static DEFAULT_TOKEN_LIMIT_BUFFER=0;static MAX_TOKEN_LIMIT_BUFFER=.5;latestUserPromptMessage;logger;modelToTokenLimit;constructor(e,l){this.latestUserPromptMessage=e,this.logger=l,this.modelToTokenLimit=new Map}toJSON(){return"BasicTruncator"}async*preRequest(e){this.initializeStateForModelOnFirstRequest(e);let l=this.modelToTokenLimit.get(e.modelInfo.name),n=l?.tokenLimit??t.DEFAULT_TOKEN_LIMIT;e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong&&this.throwIfOverTokenLimitOnFirstTurn(e,n);let r=l?.tokenLimitBuffer??t.DEFAULT_TOKEN_LIMIT_BUFFER,a=n*(1-r),I=this.latestUserPromptMessage?LXt(this.latestUserPromptMessage,e.messages):-1,s=[()=>gin(e.messages,e.toolDefinitions,e.modelInfo.name,a),I===-1?void 0:()=>Zin(e.messages,e.toolDefinitions,e.modelInfo.name,a,I)].filter(d=>d!==void 0),o=0,c;for(;(!c||c.postTruncationTokensInMessages>a)&&o<s.length;){let d=s[o]();c=Ain(c,d),o++}return c=c??Nin(e.messages,e.toolDefinitions,e.modelInfo.name,a),c.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(c)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:c},c}async preErrorThrow(){}async onRequestError(e){let l=this.modelToTokenLimit.get(e.modelInfo.name);if(l===void 0){this.logger.warning("Unable to determine if error relates to token limits due to missing information.");return}let{tokenLimit:n,tokenLimitBuffer:r}=l,a=hin(e.error,n);if(a!==void 0){if(a<n)this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:a,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER}),this.logger.debug(`Adjusted model token limit to ${a}`);else{let I=Math.min(r+t.MAX_TOKEN_LIMIT_BUFFER/e.maxRetries,t.MAX_TOKEN_LIMIT_BUFFER);this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:n,tokenLimitBuffer:I}),this.logger.debug(`Adjusted model token limit to ${n}, token limit retry buffer to ${I}`)}return{retryAfter:1}}}getTokenLimitForModel(e){let l=this.modelToTokenLimit.get(e),n=l?l.tokenLimit*(1-l.tokenLimitBuffer):void 0;return{tokenLimit:l?.tokenLimit,tokenLimitBuffer:l?.tokenLimitBuffer,effectiveTokenLimit:n}}initializeStateForModelOnFirstRequest(e){e.turn===0&&e.retry===0&&this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:e.modelInfo.capabilities?.limits?.max_prompt_tokens||e.modelInfo.capabilities?.limits?.max_context_window_tokens||t.DEFAULT_TOKEN_LIMIT,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER})}throwIfOverTokenLimitOnFirstTurn(e,l){if(e.turn===0){let n=jte(e.messages,e.modelInfo.name),r=FZt(e.toolDefinitions,e.modelInfo.name);if(n+r>l){if(e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong)throw new Error(`Initial inputs exceed the model token limit of ${l} tokens.`);this.logger.warning(`Initial inputs exceed the model token limit of ${l} tokens. The model may not be able to process the inputs correctly.`)}}}};function hin(t,e){if(t&&typeof t=="object"){let l="message"in t&&typeof t.message=="string"?t.message.match(/prompt token count of (\d+) exceeds the limit of (\d+)/):null;if(l){let I=parseInt(l[2],10);return isNaN(I)?e:I}if("code"in t&&t.code==="model_max_prompt_tokens_exceeded")return e;let r=[JSON.stringify(t)];t instanceof Error&&(r.push(t.message),t.cause instanceof Error?r.push(t.cause.message):t.cause&&r.push(JSON.stringify(t.cause)));let a="Input length and `max_tokens` exceed context limit";if(r.some(I=>I.includes(a)))return e}}function Ain(t,e){return t?{preTruncationMessagesLength:t.preTruncationMessagesLength,preTruncationTokensInMessages:t.preTruncationTokensInMessages,tokensRemovedDuringTruncation:t.tokensRemovedDuringTruncation+e.tokensRemovedDuringTruncation,messagesRemovedDuringTruncation:t.messagesRemovedDuringTruncation+e.messagesRemovedDuringTruncation,tokenLimit:t.tokenLimit,postTruncationMessagesLength:e.postTruncationMessagesLength,postTruncationTokensInMessages:e.postTruncationTokensInMessages}:e}var SXt=.95;function gin(t,e,l,n,r){let a=t.length;if(a===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:a,postTruncationTokensInMessages:0,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let I=t.map(p=>hD(p,l)),s=jR(JSON.stringify(e),l),o=n*SXt,c=I.reduce((p,A)=>p+A,0)+s;if(c<=o)return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,m=0,G=Math.min(r??t.length,t.length);for(let p=0;p<G;p++){let A=t[p];if(A.role!=="system"&&A.role!=="tool"&&A.role!=="user"){if(A.role==="assistant"){let Z=A.tool_calls||[],W=Z.filter(kA).filter(X=>X.function.name===oS),R=Z.filter(kA).filter(X=>X.function.name!==oS),V=W.length===0,v=new Set(R.map(X=>X.id));if(R.length>0&&(A.tool_calls=W,I[p]=hD(A,l)),V&&(d.add(p),m+=I[p]),v.size>0)for(let X=p+1;X<t.length;X++){let x=t[X];if(x.role==="tool"&&v.has(x.tool_call_id)&&(d.add(X),m+=I[X],v.delete(x.tool_call_id),v.size===0))break}}if(c-m<o)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c-m,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:m,messagesRemovedDuringTruncation:a-t.length}}function Zin(t,e,l,n,r){let a=t.length;if(a===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:a,postTruncationTokensInMessages:0,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let I=t.map(p=>hD(p,l)),s=jR(JSON.stringify(e),l),o=n*SXt,c=I.reduce((p,A)=>p+A,0)+s;if(c<=o)return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c,postTruncationMessagesLength:a,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let d=new Set,m=0,G=Math.min(r??t.length,t.length);for(let p=0;p<G;p++){let A=t[p];if(A.role!=="system"&&A.role!=="tool"){if(A.role==="user")d.add(p),m+=I[p];else if(A.role==="assistant"){let Z=A.tool_calls||[],W=new Set(Z.map(R=>R.id));if(d.add(p),m+=I[p],W.size>0)for(let R=p+1;R<t.length;R++){let V=t[R];if(V.role==="tool"&&W.has(V.tool_call_id)&&(d.add(R),m+=I[R],W.delete(V.tool_call_id),W.size===0))break}}if(c-m<o)break}}for(let p=t.length-1;p>=0;p--)d.has(p)&&t.splice(p,1);return{tokenLimit:n,preTruncationTokensInMessages:c,preTruncationMessagesLength:a,postTruncationTokensInMessages:c-m,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:m,messagesRemovedDuringTruncation:a-t.length}}function Nin(t,e,l,n){let r=t.length;if(r===0)return{tokenLimit:n,preTruncationTokensInMessages:0,preTruncationMessagesLength:r,postTruncationTokensInMessages:0,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let a=t.map(o=>hD(o,l)),I=jR(JSON.stringify(e),l),s=a.reduce((o,c)=>o+c,0)+I;return{tokenLimit:n,preTruncationTokensInMessages:s,preTruncationMessagesLength:r,postTruncationTokensInMessages:s,postTruncationMessagesLength:r,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}var xd=class extends qF{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,l){}endGroup(e){}};var BXt={fetch:{tools:[{toolName:"fetch"}]},time:{tools:[{toolName:"get_current_time"},{toolName:"convert_time"}]},sequentialthinking:{tools:[{toolName:"sequentialthinking"}]},"github-mcp-server":{tools:[{toolName:"get_code_scanning_alert"},{toolName:"get_commit"},{toolName:"get_file_contents"},{toolName:"get_issue"},{toolName:"get_issue_comments"},{toolName:"get_me"},{toolName:"get_copilot_space"},{toolName:"get_pull_request"},{toolName:"get_pull_request_comments"},{toolName:"get_pull_request_files"},{toolName:"get_pull_request_reviews"},{toolName:"get_pull_request_status"},{toolName:"get_secret_scanning_alert"},{toolName:"get_tag"},{toolName:"list_branches"},{toolName:"list_code_scanning_alerts"},{toolName:"list_commits"},{toolName:"list_issues"},{toolName:"list_pull_requests"},{toolName:"list_secret_scanning_alerts"},{toolName:"list_tags"},{toolName:"search_code"},{toolName:"search_issues"},{toolName:"search_repositories"},{toolName:"search_users"},{toolName:"get_job_logs"},{toolName:"get_workflow_run"},{toolName:"get_workflow_run_logs"},{toolName:"list_workflow_jobs"},{toolName:"list_workflow_runs"},{toolName:"list_workflow_run_artifacts"},{toolName:"list_workflows"},{toolName:"summarize_job_log_failures"}]},playwright:{tools:[{toolName:"browser_close"},{toolName:"browser_resize"},{toolName:"browser_console_messages"},{toolName:"browser_handle_dialog"},{toolName:"browser_file_upload"},{toolName:"browser_install"},{toolName:"browser_press_key"},{toolName:"browser_navigate"},{toolName:"browser_navigate_back"},{toolName:"browser_navigate_forward"},{toolName:"browser_network_requests"},{toolName:"browser_pdf_save"},{toolName:"browser_take_screenshot"},{toolName:"browser_snapshot"},{toolName:"browser_click"},{toolName:"browser_drag"},{toolName:"browser_hover"},{toolName:"browser_type"},{toolName:"browser_select_option"},{toolName:"browser_tab_list"},{toolName:"browser_tab_new"},{toolName:"browser_tab_select"},{toolName:"browser_tab_close"},{toolName:"browser_generate_playwright_test"},{toolName:"browser_wait_for"}]},primer:{tools:[{toolName:"init"},{toolName:"list_components"},{toolName:"get_component"},{toolName:"get_component_examples"},{toolName:"get_component_usage_guidelines"},{toolName:"get_component_accessibility_guidelines"},{toolName:"list_patterns"},{toolName:"get_pattern"},{toolName:"list_tokens"},{toolName:"get_color_usage"},{toolName:"get_typography_usage"},{toolName:"list_icons"},{toolName:"get_icon"},{toolName:"review_alt_text"}]},azure:"azure-mcp-server","azure-azmcp":"azure-mcp-server","azure-mcp-server-azmcp":"azure-mcp-server","azure-mcp-server":{tools:[{toolName:"aks"},{toolName:"appconfig"},{toolName:"azureterraformbestpractices"},{toolName:"bestpractices"},{toolName:"bicepschema"},{toolName:"cosmos"},{toolName:"datadog"},{toolName:"documentation"},{toolName:"extension_az"},{toolName:"extension_azd"},{toolName:"extension_azqr"},{toolName:"foundry"},{toolName:"grafana"},{toolName:"group"},{toolName:"keyvault"},{toolName:"kusto"},{toolName:"loadtesting"},{toolName:"marketplace"},{toolName:"monitor"},{toolName:"postgres"},{toolName:"redis"},{toolName:"role"},{toolName:"search"},{toolName:"servicebus"},{toolName:"sql"},{toolName:"storage"},{toolName:"subscription"},{toolName:"workbooks"}]}};function p0e(t,e,l){let n=(l||BXt)[t.toLowerCase()],r=new Set;for(;typeof n=="string";){if(r.has(n))return!1;r.add(n),n=BXt[n]}if(!n)return!1;let a=e.toLowerCase();return n.tools.some(I=>I.toolName===a)}var Win="image";var yin="resource",Ein=180*1e3,Rin={timeout:Ein};var pMe=class{constructor(e,l,n){this.settings=e;this.logger=l;this.cacheProviderTools=n}cachedTools=new Map;async invokeTool(e,l,n="hidden_characters"){let r=await this.doInvokeTool(e,l);return this.invokeToolResponseToToolResult(r,n)}invokeToolResponseToToolResult(e,l){let n=e.content||[],r="",a=[];for(let c of n)if(c.type==="text")r+=c.text||"";else if(c.type==="resource"){let d=c.resource;d&&d.blob?a.push({type:yin,data:d.blob,mimeType:d.mimeType||"application/octet-stream"}):d&&d.text&&(r+=d.text)}else c.type==="image"&&a.push({type:Win,data:c.data,mimeType:c.mimeType});let I=r;if(r==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),I=r;else try{let c=JSON.parse(r),d=wOe(c,l);I=JSON.stringify(d)}catch(c){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${c}`),I=YOe(r,l)}this.logger.debug(`Tool invocation result: ${I}`);let s={},o=I?uc(I,"output"):"";return e.isToolError?{textResultForLlm:I,resultType:"failure",error:I,sessionLog:o,toolTelemetry:s}:{textResultForLlm:I,binaryResultForLlm:a,resultType:"success",sessionLog:o,toolTelemetry:s}}async loadTools(e,l={requestRequired:!1}){let n=this.getProviderCacheKey(e),r=this.cachedTools.get(n),a=r??await this.loadToolsFromProvider(e);this.cacheProviderTools&&!r&&this.cachedTools.set(n,a);let I={};for(let[s,o]of Object.entries(a)){let c=o.filterMode||"hidden_characters";I[s]={name:o.name,namespacedName:o.namespacedName,title:o.title||o.name,description:o.description,input_schema:o.input_schema,callback:async d=>{let m=a[s].serverName,G=a[s].name,p=a[s].title;if(!l.requestRequired)return this.invokeTool(s,d,c);let A=await l.request({kind:"mcp",serverName:m,toolName:G,toolTitle:p,args:d,readOnly:!!o.readOnly});switch(A.kind){case"approved":return this.invokeTool(s,d,c);case"denied-by-rules":return wWe(A.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return QWe;case"denied-interactively-by-user":return VWe;default:wo(A,`Unhandled permission result kind: ${A}`)}},safeForTelemetry:o.safeForTelemetry}}return Object.values(I)}};var soe=class t extends pMe{toolIdToClientInfo=new Map;constructor(e,l,n=!1){super(e,l,n)}async doInvokeTool(e,l){let n=this.toolIdToClientInfo.get(e);if(!n)throw new Error(`No MCP client found for tool ID: ${e}`);let r=n.mcpClient,a=t.getToolNameFromIdAndClientName(e,n.clientName),I=await r.callTool({name:a,arguments:l},void 0,{...Rin,onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(I.content))throw new Error("Expected array of results");return{content:I.content,isToolError:I.error!==void 0&&I.error!==null||I.isError===!0}}getProviderCacheKey(e){return[e.clientName,...e.tools,JSON.stringify(e.filterMapping)].join("+")}async loadToolsFromProvider(e){let l={};this.logger.debug(`Loading tools for client: ${e.clientName}`);for(let n of(await e.mcpClient.listTools()).tools){if(!e.tools.includes("*")&&!e.tools.includes(n.name)){this.logger.debug(`Skipping tool ${n.name} for client ${e.clientName}`);continue}let r=t.getToolIdFromClientAndToolName(e.clientName,n.name);this.toolIdToClientInfo.set(r,e);let a;e.safeForTelemetry===!0?a={name:!0,inputsNames:!0}:e.safeForTelemetry&&typeof e.safeForTelemetry=="object"?a=e.safeForTelemetry:a={name:p0e(e.clientName,n.name),inputsNames:!1},this.logger.debug(`Adding tool: ${r}`);let I;e.filterMapping===void 0?I="hidden_characters":typeof e.filterMapping=="object"?I=e.filterMapping[n.name]||"hidden_characters":I=e.filterMapping,l[r]={serverName:e.clientName,name:r,namespacedName:`${e.clientName}/${n.name}`,title:n.title||n.annotations?.title||n.name,description:n.description||"",input_schema:n.inputSchema,readOnly:n.annotations?.readOnlyHint,safeForTelemetry:a,filterMode:I}}return l}static getToolIdFromClientAndToolName(e,l){return`${e}-${l}`}static getToolNameFromIdAndClientName(e,l){return e.substring(l.length+1)}};var h0e=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,l,n,r,a,I){this.settings=e,this.logger=l,this.gitHandler=n,this.location=r,this.commitPriorToCompletionWithTools=a,this.jitInstructions=I||{},this.emittedJitInstructions=new Set}toJSON(){return"JitInstructionsProcessor"}async*preRequest(e){if(this.jitInstructions&&Object.keys(this.jitInstructions).length>0){let l,n=async()=>{if(l===void 0)try{l=(await this.gitHandler.getChangedPaths(this.location,"HEAD",this.commitPriorToCompletionWithTools)).length}catch(s){this.logger.error(`Failed to get changed paths, err: ${s}`),l=1}return l},r=[];for(let[s,o]of Object.entries(this.jitInstructions)){let c=eZt(this.settings,o.percentRemainingOfTimeout);c.isWithin&&r.push({config:o,withinMs:c.withinMs})}let a=r.map(({config:s,withinMs:o})=>{let c=typeof s.instruction=="function"?s.instruction(this.location):s.instruction;return{config:s,withinMs:o,instruction:c}}).filter(({instruction:s})=>!this.emittedJitInstructions.has(s)),I;for(let{config:s,withinMs:o,instruction:c}of a)(s.whenNoPathsChanged?await n()===0:!0)&&(!I||o<I.withinMs)&&(I={withinMs:o,instruction:c});if(I){this.logger.debug(`Adding JIT instructions to the history: ${I.instruction}`),this.emittedJitInstructions.add(I.instruction);let s={role:"user",content:I.instruction};e.messages.push(s),yield{kind:"message",turn:e.turn,callId:e.callId,message:s,source:"jit-instruction"}}}}},hMe={remindWhereToDoWork:{instruction:HXt,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:u0e.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:u0e.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:u0e.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};var AMe={agent:"sweagent-capi",model:"claude-sonnet-4"},TXt=AMe;function JB(t){if(!t)return TXt;let[e,...l]=t?.split(":")??[t,void 0],n=l.join(":")||void 0;return{agent:e||void 0,model:n||void 0}}import Sxt from"path";var g0e="4.12.0",xB="04b07795-8ddb-461a-bbee-02f9e1bf7b46",OXt="common",A0e;(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"})(A0e||(A0e={}));var ioe=A0e.AzurePublicCloud,UXt="login.microsoftonline.com",MXt=["*"],_Xt="cae",DXt="nocae",zXt="msal.cache";var gMe;var Yin,Z0e,jXt;function KXt(){return Z0e!==void 0&&jXt!==void 0}function Vin(t){let e={cache:{},broker:{...t.brokerOptions,isEnabled:t.brokerOptions?.enabled??!1,enableMsaPassthrough:t.brokerOptions?.legacyEnableMsaPassthrough??!1}};if(t.tokenCachePersistenceOptions?.enabled){if(gMe===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||zXt;e.cache.cachePlugin=gMe({name:`${l}.${DXt}`,...t.tokenCachePersistenceOptions}),e.cache.cachePluginCae=gMe({name:`${l}.${_Xt}`,...t.tokenCachePersistenceOptions})}return t.brokerOptions?.enabled&&(e.broker.nativeBrokerPlugin=Qin(t.isVSCodeCredential||!1)),e}var PXt={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(" ")},win={vsCode:{credentialName:"Visual Studio Code Credential",packageName:"@azure/identity-vscode",pluginVar:"vsCodePlugin",get brokerInfo(){return jXt}},native:{credentialName:"Broker for WAM",packageName:"@azure/identity-broker",pluginVar:"nativeBrokerPlugin",get brokerInfo(){return Yin}}};function Qin(t){let{credentialName:e,packageName:l,pluginVar:n,brokerInfo:r}=win[t?"vsCode":"native"];if(r===void 0)throw new Error(PXt.missing(e,l,n));if(r.broker.isBrokerAvailable===!1)throw new Error(PXt.unavailable(e,l));return r.broker}var qXt={generatePluginConfiguration:Vin};function Fin(t){return t&&typeof t.error=="string"&&typeof t.error_description=="string"}var e5t="CredentialUnavailableError",tr=class extends Error{constructor(e,l){super(e,l),this.name=e5t}},N0e="AuthenticationError",q4=class extends Error{statusCode;errorResponse;constructor(e,l,n){let r={error:"unknown",errorDescription:"An unknown error occurred and no additional details are available."};if(Fin(l))r=$Xt(l);else if(typeof l=="string")try{let a=JSON.parse(l);r=$Xt(a)}catch{e===400?r={error:"invalid_request",errorDescription:`The service indicated that the request was invalid.
|
|
1747
1747
|
|
|
1748
1748
|
${l}`}:r={error:"unknown_error",errorDescription:`An unknown error has occurred. Response body:
|
|
1749
1749
|
|
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.354-
|
|
4
|
+
"version": "0.0.354-8",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"repository": {
|
|
@@ -37,6 +37,6 @@
|
|
|
37
37
|
"worker/**/*"
|
|
38
38
|
],
|
|
39
39
|
"buildMetadata": {
|
|
40
|
-
"gitCommit": "
|
|
40
|
+
"gitCommit": "a07bcff"
|
|
41
41
|
}
|
|
42
42
|
}
|
package/sdk/index.js
CHANGED
|
@@ -1343,7 +1343,7 @@ ${t}
|
|
|
1343
1343
|
|
|
1344
1344
|
<reminder>
|
|
1345
1345
|
The user may have mentioned images, if so these will have been attached to this message, in the order they were mentioned
|
|
1346
|
-
</reminder>`),l.trim()},_8={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."},Z8e=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${Rue(t)}. Commit changes by using the **report_progress** tool.</reminder>`;var nZe="/tmp/playwright-logs",P7I="0.0.40",cZe=[`@playwright/mcp@${P7I}`,"--viewport-size","1280, 720","--output-dir",nZe],nxl=[...cZe,"--isolated"];var rZe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},vB=2e3;async function _7I(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=`${U2e(l)}/${t}`;I.info(`Downloading image from ${c}`);try{let r=await fetch(c,{method:"GET",headers:n});if(I.info(`Response status: ${r.status} ${r.statusText}`),I.debug(`Download Response URL: ${r.url}`),!r.ok){I.info(`Failed to download image, status: ${r.status}, statusText: ${r.statusText}`);try{let d=await r.text();I.info(`Error response body: ${d}`)}catch(d){I.info(`Could not read error response body: ${d}`)}return{size:0}}let a=(await r.json()).url;if(!a)return I.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let o=await fetch(a,{method:"GET"});if(!o.ok)return I.error(`Failed to download image: ${o.status} ${o.statusText}`),{size:0};let G=await o.arrayBuffer(),i=G.byteLength;return I.info(`Downloaded content size: ${Um(i)}`),{size:i,buffer:Buffer.from(G),mimeType:o.headers.get("content-type")||void 0}}catch(r){return I.error("Network error downloading image"),r instanceof Error&&(I.info(`Error message: ${r.message}`),I.info(`Error stack: ${r.stack}`)),{size:0}}}function sZe(t,e,I,l){let n=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,c=/!\[.*?\]\((.*?)\)/g,r=[];return r.push(...W8e(t,e,n,I,l)),r.push(...W8e(t,e,c,I,l)),r}function W8e(t,e,I,l,n){let c=t.matchAll(I),r=[],s=/\/([a-f0-9-]+)$/;for(let a of c){let o=t_I(a[1],e),G=l_I(a[1],e,n);if(o||G){let i=a[1].match(s),d={url:a[1],guid:"",kind:G?"legacy_attachment":"attachment"};i&&i.length>1&&(d.guid=i[1]),r.push(d)}else if(l){let i={url:a[1],guid:"",kind:"committed_attachment"};r.push(i)}}return r}function $7I(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&GZe(t)}function GZe(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function e_I(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 I_I(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,a=CB.dirname(s);c=CB.resolve("/",a,e).slice(1)}return`${I}/${l}/blob/${n}/${c}`}function t_I(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function l_I(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 iZe(t){let{width:e,height:I}=wPe(t);if(e===void 0||I===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:I}}async function $8(t,e,I,l,n,c){t.debug(`Checking if image is valid size and dimensions. Max size: ${I}, Max dimension: ${l}`);let{exceedsSizeLimit:r,exceedsDimensionLimit:s}=await JB(I,l,c);if(!s&&!r)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[a,o]=await r_I(t,c,l,I,n);if(!a){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:G}=await JB(I,l,a);if(G){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),a}if(r){t.debug(`Image size ${Um(c.length)} is larger than the maximum size of ${Um(I)}, attempting to reduce image quality`);let a=await s_I(t,c,l,I,n);if(!a){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."),a}}async function JB(t,e,I){let l=await iZe(I),n=I.length;return!l.width||!l.height?{exceedsSizeLimit:n>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await c_I(t,I),exceedsDimensionLimit:await n_I(e,I)}}async function n_I(t,e){let I=await iZe(e);return!I.width||!I.height?!1:I.width>t||I.height>t}async function c_I(t,e){return e.length>t}async function r_I(t,e,I,l,n){try{if(!N8e(t,n))return[void 0,"unsupported_mime_type"];let c=await iZe(e);if(!c.width||!c.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let r=async(u,Z)=>{let N=(0,oZe.default)(e).resize(u,Z,{fit:"inside",withoutEnlargement:!0});return aZe(t,await N.toBuffer(),void 0,n)},s=Math.min(I,c.width),a=Math.min(I,c.height),o=await r(s,a);if(o&&o.length<=l)return[o,void 0];let G=Math.max(s,a),i=1,d=G-1,b,m=0,h=10;for(;i<=d&&m<h;){let u=Math.floor((i+d)/2),Z=await r(u,u);if(!Z)break;let{exceedsSizeLimit:N,exceedsDimensionLimit:g}=await JB(l,I,Z);!N&&!g?(b=Z,i=u+1):d=u-1,m++}return[b,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 s_I(t,e,I,l,n){try{let c=n==="image/png"?80:100,r=n==="image/png"?Math.floor(c*.4):20,s=await aZe(t,e,r,n);if(!s||s.length>l)return;let a=r,o=c,G,i=0,d=10,b=a,m=o-1;for(;b<=m&&i<d;){let h=Math.floor((b+m)/2),u=await aZe(t,e,h,n);if(!u)return G;let{exceedsSizeLimit:Z,exceedsDimensionLimit:N}=await JB(l,I,u);!Z&&!N?(G=u,b=h+1):m=h-1,i++}return G}catch(c){t.error(`Failed to reduce image quality: ${c instanceof Error?c.message:String(c)}`);return}}async function aZe(t,e,I,l){let n=(0,oZe.default)(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 LB=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function a_I(t,e,I,l){if(e<=0)return[];let n=[];for(let c of t){if(c.role!=="user"||n.length>=e)continue;let r=typeof c.content=="string"?c.content:JSON.stringify(c.content),s=e_I(r);if(s)for(let a in s){if(n.length>=e)break;let o=s[a].contents,G=sZe(o,I,!0,l);for(let i of G){if(n.length>=e)break;let d=i.url,b="",m=!1;if(i.kind==="attachment"||i.kind==="legacy_attachment"?n.push(i):$7I(d)?(m=!0,b=I_I(s[a],d,I),n.push({url:b,guid:i.guid,kind:"committed_attachment"})):GZe(d)&&d.startsWith(I)&&(m=!0,n.push({...i,kind:"committed_attachment"})),m){let h=n[n.length-1],u=new RegExp(`^${I}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),Z=h.url.match(u);if(l.info(`Blob match for ${h.url}: ${JSON.stringify(Z)}`),Z&&Z.length===5){let[,N,g,y,F]=Z;h.owner=N,h.repo=g,h.branch=y,h.path=F,l.info(`Repository metadata extracted: owner=${N}, repo=${g}, branch=${y}, path=${F}`)}else l.info(`Failed to extract repository metadata from URL: ${h.url}`)}}}}return n}function o_I(t,e){let I=e.flatMap(n=>n0(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 e7=class{async resolveRepositoryImages(e,I,l,n,c,r){if(I<=0)return[];let s=a_I(e,I,l,n);this.logger.debug(`Found ${s.length} repository image URLs to process`);let a=o_I(s,e),o=await this.processImageReferences(a,c,r);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",turn:e.turn,callId:e.callId,message:i};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,r=0,s=[],a=new LB,o=new Map;for(let i of e.messages)if(i.role=="user")if(typeof i.content=="string"){let d=sZe(i.content,this.gitHubServerUrl,!1,this.logger).filter(m=>!this.processedImageUrls.has(m.url)),b=await this.processImageReferences(d,c,a);s.push(...b.addedImages)}else{let d=[];for(let[b,m]of i.content.entries()){if(m.type==="text"){let h=sZe(m.text,this.gitHubServerUrl,!1,this.logger).filter(Z=>!this.processedImageUrls.has(Z.url)),u=await this.processImageReferences(h,c,a);s.push(...u.addedImages)}else if(m.type==="image_url"){if(m.image_url.url.startsWith("data:")){let[h,u]=await this.extractAndUploadImageData(m,c,a);if(h===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(h),b>=1&&d.length>0){let Z=d.at(-1);Z&&Z.type==="text"&&Z.text&&Z.text.includes("screenshot")&&o.set(h,u8e(h))}d.pop();continue}r++}d.push(m)}i.content=d}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${n}`);r<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 d=`Here is the image url: ${i}`;o.has(i)&&(d=o.get(i)||d),this.logger.debug(`Adding image url: ${i}`),l.push({role:"user",content:[{type:"text",text:d},{type:"image_url",image_url:{url:i}}]}),r++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),r<n)){let i=await this.resolveRepositoryImages(e.messages,n-r,this.settings.github?.serverUrl||"",this.logger,c,a);this.logger.debug(`Resolved ${i.length} repository image URLs`);for(let d of i){if(r>=n)break;if(this.processedImageUrls.has(d)){this.logger.debug(`Skipping already processed repository image url: ${d}`);continue}l.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:d}}]}),this.processedImageUrls.add(d),r++}}let G={imagesExtractedCount:a.extractedImagesSize.length,base64ImagesCount:a.base64ImagesSize.length,imagesRemovedDueToSize:a.imagesRemovedDueToSize,imagesRemovedDueToDimensions:a.imagesRemovedDueToDimensions,imagesResized:a.imagesResized,imagesResolvedFromGitHubMCPCount:a.imagesResolvedFromGitHubMCPSize.length};for(let i=0;i<a.base64ImagesSize.length;i++)G[`base64ImageSize_${i}`]=a.base64ImagesSize[i];for(let i=0;i<a.resizedBase64ImagesSize.length;i++)G[`resizedBase64ImageSize_${i}`]=a.resizedBase64ImagesSize[i];for(let i=0;i<a.extractedImagesSize.length;i++)G[`extractedImageSize_${i}`]=a.extractedImagesSize[i];for(let i=0;i<a.imagesResolvedFromGitHubMCPSize.length;i++)G[`imagesResolvedFromGitHubMCPSize_${i}`]=a.imagesResolvedFromGitHubMCPSize[i];l.length>0&&this.logger.debug(`Using ${l.length} image messages`);for(let i of l)yield{kind:"message",turn:e.turn,callId:e.callId,message:i},e.messages.push(i);G.allImagesSendToLlm=e.messages.filter(n0).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:G},e.messages.some(i=>n0(i))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,I,l){let n=IC(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 r=c[1];if(!N8e(this.logger,r))return[""];let s=c[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let a=Buffer.from(s,"base64");if(l.base64ImagesSize.push(a.length),a=await $8(this.logger,l,I,vB,r,a),l.resizedBase64ImagesSize.push(a?.length??-1),!a)return["",new rZe(`Image size exceeds maximum size of ${Um(I)}`)];s=a.toString("base64");try{let o=await this.uploadBase64ImageData(s,r,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 G=o instanceof Error?o.message:String(o);return this.logger.debug(`Error during image upload: ${G}`),[""]}}async uploadBase64ImageData(e,I,l){try{let n=z2e(this.settings),c=I.split("/").at(1),r=`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 a=this.settings.github?.repo?.id;if(!a)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let o=`${n}?name=${encodeURIComponent(r)}&content_type=${encodeURIComponent(I)}&repository_id=${a}`;this.logger.debug(`Uploading image data (${Um(s.length)}) to ${n} with name ${encodeURIComponent(r)} and content type ${encodeURIComponent(I)}`);let G={"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:G,body:s}).catch(b=>{throw b instanceof Error?(this.logger.error(`Failed to upload image: ${b.message}`),b.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):b.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(b.message.includes("request entity too large")||b.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof b=="object"&&b!==null&&"code"in b&&"message"in b?(this.logger.error(`Failed to upload image: ${b.message}`),b.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):b.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(b.message.includes("request entity too large")||b.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(b)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:b?.code,message:b?.message,stack:b?.stack,name:b?.name,cause:b?.cause},null,2)}`),b});if(!i.ok){let b=await i.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${i.status} ${i.statusText} - ${b}`),null}let d=await i.json();return this.logger.debug(`Upload result: ${JSON.stringify(d,null,2)}`),d.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},{toolCallId:crypto.randomUUID(),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:r,attachment:s}of c)if(this.logger.debug(`Processing attachment for ${r.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(I.extractedImagesSize.push(s.buffer.length),hl(this.settings,"copilot_swe_agent_resize_image_references")){if(!await $8(this.logger,I,l,vB,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}n.push(r.url)}else{let a=await JB(l,vB,s.buffer);if(this.logger.debug(`Image size check for ${r.url}: size=${s.buffer.length}, maxSize=${l}, exceedsSize=${a.exceedsSizeLimit}, exceedsDimensions=${a.exceedsDimensionLimit}`),a.exceedsSizeLimit?(I.imagesRemovedDueToSize++,this.logger.debug(`Image ${r.url} removed due to size (${s.buffer.length} > ${l})`)):a.exceedsDimensionLimit&&(I.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${r.url} removed due to dimensions`)),a.exceedsSizeLimit||a.exceedsDimensionLimit){this.processedImageUrls.add(r.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${Um(l)}.`);continue}n.push(r.url),this.logger.debug(`Image ${r.url} passed size checks and added to results`)}else this.processedImageUrls.add(r.url),this.logger.debug(`Skipping image ${r.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 a=await this.getRepositoryImageViaTools(s);return a?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${a.buffer.length} bytes`),l.imagesResolvedFromGitHubMCPSize.push(a.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:a?.buffer?.length||0,mimeType:a?.mimeType||"",buffer:a?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await _7I(s.guid,IC(this.settings),this.logger,this.settings)}}),r=await this.getImgRefsSmallerThanMaxSize(c,l,I);return this.logger.debug(`Processed image references, found ${r.length} attachments smaller than max size of ${Um(I)}`),{addedImages:r}}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(G_I(n,l));if(c.length===0){let r=await b_I(e.toolCall,this.logger);r&&c.push(r)}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*G_I(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 i_I="playwright-browser_take_screenshot";function d_I(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function b_I(t,e){if(t.function.name!==i_I)return;e.debug("Adding images using Playwright params fallback strategy");let I=JSON.parse(t.function.arguments);if(d_I(I)){let l=CB.isAbsolute(I.filename)?I.filename:CB.join(nZe,I.filename);e.debug(`Image from Playwright params: ${I.filename}. Updated to ${l}.`);let n=await h_I(l,e);if(n){let c=n.buffer.toString("base64");return{url:`data:${n.mimeType};base64,${c}`,isScreenshot:!0}}}}function m_I(t){switch(CB.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function N8e(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 h_I(t,e){try{if(!GZe(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let I=m_I(t);return I?{buffer:await q7I.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}}var ov=class t{static DEFAULT_TOKEN_LIMIT=128e3;static DEFAULT_TOKEN_LIMIT_BUFFER=0;static MAX_TOKEN_LIMIT_BUFFER=.5;latestUserPromptMessage;logger;modelToTokenLimit;constructor(e,I){this.latestUserPromptMessage=e,this.logger=I,this.modelToTokenLimit=new Map}toJSON(){return"BasicTruncator"}async*preRequest(e){this.initializeStateForModelOnFirstRequest(e);let I=this.modelToTokenLimit.get(e.modelInfo.name),l=I?.tokenLimit??t.DEFAULT_TOKEN_LIMIT;e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong&&this.throwIfOverTokenLimitOnFirstTurn(e,l);let n=I?.tokenLimitBuffer??t.DEFAULT_TOKEN_LIMIT_BUFFER,c=l*(1-n),r=this.latestUserPromptMessage?nze(this.latestUserPromptMessage,e.messages):-1,s=[()=>Z_I(e.messages,e.toolDefinitions,e.modelInfo.name,c),r===-1?void 0:()=>W_I(e.messages,e.toolDefinitions,e.modelInfo.name,c,r)].filter(G=>G!==void 0),a=0,o;for(;(!o||o.postTruncationTokensInMessages>c)&&a<s.length;){let G=s[a]();o=u_I(o,G),a++}return o=o??N_I(e.messages,e.toolDefinitions,e.modelInfo.name,c),o.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(o)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:o},o}async preErrorThrow(){}async onRequestError(e){let I=this.modelToTokenLimit.get(e.modelInfo.name);if(I===void 0){this.logger.warning("Unable to determine if error relates to token limits due to missing information.");return}let{tokenLimit:l,tokenLimitBuffer:n}=I,c=p_I(e.error,l);if(c!==void 0){if(c<l)this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:c,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER}),this.logger.debug(`Adjusted model token limit to ${c}`);else{let r=Math.min(n+t.MAX_TOKEN_LIMIT_BUFFER/e.maxRetries,t.MAX_TOKEN_LIMIT_BUFFER);this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:l,tokenLimitBuffer:r}),this.logger.debug(`Adjusted model token limit to ${l}, token limit retry buffer to ${r}`)}return{retryAfter:1}}}getTokenLimitForModel(e){let I=this.modelToTokenLimit.get(e),l=I?I.tokenLimit*(1-I.tokenLimitBuffer):void 0;return{tokenLimit:I?.tokenLimit,tokenLimitBuffer:I?.tokenLimitBuffer,effectiveTokenLimit:l}}initializeStateForModelOnFirstRequest(e){e.turn===0&&e.retry===0&&this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:e.modelInfo.capabilities?.limits?.max_prompt_tokens||e.modelInfo.capabilities?.limits?.max_context_window_tokens||t.DEFAULT_TOKEN_LIMIT,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER})}throwIfOverTokenLimitOnFirstTurn(e,I){if(e.turn===0){let l=d2e(e.messages,e.modelInfo.name),n=b2e(e.toolDefinitions,e.modelInfo.name);if(l+n>I){if(e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong)throw new Error(`Initial inputs exceed the model token limit of ${I} tokens.`);this.logger.warning(`Initial inputs exceed the model token limit of ${I} tokens. The model may not be able to process the inputs correctly.`)}}}};function p_I(t,e){if(t&&typeof t=="object"){let I="message"in t&&typeof t.message=="string"?t.message.match(/prompt token count of (\d+) exceeds the limit of (\d+)/):null;if(I){let r=parseInt(I[2],10);return isNaN(r)?e:r}if("code"in t&&t.code==="model_max_prompt_tokens_exceeded")return e;let n=[JSON.stringify(t)];t instanceof Error&&(n.push(t.message),t.cause instanceof Error?n.push(t.cause.message):t.cause&&n.push(JSON.stringify(t.cause)));let c="Input length and `max_tokens` exceed context limit";if(n.some(r=>r.includes(c)))return e}}function u_I(t,e){return t?{preTruncationMessagesLength:t.preTruncationMessagesLength,preTruncationTokensInMessages:t.preTruncationTokensInMessages,tokensRemovedDuringTruncation:t.tokensRemovedDuringTruncation+e.tokensRemovedDuringTruncation,messagesRemovedDuringTruncation:t.messagesRemovedDuringTruncation+e.messagesRemovedDuringTruncation,tokenLimit:t.tokenLimit,postTruncationMessagesLength:e.postTruncationMessagesLength,postTruncationTokensInMessages:e.postTruncationTokensInMessages}:e}var Y8e=.95;function Z_I(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 r=t.map(b=>zF(b,I)),s=Td(JSON.stringify(e),I),a=l*Y8e,o=r.reduce((b,m)=>b+m,0)+s;if(o<=a)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let G=new Set,i=0,d=Math.min(n??t.length,t.length);for(let b=0;b<d;b++){let m=t[b];if(m.role!=="system"&&m.role!=="tool"&&m.role!=="user"){if(m.role==="assistant"){let h=m.tool_calls||[],u=h.filter(AG).filter(y=>y.function.name===sJ),Z=h.filter(AG).filter(y=>y.function.name!==sJ),N=u.length===0,g=new Set(Z.map(y=>y.id));if(Z.length>0&&(m.tool_calls=u,r[b]=zF(m,I)),N&&(G.add(b),i+=r[b]),g.size>0)for(let y=b+1;y<t.length;y++){let F=t[y];if(F.role==="tool"&&g.has(F.tool_call_id)&&(G.add(y),i+=r[y],g.delete(F.tool_call_id),g.size===0))break}}if(o-i<a)break}}for(let b=t.length-1;b>=0;b--)G.has(b)&&t.splice(b,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function W_I(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 r=t.map(b=>zF(b,I)),s=Td(JSON.stringify(e),I),a=l*Y8e,o=r.reduce((b,m)=>b+m,0)+s;if(o<=a)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let G=new Set,i=0,d=Math.min(n??t.length,t.length);for(let b=0;b<d;b++){let m=t[b];if(m.role!=="system"&&m.role!=="tool"){if(m.role==="user")G.add(b),i+=r[b];else if(m.role==="assistant"){let h=m.tool_calls||[],u=new Set(h.map(Z=>Z.id));if(G.add(b),i+=r[b],u.size>0)for(let Z=b+1;Z<t.length;Z++){let N=t[Z];if(N.role==="tool"&&u.has(N.tool_call_id)&&(G.add(Z),i+=r[Z],u.delete(N.tool_call_id),u.size===0))break}}if(o-i<a)break}}for(let b=t.length-1;b>=0;b--)G.has(b)&&t.splice(b,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function N_I(t,e,I,l){let n=t.length;if(n===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:n,postTruncationTokensInMessages:0,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let c=t.map(a=>zF(a,I)),r=Td(JSON.stringify(e),I),s=c.reduce((a,o)=>a+o,0)+r;return{tokenLimit:l,preTruncationTokensInMessages:s,preTruncationMessagesLength:n,postTruncationTokensInMessages:s,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}var dW=class extends Mp{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,I){}endGroup(e){}};var V8e={fetch:{tools:[{toolName:"fetch"}]},time:{tools:[{toolName:"get_current_time"},{toolName:"convert_time"}]},sequentialthinking:{tools:[{toolName:"sequentialthinking"}]},"github-mcp-server":{tools:[{toolName:"get_code_scanning_alert"},{toolName:"get_commit"},{toolName:"get_file_contents"},{toolName:"get_issue"},{toolName:"get_issue_comments"},{toolName:"get_me"},{toolName:"get_copilot_space"},{toolName:"get_pull_request"},{toolName:"get_pull_request_comments"},{toolName:"get_pull_request_files"},{toolName:"get_pull_request_reviews"},{toolName:"get_pull_request_status"},{toolName:"get_secret_scanning_alert"},{toolName:"get_tag"},{toolName:"list_branches"},{toolName:"list_code_scanning_alerts"},{toolName:"list_commits"},{toolName:"list_issues"},{toolName:"list_pull_requests"},{toolName:"list_secret_scanning_alerts"},{toolName:"list_tags"},{toolName:"search_code"},{toolName:"search_issues"},{toolName:"search_repositories"},{toolName:"search_users"},{toolName:"get_job_logs"},{toolName:"get_workflow_run"},{toolName:"get_workflow_run_logs"},{toolName:"list_workflow_jobs"},{toolName:"list_workflow_runs"},{toolName:"list_workflow_run_artifacts"},{toolName:"list_workflows"},{toolName:"summarize_job_log_failures"}]},playwright:{tools:[{toolName:"browser_close"},{toolName:"browser_resize"},{toolName:"browser_console_messages"},{toolName:"browser_handle_dialog"},{toolName:"browser_file_upload"},{toolName:"browser_install"},{toolName:"browser_press_key"},{toolName:"browser_navigate"},{toolName:"browser_navigate_back"},{toolName:"browser_navigate_forward"},{toolName:"browser_network_requests"},{toolName:"browser_pdf_save"},{toolName:"browser_take_screenshot"},{toolName:"browser_snapshot"},{toolName:"browser_click"},{toolName:"browser_drag"},{toolName:"browser_hover"},{toolName:"browser_type"},{toolName:"browser_select_option"},{toolName:"browser_tab_list"},{toolName:"browser_tab_new"},{toolName:"browser_tab_select"},{toolName:"browser_tab_close"},{toolName:"browser_generate_playwright_test"},{toolName:"browser_wait_for"}]},primer:{tools:[{toolName:"init"},{toolName:"list_components"},{toolName:"get_component"},{toolName:"get_component_examples"},{toolName:"get_component_usage_guidelines"},{toolName:"get_component_accessibility_guidelines"},{toolName:"list_patterns"},{toolName:"get_pattern"},{toolName:"list_tokens"},{toolName:"get_color_usage"},{toolName:"get_typography_usage"},{toolName:"list_icons"},{toolName:"get_icon"},{toolName:"review_alt_text"}]},azure:"azure-mcp-server","azure-azmcp":"azure-mcp-server","azure-mcp-server-azmcp":"azure-mcp-server","azure-mcp-server":{tools:[{toolName:"aks"},{toolName:"appconfig"},{toolName:"azureterraformbestpractices"},{toolName:"bestpractices"},{toolName:"bicepschema"},{toolName:"cosmos"},{toolName:"datadog"},{toolName:"documentation"},{toolName:"extension_az"},{toolName:"extension_azd"},{toolName:"extension_azqr"},{toolName:"foundry"},{toolName:"grafana"},{toolName:"group"},{toolName:"keyvault"},{toolName:"kusto"},{toolName:"loadtesting"},{toolName:"marketplace"},{toolName:"monitor"},{toolName:"postgres"},{toolName:"redis"},{toolName:"role"},{toolName:"search"},{toolName:"servicebus"},{toolName:"sql"},{toolName:"storage"},{toolName:"subscription"},{toolName:"workbooks"}]}};function I7(t,e,I){let l=(I||V8e)[t.toLowerCase()],n=new Set;for(;typeof l=="string";){if(n.has(l))return!1;n.add(l),l=V8e[l]}if(!l)return!1;let c=e.toLowerCase();return l.tools.some(r=>r.toolName===c)}var Y_I="image";var V_I="resource",R_I=180*1e3,y_I={timeout:R_I};var dZe=class{constructor(e,I,l){this.settings=e;this.logger=I;this.cacheProviderTools=l}cachedTools=new Map;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 G=o.resource;G&&G.blob?c.push({type:V_I,data:G.blob,mimeType:G.mimeType||"application/octet-stream"}):G&&G.text&&(n+=G.text)}else o.type==="image"&&c.push({type:Y_I,data:o.data,mimeType:o.mimeType});let r=n;if(n==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),r=n;else try{let o=JSON.parse(n),G=xpe(o,I);r=JSON.stringify(G)}catch(o){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${o}`),r=fpe(n,I)}this.logger.debug(`Tool invocation result: ${r}`);let s={},a=r?Dn(r,"output"):"";return e.isToolError?{textResultForLlm:r,resultType:"failure",error:r,sessionLog:a,toolTelemetry:s}:{textResultForLlm:r,binaryResultForLlm:c,resultType:"success",sessionLog:a,toolTelemetry:s}}async loadTools(e,I={requestRequired:!1}){let l=this.getProviderCacheKey(e),n=this.cachedTools.get(l),c=n??await this.loadToolsFromProvider(e);this.cacheProviderTools&&!n&&this.cachedTools.set(l,c);let r={};for(let[s,a]of Object.entries(c)){let o=a.filterMode||"hidden_characters";r[s]={name:a.name,namespacedName:a.namespacedName,title:a.title||a.name,description:a.description,input_schema:a.input_schema,callback:async G=>{let i=c[s].serverName,d=c[s].name,b=c[s].title;if(!I.requestRequired)return this.invokeTool(s,G,o);let m=await I.request({kind:"mcp",serverName:i,toolName:d,toolTitle:b,args:G,readOnly:!!a.readOnly});switch(m.kind){case"approved":return this.invokeTool(s,G,o);case"denied-by-rules":return kT(m.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return xT;case"denied-interactively-by-user":return fT;default:bm(m,`Unhandled permission result kind: ${m}`)}},safeForTelemetry:a.safeForTelemetry}}return Object.values(r)}};var fB=class t extends dZe{toolIdToClientInfo=new Map;constructor(e,I,l=!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),r=await n.callTool({name:c,arguments:I},void 0,{...y_I,onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(r.content))throw new Error("Expected array of results");return{content:r.content,isToolError:r.error!==void 0&&r.error!==null||r.isError===!0}}getProviderCacheKey(e){return[e.clientName,...e.tools,JSON.stringify(e.filterMapping)].join("+")}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:I7(e.clientName,l.name),inputsNames:!1},this.logger.debug(`Adding tool: ${n}`);let r;e.filterMapping===void 0?r="hidden_characters":typeof e.filterMapping=="object"?r=e.filterMapping[l.name]||"hidden_characters":r=e.filterMapping,I[n]={serverName:e.clientName,name:n,namespacedName:`${e.clientName}/${l.name}`,title:l.title||l.annotations?.title||l.name,description:l.description||"",input_schema:l.inputSchema,readOnly:l.annotations?.readOnlyHint,safeForTelemetry:c,filterMode:r}}return I}static getToolIdFromClientAndToolName(e,I){return`${e}-${I}`}static getToolNameFromIdAndClientName(e,I){return e.substring(I.length+1)}};var t7=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,I,l,n,c,r){this.settings=e,this.logger=I,this.gitHandler=l,this.location=n,this.commitPriorToCompletionWithTools=c,this.jitInstructions=r||{},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(r){this.logger.error(`Failed to get changed paths, err: ${r}`),I=1}return I},n;for(let[r,s]of Object.entries(this.jitInstructions)){let a=l2e(this.settings,s.percentRemainingOfTimeout);a.isWithin&&(!s.whenNoPathsChanged||await l()===0)&&(!n||a.withinMs<n[0])&&(n=[a.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 r={role:"user",content:c};e.messages.push(r),yield{kind:"message",turn:e.turn,callId:e.callId,message:r,source:"jit-instruction"}}}}},mZe={remindWhereToDoWork:{instruction:Z8e,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:_8.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:_8.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:_8.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};function l7(t){if(!t)return cze;let[e,...I]=t?.split(":")??[t,void 0],l=I.join(":")||void 0;return{agent:e||void 0,model:l||void 0}}var kB=class{logger;forcePremiumRequest=!1;constructor(e){this.logger=e}async*preRequest(e){e.turn===0||this.forcePremiumRequest?(e.additionalRequestHeaders["X-Initiator"]="user",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'user'")):(e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'agent'")),this.resetPremiumRequest(),yield*[]}setForcePremiumRequest(){this.forcePremiumRequest=!0}toJSON(){return JSON.stringify({type:"InitiatorHeaderProcessor"})}resetPremiumRequest(){this.forcePremiumRequest=!1}},xB=class{logger;constructor(e){this.logger=e}async*preRequest(e){e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("FreeRequestProcessor: Setting X-Initiator to 'agent'"),yield*[]}setForcePremiumRequest(){}toJSON(){return JSON.stringify({type:"FreeRequestProcessor"})}};function n7(t){return t.kind==="message"&&t.message.role==="assistant"}function R8e(t){return t.kind==="message"&&t.message.role==="user"}function y8e(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function g8e(t){return t.kind==="message"&&t.message.role==="tool"}function g_I(t,e){return t.toolCalls.find(I=>I.toolCallId===e)}function F_I(t,e,I){let l=I.function.name;try{let n=JSON.parse(I.function.arguments||"{}"),c=e.find(o=>o.name===l),r=c?.safeForTelemetry||{name:!1,inputsNames:!1},s=bX(c),a;if(s&&t.customAgents&&t.settings){let o=t.customAgents.find(G=>G.name===l);if(o){let G=t.settings.github?.repo?.name??"",i=G.split("/"),d=i.length===2?i[0]:"",b=i.length===2?i[1]:G,m=o.mcpServers?Object.keys(o.mcpServers).join(","):"",h=o.mcpServers?Object.keys(o.mcpServers).length:0;a={repoOwner:d,repoName:b,displayName:o.name,mcpServerNames:m,mcpServerCount:h}}}return{toolCallId:I.id,toolName:l,arguments:I.function.arguments,safeForTelemetryToolName:r===!0||r.name?l:XR(l),safeForTelemetryArguments:r===!0||r.inputsNames?Ize(n):"",isCustomAgent:s,customAgentInfo:a}}catch{return{toolCallId:I.id,toolName:l,arguments:I.function.arguments,safeForTelemetryToolName:XR(l),safeForTelemetryArguments:"",isCustomAgent:!1,customAgentInfo:void 0}}}var c7=class{constructor(e,I,l){this.runtimeContext=e;this.forAgent=I;this.toolsInUse=l}turnDataCache=new Map;emittedTurns=new Set;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:Z$(this.runtimeContext.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,callId:e.callId,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:tze(e.requestMessages)},e.kind==="model_call_success"&&(l={...l,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):R8e(e)&&e.source==="jit-instruction"?l={...l,jitInstructionsAdded:(l?.jitInstructionsAdded??0)+1}:n7(e)&&e.message.tool_calls?l={...l,toolCalls:l.toolCalls.concat(e.message.tool_calls.map(n=>({...F_I(this.runtimeContext,this.toolsInUse,n)})))}:g8e(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:{callId:I.callId,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:Z$(this.runtimeContext.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.runtimeContext.callback?.progress(l)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,I){let l=I.toolCallId,n=g_I(e,l);if(n){let c=I.toolResult,r={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...c.toolTelemetry.properties,completionWithToolsCallId:I.callId,resultType:c.resultType,toolCallId:l,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id,isCustomAgent:n.isCustomAgent?"true":"false"},restrictedProperties:{...c.toolTelemetry.restrictedProperties,arguments:n.arguments,result:c.textResultForLlm,toolName:n.toolName,error:c.error,customAgent:n.customAgentInfo?JSON.stringify({repoOwner:n.customAgentInfo.repoOwner,repoName:n.customAgentInfo.repoName,displayName:n.customAgentInfo.displayName,mcpServerNames:n.customAgentInfo.mcpServerNames}):void 0},metrics:{...c.toolTelemetry.metrics,durationMs:I.durationMs,customAgentMcpServerCount:n.customAgentInfo?.mcpServerCount}}};await this.runtimeContext.callback?.progress(r)}}};var BB=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var A_I=void 0,r7=class{constructor(e,I=A_I){this.runtimeContext=e;this.agentId=I;this.gitHandlers={silent:new No(new dW,this.runtimeContext.exec),logging:new No(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,I,l,n,c,r,s,a=new BB,o){let G=async(m,h,u)=>{let Z={role:"user",content:m};return await this.runtimeContext.callback?.progress({kind:"message",turn:0,callId:this.agentId,message:Z}),await this.runCompletionWithTools(e,I,[...h??[],Z],r,s,c,{executeToolsInParallel:hl(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:u},o,a)},i=n,d=l??[],b;for(;i;){let m=await G(i,d,b);b=m.finalTurnCount,d=m.messages,i=await o?.onResult(m.postCompletionWithToolsCommitHash)}for(let m of r)if(m.shutdown){let h=await m.shutdown();h&&await this.runtimeContext.callback?.progress(h)}return{finalTurnCount:b||0,messages:d}}async runCompletionWithTools(e,I,l,n,c,r,s,a,o=new BB){let G=this.runtimeContext.callback?new c7(this.runtimeContext,"sweagent-capi",n):void 0,i=this.gitHandlers.logging,d=await i.getCurrentCommitHash(e),b=l.filter(y=>y.role==="user").at(-1),m=this.createCompletionWithToolsProcessors(e,d,n,c,o,r,a,b),h=this.runtimeContext.client.getCompletionWithTools(I,l,n,{...s,callId:this.agentId,processors:m}),u=0,Z=[...l],N=[];for await(let y of h){if(hl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let F=await this.runtimeContext.callback?.progress(y,{accepts_user_messages:o.canProcessUserMessages()});o.handleCallbackResponse(F)}else await this.runtimeContext.callback?.progress(y);G&&await G.ingestEvent(y),(y.kind==="message"||y.kind==="response")&&(y.kind==="message"&&Z.push(y.message),y.kind==="response"&&N.push(y.response),u=Math.max(u,y.turn??0))}let g=await i.getCurrentCommitHash(e);return{finalTurnCount:u,messages:Z,resultMessages:N,preCompletionWithToolsCommitHash:d,postCompletionWithToolsCommitHash:g}}createCompletionWithToolsProcessors(e,I,l,n,c,r,s,a){let o=new e7(this.runtimeContext.logger,this.runtimeContext.settings,l.find(b=>b.name==="github-mcp-server-get_file_contents")),G=new t7(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,I,r),i=new ov(a,this.runtimeContext.logger),d=[G,o,i];return hl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&d.push(c),d.push(n),{preRequest:d.filter(b=>b!==void 0),preToolsExecution:[s].filter(b=>b!==void 0),postToolExecution:[o,s].filter(b=>b!==void 0),onRequestError:[o,i].filter(b=>b!==void 0)}}};async function hZe(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 A8e=t=>hl(t,"copilot_swe_agent_search")||t2e(t,"SearchAgentExperiment")==="enabled",F8e="search";function pZe(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var Q_I=(t,e,I)=>`
|
|
1346
|
+
</reminder>`),l.trim()},_8={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."},Z8e=t=>`<reminder>You haven't committed any changes yet. Any code changes not meant to be temporary must be made in ${Rue(t)}. Commit changes by using the **report_progress** tool.</reminder>`;var nZe="/tmp/playwright-logs",P7I="0.0.40",cZe=[`@playwright/mcp@${P7I}`,"--viewport-size","1280, 720","--output-dir",nZe],nxl=[...cZe,"--isolated"];var rZe=class t extends Error{constructor(e){super(e),this.name="ImageSizeError",Object.setPrototypeOf(this,t.prototype)}},vB=2e3;async function _7I(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=`${U2e(l)}/${t}`;I.info(`Downloading image from ${c}`);try{let r=await fetch(c,{method:"GET",headers:n});if(I.info(`Response status: ${r.status} ${r.statusText}`),I.debug(`Download Response URL: ${r.url}`),!r.ok){I.info(`Failed to download image, status: ${r.status}, statusText: ${r.statusText}`);try{let d=await r.text();I.info(`Error response body: ${d}`)}catch(d){I.info(`Could not read error response body: ${d}`)}return{size:0}}let a=(await r.json()).url;if(!a)return I.error(`No asset URL found in response for image GUID: ${t}`),{size:0};let o=await fetch(a,{method:"GET"});if(!o.ok)return I.error(`Failed to download image: ${o.status} ${o.statusText}`),{size:0};let G=await o.arrayBuffer(),i=G.byteLength;return I.info(`Downloaded content size: ${Um(i)}`),{size:i,buffer:Buffer.from(G),mimeType:o.headers.get("content-type")||void 0}}catch(r){return I.error("Network error downloading image"),r instanceof Error&&(I.info(`Error message: ${r.message}`),I.info(`Error stack: ${r.stack}`)),{size:0}}}function sZe(t,e,I,l){let n=/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/g,c=/!\[.*?\]\((.*?)\)/g,r=[];return r.push(...W8e(t,e,n,I,l)),r.push(...W8e(t,e,c,I,l)),r}function W8e(t,e,I,l,n){let c=t.matchAll(I),r=[],s=/\/([a-f0-9-]+)$/;for(let a of c){let o=t_I(a[1],e),G=l_I(a[1],e,n);if(o||G){let i=a[1].match(s),d={url:a[1],guid:"",kind:G?"legacy_attachment":"attachment"};i&&i.length>1&&(d.guid=i[1]),r.push(d)}else if(l){let i={url:a[1],guid:"",kind:"committed_attachment"};r.push(i)}}return r}function $7I(t){return!t.startsWith("http://")&&!t.startsWith("https://")&&GZe(t)}function GZe(t){return/\.(png|jpe?g|gif|svg|webp|bmp|tiff?|ico|heic|avif)$/i.test(t)}function e_I(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 I_I(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,a=CB.dirname(s);c=CB.resolve("/",a,e).slice(1)}return`${I}/${l}/blob/${n}/${c}`}function t_I(t,e){return e?!!t.startsWith(`${e}/user-attachments/assets`):!1}function l_I(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 iZe(t){let{width:e,height:I}=wPe(t);if(e===void 0||I===void 0)throw new Error("Unable to determine image dimensions.");return{width:e,height:I}}async function $8(t,e,I,l,n,c){t.debug(`Checking if image is valid size and dimensions. Max size: ${I}, Max dimension: ${l}`);let{exceedsSizeLimit:r,exceedsDimensionLimit:s}=await JB(I,l,c);if(!s&&!r)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[a,o]=await r_I(t,c,l,I,n);if(!a){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:G}=await JB(I,l,a);if(G){e.imagesRemovedDueToDimensions++,t.debug("Image dimensions exceed the maximum dimensions limits, skipping");return}return e.imagesResized++,t.debug("Image resized successfully."),a}if(r){t.debug(`Image size ${Um(c.length)} is larger than the maximum size of ${Um(I)}, attempting to reduce image quality`);let a=await s_I(t,c,l,I,n);if(!a){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."),a}}async function JB(t,e,I){let l=await iZe(I),n=I.length;return!l.width||!l.height?{exceedsSizeLimit:n>t,exceedsDimensionLimit:!1}:{exceedsSizeLimit:await c_I(t,I),exceedsDimensionLimit:await n_I(e,I)}}async function n_I(t,e){let I=await iZe(e);return!I.width||!I.height?!1:I.width>t||I.height>t}async function c_I(t,e){return e.length>t}async function r_I(t,e,I,l,n){try{if(!N8e(t,n))return[void 0,"unsupported_mime_type"];let c=await iZe(e);if(!c.width||!c.height)return t.error("Failed to determine size of uploaded image"),[void 0,"determine_dimensions_failed"];let r=async(u,Z)=>{let N=(0,oZe.default)(e).resize(u,Z,{fit:"inside",withoutEnlargement:!0});return aZe(t,await N.toBuffer(),void 0,n)},s=Math.min(I,c.width),a=Math.min(I,c.height),o=await r(s,a);if(o&&o.length<=l)return[o,void 0];let G=Math.max(s,a),i=1,d=G-1,b,m=0,h=10;for(;i<=d&&m<h;){let u=Math.floor((i+d)/2),Z=await r(u,u);if(!Z)break;let{exceedsSizeLimit:N,exceedsDimensionLimit:g}=await JB(l,I,Z);!N&&!g?(b=Z,i=u+1):d=u-1,m++}return[b,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 s_I(t,e,I,l,n){try{let c=n==="image/png"?80:100,r=n==="image/png"?Math.floor(c*.4):20,s=await aZe(t,e,r,n);if(!s||s.length>l)return;let a=r,o=c,G,i=0,d=10,b=a,m=o-1;for(;b<=m&&i<d;){let h=Math.floor((b+m)/2),u=await aZe(t,e,h,n);if(!u)return G;let{exceedsSizeLimit:Z,exceedsDimensionLimit:N}=await JB(l,I,u);!Z&&!N?(G=u,b=h+1):m=h-1,i++}return G}catch(c){t.error(`Failed to reduce image quality: ${c instanceof Error?c.message:String(c)}`);return}}async function aZe(t,e,I,l){let n=(0,oZe.default)(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 LB=class{imagesRemovedDueToSize=0;imagesRemovedDueToDimensions=0;imagesResized=0;imagesWithLoweredQuality=0;imagesFailedToResize=0;imagesFailedToReduceQuality=0;base64ImagesSize=[];resizedBase64ImagesSize=[];extractedImagesSize=[];imagesResolvedFromGitHubMCPSize=[];resizeErrorsUnsupportedMimeType=0;resizeErrorsUnknown=0};function a_I(t,e,I,l){if(e<=0)return[];let n=[];for(let c of t){if(c.role!=="user"||n.length>=e)continue;let r=typeof c.content=="string"?c.content:JSON.stringify(c.content),s=e_I(r);if(s)for(let a in s){if(n.length>=e)break;let o=s[a].contents,G=sZe(o,I,!0,l);for(let i of G){if(n.length>=e)break;let d=i.url,b="",m=!1;if(i.kind==="attachment"||i.kind==="legacy_attachment"?n.push(i):$7I(d)?(m=!0,b=I_I(s[a],d,I),n.push({url:b,guid:i.guid,kind:"committed_attachment"})):GZe(d)&&d.startsWith(I)&&(m=!0,n.push({...i,kind:"committed_attachment"})),m){let h=n[n.length-1],u=new RegExp(`^${I}/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$`),Z=h.url.match(u);if(l.info(`Blob match for ${h.url}: ${JSON.stringify(Z)}`),Z&&Z.length===5){let[,N,g,y,F]=Z;h.owner=N,h.repo=g,h.branch=y,h.path=F,l.info(`Repository metadata extracted: owner=${N}, repo=${g}, branch=${y}, path=${F}`)}else l.info(`Failed to extract repository metadata from URL: ${h.url}`)}}}}return n}function o_I(t,e){let I=e.flatMap(n=>n0(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 e7=class{async resolveRepositoryImages(e,I,l,n,c,r){if(I<=0)return[];let s=a_I(e,I,l,n);this.logger.debug(`Found ${s.length} repository image URLs to process`);let a=o_I(s,e),o=await this.processImageReferences(a,c,r);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",turn:e.turn,callId:e.callId,message:i};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,r=0,s=[],a=new LB,o=new Map;for(let i of e.messages)if(i.role=="user")if(typeof i.content=="string"){let d=sZe(i.content,this.gitHubServerUrl,!1,this.logger).filter(m=>!this.processedImageUrls.has(m.url)),b=await this.processImageReferences(d,c,a);s.push(...b.addedImages)}else{let d=[];for(let[b,m]of i.content.entries()){if(m.type==="text"){let h=sZe(m.text,this.gitHubServerUrl,!1,this.logger).filter(Z=>!this.processedImageUrls.has(Z.url)),u=await this.processImageReferences(h,c,a);s.push(...u.addedImages)}else if(m.type==="image_url"){if(m.image_url.url.startsWith("data:")){let[h,u]=await this.extractAndUploadImageData(m,c,a);if(h===""){this.logger.debug("Skipping image upload for empty image data");continue}if(s.push(h),b>=1&&d.length>0){let Z=d.at(-1);Z&&Z.type==="text"&&Z.text&&Z.text.includes("screenshot")&&o.set(h,u8e(h))}d.pop();continue}r++}d.push(m)}i.content=d}for(this.logger.debug(`Found ${s.length} image urls in the messages`),this.logger.debug(`Allowed number of images: ${n}`);r<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 d=`Here is the image url: ${i}`;o.has(i)&&(d=o.get(i)||d),this.logger.debug(`Adding image url: ${i}`),l.push({role:"user",content:[{type:"text",text:d},{type:"image_url",image_url:{url:i}}]}),r++}if(this.settings.featureFlags?.copilot_swe_agent_resolve_repo_images&&(this.logger.debug("Resolving repository images..."),r<n)){let i=await this.resolveRepositoryImages(e.messages,n-r,this.settings.github?.serverUrl||"",this.logger,c,a);this.logger.debug(`Resolved ${i.length} repository image URLs`);for(let d of i){if(r>=n)break;if(this.processedImageUrls.has(d)){this.logger.debug(`Skipping already processed repository image url: ${d}`);continue}l.push({role:"user",content:[{type:"text",text:"Here is the image url:"},{type:"image_url",image_url:{url:d}}]}),this.processedImageUrls.add(d),r++}}let G={imagesExtractedCount:a.extractedImagesSize.length,base64ImagesCount:a.base64ImagesSize.length,imagesRemovedDueToSize:a.imagesRemovedDueToSize,imagesRemovedDueToDimensions:a.imagesRemovedDueToDimensions,imagesResized:a.imagesResized,imagesResolvedFromGitHubMCPCount:a.imagesResolvedFromGitHubMCPSize.length};for(let i=0;i<a.base64ImagesSize.length;i++)G[`base64ImageSize_${i}`]=a.base64ImagesSize[i];for(let i=0;i<a.resizedBase64ImagesSize.length;i++)G[`resizedBase64ImageSize_${i}`]=a.resizedBase64ImagesSize[i];for(let i=0;i<a.extractedImagesSize.length;i++)G[`extractedImageSize_${i}`]=a.extractedImagesSize[i];for(let i=0;i<a.imagesResolvedFromGitHubMCPSize.length;i++)G[`imagesResolvedFromGitHubMCPSize_${i}`]=a.imagesResolvedFromGitHubMCPSize[i];l.length>0&&this.logger.debug(`Using ${l.length} image messages`);for(let i of l)yield{kind:"message",turn:e.turn,callId:e.callId,message:i},e.messages.push(i);G.allImagesSendToLlm=e.messages.filter(n0).length,yield{kind:"image_processing",turn:e.turn,imageProcessingMetrics:G},e.messages.some(i=>n0(i))&&(e.additionalRequestHeaders["Copilot-Vision-Request"]="true")}async extractAndUploadImageData(e,I,l){let n=IC(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 r=c[1];if(!N8e(this.logger,r))return[""];let s=c[2];if(s.length===0)return this.logger.debug("Empty base64 image data, skipping"),[""];let a=Buffer.from(s,"base64");if(l.base64ImagesSize.push(a.length),a=await $8(this.logger,l,I,vB,r,a),l.resizedBase64ImagesSize.push(a?.length??-1),!a)return["",new rZe(`Image size exceeds maximum size of ${Um(I)}`)];s=a.toString("base64");try{let o=await this.uploadBase64ImageData(s,r,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 G=o instanceof Error?o.message:String(o);return this.logger.debug(`Error during image upload: ${G}`),[""]}}async uploadBase64ImageData(e,I,l){try{let n=z2e(this.settings),c=I.split("/").at(1),r=`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 a=this.settings.github?.repo?.id;if(!a)return this.logger.error("GitHub repository ID is not configured, cannot upload image"),null;let o=`${n}?name=${encodeURIComponent(r)}&content_type=${encodeURIComponent(I)}&repository_id=${a}`;this.logger.debug(`Uploading image data (${Um(s.length)}) to ${n} with name ${encodeURIComponent(r)} and content type ${encodeURIComponent(I)}`);let G={"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:G,body:s}).catch(b=>{throw b instanceof Error?(this.logger.error(`Failed to upload image: ${b.message}`),b.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):b.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(b.message.includes("request entity too large")||b.message.includes("payload too large"))&&this.logger.error("Request payload too large. Try reducing the image size.")):typeof b=="object"&&b!==null&&"code"in b&&"message"in b?(this.logger.error(`Failed to upload image: ${b.message}`),b.code==="ECONNREFUSED"?this.logger.error("Connection refused. The server might be down or blocked."):b.code==="ETIMEDOUT"?this.logger.error("Connection timed out. Check network conditions or server load."):(b.message.includes("request entity too large")||b.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(b)}`),this.logger.debug(`Complete error details: ${JSON.stringify({code:b?.code,message:b?.message,stack:b?.stack,name:b?.name,cause:b?.cause},null,2)}`),b});if(!i.ok){let b=await i.text().catch(()=>"Unable to read error response");return this.logger.error(`Failed to upload image: ${i.status} ${i.statusText} - ${b}`),null}let d=await i.json();return this.logger.debug(`Upload result: ${JSON.stringify(d,null,2)}`),d.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},{toolCallId:crypto.randomUUID(),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:r,attachment:s}of c)if(this.logger.debug(`Processing attachment for ${r.url}, has buffer: ${!!s.buffer}, buffer size: ${s.buffer?.length||0}`),s.buffer)if(I.extractedImagesSize.push(s.buffer.length),hl(this.settings,"copilot_swe_agent_resize_image_references")){if(!await $8(this.logger,I,l,vB,s.mimeType,s.buffer)){this.logger.info("Unable to resize image to be within limits, skipping");continue}n.push(r.url)}else{let a=await JB(l,vB,s.buffer);if(this.logger.debug(`Image size check for ${r.url}: size=${s.buffer.length}, maxSize=${l}, exceedsSize=${a.exceedsSizeLimit}, exceedsDimensions=${a.exceedsDimensionLimit}`),a.exceedsSizeLimit?(I.imagesRemovedDueToSize++,this.logger.debug(`Image ${r.url} removed due to size (${s.buffer.length} > ${l})`)):a.exceedsDimensionLimit&&(I.imagesRemovedDueToDimensions++,this.logger.debug(`Image ${r.url} removed due to dimensions`)),a.exceedsSizeLimit||a.exceedsDimensionLimit){this.processedImageUrls.add(r.url),this.logger.info(`Image has been removed from the request due to size constraints. Please resize images to be smaller than ${Um(l)}.`);continue}n.push(r.url),this.logger.debug(`Image ${r.url} passed size checks and added to results`)}else this.processedImageUrls.add(r.url),this.logger.debug(`Skipping image ${r.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 a=await this.getRepositoryImageViaTools(s);return a?.buffer?(this.logger.debug(`Successfully fetched repository image buffer, size: ${a.buffer.length} bytes`),l.imagesResolvedFromGitHubMCPSize.push(a.buffer.length)):this.logger.debug("Failed to fetch repository image buffer"),{imgRef:s,attachment:{size:a?.buffer?.length||0,mimeType:a?.mimeType||"",buffer:a?.buffer||null}}}else return this.logger.debug(`Non-repository image, using getAttachmentFromGuid for: ${s.url}`),{imgRef:s,attachment:await _7I(s.guid,IC(this.settings),this.logger,this.settings)}}),r=await this.getImgRefsSmallerThanMaxSize(c,l,I);return this.logger.debug(`Processed image references, found ${r.length} attachments smaller than max size of ${Um(I)}`),{addedImages:r}}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(G_I(n,l));if(c.length===0){let r=await b_I(e.toolCall,this.logger);r&&c.push(r)}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*G_I(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 i_I="playwright-browser_take_screenshot";function d_I(t){return typeof t=="object"&&t!==null&&typeof t.filename=="string"}async function b_I(t,e){if(t.function.name!==i_I)return;e.debug("Adding images using Playwright params fallback strategy");let I=JSON.parse(t.function.arguments);if(d_I(I)){let l=CB.isAbsolute(I.filename)?I.filename:CB.join(nZe,I.filename);e.debug(`Image from Playwright params: ${I.filename}. Updated to ${l}.`);let n=await h_I(l,e);if(n){let c=n.buffer.toString("base64");return{url:`data:${n.mimeType};base64,${c}`,isScreenshot:!0}}}}function m_I(t){switch(CB.extname(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return null}}function N8e(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 h_I(t,e){try{if(!GZe(t))return e.debug(`Image ${t} does not have a valid image extension, skipping read`),null;let I=m_I(t);return I?{buffer:await q7I.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}}var ov=class t{static DEFAULT_TOKEN_LIMIT=128e3;static DEFAULT_TOKEN_LIMIT_BUFFER=0;static MAX_TOKEN_LIMIT_BUFFER=.5;latestUserPromptMessage;logger;modelToTokenLimit;constructor(e,I){this.latestUserPromptMessage=e,this.logger=I,this.modelToTokenLimit=new Map}toJSON(){return"BasicTruncator"}async*preRequest(e){this.initializeStateForModelOnFirstRequest(e);let I=this.modelToTokenLimit.get(e.modelInfo.name),l=I?.tokenLimit??t.DEFAULT_TOKEN_LIMIT;e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong&&this.throwIfOverTokenLimitOnFirstTurn(e,l);let n=I?.tokenLimitBuffer??t.DEFAULT_TOKEN_LIMIT_BUFFER,c=l*(1-n),r=this.latestUserPromptMessage?nze(this.latestUserPromptMessage,e.messages):-1,s=[()=>Z_I(e.messages,e.toolDefinitions,e.modelInfo.name,c),r===-1?void 0:()=>W_I(e.messages,e.toolDefinitions,e.modelInfo.name,c,r)].filter(G=>G!==void 0),a=0,o;for(;(!o||o.postTruncationTokensInMessages>c)&&a<s.length;){let G=s[a]();o=u_I(o,G),a++}return o=o??N_I(e.messages,e.toolDefinitions,e.modelInfo.name,c),o.tokensRemovedDuringTruncation>0&&this.logger.debug(`BasicTruncator truncated: ${JSON.stringify(o)}`),yield{kind:"history_truncated",turn:e.turn,performedBy:"BasicTruncator",truncateResult:o},o}async preErrorThrow(){}async onRequestError(e){let I=this.modelToTokenLimit.get(e.modelInfo.name);if(I===void 0){this.logger.warning("Unable to determine if error relates to token limits due to missing information.");return}let{tokenLimit:l,tokenLimitBuffer:n}=I,c=p_I(e.error,l);if(c!==void 0){if(c<l)this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:c,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER}),this.logger.debug(`Adjusted model token limit to ${c}`);else{let r=Math.min(n+t.MAX_TOKEN_LIMIT_BUFFER/e.maxRetries,t.MAX_TOKEN_LIMIT_BUFFER);this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:l,tokenLimitBuffer:r}),this.logger.debug(`Adjusted model token limit to ${l}, token limit retry buffer to ${r}`)}return{retryAfter:1}}}getTokenLimitForModel(e){let I=this.modelToTokenLimit.get(e),l=I?I.tokenLimit*(1-I.tokenLimitBuffer):void 0;return{tokenLimit:I?.tokenLimit,tokenLimitBuffer:I?.tokenLimitBuffer,effectiveTokenLimit:l}}initializeStateForModelOnFirstRequest(e){e.turn===0&&e.retry===0&&this.modelToTokenLimit.set(e.modelInfo.name,{tokenLimit:e.modelInfo.capabilities?.limits?.max_prompt_tokens||e.modelInfo.capabilities?.limits?.max_context_window_tokens||t.DEFAULT_TOKEN_LIMIT,tokenLimitBuffer:t.DEFAULT_TOKEN_LIMIT_BUFFER})}throwIfOverTokenLimitOnFirstTurn(e,I){if(e.turn===0){let l=d2e(e.messages,e.modelInfo.name),n=b2e(e.toolDefinitions,e.modelInfo.name);if(l+n>I){if(e.getCompletionWithToolsOptions?.failIfInitialInputsTooLong)throw new Error(`Initial inputs exceed the model token limit of ${I} tokens.`);this.logger.warning(`Initial inputs exceed the model token limit of ${I} tokens. The model may not be able to process the inputs correctly.`)}}}};function p_I(t,e){if(t&&typeof t=="object"){let I="message"in t&&typeof t.message=="string"?t.message.match(/prompt token count of (\d+) exceeds the limit of (\d+)/):null;if(I){let r=parseInt(I[2],10);return isNaN(r)?e:r}if("code"in t&&t.code==="model_max_prompt_tokens_exceeded")return e;let n=[JSON.stringify(t)];t instanceof Error&&(n.push(t.message),t.cause instanceof Error?n.push(t.cause.message):t.cause&&n.push(JSON.stringify(t.cause)));let c="Input length and `max_tokens` exceed context limit";if(n.some(r=>r.includes(c)))return e}}function u_I(t,e){return t?{preTruncationMessagesLength:t.preTruncationMessagesLength,preTruncationTokensInMessages:t.preTruncationTokensInMessages,tokensRemovedDuringTruncation:t.tokensRemovedDuringTruncation+e.tokensRemovedDuringTruncation,messagesRemovedDuringTruncation:t.messagesRemovedDuringTruncation+e.messagesRemovedDuringTruncation,tokenLimit:t.tokenLimit,postTruncationMessagesLength:e.postTruncationMessagesLength,postTruncationTokensInMessages:e.postTruncationTokensInMessages}:e}var Y8e=.95;function Z_I(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 r=t.map(b=>zF(b,I)),s=Td(JSON.stringify(e),I),a=l*Y8e,o=r.reduce((b,m)=>b+m,0)+s;if(o<=a)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let G=new Set,i=0,d=Math.min(n??t.length,t.length);for(let b=0;b<d;b++){let m=t[b];if(m.role!=="system"&&m.role!=="tool"&&m.role!=="user"){if(m.role==="assistant"){let h=m.tool_calls||[],u=h.filter(AG).filter(y=>y.function.name===sJ),Z=h.filter(AG).filter(y=>y.function.name!==sJ),N=u.length===0,g=new Set(Z.map(y=>y.id));if(Z.length>0&&(m.tool_calls=u,r[b]=zF(m,I)),N&&(G.add(b),i+=r[b]),g.size>0)for(let y=b+1;y<t.length;y++){let F=t[y];if(F.role==="tool"&&g.has(F.tool_call_id)&&(G.add(y),i+=r[y],g.delete(F.tool_call_id),g.size===0))break}}if(o-i<a)break}}for(let b=t.length-1;b>=0;b--)G.has(b)&&t.splice(b,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function W_I(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 r=t.map(b=>zF(b,I)),s=Td(JSON.stringify(e),I),a=l*Y8e,o=r.reduce((b,m)=>b+m,0)+s;if(o<=a)return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o,postTruncationMessagesLength:c,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let G=new Set,i=0,d=Math.min(n??t.length,t.length);for(let b=0;b<d;b++){let m=t[b];if(m.role!=="system"&&m.role!=="tool"){if(m.role==="user")G.add(b),i+=r[b];else if(m.role==="assistant"){let h=m.tool_calls||[],u=new Set(h.map(Z=>Z.id));if(G.add(b),i+=r[b],u.size>0)for(let Z=b+1;Z<t.length;Z++){let N=t[Z];if(N.role==="tool"&&u.has(N.tool_call_id)&&(G.add(Z),i+=r[Z],u.delete(N.tool_call_id),u.size===0))break}}if(o-i<a)break}}for(let b=t.length-1;b>=0;b--)G.has(b)&&t.splice(b,1);return{tokenLimit:l,preTruncationTokensInMessages:o,preTruncationMessagesLength:c,postTruncationTokensInMessages:o-i,postTruncationMessagesLength:t.length,tokensRemovedDuringTruncation:i,messagesRemovedDuringTruncation:c-t.length}}function N_I(t,e,I,l){let n=t.length;if(n===0)return{tokenLimit:l,preTruncationTokensInMessages:0,preTruncationMessagesLength:n,postTruncationTokensInMessages:0,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0};let c=t.map(a=>zF(a,I)),r=Td(JSON.stringify(e),I),s=c.reduce((a,o)=>a+o,0)+r;return{tokenLimit:l,preTruncationTokensInMessages:s,preTruncationMessagesLength:n,postTruncationTokensInMessages:s,postTruncationMessagesLength:n,tokensRemovedDuringTruncation:0,messagesRemovedDuringTruncation:0}}var dW=class extends Mp{constructor(){super()}debug(e){}log(e){}info(e){}notice(e){}warning(e){}error(e){}startGroup(e,I){}endGroup(e){}};var V8e={fetch:{tools:[{toolName:"fetch"}]},time:{tools:[{toolName:"get_current_time"},{toolName:"convert_time"}]},sequentialthinking:{tools:[{toolName:"sequentialthinking"}]},"github-mcp-server":{tools:[{toolName:"get_code_scanning_alert"},{toolName:"get_commit"},{toolName:"get_file_contents"},{toolName:"get_issue"},{toolName:"get_issue_comments"},{toolName:"get_me"},{toolName:"get_copilot_space"},{toolName:"get_pull_request"},{toolName:"get_pull_request_comments"},{toolName:"get_pull_request_files"},{toolName:"get_pull_request_reviews"},{toolName:"get_pull_request_status"},{toolName:"get_secret_scanning_alert"},{toolName:"get_tag"},{toolName:"list_branches"},{toolName:"list_code_scanning_alerts"},{toolName:"list_commits"},{toolName:"list_issues"},{toolName:"list_pull_requests"},{toolName:"list_secret_scanning_alerts"},{toolName:"list_tags"},{toolName:"search_code"},{toolName:"search_issues"},{toolName:"search_repositories"},{toolName:"search_users"},{toolName:"get_job_logs"},{toolName:"get_workflow_run"},{toolName:"get_workflow_run_logs"},{toolName:"list_workflow_jobs"},{toolName:"list_workflow_runs"},{toolName:"list_workflow_run_artifacts"},{toolName:"list_workflows"},{toolName:"summarize_job_log_failures"}]},playwright:{tools:[{toolName:"browser_close"},{toolName:"browser_resize"},{toolName:"browser_console_messages"},{toolName:"browser_handle_dialog"},{toolName:"browser_file_upload"},{toolName:"browser_install"},{toolName:"browser_press_key"},{toolName:"browser_navigate"},{toolName:"browser_navigate_back"},{toolName:"browser_navigate_forward"},{toolName:"browser_network_requests"},{toolName:"browser_pdf_save"},{toolName:"browser_take_screenshot"},{toolName:"browser_snapshot"},{toolName:"browser_click"},{toolName:"browser_drag"},{toolName:"browser_hover"},{toolName:"browser_type"},{toolName:"browser_select_option"},{toolName:"browser_tab_list"},{toolName:"browser_tab_new"},{toolName:"browser_tab_select"},{toolName:"browser_tab_close"},{toolName:"browser_generate_playwright_test"},{toolName:"browser_wait_for"}]},primer:{tools:[{toolName:"init"},{toolName:"list_components"},{toolName:"get_component"},{toolName:"get_component_examples"},{toolName:"get_component_usage_guidelines"},{toolName:"get_component_accessibility_guidelines"},{toolName:"list_patterns"},{toolName:"get_pattern"},{toolName:"list_tokens"},{toolName:"get_color_usage"},{toolName:"get_typography_usage"},{toolName:"list_icons"},{toolName:"get_icon"},{toolName:"review_alt_text"}]},azure:"azure-mcp-server","azure-azmcp":"azure-mcp-server","azure-mcp-server-azmcp":"azure-mcp-server","azure-mcp-server":{tools:[{toolName:"aks"},{toolName:"appconfig"},{toolName:"azureterraformbestpractices"},{toolName:"bestpractices"},{toolName:"bicepschema"},{toolName:"cosmos"},{toolName:"datadog"},{toolName:"documentation"},{toolName:"extension_az"},{toolName:"extension_azd"},{toolName:"extension_azqr"},{toolName:"foundry"},{toolName:"grafana"},{toolName:"group"},{toolName:"keyvault"},{toolName:"kusto"},{toolName:"loadtesting"},{toolName:"marketplace"},{toolName:"monitor"},{toolName:"postgres"},{toolName:"redis"},{toolName:"role"},{toolName:"search"},{toolName:"servicebus"},{toolName:"sql"},{toolName:"storage"},{toolName:"subscription"},{toolName:"workbooks"}]}};function I7(t,e,I){let l=(I||V8e)[t.toLowerCase()],n=new Set;for(;typeof l=="string";){if(n.has(l))return!1;n.add(l),l=V8e[l]}if(!l)return!1;let c=e.toLowerCase();return l.tools.some(r=>r.toolName===c)}var Y_I="image";var V_I="resource",R_I=180*1e3,y_I={timeout:R_I};var dZe=class{constructor(e,I,l){this.settings=e;this.logger=I;this.cacheProviderTools=l}cachedTools=new Map;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 G=o.resource;G&&G.blob?c.push({type:V_I,data:G.blob,mimeType:G.mimeType||"application/octet-stream"}):G&&G.text&&(n+=G.text)}else o.type==="image"&&c.push({type:Y_I,data:o.data,mimeType:o.mimeType});let r=n;if(n==="")this.logger.debug("Tool invocation result is empty or undefined, skipping content filtering."),r=n;else try{let o=JSON.parse(n),G=xpe(o,I);r=JSON.stringify(G)}catch(o){this.logger.debug(`Unable to parse tool invocation as JSON. Treating it as a string for filtering: ${o}`),r=fpe(n,I)}this.logger.debug(`Tool invocation result: ${r}`);let s={},a=r?Dn(r,"output"):"";return e.isToolError?{textResultForLlm:r,resultType:"failure",error:r,sessionLog:a,toolTelemetry:s}:{textResultForLlm:r,binaryResultForLlm:c,resultType:"success",sessionLog:a,toolTelemetry:s}}async loadTools(e,I={requestRequired:!1}){let l=this.getProviderCacheKey(e),n=this.cachedTools.get(l),c=n??await this.loadToolsFromProvider(e);this.cacheProviderTools&&!n&&this.cachedTools.set(l,c);let r={};for(let[s,a]of Object.entries(c)){let o=a.filterMode||"hidden_characters";r[s]={name:a.name,namespacedName:a.namespacedName,title:a.title||a.name,description:a.description,input_schema:a.input_schema,callback:async G=>{let i=c[s].serverName,d=c[s].name,b=c[s].title;if(!I.requestRequired)return this.invokeTool(s,G,o);let m=await I.request({kind:"mcp",serverName:i,toolName:d,toolTitle:b,args:G,readOnly:!!a.readOnly});switch(m.kind){case"approved":return this.invokeTool(s,G,o);case"denied-by-rules":return kT(m.rules);case"denied-no-approval-rule-and-could-not-request-from-user":return xT;case"denied-interactively-by-user":return fT;default:bm(m,`Unhandled permission result kind: ${m}`)}},safeForTelemetry:a.safeForTelemetry}}return Object.values(r)}};var fB=class t extends dZe{toolIdToClientInfo=new Map;constructor(e,I,l=!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),r=await n.callTool({name:c,arguments:I},void 0,{...y_I,onprogress:s=>{this.logger.info(`Tool ${e} progress: ${JSON.stringify(s)}`)},resetTimeoutOnProgress:!0});if(!Array.isArray(r.content))throw new Error("Expected array of results");return{content:r.content,isToolError:r.error!==void 0&&r.error!==null||r.isError===!0}}getProviderCacheKey(e){return[e.clientName,...e.tools,JSON.stringify(e.filterMapping)].join("+")}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:I7(e.clientName,l.name),inputsNames:!1},this.logger.debug(`Adding tool: ${n}`);let r;e.filterMapping===void 0?r="hidden_characters":typeof e.filterMapping=="object"?r=e.filterMapping[l.name]||"hidden_characters":r=e.filterMapping,I[n]={serverName:e.clientName,name:n,namespacedName:`${e.clientName}/${l.name}`,title:l.title||l.annotations?.title||l.name,description:l.description||"",input_schema:l.inputSchema,readOnly:l.annotations?.readOnlyHint,safeForTelemetry:c,filterMode:r}}return I}static getToolIdFromClientAndToolName(e,I){return`${e}-${I}`}static getToolNameFromIdAndClientName(e,I){return e.substring(I.length+1)}};var t7=class{settings;logger;gitHandler;location;commitPriorToCompletionWithTools;jitInstructions;emittedJitInstructions;constructor(e,I,l,n,c,r){this.settings=e,this.logger=I,this.gitHandler=l,this.location=n,this.commitPriorToCompletionWithTools=c,this.jitInstructions=r||{},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(s){this.logger.error(`Failed to get changed paths, err: ${s}`),I=1}return I},n=[];for(let[s,a]of Object.entries(this.jitInstructions)){let o=l2e(this.settings,a.percentRemainingOfTimeout);o.isWithin&&n.push({config:a,withinMs:o.withinMs})}let c=n.map(({config:s,withinMs:a})=>{let o=typeof s.instruction=="function"?s.instruction(this.location):s.instruction;return{config:s,withinMs:a,instruction:o}}).filter(({instruction:s})=>!this.emittedJitInstructions.has(s)),r;for(let{config:s,withinMs:a,instruction:o}of c)(s.whenNoPathsChanged?await l()===0:!0)&&(!r||a<r.withinMs)&&(r={withinMs:a,instruction:o});if(r){this.logger.debug(`Adding JIT instructions to the history: ${r.instruction}`),this.emittedJitInstructions.add(r.instruction);let s={role:"user",content:r.instruction};e.messages.push(s),yield{kind:"message",turn:e.turn,callId:e.callId,message:s,source:"jit-instruction"}}}}},mZe={remindWhereToDoWork:{instruction:Z8e,percentRemainingOfTimeout:1/2,whenNoPathsChanged:!0},completeAsSoonAsPossible:{instruction:_8.completeAsSoonAsPossible,percentRemainingOfTimeout:1/6},commitNow:{instruction:_8.commitNow,percentRemainingOfTimeout:2/15},finalAnswerNeeded:{instruction:_8.finalAnswerNeeded,percentRemainingOfTimeout:1/10}};function l7(t){if(!t)return cze;let[e,...I]=t?.split(":")??[t,void 0],l=I.join(":")||void 0;return{agent:e||void 0,model:l||void 0}}var kB=class{logger;forcePremiumRequest=!1;constructor(e){this.logger=e}async*preRequest(e){e.turn===0||this.forcePremiumRequest?(e.additionalRequestHeaders["X-Initiator"]="user",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'user'")):(e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("InitiatorHeaderProcessor: Setting X-Initiator to 'agent'")),this.resetPremiumRequest(),yield*[]}setForcePremiumRequest(){this.forcePremiumRequest=!0}toJSON(){return JSON.stringify({type:"InitiatorHeaderProcessor"})}resetPremiumRequest(){this.forcePremiumRequest=!1}},xB=class{logger;constructor(e){this.logger=e}async*preRequest(e){e.additionalRequestHeaders["X-Initiator"]="agent",this.logger.debug("FreeRequestProcessor: Setting X-Initiator to 'agent'"),yield*[]}setForcePremiumRequest(){}toJSON(){return JSON.stringify({type:"FreeRequestProcessor"})}};function n7(t){return t.kind==="message"&&t.message.role==="assistant"}function R8e(t){return t.kind==="message"&&t.message.role==="user"}function y8e(t){return t.kind==="message"&&t.message.role==="assistant"&&!!t.message.tool_calls}function g8e(t){return t.kind==="message"&&t.message.role==="tool"}function g_I(t,e){return t.toolCalls.find(I=>I.toolCallId===e)}function F_I(t,e,I){let l=I.function.name;try{let n=JSON.parse(I.function.arguments||"{}"),c=e.find(o=>o.name===l),r=c?.safeForTelemetry||{name:!1,inputsNames:!1},s=bX(c),a;if(s&&t.customAgents&&t.settings){let o=t.customAgents.find(G=>G.name===l);if(o){let G=t.settings.github?.repo?.name??"",i=G.split("/"),d=i.length===2?i[0]:"",b=i.length===2?i[1]:G,m=o.mcpServers?Object.keys(o.mcpServers).join(","):"",h=o.mcpServers?Object.keys(o.mcpServers).length:0;a={repoOwner:d,repoName:b,displayName:o.name,mcpServerNames:m,mcpServerCount:h}}}return{toolCallId:I.id,toolName:l,arguments:I.function.arguments,safeForTelemetryToolName:r===!0||r.name?l:XR(l),safeForTelemetryArguments:r===!0||r.inputsNames?Ize(n):"",isCustomAgent:s,customAgentInfo:a}}catch{return{toolCallId:I.id,toolName:l,arguments:I.function.arguments,safeForTelemetryToolName:XR(l),safeForTelemetryArguments:"",isCustomAgent:!1,customAgentInfo:void 0}}}var c7=class{constructor(e,I,l){this.runtimeContext=e;this.forAgent=I;this.toolsInUse=l}turnDataCache=new Map;emittedTurns=new Set;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:Z$(this.runtimeContext.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,callId:e.callId,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:tze(e.requestMessages)},e.kind==="model_call_success"&&(l={...l,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):R8e(e)&&e.source==="jit-instruction"?l={...l,jitInstructionsAdded:(l?.jitInstructionsAdded??0)+1}:n7(e)&&e.message.tool_calls?l={...l,toolCalls:l.toolCalls.concat(e.message.tool_calls.map(n=>({...F_I(this.runtimeContext,this.toolsInUse,n)})))}:g8e(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:{callId:I.callId,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:Z$(this.runtimeContext.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.runtimeContext.callback?.progress(l)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,I){let l=I.toolCallId,n=g_I(e,l);if(n){let c=I.toolResult,r={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...c.toolTelemetry.properties,completionWithToolsCallId:I.callId,resultType:c.resultType,toolCallId:l,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id,isCustomAgent:n.isCustomAgent?"true":"false"},restrictedProperties:{...c.toolTelemetry.restrictedProperties,arguments:n.arguments,result:c.textResultForLlm,toolName:n.toolName,error:c.error,customAgent:n.customAgentInfo?JSON.stringify({repoOwner:n.customAgentInfo.repoOwner,repoName:n.customAgentInfo.repoName,displayName:n.customAgentInfo.displayName,mcpServerNames:n.customAgentInfo.mcpServerNames}):void 0},metrics:{...c.toolTelemetry.metrics,durationMs:I.durationMs,customAgentMcpServerCount:n.customAgentInfo?.mcpServerCount}}};await this.runtimeContext.callback?.progress(r)}}};var BB=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}};var A_I=void 0,r7=class{constructor(e,I=A_I){this.runtimeContext=e;this.agentId=I;this.gitHandlers={silent:new No(new dW,this.runtimeContext.exec),logging:new No(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,I,l,n,c,r,s,a=new BB,o){let G=async(m,h,u)=>{let Z={role:"user",content:m};return await this.runtimeContext.callback?.progress({kind:"message",turn:0,callId:this.agentId,message:Z}),await this.runCompletionWithTools(e,I,[...h??[],Z],r,s,c,{executeToolsInParallel:hl(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:u},o,a)},i=n,d=l??[],b;for(;i;){let m=await G(i,d,b);b=m.finalTurnCount,d=m.messages,i=await o?.onResult(m.postCompletionWithToolsCommitHash)}for(let m of r)if(m.shutdown){let h=await m.shutdown();h&&await this.runtimeContext.callback?.progress(h)}return{finalTurnCount:b||0,messages:d}}async runCompletionWithTools(e,I,l,n,c,r,s,a,o=new BB){let G=this.runtimeContext.callback?new c7(this.runtimeContext,"sweagent-capi",n):void 0,i=this.gitHandlers.logging,d=await i.getCurrentCommitHash(e),b=l.filter(y=>y.role==="user").at(-1),m=this.createCompletionWithToolsProcessors(e,d,n,c,o,r,a,b),h=this.runtimeContext.client.getCompletionWithTools(I,l,n,{...s,callId:this.agentId,processors:m}),u=0,Z=[...l],N=[];for await(let y of h){if(hl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")){let F=await this.runtimeContext.callback?.progress(y,{accepts_user_messages:o.canProcessUserMessages()});o.handleCallbackResponse(F)}else await this.runtimeContext.callback?.progress(y);G&&await G.ingestEvent(y),(y.kind==="message"||y.kind==="response")&&(y.kind==="message"&&Z.push(y.message),y.kind==="response"&&N.push(y.response),u=Math.max(u,y.turn??0))}let g=await i.getCurrentCommitHash(e);return{finalTurnCount:u,messages:Z,resultMessages:N,preCompletionWithToolsCommitHash:d,postCompletionWithToolsCommitHash:g}}createCompletionWithToolsProcessors(e,I,l,n,c,r,s,a){let o=new e7(this.runtimeContext.logger,this.runtimeContext.settings,l.find(b=>b.name==="github-mcp-server-get_file_contents")),G=new t7(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,I,r),i=new ov(a,this.runtimeContext.logger),d=[G,o,i];return hl(this.runtimeContext.settings,"copilot_swe_agent_progress_commands")&&d.push(c),d.push(n),{preRequest:d.filter(b=>b!==void 0),preToolsExecution:[s].filter(b=>b!==void 0),postToolExecution:[o,s].filter(b=>b!==void 0),onRequestError:[o,i].filter(b=>b!==void 0)}}};async function hZe(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 A8e=t=>hl(t,"copilot_swe_agent_search")||t2e(t,"SearchAgentExperiment")==="enabled",F8e="search";function pZe(t){return t!==null&&typeof t=="object"&&"question"in t&&"reason"in t&&"searchCommand"in t}var Q_I=(t,e,I)=>`
|
|
1347
1347
|
You are a question answering agent that is a component of GitHub Copilot coding agent. Your task is to take the given question
|
|
1348
1348
|
and answer it using the given facts.
|
|
1349
1349
|
|