@github/copilot 0.0.371-0 → 0.0.371
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 +220 -220
- package/package.json +8 -8
- package/sdk/index.js +48 -48
package/sdk/index.js
CHANGED
|
@@ -601,21 +601,21 @@ ${n.join(`
|
|
|
601
601
|
`)}function lht(t){if(!t.trim())return"parameter must be a non-empty string."}function qwI(t){if(!N3.includes(t)&&!nht(t))return`ecosystem '${t}' is not supported. Supported ecosystems are: ${N3.join(", ")}.`}function oht(t){let e=[],I=lht(t.name);I&&e.push(`name: ${I}`);let l=lht(t.version);l&&e.push(`version: ${l}`);let n=qwI(t.ecosystem);return n&&e.push(`ecosystem: ${n}`),e}var N3,PwI,cht=m(()=>{"use strict";tae();ZS();N3=["actions","composer","erlang","go","maven","npm","nuget","other","pip","pub","rubygems","rust","swift"],PwI={npm_and_yarn:"npm",bun:"npm",bundler:"rubygems",pip:"pip",uv:"pip",maven:"maven",composer:"composer",go_modules:"go",github_actions:"actions",cargo:"rust",pub:"pub",swift:"swift",nuget:"nuget",gradle:"maven",hex:"erlang",other:"other"}});async function e1I({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=oht(l);if(n.length>0){let r=`Invalid parameters found for dependency ${l.name}: ${n.join(", ")}`;return{textResultForLlm:r,resultType:"failure",sessionLog:r,toolTelemetry:{}}}try{let r=e?uS(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=rht(r,e?.settings,$wI,void 0);I.push(...await aht(a,l))}catch(r){let a=`Error checking dependency ${l.name}: ${String(r)}`,s=r instanceof Error?r.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=sht(I);return{textResultForLlm:l,resultType:"success",sessionLog:l,toolTelemetry:{restrictedProperties:{vulnerableDeps:I.map(n=>`${n.name}@${n.version}`).join(", ")},metrics:{vulnerableDependencies:I.length}}}}}var _wI,iht,$wI,dht,sve=m(()=>{"use strict";KG();cht();_wI="gh-advisory-database",iht="copilot_swe_agent_validation_agent_dependencies",$wI="security agent",dht={name:_wI,description:`Security tool that checks the GitHub advisory DB for vulnerabilities in dependencies. Run this tool ALWAYS before adding new dependencies from these SUPPORTED ecosystems: ${N3.join(", ")}. For ANY other ecosystem (e.g., Haskell/Cabal, C++/vcpkg, Elixir/Hex, etc.), DO NOT call this tool - just proceed with adding the dependency. If you don't know the version number, 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'."},ecosystem:{type:"string",enum:N3,description:"The package ecosystem for the dependency. Must be one of the supported ecosystems. If the dependency's ecosystem is not in the list of supported ecosystems, DO NOT use this tool."}},required:["name","version","ecosystem"]}}},required:["dependencies"]},callback:e1I,safeForTelemetry:{name:!0,inputsNames:!1}}});function Ght(t,e){var I=Object.keys(t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);e&&(l=l.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),I.push.apply(I,l)}return I}function bht(t){for(var e=1;e<arguments.length;e++){var I=arguments[e]!=null?arguments[e]:{};e%2?Ght(Object(I),!0).forEach(function(l){t1I(t,l,I[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(I)):Ght(Object(I)).forEach(function(l){Object.defineProperty(t,l,Object.getOwnPropertyDescriptor(I,l))})}return t}function t1I(t,e,I){return e=I1I(e),e in t?Object.defineProperty(t,e,{value:I,enumerable:!0,configurable:!0,writable:!0}):t[e]=I,t}function I1I(t){var e=l1I(t,"string");return typeof e=="symbol"?e:String(e)}function l1I(t,e){if(typeof t!="object"||t===null)return t;var I=t[Symbol.toPrimitive];if(I!==void 0){var l=I.call(t,e||"default");if(typeof l!="object")return l;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function uht(t){return e.withOptions=I=>uht(bht(bht({},t),I)),e;function e(I,...l){let n=typeof I=="string"?[I]:I.raw,{escapeSpecialCharacters:r=Array.isArray(I),trimWhitespace:a=!0}=t,s="";for(let i=0;i<n.length;i++){let d=n[i];r&&(d=d.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),s+=d,i<l.length&&(s+=l[i])}let o=s.split(`
|
|
602
602
|
`),c=null;for(let i of o){let d=i.match(/^(\s+)\S+/);if(d){let G=d[1].length;c?c=Math.min(c,G):c=G}}if(c!==null){let i=c;s=o.map(d=>d[0]===" "||d[0]===" "?d.slice(i):d).join(`
|
|
603
603
|
`)}return a&&(s=s.trim()),r&&(s=s.replace(/\\n/g,`
|
|
604
|
-
`)),s}}var n1I,mht,hht=m(()=>{n1I=uht({}),mht=n1I});function lse(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function nse(t){return yj(t)||Vj(t)}function yj(t){return t.type?.toLowerCase()==="http"}function Vj(t){return t.type?.toLowerCase()==="sse"}function rse(t){return t.type?.toLowerCase()==="memory"}var Ise,ove,cve=m(()=>{"use strict";Ise="github-mcp-server",ove="playwright"});var Pht=g((Rj,g3)=>{var r1I=200,a1I="Expected a function",Wve="__lodash_hash_undefined__",bse=1,y3=2,Aht=1/0,Fht=9007199254740991,ase="[object Arguments]",Gve="[object Array]",wht="[object Boolean]",Qht="[object Date]",Eht="[object Error]",vht="[object Function]",s1I="[object GeneratorFunction]",sse="[object Map]",Xht="[object Number]",Y3="[object Object]",pht="[object Promise]",Hht="[object RegExp]",ose="[object Set]",Cht="[object String]",fht="[object Symbol]",bve="[object WeakMap]",Jht="[object ArrayBuffer]",cse="[object DataView]",o1I="[object Float32Array]",c1I="[object Float64Array]",i1I="[object Int8Array]",d1I="[object Int16Array]",G1I="[object Int32Array]",b1I="[object Uint8Array]",m1I="[object Uint8ClampedArray]",u1I="[object Uint16Array]",h1I="[object Uint32Array]",p1I=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Z1I=/^\w*$/,W1I=/^\./,N1I=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Y1I=/[\\^$.*+?()[\]{}|]/g,g1I=/\\(\\)?/g,y1I=/^\[object .+?Constructor\]$/,V1I=/^(?:0|[1-9]\d*)$/,da={};da[o1I]=da[c1I]=da[i1I]=da[d1I]=da[G1I]=da[b1I]=da[m1I]=da[u1I]=da[h1I]=!0;da[ase]=da[Gve]=da[Jht]=da[wht]=da[cse]=da[Qht]=da[Eht]=da[vht]=da[sse]=da[Xht]=da[Y3]=da[Hht]=da[ose]=da[Cht]=da[bve]=!1;var Lht=typeof global=="object"&&global&&global.Object===Object&&global,R1I=typeof self=="object"&&self&&self.Object===Object&&self,hA=Lht||R1I||Function("return this")(),kht=typeof Rj=="object"&&Rj&&!Rj.nodeType&&Rj,Zht=kht&&typeof g3=="object"&&g3&&!g3.nodeType&&g3,A1I=Zht&&Zht.exports===kht,Wht=A1I&&Lht.process,Nht=(function(){try{return Wht&&Wht.binding("util")}catch{}})(),Yht=Nht&&Nht.isTypedArray;function F1I(t,e){for(var I=-1,l=t?t.length:0;++I<l;)if(e(t[I],I,t))return!0;return!1}function w1I(t){return function(e){return e?.[t]}}function Q1I(t,e){for(var I=-1,l=Array(t);++I<t;)l[I]=e(I);return l}function E1I(t){return function(e){return t(e)}}function v1I(t,e){return t?.[e]}function mve(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}function X1I(t){var e=-1,I=Array(t.size);return t.forEach(function(l,n){I[++e]=[n,l]}),I}function H1I(t,e){return function(I){return t(e(I))}}function C1I(t){var e=-1,I=Array(t.size);return t.forEach(function(l){I[++e]=l}),I}var f1I=Array.prototype,J1I=Function.prototype,mse=Object.prototype,ive=hA["__core-js_shared__"],ght=(function(){var t=/[^.]+$/.exec(ive&&ive.keys&&ive.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})(),xht=J1I.toString,tg=mse.hasOwnProperty,V3=mse.toString,L1I=RegExp("^"+xht.call(tg).replace(Y1I,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),yht=hA.Symbol,Vht=hA.Uint8Array,k1I=mse.propertyIsEnumerable,x1I=f1I.splice,B1I=H1I(Object.keys,Object),uve=R3(hA,"DataView"),Aj=R3(hA,"Map"),hve=R3(hA,"Promise"),pve=R3(hA,"Set"),Zve=R3(hA,"WeakMap"),Fj=R3(Object,"create"),S1I=kE(uve),z1I=kE(Aj),U1I=kE(hve),O1I=kE(pve),M1I=kE(Zve),ise=yht?yht.prototype:void 0,dve=ise?ise.valueOf:void 0,Rht=ise?ise.toString:void 0;function JE(t){var e=-1,I=t?t.length:0;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function T1I(){this.__data__=Fj?Fj(null):{}}function j1I(t){return this.has(t)&&delete this.__data__[t]}function D1I(t){var e=this.__data__;if(Fj){var I=e[t];return I===Wve?void 0:I}return tg.call(e,t)?e[t]:void 0}function K1I(t){var e=this.__data__;return Fj?e[t]!==void 0:tg.call(e,t)}function P1I(t,e){var I=this.__data__;return I[t]=Fj&&e===void 0?Wve:e,this}JE.prototype.clear=T1I;JE.prototype.delete=j1I;JE.prototype.get=D1I;JE.prototype.has=K1I;JE.prototype.set=P1I;function Ig(t){var e=-1,I=t?t.length:0;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function q1I(){this.__data__=[]}function _1I(t){var e=this.__data__,I=use(e,t);if(I<0)return!1;var l=e.length-1;return I==l?e.pop():x1I.call(e,I,1),!0}function $1I(t){var e=this.__data__,I=use(e,t);return I<0?void 0:e[I][1]}function eQI(t){return use(this.__data__,t)>-1}function tQI(t,e){var I=this.__data__,l=use(I,t);return l<0?I.push([t,e]):I[l][1]=e,this}Ig.prototype.clear=q1I;Ig.prototype.delete=_1I;Ig.prototype.get=$1I;Ig.prototype.has=eQI;Ig.prototype.set=tQI;function lg(t){var e=-1,I=t?t.length:0;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function IQI(){this.__data__={hash:new JE,map:new(Aj||Ig),string:new JE}}function lQI(t){return hse(this,t).delete(t)}function nQI(t){return hse(this,t).get(t)}function rQI(t){return hse(this,t).has(t)}function aQI(t,e){return hse(this,t).set(t,e),this}lg.prototype.clear=IQI;lg.prototype.delete=lQI;lg.prototype.get=nQI;lg.prototype.has=rQI;lg.prototype.set=aQI;function dse(t){var e=-1,I=t?t.length:0;for(this.__data__=new lg;++e<I;)this.add(t[e])}function sQI(t){return this.__data__.set(t,Wve),this}function oQI(t){return this.__data__.has(t)}dse.prototype.add=dse.prototype.push=sQI;dse.prototype.has=oQI;function eg(t){this.__data__=new Ig(t)}function cQI(){this.__data__=new Ig}function iQI(t){return this.__data__.delete(t)}function dQI(t){return this.__data__.get(t)}function GQI(t){return this.__data__.has(t)}function bQI(t,e){var I=this.__data__;if(I instanceof Ig){var l=I.__data__;if(!Aj||l.length<r1I-1)return l.push([t,e]),this;I=this.__data__=new lg(l)}return I.set(t,e),this}eg.prototype.clear=cQI;eg.prototype.delete=iQI;eg.prototype.get=dQI;eg.prototype.has=GQI;eg.prototype.set=bQI;function mQI(t,e){var I=LE(t)||jht(t)?Q1I(t.length,String):[],l=I.length,n=!!l;for(var r in t)(e||tg.call(t,r))&&!(n&&(r=="length"||Uht(r,l)))&&I.push(r);return I}function use(t,e){for(var I=t.length;I--;)if(Tht(t[I][0],e))return I;return-1}var uQI=QQI();function hQI(t,e){return t&&uQI(t,e,Gse)}function Bht(t,e){e=pse(e,t)?[e]:Sht(e);for(var I=0,l=e.length;t!=null&&I<l;)t=t[Zse(e[I++])];return I&&I==l?t:void 0}function pQI(t){return V3.call(t)}function ZQI(t,e){return t!=null&&e in Object(t)}function Nve(t,e,I,l,n){return t===e?!0:t==null||e==null||!Wse(t)&&!Nse(e)?t!==t&&e!==e:WQI(t,e,Nve,I,l,n)}function WQI(t,e,I,l,n,r){var a=LE(t),s=LE(e),o=Gve,c=Gve;a||(o=uA(t),o=o==ase?Y3:o),s||(c=uA(e),c=c==ase?Y3:c);var i=o==Y3&&!mve(t),d=c==Y3&&!mve(e),G=o==c;if(G&&!i)return r||(r=new eg),a||xQI(t)?zht(t,e,I,l,n,r):EQI(t,e,o,I,l,n,r);if(!(n&y3)){var b=i&&tg.call(t,"__wrapped__"),u=d&&tg.call(e,"__wrapped__");if(b||u){var h=b?t.value():t,p=u?e.value():e;return r||(r=new eg),I(h,p,l,n,r)}}return G?(r||(r=new eg),vQI(t,e,I,l,n,r)):!1}function NQI(t,e,I,l){var n=I.length,r=n,a=!l;if(t==null)return!r;for(t=Object(t);n--;){var s=I[n];if(a&&s[2]?s[1]!==t[s[0]]:!(s[0]in t))return!1}for(;++n<r;){s=I[n];var o=s[0],c=t[o],i=s[1];if(a&&s[2]){if(c===void 0&&!(o in t))return!1}else{var d=new eg;if(l)var G=l(c,i,o,t,e,d);if(!(G===void 0?Nve(i,c,l,bse|y3,d):G))return!1}}return!0}function YQI(t){if(!Wse(t)||fQI(t))return!1;var e=Kht(t)||mve(t)?L1I:y1I;return e.test(kE(t))}function gQI(t){return Nse(t)&&gve(t.length)&&!!da[V3.call(t)]}function yQI(t){return typeof t=="function"?t:t==null?OQI:typeof t=="object"?LE(t)?AQI(t[0],t[1]):RQI(t):MQI(t)}function VQI(t){if(!JQI(t))return B1I(t);var e=[];for(var I in Object(t))tg.call(t,I)&&I!="constructor"&&e.push(I);return e}function RQI(t){var e=XQI(t);return e.length==1&&e[0][2]?Mht(e[0][0],e[0][1]):function(I){return I===t||NQI(I,t,e)}}function AQI(t,e){return pse(t)&&Oht(e)?Mht(Zse(t),e):function(I){var l=SQI(I,t);return l===void 0&&l===e?zQI(I,t):Nve(e,l,void 0,bse|y3)}}function FQI(t){return function(e){return Bht(e,t)}}function wQI(t){if(typeof t=="string")return t;if(yve(t))return Rht?Rht.call(t):"";var e=t+"";return e=="0"&&1/t==-Aht?"-0":e}function Sht(t){return LE(t)?t:LQI(t)}function QQI(t){return function(e,I,l){for(var n=-1,r=Object(e),a=l(e),s=a.length;s--;){var o=a[t?s:++n];if(I(r[o],o,r)===!1)break}return e}}function zht(t,e,I,l,n,r){var a=n&y3,s=t.length,o=e.length;if(s!=o&&!(a&&o>s))return!1;var c=r.get(t);if(c&&r.get(e))return c==e;var i=-1,d=!0,G=n&bse?new dse:void 0;for(r.set(t,e),r.set(e,t);++i<s;){var b=t[i],u=e[i];if(l)var h=a?l(u,b,i,e,t,r):l(b,u,i,t,e,r);if(h!==void 0){if(h)continue;d=!1;break}if(G){if(!F1I(e,function(p,W){if(!G.has(W)&&(b===p||I(b,p,l,n,r)))return G.add(W)})){d=!1;break}}else if(!(b===u||I(b,u,l,n,r))){d=!1;break}}return r.delete(t),r.delete(e),d}function EQI(t,e,I,l,n,r,a){switch(I){case cse:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case Jht:return!(t.byteLength!=e.byteLength||!l(new Vht(t),new Vht(e)));case wht:case Qht:case Xht:return Tht(+t,+e);case Eht:return t.name==e.name&&t.message==e.message;case Hht:case Cht:return t==e+"";case sse:var s=X1I;case ose:var o=r&y3;if(s||(s=C1I),t.size!=e.size&&!o)return!1;var c=a.get(t);if(c)return c==e;r|=bse,a.set(t,e);var i=zht(s(t),s(e),l,n,r,a);return a.delete(t),i;case fht:if(dve)return dve.call(t)==dve.call(e)}return!1}function vQI(t,e,I,l,n,r){var a=n&y3,s=Gse(t),o=s.length,c=Gse(e),i=c.length;if(o!=i&&!a)return!1;for(var d=o;d--;){var G=s[d];if(!(a?G in e:tg.call(e,G)))return!1}var b=r.get(t);if(b&&r.get(e))return b==e;var u=!0;r.set(t,e),r.set(e,t);for(var h=a;++d<o;){G=s[d];var p=t[G],W=e[G];if(l)var N=a?l(W,p,G,e,t,r):l(p,W,G,t,e,r);if(!(N===void 0?p===W||I(p,W,l,n,r):N)){u=!1;break}h||(h=G=="constructor")}if(u&&!h){var Y=t.constructor,y=e.constructor;Y!=y&&"constructor"in t&&"constructor"in e&&!(typeof Y=="function"&&Y instanceof Y&&typeof y=="function"&&y instanceof y)&&(u=!1)}return r.delete(t),r.delete(e),u}function hse(t,e){var I=t.__data__;return CQI(e)?I[typeof e=="string"?"string":"hash"]:I.map}function XQI(t){for(var e=Gse(t),I=e.length;I--;){var l=e[I],n=t[l];e[I]=[l,n,Oht(n)]}return e}function R3(t,e){var I=v1I(t,e);return YQI(I)?I:void 0}var uA=pQI;(uve&&uA(new uve(new ArrayBuffer(1)))!=cse||Aj&&uA(new Aj)!=sse||hve&&uA(hve.resolve())!=pht||pve&&uA(new pve)!=ose||Zve&&uA(new Zve)!=bve)&&(uA=function(t){var e=V3.call(t),I=e==Y3?t.constructor:void 0,l=I?kE(I):void 0;if(l)switch(l){case S1I:return cse;case z1I:return sse;case U1I:return pht;case O1I:return ose;case M1I:return bve}return e});function HQI(t,e,I){e=pse(e,t)?[e]:Sht(e);for(var l,n=-1,a=e.length;++n<a;){var r=Zse(e[n]);if(!(l=t!=null&&I(t,r)))break;t=t[r]}if(l)return l;var a=t?t.length:0;return!!a&&gve(a)&&Uht(r,a)&&(LE(t)||jht(t))}function Uht(t,e){return e=e??Fht,!!e&&(typeof t=="number"||V1I.test(t))&&t>-1&&t%1==0&&t<e}function pse(t,e){if(LE(t))return!1;var I=typeof t;return I=="number"||I=="symbol"||I=="boolean"||t==null||yve(t)?!0:Z1I.test(t)||!p1I.test(t)||e!=null&&t in Object(e)}function CQI(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function fQI(t){return!!ght&&ght in t}function JQI(t){var e=t&&t.constructor,I=typeof e=="function"&&e.prototype||mse;return t===I}function Oht(t){return t===t&&!Wse(t)}function Mht(t,e){return function(I){return I==null?!1:I[t]===e&&(e!==void 0||t in Object(I))}}var LQI=Yve(function(t){t=BQI(t);var e=[];return W1I.test(t)&&e.push(""),t.replace(N1I,function(I,l,n,r){e.push(n?r.replace(g1I,"$1"):l||I)}),e});function Zse(t){if(typeof t=="string"||yve(t))return t;var e=t+"";return e=="0"&&1/t==-Aht?"-0":e}function kE(t){if(t!=null){try{return xht.call(t)}catch{}try{return t+""}catch{}}return""}function Yve(t,e){if(typeof t!="function"||e&&typeof e!="function")throw new TypeError(a1I);var I=function(){var l=arguments,n=e?e.apply(this,l):l[0],r=I.cache;if(r.has(n))return r.get(n);var a=t.apply(this,l);return I.cache=r.set(n,a),a};return I.cache=new(Yve.Cache||lg),I}Yve.Cache=lg;function Tht(t,e){return t===e||t!==t&&e!==e}function jht(t){return kQI(t)&&tg.call(t,"callee")&&(!k1I.call(t,"callee")||V3.call(t)==ase)}var LE=Array.isArray;function Dht(t){return t!=null&&gve(t.length)&&!Kht(t)}function kQI(t){return Nse(t)&&Dht(t)}function Kht(t){var e=Wse(t)?V3.call(t):"";return e==vht||e==s1I}function gve(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Fht}function Wse(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function Nse(t){return!!t&&typeof t=="object"}function yve(t){return typeof t=="symbol"||Nse(t)&&V3.call(t)==fht}var xQI=Yht?E1I(Yht):gQI;function BQI(t){return t==null?"":wQI(t)}function SQI(t,e,I){var l=t==null?void 0:Bht(t,e);return l===void 0?I:l}function zQI(t,e){return t!=null&&HQI(t,e,ZQI)}function Gse(t){return Dht(t)?mQI(t):VQI(t)}function UQI(t,e){var I={};return e=yQI(e,3),hQI(t,function(l,n,r){I[e(l,n,r)]=l}),I}function OQI(t){return t}function MQI(t){return pse(t)?w1I(Zse(t)):FQI(t)}g3.exports=UQI});function KQI(t,e){let I=_ht(t,l=>e.priority<=l.priority);t.splice(I+1,0,e)}function _ht(t,e){for(let I=t.length-1;I>=0;I--)if(e(t[I]))return I;return-1}function $ht(t,e,I=TQI){return{acquire:(l,n)=>{let r;if(Yse(t)?r=l:(r=void 0,n=l),r!==void 0&&r<=0)throw new Error(`invalid weight ${r}: must be positive`);return new Promise((a,s)=>qht(this,void 0,void 0,function*(){let o=!1,c=setTimeout(()=>{o=!0,s(I)},e);try{let i=yield Yse(t)?t.acquire(r,n):t.acquire(n);o?(Array.isArray(i)?i[1]:i)():(clearTimeout(c),a(i))}catch(i){o||(clearTimeout(c),s(i))}}))},runExclusive(l,n,r){return qht(this,void 0,void 0,function*(){let a=()=>{};try{let s=yield this.acquire(n,r);return Array.isArray(s)?(a=s[1],yield l(s[0])):(a=s,yield l())}finally{a()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,n)=>{let r;if(Yse(t)?r=l:(r=void 0,n=l),r!==void 0&&r<=0)throw new Error(`invalid weight ${r}: must be positive`);return new Promise((a,s)=>{let o=setTimeout(()=>s(I),e);(Yse(t)?t.waitForUnlock(r,n):t.waitForUnlock(n)).then(()=>{clearTimeout(o),a()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function Yse(t){return t.getValue!==void 0}var TQI,uan,jQI,DQI,Vve,PQI,gse,qht,ept=m(()=>{TQI=new Error("timeout while waiting for mutex to become available"),uan=new Error("mutex already locked"),jQI=new Error("request for lock canceled"),DQI=function(t,e,I,l){function n(r){return r instanceof I?r:new I(function(a){a(r)})}return new(I||(I=Promise))(function(r,a){function s(i){try{c(l.next(i))}catch(d){a(d)}}function o(i){try{c(l.throw(i))}catch(d){a(d)}}function c(i){i.done?r(i.value):n(i.value).then(s,o)}c((l=l.apply(t,e||[])).next())})},Vve=class{constructor(e,I=jQI){this._value=e,this._cancelError=I,this._queue=[],this._weightedWaiters=[]}acquire(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((l,n)=>{let r={resolve:l,reject:n,weight:e,priority:I},a=_ht(this._queue,s=>I<=s.priority);a===-1&&e<=this._value?this._dispatchItem(r):this._queue.splice(a+1,0,r)})}runExclusive(e){return DQI(this,arguments,void 0,function*(I,l=1,n=0){let[r,a]=yield this.acquire(l,n);try{return yield I(r)}finally{a()}})}waitForUnlock(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,I)?Promise.resolve():new Promise(l=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),KQI(this._weightedWaiters[e-1],{resolve:l,priority:I})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let I=this._value;this._value-=e.weight,e.resolve([I,this._newReleaser(e.weight)])}_newReleaser(e){let I=!1;return()=>{I||(I=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let I=this._weightedWaiters[e-1];I&&(I.forEach(l=>l.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let I=this._value;I>0;I--){let l=this._weightedWaiters[I-1];if(!l)continue;let n=l.findIndex(r=>r.priority<=e);(n===-1?l:l.splice(0,n)).forEach((r=>r.resolve()))}}}_couldLockImmediately(e,I){return(this._queue.length===0||this._queue[0].priority<I)&&e<=this._value}};PQI=function(t,e,I,l){function n(r){return r instanceof I?r:new I(function(a){a(r)})}return new(I||(I=Promise))(function(r,a){function s(i){try{c(l.next(i))}catch(d){a(d)}}function o(i){try{c(l.throw(i))}catch(d){a(d)}}function c(i){i.done?r(i.value):n(i.value).then(s,o)}c((l=l.apply(t,e||[])).next())})},gse=class{constructor(e){this._semaphore=new Vve(1,e)}acquire(){return PQI(this,arguments,void 0,function*(e=0){let[,I]=yield this._semaphore.acquire(1,e);return I})}runExclusive(e,I=0){return this._semaphore.runExclusive(()=>e(),1,I)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},qht=function(t,e,I,l){function n(r){return r instanceof I?r:new I(function(a){a(r)})}return new(I||(I=Promise))(function(r,a){function s(i){try{c(l.next(i))}catch(d){a(d)}}function o(i){try{c(l.throw(i))}catch(d){a(d)}}function c(i){i.done?r(i.value):n(i.value).then(s,o)}c((l=l.apply(t,e||[])).next())})}});var yse,tpt=m(()=>{"use strict";ept();yse=class{mutexes=new Map;async runExclusive(e,I,l=5e3){let n=this.mutexes.get(e);n||(n=new gse,n.refCount=0,this.mutexes.set(e,n));let r=n;try{return r.refCount++,await $ht(n,l).runExclusive(I)}finally{--r.refCount===0&&this.mutexes.delete(e)}}}});import{existsSync as Vse}from"fs";import{appendFile as qQI,mkdir as _QI,readdir as Rse,readFile as lpt,stat as Ase,writeFile as $QI}from"fs/promises";import{homedir as npt}from"os";import{dirname as eEI,join as Ab}from"path";function tEI(t){if(t instanceof Ji){let e=t.issues[0];if(e){let I=e.path.join("."),l=e.message;return l.includes("Invalid discriminator value")?"Unknown event type":I?`${I}: ${l}`:l}}return Ae(t)}function Ipt(t){return Object.values(Qse).includes(t)}async function rpt(t){let e=eEI(t);try{await _QI(e,{recursive:!0,mode:448})}catch{}}async function IEI(t,e){if(Vse(t))try{let I={},l=await wse.runExclusive(t,()=>lpt(t,"utf8"));return l.trim().startsWith("{")?I=JSON.parse(l):l.split(`
|
|
605
|
-
`).forEach(n=>{let[r,a]=n.split("=").map(s=>s.trim());r&&a&&(I[r]=a)}),e(I)}catch(I){throw new Error(`Failed to read configuration from ${t}: ${Ae(I)}`)}}async function lEI(t,e){try{await
|
|
606
|
-
`).filter(u=>u.trim()),b=[];for(let u=0;u<G.length;u++)try{let h=JSON.parse(G[u]),p=t(h);b.push(p)}catch(h){let p=tEI(h),W=G[u].length>100?G[u].substring(0,100)+"...":G[u],N=p;if(p.includes("Unknown event type"))try{let Y=JSON.parse(G[u]);Y&&typeof Y=="object"&&"type"in Y&&(N=`Unknown event type: "${Y.type}"`)}catch{}throw new Error(`Invalid event at line ${u+1}: ${N}. Event: ${W}`)}return b}catch(d){throw new Error(`Failed to read JSONL from ${i}: ${Ae(d)}`)}},append:async(c,i)=>{let d=n(i),G=Array.isArray(c)?c:[c];try{await
|
|
604
|
+
`)),s}}var n1I,mht,hht=m(()=>{n1I=uht({}),mht=n1I});function lse(t){return t.type===void 0||t.type.toLowerCase()==="local"||t.type.toLowerCase()==="stdio"}function nse(t){return yj(t)||Vj(t)}function yj(t){return t.type?.toLowerCase()==="http"}function Vj(t){return t.type?.toLowerCase()==="sse"}function rse(t){return t.type?.toLowerCase()==="memory"}var Ise,ove,cve=m(()=>{"use strict";Ise="github-mcp-server",ove="playwright"});function ive(t){switch(t){case"project":return"Project";case"personal-copilot":return"Personal (Copilot)";case"personal-claude":return"Personal (Claude)";case"custom":return"Custom"}}function Zht(t){switch(t){case"project":return"project";case"personal-copilot":case"personal-claude":return"user";case"custom":return"custom"}}var pht,Rj=m(()=>{"use strict";ac();pht=V.object({name:V.string().regex(/^[a-z0-9-]+$/,"Skill name must contain only lowercase letters, numbers, and hyphens").max(64,"Skill name must be at most 64 characters"),description:V.string().max(1024,"Skill description must be at most 1024 characters"),"allowed-tools":V.string().optional()})});var _ht=g((Aj,g3)=>{var r1I=200,a1I="Expected a function",Nve="__lodash_hash_undefined__",bse=1,y3=2,wht=1/0,Qht=9007199254740991,ase="[object Arguments]",bve="[object Array]",Eht="[object Boolean]",vht="[object Date]",Xht="[object Error]",Hht="[object Function]",s1I="[object GeneratorFunction]",sse="[object Map]",Cht="[object Number]",Y3="[object Object]",Wht="[object Promise]",fht="[object RegExp]",ose="[object Set]",Jht="[object String]",Lht="[object Symbol]",mve="[object WeakMap]",kht="[object ArrayBuffer]",cse="[object DataView]",o1I="[object Float32Array]",c1I="[object Float64Array]",i1I="[object Int8Array]",d1I="[object Int16Array]",G1I="[object Int32Array]",b1I="[object Uint8Array]",m1I="[object Uint8ClampedArray]",u1I="[object Uint16Array]",h1I="[object Uint32Array]",p1I=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Z1I=/^\w*$/,W1I=/^\./,N1I=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Y1I=/[\\^$.*+?()[\]{}|]/g,g1I=/\\(\\)?/g,y1I=/^\[object .+?Constructor\]$/,V1I=/^(?:0|[1-9]\d*)$/,da={};da[o1I]=da[c1I]=da[i1I]=da[d1I]=da[G1I]=da[b1I]=da[m1I]=da[u1I]=da[h1I]=!0;da[ase]=da[bve]=da[kht]=da[Eht]=da[cse]=da[vht]=da[Xht]=da[Hht]=da[sse]=da[Cht]=da[Y3]=da[fht]=da[ose]=da[Jht]=da[mve]=!1;var xht=typeof global=="object"&&global&&global.Object===Object&&global,R1I=typeof self=="object"&&self&&self.Object===Object&&self,hA=xht||R1I||Function("return this")(),Bht=typeof Aj=="object"&&Aj&&!Aj.nodeType&&Aj,Nht=Bht&&typeof g3=="object"&&g3&&!g3.nodeType&&g3,A1I=Nht&&Nht.exports===Bht,Yht=A1I&&xht.process,ght=(function(){try{return Yht&&Yht.binding("util")}catch{}})(),yht=ght&&ght.isTypedArray;function F1I(t,e){for(var I=-1,l=t?t.length:0;++I<l;)if(e(t[I],I,t))return!0;return!1}function w1I(t){return function(e){return e?.[t]}}function Q1I(t,e){for(var I=-1,l=Array(t);++I<t;)l[I]=e(I);return l}function E1I(t){return function(e){return t(e)}}function v1I(t,e){return t?.[e]}function uve(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}function X1I(t){var e=-1,I=Array(t.size);return t.forEach(function(l,n){I[++e]=[n,l]}),I}function H1I(t,e){return function(I){return t(e(I))}}function C1I(t){var e=-1,I=Array(t.size);return t.forEach(function(l){I[++e]=l}),I}var f1I=Array.prototype,J1I=Function.prototype,mse=Object.prototype,dve=hA["__core-js_shared__"],Vht=(function(){var t=/[^.]+$/.exec(dve&&dve.keys&&dve.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})(),Sht=J1I.toString,tg=mse.hasOwnProperty,V3=mse.toString,L1I=RegExp("^"+Sht.call(tg).replace(Y1I,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Rht=hA.Symbol,Aht=hA.Uint8Array,k1I=mse.propertyIsEnumerable,x1I=f1I.splice,B1I=H1I(Object.keys,Object),hve=R3(hA,"DataView"),Fj=R3(hA,"Map"),pve=R3(hA,"Promise"),Zve=R3(hA,"Set"),Wve=R3(hA,"WeakMap"),wj=R3(Object,"create"),S1I=kE(hve),z1I=kE(Fj),U1I=kE(pve),O1I=kE(Zve),M1I=kE(Wve),ise=Rht?Rht.prototype:void 0,Gve=ise?ise.valueOf:void 0,Fht=ise?ise.toString:void 0;function JE(t){var e=-1,I=t?t.length:0;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function T1I(){this.__data__=wj?wj(null):{}}function j1I(t){return this.has(t)&&delete this.__data__[t]}function D1I(t){var e=this.__data__;if(wj){var I=e[t];return I===Nve?void 0:I}return tg.call(e,t)?e[t]:void 0}function K1I(t){var e=this.__data__;return wj?e[t]!==void 0:tg.call(e,t)}function P1I(t,e){var I=this.__data__;return I[t]=wj&&e===void 0?Nve:e,this}JE.prototype.clear=T1I;JE.prototype.delete=j1I;JE.prototype.get=D1I;JE.prototype.has=K1I;JE.prototype.set=P1I;function Ig(t){var e=-1,I=t?t.length:0;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function q1I(){this.__data__=[]}function _1I(t){var e=this.__data__,I=use(e,t);if(I<0)return!1;var l=e.length-1;return I==l?e.pop():x1I.call(e,I,1),!0}function $1I(t){var e=this.__data__,I=use(e,t);return I<0?void 0:e[I][1]}function eQI(t){return use(this.__data__,t)>-1}function tQI(t,e){var I=this.__data__,l=use(I,t);return l<0?I.push([t,e]):I[l][1]=e,this}Ig.prototype.clear=q1I;Ig.prototype.delete=_1I;Ig.prototype.get=$1I;Ig.prototype.has=eQI;Ig.prototype.set=tQI;function lg(t){var e=-1,I=t?t.length:0;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function IQI(){this.__data__={hash:new JE,map:new(Fj||Ig),string:new JE}}function lQI(t){return hse(this,t).delete(t)}function nQI(t){return hse(this,t).get(t)}function rQI(t){return hse(this,t).has(t)}function aQI(t,e){return hse(this,t).set(t,e),this}lg.prototype.clear=IQI;lg.prototype.delete=lQI;lg.prototype.get=nQI;lg.prototype.has=rQI;lg.prototype.set=aQI;function dse(t){var e=-1,I=t?t.length:0;for(this.__data__=new lg;++e<I;)this.add(t[e])}function sQI(t){return this.__data__.set(t,Nve),this}function oQI(t){return this.__data__.has(t)}dse.prototype.add=dse.prototype.push=sQI;dse.prototype.has=oQI;function eg(t){this.__data__=new Ig(t)}function cQI(){this.__data__=new Ig}function iQI(t){return this.__data__.delete(t)}function dQI(t){return this.__data__.get(t)}function GQI(t){return this.__data__.has(t)}function bQI(t,e){var I=this.__data__;if(I instanceof Ig){var l=I.__data__;if(!Fj||l.length<r1I-1)return l.push([t,e]),this;I=this.__data__=new lg(l)}return I.set(t,e),this}eg.prototype.clear=cQI;eg.prototype.delete=iQI;eg.prototype.get=dQI;eg.prototype.has=GQI;eg.prototype.set=bQI;function mQI(t,e){var I=LE(t)||Kht(t)?Q1I(t.length,String):[],l=I.length,n=!!l;for(var r in t)(e||tg.call(t,r))&&!(n&&(r=="length"||Mht(r,l)))&&I.push(r);return I}function use(t,e){for(var I=t.length;I--;)if(Dht(t[I][0],e))return I;return-1}var uQI=QQI();function hQI(t,e){return t&&uQI(t,e,Gse)}function zht(t,e){e=pse(e,t)?[e]:Uht(e);for(var I=0,l=e.length;t!=null&&I<l;)t=t[Zse(e[I++])];return I&&I==l?t:void 0}function pQI(t){return V3.call(t)}function ZQI(t,e){return t!=null&&e in Object(t)}function Yve(t,e,I,l,n){return t===e?!0:t==null||e==null||!Wse(t)&&!Nse(e)?t!==t&&e!==e:WQI(t,e,Yve,I,l,n)}function WQI(t,e,I,l,n,r){var a=LE(t),s=LE(e),o=bve,c=bve;a||(o=uA(t),o=o==ase?Y3:o),s||(c=uA(e),c=c==ase?Y3:c);var i=o==Y3&&!uve(t),d=c==Y3&&!uve(e),G=o==c;if(G&&!i)return r||(r=new eg),a||xQI(t)?Oht(t,e,I,l,n,r):EQI(t,e,o,I,l,n,r);if(!(n&y3)){var b=i&&tg.call(t,"__wrapped__"),u=d&&tg.call(e,"__wrapped__");if(b||u){var h=b?t.value():t,p=u?e.value():e;return r||(r=new eg),I(h,p,l,n,r)}}return G?(r||(r=new eg),vQI(t,e,I,l,n,r)):!1}function NQI(t,e,I,l){var n=I.length,r=n,a=!l;if(t==null)return!r;for(t=Object(t);n--;){var s=I[n];if(a&&s[2]?s[1]!==t[s[0]]:!(s[0]in t))return!1}for(;++n<r;){s=I[n];var o=s[0],c=t[o],i=s[1];if(a&&s[2]){if(c===void 0&&!(o in t))return!1}else{var d=new eg;if(l)var G=l(c,i,o,t,e,d);if(!(G===void 0?Yve(i,c,l,bse|y3,d):G))return!1}}return!0}function YQI(t){if(!Wse(t)||fQI(t))return!1;var e=qht(t)||uve(t)?L1I:y1I;return e.test(kE(t))}function gQI(t){return Nse(t)&&yve(t.length)&&!!da[V3.call(t)]}function yQI(t){return typeof t=="function"?t:t==null?OQI:typeof t=="object"?LE(t)?AQI(t[0],t[1]):RQI(t):MQI(t)}function VQI(t){if(!JQI(t))return B1I(t);var e=[];for(var I in Object(t))tg.call(t,I)&&I!="constructor"&&e.push(I);return e}function RQI(t){var e=XQI(t);return e.length==1&&e[0][2]?jht(e[0][0],e[0][1]):function(I){return I===t||NQI(I,t,e)}}function AQI(t,e){return pse(t)&&Tht(e)?jht(Zse(t),e):function(I){var l=SQI(I,t);return l===void 0&&l===e?zQI(I,t):Yve(e,l,void 0,bse|y3)}}function FQI(t){return function(e){return zht(e,t)}}function wQI(t){if(typeof t=="string")return t;if(Vve(t))return Fht?Fht.call(t):"";var e=t+"";return e=="0"&&1/t==-wht?"-0":e}function Uht(t){return LE(t)?t:LQI(t)}function QQI(t){return function(e,I,l){for(var n=-1,r=Object(e),a=l(e),s=a.length;s--;){var o=a[t?s:++n];if(I(r[o],o,r)===!1)break}return e}}function Oht(t,e,I,l,n,r){var a=n&y3,s=t.length,o=e.length;if(s!=o&&!(a&&o>s))return!1;var c=r.get(t);if(c&&r.get(e))return c==e;var i=-1,d=!0,G=n&bse?new dse:void 0;for(r.set(t,e),r.set(e,t);++i<s;){var b=t[i],u=e[i];if(l)var h=a?l(u,b,i,e,t,r):l(b,u,i,t,e,r);if(h!==void 0){if(h)continue;d=!1;break}if(G){if(!F1I(e,function(p,W){if(!G.has(W)&&(b===p||I(b,p,l,n,r)))return G.add(W)})){d=!1;break}}else if(!(b===u||I(b,u,l,n,r))){d=!1;break}}return r.delete(t),r.delete(e),d}function EQI(t,e,I,l,n,r,a){switch(I){case cse:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case kht:return!(t.byteLength!=e.byteLength||!l(new Aht(t),new Aht(e)));case Eht:case vht:case Cht:return Dht(+t,+e);case Xht:return t.name==e.name&&t.message==e.message;case fht:case Jht:return t==e+"";case sse:var s=X1I;case ose:var o=r&y3;if(s||(s=C1I),t.size!=e.size&&!o)return!1;var c=a.get(t);if(c)return c==e;r|=bse,a.set(t,e);var i=Oht(s(t),s(e),l,n,r,a);return a.delete(t),i;case Lht:if(Gve)return Gve.call(t)==Gve.call(e)}return!1}function vQI(t,e,I,l,n,r){var a=n&y3,s=Gse(t),o=s.length,c=Gse(e),i=c.length;if(o!=i&&!a)return!1;for(var d=o;d--;){var G=s[d];if(!(a?G in e:tg.call(e,G)))return!1}var b=r.get(t);if(b&&r.get(e))return b==e;var u=!0;r.set(t,e),r.set(e,t);for(var h=a;++d<o;){G=s[d];var p=t[G],W=e[G];if(l)var N=a?l(W,p,G,e,t,r):l(p,W,G,t,e,r);if(!(N===void 0?p===W||I(p,W,l,n,r):N)){u=!1;break}h||(h=G=="constructor")}if(u&&!h){var Y=t.constructor,y=e.constructor;Y!=y&&"constructor"in t&&"constructor"in e&&!(typeof Y=="function"&&Y instanceof Y&&typeof y=="function"&&y instanceof y)&&(u=!1)}return r.delete(t),r.delete(e),u}function hse(t,e){var I=t.__data__;return CQI(e)?I[typeof e=="string"?"string":"hash"]:I.map}function XQI(t){for(var e=Gse(t),I=e.length;I--;){var l=e[I],n=t[l];e[I]=[l,n,Tht(n)]}return e}function R3(t,e){var I=v1I(t,e);return YQI(I)?I:void 0}var uA=pQI;(hve&&uA(new hve(new ArrayBuffer(1)))!=cse||Fj&&uA(new Fj)!=sse||pve&&uA(pve.resolve())!=Wht||Zve&&uA(new Zve)!=ose||Wve&&uA(new Wve)!=mve)&&(uA=function(t){var e=V3.call(t),I=e==Y3?t.constructor:void 0,l=I?kE(I):void 0;if(l)switch(l){case S1I:return cse;case z1I:return sse;case U1I:return Wht;case O1I:return ose;case M1I:return mve}return e});function HQI(t,e,I){e=pse(e,t)?[e]:Uht(e);for(var l,n=-1,a=e.length;++n<a;){var r=Zse(e[n]);if(!(l=t!=null&&I(t,r)))break;t=t[r]}if(l)return l;var a=t?t.length:0;return!!a&&yve(a)&&Mht(r,a)&&(LE(t)||Kht(t))}function Mht(t,e){return e=e??Qht,!!e&&(typeof t=="number"||V1I.test(t))&&t>-1&&t%1==0&&t<e}function pse(t,e){if(LE(t))return!1;var I=typeof t;return I=="number"||I=="symbol"||I=="boolean"||t==null||Vve(t)?!0:Z1I.test(t)||!p1I.test(t)||e!=null&&t in Object(e)}function CQI(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function fQI(t){return!!Vht&&Vht in t}function JQI(t){var e=t&&t.constructor,I=typeof e=="function"&&e.prototype||mse;return t===I}function Tht(t){return t===t&&!Wse(t)}function jht(t,e){return function(I){return I==null?!1:I[t]===e&&(e!==void 0||t in Object(I))}}var LQI=gve(function(t){t=BQI(t);var e=[];return W1I.test(t)&&e.push(""),t.replace(N1I,function(I,l,n,r){e.push(n?r.replace(g1I,"$1"):l||I)}),e});function Zse(t){if(typeof t=="string"||Vve(t))return t;var e=t+"";return e=="0"&&1/t==-wht?"-0":e}function kE(t){if(t!=null){try{return Sht.call(t)}catch{}try{return t+""}catch{}}return""}function gve(t,e){if(typeof t!="function"||e&&typeof e!="function")throw new TypeError(a1I);var I=function(){var l=arguments,n=e?e.apply(this,l):l[0],r=I.cache;if(r.has(n))return r.get(n);var a=t.apply(this,l);return I.cache=r.set(n,a),a};return I.cache=new(gve.Cache||lg),I}gve.Cache=lg;function Dht(t,e){return t===e||t!==t&&e!==e}function Kht(t){return kQI(t)&&tg.call(t,"callee")&&(!k1I.call(t,"callee")||V3.call(t)==ase)}var LE=Array.isArray;function Pht(t){return t!=null&&yve(t.length)&&!qht(t)}function kQI(t){return Nse(t)&&Pht(t)}function qht(t){var e=Wse(t)?V3.call(t):"";return e==Hht||e==s1I}function yve(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Qht}function Wse(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}function Nse(t){return!!t&&typeof t=="object"}function Vve(t){return typeof t=="symbol"||Nse(t)&&V3.call(t)==Lht}var xQI=yht?E1I(yht):gQI;function BQI(t){return t==null?"":wQI(t)}function SQI(t,e,I){var l=t==null?void 0:zht(t,e);return l===void 0?I:l}function zQI(t,e){return t!=null&&HQI(t,e,ZQI)}function Gse(t){return Pht(t)?mQI(t):VQI(t)}function UQI(t,e){var I={};return e=yQI(e,3),hQI(t,function(l,n,r){I[e(l,n,r)]=l}),I}function OQI(t){return t}function MQI(t){return pse(t)?w1I(Zse(t)):FQI(t)}g3.exports=UQI});function KQI(t,e){let I=ept(t,l=>e.priority<=l.priority);t.splice(I+1,0,e)}function ept(t,e){for(let I=t.length-1;I>=0;I--)if(e(t[I]))return I;return-1}function tpt(t,e,I=TQI){return{acquire:(l,n)=>{let r;if(Yse(t)?r=l:(r=void 0,n=l),r!==void 0&&r<=0)throw new Error(`invalid weight ${r}: must be positive`);return new Promise((a,s)=>$ht(this,void 0,void 0,function*(){let o=!1,c=setTimeout(()=>{o=!0,s(I)},e);try{let i=yield Yse(t)?t.acquire(r,n):t.acquire(n);o?(Array.isArray(i)?i[1]:i)():(clearTimeout(c),a(i))}catch(i){o||(clearTimeout(c),s(i))}}))},runExclusive(l,n,r){return $ht(this,void 0,void 0,function*(){let a=()=>{};try{let s=yield this.acquire(n,r);return Array.isArray(s)?(a=s[1],yield l(s[0])):(a=s,yield l())}finally{a()}})},release(l){t.release(l)},cancel(){return t.cancel()},waitForUnlock:(l,n)=>{let r;if(Yse(t)?r=l:(r=void 0,n=l),r!==void 0&&r<=0)throw new Error(`invalid weight ${r}: must be positive`);return new Promise((a,s)=>{let o=setTimeout(()=>s(I),e);(Yse(t)?t.waitForUnlock(r,n):t.waitForUnlock(n)).then(()=>{clearTimeout(o),a()})})},isLocked:()=>t.isLocked(),getValue:()=>t.getValue(),setValue:l=>t.setValue(l)}}function Yse(t){return t.getValue!==void 0}var TQI,pan,jQI,DQI,Rve,PQI,gse,$ht,Ipt=m(()=>{TQI=new Error("timeout while waiting for mutex to become available"),pan=new Error("mutex already locked"),jQI=new Error("request for lock canceled"),DQI=function(t,e,I,l){function n(r){return r instanceof I?r:new I(function(a){a(r)})}return new(I||(I=Promise))(function(r,a){function s(i){try{c(l.next(i))}catch(d){a(d)}}function o(i){try{c(l.throw(i))}catch(d){a(d)}}function c(i){i.done?r(i.value):n(i.value).then(s,o)}c((l=l.apply(t,e||[])).next())})},Rve=class{constructor(e,I=jQI){this._value=e,this._cancelError=I,this._queue=[],this._weightedWaiters=[]}acquire(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((l,n)=>{let r={resolve:l,reject:n,weight:e,priority:I},a=ept(this._queue,s=>I<=s.priority);a===-1&&e<=this._value?this._dispatchItem(r):this._queue.splice(a+1,0,r)})}runExclusive(e){return DQI(this,arguments,void 0,function*(I,l=1,n=0){let[r,a]=yield this.acquire(l,n);try{return yield I(r)}finally{a()}})}waitForUnlock(e=1,I=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,I)?Promise.resolve():new Promise(l=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),KQI(this._weightedWaiters[e-1],{resolve:l,priority:I})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let I=this._value;this._value-=e.weight,e.resolve([I,this._newReleaser(e.weight)])}_newReleaser(e){let I=!1;return()=>{I||(I=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let I=this._weightedWaiters[e-1];I&&(I.forEach(l=>l.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let I=this._value;I>0;I--){let l=this._weightedWaiters[I-1];if(!l)continue;let n=l.findIndex(r=>r.priority<=e);(n===-1?l:l.splice(0,n)).forEach((r=>r.resolve()))}}}_couldLockImmediately(e,I){return(this._queue.length===0||this._queue[0].priority<I)&&e<=this._value}};PQI=function(t,e,I,l){function n(r){return r instanceof I?r:new I(function(a){a(r)})}return new(I||(I=Promise))(function(r,a){function s(i){try{c(l.next(i))}catch(d){a(d)}}function o(i){try{c(l.throw(i))}catch(d){a(d)}}function c(i){i.done?r(i.value):n(i.value).then(s,o)}c((l=l.apply(t,e||[])).next())})},gse=class{constructor(e){this._semaphore=new Rve(1,e)}acquire(){return PQI(this,arguments,void 0,function*(e=0){let[,I]=yield this._semaphore.acquire(1,e);return I})}runExclusive(e,I=0){return this._semaphore.runExclusive(()=>e(),1,I)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}},$ht=function(t,e,I,l){function n(r){return r instanceof I?r:new I(function(a){a(r)})}return new(I||(I=Promise))(function(r,a){function s(i){try{c(l.next(i))}catch(d){a(d)}}function o(i){try{c(l.throw(i))}catch(d){a(d)}}function c(i){i.done?r(i.value):n(i.value).then(s,o)}c((l=l.apply(t,e||[])).next())})}});var yse,lpt=m(()=>{"use strict";Ipt();yse=class{mutexes=new Map;async runExclusive(e,I,l=5e3){let n=this.mutexes.get(e);n||(n=new gse,n.refCount=0,this.mutexes.set(e,n));let r=n;try{return r.refCount++,await tpt(n,l).runExclusive(I)}finally{--r.refCount===0&&this.mutexes.delete(e)}}}});import{existsSync as Vse}from"fs";import{appendFile as qQI,mkdir as _QI,readdir as Rse,readFile as rpt,stat as Ase,writeFile as $QI}from"fs/promises";import{homedir as apt}from"os";import{dirname as eEI,join as Ab}from"path";function tEI(t){if(t instanceof Ji){let e=t.issues[0];if(e){let I=e.path.join("."),l=e.message;return l.includes("Invalid discriminator value")?"Unknown event type":I?`${I}: ${l}`:l}}return Ae(t)}function npt(t){return Object.values(Qse).includes(t)}async function spt(t){let e=eEI(t);try{await _QI(e,{recursive:!0,mode:448})}catch{}}async function IEI(t,e){if(Vse(t))try{let I={},l=await wse.runExclusive(t,()=>rpt(t,"utf8"));return l.trim().startsWith("{")?I=JSON.parse(l):l.split(`
|
|
605
|
+
`).forEach(n=>{let[r,a]=n.split("=").map(s=>s.trim());r&&a&&(I[r]=a)}),e(I)}catch(I){throw new Error(`Failed to read configuration from ${t}: ${Ae(I)}`)}}async function lEI(t,e){try{await spt(t);let I=JSON.stringify(e,null,2);await wse.runExclusive(t,()=>$QI(t,I,{mode:384}))}catch(I){throw new Error(`Failed to write configuration to ${t}: ${Ae(I)}`)}}var Qse,Fse,wse,opt,Ese,cpt,ipt,Qj=m(()=>{"use strict";ac();DI();lpt();Qse=(I=>(I.DEFAULT="config",I.MCP="mcp",I))(Qse||{});Fse=".copilot",wse=new yse;opt=(t,e,{shouldCache:I})=>{let l=new Map,n=()=>{let G=npt(e)?process.env.XDG_CONFIG_HOME:process.env.XDG_STATE_HOME;return G?Ab(G,Fse):Ab(apt(),Fse)},r=()=>{let G=npt(e)?"-config":"-state";return`${e}${e=="config"?"":G}`},a=G=>{let b=".json",u=r()+(G?"":b),h=Ab(n(),u,G?`${G}${b}`:"");return!Vse(h)&&Vse(h.replace(/\.json$/,""))&&(h=h.replace(/\.json$/,"")),h},s=async()=>{let G=Ab(n(),r());try{let u=(await Rse(G,{withFileTypes:!0})).filter(p=>p.isFile()&&p.name.endsWith(".json")).map(p=>p.name),h=await Promise.all(u.map(async p=>{let W=Ab(G,p);try{let N=await Ase(W);return{file:p,mtime:N.mtime}}catch{return{file:p,mtime:new Date}}}));return h.sort((p,W)=>W.mtime.getTime()-p.mtime.getTime()),h.map(p=>p.file)}catch{}return[]},o=async()=>{let G=Ab(n(),r());try{let u=(await Rse(G,{withFileTypes:!0})).filter(p=>p.isFile()&&p.name.endsWith(".json")).map(p=>p.name),h=await Promise.all(u.map(async p=>{let W=Ab(G,p);try{let N=await Ase(W);return{file:p,mtime:N.mtime,birthtime:N.birthtime}}catch{return{file:p,mtime:new Date,birthtime:new Date}}}));return h.sort((p,W)=>W.mtime.getTime()-p.mtime.getTime()),h}catch{}return[]},c=async(G="")=>{if(I&&l.has(G))return l.get(G);let b=await IEI(a(G),t);return I&&b&&l.set(G,b),b},i=async(G,b="")=>{I&&l.set(b,G),await lEI(a(b),G)};return{load:c,write:i,writeKey:async(G,b,u)=>{let h=await c(u);if(b===void 0){h&&(delete h[G],await i(h,u));return}let p={[G]:b},W;h?W={...h,...p}:W=p,await i(W,u)},path:a,directoryFiles:s,directoryFilesWithMetadata:o}},Ese=(t,e)=>opt(t,e,{shouldCache:!0}),cpt=(t,e)=>opt(t,e,{shouldCache:!1}),ipt=(t,e)=>{let I=()=>{let c=process.env.XDG_STATE_HOME;return c?Ab(c,Fse):Ab(apt(),Fse)},l=()=>`${e}-state`,n=c=>{let i=".jsonl",d=l()+(c?"":i);return Ab(I(),d,c?`${c}${i}`:"")};return{load:async c=>{let i=n(c);if(!Vse(i))return[];try{let G=(await wse.runExclusive(i,()=>rpt(i,"utf8"))).trim().split(`
|
|
606
|
+
`).filter(u=>u.trim()),b=[];for(let u=0;u<G.length;u++)try{let h=JSON.parse(G[u]),p=t(h);b.push(p)}catch(h){let p=tEI(h),W=G[u].length>100?G[u].substring(0,100)+"...":G[u],N=p;if(p.includes("Unknown event type"))try{let Y=JSON.parse(G[u]);Y&&typeof Y=="object"&&"type"in Y&&(N=`Unknown event type: "${Y.type}"`)}catch{}throw new Error(`Invalid event at line ${u+1}: ${N}. Event: ${W}`)}return b}catch(d){throw new Error(`Failed to read JSONL from ${i}: ${Ae(d)}`)}},append:async(c,i)=>{let d=n(i),G=Array.isArray(c)?c:[c];try{await spt(d);let b=G.map(u=>JSON.stringify(u)).join(`
|
|
607
607
|
`)+`
|
|
608
|
-
`;await wse.runExclusive(d,()=>qQI(d,b,{mode:384}))}catch(b){throw new Error(`Failed to append to JSONL file ${d}: ${Ae(b)}`)}},path:n,directoryFiles:async()=>{let c=Ab(I(),l());try{let d=(await Rse(c,{withFileTypes:!0})).filter(b=>b.isFile()&&b.name.endsWith(".jsonl")).map(b=>b.name),G=await Promise.all(d.map(async b=>{let u=Ab(c,b);try{let h=await Ase(u);return{file:b,mtime:h.mtime}}catch{return{file:b,mtime:new Date}}}));return G.sort((b,u)=>u.mtime.getTime()-b.mtime.getTime()),G.map(b=>b.file)}catch{return[]}},directoryFilesWithMetadata:async()=>{let c=Ab(I(),l());try{let d=(await Rse(c,{withFileTypes:!0})).filter(b=>b.isFile()&&b.name.endsWith(".jsonl")).map(b=>b.name),G=await Promise.all(d.map(async b=>{let u=Ab(c,b);try{let h=await Ase(u);return{file:b,mtime:h.mtime,birthtime:h.birthtime}}catch{return{file:b,mtime:new Date,birthtime:new Date}}}));return G.sort((b,u)=>u.mtime.getTime()-b.mtime.getTime()),G}catch{return[]}},home:I,directory:l}}});var dpt,
|
|
608
|
+
`;await wse.runExclusive(d,()=>qQI(d,b,{mode:384}))}catch(b){throw new Error(`Failed to append to JSONL file ${d}: ${Ae(b)}`)}},path:n,directoryFiles:async()=>{let c=Ab(I(),l());try{let d=(await Rse(c,{withFileTypes:!0})).filter(b=>b.isFile()&&b.name.endsWith(".jsonl")).map(b=>b.name),G=await Promise.all(d.map(async b=>{let u=Ab(c,b);try{let h=await Ase(u);return{file:b,mtime:h.mtime}}catch{return{file:b,mtime:new Date}}}));return G.sort((b,u)=>u.mtime.getTime()-b.mtime.getTime()),G.map(b=>b.file)}catch{return[]}},directoryFilesWithMetadata:async()=>{let c=Ab(I(),l());try{let d=(await Rse(c,{withFileTypes:!0})).filter(b=>b.isFile()&&b.name.endsWith(".jsonl")).map(b=>b.name),G=await Promise.all(d.map(async b=>{let u=Ab(c,b);try{let h=await Ase(u);return{file:b,mtime:h.mtime,birthtime:h.birthtime}}catch{return{file:b,mtime:new Date,birthtime:new Date}}}));return G.sort((b,u)=>u.mtime.getTime()-b.mtime.getTime()),G}catch{return[]}},home:I,directory:l}}});var bpt,dpt,nEI,rEI,aEI,sEI,Gpt,Go,xE=m(()=>{"use strict";bpt=lI(_ht(),1);ac();Qj();dpt=Ue({host:P(),login:P()}),nEI=Ue({auto_update:al().optional(),update_channel:xi(["stable","prerelease"]).optional(),banner:xi(["always","once","never"]).optional(),beep:al().optional(),last_logged_in_user:dpt.optional(),logged_in_users:Sr(dpt).optional(),model:P().optional(),render_markdown:al().optional(),screen_reader:al().optional(),theme:P().optional(),trusted_folders:Sr(P()).optional(),store_token_plaintext:al().optional(),stream:al().optional(),parallel_tool_execution:al().optional(),custom_agents:Ue({default_local_only:al().optional()}).optional(),feature_flags:Ue({enabled:Sr(P()).optional()}).optional(),skill_directories:Sr(P()).optional(),disabled_skills:Sr(P()).optional(),asked_setup_terminals:Sr(P()).optional(),copilot_tokens:bm(P(),P()).optional(),copilot_url:P().optional(),staff:al().optional(),log_level:xi(["none","error","warning","info","debug","all","default"]).optional()}),rEI=bm(P(),V2e()),aEI=rEI.transform(t=>(0,bpt.default)(t,(e,I)=>I.toLowerCase())),sEI=aEI.pipe(nEI),Gpt=Ese((t,e)=>sEI.parse(t,e),"config"),Go={...Gpt,load:async t=>await Gpt.load(t)??{}}});function oEI(t){return t.length>0&&/^[0-9a-zA-Z_-]+$/.test(t)}var mpt,upt,cEI,iEI,dEI,hpt,ppt=m(()=>{"use strict";ac();WY();Qj();mpt=xi(["none","markdown","hidden_characters"]),upt=Ue({tools:Sr(P()),type:P().optional(),isDefaultServer:al().optional(),filterMapping:bm(P(),mpt).or(mpt).optional(),timeout:ul().positive().optional()}),cEI=upt.extend({type:gt("local").or(gt("stdio")).optional(),command:P(),args:Sr(P()),env:bm(P(),P()).optional()}),iEI=upt.extend({type:gt("http").or(gt("sse")),url:P(),headers:bm(P(),P()).optional()}),dEI=Ue({mcpServers:bm(P().min(1,"MCP server name cannot be empty").refine(oEI,{message:"MCP server name must only contain alphanumeric characters, underscores, and hyphens"}),cEI.or(iEI))}),hpt=Ese(dEI.parse,"mcp")});function Wpt(t){return"host"in t&&t.host?t.host:"https://github.com"}function Npt(t){return Ej(t,{onHMACAuthInfo:()=>"Logged in with HMAC",onEnvAuthInfo:e=>e.login?`Logged in with ${e.envVar} as user: ${e.login}`:`Logged in via ${e.envVar} (server-to-server)`,onUserAuthInfo:e=>`Logged in as user: ${Zpt(e)}`,onGhCliAuthInfo:e=>`Logged in with gh as user: ${Zpt(e)}`,onApiKeyAuthInfo:e=>`Logged in with API key to ${e.host}`,onTokenAuthInfo:e=>`Logged in with token to ${e.host}`})}function Zpt(t){return t.host!==WS?`${t.login} (${t.host})`:t.login}var vse=m(()=>{"use strict";xE();G1();BE()});function mEI(){let t=new Map;for(let[e,I]of Object.entries(wa)){for(let[l,n]of Object.entries(I))wa[l]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},I[l]=wa[l],t.set(n[0],n[1]);Object.defineProperty(wa,e,{value:I,enumerable:!1})}return Object.defineProperty(wa,"codes",{value:t,enumerable:!1}),wa.color.close="\x1B[39m",wa.bgColor.close="\x1B[49m",wa.color.ansi=Ypt(),wa.color.ansi256=gpt(),wa.color.ansi16m=ypt(),wa.bgColor.ansi=Ypt(10),wa.bgColor.ansi256=gpt(10),wa.bgColor.ansi16m=ypt(10),Object.defineProperties(wa,{rgbToAnsi256:{value(e,I,l){return e===I&&I===l?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(I/255*5)+Math.round(l/255*5)},enumerable:!1},hexToRgb:{value(e){let I=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!I)return[0,0,0];let[l]=I;l.length===3&&(l=[...l].map(r=>r+r).join(""));let n=Number.parseInt(l,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:e=>wa.rgbToAnsi256(...wa.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let I,l,n;if(e>=232)I=((e-232)*10+8)/255,l=I,n=I;else{e-=16;let s=e%36;I=Math.floor(e/36)/5,l=Math.floor(s/6)/5,n=s%6/5}let r=Math.max(I,l,n)*2;if(r===0)return 30;let a=30+(Math.round(n)<<2|Math.round(l)<<1|Math.round(I));return r===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,I,l)=>wa.ansi256ToAnsi(wa.rgbToAnsi256(e,I,l)),enumerable:!1},hexToAnsi:{value:e=>wa.ansi256ToAnsi(wa.hexToAnsi256(e)),enumerable:!1}}),wa}var Ypt,gpt,ypt,wa,Ban,GEI,bEI,San,uEI,ZZ,Vpt=m(()=>{Ypt=(t=0)=>e=>`\x1B[${e+t}m`,gpt=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,ypt=(t=0)=>(e,I,l)=>`\x1B[${38+t};2;${e};${I};${l}m`,wa={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Ban=Object.keys(wa.modifier),GEI=Object.keys(wa.color),bEI=Object.keys(wa.bgColor),San=[...GEI,...bEI];uEI=mEI(),ZZ=uEI});import Ave from"node:process";import hEI from"node:os";import Rpt from"node:tty";function Nh(t,e=globalThis.Deno?globalThis.Deno.args:Ave.argv){let I=t.startsWith("-")?"":t.length===1?"-":"--",l=e.indexOf(I+t),n=e.indexOf("--");return l!==-1&&(n===-1||l<n)}function pEI(){if("FORCE_COLOR"in Qa)return Qa.FORCE_COLOR==="true"?1:Qa.FORCE_COLOR==="false"?0:Qa.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(Qa.FORCE_COLOR,10),3)}function ZEI(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function WEI(t,{streamIsTTY:e,sniffFlags:I=!0}={}){let l=pEI();l!==void 0&&(Xse=l);let n=I?Xse:l;if(n===0)return 0;if(I){if(Nh("color=16m")||Nh("color=full")||Nh("color=truecolor"))return 3;if(Nh("color=256"))return 2}if("TF_BUILD"in Qa&&"AGENT_NAME"in Qa)return 1;if(t&&!e&&n===void 0)return 0;let r=n||0;if(Qa.TERM==="dumb")return r;if(Ave.platform==="win32"){let a=hEI.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in Qa)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(a=>a in Qa)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(a=>a in Qa)||Qa.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in Qa)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Qa.TEAMCITY_VERSION)?1:0;if(Qa.COLORTERM==="truecolor"||Qa.TERM==="xterm-kitty"||Qa.TERM==="xterm-ghostty"||Qa.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Qa){let a=Number.parseInt((Qa.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Qa.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Qa.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Qa.TERM)||"COLORTERM"in Qa?1:r}function Apt(t,e={}){let I=WEI(t,{streamIsTTY:t&&t.isTTY,...e});return ZEI(I)}var Qa,Xse,NEI,Fpt,wpt=m(()=>{({env:Qa}=Ave);Nh("no-color")||Nh("no-colors")||Nh("color=false")||Nh("color=never")?Xse=0:(Nh("color")||Nh("colors")||Nh("color=true")||Nh("color=always"))&&(Xse=1);NEI={stdout:Apt({isTTY:Rpt.isatty(1)}),stderr:Apt({isTTY:Rpt.isatty(2)})},Fpt=NEI});function Qpt(t,e,I){let l=t.indexOf(e);if(l===-1)return t;let n=e.length,r=0,a="";do a+=t.slice(r,l)+e+I,r=l+n,l=t.indexOf(e,r);while(l!==-1);return a+=t.slice(r),a}function Ept(t,e,I,l){let n=0,r="";do{let a=t[l-1]==="\r";r+=t.slice(n,a?l-1:l)+e+(a?`\r
|
|
609
609
|
`:`
|
|
610
610
|
`)+I,n=l+1,l=t.indexOf(`
|
|
611
|
-
`,n)}while(l!==-1);return r+=t.slice(n),r}var
|
|
612
|
-
`);return r!==-1&&(e=
|
|
611
|
+
`,n)}while(l!==-1);return r+=t.slice(n),r}var vpt=m(()=>{});function Xj(t){return gEI(t)}var Xpt,Hpt,Fve,A3,vj,Cpt,F3,YEI,gEI,wve,yEI,VEI,Qve,Hse,REI,AEI,qan,Tm,fpt=m(()=>{Vpt();wpt();vpt();({stdout:Xpt,stderr:Hpt}=Fpt),Fve=Symbol("GENERATOR"),A3=Symbol("STYLER"),vj=Symbol("IS_EMPTY"),Cpt=["ansi","ansi","ansi256","ansi16m"],F3=Object.create(null),YEI=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let I=Xpt?Xpt.level:0;t.level=e.level===void 0?I:e.level},gEI=t=>{let e=(...I)=>I.join(" ");return YEI(e,t),Object.setPrototypeOf(e,Xj.prototype),e};Object.setPrototypeOf(Xj.prototype,Function.prototype);for(let[t,e]of Object.entries(ZZ))F3[t]={get(){let I=Hse(this,Qve(e.open,e.close,this[A3]),this[vj]);return Object.defineProperty(this,t,{value:I}),I}};F3.visible={get(){let t=Hse(this,this[A3],!0);return Object.defineProperty(this,"visible",{value:t}),t}};wve=(t,e,I,...l)=>t==="rgb"?e==="ansi16m"?ZZ[I].ansi16m(...l):e==="ansi256"?ZZ[I].ansi256(ZZ.rgbToAnsi256(...l)):ZZ[I].ansi(ZZ.rgbToAnsi(...l)):t==="hex"?wve("rgb",e,I,...ZZ.hexToRgb(...l)):ZZ[I][t](...l),yEI=["rgb","hex","ansi256"];for(let t of yEI){F3[t]={get(){let{level:I}=this;return function(...l){let n=Qve(wve(t,Cpt[I],"color",...l),ZZ.color.close,this[A3]);return Hse(this,n,this[vj])}}};let e="bg"+t[0].toUpperCase()+t.slice(1);F3[e]={get(){let{level:I}=this;return function(...l){let n=Qve(wve(t,Cpt[I],"bgColor",...l),ZZ.bgColor.close,this[A3]);return Hse(this,n,this[vj])}}}}VEI=Object.defineProperties(()=>{},{...F3,level:{enumerable:!0,get(){return this[Fve].level},set(t){this[Fve].level=t}}}),Qve=(t,e,I)=>{let l,n;return I===void 0?(l=t,n=e):(l=I.openAll+t,n=e+I.closeAll),{open:t,close:e,openAll:l,closeAll:n,parent:I}},Hse=(t,e,I)=>{let l=(...n)=>REI(l,n.length===1?""+n[0]:n.join(" "));return Object.setPrototypeOf(l,VEI),l[Fve]=t,l[A3]=e,l[vj]=I,l},REI=(t,e)=>{if(t.level<=0||!e)return t[vj]?"":e;let I=t[A3];if(I===void 0)return e;let{openAll:l,closeAll:n}=I;if(e.includes("\x1B"))for(;I!==void 0;)e=Qpt(e,I.close,I.open),I=I.parent;let r=e.indexOf(`
|
|
612
|
+
`);return r!==-1&&(e=Ept(e,n,l,r)),l+e+n};Object.defineProperties(Xj.prototype,F3);AEI=Xj(),qan=Xj({level:Hpt?Hpt.level:0}),Tm=AEI});function Jpt(t){return t==="auto"||t==="dark"||t==="light"}var Lpt,tsn,Isn,kpt=m(()=>{"use strict";fpt();xE();Lpt=(t,e)=>{let I=t?Tm.cyanBright:Tm.blueBright,l=t?Tm.magentaBright:Tm.magenta;return{heading:Tm.bold,firstHeading:Tm.whiteBright.bold,strong:Tm.bold,em:Tm.italic,del:Tm.strikethrough,hr:Tm.white,link:I,href:I,image:(n,r,a)=>l(a?`Image: ${a} \u2192 ${n}`:`Image: ${n}`),codespan:Tm.cyan,code:Tm.cyan,list:(n,r,a)=>{let s=n.replace(/^(\s*)\* /gm,"$1- ");return a&&(s=s.split(`
|
|
613
613
|
`).map(i=>i.startsWith(a)?i.slice(a.length):i).join(`
|
|
614
|
-
`)),s.trimEnd()},reflowText:!0,width:e,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2,tableOptions:{style:{compact:!1}}}}
|
|
615
|
-
`).filter(r=>r.trim()),l=I.length;if(l===0)return"No output";if(e==="grep"||e==="glob")return`${l} ${l===1?"match":"matches"}`;if(e==="view")return`${l} line${l===1?"":"s"}`;if(e==="bash"||e==="local_shell")return`${l} line${l===1?"":"s"}`;let n=kEI(I[0],60);return l===1?n:`${l} lines`}function
|
|
616
|
-
`).length<=e}function
|
|
614
|
+
`)),s.trimEnd()},reflowText:!0,width:e,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2,tableOptions:{style:{compact:!1}}}},tsn=Lpt(!0),Isn=Lpt(!1)});function xpt(t,e){switch(t.type){case"copilot":return e.onCopilot(t);case"error":return e.onError(t);case"group_tool_call_requested":return e.onGroupToolCallRequested(t);case"group_tool_call_completed":return e.onGroupToolCallCompleted(t);case"info":return e.onInfo(t);case"tool_call_requested":return e.onToolCallRequested(t);case"tool_call_completed":return e.onToolCallCompleted(t);case"user":return e.onUser(t);case"handoff":return e.onHandoff(t);default:eh(t,"Unknown timeline entry type")}}var FEI,wEI,QEI,EEI,vEI,XEI,HEI,CEI,fEI,JEI,rsn,asn,ssn,osn,Eve,csn,isn,vve=m(()=>{"use strict";ac();BQ();FEI=Ue({command:P(),description:P(),timeout:ul().optional(),sessionId:P().optional(),async:al().optional()}),wEI=Ue({sessionId:P(),input:P(),delay:ul().optional()}),QEI=Ue({sessionId:P(),delay:ul()}),EEI=Ue({sessionId:P()}),vEI=ki([FEI,wEI,QEI,EEI]),XEI=Ue({command:gt("view"),path:P(),view_range:Yee([ul(),ul()]).optional()}),HEI=Ue({command:gt("create"),path:P(),file_text:P()}),CEI=Ue({command:gt("str_replace"),path:P(),new_str:P().optional(),old_str:P()}),fEI=Ue({command:gt("insert"),path:P(),insert_line:ul(),new_str:P()}),JEI=mS("command",[XEI,HEI,CEI,fEI]),rsn=Ue({path:P(),view_range:Yee([ul(),ul()]).optional()}),asn=Ue({path:P(),file_text:P()}),ssn=Ue({path:P(),old_str:P(),new_str:P().optional()}),osn=Ue({command:gt("apply_patch"),actions:Sr(Ue({actionLabel:P(),path:P(),additions:ul().optional(),deletions:ul().optional()}))}),Eve=ki([vEI,JEI,Rp()]),csn=Ue({pattern:P(),path:P().optional(),output_mode:xi(["content","files_with_matches","count"]).optional(),glob:P().optional(),type:P().optional(),"-i":al().optional(),"-A":ul().optional(),"-B":ul().optional(),"-C":ul().optional(),"-n":al().optional(),head_limit:ul().optional(),multiline:al().optional()}),isn=Ue({pattern:P(),path:P().optional()})});import{writeFile as LEI}from"node:fs/promises";function kEI(t,e){return t.length<=e?t:t.substring(0,e-3)+"..."}function Bpt(t,e){let I=t.split(`
|
|
615
|
+
`).filter(r=>r.trim()),l=I.length;if(l===0)return"No output";if(e==="grep"||e==="glob")return`${l} ${l===1?"match":"matches"}`;if(e==="view")return`${l} line${l===1?"":"s"}`;if(e==="bash"||e==="local_shell")return`${l} line${l===1?"":"s"}`;let n=kEI(I[0],60);return l===1?n:`${l} lines`}function Spt(t,e){if(t==="grep"){let I=[],l=e.pattern;return I.push(`"${l}"`),e.glob?I.push(`in ${e.glob}`):e.type&&I.push(`in ${e.type} files`),e.path&&e.path!=="."&&I.push(`(${e.path})`),I.join(" ")}if(t==="glob"){let I=[],l=e.pattern;return I.push(`"${l}"`),e.path&&e.path!=="."&&I.push(`in ${e.path}`),I.join(" ")}if(t==="bash"||t==="local_shell")return`$ ${e.command}`;if(t==="view"){let I=e.path,l=e.view_range;return l?`${I} (lines ${l[0]}-${l[1]})`:I}return t==="edit"||t==="create"?e.path:null}function xEI(t,e=5){return t.split(`
|
|
616
|
+
`).length<=e}function zpt(t){return t.includes("diff --git")||t.includes("@@")&&(t.includes("+++")||t.includes("---"))}function BEI(t){return t.includes("</details>")||t.includes("<details")||t.includes("</summary>")||t.includes("<summary")}function Cse(t){return t.replace(/</g,"\\<").replace(/>/g,"\\>")}function SEI(t){let e=0,I=0;for(let l of t)l==="`"?(I++,e=Math.max(e,I)):I=0;return e}function SE(t,e=""){let I=SEI(t),l=Math.max(3,I+1),n="`".repeat(l);return`${n}${e}
|
|
617
617
|
${t}
|
|
618
|
-
${n}`}function
|
|
618
|
+
${n}`}function Xve(t){return xpt(t,{onCopilot:e=>`### \u{1F4AC} Copilot
|
|
619
619
|
|
|
620
620
|
${Cse(e.text)}
|
|
621
621
|
`,onError:e=>`### \u274C Error
|
|
@@ -629,7 +629,7 @@ ${Cse(e.text)}
|
|
|
629
629
|
${Cse(e.text)}
|
|
630
630
|
`,onToolCallRequested:e=>{let I=`### \u{1F527} \`${e.name}\``;e.intentionSummary&&(I+=`
|
|
631
631
|
|
|
632
|
-
**${e.intentionSummary}**`);let l=e.arguments?
|
|
632
|
+
**${e.intentionSummary}**`);let l=e.arguments?Spt(e.name,e.arguments):null;if(l)I+=`
|
|
633
633
|
|
|
634
634
|
${l}`;else if(e.arguments){let n=JSON.stringify(e.arguments,null,2);I+=`
|
|
635
635
|
|
|
@@ -640,7 +640,7 @@ ${SE(n,"json")}
|
|
|
640
640
|
|
|
641
641
|
</details>`}if(I+=`
|
|
642
642
|
|
|
643
|
-
`,e.partialOutput){let n=
|
|
643
|
+
`,e.partialOutput){let n=Bpt(e.partialOutput,e.name);I+=`<details>
|
|
644
644
|
<summary>Partial Output \u2022 ${n}</summary>
|
|
645
645
|
|
|
646
646
|
${SE(e.partialOutput)}
|
|
@@ -649,7 +649,7 @@ ${SE(e.partialOutput)}
|
|
|
649
649
|
|
|
650
650
|
`}return I},onToolCallCompleted:e=>{let I="";e.result.type==="success"?I="\u2705":e.result.type==="failure"?I="\u274C":e.result.type==="rejected"?I="\u{1F6AB}":e.result.type==="denied"&&(I="\u26D4");let l=`### ${I} \`${e.name}\``;e.intentionSummary&&(l+=`
|
|
651
651
|
|
|
652
|
-
**${e.intentionSummary}**`);let n=e.arguments?
|
|
652
|
+
**${e.intentionSummary}**`);let n=e.arguments?Spt(e.name,e.arguments):null;if(n)l+=`
|
|
653
653
|
|
|
654
654
|
${n}`;else if(e.arguments){let r=JSON.stringify(e.arguments,null,2);l+=`
|
|
655
655
|
|
|
@@ -660,22 +660,22 @@ ${SE(r,"json")}
|
|
|
660
660
|
|
|
661
661
|
</details>`}if(l+=`
|
|
662
662
|
|
|
663
|
-
`,e.result.type==="success"||e.result.type==="failure"||e.result.type==="denied"){let r=e.result.log||"";if(r){let a=
|
|
663
|
+
`,e.result.type==="success"||e.result.type==="failure"||e.result.type==="denied"){let r=e.result.log||"";if(r){let a=Bpt(r,e.name),s=BEI(r);if(!xEI(r)&&!s){let c=zpt(r),i=r.trimEnd(),d=e.result.markdown?i:c?SE(i,"diff"):SE(i);l+=`<details>
|
|
664
664
|
<summary>${a}</summary>
|
|
665
665
|
|
|
666
666
|
${d}
|
|
667
667
|
|
|
668
668
|
</details>
|
|
669
669
|
|
|
670
|
-
`}else{let c=
|
|
670
|
+
`}else{let c=zpt(r),i=e.result.markdown?r:c?SE(r,"diff"):SE(r);l+=`${i}
|
|
671
671
|
|
|
672
672
|
`}}}else e.result.type==="rejected"&&(l+=`_Rejected by user_
|
|
673
673
|
|
|
674
|
-
`);return l},onGroupToolCallRequested:e=>{let I=e.timelineEntries.map(l=>
|
|
674
|
+
`);return l},onGroupToolCallRequested:e=>{let I=e.timelineEntries.map(l=>Xve(l)).join(`
|
|
675
675
|
`);return`### \u{1F4E6} ${e.title}
|
|
676
676
|
|
|
677
677
|
${I}
|
|
678
|
-
`},onGroupToolCallCompleted:e=>{let I=e.timelineEntries.map(l=>
|
|
678
|
+
`},onGroupToolCallCompleted:e=>{let I=e.timelineEntries.map(l=>Xve(l)).join(`
|
|
679
679
|
`);return`### \u{1F4E6} ${e.title} (Completed)
|
|
680
680
|
|
|
681
681
|
${I}
|
|
@@ -683,7 +683,7 @@ ${I}
|
|
|
683
683
|
**Summary:** ${e.summary}`:"";return`### \u{1F504} Session Handoff
|
|
684
684
|
|
|
685
685
|
**Repository:** ${I}${l}
|
|
686
|
-
`}})}function
|
|
686
|
+
`}})}function Upt(t,e,I){let l=new Date,n=Math.floor((l.getTime()-I.getTime())/1e3),r=Math.floor(n/60),a=n%60,s=r>0?`${r}m ${a}s`:`${a}s`,o=`# \u{1F916} Copilot CLI Session
|
|
687
687
|
|
|
688
688
|
> **Session ID:** \`${e}\`
|
|
689
689
|
> **Started:** ${I.toLocaleString()}
|
|
@@ -692,39 +692,39 @@ ${I}
|
|
|
692
692
|
|
|
693
693
|
`,c=t.map(d=>{let G=Math.floor((d.timestamp.getTime()-I.getTime())/1e3);return`<sub>\u23F1\uFE0F ${G<60?`${G}s`:`${Math.floor(G/60)}m ${G%60}s`}</sub>
|
|
694
694
|
|
|
695
|
-
`+
|
|
695
|
+
`+Xve(d)}).join(`
|
|
696
696
|
---
|
|
697
697
|
|
|
698
698
|
`);return o+c+`
|
|
699
699
|
---
|
|
700
700
|
|
|
701
701
|
<sub>Generated by [GitHub Copilot CLI](https://github.com/features/copilot/cli)</sub>
|
|
702
|
-
`}async function
|
|
703
|
-
`;break;case 114:Y+="\r";break;case 116:Y+=" ";break;case 117:let E=G(4,!0);E>=0?Y+=String.fromCharCode(E):d=4;break;default:d=5}y=l;continue}if(w>=0&&w<=31)if(
|
|
704
|
-
`),s++,c=l,a=14;switch(Y){case 123:return l++,a=1;case 125:return l++,a=2;case 91:return l++,a=3;case 93:return l++,a=4;case 58:return l++,a=6;case 44:return l++,a=5;case 34:return l++,n=h(),a=10;case 47:let y=l-1;if(t.charCodeAt(l+1)===47){for(l+=2;l<I&&!
|
|
702
|
+
`}async function Opt(t,e,I,l){let n=Upt(t,e,I);await LEI(l,n,"utf-8")}function zEI(t){let e=t.find(r=>r.type==="user");if(!e||e.type!=="user")return"copilot-cli-session";let I=e.text,l=I.lastIndexOf("<reminder>");l!==-1&&(I=I.substring(0,l).trim());let n=I.replace(/\s+/g," ").trim();return n.length>75&&(n=n.substring(0,55).trim()+"..."),n=n.split("").filter(r=>{let a=r.charCodeAt(0);return!(a<32||a===127||'/\\:*?"<>|'.includes(r))}).join(""),n||"copilot-cli-session"}async function Mpt(t,e,I,l,n){let r=Upt(t,e,I),a=new M4({auth:l}),s=zEI(t),c=`Coding session with ${n?`@${n}`:"a user"} and Copilot CLI - https://github.com/features/copilot/cli`,i=await a.request("POST /gists",{description:c,public:!1,files:{[`${s}.md`]:{content:r}},headers:{"X-GitHub-Api-Version":"2022-11-28"}});if(!i.data.html_url)throw new Error("Failed to create gist: no URL returned");return i.data.html_url}var Tpt=m(()=>{"use strict";tae();vve()});function Hve(t){return t()}var Cve=m(()=>{"use strict"});function jpt(){return UEI===!0}var UEI,Dpt=m(()=>{"use strict"});function Cj(t,e=!1){let I=t.length,l=0,n="",r=0,a=16,s=0,o=0,c=0,i=0,d=0;function G(Y,y){let w=0,C=0;for(;w<Y||!y;){let E=t.charCodeAt(l);if(E>=48&&E<=57)C=C*16+E-48;else if(E>=65&&E<=70)C=C*16+E-65+10;else if(E>=97&&E<=102)C=C*16+E-97+10;else break;l++,w++}return w<Y&&(C=-1),C}function b(Y){l=Y,n="",r=0,a=16,d=0}function u(){let Y=l;if(t.charCodeAt(l)===48)l++;else for(l++;l<t.length&&w3(t.charCodeAt(l));)l++;if(l<t.length&&t.charCodeAt(l)===46)if(l++,l<t.length&&w3(t.charCodeAt(l)))for(l++;l<t.length&&w3(t.charCodeAt(l));)l++;else return d=3,t.substring(Y,l);let y=l;if(l<t.length&&(t.charCodeAt(l)===69||t.charCodeAt(l)===101))if(l++,(l<t.length&&t.charCodeAt(l)===43||t.charCodeAt(l)===45)&&l++,l<t.length&&w3(t.charCodeAt(l))){for(l++;l<t.length&&w3(t.charCodeAt(l));)l++;y=l}else d=3;return t.substring(Y,y)}function h(){let Y="",y=l;for(;;){if(l>=I){Y+=t.substring(y,l),d=2;break}let w=t.charCodeAt(l);if(w===34){Y+=t.substring(y,l),l++;break}if(w===92){if(Y+=t.substring(y,l),l++,l>=I){d=2;break}switch(t.charCodeAt(l++)){case 34:Y+='"';break;case 92:Y+="\\";break;case 47:Y+="/";break;case 98:Y+="\b";break;case 102:Y+="\f";break;case 110:Y+=`
|
|
703
|
+
`;break;case 114:Y+="\r";break;case 116:Y+=" ";break;case 117:let E=G(4,!0);E>=0?Y+=String.fromCharCode(E):d=4;break;default:d=5}y=l;continue}if(w>=0&&w<=31)if(Hj(w)){Y+=t.substring(y,l),d=2;break}else d=6;l++}return Y}function p(){if(n="",d=0,r=l,o=s,i=c,l>=I)return r=I,a=17;let Y=t.charCodeAt(l);if(fve(Y)){do l++,n+=String.fromCharCode(Y),Y=t.charCodeAt(l);while(fve(Y));return a=15}if(Hj(Y))return l++,n+=String.fromCharCode(Y),Y===13&&t.charCodeAt(l)===10&&(l++,n+=`
|
|
704
|
+
`),s++,c=l,a=14;switch(Y){case 123:return l++,a=1;case 125:return l++,a=2;case 91:return l++,a=3;case 93:return l++,a=4;case 58:return l++,a=6;case 44:return l++,a=5;case 34:return l++,n=h(),a=10;case 47:let y=l-1;if(t.charCodeAt(l+1)===47){for(l+=2;l<I&&!Hj(t.charCodeAt(l));)l++;return n=t.substring(y,l),a=12}if(t.charCodeAt(l+1)===42){l+=2;let w=I-1,C=!1;for(;l<w;){let E=t.charCodeAt(l);if(E===42&&t.charCodeAt(l+1)===47){l+=2,C=!0;break}l++,Hj(E)&&(E===13&&t.charCodeAt(l)===10&&l++,s++,c=l)}return C||(l++,d=1),n=t.substring(y,l),a=13}return n+=String.fromCharCode(Y),l++,a=16;case 45:if(n+=String.fromCharCode(Y),l++,l===I||!w3(t.charCodeAt(l)))return a=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return n+=u(),a=11;default:for(;l<I&&W(Y);)l++,Y=t.charCodeAt(l);if(r!==l){switch(n=t.substring(r,l),n){case"true":return a=8;case"false":return a=9;case"null":return a=7}return a=16}return n+=String.fromCharCode(Y),l++,a=16}}function W(Y){if(fve(Y)||Hj(Y))return!1;switch(Y){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function N(){let Y;do Y=p();while(Y>=12&&Y<=15);return Y}return{setPosition:b,getPosition:()=>l,scan:e?N:p,getToken:()=>a,getTokenValue:()=>n,getTokenOffset:()=>r,getTokenLength:()=>l-r,getTokenStartLine:()=>o,getTokenStartCharacter:()=>r-i,getTokenError:()=>d}}function fve(t){return t===32||t===9}function Hj(t){return t===10||t===13}function w3(t){return t>=48&&t<=57}var Kpt,fse=m(()=>{"use strict";(function(t){t[t.lineFeed=10]="lineFeed",t[t.carriageReturn=13]="carriageReturn",t[t.space=32]="space",t[t._0=48]="_0",t[t._1=49]="_1",t[t._2=50]="_2",t[t._3=51]="_3",t[t._4=52]="_4",t[t._5=53]="_5",t[t._6=54]="_6",t[t._7=55]="_7",t[t._8=56]="_8",t[t._9=57]="_9",t[t.a=97]="a",t[t.b=98]="b",t[t.c=99]="c",t[t.d=100]="d",t[t.e=101]="e",t[t.f=102]="f",t[t.g=103]="g",t[t.h=104]="h",t[t.i=105]="i",t[t.j=106]="j",t[t.k=107]="k",t[t.l=108]="l",t[t.m=109]="m",t[t.n=110]="n",t[t.o=111]="o",t[t.p=112]="p",t[t.q=113]="q",t[t.r=114]="r",t[t.s=115]="s",t[t.t=116]="t",t[t.u=117]="u",t[t.v=118]="v",t[t.w=119]="w",t[t.x=120]="x",t[t.y=121]="y",t[t.z=122]="z",t[t.A=65]="A",t[t.B=66]="B",t[t.C=67]="C",t[t.D=68]="D",t[t.E=69]="E",t[t.F=70]="F",t[t.G=71]="G",t[t.H=72]="H",t[t.I=73]="I",t[t.J=74]="J",t[t.K=75]="K",t[t.L=76]="L",t[t.M=77]="M",t[t.N=78]="N",t[t.O=79]="O",t[t.P=80]="P",t[t.Q=81]="Q",t[t.R=82]="R",t[t.S=83]="S",t[t.T=84]="T",t[t.U=85]="U",t[t.V=86]="V",t[t.W=87]="W",t[t.X=88]="X",t[t.Y=89]="Y",t[t.Z=90]="Z",t[t.asterisk=42]="asterisk",t[t.backslash=92]="backslash",t[t.closeBrace=125]="closeBrace",t[t.closeBracket=93]="closeBracket",t[t.colon=58]="colon",t[t.comma=44]="comma",t[t.dot=46]="dot",t[t.doubleQuote=34]="doubleQuote",t[t.minus=45]="minus",t[t.openBrace=123]="openBrace",t[t.openBracket=91]="openBracket",t[t.plus=43]="plus",t[t.slash=47]="slash",t[t.formFeed=12]="formFeed",t[t.tab=9]="tab"})(Kpt||(Kpt={}))});var jm,Q3,Jve,Ppt,qpt=m(()=>{jm=new Array(20).fill(0).map((t,e)=>" ".repeat(e)),Q3=200,Jve={" ":{"\n":new Array(Q3).fill(0).map((t,e)=>`
|
|
705
705
|
`+" ".repeat(e)),"\r":new Array(Q3).fill(0).map((t,e)=>"\r"+" ".repeat(e)),"\r\n":new Array(Q3).fill(0).map((t,e)=>`\r
|
|
706
706
|
`+" ".repeat(e))}," ":{"\n":new Array(Q3).fill(0).map((t,e)=>`
|
|
707
707
|
`+" ".repeat(e)),"\r":new Array(Q3).fill(0).map((t,e)=>"\r"+" ".repeat(e)),"\r\n":new Array(Q3).fill(0).map((t,e)=>`\r
|
|
708
|
-
`+" ".repeat(e))}},
|
|
708
|
+
`+" ".repeat(e))}},Ppt=[`
|
|
709
709
|
`,"\r",`\r
|
|
710
|
-
`]});function
|
|
710
|
+
`]});function Lve(t,e,I){let l,n,r,a,s;if(e){for(a=e.offset,s=a+e.length,r=a;r>0&&!fj(t,r-1);)r--;let w=s;for(;w<t.length&&!fj(t,w);)w++;n=t.substring(r,w),l=MEI(n,I)}else n=t,l=0,r=0,a=0,s=t.length;let o=TEI(I,t),c=Ppt.includes(o),i=0,d=0,G;I.insertSpaces?G=jm[I.tabSize||4]??E3(jm[1],I.tabSize||4):G=" ";let b=G===" "?" ":" ",u=Cj(n,!1),h=!1;function p(){if(i>1)return E3(o,i)+E3(G,l+d);let w=G.length*(l+d);return!c||w>Jve[b][o].length?o+E3(G,l+d):w<=0?o:Jve[b][o][w]}function W(){let w=u.scan();for(i=0;w===15||w===14;)w===14&&I.keepLines?i+=1:w===14&&(i=1),w=u.scan();return h=w===16||u.getTokenError()!==0,w}let N=[];function Y(w,C,E){!h&&(!e||C<s&&E>a)&&t.substring(C,E)!==w&&N.push({offset:C,length:E-C,content:w})}let y=W();if(I.keepLines&&i>0&&Y(E3(o,i),0,0),y!==17){let w=u.getTokenOffset()+r,C=G.length*l<20&&I.insertSpaces?jm[G.length*l]:E3(G,l);Y(C,r,w)}for(;y!==17;){let w=u.getTokenOffset()+u.getTokenLength()+r,C=W(),E="",X=!1;for(;i===0&&(C===12||C===13);){let x=u.getTokenOffset()+r;Y(jm[1],w,x),w=u.getTokenOffset()+u.getTokenLength()+r,X=C===12,E=X?p():"",C=W()}if(C===2)y!==1&&d--,I.keepLines&&i>0||!I.keepLines&&y!==1?E=p():I.keepLines&&(E=jm[1]);else if(C===4)y!==3&&d--,I.keepLines&&i>0||!I.keepLines&&y!==3?E=p():I.keepLines&&(E=jm[1]);else{switch(y){case 3:case 1:d++,I.keepLines&&i>0||!I.keepLines?E=p():E=jm[1];break;case 5:I.keepLines&&i>0||!I.keepLines?E=p():E=jm[1];break;case 12:E=p();break;case 13:i>0?E=p():X||(E=jm[1]);break;case 6:I.keepLines&&i>0?E=p():X||(E=jm[1]);break;case 10:I.keepLines&&i>0?E=p():C===6&&!X&&(E="");break;case 7:case 8:case 9:case 11:case 2:case 4:I.keepLines&&i>0?E=p():(C===12||C===13)&&!X?E=jm[1]:C!==5&&C!==17&&(h=!0);break;case 16:h=!0;break}i>0&&(C===12||C===13)&&(E=p())}C===17&&(I.keepLines&&i>0?E=p():E=I.insertFinalNewline?o:"");let f=u.getTokenOffset()+r;Y(E,w,f),y=C}return N}function E3(t,e){let I="";for(let l=0;l<e;l++)I+=t;return I}function MEI(t,e){let I=0,l=0,n=e.tabSize||4;for(;I<t.length;){let r=t.charAt(I);if(r===jm[1])l++;else if(r===" ")l+=n;else break;I++}return Math.floor(l/n)}function TEI(t,e){for(let I=0;I<e.length;I++){let l=e.charAt(I);if(l==="\r")return I+1<e.length&&e.charAt(I+1)===`
|
|
711
711
|
`?`\r
|
|
712
712
|
`:"\r";if(l===`
|
|
713
713
|
`)return`
|
|
714
714
|
`}return t&&t.eol||`
|
|
715
|
-
`}function
|
|
716
|
-
`.indexOf(t.charAt(e))!==-1}var Lve=m(()=>{"use strict";fse();Kpt()});function Ppt(t,e=[],I=fj.DEFAULT){let l=null,n=[],r=[];function a(o){Array.isArray(n)?n.push(o):l!==null&&(n[l]=o)}return xve(t,{onObjectBegin:()=>{let o={};a(o),r.push(n),n=o,l=null},onObjectProperty:o=>{l=o},onObjectEnd:()=>{n=r.pop()},onArrayBegin:()=>{let o=[];a(o),r.push(n),n=o,l=null},onArrayEnd:()=>{n=r.pop()},onLiteralValue:a,onError:(o,c,i)=>{e.push({error:o,offset:c,length:i})}},I),n[0]}function kve(t,e=[],I=fj.DEFAULT){let l={type:"array",offset:-1,length:-1,children:[],parent:void 0};function n(o){l.type==="property"&&(l.length=o-l.offset,l=l.parent)}function r(o){return l.children.push(o),o}xve(t,{onObjectBegin:o=>{l=r({type:"object",offset:o,length:-1,parent:l,children:[]})},onObjectProperty:(o,c,i)=>{l=r({type:"property",offset:c,length:-1,parent:l,children:[]}),l.children.push({type:"string",value:o,offset:c,length:i,parent:l})},onObjectEnd:(o,c)=>{n(o+c),l.length=o+c-l.offset,l=l.parent,n(o+c)},onArrayBegin:(o,c)=>{l=r({type:"array",offset:o,length:-1,parent:l,children:[]})},onArrayEnd:(o,c)=>{l.length=o+c-l.offset,l=l.parent,n(o+c)},onLiteralValue:(o,c,i)=>{r({type:DEI(o),offset:c,length:i,parent:l,value:o}),n(c+i)},onSeparator:(o,c,i)=>{l.type==="property"&&(o===":"?l.colonOffset=c:o===","&&n(c))},onError:(o,c,i)=>{e.push({error:o,offset:c,length:i})}},I);let s=l.children[0];return s&&delete s.parent,s}function Jse(t,e){if(!t)return;let I=t;for(let l of e)if(typeof l=="string"){if(I.type!=="object"||!Array.isArray(I.children))return;let n=!1;for(let r of I.children)if(Array.isArray(r.children)&&r.children[0].value===l&&r.children.length===2){I=r.children[1],n=!0;break}if(!n)return}else{let n=l;if(I.type!=="array"||n<0||!Array.isArray(I.children)||n>=I.children.length)return;I=I.children[n]}return I}function xve(t,e,I=fj.DEFAULT){let l=Hj(t,!1),n=[],r=0;function a(J){return J?()=>r===0&&J(l.getTokenOffset(),l.getTokenLength(),l.getTokenStartLine(),l.getTokenStartCharacter()):()=>!0}function s(J){return J?te=>r===0&&J(te,l.getTokenOffset(),l.getTokenLength(),l.getTokenStartLine(),l.getTokenStartCharacter()):()=>!0}function o(J){return J?te=>r===0&&J(te,l.getTokenOffset(),l.getTokenLength(),l.getTokenStartLine(),l.getTokenStartCharacter(),()=>n.slice()):()=>!0}function c(J){return J?()=>{r>0?r++:J(l.getTokenOffset(),l.getTokenLength(),l.getTokenStartLine(),l.getTokenStartCharacter(),()=>n.slice())===!1&&(r=1)}:()=>!0}function i(J){return J?()=>{r>0&&r--,r===0&&J(l.getTokenOffset(),l.getTokenLength(),l.getTokenStartLine(),l.getTokenStartCharacter())}:()=>!0}let d=c(e.onObjectBegin),G=o(e.onObjectProperty),b=i(e.onObjectEnd),u=c(e.onArrayBegin),h=i(e.onArrayEnd),p=o(e.onLiteralValue),W=s(e.onSeparator),N=a(e.onComment),Y=s(e.onError),y=I&&I.disallowComments,w=I&&I.allowTrailingComma;function C(){for(;;){let J=l.scan();switch(l.getTokenError()){case 4:E(14);break;case 5:E(15);break;case 3:E(13);break;case 1:y||E(11);break;case 2:E(12);break;case 6:E(16);break}switch(J){case 12:case 13:y?E(10):N();break;case 16:E(1);break;case 15:case 14:break;default:return J}}}function E(J,te=[],Je=[]){if(Y(J),te.length+Je.length>0){let ve=l.getToken();for(;ve!==17;){if(te.indexOf(ve)!==-1){C();break}else if(Je.indexOf(ve)!==-1)break;ve=C()}}}function X(J){let te=l.getTokenValue();return J?p(te):(G(te),n.push(te)),C(),!0}function f(){switch(l.getToken()){case 11:let J=l.getTokenValue(),te=Number(J);isNaN(te)&&(E(2),te=0),p(te);break;case 7:p(null);break;case 8:p(!0);break;case 9:p(!1);break;default:return!1}return C(),!0}function x(){return l.getToken()!==10?(E(3,[],[2,5]),!1):(X(!1),l.getToken()===6?(W(":"),C(),Qe()||E(4,[],[2,5])):E(5,[],[2,5]),n.pop(),!0)}function H(){d(),C();let J=!1;for(;l.getToken()!==2&&l.getToken()!==17;){if(l.getToken()===5){if(J||E(4,[],[]),W(","),C(),l.getToken()===2&&w)break}else J&&E(6,[],[]);x()||E(4,[],[2,5]),J=!0}return b(),l.getToken()!==2?E(7,[2],[]):C(),!0}function ne(){u(),C();let J=!0,te=!1;for(;l.getToken()!==4&&l.getToken()!==17;){if(l.getToken()===5){if(te||E(4,[],[]),W(","),C(),l.getToken()===4&&w)break}else te&&E(6,[],[]);J?(n.push(0),J=!1):n[n.length-1]++,Qe()||E(4,[],[4,5]),te=!0}return h(),J||n.pop(),l.getToken()!==4?E(8,[4],[]):C(),!0}function Qe(){switch(l.getToken()){case 3:return ne();case 1:return H();case 10:return X(!0);default:return f()}}return C(),l.getToken()===17?I.allowEmptyContent?!0:(E(4,[],[]),!1):Qe()?(l.getToken()!==17&&E(9,[],[]),!0):(E(4,[],[]),!1)}function DEI(t){switch(typeof t){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(t){if(Array.isArray(t))return"array"}else return"null";return"object"}default:return"null"}}var fj,Bve=m(()=>{"use strict";fse();(function(t){t.DEFAULT={allowTrailingComma:!1}})(fj||(fj={}))});function qpt(t,e,I,l){let n=e.slice(),a=kve(t,[]),s,o;for(;n.length>0&&(o=n.pop(),s=Jse(a,n),s===void 0&&I!==void 0);)typeof o=="string"?I={[o]:I}:I=[I];if(s)if(s.type==="object"&&typeof o=="string"&&Array.isArray(s.children)){let c=Jse(s,[o]);if(c!==void 0)if(I===void 0){if(!c.parent)throw new Error("Malformed AST");let i=s.children.indexOf(c.parent),d,G=c.parent.offset+c.parent.length;if(i>0){let b=s.children[i-1];d=b.offset+b.length}else d=s.offset+1,s.children.length>1&&(G=s.children[1].offset);return zE(t,{offset:d,length:G-d,content:""},l)}else return zE(t,{offset:c.offset,length:c.length,content:JSON.stringify(I)},l);else{if(I===void 0)return[];let i=`${JSON.stringify(o)}: ${JSON.stringify(I)}`,d=l.getInsertionIndex?l.getInsertionIndex(s.children.map(b=>b.children[0].value)):s.children.length,G;if(d>0){let b=s.children[d-1];G={offset:b.offset+b.length,length:0,content:","+i}}else s.children.length===0?G={offset:s.offset+1,length:0,content:i}:G={offset:s.offset+1,length:0,content:i+","};return zE(t,G,l)}}else if(s.type==="array"&&typeof o=="number"&&Array.isArray(s.children)){let c=o;if(c===-1){let i=`${JSON.stringify(I)}`,d;if(s.children.length===0)d={offset:s.offset+1,length:0,content:i};else{let G=s.children[s.children.length-1];d={offset:G.offset+G.length,length:0,content:","+i}}return zE(t,d,l)}else if(I===void 0&&s.children.length>=0){let i=o,d=s.children[i],G;if(s.children.length===1)G={offset:s.offset+1,length:s.length-2,content:""};else if(s.children.length-1===i){let b=s.children[i-1],u=b.offset+b.length,h=s.offset+s.length;G={offset:u,length:h-2-u,content:""}}else G={offset:d.offset,length:s.children[i+1].offset-d.offset,content:""};return zE(t,G,l)}else if(I!==void 0){let i,d=`${JSON.stringify(I)}`;if(!l.isArrayInsertion&&s.children.length>o){let G=s.children[o];i={offset:G.offset,length:G.length,content:d}}else if(s.children.length===0||o===0)i={offset:s.offset+1,length:0,content:s.children.length===0?d:d+","};else{let G=o>s.children.length?s.children.length:o,b=s.children[G-1];i={offset:b.offset+b.length,length:0,content:","+d}}return zE(t,i,l)}else throw new Error(`Can not ${I===void 0?"remove":l.isArrayInsertion?"insert":"modify"} Array index ${c} as length is not sufficient`)}else throw new Error(`Can not add ${typeof o!="number"?"index":"property"} to parent of type ${s.type}`);else{if(I===void 0)throw new Error("Can not delete in empty document");return zE(t,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(I)},l)}}function zE(t,e,I){if(!I.formattingOptions)return[e];let l=Lse(t,e),n=e.offset,r=e.offset+e.content.length;if(e.length===0||e.content.length===0){for(;n>0&&!Cj(l,n-1);)n--;for(;r<l.length&&!Cj(l,r);)r++}let a=Jve(l,{offset:n,length:r-n},{...I.formattingOptions,keepLines:!1});for(let o=a.length-1;o>=0;o--){let c=a[o];l=Lse(l,c),n=Math.min(n,c.offset),r=Math.max(r,c.offset+c.length),r+=c.content.length-c.length}let s=t.length-(l.length-r)-n;return[{offset:n,length:s,content:l.substring(n,r)}]}function Lse(t,e){return t.substring(0,e.offset)+e.content+t.substring(e.offset+e.length)}var _pt=m(()=>{"use strict";Lve();Bve()});function lZt(t,e,I,l){return qpt(t,e,I,l)}function nZt(t,e){let I=e.slice(0).sort((n,r)=>{let a=n.offset-r.offset;return a===0?n.length-r.length:a}),l=t.length;for(let n=I.length-1;n>=0;n--){let r=I[n];if(r.offset+r.length<=l)t=Lse(t,r);else throw new Error("Overlapping edit");l=r.offset}return t}var $pt,eZt,IZt,tZt,rZt=m(()=>{"use strict";Lve();_pt();fse();Bve();(function(t){t[t.None=0]="None",t[t.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",t[t.UnexpectedEndOfString=2]="UnexpectedEndOfString",t[t.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",t[t.InvalidUnicode=4]="InvalidUnicode",t[t.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",t[t.InvalidCharacter=6]="InvalidCharacter"})($pt||($pt={}));(function(t){t[t.OpenBraceToken=1]="OpenBraceToken",t[t.CloseBraceToken=2]="CloseBraceToken",t[t.OpenBracketToken=3]="OpenBracketToken",t[t.CloseBracketToken=4]="CloseBracketToken",t[t.CommaToken=5]="CommaToken",t[t.ColonToken=6]="ColonToken",t[t.NullKeyword=7]="NullKeyword",t[t.TrueKeyword=8]="TrueKeyword",t[t.FalseKeyword=9]="FalseKeyword",t[t.StringLiteral=10]="StringLiteral",t[t.NumericLiteral=11]="NumericLiteral",t[t.LineCommentTrivia=12]="LineCommentTrivia",t[t.BlockCommentTrivia=13]="BlockCommentTrivia",t[t.LineBreakTrivia=14]="LineBreakTrivia",t[t.Trivia=15]="Trivia",t[t.Unknown=16]="Unknown",t[t.EOF=17]="EOF"})(eZt||(eZt={}));IZt=Ppt;(function(t){t[t.InvalidSymbol=1]="InvalidSymbol",t[t.InvalidNumberFormat=2]="InvalidNumberFormat",t[t.PropertyNameExpected=3]="PropertyNameExpected",t[t.ValueExpected=4]="ValueExpected",t[t.ColonExpected=5]="ColonExpected",t[t.CommaExpected=6]="CommaExpected",t[t.CloseBraceExpected=7]="CloseBraceExpected",t[t.CloseBracketExpected=8]="CloseBracketExpected",t[t.EndOfFileExpected=9]="EndOfFileExpected",t[t.InvalidCommentToken=10]="InvalidCommentToken",t[t.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",t[t.UnexpectedEndOfString=12]="UnexpectedEndOfString",t[t.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",t[t.InvalidUnicode=14]="InvalidUnicode",t[t.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",t[t.InvalidCharacter=16]="InvalidCharacter"})(tZt||(tZt={}))});import{promises as kse}from"node:fs";import*as kj from"node:os";import*as v3 from"node:path";async function $EI(t,e){try{let I=new Date().toISOString().replace(/[:.]/g,"-"),l=`${e}.${I}.backup`;return await kse.copyFile(e,l),l}catch(I){return t.warning(`Failed to backup ${e}: ${Ae(I)}`),null}}function evI(t,e){let I=kj.platform(),l=Xve(()=>I==="darwin"?v3.join(kj.homedir(),"Library","Application Support"):I==="win32"?process.env.APPDATA?v3.join(process.env.APPDATA):(t.warning(`Unable to determine ${e} config path on Windows. APPDATA environment variable is not set.`),null):v3.join(kj.homedir(),".config"));return l===null?null:v3.join(l,e,"User")}async function oZt(t,e,I){let l=evI(t,I);return tvI(t,l,e,async n=>{await kse.mkdir(n,{recursive:!0})},async(n,r,a)=>{let s=await $EI(n,r);return await kse.writeFile(r,a,"utf8"),s})}async function tvI(t,e,I,l,n){if(!e)return{state:"failed",message:`Unable to determine ${I} config path.`};let r=v3.join(e,"keybindings.json"),a=null;try{await l(e);let s=[],o;try{let p=await kse.readFile(r,"utf8");o=p;try{let W=IZt(p);if(!Array.isArray(W))return{state:"failed",message:`Key bindings file for ${I} found but it is not a valid JSON array. Fix the file manually or delete it and try to setup the terminal again.
|
|
715
|
+
`}function fj(t,e){return`\r
|
|
716
|
+
`.indexOf(t.charAt(e))!==-1}var kve=m(()=>{"use strict";fse();qpt()});function _pt(t,e=[],I=Jj.DEFAULT){let l=null,n=[],r=[];function a(o){Array.isArray(n)?n.push(o):l!==null&&(n[l]=o)}return Bve(t,{onObjectBegin:()=>{let o={};a(o),r.push(n),n=o,l=null},onObjectProperty:o=>{l=o},onObjectEnd:()=>{n=r.pop()},onArrayBegin:()=>{let o=[];a(o),r.push(n),n=o,l=null},onArrayEnd:()=>{n=r.pop()},onLiteralValue:a,onError:(o,c,i)=>{e.push({error:o,offset:c,length:i})}},I),n[0]}function xve(t,e=[],I=Jj.DEFAULT){let l={type:"array",offset:-1,length:-1,children:[],parent:void 0};function n(o){l.type==="property"&&(l.length=o-l.offset,l=l.parent)}function r(o){return l.children.push(o),o}Bve(t,{onObjectBegin:o=>{l=r({type:"object",offset:o,length:-1,parent:l,children:[]})},onObjectProperty:(o,c,i)=>{l=r({type:"property",offset:c,length:-1,parent:l,children:[]}),l.children.push({type:"string",value:o,offset:c,length:i,parent:l})},onObjectEnd:(o,c)=>{n(o+c),l.length=o+c-l.offset,l=l.parent,n(o+c)},onArrayBegin:(o,c)=>{l=r({type:"array",offset:o,length:-1,parent:l,children:[]})},onArrayEnd:(o,c)=>{l.length=o+c-l.offset,l=l.parent,n(o+c)},onLiteralValue:(o,c,i)=>{r({type:DEI(o),offset:c,length:i,parent:l,value:o}),n(c+i)},onSeparator:(o,c,i)=>{l.type==="property"&&(o===":"?l.colonOffset=c:o===","&&n(c))},onError:(o,c,i)=>{e.push({error:o,offset:c,length:i})}},I);let s=l.children[0];return s&&delete s.parent,s}function Jse(t,e){if(!t)return;let I=t;for(let l of e)if(typeof l=="string"){if(I.type!=="object"||!Array.isArray(I.children))return;let n=!1;for(let r of I.children)if(Array.isArray(r.children)&&r.children[0].value===l&&r.children.length===2){I=r.children[1],n=!0;break}if(!n)return}else{let n=l;if(I.type!=="array"||n<0||!Array.isArray(I.children)||n>=I.children.length)return;I=I.children[n]}return I}function Bve(t,e,I=Jj.DEFAULT){let l=Cj(t,!1),n=[],r=0;function a(J){return J?()=>r===0&&J(l.getTokenOffset(),l.getTokenLength(),l.getTokenStartLine(),l.getTokenStartCharacter()):()=>!0}function s(J){return J?te=>r===0&&J(te,l.getTokenOffset(),l.getTokenLength(),l.getTokenStartLine(),l.getTokenStartCharacter()):()=>!0}function o(J){return J?te=>r===0&&J(te,l.getTokenOffset(),l.getTokenLength(),l.getTokenStartLine(),l.getTokenStartCharacter(),()=>n.slice()):()=>!0}function c(J){return J?()=>{r>0?r++:J(l.getTokenOffset(),l.getTokenLength(),l.getTokenStartLine(),l.getTokenStartCharacter(),()=>n.slice())===!1&&(r=1)}:()=>!0}function i(J){return J?()=>{r>0&&r--,r===0&&J(l.getTokenOffset(),l.getTokenLength(),l.getTokenStartLine(),l.getTokenStartCharacter())}:()=>!0}let d=c(e.onObjectBegin),G=o(e.onObjectProperty),b=i(e.onObjectEnd),u=c(e.onArrayBegin),h=i(e.onArrayEnd),p=o(e.onLiteralValue),W=s(e.onSeparator),N=a(e.onComment),Y=s(e.onError),y=I&&I.disallowComments,w=I&&I.allowTrailingComma;function C(){for(;;){let J=l.scan();switch(l.getTokenError()){case 4:E(14);break;case 5:E(15);break;case 3:E(13);break;case 1:y||E(11);break;case 2:E(12);break;case 6:E(16);break}switch(J){case 12:case 13:y?E(10):N();break;case 16:E(1);break;case 15:case 14:break;default:return J}}}function E(J,te=[],Je=[]){if(Y(J),te.length+Je.length>0){let ve=l.getToken();for(;ve!==17;){if(te.indexOf(ve)!==-1){C();break}else if(Je.indexOf(ve)!==-1)break;ve=C()}}}function X(J){let te=l.getTokenValue();return J?p(te):(G(te),n.push(te)),C(),!0}function f(){switch(l.getToken()){case 11:let J=l.getTokenValue(),te=Number(J);isNaN(te)&&(E(2),te=0),p(te);break;case 7:p(null);break;case 8:p(!0);break;case 9:p(!1);break;default:return!1}return C(),!0}function x(){return l.getToken()!==10?(E(3,[],[2,5]),!1):(X(!1),l.getToken()===6?(W(":"),C(),Qe()||E(4,[],[2,5])):E(5,[],[2,5]),n.pop(),!0)}function H(){d(),C();let J=!1;for(;l.getToken()!==2&&l.getToken()!==17;){if(l.getToken()===5){if(J||E(4,[],[]),W(","),C(),l.getToken()===2&&w)break}else J&&E(6,[],[]);x()||E(4,[],[2,5]),J=!0}return b(),l.getToken()!==2?E(7,[2],[]):C(),!0}function ne(){u(),C();let J=!0,te=!1;for(;l.getToken()!==4&&l.getToken()!==17;){if(l.getToken()===5){if(te||E(4,[],[]),W(","),C(),l.getToken()===4&&w)break}else te&&E(6,[],[]);J?(n.push(0),J=!1):n[n.length-1]++,Qe()||E(4,[],[4,5]),te=!0}return h(),J||n.pop(),l.getToken()!==4?E(8,[4],[]):C(),!0}function Qe(){switch(l.getToken()){case 3:return ne();case 1:return H();case 10:return X(!0);default:return f()}}return C(),l.getToken()===17?I.allowEmptyContent?!0:(E(4,[],[]),!1):Qe()?(l.getToken()!==17&&E(9,[],[]),!0):(E(4,[],[]),!1)}function DEI(t){switch(typeof t){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(t){if(Array.isArray(t))return"array"}else return"null";return"object"}default:return"null"}}var Jj,Sve=m(()=>{"use strict";fse();(function(t){t.DEFAULT={allowTrailingComma:!1}})(Jj||(Jj={}))});function $pt(t,e,I,l){let n=e.slice(),a=xve(t,[]),s,o;for(;n.length>0&&(o=n.pop(),s=Jse(a,n),s===void 0&&I!==void 0);)typeof o=="string"?I={[o]:I}:I=[I];if(s)if(s.type==="object"&&typeof o=="string"&&Array.isArray(s.children)){let c=Jse(s,[o]);if(c!==void 0)if(I===void 0){if(!c.parent)throw new Error("Malformed AST");let i=s.children.indexOf(c.parent),d,G=c.parent.offset+c.parent.length;if(i>0){let b=s.children[i-1];d=b.offset+b.length}else d=s.offset+1,s.children.length>1&&(G=s.children[1].offset);return zE(t,{offset:d,length:G-d,content:""},l)}else return zE(t,{offset:c.offset,length:c.length,content:JSON.stringify(I)},l);else{if(I===void 0)return[];let i=`${JSON.stringify(o)}: ${JSON.stringify(I)}`,d=l.getInsertionIndex?l.getInsertionIndex(s.children.map(b=>b.children[0].value)):s.children.length,G;if(d>0){let b=s.children[d-1];G={offset:b.offset+b.length,length:0,content:","+i}}else s.children.length===0?G={offset:s.offset+1,length:0,content:i}:G={offset:s.offset+1,length:0,content:i+","};return zE(t,G,l)}}else if(s.type==="array"&&typeof o=="number"&&Array.isArray(s.children)){let c=o;if(c===-1){let i=`${JSON.stringify(I)}`,d;if(s.children.length===0)d={offset:s.offset+1,length:0,content:i};else{let G=s.children[s.children.length-1];d={offset:G.offset+G.length,length:0,content:","+i}}return zE(t,d,l)}else if(I===void 0&&s.children.length>=0){let i=o,d=s.children[i],G;if(s.children.length===1)G={offset:s.offset+1,length:s.length-2,content:""};else if(s.children.length-1===i){let b=s.children[i-1],u=b.offset+b.length,h=s.offset+s.length;G={offset:u,length:h-2-u,content:""}}else G={offset:d.offset,length:s.children[i+1].offset-d.offset,content:""};return zE(t,G,l)}else if(I!==void 0){let i,d=`${JSON.stringify(I)}`;if(!l.isArrayInsertion&&s.children.length>o){let G=s.children[o];i={offset:G.offset,length:G.length,content:d}}else if(s.children.length===0||o===0)i={offset:s.offset+1,length:0,content:s.children.length===0?d:d+","};else{let G=o>s.children.length?s.children.length:o,b=s.children[G-1];i={offset:b.offset+b.length,length:0,content:","+d}}return zE(t,i,l)}else throw new Error(`Can not ${I===void 0?"remove":l.isArrayInsertion?"insert":"modify"} Array index ${c} as length is not sufficient`)}else throw new Error(`Can not add ${typeof o!="number"?"index":"property"} to parent of type ${s.type}`);else{if(I===void 0)throw new Error("Can not delete in empty document");return zE(t,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(I)},l)}}function zE(t,e,I){if(!I.formattingOptions)return[e];let l=Lse(t,e),n=e.offset,r=e.offset+e.content.length;if(e.length===0||e.content.length===0){for(;n>0&&!fj(l,n-1);)n--;for(;r<l.length&&!fj(l,r);)r++}let a=Lve(l,{offset:n,length:r-n},{...I.formattingOptions,keepLines:!1});for(let o=a.length-1;o>=0;o--){let c=a[o];l=Lse(l,c),n=Math.min(n,c.offset),r=Math.max(r,c.offset+c.length),r+=c.content.length-c.length}let s=t.length-(l.length-r)-n;return[{offset:n,length:s,content:l.substring(n,r)}]}function Lse(t,e){return t.substring(0,e.offset)+e.content+t.substring(e.offset+e.length)}var eZt=m(()=>{"use strict";kve();Sve()});function rZt(t,e,I,l){return $pt(t,e,I,l)}function aZt(t,e){let I=e.slice(0).sort((n,r)=>{let a=n.offset-r.offset;return a===0?n.length-r.length:a}),l=t.length;for(let n=I.length-1;n>=0;n--){let r=I[n];if(r.offset+r.length<=l)t=Lse(t,r);else throw new Error("Overlapping edit");l=r.offset}return t}var tZt,IZt,nZt,lZt,sZt=m(()=>{"use strict";kve();eZt();fse();Sve();(function(t){t[t.None=0]="None",t[t.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",t[t.UnexpectedEndOfString=2]="UnexpectedEndOfString",t[t.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",t[t.InvalidUnicode=4]="InvalidUnicode",t[t.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",t[t.InvalidCharacter=6]="InvalidCharacter"})(tZt||(tZt={}));(function(t){t[t.OpenBraceToken=1]="OpenBraceToken",t[t.CloseBraceToken=2]="CloseBraceToken",t[t.OpenBracketToken=3]="OpenBracketToken",t[t.CloseBracketToken=4]="CloseBracketToken",t[t.CommaToken=5]="CommaToken",t[t.ColonToken=6]="ColonToken",t[t.NullKeyword=7]="NullKeyword",t[t.TrueKeyword=8]="TrueKeyword",t[t.FalseKeyword=9]="FalseKeyword",t[t.StringLiteral=10]="StringLiteral",t[t.NumericLiteral=11]="NumericLiteral",t[t.LineCommentTrivia=12]="LineCommentTrivia",t[t.BlockCommentTrivia=13]="BlockCommentTrivia",t[t.LineBreakTrivia=14]="LineBreakTrivia",t[t.Trivia=15]="Trivia",t[t.Unknown=16]="Unknown",t[t.EOF=17]="EOF"})(IZt||(IZt={}));nZt=_pt;(function(t){t[t.InvalidSymbol=1]="InvalidSymbol",t[t.InvalidNumberFormat=2]="InvalidNumberFormat",t[t.PropertyNameExpected=3]="PropertyNameExpected",t[t.ValueExpected=4]="ValueExpected",t[t.ColonExpected=5]="ColonExpected",t[t.CommaExpected=6]="CommaExpected",t[t.CloseBraceExpected=7]="CloseBraceExpected",t[t.CloseBracketExpected=8]="CloseBracketExpected",t[t.EndOfFileExpected=9]="EndOfFileExpected",t[t.InvalidCommentToken=10]="InvalidCommentToken",t[t.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",t[t.UnexpectedEndOfString=12]="UnexpectedEndOfString",t[t.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",t[t.InvalidUnicode=14]="InvalidUnicode",t[t.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",t[t.InvalidCharacter=16]="InvalidCharacter"})(lZt||(lZt={}))});import{promises as kse}from"node:fs";import*as xj from"node:os";import*as v3 from"node:path";async function $EI(t,e){try{let I=new Date().toISOString().replace(/[:.]/g,"-"),l=`${e}.${I}.backup`;return await kse.copyFile(e,l),l}catch(I){return t.warning(`Failed to backup ${e}: ${Ae(I)}`),null}}function evI(t,e){let I=xj.platform(),l=Hve(()=>I==="darwin"?v3.join(xj.homedir(),"Library","Application Support"):I==="win32"?process.env.APPDATA?v3.join(process.env.APPDATA):(t.warning(`Unable to determine ${e} config path on Windows. APPDATA environment variable is not set.`),null):v3.join(xj.homedir(),".config"));return l===null?null:v3.join(l,e,"User")}async function iZt(t,e,I){let l=evI(t,I);return tvI(t,l,e,async n=>{await kse.mkdir(n,{recursive:!0})},async(n,r,a)=>{let s=await $EI(n,r);return await kse.writeFile(r,a,"utf8"),s})}async function tvI(t,e,I,l,n){if(!e)return{state:"failed",message:`Unable to determine ${I} config path.`};let r=v3.join(e,"keybindings.json"),a=null;try{await l(e);let s=[],o;try{let p=await kse.readFile(r,"utf8");o=p;try{let W=nZt(p);if(!Array.isArray(W))return{state:"failed",message:`Key bindings file for ${I} found but it is not a valid JSON array. Fix the file manually or delete it and try to setup the terminal again.
|
|
717
717
|
Path: ${r}`};s=W}catch(W){return{state:"failed",message:`Failed to parse the key bindings file for ${I}: invalid JSON file.
|
|
718
718
|
Fix the file manually or delete it and try to setup the terminal again.
|
|
719
719
|
Path: ${r}
|
|
720
|
-
Error: ${Ae(W)}`}}}catch{}let c={...
|
|
720
|
+
Error: ${Ae(W)}`}}}catch{}let c={...cZt,key:zve},i={...cZt,key:Uve},d=s.some(p=>{let W=p;return W.key===zve&&W.command===Lj&&W.args?.text===kj}),G=s.some(p=>{let W=p;return W.key===Uve&&W.command===Lj&&W.args?.text===kj});if(G&&d)return{state:"not-needed",message:`Key bindings for ${I} are already set up. Your terminal already has multiline support with Shift+Enter and Ctrl+Enter.`};let b=s.find(p=>{let W=p;return W.key===zve&&(W.command!==Lj||W.args?.text!==kj)}),u=s.find(p=>{let W=p;return W.key===Uve&&(W.command!==Lj||W.args?.text!==kj)});if(b||u){let p=[];return b&&p.push("Shift+Enter"),u&&p.push("Ctrl+Enter"),{state:"failed",message:`Found key bindings for ${new Intl.ListFormat("en").format(p)}. Those will not be modified.
|
|
721
721
|
Please make sure they are correct and modify them manually if needed, or delete them and try to setup the terminal again.
|
|
722
|
-
Path: ${r}`}}d||s.unshift(c),G||s.unshift(i);let h;if(o&&s.length>0){let p=o,W=N=>{let Y=
|
|
722
|
+
Path: ${r}`}}d||s.unshift(c),G||s.unshift(i);let h;if(o&&s.length>0){let p=o,W=N=>{let Y=rZt(p,[0],N,{formattingOptions:{insertSpaces:!0,tabSize:oZt},isArrayInsertion:!0});return aZt(p,Y)};G||(p=W(i)),d||(p=W(c)),h=p}else h=JSON.stringify(s,null,oZt);return a=await n(t,r,h),a&&t.info(`Backup of previous key bindings created at ${a}`),{state:"succeeded",message:`Added key bindings Shift+Enter and Ctrl+Enter for ${I} successfully.`}}catch(s){let o=a?`
|
|
723
723
|
You can restore your previous key bindings from ${a}`:"";return{state:"failed",message:`Failed to setup ${I}.
|
|
724
724
|
Path: ${r}${o}
|
|
725
|
-
Error: ${Ae(s)}`}}}var
|
|
726
|
-
`,
|
|
727
|
-
`)}function jve(t){return t==="~"?X3():t.startsWith("~/")?WZ.join(X3(),t.slice(2)):t}var ZZt,WZt,NZt,YZt,gZt,yZt,VZt,RZt,AZt,FZt,wZt,mZt,ivI,dvI,GvI,bvI,mvI,uvI,QZt,EZt,vZt,hvI,pvI,ZvI,WvI,NvI,XZt,HZt,uZt,YvI,gvI,CZt,fZt,JZt,hZt,yvI,VvI,LZt,pZt,RvI,kZt,xZt,AvI,SZt=m(()=>{"use strict";hht();cve();xE();
|
|
725
|
+
Error: ${Ae(s)}`}}}var Lj,_EI,kj,zve,Uve,oZt,cZt,dZt=m(()=>{"use strict";sZt();DI();Cve();Lj="workbench.action.terminal.sendSequence",_EI="terminalFocus",kj=`\\\r
|
|
726
|
+
`,zve="shift+enter",Uve="ctrl+enter",oZt=4,cZt={key:"",command:Lj,when:_EI,args:{text:kj}}});import{exec as IvI}from"node:child_process";import*as Ove from"node:os";import{promisify as lvI}from"node:util";async function avI(t){if(Ove.platform()==="linux"&&process.env.WSL_DISTRO_NAME)return"wsl";let e=(process.env.VSCODE_GIT_ASKPASS_MAIN||"").toLowerCase();if(process.env.CURSOR_TRACE_ID||e.includes("cursor"))return"cursor";if(e.includes("windsurf"))return"windsurf";if(e.includes("code"))return e.includes("insiders")?"vscode-insiders":"vscode";if(process.env.TERM_PROGRAM==="vscode"||process.env.VSCODE_GIT_IPC_HANDLE)return"vscode";try{let l=Ove.platform()==="win32"?'(Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessId=$PID").ParentProcessId).Path':"ps -o comm= -p $PPID",{stdout:n}=await nvI(l),r=n.trim().toLowerCase();if(r.includes("windsurf"))return"windsurf";if(r.includes("cursor"))return"cursor";if(r.includes("code"))return r.includes("insiders")?"vscode-insiders":"vscode"}catch(l){t.debug(`Failed to detect parent process: ${Ae(l)}`)}return null}async function GZt(t){if(jpt())return{state:"not-needed",message:"Your terminal already has multiline support with Shift+Enter and Ctrl+Enter."};let e=await avI(t);if(!e)return{state:"failed",message:"No supported terminal detected. `/terminal-setup` is supported only in VS Code, Cursor and Windsurf."};switch(e){case"vscode":case"vscode-insiders":case"cursor":case"windsurf":{let I=rvI[e];return iZt(t,I.terminalName,I.appName)}case"wsl":return{state:"failed",message:"WSL terminal detected.\n\nIf you're running WSL from VS Code, Windsurf or Cursor, please switch to a supported terminal within the IDE (e.g. PowerShell or Command Prompt) and run `/terminal-setup` again."};default:return{state:"failed",message:`Terminal "${e}" not supported. \`/terminal-setup\` is supported only in VS Code, Cursor and Windsurf.`}}}var nvI,rvI,bZt=m(()=>{"use strict";Mve();DI();xE();Cve();Dpt();dZt();nvI=lvI(IvI),rvI={vscode:{appName:"Code",terminalName:"VS Code"},"vscode-insiders":{appName:"Code - Insiders",terminalName:"VS Code (Insiders)"},cursor:{appName:"Cursor",terminalName:"Cursor"},windsurf:{appName:"Windsurf",terminalName:"Windsurf"}}});var BZt={};ya(BZt,{addDirCommand:()=>WZt,agentCommand:()=>NZt,clearCommand:()=>YZt,createBuiltInSlashCommands:()=>AvI,cwdCommand:()=>gZt,delegateCommand:()=>xZt,exitCommand:()=>yZt,feedbackCommand:()=>VZt,getMatchingSlashCommands:()=>ovI,getSlashCommandsHelpText:()=>cvI,helpCommand:()=>RZt,listDirsCommand:()=>AZt,loginCommand:()=>FZt,logoutCommand:()=>wZt,mcpCommand:()=>QZt,modelCommand:()=>EZt,resetAllowedToolsCommand:()=>vZt,sessionCommand:()=>HZt,shareCommand:()=>kZt,skillsCommand:()=>XZt,terminalSetupCommand:()=>CZt,themeCommand:()=>fZt,usageCommand:()=>JZt,userCommand:()=>LZt});import{homedir as X3}from"node:os";import WZ,{resolve as svI}from"node:path";function ovI(t,e){let I=e.trim();if(!I.startsWith("/"))return[];let l=I.split(" ")[0];return t.filter(n=>n.name.startsWith(l)?!0:n.aliases?n.aliases.some(r=>r.startsWith(l)):!1)}function cvI(t,e){let I=" ".repeat(e),l=t.reduce((n,r)=>{let a=r.aliases&&r.aliases.length>0?`, ${r.aliases.join(", ")}`:"";return Math.max(n,r.name.length+a.length+(r.args?r.args.length+1:0))},0);return t.map(n=>{let r=n.aliases&&n.aliases.length>0?`, ${n.aliases.join(", ")}`:"",a=(n.args?`${n.name}${r} ${n.args}`:`${n.name}${r}`).padEnd(l);return`${I}${a} ${n.help}`}).join(`
|
|
727
|
+
`)}function jve(t){return t==="~"?X3():t.startsWith("~/")?WZ.join(X3(),t.slice(2)):t}var ZZt,WZt,NZt,YZt,gZt,yZt,VZt,RZt,AZt,FZt,wZt,mZt,ivI,dvI,GvI,bvI,mvI,uvI,QZt,EZt,vZt,hvI,pvI,ZvI,WvI,NvI,XZt,HZt,uZt,YvI,gvI,CZt,fZt,JZt,hZt,yvI,VvI,LZt,pZt,RvI,kZt,xZt,AvI,SZt=m(()=>{"use strict";hht();cve();Rj();xE();ppt();BE();vse();C3();kpt();Tpt();bZt();ZZt={kind:"noop"};WZt={name:"/add-dir",args:"<directory>",help:"Add a directory to the allowed list for file access",execute:async(t,e)=>{if(e.length<1)return{kind:"add-timeline-entry",entry:{type:"error",text:`Usage: /add-dir <directory>
|
|
728
728
|
Example: /add-dir /home/user/projects`}};let I=e.join(" "),l=jve(I);try{return await t.permissions.addAllowedDirectory(l),{kind:"add-timeline-entry",entry:{type:"info",text:`Added directory to allowed list: ${l}`}}}catch(n){return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to add directory: ${n instanceof Error?n.message:String(n)}`}}}}},NZt={name:"/agent",help:"Browse and select from available agents (if any)",execute:async(t,e)=>t.customAgents.available.length===0?t.customAgents.warnings.length>0?{kind:"add-timeline-entry",entry:{type:"error",text:`No available custom agents:
|
|
729
729
|
${t.customAgents.warnings.map(l=>`\u2022 ${l}`).join(`
|
|
730
730
|
`)}`}}:{kind:"add-timeline-entry",entry:{type:"info",text:"No available custom agents."}}:{kind:"show-dialog",dialog:{kind:"custom-agent-picker"}}},YZt={name:"/clear",help:"Clear the conversation history",execute:async(t,e)=>(await t.session.clearHistory(),t.ui.clear(),ZZt)},gZt={name:"/cwd",args:"[directory]",help:"Change working directory or show current directory",execute:async(t,e)=>{if(e.length===0)return{kind:"add-timeline-entry",entry:{type:"info",text:`Current working directory: ${t.process.cwd}`}};let I=e.join(" "),l=jve(I),n=svI(l);try{return await t.process.chdir(n),{kind:"add-timeline-entry",entry:{type:"info",text:`Changed working directory to: ${n}`}}}catch(r){return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to change directory: ${r instanceof Error?r.message:String(r)}`}}}}},yZt={name:"/exit",aliases:["/quit"],help:"Exit the CLI",execute:async(t,e)=>({kind:"exit"})},VZt={name:"/feedback",help:"Provide feedback about the CLI",execute:async(t,e)=>({kind:"show-dialog",dialog:{kind:"feedback"}})},RZt={name:"/help",help:"Show help for interactive commands",execute:async(t,e)=>({kind:"add-timeline-entry",entry:{type:"info",text:[mht(`
|
|
@@ -768,7 +768,7 @@ ${t.customAgents.warnings.map(l=>`\u2022 ${l}`).join(`
|
|
|
768
768
|
`)}})},AZt={name:"/list-dirs",help:"Display all allowed directories for file access",execute:async(t,e)=>{let I=t.permissions.allowedDirs();return I.length===0?{kind:"add-timeline-entry",entry:{type:"info",text:`No directories are currently allowed for file access.
|
|
769
769
|
|
|
770
770
|
Use /add-dir <directory> to add a directory to the allowed list.`}}:{kind:"add-timeline-entry",entry:{type:"info",text:["Allowed directories for file access:","",...I.map((n,r)=>`${r+1}. ${n}`),"",`Total: ${I.length} ${I.length===1?"directory":"directories"}`,"","Use /add-dir <directory> to add more directories.","Subdirectories of allowed paths are added automatically."].join(`
|
|
771
|
-
`)}}}},FZt={name:"/login",help:"Log in to Copilot",execute:async(t,e)=>({kind:"show-dialog",dialog:{kind:"login"}})},wZt={name:"/logout",help:"Log out of Copilot",execute:async(t,e)=>{if(t.auth.loginStatus.status!=="LoggedIn")return{kind:"add-timeline-entry",entry:{type:"error",text:"You are not logged in."}};let I=await t.auth.logout();return t.session.addTimelineEntry({type:"info",text:"You have been logged out successfully."}),I?{kind:"show-dialog",dialog:{kind:"user-switcher"}}:ZZt}},mZt=async(t,e)=>({kind:"show-dialog",dialog:{kind:"mcp"}}),ivI=async(t,e)=>{let I=await t.mcp.config(),l=Object.fromEntries(Object.entries(I.mcpServers).filter(a=>(a[1].type||"local")!=="memory")),n=Object.keys(l);return n.length===0?{kind:"add-timeline-entry",entry:{type:"info",text:"No MCP servers configured."}}:{kind:"add-timeline-entry",entry:{type:"info",text:["MCP Server Configuration:","",...n.map(a=>{let s=l[a],o=s.type||"local",c=nse(s)?`URL: ${s.url}`:`Command: ${s.command}`;return`\u2022 ${a} (${o}): ${c}`}),"",`Total servers: ${n.length}`,`Config file: ${
|
|
771
|
+
`)}}}},FZt={name:"/login",help:"Log in to Copilot",execute:async(t,e)=>({kind:"show-dialog",dialog:{kind:"login"}})},wZt={name:"/logout",help:"Log out of Copilot",execute:async(t,e)=>{if(t.auth.loginStatus.status!=="LoggedIn")return{kind:"add-timeline-entry",entry:{type:"error",text:"You are not logged in."}};let I=await t.auth.logout();return t.session.addTimelineEntry({type:"info",text:"You have been logged out successfully."}),I?{kind:"show-dialog",dialog:{kind:"user-switcher"}}:ZZt}},mZt=async(t,e)=>({kind:"show-dialog",dialog:{kind:"mcp"}}),ivI=async(t,e)=>{let I=await t.mcp.config(),l=Object.fromEntries(Object.entries(I.mcpServers).filter(a=>(a[1].type||"local")!=="memory")),n=Object.keys(l);return n.length===0?{kind:"add-timeline-entry",entry:{type:"info",text:"No MCP servers configured."}}:{kind:"add-timeline-entry",entry:{type:"info",text:["MCP Server Configuration:","",...n.map(a=>{let s=l[a],o=s.type||"local",c=nse(s)?`URL: ${s.url}`:`Command: ${s.command}`;return`\u2022 ${a} (${o}): ${c}`}),"",`Total servers: ${n.length}`,`Config file: ${hpt.path()}`].join(`
|
|
772
772
|
`)}}},dvI=async(t,e)=>({kind:"show-dialog",dialog:{kind:"mcp",mode:"add",serverName:e.length>=1?e[0]:void 0}}),GvI=async(t,e)=>{if(e.length<1)return{kind:"add-timeline-entry",entry:{type:"error",text:`Usage: /mcp edit <server-name>
|
|
773
773
|
This will start an interactive configuration wizard.`}};let I=e[0];return await t.mcp.hasServer(I)?{kind:"show-dialog",dialog:{kind:"mcp",mode:"edit",serverName:I}}:{kind:"add-timeline-entry",entry:{type:"error",text:`Server "${I}" not found. Use /mcp add to create it.`}}},bvI=async(t,e)=>{if(e.length<1)return{kind:"add-timeline-entry",entry:{type:"error",text:"Usage: /mcp delete <server-name>"}};let I=e[0];if(!await t.mcp.hasServer(I))return{kind:"add-timeline-entry",entry:{type:"error",text:`Server "${I}" not found.`}};try{return await t.mcp.deleteServer(I),{kind:"add-timeline-entry",entry:{type:"info",text:`Successfully deleted MCP server "${I}" and updated in memory. Changes effective immediately.`}}}catch(n){return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to delete MCP server "${I}": ${n instanceof Error?n.message:String(n)}`}}}},mvI=async(t,e)=>{if(e.length<1)return{kind:"add-timeline-entry",entry:{type:"error",text:"Usage: /mcp disable <server-name>"}};let I=e[0];if(!t.mcp.host)return{kind:"add-timeline-entry",entry:{type:"error",text:"MCP host not available for server management."}};if(t.mcp.host.isServerDisabled(I))return{kind:"add-timeline-entry",entry:{type:"info",text:`MCP server "${I}" is already disabled.`}};try{return await t.mcp.host.disableServer(I),{kind:"add-timeline-entry",entry:{type:"info",text:`MCP server "${I}" has been disabled for this session.`}}}catch(l){return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to disable MCP server "${I}": ${l instanceof Error?l.message:String(l)}`}}}},uvI=async(t,e)=>{if(e.length<1)return{kind:"add-timeline-entry",entry:{type:"error",text:"Usage: /mcp enable <server-name>"}};let I=e[0];if(!t.mcp.host)return{kind:"add-timeline-entry",entry:{type:"error",text:"MCP host not available for server management."}};if(!t.mcp.host.isServerDisabled(I))return{kind:"add-timeline-entry",entry:{type:"info",text:`MCP server "${I}" is already enabled.`}};try{return await t.mcp.host.enableServer(I),{kind:"add-timeline-entry",entry:{type:"info",text:`MCP server "${I}" has been enabled for this session.`}}}catch(l){return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to enable MCP server "${I}": ${l instanceof Error?l.message:String(l)}`}}}},QZt={name:"/mcp",args:"[show|add|edit|delete|disable|enable] [server-name]",help:"Manage MCP server configuration",execute:async(t,e)=>{let[I,...l]=e;if(!I)return mZt(t,l);switch(I){case"config":return mZt(t,l);case"show":return ivI(t,l);case"add":return dvI(t,l);case"edit":return GvI(t,l);case"delete":return bvI(t,l);case"disable":return mvI(t,l);case"enable":return uvI(t,l);default:return{kind:"add-timeline-entry",entry:{type:"info",text:["MCP Command Usage:","/mcp (or /mcp config) - Open visual MCP server configuration interface","/mcp show - Display all configured MCP servers","/mcp add [server-name] - Add a new MCP server (interactive wizard)","/mcp edit <server-name> - Edit an existing MCP server (interactive wizard)","/mcp delete <server-name> - Delete an MCP server","/mcp disable <server-name> - Disable an MCP server for this session","/mcp enable <server-name> - Enable a previously disabled MCP server","","The add and edit commands will open an interactive wizard that guides you","through configuring your MCP server with individual input fields.","","Disable/enable commands temporarily stop/start servers without modifying","the configuration file. Changes only last for the current session."].join(`
|
|
774
774
|
`)}}}}},EZt={name:"/model",args:"[model]",help:"Select AI model to use",execute:async(t,e)=>{if(t.auth.loginStatus.status!=="LoggedIn")return{kind:"add-timeline-entry",entry:{type:"error",text:"You must be logged in to select a model. Use /login to authenticate."}};if(e.length===0)return{kind:"show-dialog",dialog:{kind:"model-picker"}};if(!t.models)return{kind:"add-timeline-entry",entry:{type:"error",text:"Unable to load available models list"}};let I=e[0],l=t.models,n=null;if(H3(I)?NZ(I,l)||(n=`Model "${I}" is unavailable.`):n=`Model "${I}" is unsupported.`,n){l.length>0?n+=`
|
|
@@ -781,12 +781,12 @@ No models are available, please check your Copilot policies and subscription.`;l
|
|
|
781
781
|
Supported models:
|
|
782
782
|
`+Tve(r,2)),{kind:"add-timeline-entry",entry:{type:"error",text:`${n}
|
|
783
783
|
|
|
784
|
-
For information on Copilot policies and subscription, visit ${UZt(t.auth.loginStatus.authInfo,"settings/copilot/features")}`}}}try{let a={...await Go.load()||{},model:I};return await Go.write(a),{kind:"set-model",model:I}}catch(r){return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to set model: ${r instanceof Error?r.message:String(r)}`}}}}},vZt={name:"/reset-allowed-tools",help:"Reset the list of allowed tools",execute:async(t,e)=>(t.permissions.resetSessionToolApprovals(),{kind:"add-timeline-entry",entry:{type:"info",text:"The list of allowed tools has been reset."}})},hvI=async(t,e)=>{try{let I=await t.skills.loadSkills();if(I.length===0)return{kind:"add-timeline-entry",entry:{type:"info",text:["No skills found.","","Skills are automatically discovered from:"," \u2022 ~/.
|
|
785
|
-
`)}};let l=new Map;for(let r of I){let a=
|
|
784
|
+
For information on Copilot policies and subscription, visit ${UZt(t.auth.loginStatus.authInfo,"settings/copilot/features")}`}}}try{let a={...await Go.load()||{},model:I};return await Go.write(a),{kind:"set-model",model:I}}catch(r){return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to set model: ${r instanceof Error?r.message:String(r)}`}}}}},vZt={name:"/reset-allowed-tools",help:"Reset the list of allowed tools",execute:async(t,e)=>(t.permissions.resetSessionToolApprovals(),{kind:"add-timeline-entry",entry:{type:"info",text:"The list of allowed tools has been reset."}})},hvI=async(t,e)=>{try{let I=await t.skills.loadSkills();if(I.length===0)return{kind:"add-timeline-entry",entry:{type:"info",text:["No skills found.","","Skills are automatically discovered from:"," \u2022 ~/.copilot/skills/ (personal GitHub skills)"," \u2022 ~/.claude/skills/ (personal Claude skills)"," \u2022 [repo-root]/.github/skills/ (project skills)"," \u2022 [repo-root]/.claude/skills/ (project Claude skills)","","To add a custom skill directory, use:"," /skills add <directory-path>"].join(`
|
|
785
|
+
`)}};let l=new Map;for(let r of I){let a=ive(r.source);l.has(a)||l.set(a,[]),l.get(a).push(r)}let n=["Available Skills",""];for(let[r,a]of l){n.push(`${r}:`);for(let s of a)n.push(` \u2022 ${s.name}`),n.push(` ${s.description}`);n.push("")}return n.push(`Found ${I.length} skill${I.length===1?"":"s"}. Use /skills info <name> to view details.`),{kind:"add-timeline-entry",entry:{type:"info",text:n.join(`
|
|
786
786
|
`)}}}catch(I){return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to load skills: ${I instanceof Error?I.message:String(I)}`}}}},pvI=async(t,e)=>{if(e.length<1)return{kind:"add-timeline-entry",entry:{type:"error",text:`Usage: /skills info <skill-name>
|
|
787
787
|
Example: /skills info my-skill`}};let I=e[0];try{let n=(await t.skills.loadSkills()).find(a=>a.name===I);if(!n)return{kind:"add-timeline-entry",entry:{type:"error",text:`Skill not found: ${I}
|
|
788
788
|
|
|
789
|
-
Use /skills list to see available skills.`}};let r=[`Skill: ${n.name}`,"",`Source: ${
|
|
789
|
+
Use /skills list to see available skills.`}};let r=[`Skill: ${n.name}`,"",`Source: ${ive(n.source)}`,`Location: ${n.filePath}`,"","Description:",n.description];return n.allowedTools&&n.allowedTools.length>0&&r.push("",`Allowed Tools: ${n.allowedTools.join(", ")}`),{kind:"add-timeline-entry",entry:{type:"info",text:r.join(`
|
|
790
790
|
`)}}}catch(l){return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to load skills: ${l instanceof Error?l.message:String(l)}`}}}},ZvI=async(t,e)=>{if(e.length<1)return{kind:"add-timeline-entry",entry:{type:"error",text:`Usage: /skills add <directory>
|
|
791
791
|
Example: /skills add ~/my-custom-skills`}};let I=e.join(" "),l=I==="~"?X3():I.startsWith("~/")?WZ.join(X3(),I.slice(2)):I,n=WZ.isAbsolute(l)?l:WZ.resolve(t.process.cwd,l);try{await t.skills.addSkillDirectory(n);let a=(await t.skills.reloadSkills()).filter(s=>WZ.dirname(s.baseDir)===n).length;return{kind:"add-timeline-entry",entry:{type:"info",text:`Added custom skill directory: ${n}
|
|
792
792
|
|
|
@@ -798,17 +798,17 @@ Skills cache updated.`}}}catch(r){return{kind:"add-timeline-entry",entry:{type:"
|
|
|
798
798
|
|
|
799
799
|
Use /theme set [auto|dark|light] to change the preference.`}}},YvI=async(t,e)=>({kind:"add-timeline-entry",entry:{type:"info",text:["Available themes:","\u2022 auto - Automatically detect based on terminal background (default)","\u2022 dark - Use dark theme colors","\u2022 light - Use light theme colors","","Usage: /theme set [auto|dark|light]"].join(`
|
|
800
800
|
`)}}),gvI=async(t,e)=>{if(e.length!==1)return{kind:"add-timeline-entry",entry:{type:"error",text:`Usage: /theme set [auto|dark|light]
|
|
801
|
-
Example: /theme set dark`}};let I=e[0].toLowerCase();return
|
|
801
|
+
Example: /theme set dark`}};let I=e[0].toLowerCase();return Jpt(I)?(await t.ui.setThemePreference(I),{kind:"add-timeline-entry",entry:{type:"info",text:`Theme preference set to: ${I==="auto"?"auto (will detect based on terminal background)":I}
|
|
802
802
|
|
|
803
803
|
The new theme will be applied on the next restart of the CLI.`}}):{kind:"add-timeline-entry",entry:{type:"error",text:`Invalid theme preference: ${I}
|
|
804
|
-
Valid options are: auto, dark, light`}}},CZt={name:"/terminal-setup",help:"Configure terminal for multiline input support (Shift+Enter and Ctrl+Enter)",execute:async(t,e)=>{let I=await
|
|
805
|
-
`)}}}}},JZt={name:"/usage",help:"Display session usage metrics and statistics",execute:async(t,e)=>({kind:"add-timeline-entry",entry:{type:"info",text:t.session.usageOutput()}})},hZt=async(t,e)=>{if(t.auth.loginStatus.status!=="LoggedIn")return{kind:"add-timeline-entry",entry:{type:"error",text:"You are not logged in."}};let I=t.auth.loginStatus.authInfo;return{kind:"add-timeline-entry",entry:{type:"info",text:
|
|
804
|
+
Valid options are: auto, dark, light`}}},CZt={name:"/terminal-setup",help:"Configure terminal for multiline input support (Shift+Enter and Ctrl+Enter)",execute:async(t,e)=>{let I=await GZt(t.logger);return{kind:"add-timeline-entry",entry:{type:I.state==="failed"?"error":"info",text:I.message}}}},fZt={name:"/theme",args:"[show|set|list] [auto|dark|light]",help:"View or configure terminal theme",execute:async(t,e)=>{let[I,...l]=e;if(!I)return uZt(t,l);switch(I){case"show":return uZt(t,l);case"list":return YvI(t,l);case"set":return gvI(t,l);default:return{kind:"add-timeline-entry",entry:{type:"info",text:["Theme Command Usage:","/theme (or /theme show) - Show current theme preference","/theme list - List available themes","/theme set [auto|dark|light] - Set theme preference","","Examples:","/theme set auto - Use automatic theme detection","/theme set dark - Use dark theme","/theme set light - Use light theme"].join(`
|
|
805
|
+
`)}}}}},JZt={name:"/usage",help:"Display session usage metrics and statistics",execute:async(t,e)=>({kind:"add-timeline-entry",entry:{type:"info",text:t.session.usageOutput()}})},hZt=async(t,e)=>{if(t.auth.loginStatus.status!=="LoggedIn")return{kind:"add-timeline-entry",entry:{type:"error",text:"You are not logged in."}};let I=t.auth.loginStatus.authInfo;return{kind:"add-timeline-entry",entry:{type:"info",text:Npt(I)}}},yvI=async(t,e)=>{let I=await t.auth.availableAuthMethods();return I.length===0?{kind:"add-timeline-entry",entry:{type:"error",text:"No users are currently logged in."}}:{kind:"add-timeline-entry",entry:{type:"info",text:`Available users:
|
|
806
806
|
|
|
807
807
|
${I.join(`
|
|
808
808
|
`)}`}}},VvI=async(t,e)=>({kind:"show-dialog",dialog:{kind:"user-switcher"}}),LZt={name:"/user",args:"[show|list|switch]",help:"Manage GitHub user list",execute:async(t,e)=>{let[I,...l]=e;if(!I)return hZt(t,l);switch(I){case"show":return hZt(t,l);case"list":return yvI(t,l);case"switch":return VvI(t,l);default:return{kind:"add-timeline-entry",entry:{type:"info",text:["User Command Usage:","/user (or /user show) - Show the currently logged-in user","/user list - List all available users","/user switch - Switch to a different user","","Examples:","/user show - Display the current user's information","/user list - Show a list of all users","/user switch - Open the user switcher dialog"].join(`
|
|
809
|
-
`)}}}}},pZt=async(t,e)=>{let I=t.session.getTimelineEntries();if(I.length===0)return{kind:"add-timeline-entry",entry:{type:"info",text:"No timeline entries to share. The session is empty."}};let l=t.session.getSessionId(),n=t.session.getSessionStartTime(),r;e.length>0?(r=jve(e.join(" ")),WZ.isAbsolute(r)||(r=WZ.resolve(t.process.cwd,r))):r=WZ.resolve(t.process.cwd,`copilot-session-${l}.md`);try{return await
|
|
809
|
+
`)}}}}},pZt=async(t,e)=>{let I=t.session.getTimelineEntries();if(I.length===0)return{kind:"add-timeline-entry",entry:{type:"info",text:"No timeline entries to share. The session is empty."}};let l=t.session.getSessionId(),n=t.session.getSessionStartTime(),r;e.length>0?(r=jve(e.join(" ")),WZ.isAbsolute(r)||(r=WZ.resolve(t.process.cwd,r))):r=WZ.resolve(t.process.cwd,`copilot-session-${l}.md`);try{return await Opt(I,l,n,r),{kind:"add-timeline-entry",entry:{type:"info",text:`Session shared successfully to:
|
|
810
810
|
${r}`}}}catch(a){return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to share session: ${a instanceof Error?a.message:String(a)}`}}}},RvI=async(t,e)=>{if(t.auth.loginStatus.status!=="LoggedIn")return{kind:"add-timeline-entry",entry:{type:"error",text:"You must be logged in to create a gist. Use /login to authenticate."}};let I=t.session.getTimelineEntries();if(I.length===0)return{kind:"add-timeline-entry",entry:{type:"info",text:"No timeline entries to share. The session is empty."}};let l=t.session.getSessionId(),n=t.session.getSessionStartTime();try{let r=await Yh(t.auth.loginStatus.authInfo);if(!r)return{kind:"add-timeline-entry",entry:{type:"error",text:"Failed to retrieve authentication token. Please log in again."}};let a=t.auth.loginStatus.authInfo.type==="user"?t.auth.loginStatus.authInfo.login:void 0;return{kind:"add-timeline-entry",entry:{type:"info",text:`Session shared successfully to secret gist:
|
|
811
|
-
${await
|
|
811
|
+
${await Mpt(I,l,n,r,a)}`}}}catch(r){let a=r instanceof Error?r.message:String(r),o=a.includes("403")||a.includes("scopes")||a.includes("gist")||a.includes("Forbidden")?`
|
|
812
812
|
|
|
813
813
|
Your token may not have the required 'gist' scope. Please log out and log back in to get a token with updated permissions.`:"";return{kind:"add-timeline-entry",entry:{type:"error",text:`Failed to share session: ${a}${o}`}}}},kZt={name:"/share",args:"[file|gist] [path]",help:"Share session to markdown file or GitHub gist",execute:async(t,e)=>{let[I,...l]=e;if(!I)return pZt(t,l);switch(I){case"file":return pZt(t,l);case"gist":return RvI(t,l);default:return{kind:"add-timeline-entry",entry:{type:"info",text:["Share Command Usage:","/share [path] - Share session to a markdown file (defaults to current directory)","/share file [path] - Share session to a markdown file at the specified path","/share gist - Create a secret GitHub gist with the session content","","Examples:","/share - Share to copilot-session-<id>.md in current directory","/share ~/sessions/my-session.md - Share to specific file path","/share gist - Create a secret gist (requires login)"].join(`
|
|
814
814
|
`)}}}}},xZt={name:"/delegate",args:"<prompt>",help:"Delegate changes to remote repository with AI-generated PR",execute:async(t,e)=>e.length<1?{kind:"add-timeline-entry",entry:{type:"error",text:`Usage: /delegate <prompt>
|
|
@@ -1770,7 +1770,7 @@ Error: ${o.error}`,sessionLog:`<agent ${I} failed: ${o.error}>`,resultType:"fail
|
|
|
1770
1770
|
|
|
1771
1771
|
Result:
|
|
1772
1772
|
${b}`,sessionLog:c?.sessionLog||`<agent ${I} completed>`,resultType:"success",toolTelemetry:{properties:d,metrics:{duration_seconds:o.completedAt?Math.floor((o.completedAt-o.startedAt)/1e3):0,result_length:b.length}}}};return{name:vtl,description:["Retrieves the status and results of a background agent.",'* Use this tool to check on agents started with mode: "background" in the task tool.',"* Returns the agent status (running, completed, failed) and results if available.","* Set wait: true to block until the agent completes (with optional timeout).","* If the agent is still running and wait is false, returns current status."].join(`
|
|
1773
|
-
`),input_schema:{type:"object",properties:{agent_id:{type:"string",description:'The ID of the background agent to read results from. This is returned when starting an agent with mode: "background".'},wait:{type:"boolean",description:"If true, wait for the agent to complete before returning. If false (default), return immediately with current status."},timeout:{type:"number",description:`Maximum time in seconds to wait if wait is true. Default is ${Xtl/1e3}, maximum is ${Rxt/1e3}.`}},required:["agent_id"]},callback:t,safeForTelemetry:!0}}var vtl,Rxt,Xtl,Fxt=m(()=>{"use strict";Lue();vtl="read_agent",Rxt=300*1e3,Xtl=30*1e3});function wxt(t){let e=
|
|
1773
|
+
`),input_schema:{type:"object",properties:{agent_id:{type:"string",description:'The ID of the background agent to read results from. This is returned when starting an agent with mode: "background".'},wait:{type:"boolean",description:"If true, wait for the agent to complete before returning. If false (default), return immediately with current status."},timeout:{type:"number",description:`Maximum time in seconds to wait if wait is true. Default is ${Xtl/1e3}, maximum is ${Rxt/1e3}.`}},required:["agent_id"]},callback:t,safeForTelemetry:!0}}var vtl,Rxt,Xtl,Fxt=m(()=>{"use strict";Lue();vtl="read_agent",Rxt=300*1e3,Xtl=30*1e3});function wxt(t){let e=pht.safeParse(t);return e.success?{success:!0,data:e.data}:{success:!1,errors:e.error.errors.map(l=>{let n=l.path.join(".");return n?`${n}: ${l.message}`:l.message})}}var rze=m(()=>{"use strict";Rj()});import*as kue from"fs/promises";import*as nw from"path";import*as Qxt from"os";import{existsSync as Ext,statSync as Htl}from"fs";function Ltl(t,e=[]){let I=[];t&&I.push({path:nw.join(t,".github","skills"),source:"project"}),t&&I.push({path:nw.join(t,".claude","skills"),source:"project"}),I.push({path:nw.join(HJ(),"skills"),source:"personal-copilot"}),I.push({path:nw.join(Qxt.homedir(),".claude","skills"),source:"personal-claude"});let l=process.env[Ctl]?.split(",").filter(Boolean)||[];for(let n of[...l,...e]){let r=n.trim();r&&I.push({path:r,source:"custom"})}return I.filter(n=>Ext(n.path))}function ktl(t){let e=/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/,I=t.match(e);if(!I)return null;try{let l=vxt.default.parse(I[1]),n=I[2];return{frontmatter:l,body:n}}catch{return null}}async function xtl(t,e){try{let I=await kue.readFile(t,"utf-8"),l=ktl(I);if(!l)return null;let n=wxt(l.frontmatter);if(!n.success||!n.data)return null;let r=n.data,a=r["allowed-tools"]?.split(",").map(s=>s.trim()).filter(Boolean);return{name:r.name,description:r.description,source:e,filePath:t,baseDir:nw.dirname(t),allowedTools:a,content:I}}catch{return null}}function Btl(t){try{let e=Htl(t);return`${e.dev}-${e.ino}`}catch{return}}async function Xxt(t,e=[],I=!0){let l=t||"__no_project__";if(I&&p8?.has(l))return p8.get(l);let n=Ltl(t,e),r=[],a=new Map,s=new Set;for(let o of n)try{let c=await kue.readdir(o.path,{withFileTypes:!0});for(let i of c){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let d=nw.join(o.path,i.name,"SKILL.md");if(!Ext(d))continue;let G=Btl(d);if(G&&a.has(G))continue;let b=await xtl(d,o.source);b&&(s.has(b.name)||(G&&a.set(G,b.name),s.add(b.name),r.push(b)))}}catch{continue}return p8=p8||new Map,p8.set(l,r),r}function Hxt(){let t=process.env[Jtl];if(t){let e=parseInt(t,10);if(!isNaN(e)&&e>0)return e}return ftl}var vxt,Ctl,ftl,Jtl,p8,aze=m(()=>{"use strict";vxt=lI(RC(),1);rze();JQ();Ctl="COPILOT_SKILLS_DIRS",ftl=15e3,Jtl="SKILL_CHAR_BUDGET"});function Stl(t){let e=Zht(t.source);return`<skill>
|
|
1774
1774
|
<name>${xue(t.name)}</name>
|
|
1775
1775
|
<description>${xue(t.description)}</description>
|
|
1776
1776
|
<location>${e}</location>
|
|
@@ -1798,7 +1798,7 @@ Important:
|
|
|
1798
1798
|
|
|
1799
1799
|
<available_skills>
|
|
1800
1800
|
${ztl(t)}
|
|
1801
|
-
</available_skills>`}var fxt=m(()=>{"use strict";
|
|
1801
|
+
</available_skills>`}var fxt=m(()=>{"use strict";Rj();aze()});var Jxt=m(()=>{"use strict";Rj();aze();rze();fxt()});import*as n9 from"fs/promises";import*as Bue from"path";function Ttl(t,e){return e.find(I=>I.name===t)}async function jtl(t){let e=[],I=new Set,l=20;async function n(r,a="",s=0){if(!(s>l))try{let o=await n9.realpath(r);if(I.has(o))return;I.add(o);let c=await n9.readdir(r,{withFileTypes:!0});for(let i of c){let d=a?Bue.join(a,i.name):i.name;i.isDirectory()?await n(Bue.join(r,i.name),d,s+1):i.isFile()&&i.name.toUpperCase()!=="SKILL.MD"&&e.push(d)}}catch{}}return await n(t),e}async function sze(t,e=[],I=new Set){let n=(await Xxt(t,e)).filter(a=>!I.has(a.name));return n.length===0?void 0:{name:Utl,description:Cxt(n),input_schema:Mtl,safeForTelemetry:!0,callback:async a=>{if(I.has(a.skill))return{textResultForLlm:`Skill "${a.skill}" is disabled. Use /skills to enable it.`,resultType:"failure",error:`Skill disabled: ${a.skill}`,toolTelemetry:{properties:{skillName:a.skill,disabled:"true"}}};let s=Ttl(a.skill,n);if(!s){let G=n.map(b=>b.name).join(", ");return{textResultForLlm:`Skill "${a.skill}" not found. Available skills: ${G}`,resultType:"failure",error:`Skill not found: ${a.skill}`,toolTelemetry:{properties:{skillName:a.skill,found:"false"}}}}let o;try{o=await n9.readFile(s.filePath,"utf-8")}catch(G){return{textResultForLlm:`Failed to read skill file: ${s.filePath}`,resultType:"failure",error:`Failed to read skill file: ${String(G)}`,toolTelemetry:{properties:{skillName:a.skill,found:"true",readError:"true"}}}}let c=await jtl(s.baseDir),i=c.length>0?`
|
|
1802
1802
|
Related files in skill directory (use view tool to read):
|
|
1803
1803
|
${c.map(G=>`- ${Bue.join(s.baseDir,G)}`).join(`
|
|
1804
1804
|
`)}
|
|
@@ -1939,8 +1939,8 @@ ${jce}`}}},"gpt-5-codex":{...JZe},"gpt-5.1-codex":{...JZe},"gpt-5.1-codex-max":{
|
|
|
1939
1939
|
<preToolPreamble>
|
|
1940
1940
|
Before invoking tools, briefly explain the next action and why it is the best next step. Explain with the tool call. Do not use "I will" statements like "I will run" or "I will install", instead use statements without self reference, e.g. "Running" or "Installing".
|
|
1941
1941
|
</preToolPreamble>`}}},"gpt-4.1":{...br,supports:{tool_choice:!0,parallel_tool_calls:!0,vision:!0},cli:{...br.cli,systemMessage:{additionalInstructions:`${RL}`}}}}}});var BTt=m(()=>{"use strict";Uo()});var STt=m(()=>{"use strict";DI();bH();BTt();dE();KG();sc();i8()});function Vsl(t,e){return t.toolCalls.find(I=>I.toolCallId===e)}function Rsl(t,e,I){let l=nZ(I),n=Tlt(I);try{let r=e.find(i=>i.name===l),a=r?.safeForTelemetry||{name:!1,inputsNames:!1},s;if(Zr(I)){let i=JSON.parse(n||"{}");s=a===!0||a.inputsNames?V3t(i):""}else $u(I)?s=yh(n):s="";let o=_F(r),c;if(o&&t.customAgents&&t.settings){let i=t.customAgents.find(d=>d.name===l);if(i){let d=t.settings.github?.repo?.name??"",G=d.split("/"),b=G.length===2?G[0]:"",u=G.length===2?G[1]:d,h=i.mcpServers?Object.keys(i.mcpServers).join(","):"",p=i.mcpServers?Object.keys(i.mcpServers).length:0;c={repoOwner:b,repoName:u,displayName:i.name,mcpServerNames:h,mcpServerCount:p}}}return{toolCallId:I.id,toolName:l,arguments:n,safeForTelemetryToolName:a===!0||a.name?l:yh(l),safeForTelemetryArguments:s,isCustomAgent:o,customAgentInfo:c}}catch{return{toolCallId:I.id,toolName:l,arguments:n,safeForTelemetryToolName:yh(l),safeForTelemetryArguments:"",isCustomAgent:!1,customAgentInfo:void 0}}}var LZe,zTt=m(()=>{"use strict";k3();Vq();VA();Qm();HL();sc();dH();LZe=class{constructor(e,I,l){this.runtimeContext=e;this.forAgent=I;this.toolsInUse=l}turnDataCache=new Map;emittedTurns=new Set;getTurnData(){return this.turnDataCache}async ingestEvent(e){let I,l;if("turn"in e&&typeof e.turn=="number"){if(I=e.turn+1,this.emittedTurns.has(I))return;this.turnDataCache.has(I)||this.turnDataCache.set(I,{featureFlagsAsString:X2e(this.runtimeContext.settings),toolCalls:[],toolCallExecutions:[],turn:I}),l=this.turnDataCache.get(I)}else return;e.kind==="tool_execution"?await this.ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(l,e):e.kind==="turn_started"||e.kind==="turn_failed"||e.kind==="turn_retry"||e.kind==="turn_ended"?(l={...l,model:e.model,modelInfo:JSON.stringify(e.modelInfo)},e.kind==="turn_started"?l={...l,startTimeMs:e.timestampMs}:e.kind==="turn_retry"?l={...l,endTimeMs:e.timestampMs,retriesUsed:(l.retriesUsed??0)+1}:e.kind==="turn_failed"?l={...l,endTimeMs:e.timestampMs,error:e.error}:e.kind==="turn_ended"&&(l={...l,endTimeMs:e.timestampMs})):e.kind==="history_truncated"?l={...l,truncateEvent:e}:e.kind==="image_processing"?l={...l,imageProcessingMetrics:e.imageProcessingMetrics}:e.kind==="images_removed"?l={...l,largeImagesRemoved:(l.largeImagesRemoved??0)+(e.largeImagesRemoved?1:0),imagesRemoved:(l.imagesRemoved??0)+(e.imagesRemoved?1:0)}:e.kind==="model_call_success"||e.kind==="model_call_failure"?(l={...l,callId:e.callId,modelCallDurationMs:e.modelCallDurationMs,api_call_id:e.modelCall.api_id,provider_call_id:e.modelCall.request_id,conversationStructureSummary:Z0t(e.requestMessages)},e.kind==="model_call_success"&&(l={...l,responsePromptTokens:e.responseUsage?.prompt_tokens,responseCompletionTokens:e.responseUsage?.completion_tokens,responseTotalTokens:e.responseUsage?.total_tokens})):ZFt(e)&&e.source==="jit-instruction"?l={...l,jitInstructionsAdded:(l?.jitInstructionsAdded??0)+1}:Xh(e)&&e.message.tool_calls?l={...l,toolCalls:l.toolCalls.concat(e.message.tool_calls.map(n=>({...Rsl(this.runtimeContext,this.toolsInUse,n)})))}:aie(e)&&(l={...l,toolCallExecutions:l.toolCallExecutions.concat([e.message.tool_call_id])}),this.turnDataCache.set(I,l),e.kind==="turn_ended"&&(await this.emitTurnTelemetry(I),this.emittedTurns.add(I),this.turnDataCache.delete(I))}async emitTurnTelemetry(e){let I=this.turnDataCache.get(e);if(I){let l={kind:"telemetry",telemetry:{event:"get_completion_with_tools_turn",properties:{callId:I.callId,model:I.model||"default",modelInfo:I.modelInfo||"{}",api_call_id:I.api_call_id,provider_call_id:I.provider_call_id,agent:this.forAgent,toolCalls:JSON.stringify(I.toolCalls.map(n=>({toolCallId:n.toolCallId,toolName:n.safeForTelemetryToolName}))),toolCallExecutions:JSON.stringify(I.toolCallExecutions),error:I.error,featureFlags:X2e(this.runtimeContext.settings),conversationStructureSummary:I.conversationStructureSummary,truncationPerformedBy:I.truncateEvent?.performedBy},metrics:{turn:e,turnDurationMs:I.endTimeMs!==void 0&&I.startTimeMs!==void 0?I.endTimeMs-I.startTimeMs:0,modelCallDurationMs:I.modelCallDurationMs,retriesUsed:I.retriesUsed??0,numToolCalls:I.toolCalls.length,numToolExecutions:I.toolCallExecutions.length,largeImagesRemoved:I.largeImagesRemoved,imagesRemoved:I.imagesRemoved,responsePromptTokens:I.responsePromptTokens,responseCompletionTokens:I.responseCompletionTokens,responseTotalTokens:I.responseTotalTokens,jitInstructionsAdded:I.jitInstructionsAdded,...I.truncateEvent?.truncateResult,...I.imageProcessingMetrics},restrictedProperties:{}}};await this.runtimeContext.callback?.progress(l)}}async ingestToolExecutionEventAndEmitToolCallExecutedTelemetry(e,I){let l=I.toolCallId,n=Vsl(e,l);if(n){let r=I.toolResult,a={kind:"telemetry",telemetry:{event:"tool_call_executed",properties:{...r.toolTelemetry?.properties,completionWithToolsCallId:I.callId,resultType:r.resultType,toolCallId:l,arguments:n.safeForTelemetryArguments,toolName:n.safeForTelemetryToolName,api_call_id:e.api_call_id,isCustomAgent:n.isCustomAgent?"true":"false"},restrictedProperties:{...r.toolTelemetry?.restrictedProperties,arguments:n.arguments,result:r.textResultForLlm,toolName:n.toolName,error:r.error,customAgent:n.customAgentInfo?JSON.stringify({repoOwner:n.customAgentInfo.repoOwner,repoName:n.customAgentInfo.repoName,displayName:n.customAgentInfo.displayName,mcpServerNames:n.customAgentInfo.mcpServerNames}):void 0},metrics:{...r.toolTelemetry?.metrics,durationMs:I.durationMs,customAgentMcpServerCount:n.customAgentInfo?.mcpServerCount}}};await this.runtimeContext.callback?.progress(a)}}}});function Asl(t,e,I){if(!t.endsWith("/*"))return!1;t=MTt(t);let l=t.slice(0,-2).toLowerCase();for(let n of e)KMe(n).startsWith(l+"/")&&I.add(n);return!0}function Fsl(t,e,I){t=MTt(t);let l=e.get(t.toLowerCase());return l?(I.add(l),!0):!1}function wsl(t,e,I,l){if(!t.includes("/"))return!1;let[n,r]=t.split("/",2),a=r.toLowerCase(),s=e.get(a);if(s)return I.add(s),!0;let o=!1,c=l[a];if(c)for(let i of c){let d=e.get(i.toLowerCase());d&&(I.add(d),o=!0)}return o}function Qsl(t,e,I){if(t!=="shell"&&t!=="runcommands"&&t!=="runcommands-runinterminal"&&t!=="runinterminal")return!1;let l=process.platform==="win32"?"powershell":"bash",n=process.platform==="win32"?"bash":"powershell",r=e.get(l.toLowerCase());return r||(r=e.get(n.toLowerCase())),r?(I.add(r),!0):!1}function Esl(t,e,I,l){let n=l[t.toLowerCase()];if(!n)return!1;let r=!1;for(let a of n){let s=e.get(a.toLowerCase());s&&(I.add(s),r=!0)}return r}function OTt(t,e,I=[]){let l=new Map,n=new Set;for(let s of e)l.set(KMe(s),s);let r=[...UTt["custom-agent"]];for(let s of I)_F(s)&&r.push(KMe(s));let a={};for(let[s,o]of Object.entries(UTt))a[s.toLowerCase()]=o;a["custom-agent"]=r,a.agent=r,a.task=r;for(let s of t){let o=s.toLowerCase().split("/"),c=o.length>2?o[0]+"__"+o.slice(1).join("/"):s.toLowerCase();Asl(c,e,n)||Esl(c,l,n,a)||Fsl(c,l,n)||wsl(c,l,n,a)||Qsl(c,l,n)}return Array.from(n)}function MTt(t){return t.startsWith("io.github.github__github-mcp-server/")?t.replace("io.github.github__github-mcp-server/","github-mcp-server/"):t.startsWith("github__github-mcp-server/")?t.replace("github__github-mcp-server/","github-mcp-server/"):t.startsWith("com.microsoft__playwright-mcp/")?t.replace("com.microsoft__playwright-mcp/","playwright/"):t.startsWith("microsoft__playwright-mcp/")?t.replace("microsoft__playwright-mcp/","playwright/"):t.startsWith("github/")?t.replace("github/","github-mcp-server/"):t}var UTt,KMe,TTt=m(()=>{"use strict";Tce();dH();UTt={execute:["bash","powershell"],shell:["bash","powershell"],bash:["bash"],powershell:["powershell"],read:["view"],NotebookRead:["view"],edit:["apply_patch","str_replace_editor","create","edit"],MultiEdit:["apply_patch","str_replace_editor","create","edit"],Write:["apply_patch","str_replace_editor","create","edit"],NotebookEdit:["apply_patch","str_replace_editor","create","edit"],search:["search"],Grep:["search"],Glob:["search"],"custom-agent":[],agent:[],task:[],runCommands:["bash","powershell"],"runCommands-runInTerminal":["bash","powershell"],runInTerminal:["bash","powershell"],"edit-editFiles":["str_replace_editor","edit"],editFiles:["str_replace_editor","edit"],"create-createFile":["str_replace_editor","create"],createFile:["str_replace_editor","create"],createDirectory:["str_replace_editor","create"],"search-codebase":["search"],codebase:["search"],"search-fileSearch":["search"],fileSearch:["search"],"search-textSearch":["search"],textSearch:["search"],"search-readFile":["view"],readFile:["view"],[Jfe]:[Lfe]};KMe=t=>(t.namespacedName||t.name).toLowerCase()});var O7,jTt=m(()=>{"use strict";rD();O7=class{async*preRequest(e){yield*[]}handleCallbackResponse(e){}getUserMessages(){return[]}clearUserMessages(){}canProcessUserMessages(){return!1}toJSON(){return JSON.stringify({type:"NoopUserMessageProcessor"})}}});function PTt(t){return vsl.includes(t)}function Hsl(t){let e=t.content;if(typeof e=="string")return e;if(!Array.isArray(e)||e.length===0||!("text"in e[0]))throw new Error("Expected text content in response");return e[0].text}async function Csl(t,e,I,l){if(!e.mcpServers||Object.keys(e.mcpServers).length===0||!l)return I;t.info(`Custom agent ${e.name} is using MCP servers: ${Object.keys(e.mcpServers).join(", ")}`);let n=I;for(let[r,a]of Object.entries(e.mcpServers))try{t.info(`Adding MCP server '${r}' for custom agent '${e.name}'`),n=await fsl(t,e,r,a,n,l)}catch(s){t.error(`Encountered an issue when trying to add MCP ${r} for custom agent '${e.name}': ${Ae(s)}`)}return n}async function fsl(t,e,I,l,n,r){let a=await r.addServerAndGetTools(I,l,t);if(a.length>0){t.info(`Adding ${a.length} new tools from server '${I}' for custom agent '${e.name}'`);for(let s of a)t.info(`Adding new tool: ${s.name}`),n.push(s)}return n}async function DTt(t,e,I,l=void 0){if(!t.callback||!I)return;let n=I.displayName||I.name;await t.callback.progress({kind:"custom_agent_session_boundary",sessionBoundaryType:e,agentName:n,agentId:l})}function qTt(t,e,I,l,n,r,a){async function s(o,c){let i=c?.toolCallId;await DTt(n,"start",I);let d=await I.prompt();n.logger.info(`Starting custom agent as tool: ${I.name}`),n.logger.info(`Custom agent system prompt: ${d}`),n.logger.info(`Candidate tools for custom agent: ${r.map(y=>y.namespacedName||y.name).join(", ")}`),n.logger.info(`Requested tools for custom agent: ${I.tools?.join(", ")??"none"}`),r=await Csl(n.logger,I,r,a);let G=PMe(r,I,"tool");n.logger.info(`Custom agent tools after filtering: ${G.map(y=>y.name).join(", ")}`);let b=new uH(n,i),u=await t(G),h=new lw(n.logger),p=e(d,o.prompt),W=await b.agent(l,u,void 0,p,{},G,h),N=W.messages[W.messages.length-1],Y=N?Hsl(N):"No response from tool";return await DTt(n,"end",I),{textResultForLlm:Y,resultType:"success",toolTelemetry:{}}}return{title:`${I.displayName||I.name} custom agent`,name:KYt(I.name),description:`${iH} ${I.description}`,input_schema:{type:"object",properties:{prompt:{type:"string",description:"The prompt for the agent."}},required:["prompt"]},callback:s}}function PMe(t,e,I){if(!e?.tools||e.tools.length===1&&e.tools[0]==="*")return t.filter(s=>I==="top-level"||!KTt.includes(s.name));let l=t.filter(s=>_F(s)),n=I==="top-level"?Jsl:Lsl;return OTt([...e.tools,...n],t,l).filter(s=>I==="top-level"||!KTt.includes(s.name))}var vsl,Xsl,uH,kZe,Jsl,Lsl,KTt,m8=m(()=>{"use strict";yS();iet();WY();DI();Ele();qYt();Koe();aCe();Igt();igt();sAt();dE();fC();sc();Uo();Uo();ffe();Oce();Tce();b8();jMe();STt();G8();zTt();TTt();dH();jTt();Ice();vsl=["sweagent-capi","sweagent-aip","sweagent-anthropic","sweagent-openai"];Xsl=void 0,uH=class{constructor(e,I=Xsl){this.runtimeContext=e;this.agentId=I;this.gitHandlers={silent:new bh(new _c,this.runtimeContext.exec),logging:new bh(this.runtimeContext.logger,this.runtimeContext.exec)}}gitHandlers;async agent(e,I,l,n,r,a,s,o=new O7,c){let i=async(u,h,p)=>{let W={role:"user",content:u};return await this.runtimeContext.callback?.progress({kind:"message",turn:0,callId:this.agentId,message:W}),await this.runCompletionWithTools(e,I,[...h??[],W],a,s,r,{executeToolsInParallel:Ll(this.runtimeContext.settings,"copilot_swe_agent_parallel_tool_execution"),initialTurnCount:p},c,o)},d=n,G=l??[],b;for(;d;){let u=await i(d,G,b);b=u.finalTurnCount,G=u.messages,d=await c?.onResult(u.postCompletionWithToolsCommitHash)}for(let u of a)if(u.shutdown){let h=await u.shutdown();h&&await this.runtimeContext.callback?.progress(h)}return{finalTurnCount:b||0,messages:G}}async getSystemPrompt(e,I,l,n){return cgt(e?.systemMessage,this.runtimeContext.sweConfig?.supports,this.runtimeContext.sweConfig?.toolConfigOverrides,I,l,this.runtimeContext.organizationCustomInstructions,n)}async runCompletionWithTools(e,I,l,n,r,a,s,o,c=new O7){let i=this.runtimeContext.agentName??"sweagent-capi",d=this.runtimeContext.callback?new LZe(this.runtimeContext,i,n):void 0,G=this.gitHandlers.logging,b=await G.getCurrentCommitHash(e),u=l.filter(w=>w.role==="user").at(-1),h=this.createCompletionWithToolsProcessors(e,b,n,r,c,a,o,u),p=this.runtimeContext.client.getCompletionWithTools(I,l,n,{...s,callId:this.agentId,processors:h}),W=0,N=[...l],Y=[];for await(let w of p){let C=await this.runtimeContext.callback?.progress(w,{accepts_user_messages:c.canProcessUserMessages()});c.handleCallbackResponse(C),d&&await d.ingestEvent(w),(w.kind==="message"||w.kind==="response")&&(w.kind==="message"&&N.push(w.message),w.kind==="response"&&Y.push(w.response),W=Math.max(W,w.turn??0))}let y=await G.getCurrentCommitHash(e);return{finalTurnCount:W,messages:N,resultMessages:Y,preCompletionWithToolsCommitHash:b,postCompletionWithToolsCommitHash:y}}createCompletionWithToolsProcessors(e,I,l,n,r,a,s,o){let c=new uD(this.runtimeContext.logger,this.runtimeContext.settings,l.find(b=>b.name==="github-mcp-server-get_file_contents")),i=new fZe(this.runtimeContext.settings,this.runtimeContext.logger,this.gitHandlers.silent,e,I,a),d=new ev(o,this.runtimeContext.logger),G=[i,c,d,r];return G.push(n),{preRequest:G.filter(b=>b!==void 0),preToolsExecution:[s].filter(b=>b!==void 0),postToolExecution:[c,s].filter(b=>b!==void 0),onRequestError:[c,d].filter(b=>b!==void 0)}}};kZe=class{constructor(e,I,l={requestRequired:!1}){this.mcpHost=e;this.settings=I;this.permissions=l}async addServerAndGetTools(e,I,l){try{await this.mcpHost.startServer(e,I),l.info(`Successfully started MCP server '${e}'`);let r=(await this.mcpHost.getTools(this.settings,l,this.permissions)).filter(a=>a.name.startsWith(`${e}-`)||a.namespacedName?.startsWith(`${e}/`));return l.info(`Found ${r.length} MCP tools from server '${e}'`),r}catch(n){return l.error(`Failed to add MCP server '${e}': ${Ae(n)}`),[]}}},Jsl=[L3,Pse],Lsl=[qoe],KTt=[L3,Pse]});function my(t){if(!t)return _Lt;let[e,...I]=t?.split(":")??[t,void 0],l=I.join(":")||void 0,n=PTt(e)?e:oue;return l?{agent:n,model:l}:$Lt(n)}function Xue(t,e){return e?.thinkingMode||Ll(t,"copilot_swe_agent_enable_responses_api")}var bH=m(()=>{"use strict";m8();rSe();sc()});function T9(){return process.env.COPILOT_ENABLE_ALT_PROVIDERS==="true"}function Tve(t,e){let I=" ".repeat(e);return t.map(l=>{let n=typeof l=="string"?l:l.id;return`${I}- "${n}"`}).join(`
|
|
1942
|
-
`)}function zZt(t){return l2.filter(e=>!t.find(I=>I.id===e))}function H3(t,e=!1){return l2.includes(t)||T9()||e}function NZ(t,e,I=!1){
|
|
1943
|
-
`),l={};for(let n of I){let r=n.split(/\s+/);if(r.length>=3){let a=r[0],s=r[1],o=r[2].replace(/[()]/g,"");l[a]||(l[a]={Name:a,FetchURL:"",PushURL:""}),o==="fetch"?l[a].FetchURL=s:o==="push"&&(l[a].PushURL=s)}}return Object.values(l)}var rjt,j7=m(()=>{"use strict";rjt=Msl(Usl)});var eTe=g((wZr,sjt)=>{"use strict";sjt.exports=function(e,I){I===!0&&(I=0);var l="";if(typeof e=="string")try{l=new URL(e).protocol}catch{}else e&&e.constructor===URL&&(l=e.protocol);var n=l.split(/\:|\+/).filter(Boolean);return typeof I=="number"?n[I]:n}});var cjt=g((QZr,ojt)=>{"use strict";var Tsl=eTe();function jsl(t){var e={protocols:[],protocol:null,port:null,resource:"",host:"",user:"",password:"",pathname:"",hash:"",search:"",href:t,query:{},parse_failed:!1};try{var I=new URL(t);e.protocols=Tsl(I),e.protocol=e.protocols[0],e.port=I.port,e.resource=I.hostname,e.host=I.host,e.user=I.username||"",e.password=I.password||"",e.pathname=I.pathname,e.hash=I.hash.slice(1),e.search=I.search.slice(1),e.href=I.href,e.query=Object.fromEntries(I.searchParams)}catch{e.protocols=["file"],e.protocol=e.protocols[0],e.port="",e.resource="",e.user="",e.pathname="",e.hash="",e.search="",e.href=t,e.query={},e.parse_failed=!0}return e}ojt.exports=jsl});var ujt=g((EZr,mjt)=>{"use strict";var Dsl=cjt();function Ksl(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var Psl=Ksl(Dsl);function qsl(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var I=function l(){if(this instanceof l){var n=[null];n.push.apply(n,arguments);var r=Function.bind.apply(e,n);return new r}return e.apply(this,arguments)};I.prototype=e.prototype}else I={};return Object.defineProperty(I,"__esModule",{value:!0}),Object.keys(t).forEach(function(l){var n=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(I,l,n.get?n:{enumerable:!0,get:function(){return t[l]}})}),I}var djt={},_sl="text/plain",$sl="us-ascii",ijt=(t,e)=>e.some(I=>I instanceof RegExp?I.test(t):I===t),eol=(t,{stripHash:e})=>{let I=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(t);if(!I)throw new Error(`Invalid URL: ${t}`);let{type:l,data:n,hash:r}=I.groups,a=l.split(";");r=e?"":r;let s=!1;a[a.length-1]==="base64"&&(a.pop(),s=!0);let o=(a.shift()||"").toLowerCase(),i=[...a.map(d=>{let[G,b=""]=d.split("=").map(u=>u.trim());return G==="charset"&&(b=b.toLowerCase(),b===$sl)?"":`${G}${b?`=${b}`:""}`}).filter(Boolean)];return s&&i.push("base64"),(i.length>0||o&&o!==_sl)&&i.unshift(o),`data:${i.join(";")},${s?n.trim():n}${r?`#${r}`:""}`};function tol(t,e){if(e={defaultProtocol:"http:",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...e},t=t.trim(),/^data:/i.test(t))return eol(t,e);if(/^view-source:/i.test(t))throw new Error("`view-source:` is not supported as it is a non-standard protocol");let I=t.startsWith("//");!I&&/^\.*\//.test(t)||(t=t.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,e.defaultProtocol));let n=new URL(t);if(e.forceHttp&&e.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(e.forceHttp&&n.protocol==="https:"&&(n.protocol="http:"),e.forceHttps&&n.protocol==="http:"&&(n.protocol="https:"),e.stripAuthentication&&(n.username="",n.password=""),e.stripHash?n.hash="":e.stripTextFragment&&(n.hash=n.hash.replace(/#?:~:text.*?$/i,"")),n.pathname){let a=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g,s=0,o="";for(;;){let i=a.exec(n.pathname);if(!i)break;let d=i[0],G=i.index,b=n.pathname.slice(s,G);o+=b.replace(/\/{2,}/g,"/"),o+=d,s=G+d.length}let c=n.pathname.slice(s,n.pathname.length);o+=c.replace(/\/{2,}/g,"/"),n.pathname=o}if(n.pathname)try{n.pathname=decodeURI(n.pathname)}catch{}if(e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let a=n.pathname.split("/"),s=a[a.length-1];ijt(s,e.removeDirectoryIndex)&&(a=a.slice(0,-1),n.pathname=a.slice(1).join("/")+"/")}if(n.hostname&&(n.hostname=n.hostname.replace(/\.$/,""),e.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(n.hostname)&&(n.hostname=n.hostname.replace(/^www\./,""))),Array.isArray(e.removeQueryParameters))for(let a of[...n.searchParams.keys()])ijt(a,e.removeQueryParameters)&&n.searchParams.delete(a);if(e.removeQueryParameters===!0&&(n.search=""),e.sortQueryParameters){n.searchParams.sort();try{n.search=decodeURIComponent(n.search)}catch{}}e.removeTrailingSlash&&(n.pathname=n.pathname.replace(/\/$/,""));let r=t;return t=n.toString(),!e.removeSingleSlash&&n.pathname==="/"&&!r.endsWith("/")&&n.hash===""&&(t=t.replace(/\/$/,"")),(e.removeTrailingSlash||n.pathname==="/")&&n.hash===""&&e.removeSingleSlash&&(t=t.replace(/\/$/,"")),I&&!e.normalizeProtocol&&(t=t.replace(/^http:\/\//,"//")),e.stripProtocol&&(t=t.replace(/^(?:https?:)?\/\//,"")),t}var Iol=Object.freeze({__proto__:null,default:tol}),lol=qsl(Iol);Object.defineProperty(djt,"__esModule",{value:!0});var nol=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rol=lol,aol=Gjt(rol),sol=Psl.default,ool=Gjt(sol);function Gjt(t){return t&&t.__esModule?t:{default:t}}var bjt=function t(e){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,l=/^(?:([a-zA-Z_][a-zA-Z0-9_-]{0,31})@|https?:\/\/)([\w\.\-@]+)[\/:](([\~,\.\w,\-,\_,\/,\s]|%[0-9A-Fa-f]{2})+?(?:\.git|\/)?)$/,n=function(o){var c=new Error(o);throw c.subject_url=e,c};(typeof e!="string"||!e.trim())&&n("Invalid url."),e.length>t.MAX_INPUT_LENGTH&&n("Input exceeds maximum length. If needed, change the value of parseUrl.MAX_INPUT_LENGTH."),I&&((typeof I>"u"?"undefined":nol(I))!=="object"&&(I={stripHash:!1}),e=(0,aol.default)(e,I));var r=(0,ool.default)(e);if(r.parse_failed){var a=r.href.match(l);a?(r.protocols=["ssh"],r.protocol="ssh",r.resource=a[2],r.host=a[2],r.user=a[1],r.pathname="/"+a[3],r.parse_failed=!1):n("URL parsing failed.")}return r};bjt.MAX_INPUT_LENGTH=2048;var col=djt.default=bjt;mjt.exports=col});var Zjt=g((vZr,pjt)=>{"use strict";var iol=eTe();function hjt(t){if(Array.isArray(t))return t.indexOf("ssh")!==-1||t.indexOf("rsync")!==-1;if(typeof t!="string")return!1;var e=iol(t);if(t=t.substring(t.indexOf("://")+3),hjt(e))return!0;var I=new RegExp(".([a-zA-Z\\d]+):(\\d+)/");return!t.match(I)&&t.indexOf("@")<t.indexOf(":")}pjt.exports=hjt});var Yjt=g((XZr,Njt)=>{"use strict";var dol=ujt(),Wjt=Zjt();function Gol(t){let e=dol(t);return e.token="",e.password==="x-oauth-basic"?e.token=e.user:e.user==="x-token-auth"&&(e.token=e.password),Wjt(e.protocols)||e.protocols.length===0&&Wjt(t)?e.protocol="ssh":e.protocols.length?e.protocol=e.protocols[0]:(e.protocol="file",e.protocols=["file"]),e.href=e.href.replace(/\/$/,""),e}Njt.exports=Gol});var yjt=g((HZr,gjt)=>{"use strict";var bol=Yjt();function tTe(t,e){if(e=e||[],typeof t!="string")throw new Error("The url must be a string.");if(!e.every(function(N){return typeof N=="string"}))throw new Error("The refs should contain only strings");var I=/^([a-z\d-]{1,39})\/([-\.\w]{1,100})$/i;I.test(t)&&(t="https://github.com/"+t);var l=bol(t),n=l.resource.split("."),r=null;switch(l.toString=function(N){return tTe.stringify(this,N)},l.source=n.length>2?n.slice(1-n.length).join("."):l.source=l.resource,l.git_suffix=/\.git$/.test(l.pathname),l.name=decodeURIComponent((l.pathname||l.href).replace(/(^\/)|(\/$)/g,"").replace(/\.git$/,"")),l.owner=decodeURIComponent(l.user),l.source){case"git.cloudforge.com":l.owner=l.user,l.organization=n[0],l.source="cloudforge.com";break;case"visualstudio.com":if(l.resource==="vs-ssh.visualstudio.com"){r=l.name.split("/"),r.length===4&&(l.organization=r[1],l.owner=r[2],l.name=r[3],l.full_name=r[2]+"/"+r[3]);break}else{r=l.name.split("/"),r.length===2?(l.owner=r[1],l.name=r[1],l.full_name="_git/"+l.name):r.length===3?(l.name=r[2],r[0]==="DefaultCollection"?(l.owner=r[2],l.organization=r[0],l.full_name=l.organization+"/_git/"+l.name):(l.owner=r[0],l.full_name=l.owner+"/_git/"+l.name)):r.length===4&&(l.organization=r[0],l.owner=r[1],l.name=r[3],l.full_name=l.organization+"/"+l.owner+"/_git/"+l.name);break}case"dev.azure.com":case"azure.com":if(l.resource==="ssh.dev.azure.com"){r=l.name.split("/"),r.length===4&&(l.organization=r[1],l.owner=r[2],l.name=r[3]);break}else{r=l.name.split("/"),r.length===5?(l.organization=r[0],l.owner=r[1],l.name=r[4],l.full_name="_git/"+l.name):r.length===3?(l.name=r[2],r[0]==="DefaultCollection"?(l.owner=r[2],l.organization=r[0],l.full_name=l.organization+"/_git/"+l.name):(l.owner=r[0],l.full_name=l.owner+"/_git/"+l.name)):r.length===4&&(l.organization=r[0],l.owner=r[1],l.name=r[3],l.full_name=l.organization+"/"+l.owner+"/_git/"+l.name),l.query&&l.query.path&&(l.filepath=l.query.path.replace(/^\/+/g,"")),l.query&&l.query.version&&(l.ref=l.query.version.replace(/^GB/,""));break}default:r=l.name.split("/");var a=r.length-1;if(r.length>=2){var s=r.indexOf("-",2),o=r.indexOf("blob",2),c=r.indexOf("tree",2),i=r.indexOf("commit",2),d=r.indexOf("issues",2),G=r.indexOf("src",2),b=r.indexOf("raw",2),u=r.indexOf("edit",2);a=s>0?s-1:o>0&&c>0?Math.min(o-1,c-1):o>0?o-1:d>0?d-1:c>0?c-1:i>0?i-1:G>0?G-1:b>0?b-1:u>0?u-1:a,l.owner=r.slice(0,a).join("/"),l.name=r[a],i&&d<0&&(l.commit=r[a+2])}l.ref="",l.filepathtype="",l.filepath="";var h=r.length>a&&r[a+1]==="-"?a+1:a;r.length>h+2&&["raw","src","blob","tree","edit"].indexOf(r[h+1])>=0&&(l.filepathtype=r[h+1],l.ref=r[h+2],r.length>h+3&&(l.filepath=r.slice(h+3).join("/"))),l.organization=l.owner;break}l.full_name||(l.full_name=l.owner,l.name&&(l.full_name&&(l.full_name+="/"),l.full_name+=l.name)),l.owner.startsWith("scm/")&&(l.source="bitbucket-server",l.owner=l.owner.replace("scm/",""),l.organization=l.owner,l.full_name=l.owner+"/"+l.name);var p=/(projects|users)\/(.*?)\/repos\/(.*?)((\/.*$)|$)/,W=p.exec(l.pathname);return W!=null&&(l.source="bitbucket-server",W[1]==="users"?l.owner="~"+W[2]:l.owner=W[2],l.organization=l.owner,l.name=W[3],r=W[4].split("/"),r.length>1&&(["raw","browse"].indexOf(r[1])>=0?(l.filepathtype=r[1],r.length>2&&(l.filepath=r.slice(2).join("/"))):r[1]==="commits"&&r.length>2&&(l.commit=r[2])),l.full_name=l.owner+"/"+l.name,l.query.at?l.ref=l.query.at:l.ref=""),e.length!==0&&l.ref&&(l.ref=hol(l.href,e)||l.ref,l.filepath=l.href.split(l.ref+"/")[1]),l}tTe.stringify=function(t,e){e=e||(t.protocols&&t.protocols.length?t.protocols.join("+"):t.protocol);var I=t.port?":"+t.port:"",l=t.user||"git",n=t.git_suffix?".git":"";switch(e){case"ssh":return I?"ssh://"+l+"@"+t.resource+I+"/"+t.full_name+n:l+"@"+t.resource+":"+t.full_name+n;case"git+ssh":case"ssh+git":case"ftp":case"ftps":return e+"://"+l+"@"+t.resource+I+"/"+t.full_name+n;case"http":case"https":var r=t.token?mol(t):t.user&&(t.protocols.includes("http")||t.protocols.includes("https"))?t.user+"@":"";return e+"://"+r+t.resource+I+"/"+uol(t)+n;default:return t.href}};function mol(t){switch(t.source){case"bitbucket.org":return"x-token-auth:"+t.token+"@";default:return t.token+"@"}}function uol(t){switch(t.source){case"bitbucket-server":return"scm/"+t.full_name;default:var e=t.full_name.split("/").map(function(I){return encodeURIComponent(I)}).join("/");return e}}function hol(t,e){var I="";return e.forEach(function(l){t.includes(l)&&l.length>I.length&&(I=l)}),I}gjt.exports=tTe});function ITe(t){try{let e=(0,Vjt.default)(t.FetchURL);return e.source!=="github.com"||!e.owner||!e.name?null:{owner:e.owner,name:e.name,host:"github.com"}}catch{return null}}async function zZe(t){let e=await ajt(t);if(e.length===0)return null;if(e.length===1)return ITe(e[0]);let I=e.find(l=>l.Name==="origin");return ITe(I||e[0])}var Vjt,lTe=m(()=>{"use strict";Vjt=lI(yjt(),1);j7()});async function Ajt(t){let e=await j9(t);if(!e.found)return{kind:"plain",path:t};try{let I=await zZe(e.gitRoot);return{kind:"git",path:e.gitRoot,repo:I}}catch{return{kind:"git",path:e.gitRoot,repo:null}}}var Rjt,nTe=m(()=>{"use strict";Rjt=lI(p$(),1);j7();lTe()});import{readdir as pol,readFile as Zol}from"node:fs/promises";import OZr,{join as Ejt}from"node:path";function Fjt(t){let e=new Set,I=[];for(let l of t)e.has(l.id)||(e.add(l.id),I.push(l));return I}async function Hjt(t,e,I,l,n,r=!1){let a=await wjt(l);if(n===null)return{agents:a.agents,warnings:a.warnings};let s=await wjt(Ejt(n.path,".github","agents")),o=Fjt([...a.agents,...s.agents]),c=[...a.warnings,...s.warnings];if(n.kind!=="git")return{agents:o,warnings:c};if(!n.repo)return{agents:o,warnings:[...c,"could not load remote agents, no github.com remote found"]};if(r)return{agents:o,warnings:c};if(!I)return{agents:o,warnings:[...c,D9(n.repo,"no authentication available")]};let i=await Wol(t,e,I,n.repo);return{agents:Fjt([...o,...i.agents]),warnings:[...c,...i.warnings]}}function D9(t,e){return`could not load remote agents for ${t.owner}/${t.name}: ${e}`}async function Wol(t,e,I,l,n=!1){let r=Qj(I,{onHMACAuthInfo:()=>R2e,onEnvAuthInfo:h=>h.host,onGhCliAuthInfo:h=>h.host,onUserAuthInfo:h=>h.host,onApiKeyAuthInfo:h=>h.host,onTokenAuthInfo:h=>h.host}),{host:a}=new URL(r);if(a!=="github.com")return{agents:[],warnings:[D9(l,"auth info does not target github.com")]};let s=await Yh(I);if(!s)return{agents:[],warnings:[D9(l,"no usable token for accessing repo contents found")]};let o=await Cjt(()=>CC(r,s,t),h=>KR("fetching copilot URL",h));if(o.kind==="error")return{agents:[],warnings:[D9(l,o.message)]};let c=`${o.value}/agents/swe/custom-agents/${l.owner}/${l.name}?exclude_invalid_config=true${n?"":"&include_sources=org,enterprise"}`,i={Authorization:`Bearer ${s}`},d=await Y2(c,{method:"GET",headers:i},t);if(!d.ok)return t.warning(`Failed to load custom agents for ${l.owner}/${l.name}: ${await d.text()}`),{agents:[],warnings:[D9(l,`server returned ${d.status}: ${d.statusText}`)]};let G=await d.json(),u=sl.object({agents:sl.array(Jjt)}).safeParse(G);return u.success?{agents:u.data.agents.map(h=>({id:h.name,displayName:h.display_name,description:h.description,tools:h.tools,prompt:async()=>{let p=await Rol({logger:t,integrationId:e,sweAgentsEndpoint:`${o.value}/agents/swe`,token:s,repoOwner:h.repo_owner,repoName:h.repo_name,customAgentName:h.name});if(!p)throw new Error(`Failed to load prompt for agent ${h.name}`);return p.prompt},mcpServers:h.mcp_servers||{},infer:h.infer})),warnings:[]}:{agents:[],warnings:[D9(l,KR("parsing http response into schema",u.error))]}}async function wjt(t){let e=await pol(t,{withFileTypes:!0}).then(r=>({kind:"success",dirEntries:r})).catch(r=>r.code==="ENOENT"?{kind:"success",dirEntries:[]}:{kind:"error",message:KR(t,r)});if(e.kind==="error")return{agents:[],warnings:[]};let I=new Map;for(let r of e.dirEntries)if(r.isFile()&&r.name.endsWith(".md")){let a=r.name.endsWith(".agent.md"),s=r.name.replace(/(\.agent)?\.md$/,""),o=I.get(s);(!o||a&&!o.isAgentMd)&&I.set(s,{fileName:r.name,isAgentMd:a})}let l=[],n=[];for(let[r,{fileName:a}]of I.entries()){let s=Ejt(t,a),o=await Qjt(s);if(o.kind==="error"){n.push(o.message);continue}l.push({id:r,displayName:o.agent.name||r,description:o.agent.description,tools:o.agent.tools||["*"],prompt:async()=>{let c=await Qjt(s);if(c.kind==="error")throw new Error(c.message);return await c.agent.prompt()},mcpServers:o.agent.mcpServers||{},infer:o.agent.infer})}return{agents:l,warnings:n}}async function Qjt(t){let e=await Cjt(()=>Zol(t,"utf-8"),l=>KR(t,l));if(e.kind==="error")return{kind:"error",message:e.message};let I=Nol(e.value);return I.kind==="error"?{kind:"error",message:`${t}: ${I.message}`}:{kind:"success",agent:I.agent}}function Yol(t){let e=(I,l="")=>{let n=I.path.join(".")||"(root)",r=[];return I.code==="invalid_union"&&"unionErrors"in I?(r.push(`${l}${n}: ${I.message}`),I.unionErrors.forEach((s,o)=>{r.push(`${l} Option ${o+1}:`),s.issues.forEach(c=>{r.push(...e(c,l+" "))})})):r.push(`${l}${n}: ${I.message}`),r};return t.issues.flatMap(I=>e(I)).join(`
|
|
1942
|
+
`)}function zZt(t){return l2.filter(e=>!t.find(I=>I.id===e))}function H3(t,e=!1){return l2.includes(t)||T9()||e}function NZ(t,e,I=!1){return I||!e?!0:!!e.find(n=>n.id===t)}function ksl(t){return l2.find(e=>NZ(e,t)&&qMe(e,t)<=1)}function qMe(t,e){if(e&&e.length>0){let l=e.find(n=>n.id===t);if(l?.billing?.multiplier!==void 0)return l.billing.multiplier}return{"claude-sonnet-4":1,"gpt-5":1,"claude-sonnet-4.5":1,"claude-haiku-4.5":.33,"gpt-5.1-codex":1,"gpt-5.1-codex-mini":.33,"gpt-5.1-codex-max":1,"gpt-5.2":1,"gpt-5.1":1,"gemini-3-pro-preview":1,"gpt-5-mini":0,"gpt-4.1":0,"claude-opus-4.5":3}[t]??1}async function _Me(t){return T9()&&process.env.COPILOT_AGENT_MODEL?process.env.COPILOT_AGENT_MODEL:`capi:${t}`}async function $Me(t,e,I,l,n=!1){if(T9()&&process.env.COPILOT_AGENT_MODEL){let{model:s}=my(process.env.COPILOT_AGENT_MODEL);if(s)return s}if(t){if(NZ(t,I,n))return t;l?.warning(`Model '${t}' from CLI argument is not available. Falling back to next option.`)}if(e){let s=await e?.getSelectedModel?.();if(s){if(NZ(s,I,n))return s;l?.warning(`Model '${s}' from session is not available. Falling back to next option.`)}}let r=process.env.COPILOT_MODEL;if(r&&H3(r,n)){if(NZ(r,I,n))return r;l?.warning(`Model '${r}' from COPILOT_MODEL environment variable is not available. Falling back to next option.`)}try{let o=(await Go.load()||{}).model;if(typeof o=="string"&&o&&H3(o,n)){if(NZ(o,I,n))return o;l?.warning(`Model '${o}' from config file is not available. Falling back to default.`)}}catch{}if(n){l?.error("Custom provider requires an explicit model. Use --model flag, COPILOT_MODEL env var, or config file.");return}let a=ksl(I);return a&&l?.info(`Using default model: ${a}`),a}var l2,C3=m(()=>{"use strict";bH();xE();l2=["claude-sonnet-4.5","claude-haiku-4.5","claude-opus-4.5","claude-sonnet-4","gpt-5.1-codex-max","gpt-5.1-codex","gpt-5.2","gpt-5.1","gpt-5","gpt-5.1-codex-mini","gpt-5-mini","gpt-4.1","gemini-3-pro-preview"]});var _Tt=m(()=>{"use strict";G1();DI()});var ejt=g((Ppr,$Tt)=>{function xsl(t){try{return B(t+"/keytar.node")}catch{}}function Bsl(){var t="prebuilds/"+process.platform+"-"+process.arch,e=["../build/Release","../"+t,"./"+t];for(var I of e){var l=xsl(I);if(l)return l}throw new Error("Failed to load keytar native addon, checked "+JSON.stringify(e)+" on "+t)}var M7=Bsl();function Xy(t,e){if(!t||t.length<=0)throw new Error(e+" is required.")}$Tt.exports={getPassword:function(t,e){return Xy(t,"Service"),Xy(e,"Account"),M7.getPassword(t,e)},setPassword:function(t,e,I){return Xy(t,"Service"),Xy(e,"Account"),Xy(I,"Password"),M7.setPassword(t,e,I)},deletePassword:function(t,e){return Xy(t,"Service"),Xy(e,"Account"),M7.deletePassword(t,e)},findPassword:function(t){return Xy(t,"Service"),M7.findPassword(t)},findCredentials:function(t){return Xy(t,"Service"),M7.findCredentials(t)}}});import{existsSync as tjt}from"fs";async function SZe(){if(BZe)return BZe;let t=await Promise.resolve().then(()=>lI(ejt(),1));return BZe=t.default||t,BZe}var xZe,BZe,T7,Ssl,Ijt,ljt=m(()=>{"use strict";xE();xZe="copilot-cli";T7=(t,e)=>{if(!(!t||!e))return`${t}:${e}`},Ssl=()=>{let t=new Map,e=async(o,c)=>{let i=T7(o,c);if(i)if(tjt(Go.path()))try{let b=(await Go.load())?.copilot_tokens?.[i];t.set(i,b&&b.trim()!==""?b:void 0)}catch{t.set(i,void 0)}else t.set(i,void 0)},I=async()=>{if(tjt(Go.path()))try{let c=(await Go.load())?.copilot_tokens;if(c){let i=Object.values(c).filter(d=>d&&d.trim()!=="");if(i.length>0)return i[0]}}catch{return}},l=async(o,c)=>{let i=T7(o,c);if(!i)return;if(t.has(i))return t.get(i);if((await Go.load())?.store_token_plaintext)return await e(o,c),t.get(i);try{let b=await(await SZe()).getPassword(xZe,i);b?t.set(i,b):await e(o,c)}catch{await e(o,c)}return t.get(i)},n=async()=>{if(t.size>0)return t.values().next().value;if((await Go.load())?.store_token_plaintext)return await I();let c;try{c=await(await SZe()).findPassword(xZe)}catch{}return c||(c=await I()),c},r=async(o,c)=>{let i=T7(o,c);if(i){t.delete(i);try{return(await SZe()).deletePassword(xZe,i)}catch{let b=(await Go.load())?.copilot_tokens??{};return delete b[i],await Go.writeKey("copilot_tokens",b),Promise.resolve(!0)}}},a=async(o,c,i)=>{if(!o)throw new Error("No token provided to store");let d=T7(c,i);if(!d)return;if(t.set(d,o),(await Go.load())?.store_token_plaintext)return await s(c,i),!0;try{return await(await SZe()).setPassword(xZe,d,o),!0}catch{return!1}},s=async(o,c)=>{let i=T7(o,c);if(!i)return;let d=t.get(i);if(!d)return;let b=(await Go.load())?.copilot_tokens??{};b[i]=d,await Go.writeKey("copilot_tokens",b)};return{getToken:l,getAnyToken:n,removeToken:r,storeToken:a,storeCurrentTokenInConfig:s}},Ijt=Ssl()});var zsl,njt=m(()=>{"use strict";oze();zsl={CUSTOM_AGENTS:!0,CCA_DELEGATE:!0,COPILOT_KITTY:!0,CONTINUITY:!1,CONTINUITY_REMOTE_CONTROL:!1,UPDATE_TODO_TOOL:!1,FEATURE_FLAG_TEST:!1,S2STOKENS:!1,[Z8]:!1}});function Ej(t,e){switch(t.type){case"hmac":return e.onHMACAuthInfo(t);case"env":return e.onEnvAuthInfo(t);case"user":return e.onUserAuthInfo(t);case"gh-cli":return e.onGhCliAuthInfo(t);case"api-key":return e.onApiKeyAuthInfo(t);case"token":return e.onTokenAuthInfo(t);default:{let I=t;throw new Error(`unexpected auth info type: ${JSON.stringify(t)}`)}}}async function Yh(t){return await Ej(t,{onHMACAuthInfo:async()=>process.env.GITHUB_MCP_SERVER_TOKEN,onEnvAuthInfo:async e=>e.token,onUserAuthInfo:async e=>await Ijt.getToken(e.host,e.login)||void 0,onGhCliAuthInfo:async e=>e.token,onApiKeyAuthInfo:async()=>{},onTokenAuthInfo:async e=>e.token})}function UZt(t,e){return!t||t.type==="hmac"?`${WS}/${e}`:`${t.host}/${e}`}var BE=m(()=>{"use strict";V2();fC();G1();C3();vse();_Tt();ljt();DI();njt()});import{execFile as Usl}from"node:child_process";import{normalize as Osl}from"node:path";import{promisify as Msl}from"node:util";async function j9(t=process.cwd()){try{let I=(await rjt("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576})).stdout.trim();if(I)return{gitRoot:Osl(I),found:!0}}catch{}return{gitRoot:t,found:!1}}async function ajt(t){let{stdout:e}=await rjt("git",["-C",t,"remote","-v"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576}),I=e.trim().split(`
|
|
1943
|
+
`),l={};for(let n of I){let r=n.split(/\s+/);if(r.length>=3){let a=r[0],s=r[1],o=r[2].replace(/[()]/g,"");l[a]||(l[a]={Name:a,FetchURL:"",PushURL:""}),o==="fetch"?l[a].FetchURL=s:o==="push"&&(l[a].PushURL=s)}}return Object.values(l)}var rjt,j7=m(()=>{"use strict";rjt=Msl(Usl)});var eTe=g((wZr,sjt)=>{"use strict";sjt.exports=function(e,I){I===!0&&(I=0);var l="";if(typeof e=="string")try{l=new URL(e).protocol}catch{}else e&&e.constructor===URL&&(l=e.protocol);var n=l.split(/\:|\+/).filter(Boolean);return typeof I=="number"?n[I]:n}});var cjt=g((QZr,ojt)=>{"use strict";var Tsl=eTe();function jsl(t){var e={protocols:[],protocol:null,port:null,resource:"",host:"",user:"",password:"",pathname:"",hash:"",search:"",href:t,query:{},parse_failed:!1};try{var I=new URL(t);e.protocols=Tsl(I),e.protocol=e.protocols[0],e.port=I.port,e.resource=I.hostname,e.host=I.host,e.user=I.username||"",e.password=I.password||"",e.pathname=I.pathname,e.hash=I.hash.slice(1),e.search=I.search.slice(1),e.href=I.href,e.query=Object.fromEntries(I.searchParams)}catch{e.protocols=["file"],e.protocol=e.protocols[0],e.port="",e.resource="",e.user="",e.pathname="",e.hash="",e.search="",e.href=t,e.query={},e.parse_failed=!0}return e}ojt.exports=jsl});var ujt=g((EZr,mjt)=>{"use strict";var Dsl=cjt();function Ksl(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var Psl=Ksl(Dsl);function qsl(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var I=function l(){if(this instanceof l){var n=[null];n.push.apply(n,arguments);var r=Function.bind.apply(e,n);return new r}return e.apply(this,arguments)};I.prototype=e.prototype}else I={};return Object.defineProperty(I,"__esModule",{value:!0}),Object.keys(t).forEach(function(l){var n=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(I,l,n.get?n:{enumerable:!0,get:function(){return t[l]}})}),I}var djt={},_sl="text/plain",$sl="us-ascii",ijt=(t,e)=>e.some(I=>I instanceof RegExp?I.test(t):I===t),eol=(t,{stripHash:e})=>{let I=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(t);if(!I)throw new Error(`Invalid URL: ${t}`);let{type:l,data:n,hash:r}=I.groups,a=l.split(";");r=e?"":r;let s=!1;a[a.length-1]==="base64"&&(a.pop(),s=!0);let o=(a.shift()||"").toLowerCase(),i=[...a.map(d=>{let[G,b=""]=d.split("=").map(u=>u.trim());return G==="charset"&&(b=b.toLowerCase(),b===$sl)?"":`${G}${b?`=${b}`:""}`}).filter(Boolean)];return s&&i.push("base64"),(i.length>0||o&&o!==_sl)&&i.unshift(o),`data:${i.join(";")},${s?n.trim():n}${r?`#${r}`:""}`};function tol(t,e){if(e={defaultProtocol:"http:",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...e},t=t.trim(),/^data:/i.test(t))return eol(t,e);if(/^view-source:/i.test(t))throw new Error("`view-source:` is not supported as it is a non-standard protocol");let I=t.startsWith("//");!I&&/^\.*\//.test(t)||(t=t.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,e.defaultProtocol));let n=new URL(t);if(e.forceHttp&&e.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(e.forceHttp&&n.protocol==="https:"&&(n.protocol="http:"),e.forceHttps&&n.protocol==="http:"&&(n.protocol="https:"),e.stripAuthentication&&(n.username="",n.password=""),e.stripHash?n.hash="":e.stripTextFragment&&(n.hash=n.hash.replace(/#?:~:text.*?$/i,"")),n.pathname){let a=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g,s=0,o="";for(;;){let i=a.exec(n.pathname);if(!i)break;let d=i[0],G=i.index,b=n.pathname.slice(s,G);o+=b.replace(/\/{2,}/g,"/"),o+=d,s=G+d.length}let c=n.pathname.slice(s,n.pathname.length);o+=c.replace(/\/{2,}/g,"/"),n.pathname=o}if(n.pathname)try{n.pathname=decodeURI(n.pathname)}catch{}if(e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let a=n.pathname.split("/"),s=a[a.length-1];ijt(s,e.removeDirectoryIndex)&&(a=a.slice(0,-1),n.pathname=a.slice(1).join("/")+"/")}if(n.hostname&&(n.hostname=n.hostname.replace(/\.$/,""),e.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(n.hostname)&&(n.hostname=n.hostname.replace(/^www\./,""))),Array.isArray(e.removeQueryParameters))for(let a of[...n.searchParams.keys()])ijt(a,e.removeQueryParameters)&&n.searchParams.delete(a);if(e.removeQueryParameters===!0&&(n.search=""),e.sortQueryParameters){n.searchParams.sort();try{n.search=decodeURIComponent(n.search)}catch{}}e.removeTrailingSlash&&(n.pathname=n.pathname.replace(/\/$/,""));let r=t;return t=n.toString(),!e.removeSingleSlash&&n.pathname==="/"&&!r.endsWith("/")&&n.hash===""&&(t=t.replace(/\/$/,"")),(e.removeTrailingSlash||n.pathname==="/")&&n.hash===""&&e.removeSingleSlash&&(t=t.replace(/\/$/,"")),I&&!e.normalizeProtocol&&(t=t.replace(/^http:\/\//,"//")),e.stripProtocol&&(t=t.replace(/^(?:https?:)?\/\//,"")),t}var Iol=Object.freeze({__proto__:null,default:tol}),lol=qsl(Iol);Object.defineProperty(djt,"__esModule",{value:!0});var nol=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rol=lol,aol=Gjt(rol),sol=Psl.default,ool=Gjt(sol);function Gjt(t){return t&&t.__esModule?t:{default:t}}var bjt=function t(e){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,l=/^(?:([a-zA-Z_][a-zA-Z0-9_-]{0,31})@|https?:\/\/)([\w\.\-@]+)[\/:](([\~,\.\w,\-,\_,\/,\s]|%[0-9A-Fa-f]{2})+?(?:\.git|\/)?)$/,n=function(o){var c=new Error(o);throw c.subject_url=e,c};(typeof e!="string"||!e.trim())&&n("Invalid url."),e.length>t.MAX_INPUT_LENGTH&&n("Input exceeds maximum length. If needed, change the value of parseUrl.MAX_INPUT_LENGTH."),I&&((typeof I>"u"?"undefined":nol(I))!=="object"&&(I={stripHash:!1}),e=(0,aol.default)(e,I));var r=(0,ool.default)(e);if(r.parse_failed){var a=r.href.match(l);a?(r.protocols=["ssh"],r.protocol="ssh",r.resource=a[2],r.host=a[2],r.user=a[1],r.pathname="/"+a[3],r.parse_failed=!1):n("URL parsing failed.")}return r};bjt.MAX_INPUT_LENGTH=2048;var col=djt.default=bjt;mjt.exports=col});var Zjt=g((vZr,pjt)=>{"use strict";var iol=eTe();function hjt(t){if(Array.isArray(t))return t.indexOf("ssh")!==-1||t.indexOf("rsync")!==-1;if(typeof t!="string")return!1;var e=iol(t);if(t=t.substring(t.indexOf("://")+3),hjt(e))return!0;var I=new RegExp(".([a-zA-Z\\d]+):(\\d+)/");return!t.match(I)&&t.indexOf("@")<t.indexOf(":")}pjt.exports=hjt});var Yjt=g((XZr,Njt)=>{"use strict";var dol=ujt(),Wjt=Zjt();function Gol(t){let e=dol(t);return e.token="",e.password==="x-oauth-basic"?e.token=e.user:e.user==="x-token-auth"&&(e.token=e.password),Wjt(e.protocols)||e.protocols.length===0&&Wjt(t)?e.protocol="ssh":e.protocols.length?e.protocol=e.protocols[0]:(e.protocol="file",e.protocols=["file"]),e.href=e.href.replace(/\/$/,""),e}Njt.exports=Gol});var yjt=g((HZr,gjt)=>{"use strict";var bol=Yjt();function tTe(t,e){if(e=e||[],typeof t!="string")throw new Error("The url must be a string.");if(!e.every(function(N){return typeof N=="string"}))throw new Error("The refs should contain only strings");var I=/^([a-z\d-]{1,39})\/([-\.\w]{1,100})$/i;I.test(t)&&(t="https://github.com/"+t);var l=bol(t),n=l.resource.split("."),r=null;switch(l.toString=function(N){return tTe.stringify(this,N)},l.source=n.length>2?n.slice(1-n.length).join("."):l.source=l.resource,l.git_suffix=/\.git$/.test(l.pathname),l.name=decodeURIComponent((l.pathname||l.href).replace(/(^\/)|(\/$)/g,"").replace(/\.git$/,"")),l.owner=decodeURIComponent(l.user),l.source){case"git.cloudforge.com":l.owner=l.user,l.organization=n[0],l.source="cloudforge.com";break;case"visualstudio.com":if(l.resource==="vs-ssh.visualstudio.com"){r=l.name.split("/"),r.length===4&&(l.organization=r[1],l.owner=r[2],l.name=r[3],l.full_name=r[2]+"/"+r[3]);break}else{r=l.name.split("/"),r.length===2?(l.owner=r[1],l.name=r[1],l.full_name="_git/"+l.name):r.length===3?(l.name=r[2],r[0]==="DefaultCollection"?(l.owner=r[2],l.organization=r[0],l.full_name=l.organization+"/_git/"+l.name):(l.owner=r[0],l.full_name=l.owner+"/_git/"+l.name)):r.length===4&&(l.organization=r[0],l.owner=r[1],l.name=r[3],l.full_name=l.organization+"/"+l.owner+"/_git/"+l.name);break}case"dev.azure.com":case"azure.com":if(l.resource==="ssh.dev.azure.com"){r=l.name.split("/"),r.length===4&&(l.organization=r[1],l.owner=r[2],l.name=r[3]);break}else{r=l.name.split("/"),r.length===5?(l.organization=r[0],l.owner=r[1],l.name=r[4],l.full_name="_git/"+l.name):r.length===3?(l.name=r[2],r[0]==="DefaultCollection"?(l.owner=r[2],l.organization=r[0],l.full_name=l.organization+"/_git/"+l.name):(l.owner=r[0],l.full_name=l.owner+"/_git/"+l.name)):r.length===4&&(l.organization=r[0],l.owner=r[1],l.name=r[3],l.full_name=l.organization+"/"+l.owner+"/_git/"+l.name),l.query&&l.query.path&&(l.filepath=l.query.path.replace(/^\/+/g,"")),l.query&&l.query.version&&(l.ref=l.query.version.replace(/^GB/,""));break}default:r=l.name.split("/");var a=r.length-1;if(r.length>=2){var s=r.indexOf("-",2),o=r.indexOf("blob",2),c=r.indexOf("tree",2),i=r.indexOf("commit",2),d=r.indexOf("issues",2),G=r.indexOf("src",2),b=r.indexOf("raw",2),u=r.indexOf("edit",2);a=s>0?s-1:o>0&&c>0?Math.min(o-1,c-1):o>0?o-1:d>0?d-1:c>0?c-1:i>0?i-1:G>0?G-1:b>0?b-1:u>0?u-1:a,l.owner=r.slice(0,a).join("/"),l.name=r[a],i&&d<0&&(l.commit=r[a+2])}l.ref="",l.filepathtype="",l.filepath="";var h=r.length>a&&r[a+1]==="-"?a+1:a;r.length>h+2&&["raw","src","blob","tree","edit"].indexOf(r[h+1])>=0&&(l.filepathtype=r[h+1],l.ref=r[h+2],r.length>h+3&&(l.filepath=r.slice(h+3).join("/"))),l.organization=l.owner;break}l.full_name||(l.full_name=l.owner,l.name&&(l.full_name&&(l.full_name+="/"),l.full_name+=l.name)),l.owner.startsWith("scm/")&&(l.source="bitbucket-server",l.owner=l.owner.replace("scm/",""),l.organization=l.owner,l.full_name=l.owner+"/"+l.name);var p=/(projects|users)\/(.*?)\/repos\/(.*?)((\/.*$)|$)/,W=p.exec(l.pathname);return W!=null&&(l.source="bitbucket-server",W[1]==="users"?l.owner="~"+W[2]:l.owner=W[2],l.organization=l.owner,l.name=W[3],r=W[4].split("/"),r.length>1&&(["raw","browse"].indexOf(r[1])>=0?(l.filepathtype=r[1],r.length>2&&(l.filepath=r.slice(2).join("/"))):r[1]==="commits"&&r.length>2&&(l.commit=r[2])),l.full_name=l.owner+"/"+l.name,l.query.at?l.ref=l.query.at:l.ref=""),e.length!==0&&l.ref&&(l.ref=hol(l.href,e)||l.ref,l.filepath=l.href.split(l.ref+"/")[1]),l}tTe.stringify=function(t,e){e=e||(t.protocols&&t.protocols.length?t.protocols.join("+"):t.protocol);var I=t.port?":"+t.port:"",l=t.user||"git",n=t.git_suffix?".git":"";switch(e){case"ssh":return I?"ssh://"+l+"@"+t.resource+I+"/"+t.full_name+n:l+"@"+t.resource+":"+t.full_name+n;case"git+ssh":case"ssh+git":case"ftp":case"ftps":return e+"://"+l+"@"+t.resource+I+"/"+t.full_name+n;case"http":case"https":var r=t.token?mol(t):t.user&&(t.protocols.includes("http")||t.protocols.includes("https"))?t.user+"@":"";return e+"://"+r+t.resource+I+"/"+uol(t)+n;default:return t.href}};function mol(t){switch(t.source){case"bitbucket.org":return"x-token-auth:"+t.token+"@";default:return t.token+"@"}}function uol(t){switch(t.source){case"bitbucket-server":return"scm/"+t.full_name;default:var e=t.full_name.split("/").map(function(I){return encodeURIComponent(I)}).join("/");return e}}function hol(t,e){var I="";return e.forEach(function(l){t.includes(l)&&l.length>I.length&&(I=l)}),I}gjt.exports=tTe});function ITe(t){try{let e=(0,Vjt.default)(t.FetchURL);return e.source!=="github.com"||!e.owner||!e.name?null:{owner:e.owner,name:e.name,host:"github.com"}}catch{return null}}async function zZe(t){let e=await ajt(t);if(e.length===0)return null;if(e.length===1)return ITe(e[0]);let I=e.find(l=>l.Name==="origin");return ITe(I||e[0])}var Vjt,lTe=m(()=>{"use strict";Vjt=lI(yjt(),1);j7()});async function Ajt(t){let e=await j9(t);if(!e.found)return{kind:"plain",path:t};try{let I=await zZe(e.gitRoot);return{kind:"git",path:e.gitRoot,repo:I}}catch{return{kind:"git",path:e.gitRoot,repo:null}}}var Rjt,nTe=m(()=>{"use strict";Rjt=lI(p$(),1);j7();lTe()});import{readdir as pol,readFile as Zol}from"node:fs/promises";import OZr,{join as Ejt}from"node:path";function Fjt(t){let e=new Set,I=[];for(let l of t)e.has(l.id)||(e.add(l.id),I.push(l));return I}async function Hjt(t,e,I,l,n,r=!1){let a=await wjt(l);if(n===null)return{agents:a.agents,warnings:a.warnings};let s=await wjt(Ejt(n.path,".github","agents")),o=Fjt([...a.agents,...s.agents]),c=[...a.warnings,...s.warnings];if(n.kind!=="git")return{agents:o,warnings:c};if(!n.repo)return{agents:o,warnings:[...c,"could not load remote agents, no github.com remote found"]};if(r)return{agents:o,warnings:c};if(!I)return{agents:o,warnings:[...c,D9(n.repo,"no authentication available")]};let i=await Wol(t,e,I,n.repo);return{agents:Fjt([...o,...i.agents]),warnings:[...c,...i.warnings]}}function D9(t,e){return`could not load remote agents for ${t.owner}/${t.name}: ${e}`}async function Wol(t,e,I,l,n=!1){let r=Ej(I,{onHMACAuthInfo:()=>R2e,onEnvAuthInfo:h=>h.host,onGhCliAuthInfo:h=>h.host,onUserAuthInfo:h=>h.host,onApiKeyAuthInfo:h=>h.host,onTokenAuthInfo:h=>h.host}),{host:a}=new URL(r);if(a!=="github.com")return{agents:[],warnings:[D9(l,"auth info does not target github.com")]};let s=await Yh(I);if(!s)return{agents:[],warnings:[D9(l,"no usable token for accessing repo contents found")]};let o=await Cjt(()=>CC(r,s,t),h=>KR("fetching copilot URL",h));if(o.kind==="error")return{agents:[],warnings:[D9(l,o.message)]};let c=`${o.value}/agents/swe/custom-agents/${l.owner}/${l.name}?exclude_invalid_config=true${n?"":"&include_sources=org,enterprise"}`,i={Authorization:`Bearer ${s}`},d=await Y2(c,{method:"GET",headers:i},t);if(!d.ok)return t.warning(`Failed to load custom agents for ${l.owner}/${l.name}: ${await d.text()}`),{agents:[],warnings:[D9(l,`server returned ${d.status}: ${d.statusText}`)]};let G=await d.json(),u=sl.object({agents:sl.array(Jjt)}).safeParse(G);return u.success?{agents:u.data.agents.map(h=>({id:h.name,displayName:h.display_name,description:h.description,tools:h.tools,prompt:async()=>{let p=await Rol({logger:t,integrationId:e,sweAgentsEndpoint:`${o.value}/agents/swe`,token:s,repoOwner:h.repo_owner,repoName:h.repo_name,customAgentName:h.name});if(!p)throw new Error(`Failed to load prompt for agent ${h.name}`);return p.prompt},mcpServers:h.mcp_servers||{},infer:h.infer})),warnings:[]}:{agents:[],warnings:[D9(l,KR("parsing http response into schema",u.error))]}}async function wjt(t){let e=await pol(t,{withFileTypes:!0}).then(r=>({kind:"success",dirEntries:r})).catch(r=>r.code==="ENOENT"?{kind:"success",dirEntries:[]}:{kind:"error",message:KR(t,r)});if(e.kind==="error")return{agents:[],warnings:[]};let I=new Map;for(let r of e.dirEntries)if(r.isFile()&&r.name.endsWith(".md")){let a=r.name.endsWith(".agent.md"),s=r.name.replace(/(\.agent)?\.md$/,""),o=I.get(s);(!o||a&&!o.isAgentMd)&&I.set(s,{fileName:r.name,isAgentMd:a})}let l=[],n=[];for(let[r,{fileName:a}]of I.entries()){let s=Ejt(t,a),o=await Qjt(s);if(o.kind==="error"){n.push(o.message);continue}l.push({id:r,displayName:o.agent.name||r,description:o.agent.description,tools:o.agent.tools||["*"],prompt:async()=>{let c=await Qjt(s);if(c.kind==="error")throw new Error(c.message);return await c.agent.prompt()},mcpServers:o.agent.mcpServers||{},infer:o.agent.infer})}return{agents:l,warnings:n}}async function Qjt(t){let e=await Cjt(()=>Zol(t,"utf-8"),l=>KR(t,l));if(e.kind==="error")return{kind:"error",message:e.message};let I=Nol(e.value);return I.kind==="error"?{kind:"error",message:`${t}: ${I.message}`}:{kind:"success",agent:I.agent}}function Yol(t){let e=(I,l="")=>{let n=I.path.join(".")||"(root)",r=[];return I.code==="invalid_union"&&"unionErrors"in I?(r.push(`${l}${n}: ${I.message}`),I.unionErrors.forEach((s,o)=>{r.push(`${l} Option ${o+1}:`),s.issues.forEach(c=>{r.push(...e(c,l+" "))})})):r.push(`${l}${n}: ${I.message}`),r};return t.issues.flatMap(I=>e(I)).join(`
|
|
1944
1944
|
`)}async function Cjt(t,e){try{return{kind:"success",value:await t()}}catch(I){return{kind:"error",message:e(I)}}}async function Rol(t){t.logger.info(`Reading custom agent "${t.customAgentName}" from ${t.repoOwner}/${t.repoName}`);try{let e={"Copilot-Integration-Id":t.integrationId,Authorization:`Bearer ${t.token}`,"X-GitHub-Job-Nonce":t.jobNonce??""},I=await Y2(`${t.sweAgentsEndpoint}/custom-agents/${t.repoOwner}/${t.repoName}/${t.customAgentName}`,{method:"GET",headers:e},t.logger,"get custom agent config");if(!I.ok){if(I.status===404)return null;throw new Error(`Failed to get custom agent config: ${I.status} ${I.statusText}`)}let l=await I.json();return Vol.parse(l)}catch(e){let I=e,l=I?.requestId||"unknown";throw t.logger.error(`Failed to get custom agent config (request ID: ${l}): ${I}`),I}}var vjt,Xjt,Nol,gol,yol,fjt,Jjt,Vol,Ljt=m(()=>{"use strict";vjt=lI(p$(),1),Xjt=lI(RC(),1);ac();Ree();KG();G1();BE();oQe();nTe();Nol=t=>{let e=sl.object({name:sl.string().optional(),description:sl.string(),tools:sl.array(sl.string()).optional(),"mcp-servers":fjt,infer:sl.boolean().optional()}),I=/^---\s*\n([\s\S]*?)\n---\s*\n?/,l=t.match(I);if(!l)return{kind:"error",message:"custom agent markdown frontmatter is malformed"};let n=l[1];try{let r=(0,Xjt.parse)(n),a=e.safeParse(r);if(!a.success)return{kind:"error",message:Yol(a.error)};let s=t.slice(l[0].length);return{kind:"success",agent:{name:a.data.name??"",displayName:a.data.name??"",description:a.data.description,tools:a.data.tools||["*"],prompt:()=>Promise.resolve(s),mcpServers:a.data["mcp-servers"]||void 0,infer:a.data.infer??!0}}}catch(r){return{kind:"error",message:KR("failed to parse front matter",r)}}};gol=sl.object({command:sl.string(),args:sl.array(sl.string()),env:sl.record(sl.string(),sl.string()).optional(),tools:sl.array(sl.string()),type:sl.enum(["local","stdio"]).optional()}),yol=sl.object({url:sl.string(),headers:sl.record(sl.string(),sl.string()).optional(),tools:sl.array(sl.string()),type:sl.enum(["http","sse"])}),fjt=sl.record(sl.string(),sl.union([gol,yol])).optional().nullable(),Jjt=sl.object({name:sl.string(),repo_owner:sl.string(),repo_name:sl.string(),display_name:sl.string(),description:sl.string(),tools:sl.array(sl.string()),version:sl.string(),mcp_servers:fjt,infer:sl.boolean()}),Vol=Jjt.extend({prompt:sl.string()})});var rTe,kjt=m(()=>{"use strict";rTe=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))}}});import{appendFile as Aol,access as Fol,mkdir as wol}from"fs/promises";import{constants as Qol}from"fs";import{dirname as Eol}from"path";async function vol(t){try{await Fol(t,Qol.F_OK)}catch{await wol(t,{recursive:!0})}}var aTe,xjt=m(()=>{"use strict";m1();aTe=class extends y2{constructor(I,l,n){super(l,n);this.filePath=I;this.writeQueue=vol(Eol(this.filePath)).catch(()=>{})}writeQueue=Promise.resolve();log(I){this.write("LOG",I)}debug(I){super.shouldLog(4)&&this.write("DEBUG",this.filterSecrets(I).toString())}info(I){super.shouldLog(3)&&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||3)&&this.write("START-GROUP",I)}endGroup(I){super.shouldLog(I||3)&&this.write("END-GROUP","")}write(I,l){let r=`${new Date().toISOString()} [${I}] ${l}
|
|
1945
1945
|
`;this.writeQueue=this.writeQueue.then(()=>this.performWrite(r)).catch(()=>{})}async performWrite(I){await Aol(this.filePath,I)}}});var UZe=m(()=>{"use strict";m1();kjt();xT();xjt();fC()});function Xol(t,e){return!!(t===e||Bjt(t)&&Bjt(e))}function Hol(t,e){if(t.length!==e.length)return!1;for(var I=0;I<t.length;I++)if(!Xol(t[I],e[I]))return!1;return!0}function Sjt(t,e){e===void 0&&(e=Hol);var I=null;function l(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];if(I&&I.lastThis===this&&e(n,I.lastArgs))return I.lastResult;var a=t.apply(this,n);return I={lastResult:a,lastArgs:n,lastThis:this},a}return l.clear=function(){I=null},l}var Bjt,zjt=m(()=>{Bjt=Number.isNaN||function(e){return typeof e=="number"&&e!==e}});import*as MZe from"fs";import*as Ujt from"path";var OZe,Ojt=m(()=>{"use strict";DI();OZe=class t{constructor(e,I){this.logger=e;this.eventsLogDirectory=I;if(this.eventsLogDirectory)try{MZe.mkdirSync(this.eventsLogDirectory,{recursive:!0}),this.loggingEnabled=!0}catch(l){this.logger.error(`Failed to create events log directory: ${Ae(l)}`)}}static MAX_FILE_SIZE=10*1024*1024;currentFileIndex=0;currentFileSize=0;loggingEnabled=!1;async progress(e){await this.writeToEventsLog(JSON.stringify({type:"progress",timestamp:new Date().toISOString(),...e}))}async partialResult(e){await this.writeToEventsLog(JSON.stringify({type:"partialResult",timestamp:new Date().toISOString(),...e}))}async commentReply(e){await this.writeToEventsLog(JSON.stringify({type:"commentReply",timestamp:new Date().toISOString(),...e}))}async result(e){await this.writeToEventsLog(JSON.stringify({type:"result",timestamp:new Date().toISOString(),...e}))}async error(e){await this.writeToEventsLog(JSON.stringify({type:"error",timestamp:new Date().toISOString(),...e}))}async writeToEventsLog(e){if(this.loggingEnabled&&this.eventsLogDirectory)try{let I=e+`
|
|
1946
1946
|
`,l=Buffer.byteLength(I,"utf8");this.currentFileSize+l>=t.MAX_FILE_SIZE&&(this.currentFileIndex++,this.currentFileSize=0);let n=`events.${this.currentFileIndex}.jsonl`,r=Ujt.join(this.eventsLogDirectory,n);await MZe.promises.appendFile(r,I),this.currentFileSize+=l}catch(I){this.logger.error(`Failed to write to events.${this.currentFileIndex}.jsonl: ${Ae(I)}`)}}}});import*as Mjt from"fs";import*as Tjt from"readline";async function jjt(){let t=new Map,e=process.env.COPILOT_AGENT_FIREWALL_LOG_FILE;if(e){let I=null;try{I=Mjt.createReadStream(e,"utf8");let l=Tjt.createInterface({input:I,crlfDelay:1/0});for await(let n of l)if(n.trim())try{let r=JSON.parse(n);if(r.blocked&&r.because!=="IPv6AlwaysBlocked"&&!r.hasBeenRedirected){let{because:a,domains:s,ip:o,originalIp:c,port:i,url:d,ruleSourceComment:G,hasBeenRedirected:b,cmd:u,blockedAt:h}=r,p={because:a,domains:s,ip:o,originalIp:c,port:i,url:d,ruleSourceComment:G,hasBeenRedirected:b,cmd:u,blockedAt:h};(p.cmd==="root process (pid 0)"||/process with pid \d+ no longer exists/.test(p.cmd))&&(p.cmd=""),t.set(JSON.stringify(p),p)}}catch{continue}}finally{I?.close()}}return Array.from(t.values())}var Djt=m(()=>{"use strict"});var TZe,Kjt=m(()=>{"use strict";Qm();gS();Uj();TZe=class{secretFilter=gW.getInstance();formatToolCall(e){let I=`<function_calls>
|
|
@@ -2097,11 +2097,11 @@ Focus particularly on:
|
|
|
2097
2097
|
Include all important tool calls and their results as part of the appropriate sections, with special emphasis on the most recent operations.`});var sNe,Tqt=m(()=>{"use strict";sNe=class{async exec(){return 0}async execReturn(){return{exitCode:0,stdout:"",stderr:""}}}});var Y8t=g((O_,yB)=>{var Qhl=200,I8t="__lodash_hash_undefined__",Ehl=800,vhl=16,l8t=9007199254740991,n8t="[object Arguments]",Xhl="[object Array]",Hhl="[object AsyncFunction]",Chl="[object Boolean]",fhl="[object Date]",Jhl="[object Error]",r8t="[object Function]",Lhl="[object GeneratorFunction]",khl="[object Map]",xhl="[object Number]",Bhl="[object Null]",a8t="[object Object]",Shl="[object Proxy]",zhl="[object RegExp]",Uhl="[object Set]",Ohl="[object String]",Mhl="[object Undefined]",Thl="[object WeakMap]",jhl="[object ArrayBuffer]",Dhl="[object DataView]",Khl="[object Float32Array]",Phl="[object Float64Array]",qhl="[object Int8Array]",_hl="[object Int16Array]",$hl="[object Int32Array]",epl="[object Uint8Array]",tpl="[object Uint8ClampedArray]",Ipl="[object Uint16Array]",lpl="[object Uint32Array]",npl=/[\\^$.*+?()[\]{}|]/g,rpl=/^\[object .+?Constructor\]$/,apl=/^(?:0|[1-9]\d*)$/,Na={};Na[Khl]=Na[Phl]=Na[qhl]=Na[_hl]=Na[$hl]=Na[epl]=Na[tpl]=Na[Ipl]=Na[lpl]=!0;Na[n8t]=Na[Xhl]=Na[jhl]=Na[Chl]=Na[Dhl]=Na[fhl]=Na[Jhl]=Na[r8t]=Na[khl]=Na[xhl]=Na[a8t]=Na[zhl]=Na[Uhl]=Na[Ohl]=Na[Thl]=!1;var s8t=typeof global=="object"&&global&&global.Object===Object&&global,spl=typeof self=="object"&&self&&self.Object===Object&&self,j_=s8t||spl||Function("return this")(),o8t=typeof O_=="object"&&O_&&!O_.nodeType&&O_,M_=o8t&&typeof yB=="object"&&yB&&!yB.nodeType&&yB,c8t=M_&&M_.exports===o8t,DDe=c8t&&s8t.process,jqt=(function(){try{var t=M_&&M_.require&&M_.require("util").types;return t||DDe&&DDe.binding&&DDe.binding("util")}catch{}})(),Dqt=jqt&&jqt.isTypedArray;function opl(t,e,I){switch(I.length){case 0:return t.call(e);case 1:return t.call(e,I[0]);case 2:return t.call(e,I[0],I[1]);case 3:return t.call(e,I[0],I[1],I[2])}return t.apply(e,I)}function cpl(t,e){for(var I=-1,l=Array(t);++I<t;)l[I]=e(I);return l}function ipl(t){return function(e){return t(e)}}function dpl(t,e){return t?.[e]}function Gpl(t,e){return function(I){return t(e(I))}}var bpl=Array.prototype,mpl=Function.prototype,iNe=Object.prototype,KDe=j_["__core-js_shared__"],dNe=mpl.toString,By=iNe.hasOwnProperty,Kqt=(function(){var t=/[^.]+$/.exec(KDe&&KDe.keys&&KDe.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})(),i8t=iNe.toString,upl=dNe.call(Object),hpl=RegExp("^"+dNe.call(By).replace(npl,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),oNe=c8t?j_.Buffer:void 0,Pqt=j_.Symbol,qqt=j_.Uint8Array,_qt=oNe?oNe.allocUnsafe:void 0,d8t=Gpl(Object.getPrototypeOf,Object),$qt=Object.create,ppl=iNe.propertyIsEnumerable,Zpl=bpl.splice,aC=Pqt?Pqt.toStringTag:void 0,cNe=(function(){try{var t=t6e(Object,"defineProperty");return t({},"",{}),t}catch{}})(),Wpl=oNe?oNe.isBuffer:void 0,e8t=Math.max,Npl=Date.now,G8t=t6e(j_,"Map"),T_=t6e(Object,"create"),Ypl=(function(){function t(){}return function(e){if(!oC(e))return{};if($qt)return $qt(e);t.prototype=e;var I=new t;return t.prototype=void 0,I}})();function sC(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function gpl(){this.__data__=T_?T_(null):{},this.size=0}function ypl(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}function Vpl(t){var e=this.__data__;if(T_){var I=e[t];return I===I8t?void 0:I}return By.call(e,t)?e[t]:void 0}function Rpl(t){var e=this.__data__;return T_?e[t]!==void 0:By.call(e,t)}function Apl(t,e){var I=this.__data__;return this.size+=this.has(t)?0:1,I[t]=T_&&e===void 0?I8t:e,this}sC.prototype.clear=gpl;sC.prototype.delete=ypl;sC.prototype.get=Vpl;sC.prototype.has=Rpl;sC.prototype.set=Apl;function Sy(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function Fpl(){this.__data__=[],this.size=0}function wpl(t){var e=this.__data__,I=GNe(e,t);if(I<0)return!1;var l=e.length-1;return I==l?e.pop():Zpl.call(e,I,1),--this.size,!0}function Qpl(t){var e=this.__data__,I=GNe(e,t);return I<0?void 0:e[I][1]}function Epl(t){return GNe(this.__data__,t)>-1}function vpl(t,e){var I=this.__data__,l=GNe(I,t);return l<0?(++this.size,I.push([t,e])):I[l][1]=e,this}Sy.prototype.clear=Fpl;Sy.prototype.delete=wpl;Sy.prototype.get=Qpl;Sy.prototype.has=Epl;Sy.prototype.set=vpl;function VB(t){var e=-1,I=t==null?0:t.length;for(this.clear();++e<I;){var l=t[e];this.set(l[0],l[1])}}function Xpl(){this.size=0,this.__data__={hash:new sC,map:new(G8t||Sy),string:new sC}}function Hpl(t){var e=mNe(this,t).delete(t);return this.size-=e?1:0,e}function Cpl(t){return mNe(this,t).get(t)}function fpl(t){return mNe(this,t).has(t)}function Jpl(t,e){var I=mNe(this,t),l=I.size;return I.set(t,e),this.size+=I.size==l?0:1,this}VB.prototype.clear=Xpl;VB.prototype.delete=Hpl;VB.prototype.get=Cpl;VB.prototype.has=fpl;VB.prototype.set=Jpl;function RB(t){var e=this.__data__=new Sy(t);this.size=e.size}function Lpl(){this.__data__=new Sy,this.size=0}function kpl(t){var e=this.__data__,I=e.delete(t);return this.size=e.size,I}function xpl(t){return this.__data__.get(t)}function Bpl(t){return this.__data__.has(t)}function Spl(t,e){var I=this.__data__;if(I instanceof Sy){var l=I.__data__;if(!G8t||l.length<Qhl-1)return l.push([t,e]),this.size=++I.size,this;I=this.__data__=new VB(l)}return I.set(t,e),this.size=I.size,this}RB.prototype.clear=Lpl;RB.prototype.delete=kpl;RB.prototype.get=xpl;RB.prototype.has=Bpl;RB.prototype.set=Spl;function zpl(t,e){var I=$De(t),l=!I&&_De(t),n=!I&&!l&&h8t(t),r=!I&&!l&&!n&&Z8t(t),a=I||l||n||r,s=a?cpl(t.length,String):[],o=s.length;for(var c in t)(e||By.call(t,c))&&!(a&&(c=="length"||n&&(c=="offset"||c=="parent")||r&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||m8t(c,o)))&&s.push(c);return s}function PDe(t,e,I){(I!==void 0&&!uNe(t[e],I)||I===void 0&&!(e in t))&&e6e(t,e,I)}function Upl(t,e,I){var l=t[e];(!(By.call(t,e)&&uNe(l,I))||I===void 0&&!(e in t))&&e6e(t,e,I)}function GNe(t,e){for(var I=t.length;I--;)if(uNe(t[I][0],e))return I;return-1}function e6e(t,e,I){e=="__proto__"&&cNe?cNe(t,e,{configurable:!0,enumerable:!0,value:I,writable:!0}):t[e]=I}var Opl=lZl();function bNe(t){return t==null?t===void 0?Mhl:Bhl:aC&&aC in Object(t)?nZl(t):iZl(t)}function t8t(t){return D_(t)&&bNe(t)==n8t}function Mpl(t){if(!oC(t)||oZl(t))return!1;var e=l6e(t)?hpl:rpl;return e.test(mZl(t))}function Tpl(t){return D_(t)&&p8t(t.length)&&!!Na[bNe(t)]}function jpl(t){if(!oC(t))return cZl(t);var e=u8t(t),I=[];for(var l in t)l=="constructor"&&(e||!By.call(t,l))||I.push(l);return I}function b8t(t,e,I,l,n){t!==e&&Opl(e,function(r,a){if(n||(n=new RB),oC(r))Dpl(t,e,a,I,b8t,l,n);else{var s=l?l(qDe(t,a),r,a+"",t,e,n):void 0;s===void 0&&(s=r),PDe(t,a,s)}},W8t)}function Dpl(t,e,I,l,n,r,a){var s=qDe(t,I),o=qDe(e,I),c=a.get(o);if(c){PDe(t,I,c);return}var i=r?r(s,o,I+"",t,e,a):void 0,d=i===void 0;if(d){var G=$De(o),b=!G&&h8t(o),u=!G&&!b&&Z8t(o);i=o,G||b||u?$De(s)?i=s:uZl(s)?i=eZl(s):b?(d=!1,i=qpl(o,!0)):u?(d=!1,i=$pl(o,!0)):i=[]:hZl(o)||_De(o)?(i=s,_De(s)?i=pZl(s):(!oC(s)||l6e(s))&&(i=rZl(o))):d=!1}d&&(a.set(o,i),n(i,o,l,r,a),a.delete(o)),PDe(t,I,i)}function Kpl(t,e){return GZl(dZl(t,e,N8t),t+"")}var Ppl=cNe?function(t,e){return cNe(t,"toString",{configurable:!0,enumerable:!1,value:WZl(e),writable:!0})}:N8t;function qpl(t,e){if(e)return t.slice();var I=t.length,l=_qt?_qt(I):new t.constructor(I);return t.copy(l),l}function _pl(t){var e=new t.constructor(t.byteLength);return new qqt(e).set(new qqt(t)),e}function $pl(t,e){var I=e?_pl(t.buffer):t.buffer;return new t.constructor(I,t.byteOffset,t.length)}function eZl(t,e){var I=-1,l=t.length;for(e||(e=Array(l));++I<l;)e[I]=t[I];return e}function tZl(t,e,I,l){var n=!I;I||(I={});for(var r=-1,a=e.length;++r<a;){var s=e[r],o=l?l(I[s],t[s],s,I,t):void 0;o===void 0&&(o=t[s]),n?e6e(I,s,o):Upl(I,s,o)}return I}function IZl(t){return Kpl(function(e,I){var l=-1,n=I.length,r=n>1?I[n-1]:void 0,a=n>2?I[2]:void 0;for(r=t.length>3&&typeof r=="function"?(n--,r):void 0,a&&aZl(I[0],I[1],a)&&(r=n<3?void 0:r,n=1),e=Object(e);++l<n;){var s=I[l];s&&t(e,s,l,r)}return e})}function lZl(t){return function(e,I,l){for(var n=-1,r=Object(e),a=l(e),s=a.length;s--;){var o=a[t?s:++n];if(I(r[o],o,r)===!1)break}return e}}function mNe(t,e){var I=t.__data__;return sZl(e)?I[typeof e=="string"?"string":"hash"]:I.map}function t6e(t,e){var I=dpl(t,e);return Mpl(I)?I:void 0}function nZl(t){var e=By.call(t,aC),I=t[aC];try{t[aC]=void 0;var l=!0}catch{}var n=i8t.call(t);return l&&(e?t[aC]=I:delete t[aC]),n}function rZl(t){return typeof t.constructor=="function"&&!u8t(t)?Ypl(d8t(t)):{}}function m8t(t,e){var I=typeof t;return e=e??l8t,!!e&&(I=="number"||I!="symbol"&&apl.test(t))&&t>-1&&t%1==0&&t<e}function aZl(t,e,I){if(!oC(I))return!1;var l=typeof e;return(l=="number"?I6e(I)&&m8t(e,I.length):l=="string"&&e in I)?uNe(I[e],t):!1}function sZl(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function oZl(t){return!!Kqt&&Kqt in t}function u8t(t){var e=t&&t.constructor,I=typeof e=="function"&&e.prototype||iNe;return t===I}function cZl(t){var e=[];if(t!=null)for(var I in Object(t))e.push(I);return e}function iZl(t){return i8t.call(t)}function dZl(t,e,I){return e=e8t(e===void 0?t.length-1:e,0),function(){for(var l=arguments,n=-1,r=e8t(l.length-e,0),a=Array(r);++n<r;)a[n]=l[e+n];n=-1;for(var s=Array(e+1);++n<e;)s[n]=l[n];return s[e]=I(a),opl(t,this,s)}}function qDe(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}var GZl=bZl(Ppl);function bZl(t){var e=0,I=0;return function(){var l=Npl(),n=vhl-(l-I);if(I=l,n>0){if(++e>=Ehl)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function mZl(t){if(t!=null){try{return dNe.call(t)}catch{}try{return t+""}catch{}}return""}function uNe(t,e){return t===e||t!==t&&e!==e}var _De=t8t((function(){return arguments})())?t8t:function(t){return D_(t)&&By.call(t,"callee")&&!ppl.call(t,"callee")},$De=Array.isArray;function I6e(t){return t!=null&&p8t(t.length)&&!l6e(t)}function uZl(t){return D_(t)&&I6e(t)}var h8t=Wpl||NZl;function l6e(t){if(!oC(t))return!1;var e=bNe(t);return e==r8t||e==Lhl||e==Hhl||e==Shl}function p8t(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=l8t}function oC(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function D_(t){return t!=null&&typeof t=="object"}function hZl(t){if(!D_(t)||bNe(t)!=a8t)return!1;var e=d8t(t);if(e===null)return!0;var I=By.call(e,"constructor")&&e.constructor;return typeof I=="function"&&I instanceof I&&dNe.call(I)==upl}var Z8t=Dqt?ipl(Dqt):Tpl;function pZl(t){return tZl(t,W8t(t))}function W8t(t){return I6e(t)?zpl(t,!0):jpl(t)}var ZZl=IZl(function(t,e,I){b8t(t,e,I)});function WZl(t){return function(){return t}}function N8t(t){return t}function NZl(){return!1}yB.exports=ZZl});async function YZl(t={}){let e=await b8e();return n8e((0,g8t.default)({},e,t))}async function n6e(t={}){if(wee())throw new Error("Settings have already been initialized");return YZl(t)}var g8t,y8t=m(()=>{"use strict";g8t=lI(Y8t(),1);Qee();YS()});import{readdir as gZl,stat as yZl}from"fs/promises";async function VZl(t,e){try{let I=await yZl(t);if(I.isDirectory()){let l=await gZl(t);return{path:t,type:"directory",lines:l.length}}else{let l=I.size/1048576;if(I.size>V8t){let r=(V8t/1048576).toFixed(0);return e.debug(`File ${t} is too large (${l.toFixed(1)}MB). Maximum file size is ${r}MB. Skipping line count.`),{path:t,type:"file",sizeMB:l}}let{totalLineCount:n}=await xle(t,1,void 0);return{path:t,type:"file",lines:n}}}catch(I){return e.debug(`Error getting file info for ${t}: ${Ae(I)}`),{path:t,type:"file",error:Ae(I)}}}async function R8t(t,e){let I=t.filter(r=>!AZ(r.path));if(I.length===0)return"";let l=await Promise.all(I.map(r=>VZl(r.path,e))),n=["<tagged_files>"];for(let r of l)r.error?n.push(`* ${r.path} (error: ${r.error})`):r.sizeMB!==void 0?n.push(`* ${r.path} (large file: ${r.sizeMB.toFixed(1)}MB)`):r.type==="directory"?n.push(`* ${r.path} (${r.lines} entries)`):n.push(`* ${r.path} (${r.lines} lines)`);return n.push("</tagged_files>"),n.join(`
|
|
2098
2098
|
`)}async function A8t(t,e){let I=t.filter(n=>n.type==="file"&&AZ(n.path));return(await Promise.all(I.map(async n=>{try{let r=await Poe(n.path,e);return r?[{type:"text",text:`Image file at path ${n.path}`},{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.base64Data}`}}]:void 0}catch(r){e.error(`Failed to process image ${n.path}: ${r instanceof Error?r.message:String(r)}`);return}}))).filter(n=>n!==void 0).flat()}var V8t,F8t=m(()=>{"use strict";DI();rZ();hD();V8t=10*1024*1024});async function Cw(t,e,I){if(!t||t.length===0)return;let l=!1,n={};for(let r of t)try{let a=await r(e);a&&(l=!0,n={...n,...a})}catch(a){I.error(`Hook execution failed: ${Ae(a)}`)}return l?n:void 0}var r6e=m(()=>{"use strict";DI()});function w8t(t){return t.filter(e=>H3(e.id)&&NZ(e.id,t)).sort((e,I)=>l2.indexOf(e.id)-l2.indexOf(I.id))}async function Q8t(t,e,I,l,n){if(T9())return[];if(l??=Eo(),I??=K_,n??=new _c,t.type==="hmac"){if(mp&&t.type===mp.authInfo.type&&t.hmac===mp.authInfo.hmac)return mp.models;let G=await GH.createWithHmac(n,e,I,t.hmac,l).listModels();return mp={models:w8t(G),authInfo:t},mp.models}let r=await Yh(t);if(!r)throw new Error("Failed to get token for auth info");if(mp&&mp.authInfo.type!=="hmac"&&r===await Yh(mp.authInfo))return mp.models;let s=await CC(t.host,r,n),c=await GH.createWithOAuthToken(n,s,I,r,l).listModels();return mp={models:w8t(c),authInfo:t},mp.models}var mp,a6e=m(()=>{"use strict";cV();G1();BE();C3();o8();UZe();AB();mp=null});function AZl(t){return l2.filter(e=>NZ(e,t)).map(e=>{let I=t.find(a=>a.id===e),l=I?.name??e,n=I?.billing?.multiplier??1,r=n<=.5?"fast/cheap":n>=2?"premium":"standard";return{id:e,label:l,description:r}})}function FZl(t,e){if(t.length===0)return t;let I=[],l=new Set,n=!1;for(let s=t.length-1;s>=0;s--){let o=t[s];if(o.role==="assistant"&&(n=!0),o.role==="assistant"&&"tool_calls"in o&&o.tool_calls&&o.tool_calls.length>0)for(let c of o.tool_calls)l.has(c.id)||I.push(c.id);else{if(n)break;o.role==="tool"&&o.tool_call_id&&l.add(o.tool_call_id)}}if(I.length===0)return t;let r="The execution of this tool, or a previous tool was interrupted.";e.info(`Completing ${I.length} orphaned tool calls.`);let a=I.map(s=>({role:"tool",tool_call_id:s,content:r}));return[...t,...a]}var RZl,K_,E8t,s6e,hNe,zy,pNe,AB=m(()=>{"use strict";zjt();cV();m8();i8();b8();G8();yS();Ojt();qjt();j7();G1();BE();vse();_jt();$jt();tDt();kqt();C3();$Se();Sqt();zqt();BQ();DI();ZS();hD();Vq();s8();TDe();Koe();aCe();Qm();HL();bH();Mqt();Tqt();V2();fC();Qee();KG();y8t();v2e();Uo();Tce();sTe();o6e();F8t();r6e();a6e();RZl="copilot-developer-cli",K_=process.env.GITHUB_COPILOT_INTEGRATION_ID||RZl,E8t=Sjt(CC);s6e=class{constructor(e,I){this.logger=e;this.session=I}messageQueue=[];async*preRequest(e){this.logger.debug("ImmediatePromptProcessor: Injecting immediate prompts");let l=(await this.session.getChatMessages()).length;for(;this.messageQueue.length>0;){let a=this.messageQueue.shift();this.session.emit("user.message",{content:a.prompt,attachments:a.attachments})}let r=(await this.session.getChatMessages()).slice(l);for(let a of r)e.messages.push(a),yield{kind:"message",message:a,turn:e.turn,source:"immediate-prompt"}}addMessage(e){this.messageQueue.push(e)}toJSON(){return"ImmediatePromptProcessor"}},hNe=class{sessionId;startTime;modifiedTime;summary;logger;events=[];_chatMessages=[];_selectedModel;eventProcessingQueue=Promise.resolve();eventHandlers={};wildcardEventHandlers=[];integrationId;availableTools;excludedTools;executeToolsInParallel;shellConfig;requestPermission;mcpServers;mcpHost;hooks;customAgents;selectedCustomAgent;organizationCustomInstructions;skipCustomInstructions;systemMessageConfig;workingDir;featureFlags;skillDirectories;disabledSkills;trajectoryFile;eventsLogDirectory;authInfo;copilotUrl;provider;onToolsUpdate;enableStreaming=!1;handoffContext;externalToolDefinitions;externalToolDispatcher;clientName;async initializeAndValidateTools(){}constructor(e={}){this.logger=e.logger||new _c,this.sessionId=e.sessionId||Eo(),this.startTime=e.startTime||new Date,this.modifiedTime=e.modifiedTime||this.startTime,this.summary=e.summary,this.integrationId=e.integrationId||K_,this.skipCustomInstructions=e.skipCustomInstructions??!1,this.workingDir=e.workingDirectory||process.cwd(),this.updateOptions(e)}static async fromEvents(e,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({...I,sessionId:l.data.sessionId,startTime:new Date(l.data.startTime)});n._selectedModel=l.data.selectedModel,n.events.push(l);for(let r=1;r<e.length;r++){let a=e[r];n.events.push(a),await n.processEventForState(a)}return n}setAuthInfo(e){this.updateOptions({authInfo:e})}updateOptions(e){e.clientName!==void 0&&(this.clientName=e.clientName),e.model!==void 0&&(this._selectedModel=e.model),e.integrationId!==void 0&&(this.integrationId=e.integrationId),e.availableTools!==void 0&&(this.availableTools=e.availableTools),e.excludedTools!==void 0&&(this.excludedTools=e.excludedTools),e.executeToolsInParallel!==void 0&&(this.executeToolsInParallel=e.executeToolsInParallel),e.shellConfig!==void 0&&(this.shellConfig=e.shellConfig),e.requestPermission!==void 0&&(this.requestPermission=e.requestPermission),e.featureFlags!==void 0&&(this.featureFlags=e.featureFlags),e.skillDirectories!==void 0&&(this.skillDirectories=e.skillDirectories),e.disabledSkills!==void 0&&(this.disabledSkills=e.disabledSkills),e.mcpServers!==void 0&&(this.mcpServers=e.mcpServers),e.mcpHost!==void 0&&(this.mcpHost=e.mcpHost),e.customAgents!==void 0?this.customAgents=e.customAgents:this.loadCustomAgents().catch(I=>this.logger.error(`Failed to load custom agents: ${Ae(I)}`)),e.selectedCustomAgent!==void 0&&(this.selectedCustomAgent=e.selectedCustomAgent),e.organizationCustomInstructions!==void 0&&(this.organizationCustomInstructions=e.organizationCustomInstructions),e.skipCustomInstructions!==void 0&&(this.skipCustomInstructions=e.skipCustomInstructions),e.systemMessage!==void 0&&(this.systemMessageConfig=e.systemMessage),e.hooks!==void 0&&(this.hooks=e.hooks),e.externalToolDefinitions!==void 0&&(this.externalToolDefinitions=e.externalToolDefinitions),e.externalToolDispatcher!==void 0&&(this.externalToolDispatcher=e.externalToolDispatcher),e.logger!==void 0&&(this.logger=e.logger),e.trajectoryFile!==void 0&&(this.trajectoryFile=e.trajectoryFile),e.eventsLogDirectory!==void 0&&(this.eventsLogDirectory=e.eventsLogDirectory),e.workingDirectory!==void 0&&(this.workingDir=e.workingDirectory),e.authInfo!==void 0&&(this.authInfo=e.authInfo),e.copilotUrl!==void 0&&(this.copilotUrl=e.copilotUrl),e.provider!==void 0&&(this.provider=e.provider),e.enableStreaming!==void 0&&(this.enableStreaming=e.enableStreaming)}setOnToolsUpdate(e){this.onToolsUpdate=e}getAvailableCustomAgents(){return this.customAgents||[]}async selectCustomAgent(e){let I=this.customAgents?.find(l=>l.name===e);if(!I)throw new Error(`Custom agent '${e}' not found`);this.selectedCustomAgent=I,this.emit("custom_agent.selected",{agentName:I.name,agentDisplayName:I.displayName,tools:I.tools})}clearCustomAgent(){this.selectedCustomAgent=void 0}on(e,I){return e==="*"?(this.wildcardEventHandlers.push(I),()=>{let l=this.wildcardEventHandlers.indexOf(I);l!==-1&&this.wildcardEventHandlers.splice(l,1)}):(this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(I),()=>{let l=this.eventHandlers[e];if(l){let n=l.indexOf(I);n!==-1&&l.splice(n,1)}})}emitInternal(e,I,l=!1){let n=Eo(),r=new Date().toISOString(),a=this.getLastEventId(),s={type:e,data:I,id:n,timestamp:r,parentId:a,...l&&{ephemeral:l}};this.events.push(s),this.enqueueEventProcessing(()=>this.processEventForState(s)).catch(o=>{this.logger.error(`Error emitting event: ${o instanceof Error?o.message:String(o)}`)}).catch(o=>{this.logger.error(`Error emitting event ${o instanceof Error?o.message:String(o)}`)}),[...this.eventHandlers[s.type]||[],...this.wildcardEventHandlers].forEach(o=>{try{o(s)}catch(c){this.logger.error(`Error in event handler for event type ${s.type}: ${c instanceof Error?c.message:String(c)}`)}})}emit(e,I){this.emitInternal(e,I)}emitEphemeral(e,I){this.emitInternal(e,I,!0)}getEvents(){return this.events}async getChatMessages(){return this.enqueueEventProcessing(()=>this._chatMessages)}async getChatContextMessages(){return(await this.getChatMessages()).filter(I=>I.role!=="system")}async getSystemContextMessages(){return(await this.getChatMessages()).filter(I=>I.role==="system")}async getSelectedModel(){return this.enqueueEventProcessing(()=>this._selectedModel)}async setSelectedModel(e){let I=await this.getSelectedModel();this.emit("session.model_change",{previousModel:I,newModel:e})}getLastEventId(){return this.events.length===0?null:this.events[this.events.length-1].id}enqueueEventProcessing(e){let I=this.eventProcessingQueue.then(()=>e());return this.eventProcessingQueue=I,I}async 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":{let I=e.data.transformedContent??e.data.content,l=[];if(e.data.attachments&&e.data.attachments.length>0){let n=await A8t(e.data.attachments,this.logger);if(l.push(...n),e.data.attachments&&e.data.attachments.length>0){let r=await R8t(e.data.attachments,this.logger);r&&(I=`${I}
|
|
2099
2099
|
|
|
2100
|
-
${r}`)}}l.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:I},...l]}):this._chatMessages.push({role:"user",content:I});break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;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=>l.toolCallId.startsWith("custom_")?{id:l.toolCallId,type:"custom",custom:{name:l.name,input:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}:{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":{if(e.data.parentToolCallId)break;e.data.isUserRequested||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.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=FZl(this._chatMessages,this.logger);break;case"session.handoff":e.data.context&&(this.handoffContext=e.data.context);break;case"assistant.intent":case"session.idle":case"session.error":case"session.info":case"session.truncation":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"custom_agent.started":case"custom_agent.completed":case"custom_agent.failed":case"custom_agent.selected":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}async loadCustomAgents(){if(this.provider){this.logger.debug("Using custom provider, skipping custom agents load");return}if(!this.authInfo){this.logger.debug("No auth info available, skipping custom agents load");return}this.customAgents=await v8t(this.authInfo,this.workingDir,this.integrationId,this.logger)}},zy=class extends hNe{callback=new Hee;isProcessing=!1;messageQueue=[];immediatePromptProcessor;abortController;activeCustomAgents=new Map;mcpHostCache;modelListCache=void 0;warnedUnknownTools=new Set;constructor(e={}){super(e),this.immediatePromptProcessor=new s6e(this.logger,this),this.mcpHostCache=new aNe(this.logger),this.on("session.model_change",()=>{this.warnedUnknownTools.clear(),this.initializeAndValidateTools()})}updateOptions(e){if(super.updateOptions(e),e.trajectoryFile!==void 0){let I=new jZe(this.logger,e.trajectoryFile);this.callback.addCallback(I)}if(e.eventsLogDirectory!==void 0){let I=new OZe(this.logger,e.eventsLogDirectory);this.callback.addCallback(I)}}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!1}}async send(e){if(e.mode==="immediate"&&this.isProcessing)this.immediatePromptProcessor.addMessage(e);else{if(this.messageQueue.push(e),this.isProcessing)return;for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let I=this.messageQueue.shift();this.abortController=I.abortController||new AbortController,await this.runAgenticLoop(I.prompt,I.attachments)}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new gB(this.logger,{mcpServers:this.mcpServers},this.excludedTools),await this.mcpHost.startServers()}catch(e){this.logger.error(`Failed to initialize MCP host: ${Ae(e)}`)}}async initializeAndValidateTools(){if(!(!this.availableTools?.length&&!this.excludedTools?.length))try{let e=await this.buildSettingsAndTools();if(e){let I=new Set([...e.builtInTools.map(l=>l.name),...e.mcpTools.map(l=>l.name),...this.externalToolDefinitions?.map(l=>l.name)||[]]);this.validateToolFilters(I)}}catch(e){this.logger.debug(`Failed to initialize tools for validation: ${Ae(e)}`)}}async buildSettingsAndTools(e){if(!this.authInfo&&!this.provider)return;await this.initializeMcpHost();let I,l;if(!this.provider){if(!this.authInfo)return;I=await Yh(this.authInfo),l=this.copilotUrl,!l&&I&&this.authInfo.type!=="hmac"&&(l=await E8t(this.authInfo.host,I||"",this.logger))}let n=!!this.provider,r=n?[]:await this.getModelList(),a=await $Me(this._selectedModel,this,r,this.logger,n);if(!a)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let s=n?`capi:${a}`:await _Me(a),c=new b1().setProblemStatement(e??"").setAgentModel(s).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(l).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(I).setCopilotToken(I).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).setFeatureFlags(this.featureFlags).setClientName(this.clientName).build();w2e();let i=await n6e(c),d=i.service?.agent?.model,G=my(d),b=mH(G.agent,G.model),u=AZl(r),h={location:this.workingDir,timeout:3e4,availableModels:u,toolPartialResultCallback:(Y,y)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:Y,partialOutput:y})},createSubAgentCallback:Y=>({progress:async y=>{if(await this.invokeCallbacks(y),K9(y))switch(y.kind){case"message":if(Xh(y)){let w=XL(y)?y.message.tool_calls.map(C=>({toolCallId:C.id,name:nZ(C),arguments:vle(C,ny)})):[];this.emit("assistant.message",{parentToolCallId:Y,messageId:Eo(),content:typeof y.message.content=="string"?y.message.content:"",toolRequests:w});for(let C of w)this.emit("tool.execution_start",{parentToolCallId:Y,toolCallId:C.toolCallId,toolName:C.name,arguments:C.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:Y,toolCallId:y.toolCallId,success:y.toolResult.resultType==="success",result:y.toolResult.resultType==="success"?{content:y.toolResult.textResultForLlm||y.toolResult.sessionLog||""}:void 0,error:y.toolResult.resultType!=="success"?{message:(y.toolResult.resultType==="failure"?y.toolResult.error:void 0)||y.toolResult.textResultForLlm||y.toolResult.sessionLog||"Tool execution failed",code:y.toolResult.resultType}:void 0});break;default:break}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}}),permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:this.shellConfig??(process.platform==="win32"?Gg.powerShell:Gg.bash).withScriptSafetyAssessor(async function(Y){return{result:"completed",commands:[{identifier:Y,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}}),skillDirectories:this.skillDirectories,disabledSkills:this.disabledSkills,...b.toolConfigOverrides},p=[];if(this.mcpHost)try{p=await this.mcpHost.getTools(i,this.logger,h.permissions)}catch(Y){this.logger.error(`Failed to get MCP tools: ${Ae(Y)}`)}kfe(b.supports,p);let N=await(b.cli?.toolInit??br.cli.toolInit)(h,i,this.logger,new sNe,this.callback,void 0);return{settings:i,builtInTools:N,mcpTools:p,config:b,toolConfig:h}}isToolEnabled(e){return this.availableTools?this.availableTools.includes(e):this.excludedTools?!this.excludedTools.includes(e):!0}validateToolFilters(e){let I=Array.from(e).filter(l=>!this.isToolEnabled(l));if(I.length>0&&!this.warnedUnknownTools.has("__disabled_tools_info__")){this.warnedUnknownTools.add("__disabled_tools_info__");let l=I.sort();this.emitEphemeral("session.info",{infoType:"configuration",message:`Disabled tools: ${l.join(", ")}`})}if(this.availableTools)for(let l of this.availableTools)!e.has(l)&&!this.warnedUnknownTools.has(l)&&(this.warnedUnknownTools.add(l),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool allowlist: "${l}"`}));if(this.excludedTools)for(let l of this.excludedTools)!e.has(l)&&!this.warnedUnknownTools.has(l)&&(this.warnedUnknownTools.add(l),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool denylist: "${l}"`}))}async buildCustomAgentTools(e,I,l,n,r,a,s){let o=async d=>await h8({location:r,version:a8(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:{...a,customAgents:!1},tools:d,organizationCustomInstructions:this.organizationCustomInstructions,toolConfigOverrides:s}),i=(this.selectedCustomAgent?[this.selectedCustomAgent]:e).filter(d=>d.infer!==!1);return await Promise.all(i.map(async d=>{let G;if(d.mcpServers&&Object.keys(d.mcpServers).length>0){let b=await this.mcpHostCache.getOrCreateHost(d.name,d.mcpServers);b&&(G=new kZe(b,I,s.permissions))}return qTt(o,Bqt,d,this.workingDir,n,l,G)}))}filterToolsForSelectedAgent(e){return this.selectedCustomAgent?PMe(e,this.selectedCustomAgent,"top-level"):e}async invokeCallbacks(e){if(K9(e))try{await this.callback.progress(e)}catch(I){this.logger.error(`Error in callback: ${Ae(I)}`)}}async getModelList(){if(this.provider)return[];if(!this.authInfo)return Promise.reject(new Error("Session was not created with authentication info or custom provider"));try{return await Q8t(this.authInfo,this.copilotUrl||A2e(),this.integrationId,this.sessionId,this.logger)}catch(e){throw new Error("Failed to list available models",{cause:e})}}async getClient(){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");let e,I;if(!this.provider){if(!this.authInfo)throw new Error("Session was not created with authentication info");e=await Yh(this.authInfo),I=this.copilotUrl,!I&&e&&this.authInfo.type!=="hmac"&&(I=await E8t(this.authInfo.host,e||"",this.logger))}let l=!!this.provider,n=l?[]:await this.getModelList(),r=await $Me(this._selectedModel,this,n,this.logger,l);if(!r)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let a=l?`capi:${r}`:await _Me(r),o=new b1().setProblemStatement("").setAgentModel(a).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(I).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(e).setCopilotToken(e).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).build();w2e();let c=await n6e(o),i=c.service?.agent?.model,d=my(i),G=mH(d.agent,d.model);return{client:Iw(c,this.logger,d.agent,{...G.clientOptions,model:d.model},this.provider),settings:c}}async getContextSummary(){let e=await this.getChatMessages();if(e.length===0)return"";let{client:I}=await this.getClient(),l=Uqt(),n=2e4,r={role:"user",content:Oqt()},a=new ev(r,this.logger);try{let s="";for await(let o of I.getCompletionWithTools(l,[...e,r],[],{failIfInitialInputsTooLong:!1,processors:{preRequest:[a],onRequestError:[a]}}))o.kind==="message"&&o.message.role==="assistant"&&(s=typeof o.message.content=="string"?o.message.content:"");return s.length>n?s.slice(0,n):s}catch(s){return this.logger.error(`Failed to summarize context: ${Ae(s)}`),""}}async runAgenticLoop(e,I=[]){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");let l=new Map,n=new Map,r=[];try{let s=(await Cw(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e,o=await this.buildSettingsAndTools(s);if(!o)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let{settings:c,builtInTools:i,mcpTools:d,config:G,toolConfig:b}=o,u=c.service?.agent?.model,h=my(u),p=Iw(c,this.logger,h.agent,{...G.clientOptions,model:h.model},this.provider),W=[];if(this.externalToolDefinitions?.length){let _=this.externalToolDispatcher;if(!_)this.logger.warning("External tool definitions provided without a dispatcher; ignoring");else for(let Ie of this.externalToolDefinitions)W.push({name:Ie.name,description:Ie.description,input_schema:Ie.parameters??{type:"object",properties:{}},callback:async(Ce,at)=>{if(!at?.toolCallId)throw new Error("External tool invocation missing toolCallId");return await _({sessionId:this.sessionId,toolCallId:at.toolCallId,toolName:Ie.name,arguments:Ce,abortSignal:at.abortSignal})}})}let N=new Set([...i,...d,...W].map(_=>_.name));this.validateToolFilters(N);let Y=[...i,...d,...W].filter(_=>this.isToolEnabled(_.name)),y=await j9(this.workingDir),w={...G.supports,reasoning:!0},C,E={progress:async _=>{if(_.kind==="message"&&_.turn===0){if(!_.callId)throw new Error("message on turn 0 event missing callId");C=_.callId}if(await this.invokeCallbacks(_),_.kind==="custom_agent_session_boundary"){let Ie=_.agentId;if(Ie)if(_.sessionBoundaryType==="start"){let Ce=this.customAgents?.find(at=>at.name===_.agentName);Ce&&(this.activeCustomAgents.set(Ie,{name:_.agentName,displayName:Ce.displayName}),this.emit("custom_agent.started",{toolCallId:Ie,agentName:_.agentName,agentDisplayName:Ce.displayName,agentDescription:Ce.description}))}else{let Ce=this.activeCustomAgents.get(Ie);Ce&&this.emit("custom_agent.completed",{toolCallId:Ie,agentName:Ce.name}),this.activeCustomAgents.delete(Ie)}return}if(K9(_)){if(!C)throw new Error("Custom agent event received without parentToolCallId");switch(_.kind){case"message":if(Xh(_)){let Ie=We.endCurrentStreamingMessage(),Ce=XL(_)?_.message.tool_calls.map(at=>({toolCallId:at.id,name:nZ(at),arguments:vle(at,ny)})):[];this.emit("assistant.message",{parentToolCallId:C,messageId:Ie??Eo(),content:typeof _.message.content=="string"?_.message.content:"",toolRequests:Ce});for(let at of Ce)this.emit("tool.execution_start",{parentToolCallId:C,toolCallId:at.toolCallId,toolName:at.name,arguments:at.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:C,toolCallId:_.toolCallId,success:_.toolResult.resultType==="success",result:_.toolResult.resultType==="success"?{content:_.toolResult.textResultForLlm||_.toolResult.sessionLog||""}:void 0,error:_.toolResult.resultType!=="success"?{message:(_.toolResult.resultType==="failure"?_.toolResult.error:void 0)||_.toolResult.textResultForLlm||_.toolResult.sessionLog||"Tool execution failed",code:_.toolResult.resultType}:void 0,toolTelemetry:_.toolResult.toolTelemetry});break;case"model_call_failure":case"model_call_success":case"image_processing":case"images_removed":case"response":case"history_truncated":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":break;default:eh(_,`Unknown event kind: ${JSON.stringify(_)}`)}}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}},X={client:p,settings:c,logger:this.logger,exec:new Hd(this.logger),customAgents:this.customAgents||[],organizationCustomInstructions:this.organizationCustomInstructions,callback:E},f=Y;if(this.customAgents&&this.customAgents.length>0){let _=await this.buildCustomAgentTools(this.customAgents,c,Y,X,y.found?y.gitRoot:"",w,b);f=[...Y,..._]}r=this.filterToolsForSelectedAgent(f),this.onToolsUpdate&&this.onToolsUpdate(r);let x=await h8({location:y.found?y.gitRoot:"",version:a8(),currentWorkingDirectory:this.workingDir,parts:G.cli?.systemMessage||{},capabilities:w,tools:r,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:b}),H=I?.some(_=>_.type==="file"&&AZ(_.path))??!1,ne=await this.selectedCustomAgent?.prompt(),Qe=xqt({customAgentPrompt:ne,problemStatement:s,capabilities:w,hasImages:H,handoffContext:this.handoffContext});this.emit("user.message",{content:s,transformedContent:Qe,attachments:I});let J=await this.getChatMessages(),te=J.findLastIndex(_=>_.role==="user"),Je=J[te];this.handoffContext=void 0;let ve=J.map((_,Ie)=>Ie===te?Je:_);await Cw(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let We=new DZe(this,()=>{},!1,this.logger),Me=new KZe(_=>{this.emitEphemeral("assistant.intent",{intent:_})}),Wt=new ev(Je,this.logger),Le=HYt(this.logger,c,f.find(_=>_.name==="github-mcp-server-get_file_contents")),CI=p.getCompletionWithTools(x,ve,r,{failIfInitialInputsTooLong:!1,processors:{preRequest:[Wt,Le,this.immediatePromptProcessor,new d8(this.logger)],postToolExecution:[Le],onRequestError:[Le,Wt],onStreamingChunk:[We,Me]},executeToolsInParallel:this.executeToolsInParallel??!0,abortSignal:this.abortController?.signal,stream:this.enableStreaming});for await(let _ of CI){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"}),this.emitEphemeral("session.info",{infoType:"cancellation",message:"Operation cancelled by user"});break}switch(await this.invokeCallbacks(_),_.kind){case"message":{if(Xh(_)){let Ce=We.endCurrentStreamingMessage()??Eo(),at=XL(_)?await Promise.all(_.message.tool_calls.map(async fI=>{let Et=nZ(fI),Ds=vle(fI,ny);l.set(fI.id,Et),n.set(fI.id,Ds);let Ks=await Cw(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Et,toolArgs:Ds},this.logger);return{toolCallId:fI.id,name:Et,arguments:Ks?.modifiedArgs??Ds}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:Ce,content:typeof _.message.content=="string"?_.message.content:"",toolRequests:at});for(let fI of at)this.emit("tool.execution_start",{toolCallId:fI.toolCallId,toolName:fI.name,arguments:fI.arguments})}else(_.message.role==="system"||_.message.role==="developer")&&this.emit("system.message",{role:_.message.role,content:typeof _.message.content=="string"?_.message.content:JSON.stringify(_.message.content),name:"name"in _.message?_.message.name:void 0});break}case"model_call_failure":{let Ie=new Error(_.modelCall?.error||"Model call failed");if(await Cw(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:Ie,errorContext:"model_call",recoverable:!0},this.logger),jDe(_.modelCall?.error||""))return;let at=_.modelCall?.error||"Unknown error occurred";_.modelCall.request_id&&(at+=` (Request ID: ${_.modelCall.request_id})`),this.emit("session.error",{errorType:"model_call",message:`Model call failed: ${at}`,stack:Ie.stack});break}case"tool_execution":{let Ce=(await Cw(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(_.toolCallId)||"unknown",toolArgs:n.get(_.toolCallId)||{},toolResult:_.toolResult},this.logger))?.modifiedResult??_.toolResult,at=(Ce.resultType==="failure"?Ce.error:void 0)||Ce.textResultForLlm||Ce.sessionLog||"";this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:_.toolCallId,success:Ce.resultType==="success",result:Ce.resultType==="success"?{content:at}:void 0,error:Ce.resultType!=="success"?{message:at,code:Ce.resultType}:void 0,toolTelemetry:Ce.toolTelemetry});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${_.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${_.turn}`});break}case"model_call_success":{let Ie=_.modelCall.model||await this.getSelectedModel(),Ce=_.modelCallDurationMs||0,at=_.responseUsage,fI=await this.getModelList(),Et=Ie?qMe(Ie,fI):1;this.emitEphemeral("assistant.usage",{model:Ie||"unknown",inputTokens:at?.prompt_tokens||0,outputTokens:at?.completion_tokens||0,cacheReadTokens:at?.prompt_tokens_details?.cached_tokens||0,cacheWriteTokens:0,cost:Et,duration:Ce,initiator:_.modelCall?.initiator,apiCallId:_.modelCall?.api_id,providerCallId:_.modelCall?.request_id,quotaSnapshots:_.quotaSnapshots});break}case"history_truncated":{this.emit("session.truncation",{..._.truncateResult,performedBy:_.performedBy});break}case"response":case"images_removed":case"image_processing":case"turn_failed":case"turn_retry":this.logger.debug(`Ignoring event of kind: ${_.kind}`);break;default:eh(_,"Unhandled event type")}}}catch(a){if(await Cw(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:a instanceof Error?a:new Error(String(a))},this.logger),a&&typeof a=="object"&&"status"in a&&(a.status===401||a.status===403)){if("message"in a&&typeof a.message=="string"){let c=jDe(a.message);c&&this.emit("session.error",{errorType:"authentication",message:c.message})}this.emit("session.error",{errorType:"authorization",message:"Authorization error, you may need to run /login"})}a&&typeof a=="object"&&"status"in a&&a.status===402&&this.emit("session.error",{errorType:"quota",message:"Quota exceeded. Upgrade to increase your limit: https://github.com/features/copilot/plans"});let o=`Execution failed: ${a instanceof Error?a.message:a&&typeof a=="object"&&"toString"in a?Ae(a):"Unknown error occurred"}`;this.emit("session.error",{errorType:"query",message:o,stack:a instanceof Error?a.stack:void 0})}finally{await Cw(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger);try{for(let a of r)a.shutdown&&await a.shutdown()}catch(a){this.logger.error(`Error during session shutdown: ${Ae(a)}`)}}}},pNe=class extends hNe{repository;remoteSessionIds;pullRequestNumber;constructor(e){super(e),this.repository=e.repository,this.remoteSessionIds=e.remoteSessionIds,this.pullRequestNumber=e.pullRequestNumber}async send(e){let{prompt:I}=e;if(!this.pullRequestNumber)throw new Error("Cannot send message: Pull request number is not available");if(!this.authInfo)throw new Error("Cannot send message: Authentication info is not available");let{owner:l,name:n}=this.repository,r=this.pullRequestNumber,a=`@copilot ${I}`;this.logger.debug(`Posting user message to PR ${l}/${n}#${r}`);let s=ppt(this.authInfo),o=new URL(`/repos/${l}/${n}/issues/${r}/comments`,oV(s)),c=await eDt(o,this.authInfo,this.logger,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:a})});if(!c.ok){let i=await c.text();throw new Error(`Failed to post comment to PR ${l}/${n}#${r}: ${c.status} ${c.statusText}
|
|
2100
|
+
${r}`)}}l.length>0?this._chatMessages.push({role:"user",content:[{type:"text",text:I},...l]}):this._chatMessages.push({role:"user",content:I});break}case"assistant.message":{if(e.ephemeral||e.data.parentToolCallId)break;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=>l.toolCallId.startsWith("custom_")?{id:l.toolCallId,type:"custom",custom:{name:l.name,input:typeof l.arguments=="string"?l.arguments:JSON.stringify(l.arguments)}}:{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":{if(e.data.parentToolCallId)break;e.data.isUserRequested||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.import_legacy":this._chatMessages=[...e.data.legacySession.chatMessages],e.data.legacySession.selectedModel&&(this._selectedModel=e.data.legacySession.selectedModel);break;case"abort":case"session.resume":this._chatMessages=FZl(this._chatMessages,this.logger);break;case"session.handoff":e.data.context&&(this.handoffContext=e.data.context);break;case"assistant.intent":case"session.idle":case"session.error":case"session.info":case"session.truncation":case"assistant.turn_start":case"assistant.turn_end":case"assistant.usage":case"tool.user_requested":case"tool.execution_start":case"tool.execution_partial_result":case"custom_agent.started":case"custom_agent.completed":case"custom_agent.failed":case"custom_agent.selected":case"hook.start":case"hook.end":break;default:{let I=e;this.logger.error(`Unknown event type: ${I.type}`);break}}}async loadCustomAgents(){if(this.provider){this.logger.debug("Using custom provider, skipping custom agents load");return}if(!this.authInfo){this.logger.debug("No auth info available, skipping custom agents load");return}this.customAgents=await v8t(this.authInfo,this.workingDir,this.integrationId,this.logger)}},zy=class extends hNe{callback=new Hee;isProcessing=!1;messageQueue=[];immediatePromptProcessor;abortController;activeCustomAgents=new Map;mcpHostCache;modelListCache=void 0;warnedUnknownTools=new Set;constructor(e={}){super(e),this.immediatePromptProcessor=new s6e(this.logger,this),this.mcpHostCache=new aNe(this.logger),this.on("session.model_change",()=>{this.warnedUnknownTools.clear(),this.initializeAndValidateTools()})}updateOptions(e){if(super.updateOptions(e),e.trajectoryFile!==void 0){let I=new jZe(this.logger,e.trajectoryFile);this.callback.addCallback(I)}if(e.eventsLogDirectory!==void 0){let I=new OZe(this.logger,e.eventsLogDirectory);this.callback.addCallback(I)}}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!1}}async send(e){if(e.mode==="immediate"&&this.isProcessing)this.immediatePromptProcessor.addMessage(e);else{if(this.messageQueue.push(e),this.isProcessing)return;for(this.isProcessing=!0,await this.initializeMcpHost();this.messageQueue.length>0;){let I=this.messageQueue.shift();this.abortController=I.abortController||new AbortController,await this.runAgenticLoop(I.prompt,I.attachments)}this.isProcessing=!1,this.emitEphemeral("session.idle",{})}}async abort(){this.abortController?.abort()}async initializeMcpHost(){if(!this.mcpHost&&this.mcpServers&&Object.keys(this.mcpServers).length>0)try{this.mcpHost=new gB(this.logger,{mcpServers:this.mcpServers},this.excludedTools),await this.mcpHost.startServers()}catch(e){this.logger.error(`Failed to initialize MCP host: ${Ae(e)}`)}}async initializeAndValidateTools(){if(!(!this.availableTools?.length&&!this.excludedTools?.length))try{let e=await this.buildSettingsAndTools();if(e){let I=new Set([...e.builtInTools.map(l=>l.name),...e.mcpTools.map(l=>l.name),...this.externalToolDefinitions?.map(l=>l.name)||[]]);this.validateToolFilters(I)}}catch(e){this.logger.debug(`Failed to initialize tools for validation: ${Ae(e)}`)}}async buildSettingsAndTools(e){if(!this.authInfo&&!this.provider)return;await this.initializeMcpHost();let I,l;if(!this.provider){if(!this.authInfo)return;I=await Yh(this.authInfo),l=this.copilotUrl,!l&&I&&this.authInfo.type!=="hmac"&&(l=await E8t(this.authInfo.host,I||"",this.logger))}let n=!!this.provider,r=n?[]:await this.getModelList(),a=await $Me(this._selectedModel,this,r,this.logger,n);if(!a)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let s=n?`capi:${a}`:await _Me(a),c=new b1().setProblemStatement(e??"").setAgentModel(s).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(l).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(I).setCopilotToken(I).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).setFeatureFlags(this.featureFlags).setClientName(this.clientName).build();w2e();let i=await n6e(c),d=i.service?.agent?.model,G=my(d),b=mH(G.agent,G.model),u=AZl(r),h={location:this.workingDir,timeout:3e4,availableModels:u,toolPartialResultCallback:(Y,y)=>{this.emitEphemeral("tool.execution_partial_result",{toolCallId:Y,partialOutput:y})},createSubAgentCallback:Y=>({progress:async y=>{if(await this.invokeCallbacks(y),K9(y))switch(y.kind){case"message":if(Xh(y)){let w=XL(y)?y.message.tool_calls.map(C=>({toolCallId:C.id,name:nZ(C),arguments:vle(C,ny)})):[];this.emit("assistant.message",{parentToolCallId:Y,messageId:Eo(),content:typeof y.message.content=="string"?y.message.content:"",toolRequests:w});for(let C of w)this.emit("tool.execution_start",{parentToolCallId:Y,toolCallId:C.toolCallId,toolName:C.name,arguments:C.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:Y,toolCallId:y.toolCallId,success:y.toolResult.resultType==="success",result:y.toolResult.resultType==="success"?{content:y.toolResult.textResultForLlm||y.toolResult.sessionLog||""}:void 0,error:y.toolResult.resultType!=="success"?{message:(y.toolResult.resultType==="failure"?y.toolResult.error:void 0)||y.toolResult.textResultForLlm||y.toolResult.sessionLog||"Tool execution failed",code:y.toolResult.resultType}:void 0});break;default:break}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}}),permissions:this.requestPermission?{requestRequired:!0,request:this.requestPermission}:{requestRequired:!1},shellConfig:this.shellConfig??(process.platform==="win32"?Gg.powerShell:Gg.bash).withScriptSafetyAssessor(async function(Y){return{result:"completed",commands:[{identifier:Y,readOnly:!1}],possiblePaths:[],hasWriteFileRedirection:!1,canOfferSessionApproval:!1}}),skillDirectories:this.skillDirectories,disabledSkills:this.disabledSkills,...b.toolConfigOverrides},p=[];if(this.mcpHost)try{p=await this.mcpHost.getTools(i,this.logger,h.permissions)}catch(Y){this.logger.error(`Failed to get MCP tools: ${Ae(Y)}`)}kfe(b.supports,p);let N=await(b.cli?.toolInit??br.cli.toolInit)(h,i,this.logger,new sNe,this.callback,void 0);return{settings:i,builtInTools:N,mcpTools:p,config:b,toolConfig:h}}isToolEnabled(e){return this.availableTools?this.availableTools.includes(e):this.excludedTools?!this.excludedTools.includes(e):!0}validateToolFilters(e){let I=Array.from(e).filter(l=>!this.isToolEnabled(l));if(I.length>0&&!this.warnedUnknownTools.has("__disabled_tools_info__")){this.warnedUnknownTools.add("__disabled_tools_info__");let l=I.sort();this.emitEphemeral("session.info",{infoType:"configuration",message:`Disabled tools: ${l.join(", ")}`})}if(this.availableTools)for(let l of this.availableTools)!e.has(l)&&!this.warnedUnknownTools.has(l)&&(this.warnedUnknownTools.add(l),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool allowlist: "${l}"`}));if(this.excludedTools)for(let l of this.excludedTools)!e.has(l)&&!this.warnedUnknownTools.has(l)&&(this.warnedUnknownTools.add(l),this.emitEphemeral("session.info",{infoType:"configuration",message:`Unknown tool name in the tool denylist: "${l}"`}))}async buildCustomAgentTools(e,I,l,n,r,a,s){let o=async d=>await h8({location:r,version:a8(),currentWorkingDirectory:this.workingDir,parts:{},capabilities:{...a,customAgents:!1},tools:d,organizationCustomInstructions:this.organizationCustomInstructions,toolConfigOverrides:s}),i=(this.selectedCustomAgent?[this.selectedCustomAgent]:e).filter(d=>d.infer!==!1);return await Promise.all(i.map(async d=>{let G;if(d.mcpServers&&Object.keys(d.mcpServers).length>0){let b=await this.mcpHostCache.getOrCreateHost(d.name,d.mcpServers);b&&(G=new kZe(b,I,s.permissions))}return qTt(o,Bqt,d,this.workingDir,n,l,G)}))}filterToolsForSelectedAgent(e){return this.selectedCustomAgent?PMe(e,this.selectedCustomAgent,"top-level"):e}async invokeCallbacks(e){if(K9(e))try{await this.callback.progress(e)}catch(I){this.logger.error(`Error in callback: ${Ae(I)}`)}}async getModelList(){if(this.provider)return[];if(!this.authInfo)return Promise.reject(new Error("Session was not created with authentication info or custom provider"));try{return await Q8t(this.authInfo,this.copilotUrl||A2e(),this.integrationId,this.sessionId,this.logger)}catch(e){throw new Error("Failed to list available models",{cause:e})}}async getClient(){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");let e,I;if(!this.provider){if(!this.authInfo)throw new Error("Session was not created with authentication info");e=await Yh(this.authInfo),I=this.copilotUrl,!I&&e&&this.authInfo.type!=="hmac"&&(I=await E8t(this.authInfo.host,e||"",this.logger))}let l=!!this.provider,n=l?[]:await this.getModelList(),r=await $Me(this._selectedModel,this,n,this.logger,l);if(!r)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let a=l?`capi:${r}`:await _Me(r),o=new b1().setProblemStatement("").setAgentModel(a).setGithubRepoName("copilot-sdk-session").setGithubRepoCommit("copilot-sdk-commit").setGithubRepoReadWrite(!1).setCopilotIntegrationId(this.integrationId).setCopilotUrl(I).setCopilotHmacKey(this.authInfo?.type==="hmac"?this.authInfo.hmac:void 0).setGithubToken(e).setCopilotToken(e).setTrajectoryOutputFile(this.trajectoryFile).setEventsLogDirectory(this.eventsLogDirectory).build();w2e();let c=await n6e(o),i=c.service?.agent?.model,d=my(i),G=mH(d.agent,d.model);return{client:Iw(c,this.logger,d.agent,{...G.clientOptions,model:d.model},this.provider),settings:c}}async getContextSummary(){let e=await this.getChatMessages();if(e.length===0)return"";let{client:I}=await this.getClient(),l=Uqt(),n=2e4,r={role:"user",content:Oqt()},a=new ev(r,this.logger);try{let s="";for await(let o of I.getCompletionWithTools(l,[...e,r],[],{failIfInitialInputsTooLong:!1,processors:{preRequest:[a],onRequestError:[a]}}))o.kind==="message"&&o.message.role==="assistant"&&(s=typeof o.message.content=="string"?o.message.content:"");return s.length>n?s.slice(0,n):s}catch(s){return this.logger.error(`Failed to summarize context: ${Ae(s)}`),""}}async runAgenticLoop(e,I=[]){if(!this.authInfo&&!this.provider)throw new Error("Session was not created with authentication info or custom provider");let l=new Map,n=new Map,r=[];try{let s=(await Cw(this.hooks?.userPromptSubmitted,{timestamp:Date.now(),cwd:this.workingDir,prompt:e},this.logger))?.modifiedPrompt??e,o=await this.buildSettingsAndTools(s);if(!o)throw new Error("No model available. Check policy enablement under GitHub Settings > Copilot");let{settings:c,builtInTools:i,mcpTools:d,config:G,toolConfig:b}=o,u=c.service?.agent?.model,h=my(u),p=Iw(c,this.logger,h.agent,{...G.clientOptions,model:h.model},this.provider),W=[];if(this.externalToolDefinitions?.length){let _=this.externalToolDispatcher;if(!_)this.logger.warning("External tool definitions provided without a dispatcher; ignoring");else for(let Ie of this.externalToolDefinitions)W.push({name:Ie.name,description:Ie.description,input_schema:Ie.parameters??{type:"object",properties:{}},callback:async(Ce,at)=>{if(!at?.toolCallId)throw new Error("External tool invocation missing toolCallId");return await _({sessionId:this.sessionId,toolCallId:at.toolCallId,toolName:Ie.name,arguments:Ce,abortSignal:at.abortSignal})}})}let N=new Set([...i,...d,...W].map(_=>_.name));this.validateToolFilters(N);let Y=[...i,...d,...W].filter(_=>this.isToolEnabled(_.name)),y=await j9(this.workingDir),w={...G.supports,reasoning:!0},C,E={progress:async _=>{if(_.kind==="message"&&_.turn===0){if(!_.callId)throw new Error("message on turn 0 event missing callId");C=_.callId}if(await this.invokeCallbacks(_),_.kind==="custom_agent_session_boundary"){let Ie=_.agentId;if(Ie)if(_.sessionBoundaryType==="start"){let Ce=this.customAgents?.find(at=>at.name===_.agentName);Ce&&(this.activeCustomAgents.set(Ie,{name:_.agentName,displayName:Ce.displayName}),this.emit("custom_agent.started",{toolCallId:Ie,agentName:_.agentName,agentDisplayName:Ce.displayName,agentDescription:Ce.description}))}else{let Ce=this.activeCustomAgents.get(Ie);Ce&&this.emit("custom_agent.completed",{toolCallId:Ie,agentName:Ce.name}),this.activeCustomAgents.delete(Ie)}return}if(K9(_)){if(!C)throw new Error("Custom agent event received without parentToolCallId");switch(_.kind){case"message":if(Xh(_)){let Ie=We.endCurrentStreamingMessage(),Ce=XL(_)?_.message.tool_calls.map(at=>({toolCallId:at.id,name:nZ(at),arguments:vle(at,ny)})):[];this.emit("assistant.message",{parentToolCallId:C,messageId:Ie??Eo(),content:typeof _.message.content=="string"?_.message.content:"",toolRequests:Ce});for(let at of Ce)this.emit("tool.execution_start",{parentToolCallId:C,toolCallId:at.toolCallId,toolName:at.name,arguments:at.arguments})}break;case"tool_execution":this.emit("tool.execution_complete",{parentToolCallId:C,toolCallId:_.toolCallId,success:_.toolResult.resultType==="success",result:_.toolResult.resultType==="success"?{content:_.toolResult.textResultForLlm||_.toolResult.sessionLog||""}:void 0,error:_.toolResult.resultType!=="success"?{message:(_.toolResult.resultType==="failure"?_.toolResult.error:void 0)||_.toolResult.textResultForLlm||_.toolResult.sessionLog||"Tool execution failed",code:_.toolResult.resultType}:void 0,toolTelemetry:_.toolResult.toolTelemetry});break;case"model_call_failure":case"model_call_success":case"image_processing":case"images_removed":case"response":case"history_truncated":case"turn_started":case"turn_ended":case"turn_failed":case"turn_retry":break;default:eh(_,`Unknown event kind: ${JSON.stringify(_)}`)}}},partialResult:async()=>{},commentReply:async()=>{},result:async()=>{},error:async()=>{}},X={client:p,settings:c,logger:this.logger,exec:new Hd(this.logger),customAgents:this.customAgents||[],organizationCustomInstructions:this.organizationCustomInstructions,callback:E},f=Y;if(this.customAgents&&this.customAgents.length>0){let _=await this.buildCustomAgentTools(this.customAgents,c,Y,X,y.found?y.gitRoot:"",w,b);f=[...Y,..._]}r=this.filterToolsForSelectedAgent(f),this.onToolsUpdate&&this.onToolsUpdate(r);let x=await h8({location:y.found?y.gitRoot:"",version:a8(),currentWorkingDirectory:this.workingDir,parts:G.cli?.systemMessage||{},capabilities:w,tools:r,organizationCustomInstructions:this.organizationCustomInstructions,skipCustomInstructions:this.skipCustomInstructions,systemMessage:this.systemMessageConfig,toolConfigOverrides:b}),H=I?.some(_=>_.type==="file"&&AZ(_.path))??!1,ne=await this.selectedCustomAgent?.prompt(),Qe=xqt({customAgentPrompt:ne,problemStatement:s,capabilities:w,hasImages:H,handoffContext:this.handoffContext});this.emit("user.message",{content:s,transformedContent:Qe,attachments:I});let J=await this.getChatMessages(),te=J.findLastIndex(_=>_.role==="user"),Je=J[te];this.handoffContext=void 0;let ve=J.map((_,Ie)=>Ie===te?Je:_);await Cw(this.hooks?.sessionStart,{timestamp:Date.now(),cwd:this.workingDir,source:"new",initialPrompt:e},this.logger);let We=new DZe(this,()=>{},!1,this.logger),Me=new KZe(_=>{this.emitEphemeral("assistant.intent",{intent:_})}),Wt=new ev(Je,this.logger),Le=HYt(this.logger,c,f.find(_=>_.name==="github-mcp-server-get_file_contents")),CI=p.getCompletionWithTools(x,ve,r,{failIfInitialInputsTooLong:!1,processors:{preRequest:[Wt,Le,this.immediatePromptProcessor,new d8(this.logger)],postToolExecution:[Le],onRequestError:[Le,Wt],onStreamingChunk:[We,Me]},executeToolsInParallel:this.executeToolsInParallel??!0,abortSignal:this.abortController?.signal,stream:this.enableStreaming});for await(let _ of CI){if(this.abortController?.signal.aborted){this.emit("abort",{reason:"user initiated"}),this.emitEphemeral("session.info",{infoType:"cancellation",message:"Operation cancelled by user"});break}switch(await this.invokeCallbacks(_),_.kind){case"message":{if(Xh(_)){let Ce=We.endCurrentStreamingMessage()??Eo(),at=XL(_)?await Promise.all(_.message.tool_calls.map(async fI=>{let Et=nZ(fI),Ds=vle(fI,ny);l.set(fI.id,Et),n.set(fI.id,Ds);let Ks=await Cw(this.hooks?.preToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:Et,toolArgs:Ds},this.logger);return{toolCallId:fI.id,name:Et,arguments:Ks?.modifiedArgs??Ds}})):[];this.emit("assistant.message",{parentToolCallId:void 0,messageId:Ce,content:typeof _.message.content=="string"?_.message.content:"",toolRequests:at});for(let fI of at)this.emit("tool.execution_start",{toolCallId:fI.toolCallId,toolName:fI.name,arguments:fI.arguments})}else(_.message.role==="system"||_.message.role==="developer")&&this.emit("system.message",{role:_.message.role,content:typeof _.message.content=="string"?_.message.content:JSON.stringify(_.message.content),name:"name"in _.message?_.message.name:void 0});break}case"model_call_failure":{let Ie=new Error(_.modelCall?.error||"Model call failed");if(await Cw(this.hooks?.errorOccurred,{timestamp:Date.now(),cwd:this.workingDir,error:Ie,errorContext:"model_call",recoverable:!0},this.logger),jDe(_.modelCall?.error||""))return;let at=_.modelCall?.error||"Unknown error occurred";_.modelCall.request_id&&(at+=` (Request ID: ${_.modelCall.request_id})`),this.emit("session.error",{errorType:"model_call",message:`Model call failed: ${at}`,stack:Ie.stack});break}case"tool_execution":{let Ce=(await Cw(this.hooks?.postToolUse,{timestamp:Date.now(),cwd:this.workingDir,toolName:l.get(_.toolCallId)||"unknown",toolArgs:n.get(_.toolCallId)||{},toolResult:_.toolResult},this.logger))?.modifiedResult??_.toolResult,at=(Ce.resultType==="failure"?Ce.error:void 0)||Ce.textResultForLlm||Ce.sessionLog||"";this.emit("tool.execution_complete",{parentToolCallId:void 0,toolCallId:_.toolCallId,success:Ce.resultType==="success",result:Ce.resultType==="success"?{content:at}:void 0,error:Ce.resultType!=="success"?{message:at,code:Ce.resultType}:void 0,toolTelemetry:Ce.toolTelemetry});break}case"turn_started":{this.emit("assistant.turn_start",{turnId:`${_.turn}`});break}case"turn_ended":{this.emit("assistant.turn_end",{turnId:`${_.turn}`});break}case"model_call_success":{let Ie=_.modelCall.model||await this.getSelectedModel(),Ce=_.modelCallDurationMs||0,at=_.responseUsage,fI=await this.getModelList(),Et=Ie?qMe(Ie,fI):1;this.emitEphemeral("assistant.usage",{model:Ie||"unknown",inputTokens:at?.prompt_tokens||0,outputTokens:at?.completion_tokens||0,cacheReadTokens:at?.prompt_tokens_details?.cached_tokens||0,cacheWriteTokens:0,cost:Et,duration:Ce,initiator:_.modelCall?.initiator,apiCallId:_.modelCall?.api_id,providerCallId:_.modelCall?.request_id,quotaSnapshots:_.quotaSnapshots});break}case"history_truncated":{this.emit("session.truncation",{..._.truncateResult,performedBy:_.performedBy});break}case"response":case"images_removed":case"image_processing":case"turn_failed":case"turn_retry":this.logger.debug(`Ignoring event of kind: ${_.kind}`);break;default:eh(_,"Unhandled event type")}}}catch(a){if(await Cw(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"error",error:a instanceof Error?a:new Error(String(a))},this.logger),a&&typeof a=="object"&&"status"in a&&(a.status===401||a.status===403)){if("message"in a&&typeof a.message=="string"){let c=jDe(a.message);c&&this.emit("session.error",{errorType:"authentication",message:c.message})}this.emit("session.error",{errorType:"authorization",message:"Authorization error, you may need to run /login"})}a&&typeof a=="object"&&"status"in a&&a.status===402&&this.emit("session.error",{errorType:"quota",message:"Quota exceeded. Upgrade to increase your limit: https://github.com/features/copilot/plans"});let o=`Execution failed: ${a instanceof Error?a.message:a&&typeof a=="object"&&"toString"in a?Ae(a):"Unknown error occurred"}`;this.emit("session.error",{errorType:"query",message:o,stack:a instanceof Error?a.stack:void 0})}finally{await Cw(this.hooks?.sessionEnd,{timestamp:Date.now(),cwd:this.workingDir,reason:"complete"},this.logger);try{for(let a of r)a.shutdown&&await a.shutdown()}catch(a){this.logger.error(`Error during session shutdown: ${Ae(a)}`)}}}},pNe=class extends hNe{repository;remoteSessionIds;pullRequestNumber;constructor(e){super(e),this.repository=e.repository,this.remoteSessionIds=e.remoteSessionIds,this.pullRequestNumber=e.pullRequestNumber}async send(e){let{prompt:I}=e;if(!this.pullRequestNumber)throw new Error("Cannot send message: Pull request number is not available");if(!this.authInfo)throw new Error("Cannot send message: Authentication info is not available");let{owner:l,name:n}=this.repository,r=this.pullRequestNumber,a=`@copilot ${I}`;this.logger.debug(`Posting user message to PR ${l}/${n}#${r}`);let s=Wpt(this.authInfo),o=new URL(`/repos/${l}/${n}/issues/${r}/comments`,oV(s)),c=await eDt(o,this.authInfo,this.logger,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:a})});if(!c.ok){let i=await c.text();throw new Error(`Failed to post comment to PR ${l}/${n}#${r}: ${c.status} ${c.statusText}
|
|
2101
2101
|
${i}
|
|
2102
|
-
${o.toString()}`)}this.logger.info(`Successfully posted user message to PR ${l}/${n}#${r}`),this.emit("user.message",{content:I})}async abort(){throw new Error("RemoteSession.abort() is not implemented yet.")}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!0,repository:this.repository,remoteSessionIds:this.remoteSessionIds,pullRequestNumber:this.pullRequestNumber}}}});import wZl from"node:path";async function v8t(t,e,I,l){I??=K_,l??=new _c;let n=await Ajt(e),{agents:r}=await Hjt(l,I,t,wZl.join(HJ(),"agents"),n,!1);return r.map(a=>({name:a.id,displayName:a.displayName,description:a.description,tools:a.tools,prompt:a.prompt,mcpServers:a.mcpServers||{},infer:a.infer}))}var o6e=m(()=>{"use strict";Ljt();nTe();JQ();UZe();AB()});var P_,EZl,vZl,XZl,HZl,CZl,fZl,JZl,LZl,kZl,xZl,BZl,SZl,zZl,UZl,OZl,MZl,TZl,jZl,DZl,KZl,PZl,qZl,_Zl,$Zl,eWl,tWl,IWl,c6e,fw,i6e=m(()=>{"use strict";ac();C3();
|
|
2102
|
+
${o.toString()}`)}this.logger.info(`Successfully posted user message to PR ${l}/${n}#${r}`),this.emit("user.message",{content:I})}async abort(){throw new Error("RemoteSession.abort() is not implemented yet.")}getMetadata(){return{sessionId:this.sessionId,startTime:this.startTime,modifiedTime:this.modifiedTime,summary:this.summary,isRemote:!0,repository:this.repository,remoteSessionIds:this.remoteSessionIds,pullRequestNumber:this.pullRequestNumber}}}});import wZl from"node:path";async function v8t(t,e,I,l){I??=K_,l??=new _c;let n=await Ajt(e),{agents:r}=await Hjt(l,I,t,wZl.join(HJ(),"agents"),n,!1);return r.map(a=>({name:a.id,displayName:a.displayName,description:a.description,tools:a.tools,prompt:a.prompt,mcpServers:a.mcpServers||{},infer:a.infer}))}var o6e=m(()=>{"use strict";Ljt();nTe();JQ();UZe();AB()});var P_,EZl,vZl,XZl,HZl,CZl,fZl,JZl,LZl,kZl,xZl,BZl,SZl,zZl,UZl,OZl,MZl,TZl,jZl,DZl,KZl,PZl,qZl,_Zl,$Zl,eWl,tWl,IWl,c6e,fw,i6e=m(()=>{"use strict";ac();C3();vve();Qj();P_=Ue({type:gt("text"),text:P()}),EZl=Ue({type:gt("refusal"),refusal:P()}),vZl=Ue({type:gt("image_url"),image_url:Ue({url:P(),detail:xi(["auto","low","high"]).optional()})}),XZl=Ue({type:gt("input_audio"),input_audio:Ue({data:P(),format:gt("wav").or(gt("mp3"))})}),HZl=Ue({type:gt("file"),file:Ue({file_date:P().optional(),file_id:P().optional(),filename:P().optional()})}),CZl=ki([P_,vZl,XZl,HZl]),fZl=Ue({name:P(),arguments:P()}),JZl=Ue({name:P(),input:P()}),LZl=Ue({id:P(),type:gt("function"),function:fZl}),kZl=Ue({id:P(),type:gt("custom"),custom:JZl}),xZl=ki([LZl,kZl]),BZl=Ue({name:P(),arguments:P()}),SZl=Ue({id:P()}),zZl=Ue({content:ki([P(),Sr(P_)]),role:gt("developer"),name:P().optional()}),UZl=Ue({content:ki([P(),Sr(P_)]),role:gt("system"),name:P().optional()}),OZl=Ue({content:ki([P(),Sr(CZl)]),role:gt("user"),name:P().optional()}),MZl=Ue({content:ki([P(),Sr(ki([P_,EZl]))]).nullable().optional(),role:gt("assistant"),name:P().optional(),refusal:P().nullable().optional(),audio:SZl.nullable().optional(),function_call:BZl.nullable().optional(),tool_calls:Sr(xZl).optional()}),TZl=Ue({content:ki([P(),Sr(P_)]),role:gt("tool"),tool_call_id:P()}),jZl=Ue({content:P().nullable(),role:gt("function"),name:P()}),DZl=ki([zZl,UZl,OZl,MZl,TZl,jZl]),KZl=Ue({type:gt("copilot"),text:P(),isStreaming:al().optional()}),PZl=Ue({type:gt("error"),text:P()}),qZl=Ue({type:gt("info"),text:P()}),_Zl=Ue({type:gt("user"),text:P()}),$Zl=Ue({type:gt("tool_call_requested"),callId:P(),name:P(),toolTitle:P().optional(),intentionSummary:P().nullable(),arguments:Eve,partialOutput:P().optional(),isHidden:al().optional(),isAlwaysExpanded:al().optional(),showNoContent:al().optional()}),eWl=Ue({type:gt("tool_call_completed"),callId:P(),name:P(),toolTitle:P().optional(),intentionSummary:P().nullable(),result:ki([Ue({type:gt("success"),log:P(),markdown:al().optional()}),Ue({type:gt("failure"),log:P(),markdown:al().optional()}),Ue({type:gt("rejected"),markdown:al().optional()}),Ue({type:gt("denied"),log:P(),markdown:al().optional()})]),arguments:Eve,isHidden:al().optional(),isAlwaysExpanded:al().optional(),showNoContent:al().optional()}),tWl=ki([KZl,PZl,qZl,_Zl,$Zl,eWl]),IWl=tWl.and(Ue({id:P(),timestamp:gee.date()})),c6e=Ue({sessionId:P(),startTime:gee.date(),chatMessages:Sr(DZl),timeline:Sr(IWl),selectedModel:xi(l2).optional()}),fw=cpt(c6e.parse,"history-session")});var xr,d6e,lWl,nWl,rWl,aWl,sWl,oWl,cWl,iWl,dWl,GWl,bWl,mWl,uWl,hWl,pWl,ZWl,WWl,NWl,YWl,gWl,yWl,VWl,RWl,AWl,FWl,wWl,QWl,EWl,X8t,G6e=m(()=>{"use strict";ac();i6e();xr=Ue({id:P().uuid(),timestamp:P().datetime(),parentId:P().uuid().nullable(),ephemeral:al().optional()}),d6e=Ue({parentToolCallId:P().optional()}),lWl=xr.extend({type:gt("session.start"),data:Ue({sessionId:P(),version:ul(),producer:P(),copilotVersion:P(),startTime:P().datetime(),selectedModel:P().optional()})}),nWl=xr.extend({type:gt("session.resume"),data:Ue({resumeTime:P().datetime(),eventCount:ul()})}),rWl=xr.extend({type:gt("session.error"),data:Ue({errorType:P(),message:P(),stack:P().optional()})}),aWl=xr.extend({type:gt("session.info"),data:Ue({infoType:P(),message:P()})}),sWl=xr.extend({type:gt("session.model_change"),data:Ue({previousModel:P().optional(),newModel:P()})}),oWl=xr.extend({type:gt("session.import_legacy"),data:Ue({legacySession:c6e,importTime:P().datetime(),sourceFile:P()})}),cWl=xr.extend({type:gt("session.handoff"),data:Ue({handoffTime:P().datetime(),sourceType:xi(["remote","local"]),repository:Ue({owner:P(),name:P(),branch:P().optional()}).optional(),context:P().optional(),summary:P().optional(),remoteSessionId:P().optional()})}),iWl=xr.extend({type:gt("session.idle"),ephemeral:gt(!0),data:Ue({})}),dWl=xr.extend({type:gt("session.truncation"),data:Ue({tokenLimit:ul(),preTruncationTokensInMessages:ul(),preTruncationMessagesLength:ul(),postTruncationTokensInMessages:ul(),postTruncationMessagesLength:ul(),tokensRemovedDuringTruncation:ul(),messagesRemovedDuringTruncation:ul(),performedBy:P()})}),GWl=Ue({type:xi(["file","directory"]),path:P(),displayName:P()}),bWl=xr.extend({type:gt("user.message"),data:Ue({content:P(),transformedContent:P().optional(),attachments:Sr(GWl).optional(),source:P().optional()})}),mWl=xr.extend({type:gt("assistant.turn_start"),data:Ue({turnId:P()})}),uWl=xr.extend({type:gt("assistant.message"),data:Ue({messageId:P(),content:P(),chunkContent:P().optional(),totalResponseSizeBytes:ul().optional(),toolRequests:Sr(Ue({toolCallId:P(),name:P(),arguments:Rp()})).optional()}).merge(d6e)}),hWl=xr.extend({type:gt("assistant.intent"),ephemeral:gt(!0),data:Ue({intent:P()})}),pWl=xr.extend({type:gt("assistant.turn_end"),data:Ue({turnId:P()})}),ZWl=xr.extend({type:gt("assistant.usage"),ephemeral:gt(!0),data:Ue({model:P().optional(),inputTokens:ul().optional(),outputTokens:ul().optional(),cacheReadTokens:ul().optional(),cacheWriteTokens:ul().optional(),cost:ul().optional(),duration:ul().optional(),initiator:P().optional(),apiCallId:P().optional(),providerCallId:P().optional(),quotaSnapshots:bm(P(),Ue({isUnlimitedEntitlement:al(),entitlementRequests:ul(),usedRequests:ul(),usageAllowedWithExhaustedQuota:al(),overage:ul(),overageAllowedWithExhaustedQuota:al(),remainingPercentage:ul(),resetDate:y2e().optional()})).optional()})}),WWl=xr.extend({type:gt("abort"),data:Ue({reason:P()})}),NWl=xr.extend({type:gt("tool.user_requested"),data:Ue({toolCallId:P(),toolName:P(),arguments:Rp()})}),YWl=xr.extend({type:gt("tool.execution_start"),data:Ue({toolCallId:P(),toolName:P(),arguments:Rp()}).merge(d6e)}),gWl=xr.extend({type:gt("tool.execution_partial_result"),ephemeral:gt(!0),data:Ue({toolCallId:P(),partialOutput:P()})}),yWl=xr.extend({type:gt("tool.execution_complete"),data:Ue({toolCallId:P(),success:al(),isUserRequested:al().optional(),result:Ue({content:P()}).optional(),error:Ue({message:P(),code:P().optional()}).optional(),toolTelemetry:bm(Rp()).optional()}).merge(d6e)}),VWl=xr.extend({type:gt("custom_agent.started"),data:Ue({toolCallId:P(),agentName:P(),agentDisplayName:P(),agentDescription:P()})}),RWl=xr.extend({type:gt("custom_agent.completed"),data:Ue({toolCallId:P(),agentName:P()})}),AWl=xr.extend({type:gt("custom_agent.failed"),data:Ue({toolCallId:P(),agentName:P(),error:P()})}),FWl=xr.extend({type:gt("custom_agent.selected"),data:Ue({agentName:P(),agentDisplayName:P(),tools:Sr(P()).nullable()})}),wWl=xr.extend({type:gt("hook.start"),data:Ue({hookInvocationId:P(),hookType:P(),input:Rp()})}),QWl=xr.extend({type:gt("hook.end"),data:Ue({hookInvocationId:P(),hookType:P(),output:Rp(),success:al(),error:Ue({message:P(),stack:P().optional()}).optional()})}),EWl=xr.extend({type:gt("system.message"),data:Ue({content:P(),role:xi(["system","developer"]),name:P().optional(),metadata:Ue({promptVersion:P().optional(),variables:bm(Rp()).optional()}).optional()})}),X8t=mS("type",[lWl,nWl,rWl,iWl,aWl,sWl,oWl,cWl,dWl,bWl,mWl,hWl,uWl,pWl,ZWl,WWl,NWl,YWl,gWl,yWl,VWl,RWl,AWl,FWl,wWl,QWl,EWl])});var Jw,H8t=m(()=>{"use strict";G6e();Qj();Jw=ipt(X8t.parse,"session")});var C8t,b6e,f8t,J8t,L8t,k8t,x8t=m(()=>{C8t=t=>{t=1831565813+(t|=0)|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296},b6e=class{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;let{length:I,separator:l,dictionaries:n,style:r,seed:a}=e;this.dictionaries=n,this.separator=l,this.length=I,this.style=r,this.seed=a}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries.
|
|
2103
2103
|
Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let e=this.seed;return this.dictionaries.slice(0,this.length).reduce((I,l)=>{let n;e?(n=(a=>{if(typeof a=="string"){let s=a.split("").map(c=>c.charCodeAt(0)).reduce((c,i)=>c+i,1),o=Math.floor(Number(s));return C8t(o)}return C8t(a)})(e),e=4294967296*n):n=Math.random();let r=l[Math.floor(n*l.length)]||"";if(this.style==="lowerCase")r=r.toLowerCase();else if(this.style==="capital"){let[a,...s]=r.split("");r=a.toUpperCase()+s.join("")}else this.style==="upperCase"&&(r=r.toUpperCase());return I?`${I}${this.separator}${r}`:`${r}`},"")}},f8t={separator:"_",dictionaries:[]},J8t=t=>{let e=[...t&&t.dictionaries||f8t.dictionaries],I={...f8t,...t,length:t&&t.length||e.length,dictionaries:e};if(!t||!t.dictionaries||!t.dictionaries.length)throw new Error('A "dictionaries" array must be provided. This is a breaking change introduced starting from Unique Name Generator v4. Read more about the breaking change here: https://github.com/andreasonny83/unique-names-generator#migration-guide');return new b6e(I).generate()},L8t=["able","above","absent","absolute","abstract","abundant","academic","acceptable","accepted","accessible","accurate","accused","active","actual","acute","added","additional","adequate","adjacent","administrative","adorable","advanced","adverse","advisory","aesthetic","afraid","aggregate","aggressive","agreeable","agreed","agricultural","alert","alive","alleged","allied","alone","alright","alternative","amateur","amazing","ambitious","amused","ancient","angry","annoyed","annual","anonymous","anxious","appalling","apparent","applicable","appropriate","arbitrary","architectural","armed","arrogant","artificial","artistic","ashamed","asleep","assistant","associated","atomic","attractive","automatic","autonomous","available","average","awake","aware","awful","awkward","back","bad","balanced","bare","basic","beautiful","beneficial","better","bewildered","big","binding","biological","bitter","bizarre","blank","blonde","blushing","boiling","bold","bored","boring","bottom","brainy","brave","breakable","breezy","brief","bright","brilliant","broad","broken","bumpy","burning","busy","calm","capable","careful","casual","causal","cautious","central","certain","changing","characteristic","charming","cheap","cheerful","chemical","chief","chilly","chosen","chronic","chubby","circular","civic","civil","classic","classical","clean","clear","clever","clinical","close","closed","cloudy","clumsy","coastal","cognitive","coherent","cold","collective","colorful","colossal","coloured","colourful","combined","comfortable","commercial","common","compact","comparable","comparative","compatible","competent","competitive","complete","complex","complicated","comprehensive","compulsory","conceptual","concerned","concrete","condemned","confident","confidential","confused","conscious","conservation","considerable","consistent","constant","constitutional","contemporary","content","continental","continued","continuing","continuous","controlled","controversial","convenient","conventional","convinced","convincing","cooing","cool","cooperative","corporate","correct","corresponding","costly","courageous","creative","creepy","criminal","critical","crooked","crowded","crucial","crude","cruel","cuddly","cultural","curious","curly","current","curved","cute","daily","damaged","damp","dangerous","dark","dead","deafening","dear","decent","decisive","deep","defeated","defensive","defiant","definite","deliberate","delicate","delicious","delighted","delightful","democratic","dependent","depressed","desirable","desperate","detailed","determined","developed","developing","devoted","different","difficult","digital","diplomatic","direct","dirty","disappointed","disastrous","disciplinary","disgusted","distant","distinct","distinctive","distinguished","disturbed","disturbing","diverse","divine","dizzy","domestic","dominant","double","doubtful","drab","dramatic","dreadful","driving","dry","dual","due","dull","dusty","dutch","dying","dynamic","eager","early","eastern","easy","economic","educational","eerie","effective","efficient","elaborate","elated","elderly","eldest","electoral","electric","electrical","electronic","elegant","eligible","embarrassed","embarrassing","emotional","empirical","empty","enchanting","encouraging","endless","energetic","enormous","enthusiastic","entire","entitled","envious","environmental","equal","equivalent","essential","established","estimated","ethical","eventual","everyday","evident","evil","evolutionary","exact","excellent","exceptional","excess","excessive","excited","exciting","exclusive","existing","exotic","expected","expensive","experienced","experimental","explicit","extended","extensive","external","extra","extraordinary","extreme","exuberant","faint","fair","faithful","familiar","famous","fancy","fantastic","far","fascinating","fashionable","fast","fatal","favourable","favourite","federal","fellow","few","fierce","final","financial","fine","firm","fiscal","fit","fixed","flaky","flat","flexible","fluffy","fluttering","flying","following","fond","foolish","foreign","formal","formidable","forthcoming","fortunate","forward","fragile","frail","frantic","free","frequent","fresh","friendly","frightened","front","frozen","full","fun","functional","fundamental","funny","furious","future","fuzzy","gastric","general","generous","genetic","gentle","genuine","geographical","giant","gigantic","given","glad","glamorous","gleaming","global","glorious","golden","good","gorgeous","gothic","governing","graceful","gradual","grand","grateful","greasy","great","grieving","grim","gross","grotesque","growing","grubby","grumpy","guilty","handsome","happy","hard","harsh","head","healthy","heavy","helpful","helpless","hidden","high","hilarious","hissing","historic","historical","hollow","holy","homely","hon","honest","horizontal","horrible","hostile","hot","huge","human","hungry","hurt","hushed","husky","icy","ideal","identical","ideological","ill","illegal","imaginative","immediate","immense","implicit","important","impossible","impressed","impressive","improved","inadequate","inc","inclined","increased","increasing","incredible","independent","indirect","individual","industrial","inevitable","influential","informal","inherent","initial","injured","inland","inner","innocent","innovative","inquisitive","instant","institutional","insufficient","intact","integral","integrated","intellectual","intelligent","intense","intensive","interested","interesting","interim","interior","intermediate","internal","international","invisible","involved","irrelevant","isolated","itchy","jealous","jittery","joint","jolly","joyous","judicial","juicy","junior","just","keen","key","kind","known","labour","large","late","latin","lazy","leading","left","legal","legislative","legitimate","lengthy","lesser","level","lexical","liable","light","like","likely","limited","linear","linguistic","liquid","literary","little","live","lively","living","local","logical","lonely","long","loose","lost","loud","lovely","low","loyal","ltd","lucky","mad","magic","magnetic","magnificent","main","major","mammoth","managerial","managing","manual","many","marginal","marine","marked","married","marvellous","mass","massive","mathematical","mature","maximum","mean","meaningful","mechanical","medical","medieval","melodic","melted","mental","mere","metropolitan","mid","middle","mighty","mild","military","miniature","minimal","minimum","ministerial","minor","miserable","misleading","missing","misty","mixed","moaning","mobile","moderate","modern","modest","molecular","monetary","monthly","moral","motionless","muddy","multiple","mushy","musical","mutual","mysterious","naked","narrow","nasty","national","natural","naughty","naval","near","nearby","neat","necessary","negative","neighbouring","nervous","net","neutral","new","nice","noble","noisy","normal","northern","nosy","notable","novel","nuclear","numerous","nursing","nutritious","nutty","obedient","objective","obliged","obnoxious","obvious","occasional","occupational","odd","official","ok","okay","old","only","open","operational","opposite","optimistic","ordinary","organic","organisational","original","orthodox","other","outdoor","outer","outrageous","outside","outstanding","overall","overseas","overwhelming","painful","pale","panicky","parallel","parental","parliamentary","partial","particular","passing","passive","past","patient","payable","peaceful","peculiar","perfect","permanent","persistent","personal","petite","philosophical","physical","plain","planned","plastic","pleasant","pleased","poised","polite","poor","popular","positive","possible","potential","powerful","practical","precious","precise","preferred","pregnant","preliminary","premier","prepared","present","presidential","pretty","previous","prickly","primary","prime","principal","printed","prior","private","probable","productive","professional","profitable","profound","progressive","prominent","promising","proper","proposed","prospective","protective","proud","provincial","psychiatric","psychological","public","puny","pure","purring","puzzled","quaint","qualified","quarrelsome","querulous","quick","quickest","quiet","quintessential","quixotic","racial","radical","rainy","random","rapid","rare","raspy","rational","ratty","raw","ready","real","realistic","rear","reasonable","recent","reduced","redundant","regional","registered","regular","regulatory","related","relative","relaxed","relevant","reliable","relieved","religious","reluctant","remaining","remarkable","remote","renewed","representative","repulsive","required","resident","residential","resonant","respectable","respective","responsible","resulting","retail","retired","revolutionary","rich","ridiculous","right","rigid","ripe","rising","rival","roasted","robust","rolling","romantic","rotten","rough","round","royal","rubber","rude","ruling","running","rural","sacred","sad","safe","salty","satisfactory","satisfied","scared","scary","scattered","scientific","scornful","scrawny","screeching","secondary","secret","secure","select","selected","selective","selfish","semantic","senior","sensible","sensitive","separate","serious","severe","shaggy","shaky","shallow","shared","sharp","sheer","shiny","shivering","shocked","short","shrill","shy","sick","significant","silent","silky","silly","similar","simple","single","skilled","skinny","sleepy","slight","slim","slimy","slippery","slow","small","smart","smiling","smoggy","smooth","social","soft","solar","sole","solid","sophisticated","sore","sorry","sound","sour","southern","spare","sparkling","spatial","special","specific","specified","spectacular","spicy","spiritual","splendid","spontaneous","sporting","spotless","spotty","square","squealing","stable","stale","standard","static","statistical","statutory","steady","steep","sticky","stiff","still","stingy","stormy","straight","straightforward","strange","strategic","strict","striking","striped","strong","structural","stuck","subjective","subsequent","substantial","subtle","successful","successive","sudden","sufficient","suitable","sunny","super","superb","superior","supporting","supposed","supreme","sure","surprised","surprising","surrounding","surviving","suspicious","sweet","swift","symbolic","sympathetic","systematic","tall","tame","tart","tasteless","tasty","technical","technological","teenage","temporary","tender","tense","terrible","territorial","testy","then","theoretical","thick","thin","thorough","thoughtful","thoughtless","thundering","tight","tiny","tired","top","total","tough","toxic","traditional","tragic","tremendous","tricky","tropical","troubled","typical","ugliest","ugly","ultimate","unable","unacceptable","unaware","uncertain","unchanged","uncomfortable","unconscious","underground","underlying","unemployed","uneven","unexpected","unfair","unfortunate","unhappy","uniform","uninterested","unique","united","universal","unknown","unlikely","unnecessary","unpleasant","unsightly","unusual","unwilling","upper","upset","uptight","urban","urgent","used","useful","useless","usual","vague","valid","valuable","variable","varied","various","varying","vast","verbal","vertical","very","vicarious","vicious","victorious","violent","visible","visiting","visual","vital","vitreous","vivacious","vivid","vocal","vocational","voiceless","voluminous","voluntary","vulnerable","wandering","warm","wasteful","watery","weak","wealthy","weary","wee","weekly","weird","welcome","well","western","wet","whispering","whole","wicked","wide","widespread","wild","wilful","willing","willowy","wily","wise","wispy","wittering","witty","wonderful","wooden","working","worldwide","worried","worrying","worthwhile","worthy","written","wrong","xenacious","xenial","xenogeneic","xeric","xerothermic","yabbering","yammering","yappiest","yappy","yawning","yearling","yearning","yeasty","yelling","yelping","yielding","yodelling","young","youngest","youthful","ytterbic","yucky","yummy","zany","zealous","zeroth","zestful","zesty","zippy","zonal","zoophagous","zygomorphic","zygotic"],k8t=["aardvark","aardwolf","albatross","alligator","alpaca","amphibian","anaconda","angelfish","anglerfish","ant","anteater","antelope","antlion","ape","aphid","armadillo","asp","baboon","badger","bandicoot","barnacle","barracuda","basilisk","bass","bat","bear","beaver","bedbug","bee","beetle","bird","bison","blackbird","boa","boar","bobcat","bobolink","bonobo","bovid","bug","butterfly","buzzard","camel","canid","canidae","capybara","cardinal","caribou","carp","cat","caterpillar","catfish","catshark","cattle","centipede","cephalopod","chameleon","cheetah","chickadee","chicken","chimpanzee","chinchilla","chipmunk","cicada","clam","clownfish","cobra","cockroach","cod","condor","constrictor","coral","cougar","cow","coyote","crab","crane","crawdad","crayfish","cricket","crocodile","crow","cuckoo","damselfly","deer","dingo","dinosaur","dog","dolphin","donkey","dormouse","dove","dragon","dragonfly","duck","eagle","earthworm","earwig","echidna","eel","egret","elephant","elk","emu","ermine","falcon","felidae","ferret","finch","firefly","fish","flamingo","flea","fly","flyingfish","fowl","fox","frog","galliform","gamefowl","gayal","gazelle","gecko","gerbil","gibbon","giraffe","goat","goldfish","goose","gopher","gorilla","grasshopper","grouse","guan","guanaco","guineafowl","gull","guppy","haddock","halibut","hamster","hare","harrier","hawk","hedgehog","heron","herring","hippopotamus","hookworm","hornet","horse","hoverfly","hummingbird","hyena","iguana","impala","jackal","jaguar","jay","jellyfish","junglefowl","kangaroo","kingfisher","kite","kiwi","koala","koi","krill","ladybug","lamprey","landfowl","lark","leech","lemming","lemur","leopard","leopon","limpet","lion","lizard","llama","lobster","locust","loon","louse","lungfish","lynx","macaw","mackerel","magpie","mammal","manatee","mandrill","marlin","marmoset","marmot","marsupial","marten","mastodon","meadowlark","meerkat","mink","minnow","mite","mockingbird","mole","mollusk","mongoose","monkey","moose","mosquito","moth","mouse","mule","muskox","narwhal","newt","nightingale","ocelot","octopus","opossum","orangutan","orca","ostrich","otter","owl","ox","panda","panther","parakeet","parrot","parrotfish","partridge","peacock","peafowl","pelican","penguin","perch","pheasant","pig","pigeon","pike","pinniped","piranha","planarian","platypus","pony","porcupine","porpoise","possum","prawn","primate","ptarmigan","puffin","puma","python","quail","quelea","quokka","rabbit","raccoon","rat","rattlesnake","raven","reindeer","reptile","rhinoceros","roadrunner","rodent","rook","rooster","roundworm","sailfish","salamander","salmon","sawfish","scallop","scorpion","seahorse","shark","sheep","shrew","shrimp","silkworm","silverfish","skink","skunk","sloth","slug","smelt","snail","snake","snipe","sole","sparrow","spider","spoonbill","squid","squirrel","starfish","stingray","stoat","stork","sturgeon","swallow","swan","swift","swordfish","swordtail","tahr","takin","tapir","tarantula","tarsier","termite","tern","thrush","tick","tiger","tiglon","toad","tortoise","toucan","trout","tuna","turkey","turtle","tyrannosaurus","unicorn","urial","vicuna","viper","vole","vulture","wallaby","walrus","warbler","wasp","weasel","whale","whippet","whitefish","wildcat","wildebeest","wildfowl","wolf","wolverine","wombat","woodpecker","worm","wren","xerinae","yak","zebra"]});import{execFile as vWl}from"node:child_process";import{promisify as XWl}from"node:util";async function B8t(t){try{let{stdout:e}=await Uy("git",["status","--porcelain","--ignore-submodules"],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:1048576}),I=e.split(`
|
|
2104
|
-
`).filter(a=>a.length>0),l=0,n=0,r=0;for(let a of I){if(a.length<2)continue;let s=a[0],o=a[1];s==="?"&&o==="?"?r++:(s!==" "&&s!=="?"&&l++,o!==" "&&o!=="?"&&n++)}return{staged:l,unstaged:n,untracked:r,hasChanges:I.length>0}}catch{return{staged:0,unstaged:0,untracked:0,hasChanges:!1}}}async function HWl(t){let{stdout:e}=await Uy("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3});return e.trim()}async function CWl(t){try{let{stdout:e}=await Uy("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3}),I=e.trim();if(!I||I==="HEAD")return"origin";let{stdout:l}=await Uy("git",["config",`branch.${I}.remote`],{cwd:t,encoding:"utf8",timeout:5e3});return l.trim()||"origin"}catch{return"origin"}}async function fWl(t){let e=await CWl(t);try{let{stdout:I}=await Uy("git",["symbolic-ref",`refs/remotes/${e}/HEAD`],{cwd:t,encoding:"utf8",timeout:5e3}),l=I.match(new RegExp(`refs/remotes/${e}/(.+)`));if(l)return l[1].trim()}catch{}try{return await Uy("git",["rev-parse","--verify",`refs/remotes/${e}/main`],{cwd:t,encoding:"utf8",timeout:5e3}),"main"}catch{}try{return await Uy("git",["rev-parse","--verify",`refs/remotes/${e}/master`],{cwd:t,encoding:"utf8",timeout:5e3}),"master"}catch{return"main"}}async function JWl(t,e){try{return await Uy("git",["rev-parse","--verify",`refs/heads/${e}`],{cwd:t,encoding:"utf8",timeout:5e3}),!0}catch{return!1}}async function LWl(t,e){let l=["adjectives","animals"],r=[];for(let a of l)a.toLowerCase()==="adjectives"&&r.push(L8t),a.toLowerCase()==="animals"&&r.push(k8t);if(r.length===0)return`${e}/session${Date.now()}`;for(let a=0;a<5;a++){let s=`${e}/${J8t({dictionaries:r,length:r.length,separator:"-"})}`;if(!await JWl(t,s))return s}return`${e}/session${Date.now()}`}async function kWl(t){return LWl(t,"copilot")}async function S8t(t){try{let[e,I,l,n]=await Promise.all([HWl(t),zZe(t),fWl(t),kWl(t)]);if(!I)throw new Error("Could not determine GitHub repository from git remotes");return{repository:`${I.owner}/${I.name}`,baseBranch:l,headBranch:e,asyncBranch:n}}catch(e){throw new Error(`Failed to get repository info: ${e instanceof Error?e.message:String(e)}`)}}async function z8t(t,e=process.cwd()){try{await Uy("git",["checkout",t],{cwd:e,encoding:"utf8",timeout:5e3,maxBuffer:10*1024*1024})}catch(I){let l=I instanceof Error?I.message:String(I);throw new Error(`Failed to switch to branch '${t}': ${l}`)}}var Uy,U8t=m(()=>{"use strict";x8t();lTe();Uy=XWl(vWl)});import{existsSync as xWl}from"fs";import{unlink as m6e}from"fs/promises";import{join as O8t}from"path";function M8t(t){if(t.role==="user")return typeof t.content=="string"?t.content:t.content.find(e=>e.type==="text")?.text}async function BWl(t){if(xWl(t))try{return await Fnt(t,e=>{if(e.trim())try{let I=JSON.parse(e);if(I.type==="session.import_legacy"){let l=I.data.legacySession.chatMessages.find(n=>n.role==="user");if(l?.content){let n=M8t(l);if(n)return u6e(n)}}if(I.type==="user.message"){let l=I.data.content;if(l)return u6e(l)}return}catch{return}})}catch{return}}function u6e(t){let e=t.lastIndexOf("<reminder>");e!==-1&&(t=t.substring(0,e).trim());let I=t.replace(/\s+/g," ").trim();return I.length>75&&(I=I.substring(0,55).trim()+"..."),I=I.split("").filter(l=>{let n=l.charCodeAt(0);return n>=32&&n!==127}).join(""),I}var ZNe,h6e,T8t=m(()=>{"use strict";Ove();mAe();AB();DI();rZ();rCe();i6e();H8t();j7();U8t();ZNe=class{constructor(e,I,l,n=!1,r){this.session=e;this.logger=I;this.flushDebounceMs=l;this.shouldSaveSession=n;this.legacySourceFile=r;this.unsubscribe=this.session.on("*",a=>{a.ephemeral||(this.unflushedEvents.push(a),!this.shouldSaveSession&&a.type==="user.message"&&(this.shouldSaveSession=!0),a.type!=="session.resume"&&this.shouldSaveSession&&(this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush().catch(s=>{this.logger.error(`Error flushing session ${this.session.sessionId}: ${s instanceof Error?s.message:String(s)}`)})},this.flushDebounceMs)))})}flushTimer=null;unflushedEvents=[];migratedLegacy=!1;isFlushing=!1;needsFlushAfterCurrent=!1;unsubscribe;dispose(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.unsubscribe()}async flush(){if(!this.shouldSaveSession||this.unflushedEvents.length===0)return;if(this.isFlushing){this.needsFlushAfterCurrent=!0;return}this.isFlushing=!0,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);let e=this.unflushedEvents;this.unflushedEvents=[];try{if(await Jw.append(e,this.session.sessionId),this.logger.debug(`Flushed ${e.length} events to session ${this.session.sessionId}`),this.legacySourceFile&&!this.migratedLegacy){this.logger.debug(`Migrated legacy session ${this.session.sessionId} from ${this.legacySourceFile}`);try{await m6e(this.legacySourceFile)}catch(I){this.logger.error(`Failed to delete legacy session file ${this.legacySourceFile}: ${Ae(I)}`)}this.migratedLegacy=!0}}catch(I){this.logger.error(`Failed to flush events for ${this.session.sessionId}: ${I instanceof Error?I.message:String(I)}`),this.unflushedEvents.unshift(...e)}finally{this.isFlushing=!1,this.needsFlushAfterCurrent&&(this.needsFlushAfterCurrent=!1,await this.flush())}}};h6e=class{sessionWriters={};copilotVersion;flushDebounceMs;logger;constructor({version:e,flushDebounceMs:I,...l}){this.logger=l.logger||new _c,this.copilotVersion=e||"unknown",this.flushDebounceMs=I||100}async createSession(e,I=!0){let l=await this.loadHooks(e),n=new zy({...e,hooks:l,startTime:e?.startTime||new Date});return this.sessionWriters[n.sessionId]=new ZNe(n,this.logger,this.flushDebounceMs),I&&n.emit("session.start",{sessionId:n.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:n.startTime.toISOString(),selectedModel:e?.model}),n}async loadHooks(e){let I=e?.workingDirectory||process.cwd(),l=await j9(I),n=l.found?l.gitRoot:I,r=O8t(n,".github","hooks");return bAe(r,(s,o)=>nCe(s,o,n),e?.hooks,this.logger)}async getSession(e,I=!0){let l,n;try{l=await this.loadSession(e)}catch(r){let a=r instanceof Error?r.message:String(r);if(a.includes("Invalid event")||a.includes("Cannot create session")||a.includes("First event must be")){this.logger.error(`Failed to parse session ${e.sessionId}: ${a}`);let o=a.match(/Invalid event at line (\d+): (.+?)\. Event: (.+)/);if(o){let d=o[1],G=o[2],b=o[3];throw this.logger.error(`Event at line ${d}: ${b}`),new Error(`Session file is corrupted (line ${d}: ${G})`)}let c=a.match(/Invalid event at line (\d+): (.+)/),i=c?`Session file is corrupted (line ${c[1]}: ${c[2]})`:"Session file is corrupted or incompatible";throw new Error(i)}try{let o=await this.loadLegacySession(e);l=o.session,n=o.legacySourceFile}catch(o){let c=o instanceof Error?o.message:String(o);if(c.includes("Invalid")||c.includes("Cannot create session"))throw this.logger.error(`Failed to parse legacy session ${e.sessionId}: ${c}`),new Error("Session file is corrupted or incompatible");return}}return this.sessionWriters[e.sessionId]||(this.sessionWriters[e.sessionId]=new ZNe(l,this.logger,this.flushDebounceMs,!0,n)),I&&l.emit("session.resume",{resumeTime:new Date().toISOString(),eventCount:l.getEvents().length}),l}async getLastSession(e={}){let I=await this.listSessions();if(I.length===0)return;I.sort((n,r)=>r.modifiedTime.getTime()-n.modifiedTime.getTime());let l=I[0].sessionId;return await this.getSession({...e,sessionId:l})}async saveSession(e){e instanceof zy&&await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let I=await Jw.load(e.sessionId);return await zy.fromEvents(I,e)}async loadLegacySession(e){let l=(await fw.directoryFiles()).filter(o=>{let c=o.match(/^session_(.+)_(\d+)\.json$/);return c&&c[1]===e.sessionId});if(l.length===0)throw new Error(`Legacy session ${e.sessionId} not found`);let n=l[0];l.length>1&&this.logger.info(`Multiple legacy sessions found for ${e.sessionId}, using newest`);let r=await fw.load(n);if(!r)throw new Error(`Failed to load legacy session from ${n}`);let a=new Date(r.startTime),s=new zy({...e,sessionId:r.sessionId,startTime:a});return s.emit("session.start",{sessionId:r.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:a.toISOString(),selectedModel:r.selectedModel}),s.emit("session.import_legacy",{legacySession:{sessionId:r.sessionId,startTime:a,chatMessages:r.chatMessages,timeline:r.timeline,selectedModel:r.selectedModel},importTime:new Date().toISOString(),sourceFile:n}),this.logger.info(`Loaded legacy session ${e.sessionId} from ${n}`),{session:s,legacySourceFile:fw.path(n.replace(/\.json$/,""))}}async listSessions(){let e=await Jw.directoryFilesWithMetadata(),I=await fw.directoryFilesWithMetadata(),l=await Promise.all(e.map(async a=>{let s=a.file.replace(".jsonl",""),o=Jw.path(s),c=await BWl(o);return{sessionId:s,startTime:a.birthtime,modifiedTime:a.mtime,summary:c,isRemote:!1}})),n=(await Promise.all(I.map(async a=>{let s=a.file.match(/^session_(.+)_(\d+)\.json$/);if(!s)return null;let o=s[1],c;try{let i=await fw.load(a.file.replace(/\.json$/,""));if(i){let d=i.chatMessages?.find(G=>G.role==="user");if(d?.content){let G=M8t(d);G&&(c=u6e(G))}}}catch{}return{sessionId:o,startTime:a.birthtime,modifiedTime:a.mtime,summary:c,isRemote:!1}}))).filter(a=>a!==null);this.logger.debug(`Found ${l.length} JSONL sessions and ${n.length} legacy sessions`);let r=new Map;for(let a of n)r.set(a.sessionId,a);for(let a of l)r.set(a.sessionId,a);return Array.from(r.values()).sort((a,s)=>s.modifiedTime.getTime()-a.modifiedTime.getTime())}async deleteSession(e){await this.closeSession(e);let I=Jw.path(e);try{await m6e(I),this.logger.info(`Deleted session file ${I}`);return}catch{let r=(await fw.directoryFiles()).filter(a=>{let s=a.match(/^session_(.+)_(\d+)\.json$/);return s&&s[1]===e});if(r.length===0)throw new Error(`Session file not found for ${e}`);for(let a of r){let s=fw.path(a.replace(/\.json$/,""));this.logger.info(`Deleting legacy session file ${s}`),await m6e(s)}}}async closeSession(e){this.logger.info(`Closing session ${e}`);let I=this.sessionWriters[e];I&&(await I.flush(),I.dispose(),delete this.sessionWriters[e])}getSessionsDirectory(){return O8t(Jw.home(),Jw.directory())}setLogger(e){this.logger=e}async*handoffSession(e,I){if(!(e instanceof pNe))throw new Error("Can only handoff RemoteSession instances to local");let l=e.getMetadata();if(!l.repository)throw new Error("Remote session missing repository information");this.logger.info(`Handing off remote session ${l.sessionId} to local...`),yield{step:"validate-repo",status:"in-progress"};let n=process.cwd(),r;try{r=await S8t(n)}catch(d){throw new Error(`Not in a git repository. Please navigate to your repository directory.
|
|
2104
|
+
`).filter(a=>a.length>0),l=0,n=0,r=0;for(let a of I){if(a.length<2)continue;let s=a[0],o=a[1];s==="?"&&o==="?"?r++:(s!==" "&&s!=="?"&&l++,o!==" "&&o!=="?"&&n++)}return{staged:l,unstaged:n,untracked:r,hasChanges:I.length>0}}catch{return{staged:0,unstaged:0,untracked:0,hasChanges:!1}}}async function HWl(t){let{stdout:e}=await Uy("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3});return e.trim()}async function CWl(t){try{let{stdout:e}=await Uy("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",timeout:5e3}),I=e.trim();if(!I||I==="HEAD")return"origin";let{stdout:l}=await Uy("git",["config",`branch.${I}.remote`],{cwd:t,encoding:"utf8",timeout:5e3});return l.trim()||"origin"}catch{return"origin"}}async function fWl(t){let e=await CWl(t);try{let{stdout:I}=await Uy("git",["symbolic-ref",`refs/remotes/${e}/HEAD`],{cwd:t,encoding:"utf8",timeout:5e3}),l=I.match(new RegExp(`refs/remotes/${e}/(.+)`));if(l)return l[1].trim()}catch{}try{return await Uy("git",["rev-parse","--verify",`refs/remotes/${e}/main`],{cwd:t,encoding:"utf8",timeout:5e3}),"main"}catch{}try{return await Uy("git",["rev-parse","--verify",`refs/remotes/${e}/master`],{cwd:t,encoding:"utf8",timeout:5e3}),"master"}catch{return"main"}}async function JWl(t,e){try{return await Uy("git",["rev-parse","--verify",`refs/heads/${e}`],{cwd:t,encoding:"utf8",timeout:5e3}),!0}catch{return!1}}async function LWl(t,e){let l=["adjectives","animals"],r=[];for(let a of l)a.toLowerCase()==="adjectives"&&r.push(L8t),a.toLowerCase()==="animals"&&r.push(k8t);if(r.length===0)return`${e}/session${Date.now()}`;for(let a=0;a<5;a++){let s=`${e}/${J8t({dictionaries:r,length:r.length,separator:"-"})}`;if(!await JWl(t,s))return s}return`${e}/session${Date.now()}`}async function kWl(t){return LWl(t,"copilot")}async function S8t(t){try{let[e,I,l,n]=await Promise.all([HWl(t),zZe(t),fWl(t),kWl(t)]);if(!I)throw new Error("Could not determine GitHub repository from git remotes");return{repository:`${I.owner}/${I.name}`,baseBranch:l,headBranch:e,asyncBranch:n}}catch(e){throw new Error(`Failed to get repository info: ${e instanceof Error?e.message:String(e)}`)}}async function z8t(t,e=process.cwd()){try{await Uy("git",["checkout",t],{cwd:e,encoding:"utf8",timeout:5e3,maxBuffer:10*1024*1024})}catch(I){let l=I instanceof Error?I.message:String(I);throw new Error(`Failed to switch to branch '${t}': ${l}`)}}var Uy,U8t=m(()=>{"use strict";x8t();lTe();Uy=XWl(vWl)});import{existsSync as xWl}from"fs";import{unlink as m6e}from"fs/promises";import{join as O8t}from"path";function M8t(t){if(t.role==="user")return typeof t.content=="string"?t.content:t.content.find(e=>e.type==="text")?.text}async function BWl(t){if(xWl(t))try{return await Fnt(t,e=>{if(e.trim())try{let I=JSON.parse(e);if(I.type==="session.import_legacy"){let l=I.data.legacySession.chatMessages.find(n=>n.role==="user");if(l?.content){let n=M8t(l);if(n)return u6e(n)}}if(I.type==="user.message"){let l=I.data.content;if(l)return u6e(l)}return}catch{return}})}catch{return}}function u6e(t){let e=t.lastIndexOf("<reminder>");e!==-1&&(t=t.substring(0,e).trim());let I=t.replace(/\s+/g," ").trim();return I.length>75&&(I=I.substring(0,55).trim()+"..."),I=I.split("").filter(l=>{let n=l.charCodeAt(0);return n>=32&&n!==127}).join(""),I}var ZNe,h6e,T8t=m(()=>{"use strict";Mve();mAe();AB();DI();rZ();rCe();i6e();H8t();j7();U8t();ZNe=class{constructor(e,I,l,n=!1,r){this.session=e;this.logger=I;this.flushDebounceMs=l;this.shouldSaveSession=n;this.legacySourceFile=r;this.unsubscribe=this.session.on("*",a=>{a.ephemeral||(this.unflushedEvents.push(a),!this.shouldSaveSession&&a.type==="user.message"&&(this.shouldSaveSession=!0),a.type!=="session.resume"&&this.shouldSaveSession&&(this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=setTimeout(()=>{this.flush().catch(s=>{this.logger.error(`Error flushing session ${this.session.sessionId}: ${s instanceof Error?s.message:String(s)}`)})},this.flushDebounceMs)))})}flushTimer=null;unflushedEvents=[];migratedLegacy=!1;isFlushing=!1;needsFlushAfterCurrent=!1;unsubscribe;dispose(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.unsubscribe()}async flush(){if(!this.shouldSaveSession||this.unflushedEvents.length===0)return;if(this.isFlushing){this.needsFlushAfterCurrent=!0;return}this.isFlushing=!0,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);let e=this.unflushedEvents;this.unflushedEvents=[];try{if(await Jw.append(e,this.session.sessionId),this.logger.debug(`Flushed ${e.length} events to session ${this.session.sessionId}`),this.legacySourceFile&&!this.migratedLegacy){this.logger.debug(`Migrated legacy session ${this.session.sessionId} from ${this.legacySourceFile}`);try{await m6e(this.legacySourceFile)}catch(I){this.logger.error(`Failed to delete legacy session file ${this.legacySourceFile}: ${Ae(I)}`)}this.migratedLegacy=!0}}catch(I){this.logger.error(`Failed to flush events for ${this.session.sessionId}: ${I instanceof Error?I.message:String(I)}`),this.unflushedEvents.unshift(...e)}finally{this.isFlushing=!1,this.needsFlushAfterCurrent&&(this.needsFlushAfterCurrent=!1,await this.flush())}}};h6e=class{sessionWriters={};copilotVersion;flushDebounceMs;logger;constructor({version:e,flushDebounceMs:I,...l}){this.logger=l.logger||new _c,this.copilotVersion=e||"unknown",this.flushDebounceMs=I||100}async createSession(e,I=!0){let l=await this.loadHooks(e),n=new zy({...e,hooks:l,startTime:e?.startTime||new Date});return this.sessionWriters[n.sessionId]=new ZNe(n,this.logger,this.flushDebounceMs),I&&n.emit("session.start",{sessionId:n.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:n.startTime.toISOString(),selectedModel:e?.model}),n}async loadHooks(e){let I=e?.workingDirectory||process.cwd(),l=await j9(I),n=l.found?l.gitRoot:I,r=O8t(n,".github","hooks");return bAe(r,(s,o)=>nCe(s,o,n),e?.hooks,this.logger)}async getSession(e,I=!0){let l,n;try{l=await this.loadSession(e)}catch(r){let a=r instanceof Error?r.message:String(r);if(a.includes("Invalid event")||a.includes("Cannot create session")||a.includes("First event must be")){this.logger.error(`Failed to parse session ${e.sessionId}: ${a}`);let o=a.match(/Invalid event at line (\d+): (.+?)\. Event: (.+)/);if(o){let d=o[1],G=o[2],b=o[3];throw this.logger.error(`Event at line ${d}: ${b}`),new Error(`Session file is corrupted (line ${d}: ${G})`)}let c=a.match(/Invalid event at line (\d+): (.+)/),i=c?`Session file is corrupted (line ${c[1]}: ${c[2]})`:"Session file is corrupted or incompatible";throw new Error(i)}try{let o=await this.loadLegacySession(e);l=o.session,n=o.legacySourceFile}catch(o){let c=o instanceof Error?o.message:String(o);if(c.includes("Invalid")||c.includes("Cannot create session"))throw this.logger.error(`Failed to parse legacy session ${e.sessionId}: ${c}`),new Error("Session file is corrupted or incompatible");return}}return this.sessionWriters[e.sessionId]||(this.sessionWriters[e.sessionId]=new ZNe(l,this.logger,this.flushDebounceMs,!0,n)),I&&l.emit("session.resume",{resumeTime:new Date().toISOString(),eventCount:l.getEvents().length}),l}async getLastSession(e={}){let I=await this.listSessions();if(I.length===0)return;I.sort((n,r)=>r.modifiedTime.getTime()-n.modifiedTime.getTime());let l=I[0].sessionId;return await this.getSession({...e,sessionId:l})}async saveSession(e){e instanceof zy&&await this.sessionWriters[e.sessionId]?.flush()}async loadSession(e){let I=await Jw.load(e.sessionId);return await zy.fromEvents(I,e)}async loadLegacySession(e){let l=(await fw.directoryFiles()).filter(o=>{let c=o.match(/^session_(.+)_(\d+)\.json$/);return c&&c[1]===e.sessionId});if(l.length===0)throw new Error(`Legacy session ${e.sessionId} not found`);let n=l[0];l.length>1&&this.logger.info(`Multiple legacy sessions found for ${e.sessionId}, using newest`);let r=await fw.load(n);if(!r)throw new Error(`Failed to load legacy session from ${n}`);let a=new Date(r.startTime),s=new zy({...e,sessionId:r.sessionId,startTime:a});return s.emit("session.start",{sessionId:r.sessionId,version:1,producer:"copilot-agent",copilotVersion:this.copilotVersion,startTime:a.toISOString(),selectedModel:r.selectedModel}),s.emit("session.import_legacy",{legacySession:{sessionId:r.sessionId,startTime:a,chatMessages:r.chatMessages,timeline:r.timeline,selectedModel:r.selectedModel},importTime:new Date().toISOString(),sourceFile:n}),this.logger.info(`Loaded legacy session ${e.sessionId} from ${n}`),{session:s,legacySourceFile:fw.path(n.replace(/\.json$/,""))}}async listSessions(){let e=await Jw.directoryFilesWithMetadata(),I=await fw.directoryFilesWithMetadata(),l=await Promise.all(e.map(async a=>{let s=a.file.replace(".jsonl",""),o=Jw.path(s),c=await BWl(o);return{sessionId:s,startTime:a.birthtime,modifiedTime:a.mtime,summary:c,isRemote:!1}})),n=(await Promise.all(I.map(async a=>{let s=a.file.match(/^session_(.+)_(\d+)\.json$/);if(!s)return null;let o=s[1],c;try{let i=await fw.load(a.file.replace(/\.json$/,""));if(i){let d=i.chatMessages?.find(G=>G.role==="user");if(d?.content){let G=M8t(d);G&&(c=u6e(G))}}}catch{}return{sessionId:o,startTime:a.birthtime,modifiedTime:a.mtime,summary:c,isRemote:!1}}))).filter(a=>a!==null);this.logger.debug(`Found ${l.length} JSONL sessions and ${n.length} legacy sessions`);let r=new Map;for(let a of n)r.set(a.sessionId,a);for(let a of l)r.set(a.sessionId,a);return Array.from(r.values()).sort((a,s)=>s.modifiedTime.getTime()-a.modifiedTime.getTime())}async deleteSession(e){await this.closeSession(e);let I=Jw.path(e);try{await m6e(I),this.logger.info(`Deleted session file ${I}`);return}catch{let r=(await fw.directoryFiles()).filter(a=>{let s=a.match(/^session_(.+)_(\d+)\.json$/);return s&&s[1]===e});if(r.length===0)throw new Error(`Session file not found for ${e}`);for(let a of r){let s=fw.path(a.replace(/\.json$/,""));this.logger.info(`Deleting legacy session file ${s}`),await m6e(s)}}}async closeSession(e){this.logger.info(`Closing session ${e}`);let I=this.sessionWriters[e];I&&(await I.flush(),I.dispose(),delete this.sessionWriters[e])}getSessionsDirectory(){return O8t(Jw.home(),Jw.directory())}setLogger(e){this.logger=e}async*handoffSession(e,I){if(!(e instanceof pNe))throw new Error("Can only handoff RemoteSession instances to local");let l=e.getMetadata();if(!l.repository)throw new Error("Remote session missing repository information");this.logger.info(`Handing off remote session ${l.sessionId} to local...`),yield{step:"validate-repo",status:"in-progress"};let n=process.cwd(),r;try{r=await S8t(n)}catch(d){throw new Error(`Not in a git repository. Please navigate to your repository directory.
|
|
2105
2105
|
${Ae(d)}`)}let a=r.repository,s=`${l.repository.owner}/${l.repository.name}`;if(a!==s)throw new Error(`Repository mismatch: You are in '${a}' but the remote session is for '${s}'.
|
|
2106
2106
|
Please navigate to the correct repository and try again.`);this.logger.info(`\u2713 Repository validated: ${a}`),yield{step:"validate-repo",status:"complete"},yield{step:"check-changes",status:"in-progress"};let o=await B8t(n);if(o.hasChanges){let d=[];throw o.staged>0&&d.push(`${o.staged} staged`),o.unstaged>0&&d.push(`${o.unstaged} unstaged`),o.untracked>0&&d.push(`${o.untracked} untracked`),new Error(`Your repository has uncommitted changes (${d.join(", ")}).
|
|
2107
2107
|
Please commit or stash your changes before handing off a remote session.
|
|
@@ -2110,7 +2110,7 @@ You may need to manually fetch and checkout the branch:
|
|
|
2110
2110
|
git fetch origin ${l.repository.branch}
|
|
2111
2111
|
git checkout ${l.repository.branch}
|
|
2112
2112
|
|
|
2113
|
-
Error: ${Ae(d)}`)}}yield{step:"checkout-branch",status:"complete"},yield{step:"create-session",status:"in-progress"},this.logger.info("Creating new local session for handoff...");let c=await this.createSession(I,!1);yield{step:"create-session",status:"complete"},yield{step:"save-session",status:"in-progress"};let i=e.getEvents();for(let d of i)c.emit(d.type,d.data);return this.logger.info(`\u2713 Replayed ${i.length} events from remote session ${l.sessionId} into local session ${c.sessionId}`),c.emit("session.handoff",{handoffTime:new Date().toISOString(),sourceType:"remote",repository:{owner:l.repository.owner,name:l.repository.name,branch:l.repository.branch},context:`This session has been handed off from session ${l.sessionId}. This history before this point comes from the remote session. Do not assume that files or tools mentioned in the earlier history exist in the local environment, use the prior history for context only.`,summary:l.summary,remoteSessionId:l.sessionId}),await this.saveSession(c),this.logger.info(`\u2713 Local session created and saved: ${c.sessionId}`),yield{step:"save-session",status:"complete"},c}async gitFetch(e,I){let{execFile:l}=await import("node:child_process"),{promisify:n}=await import("node:util"),r=n(l);try{await r("git",["fetch","origin",I],{cwd:e,encoding:"utf8",timeout:3e4,maxBuffer:10*1024*1024})}catch(a){let s=a instanceof Error?a.message:String(a);throw new Error(`Git fetch failed: ${s}`)}}}});var j8t={};ya(j8t,{LocalSessionManager:()=>h6e});var D8t=m(()=>{"use strict";T8t()});async function*Vyr(t){let{prompt:e,abortController:I,...l}=t,n=new zy(l),r=[],a=!1,s=n.on("*",c=>{r.push(c),c.type==="session.idle"&&(a=!0)}),o={prompt:e};for(I&&(o.abortController=I),n.send(o);!a||r.length>0;){let c=r.shift();c?yield c:await new Promise(i=>setTimeout(i,10))}s()}var K8t=m(()=>{"use strict";AB()});var P8t=m(()=>{"use strict"});var
|
|
2113
|
+
Error: ${Ae(d)}`)}}yield{step:"checkout-branch",status:"complete"},yield{step:"create-session",status:"in-progress"},this.logger.info("Creating new local session for handoff...");let c=await this.createSession(I,!1);yield{step:"create-session",status:"complete"},yield{step:"save-session",status:"in-progress"};let i=e.getEvents();for(let d of i)c.emit(d.type,d.data);return this.logger.info(`\u2713 Replayed ${i.length} events from remote session ${l.sessionId} into local session ${c.sessionId}`),c.emit("session.handoff",{handoffTime:new Date().toISOString(),sourceType:"remote",repository:{owner:l.repository.owner,name:l.repository.name,branch:l.repository.branch},context:`This session has been handed off from session ${l.sessionId}. This history before this point comes from the remote session. Do not assume that files or tools mentioned in the earlier history exist in the local environment, use the prior history for context only.`,summary:l.summary,remoteSessionId:l.sessionId}),await this.saveSession(c),this.logger.info(`\u2713 Local session created and saved: ${c.sessionId}`),yield{step:"save-session",status:"complete"},c}async gitFetch(e,I){let{execFile:l}=await import("node:child_process"),{promisify:n}=await import("node:util"),r=n(l);try{await r("git",["fetch","origin",I],{cwd:e,encoding:"utf8",timeout:3e4,maxBuffer:10*1024*1024})}catch(a){let s=a instanceof Error?a.message:String(a);throw new Error(`Git fetch failed: ${s}`)}}}});var j8t={};ya(j8t,{LocalSessionManager:()=>h6e});var D8t=m(()=>{"use strict";T8t()});async function*Vyr(t){let{prompt:e,abortController:I,...l}=t,n=new zy(l),r=[],a=!1,s=n.on("*",c=>{r.push(c),c.type==="session.idle"&&(a=!0)}),o={prompt:e};for(I&&(o.abortController=I),n.send(o);!a||r.length>0;){let c=r.shift();c?yield c:await new Promise(i=>setTimeout(i,10))}s()}var K8t=m(()=>{"use strict";AB()});var P8t=m(()=>{"use strict"});var Mve=m(()=>{o6e();r6e();D8t();UZe();a6e();K8t();AB();G6e();P8t()});Mve();export{y2 as BaseLogger,rTe as CompoundLogger,GE as ConsoleLogger,RZl as DEFAULT_INTEGRATION_ID,aTe as FileLogger,K_ as INTEGRATION_ID,zy as LocalSession,_c as NoopLogger,pNe as RemoteSession,hNe as Session,X8t as SessionEventSchema,FZl as completeOrphanedToolCalls,Cw as executeHooks,v8t as getCustomAgents,j8t as internal,J2e as isDebugEnvironment,Vyr as query,Q8t as retrieveAvailableModels};
|
|
2114
2114
|
/*! Bundled license information:
|
|
2115
2115
|
|
|
2116
2116
|
react/cjs/react.production.js:
|