@github/copilot 0.0.337 → 0.0.338-1
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 +42 -42
- package/package.json +2 -2
- package/sdk/index.d.ts +2 -1
- package/sdk/index.js +2 -2
- package/sdk/index.js.map +1 -1
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.
|
|
4
|
+
"version": "0.0.338-1",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"sdk/**/*"
|
|
34
34
|
],
|
|
35
35
|
"buildMetadata": {
|
|
36
|
-
"gitCommit": "
|
|
36
|
+
"gitCommit": "afc7090"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"node-pty": "npm:@devm33/node-pty@^1.0.8",
|
package/sdk/index.d.ts
CHANGED
|
@@ -501,8 +501,9 @@ export declare class Session implements SessionMetadata {
|
|
|
501
501
|
/**
|
|
502
502
|
* Add an event to the session
|
|
503
503
|
* Auto-generates id, timestamp, and parentId
|
|
504
|
+
* Returns the created event
|
|
504
505
|
*/
|
|
505
|
-
addEvent(eventData: Partial<Pick<SessionEvent, "id" | "timestamp" | "parentId">> & Omit<SessionEvent, "id" | "timestamp" | "parentId">):
|
|
506
|
+
addEvent(eventData: Partial<Pick<SessionEvent, "id" | "timestamp" | "parentId">> & Omit<SessionEvent, "id" | "timestamp" | "parentId">): SessionEvent;
|
|
506
507
|
/**
|
|
507
508
|
* Get all events in the session
|
|
508
509
|
*/
|
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
|
|
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.
|
|
@@ -1345,7 +1345,7 @@ Pay attention to the following when using it:
|
|
|
1345
1345
|
`}var nTI=aq.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function cTI(){let t={};for(let e of nTI){let I=aq.env[e];I!==void 0&&(I.startsWith("()")||(t[e]=I))}return t}var cq=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new nq,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new lTI)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,I)=>{var l,n,c,a,s;this._process=(0,uDe.default)(this._serverParams.command,(l=this._serverParams.args)!==null&&l!==void 0?l:[],{env:{...cTI(),...this._serverParams.env},stdio:["pipe","pipe",(n=this._serverParams.stderr)!==null&&n!==void 0?n:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:aq.platform==="win32"&&aTI(),cwd:this._serverParams.cwd}),this._process.on("error",r=>{var o,d;if(r.name==="AbortError"){(o=this.onclose)===null||o===void 0||o.call(this);return}I(r),(d=this.onerror)===null||d===void 0||d.call(this,r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{var o;this._process=void 0,(o=this.onclose)===null||o===void 0||o.call(this)}),(c=this._process.stdin)===null||c===void 0||c.on("error",r=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,r)}),(a=this._process.stdout)===null||a===void 0||a.on("data",r=>{this._readBuffer.append(r),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",r=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,r)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,I;return this._stderrStream?this._stderrStream:(I=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&I!==void 0?I:null}get pid(){var e,I;return(I=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&I!==void 0?I:null}processReadBuffer(){for(var e,I;;)try{let l=this._readBuffer.readMessage();if(l===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,l)}catch(l){(I=this.onerror)===null||I===void 0||I.call(this,l)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(I=>{var l;if(!(!((l=this._process)===null||l===void 0)&&l.stdin))throw new Error("Not connected");let n=ZDe(e);this._process.stdin.write(n)?I():this._process.stdin.once("drain",I)})}};function aTI(){return"type"in aq}G();G();var sq=class extends TransformStream{constructor({onError:e,onRetry:I,onComment:l}={}){let n;super({start(c){n=_6({onEvent:a=>{c.enqueue(a)},onError(a){e==="terminate"?c.error(a):typeof e=="function"&&e(a)},onRetry:I,onComment:l})},transform(c){n.feed(c)}})}};var sTI={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},ux=class extends Error{constructor(e,I){super(`Streamable HTTP error: ${I}`),this.code=e}},rq=class{constructor(e,I){var l;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=I?.requestInit,this._authProvider=I?.authProvider,this._fetch=I?.fetch,this._sessionId=I?.sessionId,this._reconnectionOptions=(l=I?.reconnectionOptions)!==null&&l!==void 0?l:sTI}async _authThenStart(){var e;if(!this._authProvider)throw new eo("No auth provider");let I;try{I=await hV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(l){throw(e=this.onerror)===null||e===void 0||e.call(this,l),l}if(I!=="AUTHORIZED")throw new eo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let I={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(I.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(I["mcp-session-id"]=this._sessionId),this._protocolVersion&&(I["mcp-protocol-version"]=this._protocolVersion);let l=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...I,...l})}async _startOrAuthSse(e){var I,l,n;let{resumptionToken:c}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),c&&a.set("last-event-id",c);let s=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,{method:"GET",headers:a,signal:(l=this._abortController)===null||l===void 0?void 0:l.signal});if(!s.ok){if(s.status===401&&this._authProvider)return await this._authThenStart();if(s.status===405)return;throw new ux(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(a){throw(n=this.onerror)===null||n===void 0||n.call(this,a),a}}_getNextReconnectionDelay(e){let I=this._reconnectionOptions.initialReconnectionDelay,l=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(I*Math.pow(l,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,I=0){var l;let n=this._reconnectionOptions.maxRetries;if(n>0&&I>=n){(l=this.onerror)===null||l===void 0||l.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let c=this._getNextReconnectionDelay(I);setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,I+1)})},c)}_handleSseStream(e,I,l){if(!e)return;let{onresumptiontoken:n,replayMessageId:c}=I,a;(async()=>{var r,o,d,i;try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new sq).getReader();for(;;){let{value:p,done:Z}=await h.read();if(Z)break;if(p.id&&(a=p.id,n?.(p.id)),!p.event||p.event==="message")try{let u=aV.parse(JSON.parse(p.data));c!==void 0&&F9(u)&&(u.id=c),(r=this.onmessage)===null||r===void 0||r.call(this,u)}catch(u){(o=this.onerror)===null||o===void 0||o.call(this,u)}}}catch(h){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${h}`)),l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:c},0)}catch(p){(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new eo("No auth provider");if(await hV(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo("Failed to authorize")}async close(){var e,I;(e=this._abortController)===null||e===void 0||e.abort(),(I=this.onclose)===null||I===void 0||I.call(this)}async send(e,I){var l,n,c,a;try{let{resumptionToken:s,onresumptiontoken:r}=I||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:a6(e)?e.id:void 0}).catch(N=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,N)});return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let d={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(l=this._abortController)===null||l===void 0?void 0:l.signal},i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,d),h=i.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=Zx(i),await hV(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new eo;return this.send(e)}let N=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${N}`)}if(i.status===202){AOe(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(N=>{var Y;return(Y=this.onerror)===null||Y===void 0?void 0:Y.call(this,N)});return}let Z=(Array.isArray(e)?e:[e]).filter(N=>"method"in N&&"id"in N&&N.id!==void 0).length>0,u=i.headers.get("content-type");if(Z)if(u?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:r},!1);else if(u?.includes("application/json")){let N=await i.json(),Y=Array.isArray(N)?N.map(y=>aV.parse(y)):[aV.parse(N)];for(let y of Y)(c=this.onmessage)===null||c===void 0||c.call(this,y)}else throw new ux(-1,`Unexpected content type: ${u}`)}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}get sessionId(){return this._sessionId}async terminateSession(){var e,I,l;if(this._sessionId)try{let n=await this._commonHeaders(),c={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((I=this._fetch)!==null&&I!==void 0?I:fetch)(this._url,c);if(!a.ok&&a.status!==405)throw new ux(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(n){throw(l=this.onerror)===null||l===void 0||l.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}};G();var Gq=class{constructor(e){this.server=e}onmessage;onerror;onclose;serverTransport;closed=!1;async start(){if(this.closed)throw new Error("Transport is closed");this.serverTransport=new dpe(this),await this.server.connect(this.serverTransport)}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.serverTransport?.onmessage?.(e)}catch(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}receive(e){this.closed||this.onmessage?.(e)}async close(){this.closed||(this.closed=!0,await this.serverTransport?.close(),this.onclose?.())}},dpe=class{constructor(e){this.clientTransport=e}onmessage;onerror;onclose;closed=!1;async start(){}async send(e){if(this.closed)throw new Error("Transport is closed");setImmediate(()=>{try{this.clientTransport.receive(e)}catch(I){this.onerror?.(I instanceof Error?I:new Error(String(I)))}})}async close(){this.closed||(this.closed=!0,this.onclose?.())}};var oq=class{createTransport(e){switch(e.type){case"stdio":{let I=new cq({command:e.command,args:e.args,env:e.env,stderr:e.stderr?"pipe":void 0});return I.stderr?.pipe(e.stderr),I}case"http":return new rq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"sse":return new tq(new URL(e.url),{requestInit:{headers:e.headers||{}}});case"memory":return new Gq(e.server);default:throw new Error(`Unsupported transport type: ${e.type}`)}}};G();var cF="blackbird-mcp-server",TE="github-mcp-server",ipe="playwright";function jE(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function dq(t){return t.type?.toLowerCase()==="http"}function iq(t){return t.type?.toLowerCase()==="sse"}function Wx(t){return t.type?.toLowerCase()==="memory"}var bpe=class extends rTI{constructor(I,l){super({decodeStrings:!1});this.serverName=I;this.logger=l}_write(I,l,n){try{let c=I.toString();this.logger.log(`[mcp server ${this.serverName} stderr] ${c}`),n()}catch(c){n(c instanceof Error?c:new Error(String(c)))}}},bq=class{constructor(e,I=new P6,l=new oq){this.logger=e;this.clientFactory=I;this.transportFactory=l}clients={};transports={};async startLocalMcpClient(e,I,l,n){this.logger.log(`Starting MCP client for ${e} with command: ${l} and args: ${n}`);let c=new bpe(e,this.logger),a={type:"stdio",command:l,args:n,env:{...I,PATH:process.env.PATH},stderr:c},s=this.transportFactory.createTransport(a);await this.setupAndConnectClient(e,s)}async startHttpMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"http",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startSseMcpClient(e,I){this.logger.log(`Starting remote MCP client for ${e} with url: ${I.url}`);let l={type:"sse",url:I.url,headers:I.headers},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async startInMemoryMcpClient(e,I){this.logger.log(`Starting in-memory MCP client for ${e}`);let l={type:"memory",server:I},n=this.transportFactory.createTransport(l);await this.setupAndConnectClient(e,n)}async setupAndConnectClient(e,I){this.transports[e]=I,I.onclose=()=>{this.logger.log(`MCP transport for ${e} closed`),delete this.transports[e]},this.logger.log(`Creating MCP client for ${e}...`);let l=this.clientFactory.createClient({name:"github-copilot-developer",version:"1.0.0"},{capabilities:{experimental:void 0,roots:void 0,sampling:void 0}}),n=Date.now();this.logger.log(`Connecting MCP client for ${e}...`),await l.connect(I),l.onclose=()=>{this.logger.log(`MCP client for ${e} closed`),delete this.clients[e]},l.onerror=c=>{this.logger.error(`MCP client for ${e} errored ${c}`)},this.logger.log(`MCP client for ${e} connected, took ${Date.now()-n}ms`),this.clients[e]=l}async getTools(e,I){let l={};for(let[n,c]of Object.entries(this.clients)){let a=[];try{this.logger.log(`Fetching tools from client: ${n}`);let s=await c.listTools(),r=e?.mcpServers[n].tools,o=e?.mcpServers[n].filterMapping;for(let i of s.tools){if(i.name==="get_copilot_space")continue;if(!(r?.includes("*")||r?.includes(i.name))){this.logger.log(`Tool ${i.name} is not in the allowed list for client: ${n}`);continue}let p=jP(n,i.name),Z=`${n}-${i.name}`,u;typeof o=="string"?u=zie(o):u=zie(o?.[i.name]??"hidden_characters"),l[`${n}/${i.name}`]={name:Z,title:i.title??i.annotations?.title??i.name,description:i.description??Z,input_schema:i.inputSchema,readOnly:i.annotations?.readOnlyHint,safeForTelemetry:{name:!!(e?.mcpServers[n].isDefaultServer||p),inputsNames:!!e?.mcpServers[n].isDefaultServer},filterMode:u},a.push(i.name),this.logger.log(`Tool ${i.name} added to tools list for client: ${n}`)}this.logger.log(`Successfully retrieved ${a.length} tools from client: ${n}`);let d=c.getServerVersion();await this.logServerSuccessWithTools(n,a,d,I)}catch(s){this.logger.error(`Failed to get tools from client: ${n} ${s}`)}}return this.logger.log(`All tools retrieved: ${JSON.stringify(l,null,2)}`),l}async logServerSuccessWithTools(e,I,l,n){if(e!=cF&&n)try{let c=I.map(r=>`- ${r}`).join(`
|
|
1346
1346
|
`),s=`MCP server started successfully${l?` (version ${l.version})`:""} with ${I.length} ${I.length===1?"tool":"tools"} - for the full output, see the verbose logs
|
|
1347
1347
|
|
|
1348
|
-
${c}`;await n.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};G();var mpe={mcpServers:{}},mq=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let I=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),mpe;if(this.logger.log("User-provided MCPs are enabled, checking for environment variable"),!this.mcpEnvConfig)return this.logger.log("No user-provided MCP servers found"),mpe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let I in e.mcpServers)e.mcpServers[I].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),mpe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){this.logger.log("Using default remote GitHub MCP server configuration");let l="repos,issues,users,pull_requests,code_security,secret_protection,actions";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[TE]=c}configureLocalGitHubMcp(e){if(e.mcpServers[TE]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[TE]??{};jE(I)&&!I.command&&(e.mcpServers[TE]={...I,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let I={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[TE]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[ipe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(l=>l.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let I={command:"npx",args:[...Fbe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[ipe]=I}}configureBlackbirdMcp(e,I){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,I):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,I){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${I.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let n=[];I.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${I.blackbird?.mode}`);let c={command:`${l}/blackbird/mcp`,args:["serve","--index",`${l}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:n,isDefaultServer:!0};e.mcpServers[cF]=c}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:I,isDefaultServer:!0};e.mcpServers[cF]=l}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(l["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:I,isDefaultServer:!0};e.mcpServers[cF]=n}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return jE(e)||dq(e)||iq(e)||Wx(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!jE(I)&&!Wx(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?jE(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(dq(I)||iq(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):Wx(I)&&!this.isValidInMemoryServerConfig(I)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,I){try{let l=this.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=this.resolveRemoteServerConfig(I);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let n=this.buildEnvironment(l),c=this.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args,l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let a=l+2;a<I.length;a++)c.push(I[a]);for(let a=0;a<l;a++)c.push(I[a]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)for(let[l,n]of Object.entries(e.env)){let c=n.trim();process.env[c]!==void 0&&(I[l]=process.env[c])}return I}resolveLocalServerConfig(e,I){let l=this.resolveString(e.command,I),n=this.resolveArray(e.args,I);return{...e,command:l,args:n}}resolveString(e,I){return I?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(l,n,c,a)=>{let r=I[n||a];return r!==void 0?r:c!==void 0?c:l}):e}resolveArray(e,I){return e?I?e.map(l=>this.resolveString(l,I)):e:[]}resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let a=this.resolveArray([c],I);l[n]=a[0]}return l}async processServers(e){if(!e)throw new Error("No servers to process");let I=Object.entries(e.mcpServers).map(([l,n])=>this.processServer(l,n));await Promise.all(I)}async processServer(e,I){if(!this.validateServerConfig(e,I)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{jE(I)?await this.processLocalServer(e,I):dq(I)&&this.remoteEnabled?await this.processHttpServer(e,I):iq(I)&&this.remoteEnabled?await this.processSseServer(e,I):Wx(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==cF&&await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var hq=class{constructor(e,I,l){this.logger=e;let n;if(typeof I=="string"){if(n=JSON.parse(I),typeof n!="object")throw new Error("Invalid MCP configuration: must be an object");if(n===null||!("mcpServers"in n)||typeof n.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=n}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new bq(this.logger),this.processor=new mq(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,I,l){if(!this.allTools){await this.startServers();let n=new W9(e,I,l),c=[];for(let a of Object.keys(this.registry.clients)){let s=await n.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});c.push(...s)}this.allTools=c}return this.allTools}getConfig(){return this.config}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.allTools=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.allTools=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};G();var DDe=Qn(jDe(),1);async function IDI(t={}){let e=await $pe();return Ppe((0,DDe.default)({},e,t))}async function KDe(t={}){if(Cx())throw new Error("Settings have already been initialized");return IDI(t)}G();async function pV(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let a=await c(e);a&&(l=!0,n={...n,...a})}catch(a){I.error(`Hook execution failed: ${a}`)}return l?n:void 0}G();var qE=class{sessionId;startTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];constructor({sessionId:e,startTime:I,logger:l}={}){this.sessionId=e||Cb(),this.startTime=I||new Date,this.logger=l||new ni}static fromEvents({events:e,logger:I}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({sessionId:l.data.sessionId,startTime:new Date(l.data.startTime),logger:I||new ni});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let a=e[c];n.events.push(a),n.processEventForState(a)}return n}addEvent(e){let I=e.id||Cb(),l=e.timestamp||new Date().toISOString(),n=e.parentId!==void 0?e.parentId:this.getLastEventId(),c={...e,id:I,timestamp:l,parentId:n};this.events.push(c),this.processEventForState(c),this.notifyEventCallbacks(c)}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let I=this.eventCallbacks.indexOf(e);I>-1&&this.eventCallbacks.splice(I,1)}}get chatMessages(){return this._chatMessages}get selectedModel(){return this._selectedModel}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getChatContextMessages(){return this._chatMessages.filter(e=>e.role!=="system")}getSystemContextMessages(){return this._chatMessages.filter(e=>e.role==="system")}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":this._chatMessages.push({role:"user",content:e.data.content});break;case"assistant.message":{let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.resume":case"session.error":case"session.info":case"session.import_legacy":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"abort":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}notifyEventCallbacks(e){for(let I of this.eventCallbacks)try{I(e)}catch(l){this.logger.error(`Error in event callback: ${l instanceof Error?l.message:String(l)}`)}}};var yq=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new ni,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new qE}async*query(e){let I=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new hq(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(Ze){this.logger.error(`Failed to initialize MCP host: ${Ze}`)}let n={timestamp:Date.now(),cwd:this.workingDir,prompt:e},a=(await pV(this.options.hooks?.userPromptSubmitted,n,this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:a}});let r=new pF().setProblemStatement(a).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-sdk-unknown").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();qpe();let o=await KDe(r),d=o.service?.agent?.model,i=Lbe(d),h=i.agent,p=i.model?{model:i.model}:void 0,Z=TGe(o,this.logger,h,p),u={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:void 0,permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:process.platform==="win32"?Hi.powerShell:Hi.bash},N=await tOe(u,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,u.permissions)}catch(Ze){this.logger.error(`Failed to get MCP tools: ${Ze}`)}let y=[...N,...Y],Q=this.applyToolFiltering(y,this.options.allowedTools,this.options.disabledTools),A=await ZUe(this.workingDir),H={...(nOe()["sweagent-capi"]?.["claude-sonnet-4"]??lOe()).supports,reasoning:!0},v=await fSe(A.found?A.gitRoot:"",vke(),this.workingDir,{},H,u,Q,void 0),ce=this.session.chatMessages.slice(0,-1),ye={role:"user",content:zSe(a,H)},Xe=[...ce,ye],He={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e};await pV(this.options.hooks?.sessionStart,He,this.logger);let ie=Z.getCompletionWithTools(v,Xe,Q,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new hE(this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let Ze of ie){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let nI=await this.translateEvent(Ze,I);for(let Je of nI)Je.type==="message"&&Je.role==="assistant"&&this.session.addEvent({type:"assistant.message",data:{messageId:`msg-${Date.now()}`,content:Je.content}}),yield Je}yield{type:"complete"}}catch(n){let c={timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:n instanceof Error?n:new Error(String(n))};await pV(this.options.hooks?.sessionEnd,c,this.logger),yield{type:"error",error:n instanceof Error?n:new Error(String(n))}}finally{let n={timestamp:Date.now(),cwd:this.workingDir,reason:"complete"};if(await pV(this.options.hooks?.sessionEnd,n,this.logger),l)try{await l.stopServers(),this.logger.log("MCP host stopped successfully")}catch(c){this.logger.error(`Error stopping MCP host: ${c}`)}}}buildAgentModelString(){switch(this.options.modelProvider.type){case"openai":return`openai:${this.options.modelProvider.model}`;case"anthropic":return`anthropic:${this.options.modelProvider.model}`;case"copilot":return`capi:${this.options.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.options.modelProvider.type}`)}}applyToolFiltering(e,I,l){let n=e;return I&&I.length>0&&(n=n.filter(c=>I.includes(c.name))),l&&l.length>0&&(n=n.filter(c=>!l.includes(c.name))),n}async translateEvent(e,I){switch(e.kind){case"message":{if(KP(e)&&e.message.content)return[{type:"message",content:typeof e.message.content=="string"?e.message.content:"",role:"assistant"}];if(PSe(e)){let l=[];for(let n of e.message.tool_calls){let c=gA(n.function.arguments);I.set(n.id,n.function.name);let a={timestamp:Date.now(),cwd:this.workingDir,toolName:n.function.name,toolArgs:c},r=(await pV(this.options.hooks?.preToolUse,a,this.logger))?.modifiedArgs??c;l.push({type:"tool_use",toolName:n.function.name,args:r,toolCallId:n.id})}return l}return[]}case"response":return[];case"model_call_failure":{let l=new Error(e.modelCall?.error||"Model call failed"),n={timestamp:Date.now(),cwd:this.workingDir,error:l,errorContext:"model_call",recoverable:!0};return await pV(this.options.hooks?.errorOccurred,n,this.logger),[{type:"error",error:l}]}case"tool_execution":{let l=I.get(e.toolCallId)||"unknown",n={timestamp:Date.now(),cwd:this.workingDir,toolName:l,toolArgs:{},toolResult:e.toolResult},a=(await pV(this.options.hooks?.postToolUse,n,this.logger))?.modifiedResult??e.toolResult;return[{type:"tool_result",toolName:l,result:a,toolCallId:e.toolCallId}]}default:return[]}}};G();G();var Fpe=class{loggers;constructor(e){this.loggers=e}isDebug(){return this.loggers.some(e=>e.isDebug())}debug(e){this.loggers.forEach(I=>I.debug(e))}log(e){this.loggers.forEach(I=>I.log(e))}info(e){this.loggers.forEach(I=>I.info(e))}notice(e){this.loggers.forEach(I=>I.notice(e))}warning(e){this.loggers.forEach(I=>I.warning(e))}error(e){this.loggers.forEach(I=>I.error(e))}startGroup(e,I){this.loggers.forEach(l=>l.startGroup(e,I))}endGroup(e){this.loggers.forEach(I=>I.endGroup(e))}};G();import{appendFile as tDI,access as lDI,mkdir as nDI}from"fs/promises";import{constants as cDI}from"fs";import{dirname as aDI}from"path";var gpe=class extends ap{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=sDI(aDI(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(I).toString())}notice(I){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(I).toString())}warning(I){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(I).toString())}error(I){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(I).toString())}startGroup(I,l){super.shouldLog(l||4)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||4)&&this.write("END-GROUP","")}write(I,l){let c=`${new Date().toISOString()} [${I}] ${l}
|
|
1348
|
+
${c}`;await n.logMCPSetup(e,s),this.logger.log(`Updated session log for ${e} with ${I.length} tools`)}catch(c){this.logger.error(`Failed to update session log for ${e}: ${c}`)}}};G();var mpe={mcpServers:{}},mq=class{constructor(e,I,l){this.logger=e;this.registry=I;this.remoteEnabled=l?.remoteEnabled??!1,this.mcp3pEnabled=l?.mcp3pEnabled??!1,this.blackbirdMetisIndexEnabled=l?.blackbirdMetisIndexEnabled??!1,this.sessionClient=l?.sessionClient,this.mcpEnvConfig=void 0}remoteEnabled;mcp3pEnabled;blackbirdMetisIndexEnabled;mcpEnvConfig;sessionClient;ReadMcpConfigFromEnv(e){this.mcpEnvConfig=process.env.GITHUB_COPILOT_MCP_JSON,this.mcp3pEnabled=process.env.GITHUB_COPILOT_3P_MCP_ENABLED==="true",this.remoteEnabled=process.env.GITHUB_COPILOT_REMOTE_MCP_ENABLED==="true",this.blackbirdMetisIndexEnabled=process.env.BLACKBIRD_METIS_INDEX_ENABLED==="true";let I=this.validateEnvConfig();return process.env.GITHUB_COPILOT_CLI_MODE==="true"?this.logger.log("CLI mode detected - skipping default MCP servers"):(this.logger.log("Adding default MCP servers to configuration"),this.configureBlackbirdMcp(I,e),this.configureGitHubMcp(I,e),this.configurePlaywrightMcp(I)),I}validateEnvConfig(){if(!this.mcp3pEnabled)return this.logger.log("User-provided MCPs are disabled"),mpe;if(this.logger.log("User-provided MCPs are enabled, checking for environment variable"),!this.mcpEnvConfig)return this.logger.log("No user-provided MCP servers found"),mpe;try{let e=JSON.parse(this.mcpEnvConfig);if(!e.mcpServers)throw new Error("User-provided config had incorrect format. Missing 'mcpServers' property.");for(let I in e.mcpServers)e.mcpServers[I].isDefaultServer=!1;return e}catch(e){return this.logger.error(`Warning: User-provided MCP servers were defined but invalid: ${e}`),mpe}}configureGitHubMcp(e,I){this.remoteEnabled?this.configureRemoteGitHubMcp(e,I):this.configureLocalGitHubMcp(e)}configureRemoteGitHubMcp(e,I){this.logger.log("Using default remote GitHub MCP server configuration");let l="repos,issues,users,pull_requests,code_security,secret_protection,actions";process.env.COPILOT_MCP_COPILOT_SPACES_ENABLED==="true"&&(this.logger.log("Enabling Copilot Spaces in GitHub MCP server configuration"),l=l+",copilot_spaces");let n={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":l,"X-MCP-Host":"github-coding-agent","X-Initiator":"agent"};I&&I.api?.copilot?.integrationId&&(n["Copilot-Integration-Id"]=I.api.copilot.integrationId),process.env.GITHUB_COPILOT_INTERACTION_ID&&(n["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let c={type:"http",url:this.getCapiMcpUrl(),headers:n,tools:["*"],isDefaultServer:!0,filterMapping:{get_issue:"markdown",get_issue_comments:"markdown",get_pull_request:"markdown",get_pull_request_comments:"markdown",get_pull_request_reviews:"markdown"}};e.mcpServers[TE]=c}configureLocalGitHubMcp(e){if(e.mcpServers[TE]){this.logger.log("Using user-provided GitHub MCP server configuration");let I=e.mcpServers[TE]??{};jE(I)&&!I.command&&(e.mcpServers[TE]={...I,command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",isDefaultServer:!0},this.logger.log("Added default command to user-provided GitHub MCP server configuration"))}else{this.logger.log("Using default local GitHub MCP server configuration");let I={command:"./copilot-developer-action-main/github-mcp-server/github-mcp-server",args:["stdio","--read-only"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",GITHUB_HOST:"GITHUB_SERVER_URL"},tools:["*"],isDefaultServer:!0};e.mcpServers[TE]=I}}configurePlaywrightMcp(e){if(!e.mcpServers[ipe]){if((process.env.COPILOT_FEATURE_FLAGS??"").split(",").map(l=>l.trim()).includes("copilot_swe_agent_playwright_use_firewall")){this.logger.log("Playwright MCP server is configured to use the firewall, skipping launch.");return}this.logger.log("Enabling Playwright MCP server");let I={command:"npx",args:[...Fbe,"--allowed-origins","localhost;localhost:*;127.0.0.1;127.0.0.1:*"],tools:["*"],isDefaultServer:!0};e.mcpServers[ipe]=I}}configureBlackbirdMcp(e,I){this.remoteEnabled?this.configureRemoteBlackbirdMcp(e):this.blackbirdMetisIndexEnabled?this.configureLocalMetisBlackbirdMCP(e,I):this.configureLocalBlackbirdMcp(e)}configureLocalMetisBlackbirdMCP(e,I){this.logger.log("Using local Metis Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${I.blackbird?.mode}`);let l=process.env.AGENT_DIR||"/agent";this.logger.log(`Using agent directory: ${l}`);let n=[];I.blackbird?.mode==="tool"&&(n=["*"]),this.logger.log(`Using blackbird Metis server: ${I.blackbird?.mode}`);let c={command:`${l}/blackbird/mcp`,args:["serve","--index",`${l}/blackbird/metis`],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",COPILOT_API_HMAC_KEY:"CAPI_HMAC_KEY",MODEL_BASED_RETRIEVAL_TOKEN:"BLACKBIRD_AUTH_MODEL_BASED_RETRIEVAL_TOKEN",METIS_API_KEY:"BLACKBIRD_AUTH_METIS_API_KEY"},tools:n,isDefaultServer:!0};e.mcpServers[cF]=c}configureLocalBlackbirdMcp(e){this.logger.log("Using local Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={command:"./copilot-developer-action-main/blackbird-mcp-server/blackbird-mcp-server",args:["stdio"],env:{GITHUB_PERSONAL_ACCESS_TOKEN:"GITHUB_PERSONAL_ACCESS_TOKEN",CAPI_HOST:"COPILOT_API_URL"},tools:I,isDefaultServer:!0};e.mcpServers[cF]=l}configureRemoteBlackbirdMcp(e){this.logger.log("Using remote Blackbird MCP server configuration"),this.logger.log(`Using blackbird mode: ${process.env.BLACKBIRD_MODE}`);let I=[];process.env.BLACKBIRD_MODE==="tool"&&(I=["*"]);let l={Authorization:"Bearer "+process.env.GITHUB_PERSONAL_ACCESS_TOKEN,"X-MCP-Toolsets":"search_agent","X-MCP-Host":"github-coding-agent"};process.env.GITHUB_COPILOT_INTERACTION_ID&&(l["X-Interaction-Id"]=process.env.GITHUB_COPILOT_INTERACTION_ID);let n={type:"http",url:this.getCapiMcpUrl(),headers:l,tools:I,isDefaultServer:!0};e.mcpServers[cF]=n}getCapiMcpUrl(){return process.env.COPILOT_API_URL?new URL("/mcp/readonly",process.env.COPILOT_API_URL).toString():"https://api.githubcopilot.com/mcp/readonly"}isValidServerType(e){return jE(e)||dq(e)||iq(e)||Wx(e)}isValidLocalServerConfig(e){return e.command!==void 0&&e.command.trim()!==""&&Array.isArray(e.args)}isValidRemoteServerConfig(e){return e.url!==void 0&&e.url.trim()!==""}isValidInMemoryServerConfig(e){return e.serverInstance!==void 0&&typeof e.serverInstance=="object"}validateServerConfig(e,I){return this.remoteEnabled&&!this.isValidServerType(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", "HTTP", "SSE", or "Memory" are supported.`),!1):!this.remoteEnabled&&!jE(I)&&!Wx(I)?(this.logger.error(`Unsupported server type "${I.type}" for server "${e}". Only "Local", "STDIO", or "Memory" are supported.`),!1):I.tools?jE(I)&&!this.isValidLocalServerConfig(I)?(this.logger.error(`Invalid local server configuration for "${e}". Please ensure 'command' and 'args' are provided.`),!1):(dq(I)||iq(I))&&!this.isValidRemoteServerConfig(I)?(this.logger.error(`Invalid remote server configuration for "${e}". Please ensure 'url' is provided.`),!1):Wx(I)&&!this.isValidInMemoryServerConfig(I)?(this.logger.error(`Invalid in-memory server configuration for "${e}". Please ensure 'serverInstance' is provided and is an instance of MCPServer.`),!1):!0:(this.logger.error(`No tools specified for server "${e}". Please provide a list of tools or "*" to include all tools.`),!1)}async processHttpServer(e,I){try{let l=this.resolveHeaders(I.headers,process.env),n={...I,headers:l};await this.registry.startHttpMcpClient(e,n),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}async processSseServer(e,I){try{let l=this.resolveRemoteServerConfig(I);await this.registry.startSseMcpClient(e,l),this.logger.log(`Started MCP client for remote server ${e}`)}catch(l){throw this.logger.error(`Failed to start MCP client for remote server ${e}: ${l}`),l}}resolveRemoteServerConfig(e){return e.url=this.resolveString(e.url,process.env),e.headers=this.resolveHeaders(e.headers,process.env),{...e,url:e.url,headers:e.headers}}async processInMemoryServer(e,I){try{await this.registry.startInMemoryMcpClient(e,I.serverInstance),this.logger.log(`Started in-memory MCP client for ${e}`)}catch(l){throw this.logger.error(`Failed to start in-memory MCP client for ${e}: ${l}`),l}}async processLocalServer(e,I){let l={...I};if(I.command==="python")try{l=await this.convertPythonToPipx(l)}catch(a){this.logger.error(`Failed to handle Python module for ${e}: ${a}`)}let n=this.buildEnvironment(l),c=this.resolveLocalServerConfig(l,n);this.logger.log(`Starting MCP client for ${e} with command: ${c.command} and args: ${c.args}`);try{await this.registry.startLocalMcpClient(e,n,c.command,c.args),this.logger.log(`Started MCP client for ${e}`)}catch(a){throw this.logger.error(`Failed to start MCP client for ${e}: ${a}`),a}}convertPythonToPipx(e){if(!e||!e.args||e.args.length===0)return e;let I=e.args,l=I.indexOf("-m");if(l===-1||l===I.length-1)throw new Error("Python command with -m flag must specify a module");let n=I[l+1];this.logger.log(`Converting Python module: ${n} to pipx command`);let c=["run",n];for(let a=l+2;a<I.length;a++)c.push(I[a]);for(let a=0;a<l;a++)c.push(I[a]);return{...e,command:"pipx",args:c}}buildEnvironment(e){let I={};if(e.env)for(let[l,n]of Object.entries(e.env)){let c=n.trim();process.env[c]!==void 0&&(I[l]=process.env[c])}return I}resolveLocalServerConfig(e,I){let l=this.resolveString(e.command,I),n=this.resolveArray(e.args,I);return{...e,command:l,args:n}}resolveString(e,I){return I?e.replace(/\$(?:\{([A-Z0-9_]+)(?::-(.*?))?\}|([A-Z0-9_]+))/g,(l,n,c,a)=>{let r=I[n||a];return r!==void 0?r:c!==void 0?c:l}):e}resolveArray(e,I){return e?I?e.map(l=>this.resolveString(l,I)):e:[]}resolveHeaders(e,I){if(!e)return{};if(!I)return e;let l={};for(let[n,c]of Object.entries(e)){let a=this.resolveArray([c],I);l[n]=a[0]}return l}async processServers(e){if(!e)throw new Error("No servers to process");let I=Object.entries(e.mcpServers).map(([l,n])=>this.processServer(l,n));await Promise.all(I)}async processServer(e,I){if(!this.validateServerConfig(e,I)){this.logger.error(`Skipping server "${e}" due to invalid configuration.`);return}try{jE(I)?await this.processLocalServer(e,I):dq(I)&&this.remoteEnabled?await this.processHttpServer(e,I):iq(I)&&this.remoteEnabled?await this.processSseServer(e,I):Wx(I)&&await this.processInMemoryServer(e,I)}catch(l){e!==cF&&await this.logServerFailure(e,l)}}async logServerFailure(e,I){if(this.sessionClient)try{await this.sessionClient.logMCPSetup(e,`<error>MCP server failed to start: ${I.message} - for the full output, see the verbose logs</error>`)}catch(l){this.logger.error(`Failed to log failure for MCP Server '${e}': '${l}'`)}}};var hq=class{constructor(e,I,l){this.logger=e;let n;if(typeof I=="string"){if(n=JSON.parse(I),typeof n!="object")throw new Error("Invalid MCP configuration: must be an object");if(n===null||!("mcpServers"in n)||typeof n.mcpServers!="object")throw new Error("Invalid MCP configuration: missing or invalid mcpServers property");this.config=n}else this.config=I;this.disabledServers=new Set(l||[]),this.registry=new bq(this.logger),this.processor=new mq(this.logger,this.registry,{mcp3pEnabled:!0,remoteEnabled:!0})}registry;processor;config;startServersPromise=null;allTools=null;disabledServers;async startServers(){return this.startServersPromise||(this.startServersPromise=this.processServersWithExtensions()),this.startServersPromise}async injectDefaultServers(e){}async processServersWithExtensions(){await this.injectDefaultServers(this.config);let e;if(this.disabledServers.size>0){let I={};for(let[l,n]of Object.entries(this.config.mcpServers))this.disabledServers.has(l)?this.logger.log(`Skipping disabled MCP server: ${l}`):I[l]=n;e={...this.config,mcpServers:I}}else e=this.config;return this.processor.processServers(e)}async stopServers(){for(let[e,I]of Object.entries(this.registry.transports))try{await I.close()}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.startServersPromise=null,this.allTools=null}async getTools(e,I,l){if(!this.allTools){await this.startServers();let n=new W9(e,I,l),c=[];for(let a of Object.keys(this.registry.clients)){let s=await n.loadTools({mcpClient:this.registry.clients[a],clientName:a,tools:this.config.mcpServers[a]?.tools||["*"],filterMapping:this.config.mcpServers[a]?.filterMapping||"hidden_characters"});c.push(...s)}this.allTools=c}return this.allTools}getConfig(){return this.config}async startServer(e,I){await this.startServers(),this.config.mcpServers[e]=I,await this.processor.processServer(e,I),this.allTools=null}async stopServer(e){let I=this.registry.transports[e];if(I)try{await I.close(),delete this.registry.transports[e]}catch(l){this.logger.error(`Error closing transport for ${e}: ${l}`)}this.registry.clients[e]&&delete this.registry.clients[e],this.allTools=null}async restartServer(e,I){this.isServerRunning(e)&&await this.stopServer(e),delete this.config.mcpServers[e],await this.startServer(e,I)}isServerRunning(e){return e in this.registry.transports&&e in this.registry.clients}isServerDisabled(e){return this.disabledServers.has(e)}async disableServer(e){if(this.disabledServers.has(e)){this.logger.log(`Server ${e} is already disabled`);return}this.disabledServers.add(e),this.logger.log(`Disabled server ${e} for this session`),this.isServerRunning(e)&&await this.stopServer(e),this.allTools=null}async enableServer(e){if(!this.disabledServers.has(e)){this.logger.log(`Server ${e} is not disabled`);return}this.disabledServers.delete(e),this.logger.log(`Enabled server ${e} for this session`);let I=this.getServerConfig(e);I?await this.startServer(e,I):await this.startBuiltInServer(e),this.allTools=null}async startBuiltInServer(e){}getServerConfig(e){return this.config.mcpServers[e]}};G();var DDe=Qn(jDe(),1);async function IDI(t={}){let e=await $pe();return Ppe((0,DDe.default)({},e,t))}async function KDe(t={}){if(Cx())throw new Error("Settings have already been initialized");return IDI(t)}G();async function pV(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let c of t)try{let a=await c(e);a&&(l=!0,n={...n,...a})}catch(a){I.error(`Hook execution failed: ${a}`)}return l?n:void 0}G();var qE=class{sessionId;startTime;events=[];_chatMessages=[];_selectedModel;logger;eventCallbacks=[];constructor({sessionId:e,startTime:I,logger:l}={}){this.sessionId=e||Cb(),this.startTime=I||new Date,this.logger=l||new ni}static fromEvents({events:e,logger:I}){if(e.length===0)throw new Error("Cannot create session from empty events array");let l=e[0];if(l.type!=="session.start")throw new Error("First event must be session.start");let n=new this({sessionId:l.data.sessionId,startTime:new Date(l.data.startTime),logger:I||new ni});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let c=1;c<e.length;c++){let a=e[c];n.events.push(a),n.processEventForState(a)}return n}addEvent(e){let I=e.id||Cb(),l=e.timestamp||new Date().toISOString(),n=e.parentId!==void 0?e.parentId:this.getLastEventId(),c={...e,id:I,timestamp:l,parentId:n};return this.events.push(c),this.processEventForState(c),this.notifyEventCallbacks(c),c}getEvents(){return this.events}onEvent(e){return this.eventCallbacks.push(e),()=>{let I=this.eventCallbacks.indexOf(e);I>-1&&this.eventCallbacks.splice(I,1)}}get chatMessages(){return this._chatMessages}get selectedModel(){return this._selectedModel}setSelectedModel(e){let I=this._selectedModel;this._selectedModel=e,this.addEvent({type:"session.model_change",data:{previousModel:I,newModel:e}})}getChatContextMessages(){return this._chatMessages.filter(e=>e.role!=="system")}getSystemContextMessages(){return this._chatMessages.filter(e=>e.role==="system")}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}processEventForState(e){switch(e.type){case"session.start":e.data.selectedModel&&(this._selectedModel=e.data.selectedModel);break;case"session.model_change":this._selectedModel=e.data.newModel;break;case"user.message":this._chatMessages.push({role:"user",content:e.data.content});break;case"assistant.message":{let I={role:"assistant",content:e.data.content||null};e.data.toolRequests&&e.data.toolRequests.length>0&&(I.tool_calls=e.data.toolRequests.map(l=>({id:l.toolCallId,type:"function",function:{name:l.name,arguments:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}))),this._chatMessages.push(I);break}case"tool.execution_complete":{this._chatMessages.push({role:"tool",tool_call_id:e.data.toolCallId,content:e.data.success?e.data.result?.content||"":e.data.error?.message||"Tool execution failed"});break}case"system.message":this._chatMessages.push({role:e.data.role,content:e.data.content,...e.data.name&&{name:e.data.name}});break;case"session.resume":case"session.error":case"session.info":case"session.import_legacy":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"abort":case"tool.execution_start":case"tool.execution_partial_result":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}notifyEventCallbacks(e){for(let I of this.eventCallbacks)try{I(e)}catch(l){this.logger.error(`Error in event callback: ${l instanceof Error?l.message:String(l)}`)}}};var yq=class{static name="Copilot";static description="Base Copilot Agent";options;logger;workingDir;session;constructor(e){this.options=e,this.logger=e.logger||new ni,this.workingDir=e.workingDirectory||process.cwd(),this.session=e.session||new qE}async*query(e){let I=new Map,l;try{if(this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0)try{l=new hq(this.logger,{mcpServers:this.options.mcpServers},this.options.disabledTools),await l.startServers()}catch(Ze){this.logger.error(`Failed to initialize MCP host: ${Ze}`)}let n={timestamp:Date.now(),cwd:this.workingDir,prompt:e},a=(await pV(this.options.hooks?.userPromptSubmitted,n,this.logger))?.modifiedPrompt??e;this.session.addEvent({type:"user.message",data:{content:a}});let r=new pF().setProblemStatement(a).setAgentModel(this.buildAgentModelString()).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.options.integrationId||"copilot-sdk-unknown").setCopilotHmacKey(this.options.hmacKey).setCopilotToken(this.options.copilotToken).build();qpe();let o=await KDe(r),d=o.service?.agent?.model,i=Lbe(d),h=i.agent,p=i.model?{model:i.model}:void 0,Z=TGe(o,this.logger,h,p),u={location:this.workingDir,timeout:3e4,requireReasoning:!0,toolPartialResultCallback:void 0,permissions:this.options.requestPermission?{requestRequired:!0,request:this.options.requestPermission}:{requestRequired:!1},shellConfig:process.platform==="win32"?Hi.powerShell:Hi.bash},N=await tOe(u,this.logger),Y=[];if(l)try{Y=await l.getTools(o,this.logger,u.permissions)}catch(Ze){this.logger.error(`Failed to get MCP tools: ${Ze}`)}let y=[...N,...Y],Q=this.applyToolFiltering(y,this.options.allowedTools,this.options.disabledTools),A=await ZUe(this.workingDir),H={...(nOe()["sweagent-capi"]?.["claude-sonnet-4"]??lOe()).supports,reasoning:!0},v=await fSe(A.found?A.gitRoot:"",vke(),this.workingDir,{},H,u,Q,void 0),ce=this.session.chatMessages.slice(0,-1),ye={role:"user",content:zSe(a,H)},Xe=[...ce,ye],He={timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e};await pV(this.options.hooks?.sessionStart,He,this.logger);let ie=Z.getCompletionWithTools(v,Xe,Q,{failIfInitialInputsTooLong:!1,processors:{preRequest:[new hE(this.logger)]},executeToolsInParallel:!1,abortSignal:this.options.abortController?.signal});for await(let Ze of ie){if(this.options.abortController?.signal.aborted){yield{type:"error",error:new Error("Operation was cancelled")};return}let nI=await this.translateEvent(Ze,I);for(let Je of nI)Je.type==="message"&&Je.role==="assistant"&&this.session.addEvent({type:"assistant.message",data:{messageId:`msg-${Date.now()}`,content:Je.content}}),yield Je}yield{type:"complete"}}catch(n){let c={timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:n instanceof Error?n:new Error(String(n))};await pV(this.options.hooks?.sessionEnd,c,this.logger),yield{type:"error",error:n instanceof Error?n:new Error(String(n))}}finally{let n={timestamp:Date.now(),cwd:this.workingDir,reason:"complete"};if(await pV(this.options.hooks?.sessionEnd,n,this.logger),l)try{await l.stopServers(),this.logger.log("MCP host stopped successfully")}catch(c){this.logger.error(`Error stopping MCP host: ${c}`)}}}buildAgentModelString(){switch(this.options.modelProvider.type){case"openai":return`openai:${this.options.modelProvider.model}`;case"anthropic":return`anthropic:${this.options.modelProvider.model}`;case"copilot":return`capi:${this.options.modelProvider.model}`;default:throw new Error(`Unsupported provider: ${this.options.modelProvider.type}`)}}applyToolFiltering(e,I,l){let n=e;return I&&I.length>0&&(n=n.filter(c=>I.includes(c.name))),l&&l.length>0&&(n=n.filter(c=>!l.includes(c.name))),n}async translateEvent(e,I){switch(e.kind){case"message":{if(KP(e)&&e.message.content)return[{type:"message",content:typeof e.message.content=="string"?e.message.content:"",role:"assistant"}];if(PSe(e)){let l=[];for(let n of e.message.tool_calls){let c=gA(n.function.arguments);I.set(n.id,n.function.name);let a={timestamp:Date.now(),cwd:this.workingDir,toolName:n.function.name,toolArgs:c},r=(await pV(this.options.hooks?.preToolUse,a,this.logger))?.modifiedArgs??c;l.push({type:"tool_use",toolName:n.function.name,args:r,toolCallId:n.id})}return l}return[]}case"response":return[];case"model_call_failure":{let l=new Error(e.modelCall?.error||"Model call failed"),n={timestamp:Date.now(),cwd:this.workingDir,error:l,errorContext:"model_call",recoverable:!0};return await pV(this.options.hooks?.errorOccurred,n,this.logger),[{type:"error",error:l}]}case"tool_execution":{let l=I.get(e.toolCallId)||"unknown",n={timestamp:Date.now(),cwd:this.workingDir,toolName:l,toolArgs:{},toolResult:e.toolResult},a=(await pV(this.options.hooks?.postToolUse,n,this.logger))?.modifiedResult??e.toolResult;return[{type:"tool_result",toolName:l,result:a,toolCallId:e.toolCallId}]}default:return[]}}};G();G();var Fpe=class{loggers;constructor(e){this.loggers=e}isDebug(){return this.loggers.some(e=>e.isDebug())}debug(e){this.loggers.forEach(I=>I.debug(e))}log(e){this.loggers.forEach(I=>I.log(e))}info(e){this.loggers.forEach(I=>I.info(e))}notice(e){this.loggers.forEach(I=>I.notice(e))}warning(e){this.loggers.forEach(I=>I.warning(e))}error(e){this.loggers.forEach(I=>I.error(e))}startGroup(e,I){this.loggers.forEach(l=>l.startGroup(e,I))}endGroup(e){this.loggers.forEach(I=>I.endGroup(e))}};G();import{appendFile as tDI,access as lDI,mkdir as nDI}from"fs/promises";import{constants as cDI}from"fs";import{dirname as aDI}from"path";var gpe=class extends ap{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=sDI(aDI(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(8)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(4)&&this.write("INFO",this.filterSecrets(I).toString())}notice(I){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(I).toString())}warning(I){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(I).toString())}error(I){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(I).toString())}startGroup(I,l){super.shouldLog(l||4)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||4)&&this.write("END-GROUP","")}write(I,l){let c=`${new Date().toISOString()} [${I}] ${l}
|
|
1349
1349
|
`;this.writeQueue=this.writeQueue.then(()=>this.performWrite(c)).catch(()=>{})}async performWrite(I){await tDI(this.filePath,I)}};async function sDI(t){try{await lDI(t,cDI.F_OK)}catch{await nDI(t,{recursive:!0})}}G();async function*Q8l(t){let{prompt:e,...I}=t;yield*new yq(I).query(e)}G();var PDe=class{sessions;logger;lastAccessedSessionId;constructor({logger:e}={}){this.sessions=new Map,this.logger=e||new ni}async createSession(){let e=new qE({logger:this.logger});return this.sessions.set(e.sessionId,e),this.lastAccessedSessionId=e.sessionId,e}async getSession(e){let I=this.sessions.get(e);return I&&(this.lastAccessedSessionId=e),I}async getLastSession(){if(this.lastAccessedSessionId){let l=this.sessions.get(this.lastAccessedSessionId);if(l)return l}let e=Array.from(this.sessions.values());if(e.length===0)return;e.sort((l,n)=>n.startTime.getTime()-l.startTime.getTime());let I=e[0];return this.lastAccessedSessionId=I.sessionId,I}async listSessions(){return Array.from(this.sessions.values()).map(e=>({sessionId:e.sessionId,startTime:e.startTime}))}async saveSession(e){}async deleteSession(e){this.sessions.delete(e.sessionId),this.lastAccessedSessionId===e.sessionId&&(this.lastAccessedSessionId=void 0)}};export{yq as Agent,ap as BaseLogger,Fpe as CompoundLogger,jV as ConsoleLogger,gpe as FileLogger,ni as NoopLogger,qE as Session,PDe as SessionManager,pV as executeHooks,I1 as isDebugEnvironment,Q8l as query};
|
|
1350
1350
|
/*! Bundled license information:
|
|
1351
1351
|
|