@github/copilot 0.0.337 → 0.0.338-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -829,7 +829,7 @@ extensions:
829
829
  `);let a=I+r,s=iJe.join(n,"pr-diff-range.yml");return oJe.writeFileSync(s,a),l(`Wrote pr-diff-range extension pack to ${s}:
830
830
  ${a}`,8),n}c();import*as Jee from"os";import*as nZe from"fs";var lkl=.05,Xgt=1024*1024;function kgt(t){let e=Jee.platform(),l=Ikl(e,t)/(1024*1024),n=nkl(l,e),I=Math.floor(l-n);return t(`Using ${I} MB for CodeQL, out of ${l} MB total.`,8),I}function nkl(t,e){let l=1024*(e==="win32"?1.5:1),n=lkl*Math.max(t-8*1024,0);return l+n}function Ikl(t,e){let l=[Jee.totalmem()];return t==="linux"&&l.push(...["/sys/fs/cgroup/memory/memory.limit_in_bytes","/sys/fs/cgroup/memory.max"].map(I=>rkl(I,e)).filter(I=>I!==void 0).map(I=>I)),Math.min(...l)}function rkl(t,e){if(!nZe.existsSync(t)){e(`While resolving RAM, did not find a cgroup memory limit at ${t}.`,8);return}let l=Number(nZe.readFileSync(t,"utf8"));if(!Number.isInteger(l)){e(`While resolving RAM, ignored the file ${t} that may contain a cgroup memory limit as this file did not contain an integer.`,8);return}let n=`${Math.floor(l/(1024*1024))} MiB`;if(l>Jee.totalmem()){e(`While resolving RAM, ignored the file ${t} that may contain a cgroup memory limit as its contents ${n} were greater than the total amount of system memory.`,8);return}if(l<Xgt){e(`While resolving RAM, ignored a cgroup limit of ${n} in ${t} as it was below ${Xgt/(1024*1024)} MiB.`,8);return}return e(`While resolving RAM, found a cgroup limit of ${n} in ${t}.`,8),l}c();import*as a_ from"fs";import*as IZe from"os";function Lgt(t){let e=[IZe.cpus().length];return IZe.platform()==="linux"&&(e.push(...["/sys/fs/cgroup/cpuset.cpus.effective","/sys/fs/cgroup/cpuset.cpus"].map(n=>skl(n,t)).filter(n=>n!==void 0&&n>0).map(n=>n)),e.push(...["/sys/fs/cgroup/cpu.max"].map(n=>akl(n,t)).filter(n=>n!==void 0&&n>0).map(n=>n))),Math.min(...e)}function akl(t,e){if(!a_.existsSync(t)){e(`While resolving threads, did not find a cgroup CPU file at ${t}.`,8);return}let n=a_.readFileSync(t,"utf-8").split(" ");if(n.length!==2){e(`While resolving threads, did not use cgroup CPU file at ${t} because it contained ${n.length} value(s) rather than the two expected.`,8);return}let I=n[0];if(I==="max")return;let r=n[1],a=Math.floor(parseInt(I)/parseInt(r));return e(`While resolving threads, found a cgroup CPU file with ${a} CPUs in ${t}.`,8),a}function skl(t,e){if(!a_.existsSync(t)){e(`While resolving threads, did not find a cgroup CPUs file at ${t}.`,8);return}let l=0,n=a_.readFileSync(t,"utf-8").trim();if(n.length!==0){for(let I of n.split(","))if(!I.includes("-"))++l;else{let r=parseInt(I.split("-")[0]),a=parseInt(I.split("-")[1]);l+=a-r+1}return e(`While resolving threads, found a cgroup CPUs file with ${l} CPUs in ${t}.`,8),l}}var s_=class t{constructor(e,l,n,I,r){this.executablePath=e;this.databaseDir=l;this.settings=n;this.sourceRoot=I;this.progressLogger=r;this.ram=this.resolveRam(),this.threads=this.resolveThreads()}static DIFF_INFORMED_FEATURE_FLAG_NAME="copilot_swe_agent_codeql_diff_informed";ram;repositorySizeCache=new Map;threads;async createDatabase(e,l){let n=`${this.databaseDir}/${l}`,I=this.getBuildMode(l);return await this.execCommand(e,`database create ${this.ram} ${this.threads} --no-sublanguage-file-coverage --no-calculate-baseline --overwrite --language ${l} --build-mode ${I} --source-root ${this.sourceRoot} ${n}`),n}static AUTOBUILD_ONLY_LANGUAGES=["cpp","go","swift"];getBuildMode(e){return t.AUTOBUILD_ONLY_LANGUAGES.includes(e)?"autobuild":"none"}async analyzeDatabase(e,l,n){let I=[];if(Ii(this.settings,t.DIFF_INFORMED_FEATURE_FLAG_NAME)){let d=o_.mkdtempSync(Bee.join(cJe.tmpdir(),"codeql-")),u=Hgt(n,d,this.progressLogger);this.progressLogger(`Created diff range data extension pack at ${u}`,8),I=["--additional-packs",u,"--extension-packs","codeql-action/pr-diff-range"]}let r=`${this.databaseDir}/${l}`,a=`${r}/results-${l}.json`;await o_.promises.rm(a,{force:!0}),this.progressLogger(`Analyzing database at ${r} for language ${l}`);let s=["database","analyze",this.ram,this.threads,"--format","sarifv2.1.0","--output",a,...I,r,`codeql/${l}-queries`];return await this.execCommand(e,s.join(" ")),new aAe(a,this.progressLogger.bind(this)).summarize(l,n)}async version(e){let l=await this.execCommand(e,"version --format json");try{return JSON.parse(l).version}catch{throw new Error(`Failed to parse CodeQL version output: ${l}`)}}async getRepositorySize(e){return this.repositorySizeCache.has(e)||this.repositorySizeCache.set(e,await this.computeRepositorySize(e)),this.repositorySizeCache.get(e)}async execCommand(e,l){return this.progressLogger(`Executing CodeQL command: ${l}`),new Promise((n,I)=>{rZe.exec(`${this.executablePath} ${l}`,{signal:e},(r,a,s)=>{let o=r?1:4;this.progressLogger(s,o,"CodeQL Output"),r?r.name=="AbortError"?I(r):I(new Error(`Error executing command: ${r} ${s}`)):n(a)})})}resolveRam(){try{return`--ram ${kgt(this.progressLogger)}`}catch(e){return this.progressLogger(`Failed to resolve RAM, not passing --ram flag to CodeQL: ${e}`,2),""}}resolveThreads(){try{return`--threads ${Lgt(this.progressLogger)}`}catch(e){return this.progressLogger(`Failed to resolve threads, not passing --threads flag to CodeQL: ${e}`,2),""}}getSccExecutablePath(){let e=Bee.dirname(this.executablePath),l;switch(cJe.platform()){case"win32":l=Bee.join(e,"tools/win64/scc.exe");break;case"darwin":l=Bee.join(e,"tools/osx64/scc");break;case"linux":l=Bee.join(e,"tools/linux64/scc");break;default:return}if(o_.existsSync(l))return l}async computeRepositorySize(e){let l=this.getSccExecutablePath();if(!l){this.progressLogger(`SCC executable not found for platform: ${cJe.platform()}`,2);return}let n=Lbt(e);if(!n){this.progressLogger(`No file extensions found for language: ${e}`,2);return}let I=["--exclude-dir",".git,.hg,.svn,target,build,dist","--format","json","--include-ext",n.join(","),"--no-complexity","--no-cocomo"],r=rZe.spawn(l,I,{cwd:this.sourceRoot}),a="",s="";r.stdout.on("data",d=>{a+=d}),r.stderr.on("data",d=>{s+=d});let o=await new Promise(d=>{r.on("close",d)});if(o!==0){this.progressLogger(`SCC failed with exit code ${o}: ${s}`,2);return}try{let u=JSON.parse(a).reduce((G,p)=>G+p.Bytes,0);return this.progressLogger(`SCC output for ${e}: ${u} bytes`,4),u}catch(d){this.progressLogger(`Failed to parse SCC output: ${d}`,2);return}}};var Bgt="codeql-bundle-linux64.tar.gz",ckl=new WM;async function dkl(t,e){let I=(await new ohe({auth:t}).rest.repos.getLatestRelease({owner:"github",repo:"codeql-action"})).data.assets.find(r=>r.name===Bgt);if(I)return e(`CodeQL asset ID: ${I.id}`),I.id;throw new Error("CodeQL asset not found")}async function ukl(t,e,l,n){let I=await fetch(`https://api.github.com/repos/github/codeql-action/releases/assets/${t}`,{headers:{Authorization:`token ${l}`,Accept:"application/octet-stream"},redirect:"follow"});if(!I.ok||!I.body)throw new Error(`Failed to download asset: ${I.statusText}`);let r=i_.join(e,Bgt),a=$Y.createWriteStream(r,{flags:"wx"});return await ikl(okl.fromWeb(I.body).pipe(a)),n(`CodeQL downloaded to ${r}`),r}async function mkl(t,e,l){await $Y.promises.mkdir(e,{recursive:!0});try{return await Yke({file:t,cwd:e}),l(`CodeQL unzipped to ${e}`),Ogt(e)}catch(n){throw ckl.error(`Error unzipping CodeQL: ${String(n)}`),n}}async function Gkl(t,e,l){let n=process.env.GITHUB_TOKEN||I3(l),I=await dkl(n,e),r=bkl(t);await $Y.promises.mkdir(r,{recursive:!0});let a=await ukl(I,r,n,e);return await mkl(a,t,e),await $Y.promises.rm(a),Sgt(t)}async function xgt(t,e,l,n){let I=pkl(t);await $Y.promises.mkdir(I,{recursive:!0});let r=await hkl(n);if(r)return new s_(r,I,l,e,n);let a=Sgt(t);if(await dJe(a))return n(`CodeQL already exists at ${a}`),new s_(a,I,l,e,n);try{let s=await Gkl(t,n,l);return new s_(s,I,l,e,n)}catch(s){throw n(`Error ensuring CodeQL: ${String(s)}`,1),s}}function bkl(t){return i_.join(t,"codeql-download")}function Sgt(t){return i_.join(Ogt(t),"codeql")}function Ogt(t){return i_.join(t,"codeql")}function pkl(t){return i_.join(t,"dbs")}async function hkl(t){if(!process.env.RUNNER_TOOL_CACHE)return;let e=aZe.findAllVersions("CodeQL");if(!e.length)return;let l=e[0],n=aZe.find("CodeQL",l,Jgt.arch());if(n){let I=i_.join(n,"codeql","codeql");if(t(`CodeQL directory found in toolcache at '${n}'.`),!await dJe(I)){let r;throw await dJe(n)?r=$Y.readdirSync(n):r=["path does not exist"],new Error(`CodeQL executable not found at '${I}'. Contents of toolcache: '${r.join(", ")}'.`)}return I}}async function dJe(t){try{return await $Y.promises.stat(t),!0}catch{return!1}}var sZe=class t{constructor(e,l,n,I,r){this.config=e;this.git=l;this.baseCommit=n;this.settings=I;this.logger=r}static DEFAULT_MAX_REPO_SIZE_BYTES=1e7;static DEFAULT_TIMEOUT_MS=180*1e3;static TOOL_NAME="codeql_checker";static CODEQL_CHECKER_ENABLED_FF="copilot_swe_agent_enable_security_tool";static CODEQL_CHECKER_DISABLED_FF="copilot_swe_agent_enable_security_tool_disabled";static isEnabled(e){return Ii(e,t.CODEQL_CHECKER_ENABLED_FF)&&!Ii(e,t.CODEQL_CHECKER_DISABLED_FF)}executor;async getCodeQLCheckerTool(){let e=await this.createCodeQLScratchDir(this.config.location);return this.executor=await xgt(e,this.config.location,this.settings,this.logProgress.bind(this)),{name:t.TOOL_NAME,description:`This is a security tool that discovers vulnerabilities in code using CodeQL. It must always be run when there are code changes.
831
831
  It is run after committing all changed code and before the final verification. Feedback from this tool must be incorporated into
832
- the change and then the tool must be re-run.`,input_schema:{type:"object",properties:{}},callback:this.callback.bind(this),safeForTelemetry:!0}}async callback(){let e={},l="unknown",n=Date.now();try{if(!this.executor)throw new Error("CodeQL Executor is not initialized.");let I=AbortSignal.timeout(this.settings.tools?.codeql?.timeout??t.DEFAULT_TIMEOUT_MS);I.throwIfAborted(),l=await this.executor.version(I),await this.git.stageChanges(this.config.location);let r=await this.git.getDiffRanges(this.config.location,this.baseCommit),a=kbt(r);a.length>0?this.logProgress(`Found ${a.join(", ")} languages to analyze.`):this.logProgress("No languages found to analyze.");let s=[],o=!0;for(let G of a){if(I.throwIfAborted(),!await this.shouldAnalyzeLanguage(this.executor,G)){e[G]={skipped:!0};continue}let p=Date.now();try{await this.executor.createDatabase(I,G),this.logProgress(`Created database for ${G}.`),e[G]={databaseCreationSuccess:!0,databaseCreationTimeMs:Date.now()-p}}catch(W){o=!1;let E=`Error creating database for ${G}: ${String(W)}`;this.logProgress(E,1),e[G]={databaseCreationError:W instanceof Error?W:new Error(String(W)),databaseCreationSuccess:!1,databaseCreationTimeMs:Date.now()-p};continue}I.throwIfAborted();let h=Date.now();try{let W=await this.executor.analyzeDatabase(I,G,r);s.push(W);let E=W.alerts.length;this.logProgress(`Completed analysis of ${G}. ${E} ${E===1?"alert":"alerts"} found.`),e[G]={...e[G],analysisSuccess:!0,analysisTimeMs:Date.now()-h,analysisRuleIds:W.alerts.flatMap(R=>R.ruleId?[R.ruleId]:[]),querySuite:`${G}-code-scanning`}}catch(W){o=!1;let E=`Error analyzing database for ${G}: ${String(W)}`;this.logProgress(E,1),e[G]={...e[G],analysisError:W instanceof Error?W:new Error(String(W)),analysisSuccess:!1,analysisTimeMs:Date.now()-h,analysisRuleIds:[]}}}let d=s.filter(G=>G.alerts.length>0).reduce((G,p)=>G+p.alerts.length,0),u=a.length===0?"No code changes detected for languages that CodeQL can analyze, so no analysis was performed.":`Analysis Result for '${a}'. Found ${d} alert(s): ${JSON.stringify(s,null,2)}`;return{resultType:o?"success":"failure",textResultForLlm:u,sessionLog:`Analysis completed successfully for '${a}'.`,toolTelemetry:{event:"tool_call_executed",properties:{"codeql.version":l},metrics:{"codeql.languages.count":a.length,"codeql.total.alerts":d,"codeql.duration.ms":Date.now()-n},restrictedProperties:{}}}}catch(I){let r=this.isAbortError(I)?`Operation cancelled due to timeout. Do not re-run the ${t.TOOL_NAME} tool because it will not complete successfully.`:`Error in CodeQL Checker: '${String(I)}'`;this.logProgress(r,1);let a={event:"tool_call_executed",properties:{"codeql.version":l,"codeql.aborted":this.isAbortError(I)?"true":"false"},metrics:{"codeql.languages.count":0,"codeql.total.alerts":0,"codeql.duration.ms":Date.now()-n},restrictedProperties:{"codeql.stack":I instanceof Error?I.stack??"":""}};return XN({telemetry:a},I,"codeql.error"),{resultType:"failure",textResultForLlm:r,sessionLog:r,toolTelemetry:a}}finally{let I=this.createTelemetryByLanguage(e,l);for(let r of I)this.config.callback?.progress({kind:"telemetry",telemetry:r})}}isAbortError(e){return e instanceof Error&&(e.name==="TimeoutError"||e.name==="AbortError")}async logProgress(e,l=4,n){switch(n&&this.logger.startGroup(n),l){case 8:this.logger.debug(e);break;case 4:this.logger.info(e);break;case 2:this.logger.warning(e);break;case 1:this.logger.error(e);break;default:this.logger.log(e);break}n&&this.logger.endGroup(),this.config.callback&&await this.config.callback?.progress({kind:"log",message:e})}async createCodeQLScratchDir(e){let l=Tgt.normalize(Tgt.join(e,"..",".codeql-scratch"));return await Ugt.promises.mkdir(l,{recursive:!0}),l}createTelemetryByLanguage(e,l){let n=[];for(let[I,r]of Object.entries(e)){if(fbt(r)){let s={event:"codeql-checker-completion",properties:{"codeql.language":I,"codeql.skipped":"true","codeql.version":l},metrics:{},restrictedProperties:{}};n.push(s);continue}let a={event:"codeql-checker-completion",properties:{"codeql.language":I,"codeql.databaseCreationSuccess":r.databaseCreationSuccess?"true":"false","codeql.analysisRuleIds":YM(r)?r.analysisRuleIds.join(","):"","codeql.version":l,"codeql.querySuite":YM(r)?r.querySuite:void 0},metrics:{"codeql.databaseCreationTimeMs":r.databaseCreationTimeMs,"codeql.analysisTimeMs":YM(r)?r.analysisTimeMs:void 0,"codeql.alertCount":YM(r)?r.analysisRuleIds.length:0},restrictedProperties:{}};r.databaseCreationError&&(XN({telemetry:a},r.databaseCreationError,"codeql.databaseCreationError"),a.restrictedProperties["codeql.databaseCreationStack"]=String(r.databaseCreationError.stack)),YM(r)&&(a.properties["codeql.analysisSuccess"]=r.analysisSuccess?"true":"false",r.analysisError&&(XN({telemetry:a},r.analysisError,"codeql.analysisError"),a.restrictedProperties["codeql.analysisStack"]=String(r.analysisError.stack))),n.push(a)}return n}async shouldAnalyzeLanguage(e,l){if(l=="actions")return!0;let n=await e.getRepositorySize(l);if(n===void 0)return!0;let I=n<=t.DEFAULT_MAX_REPO_SIZE_BYTES;return I||this.logProgress(`Skipping analysis for ${l} because the repository size is ${n} bytes, which exceeds the limit of ${t.DEFAULT_MAX_REPO_SIZE_BYTES} bytes.`,2),I}};c();var Akl="gh-advisory-database",_gt="copilot_swe_agent_validation_agent_dependencies",Zkl="security agent",Dgt={name:Akl,description:"Security tool that checks the GitHub advisory DB and informs you about reported vulnerabilities in dependencies. Run this tool ALWAYS before you add new dependencies, to check if they contain vulnerabilities. This is NOT optional. If you don't know the version number you are going to install, retrieve that first. Feedback from this tool MUST be incorporated. Re-run the tool as appropriate.",input_schema:{type:"object",properties:{dependencies:{type:"array",items:{type:"object",properties:{version:{type:"string",description:"The version of the dependency in semver format. Examples: '1.0.0', '2.1.0'."},name:{type:"string",description:"The name of the dependency. Examples: 'express', 'lodash'."}},required:["name","version"]}}},required:["dependencies"]},callback:gkl,safeForTelemetry:{name:!0,inputsNames:!1}};async function gkl({dependencies:t},e){if(!t||t.length===0)return{textResultForLlm:"No dependencies provided for checking.",resultType:"success",sessionLog:"No dependencies provided for checking.",toolTelemetry:{}};let l=[];for(let n of t){let I=ykl(n);if(I)return Promise.resolve(I);try{let r=e?I3(e.settings):process.env.GH_TOKEN;if(!r){let s="GitHub token is required to use the dependency checker tool. Please set it in the settings or as the GH_TOKEN environment variable.";return{textResultForLlm:s,resultType:"failure",sessionLog:s,toolTelemetry:{properties:{error:s}}}}let a=new ohe({userAgent:Zkl,auth:r});l.push(...await Nkl(a,n))}catch(r){let a=`Error checking dependency ${n.name}: ${String(r)}`,s=r instanceof Error?r.stack:void 0;return{textResultForLlm:a,resultType:"failure",sessionLog:a,toolTelemetry:{restrictedProperties:{dep:`${n.name}@${n.version}`,error:a,stackTrace:s}}}}}if(l.length===0)return{textResultForLlm:"No vulnerabilities found in the provided dependencies.",resultType:"success",sessionLog:"No vulnerabilities found in the provided dependencies.",toolTelemetry:{}};{let n=Wkl(l);return{textResultForLlm:n,resultType:"success",sessionLog:n,toolTelemetry:{restrictedProperties:{vulnerableDeps:l.map(I=>`${I.name}@${I.version}`).join(", ")},metrics:{vulnerableDependencies:l.length}}}}}async function Nkl(t,e){let l=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,severity:"high"}),n=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,severity:"critical"}),I=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,type:"malware"}),r=[...l.data,...n.data,...I.data];return r.length===0?[]:r.flatMap(a=>a.vulnerabilities?.map(s=>({name:e.name,version:e.version,summary:a.summary,ecosystem:s.package.ecosystem,affectedVersions:s.vulnerable_version_range??"",patchedVersion:s.first_patched_version??"not available",severity:a.severity,type:a.type}))??[])}function Wkl(t){return t.map(e=>{let l=e.type==="malware"?"is malware":"has a vulnerability";return`Dependency ${e.name} version ${e.version} in ecosystem ${e.ecosystem} ${l}: ${e.summary}. Affected versions: ${e.affectedVersions}. Patched version: ${e.patchedVersion}.`}).join(`
832
+ the change and then the tool must be re-run.`,input_schema:{type:"object",properties:{}},callback:this.callback.bind(this),safeForTelemetry:!0}}async callback(){let e={},l="unknown",n=Date.now();try{if(!this.executor)throw new Error("CodeQL Executor is not initialized.");let I=AbortSignal.timeout(this.settings.tools?.codeql?.timeout??t.DEFAULT_TIMEOUT_MS);I.throwIfAborted(),l=await this.executor.version(I),await this.git.stageChanges(this.config.location);let r=await this.git.getDiffRanges(this.config.location,this.baseCommit),a=kbt(r);a.length>0?this.logProgress(`Found ${a.join(", ")} languages to analyze.`):this.logProgress("No languages found to analyze.");let s=[],o=!0;for(let G of a){if(I.throwIfAborted(),!await this.shouldAnalyzeLanguage(this.executor,G)){e[G]={skipped:!0};continue}let p=Date.now();try{await this.executor.createDatabase(I,G),this.logProgress(`Created database for ${G}.`),e[G]={databaseCreationSuccess:!0,databaseCreationTimeMs:Date.now()-p}}catch(W){if(this.isAbortError(W))throw W;o=!1;let E=`Error creating database for ${G}: ${String(W)}`;this.logProgress(E,1),e[G]={databaseCreationError:W instanceof Error?W:new Error(String(W)),databaseCreationSuccess:!1,databaseCreationTimeMs:Date.now()-p};continue}I.throwIfAborted();let h=Date.now();try{let W=await this.executor.analyzeDatabase(I,G,r);s.push(W);let E=W.alerts.length;this.logProgress(`Completed analysis of ${G}. ${E} ${E===1?"alert":"alerts"} found.`),e[G]={...e[G],analysisSuccess:!0,analysisTimeMs:Date.now()-h,analysisRuleIds:W.alerts.flatMap(R=>R.ruleId?[R.ruleId]:[]),querySuite:`${G}-code-scanning`}}catch(W){if(this.isAbortError(W))throw W;o=!1;let E=`Error analyzing database for ${G}: ${String(W)}`;this.logProgress(E,1),e[G]={...e[G],analysisError:W instanceof Error?W:new Error(String(W)),analysisSuccess:!1,analysisTimeMs:Date.now()-h,analysisRuleIds:[]}}}let d=s.filter(G=>G.alerts.length>0).reduce((G,p)=>G+p.alerts.length,0),u=a.length===0?"No code changes detected for languages that CodeQL can analyze, so no analysis was performed.":`Analysis Result for '${a.join(", ")}'. Found ${d} alert(s): ${JSON.stringify(s,null,2)}`;return{resultType:o?"success":"failure",textResultForLlm:u,sessionLog:u,toolTelemetry:{event:"tool_call_executed",properties:{"codeql.version":l},metrics:{"codeql.languages.count":a.length,"codeql.total.alerts":d,"codeql.duration.ms":Date.now()-n},restrictedProperties:{}}}}catch(I){let r=this.isAbortError(I)?`Operation cancelled due to timeout. Do not re-run the ${t.TOOL_NAME} tool because it will not complete successfully.`:`Error in CodeQL Checker: '${String(I)}'`;this.logProgress(r,1);let a={event:"tool_call_executed",properties:{"codeql.version":l,"codeql.aborted":this.isAbortError(I)?"true":"false"},metrics:{"codeql.languages.count":0,"codeql.total.alerts":0,"codeql.duration.ms":Date.now()-n},restrictedProperties:{"codeql.stack":I instanceof Error?I.stack??"":""}};return XN({telemetry:a},I,"codeql.error"),{resultType:"failure",textResultForLlm:r,sessionLog:r,toolTelemetry:a}}finally{let I=this.createTelemetryByLanguage(e,l);for(let r of I)this.config.callback?.progress({kind:"telemetry",telemetry:r})}}isAbortError(e){return e instanceof Error&&(e.name==="TimeoutError"||e.name==="AbortError")}async logProgress(e,l=4,n){switch(n&&this.logger.startGroup(n),l){case 8:this.logger.debug(e);break;case 4:this.logger.info(e);break;case 2:this.logger.warning(e);break;case 1:this.logger.error(e);break;default:this.logger.log(e);break}n&&this.logger.endGroup(),this.config.callback&&await this.config.callback?.progress({kind:"log",message:e})}async createCodeQLScratchDir(e){let l=Tgt.normalize(Tgt.join(e,"..",".codeql-scratch"));return await Ugt.promises.mkdir(l,{recursive:!0}),l}createTelemetryByLanguage(e,l){let n=[];for(let[I,r]of Object.entries(e)){if(fbt(r)){let s={event:"codeql-checker-completion",properties:{"codeql.language":I,"codeql.skipped":"true","codeql.version":l},metrics:{},restrictedProperties:{}};n.push(s);continue}let a={event:"codeql-checker-completion",properties:{"codeql.language":I,"codeql.databaseCreationSuccess":r.databaseCreationSuccess?"true":"false","codeql.analysisRuleIds":YM(r)?r.analysisRuleIds.join(","):"","codeql.version":l,"codeql.querySuite":YM(r)?r.querySuite:void 0},metrics:{"codeql.databaseCreationTimeMs":r.databaseCreationTimeMs,"codeql.analysisTimeMs":YM(r)?r.analysisTimeMs:void 0,"codeql.alertCount":YM(r)?r.analysisRuleIds.length:0},restrictedProperties:{}};r.databaseCreationError&&(XN({telemetry:a},r.databaseCreationError,"codeql.databaseCreationError"),a.restrictedProperties["codeql.databaseCreationStack"]=String(r.databaseCreationError.stack)),YM(r)&&(a.properties["codeql.analysisSuccess"]=r.analysisSuccess?"true":"false",r.analysisError&&(XN({telemetry:a},r.analysisError,"codeql.analysisError"),a.restrictedProperties["codeql.analysisStack"]=String(r.analysisError.stack))),n.push(a)}return n}async shouldAnalyzeLanguage(e,l){if(l=="actions")return!0;let n=await e.getRepositorySize(l);if(n===void 0)return!0;let I=n<=t.DEFAULT_MAX_REPO_SIZE_BYTES;return I||this.logProgress(`Skipping analysis for ${l} because the repository size is ${n} bytes, which exceeds the limit of ${t.DEFAULT_MAX_REPO_SIZE_BYTES} bytes.`,2),I}};c();var Akl="gh-advisory-database",_gt="copilot_swe_agent_validation_agent_dependencies",Zkl="security agent",Dgt={name:Akl,description:"Security tool that checks the GitHub advisory DB and informs you about reported vulnerabilities in dependencies. Run this tool ALWAYS before you add new dependencies, to check if they contain vulnerabilities. This is NOT optional. If you don't know the version number you are going to install, retrieve that first. Feedback from this tool MUST be incorporated. Re-run the tool as appropriate.",input_schema:{type:"object",properties:{dependencies:{type:"array",items:{type:"object",properties:{version:{type:"string",description:"The version of the dependency in semver format. Examples: '1.0.0', '2.1.0'."},name:{type:"string",description:"The name of the dependency. Examples: 'express', 'lodash'."}},required:["name","version"]}}},required:["dependencies"]},callback:gkl,safeForTelemetry:{name:!0,inputsNames:!1}};async function gkl({dependencies:t},e){if(!t||t.length===0)return{textResultForLlm:"No dependencies provided for checking.",resultType:"success",sessionLog:"No dependencies provided for checking.",toolTelemetry:{}};let l=[];for(let n of t){let I=ykl(n);if(I)return Promise.resolve(I);try{let r=e?I3(e.settings):process.env.GH_TOKEN;if(!r){let s="GitHub token is required to use the dependency checker tool. Please set it in the settings or as the GH_TOKEN environment variable.";return{textResultForLlm:s,resultType:"failure",sessionLog:s,toolTelemetry:{properties:{error:s}}}}let a=new ohe({userAgent:Zkl,auth:r});l.push(...await Nkl(a,n))}catch(r){let a=`Error checking dependency ${n.name}: ${String(r)}`,s=r instanceof Error?r.stack:void 0;return{textResultForLlm:a,resultType:"failure",sessionLog:a,toolTelemetry:{restrictedProperties:{dep:`${n.name}@${n.version}`,error:a,stackTrace:s}}}}}if(l.length===0)return{textResultForLlm:"No vulnerabilities found in the provided dependencies.",resultType:"success",sessionLog:"No vulnerabilities found in the provided dependencies.",toolTelemetry:{}};{let n=Wkl(l);return{textResultForLlm:n,resultType:"success",sessionLog:n,toolTelemetry:{restrictedProperties:{vulnerableDeps:l.map(I=>`${I.name}@${I.version}`).join(", ")},metrics:{vulnerableDependencies:l.length}}}}}async function Nkl(t,e){let l=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,severity:"high"}),n=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,severity:"critical"}),I=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,type:"malware"}),r=[...l.data,...n.data,...I.data];return r.length===0?[]:r.flatMap(a=>a.vulnerabilities?.map(s=>({name:e.name,version:e.version,summary:a.summary,ecosystem:s.package.ecosystem,affectedVersions:s.vulnerable_version_range??"",patchedVersion:s.first_patched_version??"not available",severity:a.severity,type:a.type}))??[])}function Wkl(t){return t.map(e=>{let l=e.type==="malware"?"is malware":"has a vulnerability";return`Dependency ${e.name} version ${e.version} in ecosystem ${e.ecosystem} ${l}: ${e.summary}. Affected versions: ${e.affectedVersions}. Patched version: ${e.patchedVersion}.`}).join(`
833
833
 
834
834
  `)}function Mgt(t){if(typeof t!="string"||t.trim()==="")return"parameter must be a non-empty string."}function ykl(t){let e=[],l=Mgt(t.name);l&&e.push(`name: ${l}`);let n=Mgt(t.version);if(n&&e.push(`version: ${n}`),e.length>0){let I=`Invalid parameters found for dependency ${t.name}: ${e.join(", ")}`;return{textResultForLlm:I,resultType:"failure",sessionLog:I,toolTelemetry:{}}}}c();var zgt="reply_to_comment",Pgt=(t,e)=>({name:zgt,description:`Reply to new comments. Use when you've completed a meaningful unit of work that specifically addresses the request, question, or feedback in the comment.
835
835
  * Use this tool no more than once per <comment_id>, and only after you have completed meaningful work that specifically addresses the text in the comment.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@github/copilot",
3
3
  "description": "GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.",
4
- "version": "0.0.337",
4
+ "version": "0.0.338-0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -33,7 +33,7 @@
33
33
  "sdk/**/*"
34
34
  ],
35
35
  "buildMetadata": {
36
- "gitCommit": "905260d"
36
+ "gitCommit": "851c99c"
37
37
  },
38
38
  "dependencies": {
39
39
  "node-pty": "npm:@devm33/node-pty@^1.0.8",
package/sdk/index.js CHANGED
@@ -291,7 +291,7 @@ extensions:
291
291
  `);let a=n+c,s=Ste.join(l,"pr-diff-range.yml");return Ute.writeFileSync(s,a),I(`Wrote pr-diff-range extension pack to ${s}:
292
292
  ${a}`,8),l}G();import*as cC from"os";import*as KS from"fs";var LmI=.05,XAe=1024*1024;function HAe(t){let e=cC.platform(),I=fmI(e,t)/(1024*1024),l=kmI(I,e),n=Math.floor(I-l);return t(`Using ${n} MB for CodeQL, out of ${I} MB total.`,8),n}function kmI(t,e){let I=1024*(e==="win32"?1.5:1),l=LmI*Math.max(t-8*1024,0);return I+l}function fmI(t,e){let I=[cC.totalmem()];return t==="linux"&&I.push(...["/sys/fs/cgroup/memory/memory.limit_in_bytes","/sys/fs/cgroup/memory.max"].map(n=>xmI(n,e)).filter(n=>n!==void 0).map(n=>n)),Math.min(...I)}function xmI(t,e){if(!KS.existsSync(t)){e(`While resolving RAM, did not find a cgroup memory limit at ${t}.`,8);return}let I=Number(KS.readFileSync(t,"utf8"));if(!Number.isInteger(I)){e(`While resolving RAM, ignored the file ${t} that may contain a cgroup memory limit as this file did not contain an integer.`,8);return}let l=`${Math.floor(I/(1024*1024))} MiB`;if(I>cC.totalmem()){e(`While resolving RAM, ignored the file ${t} that may contain a cgroup memory limit as its contents ${l} were greater than the total amount of system memory.`,8);return}if(I<XAe){e(`While resolving RAM, ignored a cgroup limit of ${l} in ${t} as it was below ${XAe/(1024*1024)} MiB.`,8);return}return e(`While resolving RAM, found a cgroup limit of ${l} in ${t}.`,8),I}G();import*as qg from"fs";import*as PS from"os";function EAe(t){let e=[PS.cpus().length];return PS.platform()==="linux"&&(e.push(...["/sys/fs/cgroup/cpuset.cpus.effective","/sys/fs/cgroup/cpuset.cpus"].map(l=>zmI(l,t)).filter(l=>l!==void 0&&l>0).map(l=>l)),e.push(...["/sys/fs/cgroup/cpu.max"].map(l=>BmI(l,t)).filter(l=>l!==void 0&&l>0).map(l=>l))),Math.min(...e)}function BmI(t,e){if(!qg.existsSync(t)){e(`While resolving threads, did not find a cgroup CPU file at ${t}.`,8);return}let l=qg.readFileSync(t,"utf-8").split(" ");if(l.length!==2){e(`While resolving threads, did not use cgroup CPU file at ${t} because it contained ${l.length} value(s) rather than the two expected.`,8);return}let n=l[0];if(n==="max")return;let c=l[1],a=Math.floor(parseInt(n)/parseInt(c));return e(`While resolving threads, found a cgroup CPU file with ${a} CPUs in ${t}.`,8),a}function zmI(t,e){if(!qg.existsSync(t)){e(`While resolving threads, did not find a cgroup CPUs file at ${t}.`,8);return}let I=0,l=qg.readFileSync(t,"utf-8").trim();if(l.length!==0){for(let n of l.split(","))if(!n.includes("-"))++I;else{let c=parseInt(n.split("-")[0]),a=parseInt(n.split("-")[1]);I+=a-c+1}return e(`While resolving threads, found a cgroup CPUs file with ${I} CPUs in ${t}.`,8),I}}var _g=class t{constructor(e,I,l,n,c){this.executablePath=e;this.databaseDir=I;this.settings=l;this.sourceRoot=n;this.progressLogger=c;this.ram=this.resolveRam(),this.threads=this.resolveThreads()}static DIFF_INFORMED_FEATURE_FLAG_NAME="copilot_swe_agent_codeql_diff_informed";ram;repositorySizeCache=new Map;threads;async createDatabase(e,I){let l=`${this.databaseDir}/${I}`,n=this.getBuildMode(I);return await this.execCommand(e,`database create ${this.ram} ${this.threads} --no-sublanguage-file-coverage --no-calculate-baseline --overwrite --language ${I} --build-mode ${n} --source-root ${this.sourceRoot} ${l}`),l}static AUTOBUILD_ONLY_LANGUAGES=["cpp","go","swift"];getBuildMode(e){return t.AUTOBUILD_ONLY_LANGUAGES.includes(e)?"autobuild":"none"}async analyzeDatabase(e,I,l){let n=[];if(vl(this.settings,t.DIFF_INFORMED_FEATURE_FLAG_NAME)){let o=$g.mkdtempSync(aC.join(Ote.tmpdir(),"codeql-")),d=wAe(l,o,this.progressLogger);this.progressLogger(`Created diff range data extension pack at ${d}`,8),n=["--additional-packs",d,"--extension-packs","codeql-action/pr-diff-range"]}let c=`${this.databaseDir}/${I}`,a=`${c}/results-${I}.json`;await $g.promises.rm(a,{force:!0}),this.progressLogger(`Analyzing database at ${c} for language ${I}`);let s=["database","analyze",this.ram,this.threads,"--format","sarifv2.1.0","--output",a,...n,c,`codeql/${I}-queries`];return await this.execCommand(e,s.join(" ")),new _U(a,this.progressLogger.bind(this)).summarize(I,l)}async version(e){let I=await this.execCommand(e,"version --format json");try{return JSON.parse(I).version}catch{throw new Error(`Failed to parse CodeQL version output: ${I}`)}}async getRepositorySize(e){return this.repositorySizeCache.has(e)||this.repositorySizeCache.set(e,await this.computeRepositorySize(e)),this.repositorySizeCache.get(e)}async execCommand(e,I){return this.progressLogger(`Executing CodeQL command: ${I}`),new Promise((l,n)=>{qS.exec(`${this.executablePath} ${I}`,{signal:e},(c,a,s)=>{let r=c?1:4;this.progressLogger(s,r,"CodeQL Output"),c?c.name=="AbortError"?n(c):n(new Error(`Error executing command: ${c} ${s}`)):l(a)})})}resolveRam(){try{return`--ram ${HAe(this.progressLogger)}`}catch(e){return this.progressLogger(`Failed to resolve RAM, not passing --ram flag to CodeQL: ${e}`,2),""}}resolveThreads(){try{return`--threads ${EAe(this.progressLogger)}`}catch(e){return this.progressLogger(`Failed to resolve threads, not passing --threads flag to CodeQL: ${e}`,2),""}}getSccExecutablePath(){let e=aC.dirname(this.executablePath),I;switch(Ote.platform()){case"win32":I=aC.join(e,"tools/win64/scc.exe");break;case"darwin":I=aC.join(e,"tools/osx64/scc");break;case"linux":I=aC.join(e,"tools/linux64/scc");break;default:return}if($g.existsSync(I))return I}async computeRepositorySize(e){let I=this.getSccExecutablePath();if(!I){this.progressLogger(`SCC executable not found for platform: ${Ote.platform()}`,2);return}let l=Eye(e);if(!l){this.progressLogger(`No file extensions found for language: ${e}`,2);return}let n=["--exclude-dir",".git,.hg,.svn,target,build,dist","--format","json","--include-ext",l.join(","),"--no-complexity","--no-cocomo"],c=qS.spawn(I,n,{cwd:this.sourceRoot}),a="",s="";c.stdout.on("data",o=>{a+=o}),c.stderr.on("data",o=>{s+=o});let r=await new Promise(o=>{c.on("close",o)});if(r!==0){this.progressLogger(`SCC failed with exit code ${r}: ${s}`,2);return}try{let d=JSON.parse(a).reduce((i,h)=>i+h.Bytes,0);return this.progressLogger(`SCC output for ${e}: ${d} bytes`,4),d}catch(o){this.progressLogger(`Failed to parse SCC output: ${o}`,2);return}}};var CAe="codeql-bundle-linux64.tar.gz",OmI=new jV;async function MmI(t,e){let n=(await new eU({auth:t}).rest.repos.getLatestRelease({owner:"github",repo:"codeql-action"})).data.assets.find(c=>c.name===CAe);if(n)return e(`CodeQL asset ID: ${n.id}`),n.id;throw new Error("CodeQL asset not found")}async function TmI(t,e,I,l){let n=await fetch(`https://api.github.com/repos/github/codeql-action/releases/assets/${t}`,{headers:{Authorization:`token ${I}`,Accept:"application/octet-stream"},redirect:"follow"});if(!n.ok||!n.body)throw new Error(`Failed to download asset: ${n.statusText}`);let c=eQ.join(e,CAe),a=rm.createWriteStream(c,{flags:"wx"});return await SmI(UmI.fromWeb(n.body).pipe(a)),l(`CodeQL downloaded to ${c}`),c}async function jmI(t,e,I){await rm.promises.mkdir(e,{recursive:!0});try{return await aIe({file:t,cwd:e}),I(`CodeQL unzipped to ${e}`),kAe(e)}catch(l){throw OmI.error(`Error unzipping CodeQL: ${String(l)}`),l}}async function DmI(t,e,I){let l=process.env.GITHUB_TOKEN||RV(I),n=await MmI(l,e),c=KmI(t);await rm.promises.mkdir(c,{recursive:!0});let a=await TmI(n,c,l,e);return await jmI(a,t,e),await rm.promises.rm(a),LAe(t)}async function JAe(t,e,I,l){let n=PmI(t);await rm.promises.mkdir(n,{recursive:!0});let c=await qmI(l);if(c)return new _g(c,n,I,e,l);let a=LAe(t);if(await Mte(a))return l(`CodeQL already exists at ${a}`),new _g(a,n,I,e,l);try{let s=await DmI(t,l,I);return new _g(s,n,I,e,l)}catch(s){throw l(`Error ensuring CodeQL: ${String(s)}`,1),s}}function KmI(t){return eQ.join(t,"codeql-download")}function LAe(t){return eQ.join(kAe(t),"codeql")}function kAe(t){return eQ.join(t,"codeql")}function PmI(t){return eQ.join(t,"dbs")}async function qmI(t){if(!process.env.RUNNER_TOOL_CACHE)return;let e=_S.findAllVersions("CodeQL");if(!e.length)return;let I=e[0],l=_S.find("CodeQL",I,vAe.arch());if(l){let n=eQ.join(l,"codeql","codeql");if(t(`CodeQL directory found in toolcache at '${l}'.`),!await Mte(n)){let c;throw await Mte(l)?c=rm.readdirSync(l):c=["path does not exist"],new Error(`CodeQL executable not found at '${n}'. Contents of toolcache: '${c.join(", ")}'.`)}return n}}async function Mte(t){try{return await rm.promises.stat(t),!0}catch{return!1}}var $S=class t{constructor(e,I,l,n,c){this.config=e;this.git=I;this.baseCommit=l;this.settings=n;this.logger=c}static DEFAULT_MAX_REPO_SIZE_BYTES=1e7;static DEFAULT_TIMEOUT_MS=180*1e3;static TOOL_NAME="codeql_checker";static CODEQL_CHECKER_ENABLED_FF="copilot_swe_agent_enable_security_tool";static CODEQL_CHECKER_DISABLED_FF="copilot_swe_agent_enable_security_tool_disabled";static isEnabled(e){return vl(e,t.CODEQL_CHECKER_ENABLED_FF)&&!vl(e,t.CODEQL_CHECKER_DISABLED_FF)}executor;async getCodeQLCheckerTool(){let e=await this.createCodeQLScratchDir(this.config.location);return this.executor=await JAe(e,this.config.location,this.settings,this.logProgress.bind(this)),{name:t.TOOL_NAME,description:`This is a security tool that discovers vulnerabilities in code using CodeQL. It must always be run when there are code changes.
293
293
  It is run after committing all changed code and before the final verification. Feedback from this tool must be incorporated into
294
- the change and then the tool must be re-run.`,input_schema:{type:"object",properties:{}},callback:this.callback.bind(this),safeForTelemetry:!0}}async callback(){let e={},I="unknown",l=Date.now();try{if(!this.executor)throw new Error("CodeQL Executor is not initialized.");let n=AbortSignal.timeout(this.settings.tools?.codeql?.timeout??t.DEFAULT_TIMEOUT_MS);n.throwIfAborted(),I=await this.executor.version(n),await this.git.stageChanges(this.config.location);let c=await this.git.getDiffRanges(this.config.location,this.baseCommit),a=Hye(c);a.length>0?this.logProgress(`Found ${a.join(", ")} languages to analyze.`):this.logProgress("No languages found to analyze.");let s=[],r=!0;for(let i of a){if(n.throwIfAborted(),!await this.shouldAnalyzeLanguage(this.executor,i)){e[i]={skipped:!0};continue}let h=Date.now();try{await this.executor.createDatabase(n,i),this.logProgress(`Created database for ${i}.`),e[i]={databaseCreationSuccess:!0,databaseCreationTimeMs:Date.now()-h}}catch(Z){r=!1;let u=`Error creating database for ${i}: ${String(Z)}`;this.logProgress(u,1),e[i]={databaseCreationError:Z instanceof Error?Z:new Error(String(Z)),databaseCreationSuccess:!1,databaseCreationTimeMs:Date.now()-h};continue}n.throwIfAborted();let p=Date.now();try{let Z=await this.executor.analyzeDatabase(n,i,c);s.push(Z);let u=Z.alerts.length;this.logProgress(`Completed analysis of ${i}. ${u} ${u===1?"alert":"alerts"} found.`),e[i]={...e[i],analysisSuccess:!0,analysisTimeMs:Date.now()-p,analysisRuleIds:Z.alerts.flatMap(N=>N.ruleId?[N.ruleId]:[]),querySuite:`${i}-code-scanning`}}catch(Z){r=!1;let u=`Error analyzing database for ${i}: ${String(Z)}`;this.logProgress(u,1),e[i]={...e[i],analysisError:Z instanceof Error?Z:new Error(String(Z)),analysisSuccess:!1,analysisTimeMs:Date.now()-p,analysisRuleIds:[]}}}let o=s.filter(i=>i.alerts.length>0).reduce((i,h)=>i+h.alerts.length,0),d=a.length===0?"No code changes detected for languages that CodeQL can analyze, so no analysis was performed.":`Analysis Result for '${a}'. Found ${o} alert(s): ${JSON.stringify(s,null,2)}`;return{resultType:r?"success":"failure",textResultForLlm:d,sessionLog:`Analysis completed successfully for '${a}'.`,toolTelemetry:{event:"tool_call_executed",properties:{"codeql.version":I},metrics:{"codeql.languages.count":a.length,"codeql.total.alerts":o,"codeql.duration.ms":Date.now()-l},restrictedProperties:{}}}}catch(n){let c=this.isAbortError(n)?`Operation cancelled due to timeout. Do not re-run the ${t.TOOL_NAME} tool because it will not complete successfully.`:`Error in CodeQL Checker: '${String(n)}'`;this.logProgress(c,1);let a={event:"tool_call_executed",properties:{"codeql.version":I,"codeql.aborted":this.isAbortError(n)?"true":"false"},metrics:{"codeql.languages.count":0,"codeql.total.alerts":0,"codeql.duration.ms":Date.now()-l},restrictedProperties:{"codeql.stack":n instanceof Error?n.stack??"":""}};return mo({telemetry:a},n,"codeql.error"),{resultType:"failure",textResultForLlm:c,sessionLog:c,toolTelemetry:a}}finally{let n=this.createTelemetryByLanguage(e,I);for(let c of n)this.config.callback?.progress({kind:"telemetry",telemetry:c})}}isAbortError(e){return e instanceof Error&&(e.name==="TimeoutError"||e.name==="AbortError")}async logProgress(e,I=4,l){switch(l&&this.logger.startGroup(l),I){case 8:this.logger.debug(e);break;case 4:this.logger.info(e);break;case 2:this.logger.warning(e);break;case 1:this.logger.error(e);break;default:this.logger.log(e);break}l&&this.logger.endGroup(),this.config.callback&&await this.config.callback?.progress({kind:"log",message:e})}async createCodeQLScratchDir(e){let I=fAe.normalize(fAe.join(e,"..",".codeql-scratch"));return await xAe.promises.mkdir(I,{recursive:!0}),I}createTelemetryByLanguage(e,I){let l=[];for(let[n,c]of Object.entries(e)){if(Aye(c)){let s={event:"codeql-checker-completion",properties:{"codeql.language":n,"codeql.skipped":"true","codeql.version":I},metrics:{},restrictedProperties:{}};l.push(s);continue}let a={event:"codeql-checker-completion",properties:{"codeql.language":n,"codeql.databaseCreationSuccess":c.databaseCreationSuccess?"true":"false","codeql.analysisRuleIds":Zg(c)?c.analysisRuleIds.join(","):"","codeql.version":I,"codeql.querySuite":Zg(c)?c.querySuite:void 0},metrics:{"codeql.databaseCreationTimeMs":c.databaseCreationTimeMs,"codeql.analysisTimeMs":Zg(c)?c.analysisTimeMs:void 0,"codeql.alertCount":Zg(c)?c.analysisRuleIds.length:0},restrictedProperties:{}};c.databaseCreationError&&(mo({telemetry:a},c.databaseCreationError,"codeql.databaseCreationError"),a.restrictedProperties["codeql.databaseCreationStack"]=String(c.databaseCreationError.stack)),Zg(c)&&(a.properties["codeql.analysisSuccess"]=c.analysisSuccess?"true":"false",c.analysisError&&(mo({telemetry:a},c.analysisError,"codeql.analysisError"),a.restrictedProperties["codeql.analysisStack"]=String(c.analysisError.stack))),l.push(a)}return l}async shouldAnalyzeLanguage(e,I){if(I=="actions")return!0;let l=await e.getRepositorySize(I);if(l===void 0)return!0;let n=l<=t.DEFAULT_MAX_REPO_SIZE_BYTES;return n||this.logProgress(`Skipping analysis for ${I} because the repository size is ${l} bytes, which exceeds the limit of ${t.DEFAULT_MAX_REPO_SIZE_BYTES} bytes.`,2),n}};G();var _mI="gh-advisory-database",zAe="copilot_swe_agent_validation_agent_dependencies",$mI="security agent",UAe={name:_mI,description:"Security tool that checks the GitHub advisory DB and informs you about reported vulnerabilities in dependencies. Run this tool ALWAYS before you add new dependencies, to check if they contain vulnerabilities. This is NOT optional. If you don't know the version number you are going to install, retrieve that first. Feedback from this tool MUST be incorporated. Re-run the tool as appropriate.",input_schema:{type:"object",properties:{dependencies:{type:"array",items:{type:"object",properties:{version:{type:"string",description:"The version of the dependency in semver format. Examples: '1.0.0', '2.1.0'."},name:{type:"string",description:"The name of the dependency. Examples: 'express', 'lodash'."}},required:["name","version"]}}},required:["dependencies"]},callback:ehI,safeForTelemetry:{name:!0,inputsNames:!1}};async function ehI({dependencies:t},e){if(!t||t.length===0)return{textResultForLlm:"No dependencies provided for checking.",resultType:"success",sessionLog:"No dependencies provided for checking.",toolTelemetry:{}};let I=[];for(let l of t){let n=lhI(l);if(n)return Promise.resolve(n);try{let c=e?RV(e.settings):process.env.GH_TOKEN;if(!c){let s="GitHub token is required to use the dependency checker tool. Please set it in the settings or as the GH_TOKEN environment variable.";return{textResultForLlm:s,resultType:"failure",sessionLog:s,toolTelemetry:{properties:{error:s}}}}let a=new eU({userAgent:$mI,auth:c});I.push(...await IhI(a,l))}catch(c){let a=`Error checking dependency ${l.name}: ${String(c)}`,s=c instanceof Error?c.stack:void 0;return{textResultForLlm:a,resultType:"failure",sessionLog:a,toolTelemetry:{restrictedProperties:{dep:`${l.name}@${l.version}`,error:a,stackTrace:s}}}}}if(I.length===0)return{textResultForLlm:"No vulnerabilities found in the provided dependencies.",resultType:"success",sessionLog:"No vulnerabilities found in the provided dependencies.",toolTelemetry:{}};{let l=thI(I);return{textResultForLlm:l,resultType:"success",sessionLog:l,toolTelemetry:{restrictedProperties:{vulnerableDeps:I.map(n=>`${n.name}@${n.version}`).join(", ")},metrics:{vulnerableDependencies:I.length}}}}}async function IhI(t,e){let I=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,severity:"high"}),l=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,severity:"critical"}),n=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,type:"malware"}),c=[...I.data,...l.data,...n.data];return c.length===0?[]:c.flatMap(a=>a.vulnerabilities?.map(s=>({name:e.name,version:e.version,summary:a.summary,ecosystem:s.package.ecosystem,affectedVersions:s.vulnerable_version_range??"",patchedVersion:s.first_patched_version??"not available",severity:a.severity,type:a.type}))??[])}function thI(t){return t.map(e=>{let I=e.type==="malware"?"is malware":"has a vulnerability";return`Dependency ${e.name} version ${e.version} in ecosystem ${e.ecosystem} ${I}: ${e.summary}. Affected versions: ${e.affectedVersions}. Patched version: ${e.patchedVersion}.`}).join(`
294
+ the change and then the tool must be re-run.`,input_schema:{type:"object",properties:{}},callback:this.callback.bind(this),safeForTelemetry:!0}}async callback(){let e={},I="unknown",l=Date.now();try{if(!this.executor)throw new Error("CodeQL Executor is not initialized.");let n=AbortSignal.timeout(this.settings.tools?.codeql?.timeout??t.DEFAULT_TIMEOUT_MS);n.throwIfAborted(),I=await this.executor.version(n),await this.git.stageChanges(this.config.location);let c=await this.git.getDiffRanges(this.config.location,this.baseCommit),a=Hye(c);a.length>0?this.logProgress(`Found ${a.join(", ")} languages to analyze.`):this.logProgress("No languages found to analyze.");let s=[],r=!0;for(let i of a){if(n.throwIfAborted(),!await this.shouldAnalyzeLanguage(this.executor,i)){e[i]={skipped:!0};continue}let h=Date.now();try{await this.executor.createDatabase(n,i),this.logProgress(`Created database for ${i}.`),e[i]={databaseCreationSuccess:!0,databaseCreationTimeMs:Date.now()-h}}catch(Z){if(this.isAbortError(Z))throw Z;r=!1;let u=`Error creating database for ${i}: ${String(Z)}`;this.logProgress(u,1),e[i]={databaseCreationError:Z instanceof Error?Z:new Error(String(Z)),databaseCreationSuccess:!1,databaseCreationTimeMs:Date.now()-h};continue}n.throwIfAborted();let p=Date.now();try{let Z=await this.executor.analyzeDatabase(n,i,c);s.push(Z);let u=Z.alerts.length;this.logProgress(`Completed analysis of ${i}. ${u} ${u===1?"alert":"alerts"} found.`),e[i]={...e[i],analysisSuccess:!0,analysisTimeMs:Date.now()-p,analysisRuleIds:Z.alerts.flatMap(N=>N.ruleId?[N.ruleId]:[]),querySuite:`${i}-code-scanning`}}catch(Z){if(this.isAbortError(Z))throw Z;r=!1;let u=`Error analyzing database for ${i}: ${String(Z)}`;this.logProgress(u,1),e[i]={...e[i],analysisError:Z instanceof Error?Z:new Error(String(Z)),analysisSuccess:!1,analysisTimeMs:Date.now()-p,analysisRuleIds:[]}}}let o=s.filter(i=>i.alerts.length>0).reduce((i,h)=>i+h.alerts.length,0),d=a.length===0?"No code changes detected for languages that CodeQL can analyze, so no analysis was performed.":`Analysis Result for '${a.join(", ")}'. Found ${o} alert(s): ${JSON.stringify(s,null,2)}`;return{resultType:r?"success":"failure",textResultForLlm:d,sessionLog:d,toolTelemetry:{event:"tool_call_executed",properties:{"codeql.version":I},metrics:{"codeql.languages.count":a.length,"codeql.total.alerts":o,"codeql.duration.ms":Date.now()-l},restrictedProperties:{}}}}catch(n){let c=this.isAbortError(n)?`Operation cancelled due to timeout. Do not re-run the ${t.TOOL_NAME} tool because it will not complete successfully.`:`Error in CodeQL Checker: '${String(n)}'`;this.logProgress(c,1);let a={event:"tool_call_executed",properties:{"codeql.version":I,"codeql.aborted":this.isAbortError(n)?"true":"false"},metrics:{"codeql.languages.count":0,"codeql.total.alerts":0,"codeql.duration.ms":Date.now()-l},restrictedProperties:{"codeql.stack":n instanceof Error?n.stack??"":""}};return mo({telemetry:a},n,"codeql.error"),{resultType:"failure",textResultForLlm:c,sessionLog:c,toolTelemetry:a}}finally{let n=this.createTelemetryByLanguage(e,I);for(let c of n)this.config.callback?.progress({kind:"telemetry",telemetry:c})}}isAbortError(e){return e instanceof Error&&(e.name==="TimeoutError"||e.name==="AbortError")}async logProgress(e,I=4,l){switch(l&&this.logger.startGroup(l),I){case 8:this.logger.debug(e);break;case 4:this.logger.info(e);break;case 2:this.logger.warning(e);break;case 1:this.logger.error(e);break;default:this.logger.log(e);break}l&&this.logger.endGroup(),this.config.callback&&await this.config.callback?.progress({kind:"log",message:e})}async createCodeQLScratchDir(e){let I=fAe.normalize(fAe.join(e,"..",".codeql-scratch"));return await xAe.promises.mkdir(I,{recursive:!0}),I}createTelemetryByLanguage(e,I){let l=[];for(let[n,c]of Object.entries(e)){if(Aye(c)){let s={event:"codeql-checker-completion",properties:{"codeql.language":n,"codeql.skipped":"true","codeql.version":I},metrics:{},restrictedProperties:{}};l.push(s);continue}let a={event:"codeql-checker-completion",properties:{"codeql.language":n,"codeql.databaseCreationSuccess":c.databaseCreationSuccess?"true":"false","codeql.analysisRuleIds":Zg(c)?c.analysisRuleIds.join(","):"","codeql.version":I,"codeql.querySuite":Zg(c)?c.querySuite:void 0},metrics:{"codeql.databaseCreationTimeMs":c.databaseCreationTimeMs,"codeql.analysisTimeMs":Zg(c)?c.analysisTimeMs:void 0,"codeql.alertCount":Zg(c)?c.analysisRuleIds.length:0},restrictedProperties:{}};c.databaseCreationError&&(mo({telemetry:a},c.databaseCreationError,"codeql.databaseCreationError"),a.restrictedProperties["codeql.databaseCreationStack"]=String(c.databaseCreationError.stack)),Zg(c)&&(a.properties["codeql.analysisSuccess"]=c.analysisSuccess?"true":"false",c.analysisError&&(mo({telemetry:a},c.analysisError,"codeql.analysisError"),a.restrictedProperties["codeql.analysisStack"]=String(c.analysisError.stack))),l.push(a)}return l}async shouldAnalyzeLanguage(e,I){if(I=="actions")return!0;let l=await e.getRepositorySize(I);if(l===void 0)return!0;let n=l<=t.DEFAULT_MAX_REPO_SIZE_BYTES;return n||this.logProgress(`Skipping analysis for ${I} because the repository size is ${l} bytes, which exceeds the limit of ${t.DEFAULT_MAX_REPO_SIZE_BYTES} bytes.`,2),n}};G();var _mI="gh-advisory-database",zAe="copilot_swe_agent_validation_agent_dependencies",$mI="security agent",UAe={name:_mI,description:"Security tool that checks the GitHub advisory DB and informs you about reported vulnerabilities in dependencies. Run this tool ALWAYS before you add new dependencies, to check if they contain vulnerabilities. This is NOT optional. If you don't know the version number you are going to install, retrieve that first. Feedback from this tool MUST be incorporated. Re-run the tool as appropriate.",input_schema:{type:"object",properties:{dependencies:{type:"array",items:{type:"object",properties:{version:{type:"string",description:"The version of the dependency in semver format. Examples: '1.0.0', '2.1.0'."},name:{type:"string",description:"The name of the dependency. Examples: 'express', 'lodash'."}},required:["name","version"]}}},required:["dependencies"]},callback:ehI,safeForTelemetry:{name:!0,inputsNames:!1}};async function ehI({dependencies:t},e){if(!t||t.length===0)return{textResultForLlm:"No dependencies provided for checking.",resultType:"success",sessionLog:"No dependencies provided for checking.",toolTelemetry:{}};let I=[];for(let l of t){let n=lhI(l);if(n)return Promise.resolve(n);try{let c=e?RV(e.settings):process.env.GH_TOKEN;if(!c){let s="GitHub token is required to use the dependency checker tool. Please set it in the settings or as the GH_TOKEN environment variable.";return{textResultForLlm:s,resultType:"failure",sessionLog:s,toolTelemetry:{properties:{error:s}}}}let a=new eU({userAgent:$mI,auth:c});I.push(...await IhI(a,l))}catch(c){let a=`Error checking dependency ${l.name}: ${String(c)}`,s=c instanceof Error?c.stack:void 0;return{textResultForLlm:a,resultType:"failure",sessionLog:a,toolTelemetry:{restrictedProperties:{dep:`${l.name}@${l.version}`,error:a,stackTrace:s}}}}}if(I.length===0)return{textResultForLlm:"No vulnerabilities found in the provided dependencies.",resultType:"success",sessionLog:"No vulnerabilities found in the provided dependencies.",toolTelemetry:{}};{let l=thI(I);return{textResultForLlm:l,resultType:"success",sessionLog:l,toolTelemetry:{restrictedProperties:{vulnerableDeps:I.map(n=>`${n.name}@${n.version}`).join(", ")},metrics:{vulnerableDependencies:I.length}}}}}async function IhI(t,e){let I=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,severity:"high"}),l=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,severity:"critical"}),n=await t.securityAdvisories.listGlobalAdvisories({affects:`${e.name}@${e.version}`,type:"malware"}),c=[...I.data,...l.data,...n.data];return c.length===0?[]:c.flatMap(a=>a.vulnerabilities?.map(s=>({name:e.name,version:e.version,summary:a.summary,ecosystem:s.package.ecosystem,affectedVersions:s.vulnerable_version_range??"",patchedVersion:s.first_patched_version??"not available",severity:a.severity,type:a.type}))??[])}function thI(t){return t.map(e=>{let I=e.type==="malware"?"is malware":"has a vulnerability";return`Dependency ${e.name} version ${e.version} in ecosystem ${e.ecosystem} ${I}: ${e.summary}. Affected versions: ${e.affectedVersions}. Patched version: ${e.patchedVersion}.`}).join(`
295
295
 
296
296
  `)}function BAe(t){if(typeof t!="string"||t.trim()==="")return"parameter must be a non-empty string."}function lhI(t){let e=[],I=BAe(t.name);I&&e.push(`name: ${I}`);let l=BAe(t.version);if(l&&e.push(`version: ${l}`),e.length>0){let n=`Invalid parameters found for dependency ${t.name}: ${e.join(", ")}`;return{textResultForLlm:n,resultType:"failure",sessionLog:n,toolTelemetry:{}}}}G();var SAe="reply_to_comment",OAe=(t,e)=>({name:SAe,description:`Reply to new comments. Use when you've completed a meaningful unit of work that specifically addresses the request, question, or feedback in the comment.
297
297
  * Use this tool no more than once per <comment_id>, and only after you have completed meaningful work that specifically addresses the text in the comment.