@sourcegraph/amp 0.0.1773416373-ge2c590 → 0.0.1773418087-gfc6b34
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/dist/main.js +9 -9
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -2559,7 +2559,7 @@ Private-MAC: `+O.digest().toHex()+`\r
|
|
|
2559
2559
|
`,V};QZ0.publicKeyToOpenSSH=function(J,Z){var Q="ssh-rsa";Z=Z||"";var Y=s9.util.createBuffer();return B_(Y,Q),jG(Y,J.e),jG(Y,J.n),Q+" "+s9.util.encode64(Y.bytes())+" "+Z};QZ0.privateKeyToOpenSSH=function(J,Z){if(!Z)return s9.pki.privateKeyToPem(J);return s9.pki.encryptRsaPrivateKey(J,Z,{legacy:!0,algorithm:"aes128"})};QZ0.getPublicKeyFingerprint=function(J,Z){Z=Z||{};var Q=Z.md||s9.md.md5.create(),Y="ssh-rsa",X=s9.util.createBuffer();B_(X,Y),jG(X,J.e),jG(X,J.n),Q.start(),Q.update(X.getBytes());var V=Q.digest();if(Z.encoding==="hex"){var K=V.toHex();if(Z.delimiter)return K.match(/.{2}/g).join(Z.delimiter);return K}else if(Z.encoding==="binary")return V.getBytes();else if(Z.encoding)throw Error('Unknown encoding "'+Z.encoding+'".');return V};function jG(J,Z){var Q=Z.toString(16);if(Q[0]>="8")Q="00"+Q;var Y=s9.util.hexToBytes(Q);J.putInt32(Y.length),J.putBytes(Y)}function B_(J,Z){J.putInt32(Z.length),J.putString(Z)}function ZZ0(){var J=s9.md.sha1.create(),Z=arguments.length;for(var Q=0;Q<Z;++Q)J.update(arguments[Q]);return J.digest()}});var Kj4=u((BE9,Vj4)=>{Vj4.exports=J5();VB();TI4();oV();RJ0();Bd();iI4();Q_();rI4();tI4();$j4();vc0();fJ0();cL();jc0();uc0();Qj4();fc0();Pc0();wc0();cJ0();JX();Ec0();Xj4();dc0();c5()});var Gj4=u((wE9,zj4)=>{zj4.exports={dc:"0.9.2342.19200300.100.1.25"}});var Kl0=u((NE9,Fj4)=>{var YZ0;Fj4.exports=W13;function W13(){var J,Z,Q,Y;if(!YZ0){YZ0=Kj4(),J=YZ0.oids;for(Z in Q=Gj4())Y=Q[Z],J[Z]==null&&(J[Z]=Y),J[Y]==null&&(J[Y]=Z)}return YZ0}});var Pd=u((OE9,Bj4)=>{var XZ0,Gl0,Rd,zl0,Uj4,qj4,Fl0;Bj4.exports=VZ0;XZ0=Kl0();Gl0={der:Dj4,pem:Wj4,txt:H13,asn1:Hj4,x509:B13};Rd=[];for(zl0 in Gl0)Uj4=Gl0[zl0],VZ0[zl0]=Rd.length,Rd.push(Uj4);VZ0.forge=VZ0.x509;qj4=Buffer.isBuffer;Fl0=Buffer.from||function(J,Z){return new Buffer(J,Z)};function VZ0(J,Z){var Q=Rd[J]||Rd[0];if(Z!=null)return Q(Z);else return Q}function Dj4(J){if(qj4(J))return J;else return Fl0(J,"binary")}function Wj4(J){var Z,Q,Y,X;J=Dj4(J).toString("base64"),Z=["-----BEGIN CERTIFICATE-----"];for(Q=0,Y=J.length;Q<Y;Q+=64)X=Q,Z.push(J.substr(X,64));return Z.push("-----END CERTIFICATE-----",""),Z.join(`\r
|
|
2560
2560
|
`)}function H13(J){var Z=Hj4(J);return"Subject\t"+Z.subject.value.map(function(Q){return Fl0(Q.value[0].value[1].value,"binary").toString("utf8")}).join("/")+`
|
|
2561
2561
|
Valid `+Z.valid.value.map(function(Q){return Q.value}).join(" - ")+`
|
|
2562
|
-
`+Wj4(J)}function Hj4(J){var Z,Q,Y,X;return Z=XZ0().asn1,J=J.toString("binary"),Q=Z.fromDer(J).value[0].value,Y=Q[0],X=Y.tagClass===Z.Class.CONTEXT_SPECIFIC&&Y.type===0&&Y.constructed,Q=Q.slice(X),{serial:Q[0],valid:Q[3],issuer:Q[2],subject:Q[4]}}function B13(J){return XZ0().pki.certificateFromAsn1(XZ0().asn1.fromDer(J.toString("binary")))}});var Nj4=u((O13)=>{O13.all=N13;O13.each=wj4;wj4.async=w13;function wj4(){var J;Ul0(arguments,J={unique:!0,ondata:function(Z){if(typeof J.$cb=="function")J.$cb(Z)}})}function w13(){var J;Ul0(arguments,J={async:!0,ondata:function(Z){if(typeof J.$cb=="function")J.$cb(void 0,Z)},onend:function(){if(typeof J.$cb=="function")J.$cb()}})}function N13(){var J;return Ul0(arguments,{ondata:J=[]}),J}function Ul0(J,Z){var Q,Y;Q=w_(),Y=J[0],Z.unique==null&&(Z.unique=!1),Z.format=Y!=null?Y:Q.der2.x509,Z.$cb=J[1]||Y,Q(Z)}});var Bl0=u((LE9,Lj4)=>{var Wl0,Oj4,ql0,Cd,Hl0,Dl0;Wl0=j0("crypto");Oj4=Kl0();ql0=Pd();Cd=Oj4().asn1;Hl0=ql0(ql0.asn1);Lj4.exports=I13;Dl0=Buffer.from||function(J,Z){return new Buffer(J,Z)};function M13(J){var Z=Wl0.createHash("sha1");return Hl0(J).subject.value.forEach(function(Q){var Y,X;if(Q=Cd.copy(Q),Y=Q.value[0].value[1],!Y.value)return;Y.type=Cd.Type.UTF8,X=Dl0(Y.value,"binary").toString("utf8"),X=X.trim().replace(/[A-Z]+/g,function(V){return V.toLowerCase()}).replace(/\s+/g," "),Y.value=Dl0(X,"utf8").toString("binary"),Z.update(Cd.toDer(Q).getBytes(),"binary")}),Ej4(Z)}function A13(J){var Z,Q;return Z=Wl0.createHash("md5"),Q=Hl0(J).subject,Z.update(Cd.toDer(Q).getBytes(),"binary"),Ej4(Z)}function Ej4(J){return J=J.digest().slice(0,4),J.writeUInt32LE(J.readUInt32BE(0),0),J.toString("hex")}function I13(J,Z){var Q=J===0?A13:M13;if(Z!=null)return Q(Z);else return Q}});var Nl0=u((ME9,Pj4)=>{var Aj4,Td,wl0,Ij4,KZ0,HB,Sd,_d;Aj4=j0("https");Td=j0("tls");wl0=Pd();Pj4.exports=jj4;jj4.inject=Rj4;Ij4=wl0(wl0.pem);KZ0=Aj4.globalAgent.options;HB=[];function jj4(J){return Rj4(J,[]),j13}function j13(J){HB.push(Ij4(J))}Sd=0;function Rj4(J,Z){if(Z)HB.length=0,HB.push.apply(HB,Z);if(J=J==="+"?2:J?1:0,J===Sd)return;switch(Sd){case 1:if(KZ0.ca===HB)delete KZ0.ca;break;case 2:if(Td.createSecureContext===Mj4)Td.createSecureContext=_d,_d=void 0}switch(Sd=J){case 1:KZ0.ca=HB;break;case 2:if(!_d)_d=Td.createSecureContext,Td.createSecureContext=Mj4}}function Mj4(J){var Z,Q,Y,X,V;if(Z=_d.apply(this,arguments),Sd===2&&!(J!=null&&J.ca))for(Q=0,X=(Y=HB).length;Q<X;++Q)V=Y[Q],Z.context.addCACert(V);return Z}});var _j4=u((Cj4,Tj4)=>{var R13=j0("stream");Cj4=Tj4.exports=Ol0;Ol0.through=Ol0;function Ol0(J,Z,Q){J=J||function(U){this.queue(U)},Z=Z||function(){this.queue(null)};var Y=!1,X=!1,V=[],K=!1,z=new R13;z.readable=z.writable=!0,z.paused=!1,z.autoDestroy=!(Q&&Q.autoDestroy===!1),z.write=function(U){return J.call(this,U),!z.paused};function G(){while(V.length&&!z.paused){var U=V.shift();if(U===null)return z.emit("end");else z.emit("data",U)}}z.queue=z.push=function(U){if(K)return z;if(U===null)K=!0;return V.push(U),G(),z},z.on("end",function(){if(z.readable=!1,!z.writable&&z.autoDestroy)process.nextTick(function(){z.destroy()})});function F(){if(z.writable=!1,Z.call(z),!z.readable&&z.autoDestroy)z.destroy()}return z.end=function(U){if(Y)return;if(Y=!0,arguments.length)z.write(U);return F(),z},z.destroy=function(){if(X)return;return X=!0,Y=!0,V.length=0,z.writable=z.readable=!1,z.emit("close"),z},z.pause=function(){if(z.paused)return;return z.paused=!0,z},z.resume=function(){if(z.paused)z.paused=!1,z.emit("resume");if(G(),!z.paused)z.emit("drain");return z},z}});var vj4=u((AE9,Sj4)=>{var P13=_j4(),C13=j0("string_decoder").StringDecoder;Sj4.exports=T13;function T13(J,Z,Q){var Y=new C13,X="",V=Q&&Q.maxLength,K=Q&&Q.trailing===!1?!1:!0;if(typeof J==="function")Z=J,J=null;if(!J)J=/\r?\n/;function z(F,U){if(Z){try{U=Z(U)}catch(q){return F.emit("error",q)}if(typeof U<"u")F.queue(U)}else F.queue(U)}function G(F,U){var q=((X!=null?X:"")+U).split(J);if(X=q.pop(),V&&X.length>V)return F.emit("error",Error("maximum buffer reached"));for(var D=0;D<q.length;D++){var W=q[D];z(F,W)}}return P13(function(F){G(this,Y.write(F))},function(){if(Y.end)G(this,Y.end());if(K&&X!=null)z(this,X);this.queue(null)})}});var Al0=u((zZ0)=>{var __dirname="/home/runner/work/amp/amp/node_modules/.pnpm/win-ca@3.5.1/node_modules/win-ca/lib",kj4,El0,yj4,GZ0,Ll0,uj4,Ml0=typeof zZ0<"u"&&zZ0||zZ0;kj4=j0("path");El0=j0("child_process");yj4=vj4();Ll0={maxBuffer:1073741824};function xj4(J){var Z;return J==null&&(J="roots.exe"),Z=GZ0,GZ0=kj4.resolve(__dirname,J),Z}xj4();Ml0.exe=xj4;Ml0.sync=_13;function _13(J){var Z,Q;return{run:V,next:Y,done:X};function Y(){if(!Z)Z=[],Q=0,V(function(K){if(K)Z.push(K)});if(Q<Z.length)return Z[Q++];Z=[]}function X(){Z=[]}function V(K){fj4(K).on("end",function(){K()}).end(El0.execFileSync(GZ0,J,Ll0))}}Ml0.async=S13;function S13(J){var Z,Q,Y;return{run:G,next:X,done:K};function X(){if(!Z)Z=[],Q=[],G(V);return Z.length?Promise.resolve(Z.shift()):Y?Promise.resolve():new Promise(function(F){Q.push(F)})}function V(F){if(Y)return;if(!F)z();else if(Q.length)Q.shift()(F);else Z.push(F)}function K(){Z=[],z()}function z(){var F,U,q,D;Y=!0;for(F=0,q=(U=Q).length;F<q;++F)D=U[F],D()}function G(F){El0.execFile(GZ0,J,Ll0,function(){}).stdout.pipe(fj4(F)).on("end",function(){F()})}}function fj4(J){return yj4(function(Z){if(Z.length)J(uj4(Z,"hex"))})}uj4=Buffer.from||function(J,Z){return new Buffer(J,Z)}});var mj4=u((FZ0)=>{var v13,bj4=typeof FZ0<"u"&&FZ0||FZ0;bj4.sync=hj4;function hj4(){return{next:function(){},done:function(){},run:function(J){return J()}}}bj4.async=v13=hj4});var dj4=u((UZ0)=>{var Il0,gj4=typeof UZ0<"u"&&UZ0||UZ0;Il0=j0("./crypt32-"+process.arch);gj4.sync=pj4;function pj4(J){var Z,Q;return Q=J.length?0:-1,{next:Y,done:X,run:V};function Y(){var K;while(Q<J.length){if(Z==null&&(Z=Q<0?Il0():Il0(J[Q])),K=Z.next())return K;Z.done(),Z=void 0,Q++}}function X(){if(Z!=null)Z.done();Z=void 0,Q=J.length}function V(K){var z;while(z=Y())K(z);K()}}gj4.async=k13;function k13(J){var Z,Q;return Z=pj4(J),Q=Z.next,Z.run=Y,Z;function Y(X){function V(){return Promise.resolve().then(Q).then(function(K){if(K)return X(K),V();X()})}V()}}});var ij4=u((CE9,lj4)=>{var cj4;cj4=j0("crypto");lj4.exports=y13;function y13(){var J=new Set;function Z(Q){var Y=cj4.createHash("sha256").update(Q).digest("base64");if(!J.has(Y))return J.add(Y),!0}return Z}});var oj4=u((TE9,aj4)=>{var nj4=(J,Z)=>function(){let Q=Z.promiseModule,Y=Array(arguments.length);for(let X=0;X<arguments.length;X++)Y[X]=arguments[X];return new Q((X,V)=>{if(Z.errorFirst)Y.push(function(K,z){if(Z.multiArgs){let G=Array(arguments.length-1);for(let F=1;F<arguments.length;F++)G[F-1]=arguments[F];if(K)G.unshift(K),V(G);else X(G)}else if(K)V(K);else X(z)});else Y.push(function(K){if(Z.multiArgs){let z=Array(arguments.length-1);for(let G=0;G<arguments.length;G++)z[G]=arguments[G];X(z)}else X(K)});J.apply(this,Y)})};aj4.exports=(J,Z)=>{Z=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},Z);let Q=(X)=>{let V=(K)=>typeof K==="string"?X===K:K.test(X);return Z.include?Z.include.some(V):!Z.exclude.some(V)},Y;if(typeof J==="function")Y=function(){if(Z.excludeMain)return J.apply(this,arguments);return nj4(J,Z).apply(this,arguments)};else Y=Object.create(Object.getPrototypeOf(J));for(let X in J){let V=J[X];Y[X]=typeof V==="function"&&Q(X)?nj4(V,Z):V}return Y}});var ej4=u((_E9,jl0)=>{var u13=j0("fs"),eL=j0("path"),rj4=oj4(),sj4={mode:511&~process.umask(),fs:u13},tj4=(J)=>{if(process.platform==="win32"){if(/[<>:"|?*]/.test(J.replace(eL.parse(J).root,""))){let Q=Error(`Path contains invalid characters: ${J}`);throw Q.code="EINVAL",Q}}};jl0.exports=(J,Z)=>Promise.resolve().then(()=>{tj4(J),Z=Object.assign({},sj4,Z);let Q=rj4(Z.fs.mkdir),Y=rj4(Z.fs.stat),X=(V)=>{return Q(V,Z.mode).then(()=>V).catch((K)=>{if(K.code==="ENOENT"){if(K.message.includes("null bytes")||eL.dirname(V)===V)throw K;return X(eL.dirname(V)).then(()=>X(V))}return Y(V).then((z)=>z.isDirectory()?V:Promise.reject()).catch(()=>{throw K})})};return X(eL.resolve(J))});jl0.exports.sync=(J,Z)=>{tj4(J),Z=Object.assign({},sj4,Z);let Q=(Y)=>{try{Z.fs.mkdirSync(Y,Z.mode)}catch(X){if(X.code==="ENOENT"){if(X.message.includes("null bytes")||eL.dirname(Y)===Y)throw X;return Q(eL.dirname(Y)),Q(Y)}try{if(!Z.fs.statSync(Y).isDirectory())throw Error("The path is not a directory")}catch(V){throw X}}return Y};return Q(eL.resolve(J))}});var GR4=u((SE9,zR4)=>{var __dirname="/home/runner/work/amp/amp/node_modules/.pnpm/win-ca@3.5.1/node_modules/win-ca/lib",kd,$R4,vd,JR4,Pl0,ZR4,QR4,YR4,XR4,VR4,KR4;kd=j0("fs");$R4=j0("os");vd=j0("path");JR4=ej4();Pl0=Pd();ZR4=Bl0();zR4.exports=x13;QR4=Pl0(Pl0.txt);YR4=ZR4();XR4=Cl0(kd.writeFile);VR4=Cl0(kd.readdir);KR4=Cl0(kd.unlink);function x13(J){var Z,Q,Y,X,V;return X={},V=new Set,K;function K(q){return Promise.resolve(q).then(z)}function z(q){if(q)Q||(Q=b13(J.save||J.$ave).then(function(D){return Z=D})),Q=Q.then(function(){if(Z)return G(q)});else if(Q)Q.then(U).then(function(){if(Y!=null)Y.end();if(Z&&J.$ave)process.env.SSL_CERT_DIR=w_().path=Z;if(typeof J.onsave=="function")J.onsave(Z)});else if(typeof J.onsave=="function")J.onsave()}function G(q){var D,W;return(Y||(Y=kd.createWriteStream(F("roots.pem")))).write(D=QR4(q)),X[W=YR4(q)]||(X[W]=0),XR4(F(W+"."+X[W]++),D).catch(Rl0)}function F(q){return V.add(q),vd.join(Z,q)}function U(){if(Z)VR4(Z).then(function(q){return Promise.all(q.filter(function(D){return!V.has(D)}).map(function(D){return vd.join(Z,D)}).map(function(D){return KR4(D).catch(Rl0)}))}).catch(Rl0)}}function f13(){return[vd.join(__dirname,"../pem"),vd.join($R4.homedir(),".local/win-ca/pem")]}function b13(J){var Z;if(typeof J==="string")J=[J];else if(!Array.isArray(J))J=f13();return Z=0,Q();function Q(){if(Z<J.length)return JR4(J[Z++]).catch(Q);else return Promise.resolve()}}function Cl0(J){return function(){var Z,Q=this;return Z=[].slice.call(arguments),new Promise(function(Y,X){Z.push(V),J.apply(Q,Z);function V(K,z){if(K)X(K);else Y(z)}})}}function Rl0(){}});var w_=u((vE9,DR4)=>{var Tl0,UR4,qR4;DR4.exports=wJ;wJ.disabled=Tl0=process.platform!=="win32";wJ.nApi=UR4=!!process.versions.napi&&wJ===w_()&&!(wJ.electron=oM4()());wJ.der2=qR4=Pd();wJ.hash=h13;wJ.inject=m13;wJ.exe=g13;p13(wJ,Nj4());if(!Tl0&&wJ===w_())wJ({inject:!0,$ave:!0,async:!0});function h13(){return(wJ.hash=Bl0()).apply(this,arguments)}function m13(){return(wJ.inject=Nl0().inject).apply(this,arguments)}function g13(){return(wJ.exe=Al0().exe).apply(this,arguments)}function wJ(J){var Z,Q,Y,X,V,K,z,G,F;if(J==null&&(J={}),Z=Tl0||J.disabled?mj4():((Q=J.fallback)!=null?Q:!UR4)?Al0():dj4(),!(Y=J.store))Y=[];else if(!Array.isArray(Y))Y=[Y];if(Z=Z[(X=J.async)?"async":"sync"](Y),V=X?q:U,J.unique!==!1)K=ij4()();if(z=qR4(J.format),Array.isArray(J.ondata))J.ondata=J.ondata.push.bind(J.ondata);if(J.save||J.$ave)G=GR4()(J);if(J.inject)F=Nl0()(J.inject);if(J.generator)return(X?W:D)();Z.run(function(O){if(!O||!K||K(O))V(O)});function U(O){if(G)G(O);if(O){if(F)F(O);if(typeof J.ondata=="function")J.ondata(z(O))}else if(typeof J.onend=="function")J.onend()}function q(O){Promise.resolve(O).then(U)}function D(){var O;return O={},O[Symbol.iterator]=FR4,O.return=B,O.next=w,O}function W(){var O,E;return O={},O[(E=Symbol.asyncIterator)!=null?E:"@"]=FR4,O.return=B,O.next=N,O}function H(O){return V(O),{done:!O,value:O!=null?z(O):O}}function B(O){return Z.done(),{done:!0,value:O}}function w(){var O;while((O=Z.next())&&K&&!K(O));return H(O)}function N(){function O(){return Promise.resolve().then(Z.next).then(function(E){if(E&&K&&!K(E))return O();else return H(E)})}return O()}}function FR4(){return this}function p13(J,Z){for(var Q in Z)J[Q]=Z[Q];return J}});import{openSync as BC4}from"node:fs";import Ti0 from"node:tty";var M5={buffer:[],stream:null,takenOver:!1};function wC4(){let J=process.versions.bun;if(!J)return!1;let Z=J.split(".").map(Number),Q=Z[0]??0,Y=Z[1]??0,X=Z[2]??0;if(!Number.isFinite(Q)||!Number.isFinite(Y)||!Number.isFinite(X))return!1;if(Q!==1||Y!==2)return!1;return X<22}function fZ0(J){J.setRawMode(!0),J.on("data",(Q)=>{M5.buffer.push(Buffer.from(Q))}),M5.stream=J;let Z=()=>{if(M5.takenOver)return;let Q=M5.stream;if(!Q)return;try{if(Q.isTTY)Q.setRawMode(!1)}catch{}try{Q.removeAllListeners("data"),Q.destroy()}catch{}M5.stream=null};process.once("exit",Z),process.once("SIGINT",Z),process.once("SIGTERM",Z)}var bZ0=process.stdin.isTTY,NC4=process.platform==="win32",OC4=wC4(),_i0=process.argv.some((J)=>J==="-x"||J==="--execute"),Si0=process.argv.some((J)=>J==="--headless"||J.startsWith("--headless=")),EC4=["usage","logout","login","mcp","review","sign-commit","update","dtw-create","dtw-curl","thread-pool-harness","thread-runtime-trace-viewer","visibility","plugins","plugin"],vi0=process.argv.some((J)=>EC4.includes(J));if(bZ0&&!NC4&&!OC4&&!_i0&&!Si0&&!vi0)try{let J=BC4("/dev/tty","r");if(Ti0.isatty(J)){let Z=new Ti0.ReadStream(J);fZ0(Z)}}catch{if(bZ0)fZ0(process.stdin)}else if(bZ0&&!_i0&&!Si0&&!vi0)fZ0(process.stdin);var JK6=process.env.AMP_ENABLE_TRACING?.trim()!=="";if(JK6)await ZK6();async function ZK6(){let[J,Z,Q,Y,X,V]=await Promise.all([Promise.resolve().then(() => D4(z4(),1)),Promise.resolve().then(() => D4(qc(),1)),Promise.resolve().then(() => D4(WY0(),1)),Promise.resolve().then(() => D4(oN1(),1)),Promise.resolve().then(() => D4(Vw(),1)),Promise.resolve().then(() => D4(Xq(),1))]);class K extends Q.InstrumentationBase{originalFetch;constructor(G={}){super("fetch-instrumentation","1.0.0",G)}init(){}enable(){this.originalFetch=globalThis.fetch;let G=this.tracer,F=this.originalFetch;globalThis.fetch=async(U,q)=>{let D=typeof U==="string"?new URL(U):U instanceof URL?U:new URL(U.url),W=q?.method||"GET";return G.startActiveSpan(`fetch ${D.pathname}${D.searchParams.size>0?"?"+D.searchParams.toString():""}`,{kind:J.SpanKind.CLIENT,attributes:{[V.ATTR_HTTP_REQUEST_METHOD]:W,[V.ATTR_URL_FULL]:D.toString()}},async(H)=>{try{let B=await F.call(globalThis,U,q);if(H.setAttribute("http.response.status_code",B.status),B.status>=400)H.setStatus({code:J.SpanStatusCode.ERROR,message:`HTTP ${B.status}`});return H.end(),B}catch(B){throw H.recordException(B instanceof Error?B:Error(String(B))),H.setStatus({code:J.SpanStatusCode.ERROR,message:B instanceof Error?B.message:String(B)}),H.end(),B}})}}disable(){if(this.originalFetch)globalThis.fetch=this.originalFetch}}new Y.NodeSDK({serviceName:"amp.cli",sampler:new X.AlwaysOnSampler,contextManager:new Z.AsyncLocalStorageContextManager,instrumentations:[new K],metricReader:void 0}).start()}import{spawn as WR4}from"node:child_process";import{randomBytes as d13}from"node:crypto";import{mkdir as MR4,readFile as AR4,writeFile as c13}from"node:fs/promises";import IR4 from"node:os";import BB from"node:path";import{stderr as E7,stdout as p6}from"node:process";import{Readable as l13}from"node:stream";import{pipeline as i13}from"node:stream/promises";da();h0();_4();var SD6=5,fI1=500;function bI1(J){if(!J)return[];return J.filter((Z)=>Z.role==="user").slice(-SD6).map((Z)=>{let Q=w9(Z.content);if(Q.length>fI1)return Q.slice(0,fI1)+"...";return Q}).filter((Z)=>Z.length>0)}var vD6=60;class Fw0{deps;constructor(J){this.deps=J}getRelativePath(J){for(let Z of this.deps.workspaceRoots)if(Y1.hasPrefix(J,Z)){let Q=Y1.relativePath(Z,J);if(Q)return Q}if(this.deps.workspaceRoots.length===0)return J.path.startsWith("/")?J.path.slice(1):J.path;return null}async getCurrentFile(){let J=this.deps.getCurrentFile?.();if(!J)return[];let Z=this.getRelativePath(J);return Z?[Z]:[]}async getOpenFiles(){let J=this.deps.getOpenFiles?.()??[],Z=this.deps.getCurrentFile?.(),Q=J.filter((X)=>!Z||!Y1.equalURIs(X,Z)).slice(0,vD6),Y=new Set;for(let X of Q){let V=this.getRelativePath(X);if(V)Y.add(V)}return Array.from(Y)}getRecentUserMessagesFromThread(J){return bI1(J?.messages)}async getContext(J){let[Z,Q]=await Promise.all([this.getCurrentFile(),this.getOpenFiles()]),Y=this.getRecentUserMessagesFromThread(J),X=await this.getDependencies(),V={threadId:J?.id,currentFile:Z,openFilesContext:Q,recentUserMessages:Y.length>0?Y:void 0,dependencies:X.length>0?X:void 0};return j.debug("[Ads] Collected codebase context",{currentFile:Z,openFilesContext:Q.slice(0,10),recentUserMessagesCount:Y.length,dependencyCount:X.length}),V}async getDependencies(){let J=this.deps.fileSystem;if(!J)return[];let Z=this.deps.workspaceRoots[0];if(!Z)return[];let Q=new Set,Y=(X)=>{if(!X||typeof X!=="object"||Array.isArray(X))return;for(let V of Object.keys(X))if(V)Q.add(V)};try{let X=await J.readFile(Y1.joinPath(Z,"package.json")),V=JSON.parse(X);Y(V.dependencies),Y(V.devDependencies),Y(V.peerDependencies),Y(V.optionalDependencies)}catch{}return[...Q]}}V4();h0();import{exec as kD6}from"node:child_process";import{platform as yD6}from"node:os";import{promisify as uD6}from"node:util";function qw0(J){if(J.startsWith("file://"))return K1.parse(J).fsPath;return J}var Uw0=uD6(kD6);async function fX(J,Z){try{let Q=yD6(),Y={timeout:5000,signal:Z};switch(Q){case"win32":await Uw0(`start "" "${J}"`,Y);break;case"darwin":await Uw0(`open "${J}"`,Y);break;default:await Uw0(`xdg-open "${J}"`,Y);break}j.info("Opened browser with auth URL",{url:J})}catch(Q){throw j.error("Failed to open browser",{error:Q}),Q}}ZY();class c1 extends Error{userMessage;exitCode;suggestion;constructor(J,Z=1,Q){super(J);this.userMessage=J;this.exitCode=Z;this.suggestion=Q;this.name="AmpError"}}aw();h0();e9();zI();H1();import rD6 from"node:fs";import sD6 from"node:os";function ak(J,Z=!1){let Q=J.length,Y=0,X="",V=0,K=16,z=0,G=0,F=0,U=0,q=0;function D(E,L){let M=0,A=0;while(M<E||!L){let I=J.charCodeAt(Y);if(I>=48&&I<=57)A=A*16+I-48;else if(I>=65&&I<=70)A=A*16+I-65+10;else if(I>=97&&I<=102)A=A*16+I-97+10;else break;Y++,M++}if(M<E)A=-1;return A}function W(E){Y=E,X="",V=0,K=16,q=0}function H(){let E=Y;if(J.charCodeAt(Y)===48)Y++;else{Y++;while(Y<J.length&&MI(J.charCodeAt(Y)))Y++}if(Y<J.length&&J.charCodeAt(Y)===46)if(Y++,Y<J.length&&MI(J.charCodeAt(Y))){Y++;while(Y<J.length&&MI(J.charCodeAt(Y)))Y++}else return q=3,J.substring(E,Y);let L=Y;if(Y<J.length&&(J.charCodeAt(Y)===69||J.charCodeAt(Y)===101)){if(Y++,Y<J.length&&J.charCodeAt(Y)===43||J.charCodeAt(Y)===45)Y++;if(Y<J.length&&MI(J.charCodeAt(Y))){Y++;while(Y<J.length&&MI(J.charCodeAt(Y)))Y++;L=Y}else q=3}return J.substring(E,L)}function B(){let E="",L=Y;while(!0){if(Y>=Q){E+=J.substring(L,Y),q=2;break}let M=J.charCodeAt(Y);if(M===34){E+=J.substring(L,Y),Y++;break}if(M===92){if(E+=J.substring(L,Y),Y++,Y>=Q){q=2;break}switch(J.charCodeAt(Y++)){case 34:E+='"';break;case 92:E+="\\";break;case 47:E+="/";break;case 98:E+="\b";break;case 102:E+="\f";break;case 110:E+=`
|
|
2562
|
+
`+Wj4(J)}function Hj4(J){var Z,Q,Y,X;return Z=XZ0().asn1,J=J.toString("binary"),Q=Z.fromDer(J).value[0].value,Y=Q[0],X=Y.tagClass===Z.Class.CONTEXT_SPECIFIC&&Y.type===0&&Y.constructed,Q=Q.slice(X),{serial:Q[0],valid:Q[3],issuer:Q[2],subject:Q[4]}}function B13(J){return XZ0().pki.certificateFromAsn1(XZ0().asn1.fromDer(J.toString("binary")))}});var Nj4=u((O13)=>{O13.all=N13;O13.each=wj4;wj4.async=w13;function wj4(){var J;Ul0(arguments,J={unique:!0,ondata:function(Z){if(typeof J.$cb=="function")J.$cb(Z)}})}function w13(){var J;Ul0(arguments,J={async:!0,ondata:function(Z){if(typeof J.$cb=="function")J.$cb(void 0,Z)},onend:function(){if(typeof J.$cb=="function")J.$cb()}})}function N13(){var J;return Ul0(arguments,{ondata:J=[]}),J}function Ul0(J,Z){var Q,Y;Q=w_(),Y=J[0],Z.unique==null&&(Z.unique=!1),Z.format=Y!=null?Y:Q.der2.x509,Z.$cb=J[1]||Y,Q(Z)}});var Bl0=u((LE9,Lj4)=>{var Wl0,Oj4,ql0,Cd,Hl0,Dl0;Wl0=j0("crypto");Oj4=Kl0();ql0=Pd();Cd=Oj4().asn1;Hl0=ql0(ql0.asn1);Lj4.exports=I13;Dl0=Buffer.from||function(J,Z){return new Buffer(J,Z)};function M13(J){var Z=Wl0.createHash("sha1");return Hl0(J).subject.value.forEach(function(Q){var Y,X;if(Q=Cd.copy(Q),Y=Q.value[0].value[1],!Y.value)return;Y.type=Cd.Type.UTF8,X=Dl0(Y.value,"binary").toString("utf8"),X=X.trim().replace(/[A-Z]+/g,function(V){return V.toLowerCase()}).replace(/\s+/g," "),Y.value=Dl0(X,"utf8").toString("binary"),Z.update(Cd.toDer(Q).getBytes(),"binary")}),Ej4(Z)}function A13(J){var Z,Q;return Z=Wl0.createHash("md5"),Q=Hl0(J).subject,Z.update(Cd.toDer(Q).getBytes(),"binary"),Ej4(Z)}function Ej4(J){return J=J.digest().slice(0,4),J.writeUInt32LE(J.readUInt32BE(0),0),J.toString("hex")}function I13(J,Z){var Q=J===0?A13:M13;if(Z!=null)return Q(Z);else return Q}});var Nl0=u((ME9,Pj4)=>{var Aj4,Td,wl0,Ij4,KZ0,HB,Sd,_d;Aj4=j0("https");Td=j0("tls");wl0=Pd();Pj4.exports=jj4;jj4.inject=Rj4;Ij4=wl0(wl0.pem);KZ0=Aj4.globalAgent.options;HB=[];function jj4(J){return Rj4(J,[]),j13}function j13(J){HB.push(Ij4(J))}Sd=0;function Rj4(J,Z){if(Z)HB.length=0,HB.push.apply(HB,Z);if(J=J==="+"?2:J?1:0,J===Sd)return;switch(Sd){case 1:if(KZ0.ca===HB)delete KZ0.ca;break;case 2:if(Td.createSecureContext===Mj4)Td.createSecureContext=_d,_d=void 0}switch(Sd=J){case 1:KZ0.ca=HB;break;case 2:if(!_d)_d=Td.createSecureContext,Td.createSecureContext=Mj4}}function Mj4(J){var Z,Q,Y,X,V;if(Z=_d.apply(this,arguments),Sd===2&&!(J!=null&&J.ca))for(Q=0,X=(Y=HB).length;Q<X;++Q)V=Y[Q],Z.context.addCACert(V);return Z}});var _j4=u((Cj4,Tj4)=>{var R13=j0("stream");Cj4=Tj4.exports=Ol0;Ol0.through=Ol0;function Ol0(J,Z,Q){J=J||function(U){this.queue(U)},Z=Z||function(){this.queue(null)};var Y=!1,X=!1,V=[],K=!1,z=new R13;z.readable=z.writable=!0,z.paused=!1,z.autoDestroy=!(Q&&Q.autoDestroy===!1),z.write=function(U){return J.call(this,U),!z.paused};function G(){while(V.length&&!z.paused){var U=V.shift();if(U===null)return z.emit("end");else z.emit("data",U)}}z.queue=z.push=function(U){if(K)return z;if(U===null)K=!0;return V.push(U),G(),z},z.on("end",function(){if(z.readable=!1,!z.writable&&z.autoDestroy)process.nextTick(function(){z.destroy()})});function F(){if(z.writable=!1,Z.call(z),!z.readable&&z.autoDestroy)z.destroy()}return z.end=function(U){if(Y)return;if(Y=!0,arguments.length)z.write(U);return F(),z},z.destroy=function(){if(X)return;return X=!0,Y=!0,V.length=0,z.writable=z.readable=!1,z.emit("close"),z},z.pause=function(){if(z.paused)return;return z.paused=!0,z},z.resume=function(){if(z.paused)z.paused=!1,z.emit("resume");if(G(),!z.paused)z.emit("drain");return z},z}});var vj4=u((AE9,Sj4)=>{var P13=_j4(),C13=j0("string_decoder").StringDecoder;Sj4.exports=T13;function T13(J,Z,Q){var Y=new C13,X="",V=Q&&Q.maxLength,K=Q&&Q.trailing===!1?!1:!0;if(typeof J==="function")Z=J,J=null;if(!J)J=/\r?\n/;function z(F,U){if(Z){try{U=Z(U)}catch(q){return F.emit("error",q)}if(typeof U<"u")F.queue(U)}else F.queue(U)}function G(F,U){var q=((X!=null?X:"")+U).split(J);if(X=q.pop(),V&&X.length>V)return F.emit("error",Error("maximum buffer reached"));for(var D=0;D<q.length;D++){var W=q[D];z(F,W)}}return P13(function(F){G(this,Y.write(F))},function(){if(Y.end)G(this,Y.end());if(K&&X!=null)z(this,X);this.queue(null)})}});var Al0=u((zZ0)=>{var __dirname="/home/runner/work/amp/amp/node_modules/.pnpm/win-ca@3.5.1/node_modules/win-ca/lib",kj4,El0,yj4,GZ0,Ll0,uj4,Ml0=typeof zZ0<"u"&&zZ0||zZ0;kj4=j0("path");El0=j0("child_process");yj4=vj4();Ll0={maxBuffer:1073741824};function xj4(J){var Z;return J==null&&(J="roots.exe"),Z=GZ0,GZ0=kj4.resolve(__dirname,J),Z}xj4();Ml0.exe=xj4;Ml0.sync=_13;function _13(J){var Z,Q;return{run:V,next:Y,done:X};function Y(){if(!Z)Z=[],Q=0,V(function(K){if(K)Z.push(K)});if(Q<Z.length)return Z[Q++];Z=[]}function X(){Z=[]}function V(K){fj4(K).on("end",function(){K()}).end(El0.execFileSync(GZ0,J,Ll0))}}Ml0.async=S13;function S13(J){var Z,Q,Y;return{run:G,next:X,done:K};function X(){if(!Z)Z=[],Q=[],G(V);return Z.length?Promise.resolve(Z.shift()):Y?Promise.resolve():new Promise(function(F){Q.push(F)})}function V(F){if(Y)return;if(!F)z();else if(Q.length)Q.shift()(F);else Z.push(F)}function K(){Z=[],z()}function z(){var F,U,q,D;Y=!0;for(F=0,q=(U=Q).length;F<q;++F)D=U[F],D()}function G(F){El0.execFile(GZ0,J,Ll0,function(){}).stdout.pipe(fj4(F)).on("end",function(){F()})}}function fj4(J){return yj4(function(Z){if(Z.length)J(uj4(Z,"hex"))})}uj4=Buffer.from||function(J,Z){return new Buffer(J,Z)}});var mj4=u((FZ0)=>{var v13,bj4=typeof FZ0<"u"&&FZ0||FZ0;bj4.sync=hj4;function hj4(){return{next:function(){},done:function(){},run:function(J){return J()}}}bj4.async=v13=hj4});var dj4=u((UZ0)=>{var Il0,gj4=typeof UZ0<"u"&&UZ0||UZ0;Il0=j0("./crypt32-"+process.arch);gj4.sync=pj4;function pj4(J){var Z,Q;return Q=J.length?0:-1,{next:Y,done:X,run:V};function Y(){var K;while(Q<J.length){if(Z==null&&(Z=Q<0?Il0():Il0(J[Q])),K=Z.next())return K;Z.done(),Z=void 0,Q++}}function X(){if(Z!=null)Z.done();Z=void 0,Q=J.length}function V(K){var z;while(z=Y())K(z);K()}}gj4.async=k13;function k13(J){var Z,Q;return Z=pj4(J),Q=Z.next,Z.run=Y,Z;function Y(X){function V(){return Promise.resolve().then(Q).then(function(K){if(K)return X(K),V();X()})}V()}}});var ij4=u((CE9,lj4)=>{var cj4;cj4=j0("crypto");lj4.exports=y13;function y13(){var J=new Set;function Z(Q){var Y=cj4.createHash("sha256").update(Q).digest("base64");if(!J.has(Y))return J.add(Y),!0}return Z}});var oj4=u((TE9,aj4)=>{var nj4=(J,Z)=>function(){let Q=Z.promiseModule,Y=Array(arguments.length);for(let X=0;X<arguments.length;X++)Y[X]=arguments[X];return new Q((X,V)=>{if(Z.errorFirst)Y.push(function(K,z){if(Z.multiArgs){let G=Array(arguments.length-1);for(let F=1;F<arguments.length;F++)G[F-1]=arguments[F];if(K)G.unshift(K),V(G);else X(G)}else if(K)V(K);else X(z)});else Y.push(function(K){if(Z.multiArgs){let z=Array(arguments.length-1);for(let G=0;G<arguments.length;G++)z[G]=arguments[G];X(z)}else X(K)});J.apply(this,Y)})};aj4.exports=(J,Z)=>{Z=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},Z);let Q=(X)=>{let V=(K)=>typeof K==="string"?X===K:K.test(X);return Z.include?Z.include.some(V):!Z.exclude.some(V)},Y;if(typeof J==="function")Y=function(){if(Z.excludeMain)return J.apply(this,arguments);return nj4(J,Z).apply(this,arguments)};else Y=Object.create(Object.getPrototypeOf(J));for(let X in J){let V=J[X];Y[X]=typeof V==="function"&&Q(X)?nj4(V,Z):V}return Y}});var ej4=u((_E9,jl0)=>{var u13=j0("fs"),eL=j0("path"),rj4=oj4(),sj4={mode:511&~process.umask(),fs:u13},tj4=(J)=>{if(process.platform==="win32"){if(/[<>:"|?*]/.test(J.replace(eL.parse(J).root,""))){let Q=Error(`Path contains invalid characters: ${J}`);throw Q.code="EINVAL",Q}}};jl0.exports=(J,Z)=>Promise.resolve().then(()=>{tj4(J),Z=Object.assign({},sj4,Z);let Q=rj4(Z.fs.mkdir),Y=rj4(Z.fs.stat),X=(V)=>{return Q(V,Z.mode).then(()=>V).catch((K)=>{if(K.code==="ENOENT"){if(K.message.includes("null bytes")||eL.dirname(V)===V)throw K;return X(eL.dirname(V)).then(()=>X(V))}return Y(V).then((z)=>z.isDirectory()?V:Promise.reject()).catch(()=>{throw K})})};return X(eL.resolve(J))});jl0.exports.sync=(J,Z)=>{tj4(J),Z=Object.assign({},sj4,Z);let Q=(Y)=>{try{Z.fs.mkdirSync(Y,Z.mode)}catch(X){if(X.code==="ENOENT"){if(X.message.includes("null bytes")||eL.dirname(Y)===Y)throw X;return Q(eL.dirname(Y)),Q(Y)}try{if(!Z.fs.statSync(Y).isDirectory())throw Error("The path is not a directory")}catch(V){throw X}}return Y};return Q(eL.resolve(J))}});var GR4=u((SE9,zR4)=>{var __dirname="/home/runner/work/amp/amp/node_modules/.pnpm/win-ca@3.5.1/node_modules/win-ca/lib",kd,$R4,vd,JR4,Pl0,ZR4,QR4,YR4,XR4,VR4,KR4;kd=j0("fs");$R4=j0("os");vd=j0("path");JR4=ej4();Pl0=Pd();ZR4=Bl0();zR4.exports=x13;QR4=Pl0(Pl0.txt);YR4=ZR4();XR4=Cl0(kd.writeFile);VR4=Cl0(kd.readdir);KR4=Cl0(kd.unlink);function x13(J){var Z,Q,Y,X,V;return X={},V=new Set,K;function K(q){return Promise.resolve(q).then(z)}function z(q){if(q)Q||(Q=b13(J.save||J.$ave).then(function(D){return Z=D})),Q=Q.then(function(){if(Z)return G(q)});else if(Q)Q.then(U).then(function(){if(Y!=null)Y.end();if(Z&&J.$ave)process.env.SSL_CERT_DIR=w_().path=Z;if(typeof J.onsave=="function")J.onsave(Z)});else if(typeof J.onsave=="function")J.onsave()}function G(q){var D,W;return(Y||(Y=kd.createWriteStream(F("roots.pem")))).write(D=QR4(q)),X[W=YR4(q)]||(X[W]=0),XR4(F(W+"."+X[W]++),D).catch(Rl0)}function F(q){return V.add(q),vd.join(Z,q)}function U(){if(Z)VR4(Z).then(function(q){return Promise.all(q.filter(function(D){return!V.has(D)}).map(function(D){return vd.join(Z,D)}).map(function(D){return KR4(D).catch(Rl0)}))}).catch(Rl0)}}function f13(){return[vd.join(__dirname,"../pem"),vd.join($R4.homedir(),".local/win-ca/pem")]}function b13(J){var Z;if(typeof J==="string")J=[J];else if(!Array.isArray(J))J=f13();return Z=0,Q();function Q(){if(Z<J.length)return JR4(J[Z++]).catch(Q);else return Promise.resolve()}}function Cl0(J){return function(){var Z,Q=this;return Z=[].slice.call(arguments),new Promise(function(Y,X){Z.push(V),J.apply(Q,Z);function V(K,z){if(K)X(K);else Y(z)}})}}function Rl0(){}});var w_=u((vE9,DR4)=>{var Tl0,UR4,qR4;DR4.exports=wJ;wJ.disabled=Tl0=process.platform!=="win32";wJ.nApi=UR4=!!process.versions.napi&&wJ===w_()&&!(wJ.electron=oM4()());wJ.der2=qR4=Pd();wJ.hash=h13;wJ.inject=m13;wJ.exe=g13;p13(wJ,Nj4());if(!Tl0&&wJ===w_())wJ({inject:!0,$ave:!0,async:!0});function h13(){return(wJ.hash=Bl0()).apply(this,arguments)}function m13(){return(wJ.inject=Nl0().inject).apply(this,arguments)}function g13(){return(wJ.exe=Al0().exe).apply(this,arguments)}function wJ(J){var Z,Q,Y,X,V,K,z,G,F;if(J==null&&(J={}),Z=Tl0||J.disabled?mj4():((Q=J.fallback)!=null?Q:!UR4)?Al0():dj4(),!(Y=J.store))Y=[];else if(!Array.isArray(Y))Y=[Y];if(Z=Z[(X=J.async)?"async":"sync"](Y),V=X?q:U,J.unique!==!1)K=ij4()();if(z=qR4(J.format),Array.isArray(J.ondata))J.ondata=J.ondata.push.bind(J.ondata);if(J.save||J.$ave)G=GR4()(J);if(J.inject)F=Nl0()(J.inject);if(J.generator)return(X?W:D)();Z.run(function(O){if(!O||!K||K(O))V(O)});function U(O){if(G)G(O);if(O){if(F)F(O);if(typeof J.ondata=="function")J.ondata(z(O))}else if(typeof J.onend=="function")J.onend()}function q(O){Promise.resolve(O).then(U)}function D(){var O;return O={},O[Symbol.iterator]=FR4,O.return=B,O.next=w,O}function W(){var O,E;return O={},O[(E=Symbol.asyncIterator)!=null?E:"@"]=FR4,O.return=B,O.next=N,O}function H(O){return V(O),{done:!O,value:O!=null?z(O):O}}function B(O){return Z.done(),{done:!0,value:O}}function w(){var O;while((O=Z.next())&&K&&!K(O));return H(O)}function N(){function O(){return Promise.resolve().then(Z.next).then(function(E){if(E&&K&&!K(E))return O();else return H(E)})}return O()}}function FR4(){return this}function p13(J,Z){for(var Q in Z)J[Q]=Z[Q];return J}});import{openSync as BC4}from"node:fs";import Ti0 from"node:tty";var M5={buffer:[],stream:null,takenOver:!1};function wC4(){let J=process.versions.bun;if(!J)return!1;let Z=J.split(".").map(Number),Q=Z[0]??0,Y=Z[1]??0,X=Z[2]??0;if(!Number.isFinite(Q)||!Number.isFinite(Y)||!Number.isFinite(X))return!1;if(Q!==1||Y!==2)return!1;return X<22}function fZ0(J){J.setRawMode(!0),J.on("data",(Q)=>{M5.buffer.push(Buffer.from(Q))}),M5.stream=J;let Z=()=>{if(M5.takenOver)return;let Q=M5.stream;if(!Q)return;try{if(Q.isTTY)Q.setRawMode(!1)}catch{}try{Q.removeAllListeners("data"),Q.destroy()}catch{}M5.stream=null};process.once("exit",Z),process.once("SIGINT",Z),process.once("SIGTERM",Z)}var bZ0=process.stdin.isTTY,NC4=process.platform==="win32",OC4=wC4(),_i0=process.argv.some((J)=>J==="-x"||J==="--execute"),Si0=process.argv.some((J)=>J==="--headless"||J.startsWith("--headless=")),EC4=["usage","logout","login","mcp","review","sign-commit","update","dtw-create","dtw-curl","thread-pool-harness","thread-runtime-trace-viewer","visibility","plugins","plugin"],vi0=process.argv.some((J)=>EC4.includes(J));if(bZ0&&!NC4&&!OC4&&!_i0&&!Si0&&!vi0)try{let J=BC4("/dev/tty","r");if(Ti0.isatty(J)){let Z=new Ti0.ReadStream(J);fZ0(Z)}}catch{if(bZ0)fZ0(process.stdin)}else if(bZ0&&!_i0&&!Si0&&!vi0)fZ0(process.stdin);var JK6=Boolean(process.env.AMP_ENABLE_TRACING?.trim());if(JK6)await ZK6();async function ZK6(){let[J,Z,Q,Y,X,V]=await Promise.all([Promise.resolve().then(() => D4(z4(),1)),Promise.resolve().then(() => D4(qc(),1)),Promise.resolve().then(() => D4(WY0(),1)),Promise.resolve().then(() => D4(oN1(),1)),Promise.resolve().then(() => D4(Vw(),1)),Promise.resolve().then(() => D4(Xq(),1))]);class K extends Q.InstrumentationBase{originalFetch;constructor(G={}){super("fetch-instrumentation","1.0.0",G)}init(){}enable(){this.originalFetch=globalThis.fetch;let G=this.tracer,F=this.originalFetch;globalThis.fetch=async(U,q)=>{let D=typeof U==="string"?new URL(U):U instanceof URL?U:new URL(U.url),W=q?.method||"GET";return G.startActiveSpan(`fetch ${D.pathname}${D.searchParams.size>0?"?"+D.searchParams.toString():""}`,{kind:J.SpanKind.CLIENT,attributes:{[V.ATTR_HTTP_REQUEST_METHOD]:W,[V.ATTR_URL_FULL]:D.toString()}},async(H)=>{try{let B=await F.call(globalThis,U,q);if(H.setAttribute("http.response.status_code",B.status),B.status>=400)H.setStatus({code:J.SpanStatusCode.ERROR,message:`HTTP ${B.status}`});return H.end(),B}catch(B){throw H.recordException(B instanceof Error?B:Error(String(B))),H.setStatus({code:J.SpanStatusCode.ERROR,message:B instanceof Error?B.message:String(B)}),H.end(),B}})}}disable(){if(this.originalFetch)globalThis.fetch=this.originalFetch}}new Y.NodeSDK({serviceName:"amp.cli",sampler:new X.AlwaysOnSampler,contextManager:new Z.AsyncLocalStorageContextManager,instrumentations:[new K],metricReader:void 0}).start()}import{spawn as WR4}from"node:child_process";import{randomBytes as d13}from"node:crypto";import{mkdir as MR4,readFile as AR4,writeFile as c13}from"node:fs/promises";import IR4 from"node:os";import BB from"node:path";import{stderr as E7,stdout as p6}from"node:process";import{Readable as l13}from"node:stream";import{pipeline as i13}from"node:stream/promises";da();h0();_4();var SD6=5,fI1=500;function bI1(J){if(!J)return[];return J.filter((Z)=>Z.role==="user").slice(-SD6).map((Z)=>{let Q=w9(Z.content);if(Q.length>fI1)return Q.slice(0,fI1)+"...";return Q}).filter((Z)=>Z.length>0)}var vD6=60;class Fw0{deps;constructor(J){this.deps=J}getRelativePath(J){for(let Z of this.deps.workspaceRoots)if(Y1.hasPrefix(J,Z)){let Q=Y1.relativePath(Z,J);if(Q)return Q}if(this.deps.workspaceRoots.length===0)return J.path.startsWith("/")?J.path.slice(1):J.path;return null}async getCurrentFile(){let J=this.deps.getCurrentFile?.();if(!J)return[];let Z=this.getRelativePath(J);return Z?[Z]:[]}async getOpenFiles(){let J=this.deps.getOpenFiles?.()??[],Z=this.deps.getCurrentFile?.(),Q=J.filter((X)=>!Z||!Y1.equalURIs(X,Z)).slice(0,vD6),Y=new Set;for(let X of Q){let V=this.getRelativePath(X);if(V)Y.add(V)}return Array.from(Y)}getRecentUserMessagesFromThread(J){return bI1(J?.messages)}async getContext(J){let[Z,Q]=await Promise.all([this.getCurrentFile(),this.getOpenFiles()]),Y=this.getRecentUserMessagesFromThread(J),X=await this.getDependencies(),V={threadId:J?.id,currentFile:Z,openFilesContext:Q,recentUserMessages:Y.length>0?Y:void 0,dependencies:X.length>0?X:void 0};return j.debug("[Ads] Collected codebase context",{currentFile:Z,openFilesContext:Q.slice(0,10),recentUserMessagesCount:Y.length,dependencyCount:X.length}),V}async getDependencies(){let J=this.deps.fileSystem;if(!J)return[];let Z=this.deps.workspaceRoots[0];if(!Z)return[];let Q=new Set,Y=(X)=>{if(!X||typeof X!=="object"||Array.isArray(X))return;for(let V of Object.keys(X))if(V)Q.add(V)};try{let X=await J.readFile(Y1.joinPath(Z,"package.json")),V=JSON.parse(X);Y(V.dependencies),Y(V.devDependencies),Y(V.peerDependencies),Y(V.optionalDependencies)}catch{}return[...Q]}}V4();h0();import{exec as kD6}from"node:child_process";import{platform as yD6}from"node:os";import{promisify as uD6}from"node:util";function qw0(J){if(J.startsWith("file://"))return K1.parse(J).fsPath;return J}var Uw0=uD6(kD6);async function fX(J,Z){try{let Q=yD6(),Y={timeout:5000,signal:Z};switch(Q){case"win32":await Uw0(`start "" "${J}"`,Y);break;case"darwin":await Uw0(`open "${J}"`,Y);break;default:await Uw0(`xdg-open "${J}"`,Y);break}j.info("Opened browser with auth URL",{url:J})}catch(Q){throw j.error("Failed to open browser",{error:Q}),Q}}ZY();class c1 extends Error{userMessage;exitCode;suggestion;constructor(J,Z=1,Q){super(J);this.userMessage=J;this.exitCode=Z;this.suggestion=Q;this.name="AmpError"}}aw();h0();e9();zI();H1();import rD6 from"node:fs";import sD6 from"node:os";function ak(J,Z=!1){let Q=J.length,Y=0,X="",V=0,K=16,z=0,G=0,F=0,U=0,q=0;function D(E,L){let M=0,A=0;while(M<E||!L){let I=J.charCodeAt(Y);if(I>=48&&I<=57)A=A*16+I-48;else if(I>=65&&I<=70)A=A*16+I-65+10;else if(I>=97&&I<=102)A=A*16+I-97+10;else break;Y++,M++}if(M<E)A=-1;return A}function W(E){Y=E,X="",V=0,K=16,q=0}function H(){let E=Y;if(J.charCodeAt(Y)===48)Y++;else{Y++;while(Y<J.length&&MI(J.charCodeAt(Y)))Y++}if(Y<J.length&&J.charCodeAt(Y)===46)if(Y++,Y<J.length&&MI(J.charCodeAt(Y))){Y++;while(Y<J.length&&MI(J.charCodeAt(Y)))Y++}else return q=3,J.substring(E,Y);let L=Y;if(Y<J.length&&(J.charCodeAt(Y)===69||J.charCodeAt(Y)===101)){if(Y++,Y<J.length&&J.charCodeAt(Y)===43||J.charCodeAt(Y)===45)Y++;if(Y<J.length&&MI(J.charCodeAt(Y))){Y++;while(Y<J.length&&MI(J.charCodeAt(Y)))Y++;L=Y}else q=3}return J.substring(E,L)}function B(){let E="",L=Y;while(!0){if(Y>=Q){E+=J.substring(L,Y),q=2;break}let M=J.charCodeAt(Y);if(M===34){E+=J.substring(L,Y),Y++;break}if(M===92){if(E+=J.substring(L,Y),Y++,Y>=Q){q=2;break}switch(J.charCodeAt(Y++)){case 34:E+='"';break;case 92:E+="\\";break;case 47:E+="/";break;case 98:E+="\b";break;case 102:E+="\f";break;case 110:E+=`
|
|
2563
2563
|
`;break;case 114:E+="\r";break;case 116:E+="\t";break;case 117:let I=D(4,!0);if(I>=0)E+=String.fromCharCode(I);else q=4;break;default:q=5}L=Y;continue}if(M>=0&&M<=31)if(nk(M)){E+=J.substring(L,Y),q=2;break}else q=6;Y++}return E}function w(){if(X="",q=0,V=Y,G=z,U=F,Y>=Q)return V=Q,K=17;let E=J.charCodeAt(Y);if(Dw0(E)){do Y++,X+=String.fromCharCode(E),E=J.charCodeAt(Y);while(Dw0(E));return K=15}if(nk(E)){if(Y++,X+=String.fromCharCode(E),E===13&&J.charCodeAt(Y)===10)Y++,X+=`
|
|
2564
2564
|
`;return z++,F=Y,K=14}switch(E){case 123:return Y++,K=1;case 125:return Y++,K=2;case 91:return Y++,K=3;case 93:return Y++,K=4;case 58:return Y++,K=6;case 44:return Y++,K=5;case 34:return Y++,X=B(),K=10;case 47:let L=Y-1;if(J.charCodeAt(Y+1)===47){Y+=2;while(Y<Q){if(nk(J.charCodeAt(Y)))break;Y++}return X=J.substring(L,Y),K=12}if(J.charCodeAt(Y+1)===42){Y+=2;let M=Q-1,A=!1;while(Y<M){let I=J.charCodeAt(Y);if(I===42&&J.charCodeAt(Y+1)===47){Y+=2,A=!0;break}if(Y++,nk(I)){if(I===13&&J.charCodeAt(Y)===10)Y++;z++,F=Y}}if(!A)Y++,q=1;return X=J.substring(L,Y),K=13}return X+=String.fromCharCode(E),Y++,K=16;case 45:if(X+=String.fromCharCode(E),Y++,Y===Q||!MI(J.charCodeAt(Y)))return K=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return X+=H(),K=11;default:while(Y<Q&&N(E))Y++,E=J.charCodeAt(Y);if(V!==Y){switch(X=J.substring(V,Y),X){case"true":return K=8;case"false":return K=9;case"null":return K=7}return K=16}return X+=String.fromCharCode(E),Y++,K=16}}function N(E){if(Dw0(E)||nk(E))return!1;switch(E){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function O(){let E;do E=w();while(E>=12&&E<=15);return E}return{setPosition:W,getPosition:()=>Y,scan:Z?O:w,getToken:()=>K,getTokenValue:()=>X,getTokenOffset:()=>V,getTokenLength:()=>Y-V,getTokenStartLine:()=>G,getTokenStartCharacter:()=>V-U,getTokenError:()=>q}}function Dw0(J){return J===32||J===9}function nk(J){return J===10||J===13}function MI(J){return J>=48&&J<=57}var pI1;(function(J){J[J.lineFeed=10]="lineFeed",J[J.carriageReturn=13]="carriageReturn",J[J.space=32]="space",J[J._0=48]="_0",J[J._1=49]="_1",J[J._2=50]="_2",J[J._3=51]="_3",J[J._4=52]="_4",J[J._5=53]="_5",J[J._6=54]="_6",J[J._7=55]="_7",J[J._8=56]="_8",J[J._9=57]="_9",J[J.a=97]="a",J[J.b=98]="b",J[J.c=99]="c",J[J.d=100]="d",J[J.e=101]="e",J[J.f=102]="f",J[J.g=103]="g",J[J.h=104]="h",J[J.i=105]="i",J[J.j=106]="j",J[J.k=107]="k",J[J.l=108]="l",J[J.m=109]="m",J[J.n=110]="n",J[J.o=111]="o",J[J.p=112]="p",J[J.q=113]="q",J[J.r=114]="r",J[J.s=115]="s",J[J.t=116]="t",J[J.u=117]="u",J[J.v=118]="v",J[J.w=119]="w",J[J.x=120]="x",J[J.y=121]="y",J[J.z=122]="z",J[J.A=65]="A",J[J.B=66]="B",J[J.C=67]="C",J[J.D=68]="D",J[J.E=69]="E",J[J.F=70]="F",J[J.G=71]="G",J[J.H=72]="H",J[J.I=73]="I",J[J.J=74]="J",J[J.K=75]="K",J[J.L=76]="L",J[J.M=77]="M",J[J.N=78]="N",J[J.O=79]="O",J[J.P=80]="P",J[J.Q=81]="Q",J[J.R=82]="R",J[J.S=83]="S",J[J.T=84]="T",J[J.U=85]="U",J[J.V=86]="V",J[J.W=87]="W",J[J.X=88]="X",J[J.Y=89]="Y",J[J.Z=90]="Z",J[J.asterisk=42]="asterisk",J[J.backslash=92]="backslash",J[J.closeBrace=125]="closeBrace",J[J.closeBracket=93]="closeBracket",J[J.colon=58]="colon",J[J.comma=44]="comma",J[J.dot=46]="dot",J[J.doubleQuote=34]="doubleQuote",J[J.minus=45]="minus",J[J.openBrace=123]="openBrace",J[J.openBracket=91]="openBracket",J[J.plus=43]="plus",J[J.slash=47]="slash",J[J.formFeed=12]="formFeed",J[J.tab=9]="tab"})(pI1||(pI1={}));var yZ=Array(20).fill(0).map((J,Z)=>{return" ".repeat(Z)});var Ww0={" ":{"\n":Array(200).fill(0).map((J,Z)=>{return`
|
|
2565
2565
|
`+" ".repeat(Z)}),"\r":Array(200).fill(0).map((J,Z)=>{return"\r"+" ".repeat(Z)}),"\r\n":Array(200).fill(0).map((J,Z)=>{return`\r
|
|
@@ -6119,11 +6119,11 @@ ${W}`))}},error:(D)=>{if(!q)q=!0,z(Error(`Failed to spawn brew: ${D.message}`))}
|
|
|
6119
6119
|
${W}`;if(X==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
|
|
6120
6120
|
|
|
6121
6121
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6122
|
-
npm install -g @sourcegraph/amp`;z(Error(H))}},error:(D)=>{if(!U)U=!0,z(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!U)U=!0,K()}})})}h0();h0();jj();async function s80(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(X,{signal:V.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let U=_K4(J,F),q=U<0,D,W;if(G.time){let H=G.time[J],B=G.time[F],w=Date.now();if(H)D=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:U,hasUpdate:q,currentVersionAge:D,latestVersionAge:W}),{hasUpdate:q,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:W,source:"npm"}}catch(z){return j.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var $R5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function t80(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${$R5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let V=_K4(J,X),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return j.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var JR5=604800000;function TK4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>JR5)return{ageMs:Q};return null}function _K4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let z=Y.parts[K]||0,G=X.parts[K]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function cx0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?RD(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function lx0(J,Z,Q={}){let Y=new s1,X=Y.pipe(R6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new TK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Qz(K);let z=X.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Qz(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){V.debug("checking disabled");return}let U=await r80(),q=U==="binary"||U==="brew";V.debug("checking",{currentVersion:J,mode:F,packageManager:U,isBinaryDistribution:q});let D=q?await t80(J):await s80(J,nE());if(!(D.latestVersion&&D.hasUpdate)){V.debug("no update available");return}let W=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=U==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:F});if(U==="brew"){if(!W())Y.next("update-available-brew");return}if(U==="binary"&&process.execPath!==bx0()){if(V.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!W())Y.next("update-available");return}if(!U){if(V.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(U==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Zg(D.latestVersion,U);let H=await GH(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")V.info("success",B),Y.next("updated");else V.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Qz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}jj();import{stderr as nz}from"node:process";function SK4(J){let Z=new rW().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await yx0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6122
|
+
npm install -g @sourcegraph/amp`;z(Error(H))}},error:(D)=>{if(!U)U=!0,z(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!U)U=!0,K()}})})}h0();h0();jj();async function s80(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(X,{signal:V.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let U=_K4(J,F),q=U<0,D,W;if(G.time){let H=G.time[J],B=G.time[F],w=Date.now();if(H)D=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:U,hasUpdate:q,currentVersionAge:D,latestVersionAge:W}),{hasUpdate:q,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:W,source:"npm"}}catch(z){return j.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var $R5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function t80(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${$R5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let V=_K4(J,X),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return j.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var JR5=604800000;function TK4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>JR5)return{ageMs:Q};return null}function _K4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let z=Y.parts[K]||0,G=X.parts[K]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function cx0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?RD(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function lx0(J,Z,Q={}){let Y=new s1,X=Y.pipe(R6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new TK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Qz(K);let z=X.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Qz(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){V.debug("checking disabled");return}let U=await r80(),q=U==="binary"||U==="brew";V.debug("checking",{currentVersion:J,mode:F,packageManager:U,isBinaryDistribution:q});let D=q?await t80(J):await s80(J,nE());if(!(D.latestVersion&&D.hasUpdate)){V.debug("no update available");return}let W=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=U==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:F});if(U==="brew"){if(!W())Y.next("update-available-brew");return}if(U==="binary"&&process.execPath!==bx0()){if(V.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!W())Y.next("update-available");return}if(!U){if(V.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(U==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Zg(D.latestVersion,U);let H=await GH(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")V.info("success",B),Y.next("updated");else V.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Qz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}jj();import{stderr as nz}from"node:process";function SK4(J){let Z=new rW().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await yx0(Y.force||!1,Y.verbose||!1,"0.0.1773418087-gfc6b34"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new rW("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await ZR5(Y.targetVersion)});J.addCommand(Q)}async function ZR5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")nz.write(Z1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6123
6123
|
|
|
6124
6124
|
`));try{if(!J){nz.write(Z1.blue(`Checking for updates...
|
|
6125
|
-
`));let{hasUpdate:Y,latestVersion:X}=ux0()?await t80("0.0.
|
|
6126
|
-
`));let z=await GH("0.0.
|
|
6125
|
+
`));let{hasUpdate:Y,latestVersion:X}=ux0()?await t80("0.0.1773418087-gfc6b34"):await s80("0.0.1773418087-gfc6b34",nE());if(!Y){let V=cx0("0.0.1773418087-gfc6b34"),K=V?.age?`released ${V.age} ago`:`built ${RD(new Date("2026-03-13T16:13:38.110Z"))} ago`;nz.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1773418087-gfc6b34"} (${K})
|
|
6126
|
+
`));let z=await GH("0.0.1773418087-gfc6b34");if(z.warning)nz.write(`
|
|
6127
6127
|
`+Z1.yellow(z.warning)+`
|
|
6128
6128
|
`);process.exit(0)}if(!X)nz.write(Z1.yellow("[WARN] could not find latest version")),process.exit(0);J=X}nz.write(Z1.blue(`Updating to version ${J}...
|
|
6129
6129
|
`)),await Zg(J,void 0,(Y)=>{nz.write(Z1.dim(`Running: ${Y}
|
|
@@ -7286,7 +7286,7 @@ Ctrl-X, Y, Z to unlock`;if(D){let b=F.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7286
7286
|
`),V=[];for(let K=0;K<X.length;K++){let F=X[K].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let U of F)if(U.startsWith("\x00")&&U.endsWith("\x01"))V.push(new C(U.slice(1,-1),new h({color:Y.app.keybind,bold:!0})));else V.push(new C(U,new h({color:Q.colorScheme.foreground})));if(K<X.length-1)V.push(new C(`
|
|
7287
7287
|
`))}return new c0({decoration:{color:Q.colorScheme.background,border:u1.all(new v1(Y.app.keybind,1,"rounded"))},child:new i0({padding:C0.symmetric(0,1),child:new $0({text:new C(void 0,void 0,V)})})})}}class tg0 extends M2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=C$0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new rg0({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function xN4(J,Z,Q,Y,X,V,K){if(V<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<V?z:null}case"bar":case"stacked-bar":{let z=K?i8:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let U=Math.max(1,Math.floor(G/V)),q=Math.floor(F/U);return q>=0&&q<V?q:null}case"line":case"sparkline":case"stacked-area":{let z=K?i8:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(V===1)return 0;let U=G/(V-1),q=Math.round(F/U);return Math.max(0,Math.min(V-1,q))}default:return null}}function Ti5(J,Z,Q,Y,X,V,K,z){if(X<=0||Z<0||Z>=X)return null;let G=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=V?i8:0,U=Q-F,q=Y-(V?G:0);if(U<=0||q<=0)return null;let D=Math.max(1,Math.floor(U/X)),W=F+Z*D+Math.floor(D/2),H=z>0?K/z:0,B=Math.round((1-H)*(q-1));return{x:W,y:B}}case"line":case"sparkline":case"stacked-area":{let F=V?i8:0,U=Q-F,q=Y-(V?G:0);if(U<=0||q<=0)return null;let D=X>1?F+Math.round(Z/(X-1)*(U-1)):F+Math.floor(U/2),W=z>0?K/z:0,H=Math.round((1-W)*(q-1));return{x:D,y:H}}default:return null}}function _i5(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function Si5(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let V=J.label.length,K=0;for(let z of Q){let G=z.points[Z];if(!G)continue;K+=G.value;let F=2+z.name.length+2+Y(G.value).length;V=Math.max(V,F)}if(X){let z=9+Y(K).length;V=Math.max(V,z)}return V}function vi5(J,Z,Q,Y,X,V,K){let z;try{let H=I1.of(J),B=f0.of(J);z={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let G=new h({color:z.foreground,bold:!0}),F=new h({color:z.foreground}),U=new h({color:z.foreground,dim:!0}),q=[],D=new h({color:z.foreground,underline:!0}),W=(H,B)=>new C(B,D,void 0,U90(H),()=>{w8(J,H)});if(Y.length<=1){if(q.push(new C(`${Z.label}: `,G)),Z.link)q.push(W(Z.link,V(Z.value)));else q.push(new C(V(Z.value),F));if(Z.meta)q.push(new C(` (${Z.meta})`,U))}else{let H=K==="stacked-bar"||K==="stacked-area";q.push(new C(`${Z.label}
|
|
7288
7288
|
`,G));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],O=N.points[Q];if(!O)continue;B+=O.value;let E=N.color??X[w%X.length]??z.foreground;if(q.push(new C("● ",new h({color:E}))),q.push(new C(`${N.name}: `,U)),O.link)q.push(W(O.link,V(O.value)));else q.push(new C(V(O.value),F));if(w<Y.length-1||H)q.push(new C(`
|
|
7289
|
-
`))}if(H)q.push(new C(" ",U)),q.push(new C("Total: ",U)),q.push(new C(V(B),F))}return new c0({decoration:{color:z.background,border:u1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,q)})})}aw();h0();e9();import{execSync as Kn5}from"node:child_process";VN();_$();H3();P7();rb();bX();n2();h$();xX();NE();_4();zx();Uk();H1();var yO4=D4(PF(),1);import{writeFile as TO4}from"fs/promises";import _O4 from"path";h0();n2();class eg0{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1773416373-ge2c590"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Rt(Z,this.configService)}catch(Z){j.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class rH extends d0{props;constructor(J){super();this.props=J}createState(){return new fN4}}class fN4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class bN4 extends p0{controller=new l7;focusNode=new r4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,z=u1.all(new v1(Q.foreground,1,"solid")),G=new FJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),q=[];if(K)q.push(new C("Enter",new h({color:Y.keybind}))),q.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));q.push(new C("Esc",new h({color:Y.keybind}))),q.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let D=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,q)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[U,new R0({height:1}),F,new V3,D]})})}}class pp extends d0{props;constructor(J){super();this.props=J}createState(){return new bN4}}import{isDeepStrictEqual as $p0}from"node:util";var ki5=/[\\/_ +.#"@[({&]/,yi5=/[\\/_ +.#"@[({&]/g,ui5=/[\s-]/,hN4=/[\s-]/g;function S$0(J,Z,Q,Y,X,V,K){if(V===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${V}`;if(K[z]!==void 0)return K[z];let G=Y.charAt(V),F=Q.indexOf(G,X),U=0,q,D,W,H;while(F>=0){if(q=S$0(J,Z,Q,Y,F+1,V+1,K),q>U){if(F===X)q*=1;else if(ui5.test(J.charAt(F-1))){if(q*=0.9,H=J.slice(X,F-1).match(hN4),H&&X>0)q*=0.999**H.length}else if(ki5.test(J.charAt(F-1))){if(q*=0.8,W=J.slice(X,F-1).match(yi5),W&&X>0)q*=0.999**W.length}else if(q*=0.3,X>0)q*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(V))q*=0.9999}if(q<0.1&&(Q.charAt(F-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(F-1)!==Y.charAt(V))){if(D=S$0(J,Z,Q,Y,F+1,V+2,K),D*0.1>q)q=D*0.1}if(q>U)U=q;F=Q.indexOf(G,F+1)}return K[z]=U,U}function _$0(J){return J.toLowerCase().replace(hN4," ")}function mN4(J,Z){let Q=S$0(J,Z,_$0(J),_$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let G=S$0(J,z,_$0(J),_$0(z),0,0,{});if(G===0)return Q;X+=G,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class bT{}class hT{}class v$0{}class k$0{}class gN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new pN4}}class pN4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function xi5(J,Z){if(J==="")return{matches:!0,score:1};let Q=mN4(Z,J);return{matches:Q>0.15,score:Q}}class o9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new dN4}}class dN4 extends p0{textController;focusNode;scrollController=new Y5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new l7(this.widget.props.controller?.query??""),this.focusNode=new r4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>$p0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!$p0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>$p0(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof bT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof hT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof v$0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof k$0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...xi5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;vT(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=u1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new FJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new P2({shortcuts:new Map([[new Y4("ArrowDown"),new bT],[new Y4("ArrowUp"),new hT],[new Y4("Tab"),new bT],[new Y4("Tab",{shift:!0}),new hT],[new Y4("n",{ctrl:!0}),new bT],[new Y4("p",{ctrl:!0}),new hT],[new Y4("Enter"),new v$0],[new Y4("Escape"),new k$0]]),focusNode:this.focusNode,child:z}),F=new S9({actions:new Map([[bT,new s4(this.invoke)],[hT,new s4(this.invoke)],[v$0,new s4(this.invoke)],[k$0,new s4(this.invoke)]]),child:G}),U=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]});this.itemContexts=[];let q;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";q=new R0({height:10,child:new l1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)q=new T1({child:new l1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new gN4(new n1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});q=new u0({children:w,crossAxisAlignment:"start"})}let D=new n1({onScroll:this.handleScroll,opaque:!1,child:new j6({controller:this.scrollController,autofocus:!1,child:q})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(U,new R0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:D}),new c0({padding:C0.only({top:1}),child:new l1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:D}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function cN4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),V=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Jp0 extends d1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>cN4(X.pubDate).length));return new o9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,V,K,z)=>{let G=f0.of(z),{colors:F}=G,U=G.app,q=V?U.selectionBackground:void 0,D=V?U.selectionForeground:F.foreground,W=F.mutedForeground,H=(B,w)=>new R0({width:w,child:U1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:q?{color:q}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[new T1({child:new $0({text:new C(X.title,new h({color:D})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(cN4(X.pubDate),Q)]})})}})}}_4();class Zp0 extends d0{createState(){return new lN4}}class lN4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var fi5=/\/threads\/(T-[^/?#\s<>]+)/i;function bi5(J){let Z=J.trim(),Y=Z.match(fi5)?.[1];if(Y&&D8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(D8(X))return X;return null}function hi5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(K.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(K),Q.set(G,F)}else X.push(K)}return Q20.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Qp0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function mi5(J,Z,Q,Y){return[Qp0("+",J,Y.success),V3.horizontal(1),Qp0("~",Z,Y.warning),V3.horizontal(1),Qp0("-",Q,Y.destructive)]}function gi5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class y$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new iN4}}class iN4 extends p0{spinner=new S3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,F=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),U=hi5(F),q=Math.max(0,...U.map((O)=>O.description.timeAgo.length)),D=f0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new l1({child:new $0({text:new C("",new h({color:D.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:D.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:D.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=bi5(O);return B};return new o9({items:U,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!gi5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:P}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,w0)=>new R0({width:w0,child:U1.end([new $0({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[O.id],k=[],f=O.relationshipType==="handoff",p=new Up({connectorColor:P.mutedForeground});if(O.depth>0){let s=[],w0=O.ancestorsAreLast.slice(1);for(let z0 of w0)s.push(new C(p.getAncestorPrefix(z0),new h({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,F0=p.getConnectorText(a);s.push(new C(F0,new h({color:p.connectorColor,dim:p.connectorDim}))),k.push(new $0({text:new C("",void 0,s)}))}let l=[],x=G===O.id?new C("(current) ",new h({color:P.success})):z.has(O.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(x)l.push(new $0({text:x}));if(mO(b))l.push(new Zp0),l.push(new R0({width:1}));let r=O.title;if(O.relationshipType==="fork"){let s=r.match(/^Forked\((\d+)\): /);if(s)r=r.slice(s[0].length);else while(r.startsWith("Forked: "))r=r.slice(8);l.push(new $0({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)l.push(new $0({text:new C("[handoff] ",new h({color:P.accent}))}));if(l.push(new T1({child:new $0({text:new C(r,new h({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:P;l.push(...mi5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),l.push(new R0({width:2}))}return l.push(m(O.description.timeAgo,q)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[...k,...l]})})}})}}function nN4(J){return 1-(1-J)**3}function aN4(J,Z,Q){return J+(Z-J)*Q}function dp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),V=nN4(Y),K=nN4(X);return{x:aN4(J.startOffset.x,J.targetOffset.x,V),y:aN4(J.startOffset.y,J.targetOffset.y,K)}}var pi5={nodeWidth:3,horizontalSpacing:3};class mT{options;constructor(J={}){this.options={...pi5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let V=0,K=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let U={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:U,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let q=[];for(let B of F)q.push(K(B,G+1));let D=Math.min(...q),W=Math.max(...q),H=Math.floor((D+W)/2);return Y.push({node:U,position:{x:H,y:G}}),H};for(let z of X)K(z,0);return Y}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),Y=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){Y.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=Y.get(z)}Y.set(V.id,K?void 0:V.parentID)}let X=new Map;for(let V of J){let K=Y.get(V.id);if(!X.has(K))X.set(K,[]);X.get(K).push(V)}return{childrenMap:X,resolvedParent:Y}}}var di5={nodeWidth:3,nodeHeight:2};class gT{options;constructor(J={}){this.options={...di5,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let V=this.calculateConnectorLine(X.position,Y.position);Z.push({points:V,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let z=K+1;if(Y.push({x:X,y:z}),X!==V)Y.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:G}),Y}}var ci5={nodeWidth:3,nodeHeight:2},li5={x:0,y:0};class x$0{options;constructor(J={}){this.options={...ci5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=li5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,b,k,f,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F,U)}))}return new c0({padding:C0.horizontal(2),child:new EH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:F}))}),new $0({text:new C(z,new h({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...X.map((D)=>D.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,U=Q?.foreground,q=[new $0({text:new C(z,new h({color:F}))})];for(let D of X){let W=" ".repeat(V-D.length);q.push(new $0({text:new C("│ ",new h({color:F}),[new C(D+W,new h({color:U??F})),new C(" │",new h({color:F}))])}))}return q.push(new $0({text:new C(G,new h({color:F}))})),new u0({crossAxisAlignment:"start",children:q})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let D of Z){let W=D.position.x+z;if(W>=0&&W<Y)F[W]="▲"}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let U=Array(Y).fill(" ");for(let D of J){let W=Z.filter((O)=>O.node.parentID===D.node.id);if(W.length===0)continue;let H=D.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)U[O]="│";else if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┬";else if(B.includes(O))if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┴";else if(U[O]===" ")U[O]="─"}}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let q=Array(Y).fill(" ");for(let D of J){if(Z.filter((B)=>B.node.parentID===D.node.id).length===0)continue;let H=D.position.x+z;if(H>=0&&H<Y)q[H]="│"}return K.push(new $0({text:new C(q.join(""),new h({color:G}))})),K}}var ii5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},ni5={x:0,y:0};class Yp0{options;constructor(J={}){this.options={...ii5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ni5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1;_.push(this.renderNode(m,b,k,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F)}))}return new c0({padding:C0.horizontal(2),child:new EH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,V=[];for(let K of Y)V.push(new $0({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of J){let q=Z.filter((w)=>w.node.parentID===U.node.id);if(q.length===0)continue;let D=U.position.x+z,W=q.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===D,O=W.includes(w);if(N&&O)if(q.length===1)F[w]="│";else if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(O)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return K.push(new $0({text:new C(F.join(""),new h({color:G}))})),K}}class cp extends N3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new oN4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class oN4 extends A4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class fL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new tN4}}var rN4=400,sN4=300,ai5=16;class tN4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new mT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new gT;renderer=new Yp0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let F=this.widget.props.threads.find((U)=>U.id===V);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:rN4,durationY:sN4};let Z=Math.max(rN4,sN4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=dp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},ai5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),V=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),U=Math.floor(G/2)-K;return{x:V,y:U}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((V)=>V.node.parentID===Q.node.id);if(X.length>0){X.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(X.length/2);Y=X[V]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(X.length>0)X.sort((V,K)=>K.position.x-V.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(X.length>0)X.sort((V,K)=>V.position.x-K.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let U=(this.selectedNodeId?this.positionedNodes.find((q)=>q.node.id===this.selectedNodeId):null)??this.positionedNodes.find((q)=>!q.node.parentID);if(U){let q=Math.max(...this.positionedNodes.map((D)=>D.position.y));this.currentOffset=this.calculateCenterOffset(U.position.x,U.position.y,q)}}let X=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new cp({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new k4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class $O4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new JO4}}class JO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var eN4=30,oi5=30;class pT{}class dT{}class f$0{}class b$0{}class Xp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new ZO4}}class ZO4 extends p0{highlightedIndex=0;controller=new l7;focusNode;scrollController=new Y5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;vT(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof pT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof dT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof f$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof b$0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=t1.of(J).size.width>=oi5+eN4,G=u1.all(new v1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),q=new FJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),D=new P2({shortcuts:new Map([[new Y4("ArrowDown"),new pT],[new Y4("ArrowUp"),new dT],[new Y4("Tab"),new pT],[new Y4("Tab",{shift:!0}),new dT],[new Y4("n",{ctrl:!0}),new pT],[new Y4("p",{ctrl:!0}),new dT],[new Y4("Enter"),new f$0],[new Y4("Escape"),new b$0]]),focusNode:this.focusNode,child:q}),W=new S9({actions:new Map([[pT,new s4(this.invoke)],[dT,new s4(this.invoke)],[f$0,new s4(this.invoke)],[b$0,new s4(this.invoke)]]),child:D}),H=new U1({children:[new c0({decoration:{color:Y.background},child:new $0({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=I?X.selectionBackground:void 0,S=I?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:I?X.selectionForeground:Y.success})));return new $O4(new n1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=F?new c0({padding:C0.all(1),child:new fL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:eN4});L=new U1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[U,H,new R0({height:1}),new T1({child:L})]})})}}class UJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UJ._instance)UJ._instance=new UJ;return UJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class QO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){j.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){j.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new o9({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(F,U,q,D)=>{let W=U?Q.selectionBackground:void 0,H=U?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new h({color:H}))})})},filterItem:(F,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(U);let D=U.trim().toLowerCase();return D.length===0||F.name.includes(D)},sortItems:(F,U,q)=>{let D="__isCreateMarker"in F.item&&F.item.__isCreateMarker,W="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(D&&!W)return-1;if(!D&&W)return 1;return U.score-F.score}})}}class Vp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new QO4}}class iV extends d0{props;constructor(J){super();this.props=J}createState(){return new YO4}}class YO4 extends p0{_spinner=new S3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=u1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let F=new c0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var lp={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},h$0=["workspace","global","flag","default","external","skill","other"];function ri5(J){return Array.from(new Set(J))}function XO4(J){return ri5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function cT(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return XO4(J).length>0?"skill":"other"}function Kp0(J){return cT(J)==="skill"}function VO4(J){let Z=XO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=cT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${lp[Y].description}: ${Q}`}function KO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}class u8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new zO4}}class zO4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,X*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),F=X-z,U=Math.max(0,F*G),q=U+z;return J>=U&&J<=q}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),F=V-G;if(F<=0)return;let U=Z-Q,q=F/U,D=K/q,W=Math.max(0,Math.min(U,this._dragStartOffset+D));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,K*z),F=Q-Y,U=K-G,q=Math.max(0,Math.min(1,X/(Q-Y))),D=Math.max(0,U*q),W=D+G;if(Z>=D&&Z<=W)return;if(Z<D)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new n1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new GO4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class GO4 extends pC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new FO4(this)}updateRenderObject(J){J.updateWidget(this)}}class FO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;f4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=["▁","▂","▃","▄","▅","▆","▇","█"],F=Y,U=Y+X;for(let q=0;q<this.size.height;q++){let D="█",W=!0;if(q===Math.floor(F)){let H=1-(F-q),B=Math.floor(H*8);D=G[B]||"█",W=!1}else if(q===Math.floor(U)){let H=1-(U-q),B=Math.floor(H*8);D=G[B]||"█"}else if(q>F&&q<U)W=!1;J.setChar(Z,Q+q,D,{fg:z,bg:K,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),V=Math.min(1,Z/J),K=Math.max(1,Y*V),z=Y-K;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:K,showScrollbar:!0}}}class bL extends d0{props;constructor(J){super();this.props=J}createState(){return new UO4}}class UO4 extends p0{scrollController=new Y5;scrollAreaKey=new m7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof _2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let U=W$0(Q);return{title:U.title,type:U.type,description:U.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=u1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new C2({child:new c0({padding:C0.symmetric(1,0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.scrollController,autofocus:!0,child:z})}),new u8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,q=this.scrollController.offset,D=this.getViewportHeight(),W=U+D;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(D,1),scrollOffset:Math.max(q,0)}}})]})})})}),F=new c0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(U==="help"){let q=new h({color:Z.app.keybind}),D=new h({color:Z.colors.foreground,dim:!0});return new C("",D,[new C("Press ",D),new C("Escape",q),new C(" to close • Use ",D),new C("↑↓",q),new C(" or ",D),new C("j/k",q),new C(" to scroll",D)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,F]})})})}}e9();class qO4 extends d0{props;constructor(J){super();this.props=J}createState(){return new DO4}}class DO4 extends p0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=c8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${m4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${m4(K,"command")}, ${z} ${m4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
|
|
7289
|
+
`))}if(H)q.push(new C(" ",U)),q.push(new C("Total: ",U)),q.push(new C(V(B),F))}return new c0({decoration:{color:z.background,border:u1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,q)})})}aw();h0();e9();import{execSync as Kn5}from"node:child_process";VN();_$();H3();P7();rb();bX();n2();h$();xX();NE();_4();zx();Uk();H1();var yO4=D4(PF(),1);import{writeFile as TO4}from"fs/promises";import _O4 from"path";h0();n2();class eg0{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1773418087-gfc6b34"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Rt(Z,this.configService)}catch(Z){j.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class rH extends d0{props;constructor(J){super();this.props=J}createState(){return new fN4}}class fN4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class bN4 extends p0{controller=new l7;focusNode=new r4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,z=u1.all(new v1(Q.foreground,1,"solid")),G=new FJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),q=[];if(K)q.push(new C("Enter",new h({color:Y.keybind}))),q.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));q.push(new C("Esc",new h({color:Y.keybind}))),q.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let D=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,q)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[U,new R0({height:1}),F,new V3,D]})})}}class pp extends d0{props;constructor(J){super();this.props=J}createState(){return new bN4}}import{isDeepStrictEqual as $p0}from"node:util";var ki5=/[\\/_ +.#"@[({&]/,yi5=/[\\/_ +.#"@[({&]/g,ui5=/[\s-]/,hN4=/[\s-]/g;function S$0(J,Z,Q,Y,X,V,K){if(V===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${V}`;if(K[z]!==void 0)return K[z];let G=Y.charAt(V),F=Q.indexOf(G,X),U=0,q,D,W,H;while(F>=0){if(q=S$0(J,Z,Q,Y,F+1,V+1,K),q>U){if(F===X)q*=1;else if(ui5.test(J.charAt(F-1))){if(q*=0.9,H=J.slice(X,F-1).match(hN4),H&&X>0)q*=0.999**H.length}else if(ki5.test(J.charAt(F-1))){if(q*=0.8,W=J.slice(X,F-1).match(yi5),W&&X>0)q*=0.999**W.length}else if(q*=0.3,X>0)q*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(V))q*=0.9999}if(q<0.1&&(Q.charAt(F-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(F-1)!==Y.charAt(V))){if(D=S$0(J,Z,Q,Y,F+1,V+2,K),D*0.1>q)q=D*0.1}if(q>U)U=q;F=Q.indexOf(G,F+1)}return K[z]=U,U}function _$0(J){return J.toLowerCase().replace(hN4," ")}function mN4(J,Z){let Q=S$0(J,Z,_$0(J),_$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let G=S$0(J,z,_$0(J),_$0(z),0,0,{});if(G===0)return Q;X+=G,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class bT{}class hT{}class v$0{}class k$0{}class gN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new pN4}}class pN4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function xi5(J,Z){if(J==="")return{matches:!0,score:1};let Q=mN4(Z,J);return{matches:Q>0.15,score:Q}}class o9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new dN4}}class dN4 extends p0{textController;focusNode;scrollController=new Y5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new l7(this.widget.props.controller?.query??""),this.focusNode=new r4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>$p0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!$p0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>$p0(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof bT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof hT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof v$0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof k$0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...xi5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;vT(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=u1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new FJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new P2({shortcuts:new Map([[new Y4("ArrowDown"),new bT],[new Y4("ArrowUp"),new hT],[new Y4("Tab"),new bT],[new Y4("Tab",{shift:!0}),new hT],[new Y4("n",{ctrl:!0}),new bT],[new Y4("p",{ctrl:!0}),new hT],[new Y4("Enter"),new v$0],[new Y4("Escape"),new k$0]]),focusNode:this.focusNode,child:z}),F=new S9({actions:new Map([[bT,new s4(this.invoke)],[hT,new s4(this.invoke)],[v$0,new s4(this.invoke)],[k$0,new s4(this.invoke)]]),child:G}),U=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]});this.itemContexts=[];let q;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";q=new R0({height:10,child:new l1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)q=new T1({child:new l1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new gN4(new n1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});q=new u0({children:w,crossAxisAlignment:"start"})}let D=new n1({onScroll:this.handleScroll,opaque:!1,child:new j6({controller:this.scrollController,autofocus:!1,child:q})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(U,new R0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:D}),new c0({padding:C0.only({top:1}),child:new l1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:D}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function cN4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),V=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Jp0 extends d1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>cN4(X.pubDate).length));return new o9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,V,K,z)=>{let G=f0.of(z),{colors:F}=G,U=G.app,q=V?U.selectionBackground:void 0,D=V?U.selectionForeground:F.foreground,W=F.mutedForeground,H=(B,w)=>new R0({width:w,child:U1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:q?{color:q}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[new T1({child:new $0({text:new C(X.title,new h({color:D})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(cN4(X.pubDate),Q)]})})}})}}_4();class Zp0 extends d0{createState(){return new lN4}}class lN4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var fi5=/\/threads\/(T-[^/?#\s<>]+)/i;function bi5(J){let Z=J.trim(),Y=Z.match(fi5)?.[1];if(Y&&D8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(D8(X))return X;return null}function hi5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(K.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(K),Q.set(G,F)}else X.push(K)}return Q20.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Qp0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function mi5(J,Z,Q,Y){return[Qp0("+",J,Y.success),V3.horizontal(1),Qp0("~",Z,Y.warning),V3.horizontal(1),Qp0("-",Q,Y.destructive)]}function gi5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class y$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new iN4}}class iN4 extends p0{spinner=new S3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,F=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),U=hi5(F),q=Math.max(0,...U.map((O)=>O.description.timeAgo.length)),D=f0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new l1({child:new $0({text:new C("",new h({color:D.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:D.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:D.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=bi5(O);return B};return new o9({items:U,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!gi5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:P}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,w0)=>new R0({width:w0,child:U1.end([new $0({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[O.id],k=[],f=O.relationshipType==="handoff",p=new Up({connectorColor:P.mutedForeground});if(O.depth>0){let s=[],w0=O.ancestorsAreLast.slice(1);for(let z0 of w0)s.push(new C(p.getAncestorPrefix(z0),new h({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,F0=p.getConnectorText(a);s.push(new C(F0,new h({color:p.connectorColor,dim:p.connectorDim}))),k.push(new $0({text:new C("",void 0,s)}))}let l=[],x=G===O.id?new C("(current) ",new h({color:P.success})):z.has(O.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(x)l.push(new $0({text:x}));if(mO(b))l.push(new Zp0),l.push(new R0({width:1}));let r=O.title;if(O.relationshipType==="fork"){let s=r.match(/^Forked\((\d+)\): /);if(s)r=r.slice(s[0].length);else while(r.startsWith("Forked: "))r=r.slice(8);l.push(new $0({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)l.push(new $0({text:new C("[handoff] ",new h({color:P.accent}))}));if(l.push(new T1({child:new $0({text:new C(r,new h({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:P;l.push(...mi5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),l.push(new R0({width:2}))}return l.push(m(O.description.timeAgo,q)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[...k,...l]})})}})}}function nN4(J){return 1-(1-J)**3}function aN4(J,Z,Q){return J+(Z-J)*Q}function dp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),V=nN4(Y),K=nN4(X);return{x:aN4(J.startOffset.x,J.targetOffset.x,V),y:aN4(J.startOffset.y,J.targetOffset.y,K)}}var pi5={nodeWidth:3,horizontalSpacing:3};class mT{options;constructor(J={}){this.options={...pi5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let V=0,K=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let U={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:U,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let q=[];for(let B of F)q.push(K(B,G+1));let D=Math.min(...q),W=Math.max(...q),H=Math.floor((D+W)/2);return Y.push({node:U,position:{x:H,y:G}}),H};for(let z of X)K(z,0);return Y}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),Y=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){Y.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=Y.get(z)}Y.set(V.id,K?void 0:V.parentID)}let X=new Map;for(let V of J){let K=Y.get(V.id);if(!X.has(K))X.set(K,[]);X.get(K).push(V)}return{childrenMap:X,resolvedParent:Y}}}var di5={nodeWidth:3,nodeHeight:2};class gT{options;constructor(J={}){this.options={...di5,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let V=this.calculateConnectorLine(X.position,Y.position);Z.push({points:V,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let z=K+1;if(Y.push({x:X,y:z}),X!==V)Y.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:G}),Y}}var ci5={nodeWidth:3,nodeHeight:2},li5={x:0,y:0};class x$0{options;constructor(J={}){this.options={...ci5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=li5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,b,k,f,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F,U)}))}return new c0({padding:C0.horizontal(2),child:new EH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:F}))}),new $0({text:new C(z,new h({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...X.map((D)=>D.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,U=Q?.foreground,q=[new $0({text:new C(z,new h({color:F}))})];for(let D of X){let W=" ".repeat(V-D.length);q.push(new $0({text:new C("│ ",new h({color:F}),[new C(D+W,new h({color:U??F})),new C(" │",new h({color:F}))])}))}return q.push(new $0({text:new C(G,new h({color:F}))})),new u0({crossAxisAlignment:"start",children:q})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let D of Z){let W=D.position.x+z;if(W>=0&&W<Y)F[W]="▲"}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let U=Array(Y).fill(" ");for(let D of J){let W=Z.filter((O)=>O.node.parentID===D.node.id);if(W.length===0)continue;let H=D.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)U[O]="│";else if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┬";else if(B.includes(O))if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┴";else if(U[O]===" ")U[O]="─"}}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let q=Array(Y).fill(" ");for(let D of J){if(Z.filter((B)=>B.node.parentID===D.node.id).length===0)continue;let H=D.position.x+z;if(H>=0&&H<Y)q[H]="│"}return K.push(new $0({text:new C(q.join(""),new h({color:G}))})),K}}var ii5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},ni5={x:0,y:0};class Yp0{options;constructor(J={}){this.options={...ii5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ni5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1;_.push(this.renderNode(m,b,k,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F)}))}return new c0({padding:C0.horizontal(2),child:new EH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,V=[];for(let K of Y)V.push(new $0({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of J){let q=Z.filter((w)=>w.node.parentID===U.node.id);if(q.length===0)continue;let D=U.position.x+z,W=q.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===D,O=W.includes(w);if(N&&O)if(q.length===1)F[w]="│";else if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(O)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return K.push(new $0({text:new C(F.join(""),new h({color:G}))})),K}}class cp extends N3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new oN4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class oN4 extends A4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class fL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new tN4}}var rN4=400,sN4=300,ai5=16;class tN4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new mT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new gT;renderer=new Yp0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let F=this.widget.props.threads.find((U)=>U.id===V);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:rN4,durationY:sN4};let Z=Math.max(rN4,sN4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=dp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},ai5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),V=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),U=Math.floor(G/2)-K;return{x:V,y:U}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((V)=>V.node.parentID===Q.node.id);if(X.length>0){X.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(X.length/2);Y=X[V]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(X.length>0)X.sort((V,K)=>K.position.x-V.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(X.length>0)X.sort((V,K)=>V.position.x-K.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let U=(this.selectedNodeId?this.positionedNodes.find((q)=>q.node.id===this.selectedNodeId):null)??this.positionedNodes.find((q)=>!q.node.parentID);if(U){let q=Math.max(...this.positionedNodes.map((D)=>D.position.y));this.currentOffset=this.calculateCenterOffset(U.position.x,U.position.y,q)}}let X=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new cp({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new k4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class $O4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new JO4}}class JO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var eN4=30,oi5=30;class pT{}class dT{}class f$0{}class b$0{}class Xp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new ZO4}}class ZO4 extends p0{highlightedIndex=0;controller=new l7;focusNode;scrollController=new Y5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;vT(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof pT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof dT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof f$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof b$0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=t1.of(J).size.width>=oi5+eN4,G=u1.all(new v1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),q=new FJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),D=new P2({shortcuts:new Map([[new Y4("ArrowDown"),new pT],[new Y4("ArrowUp"),new dT],[new Y4("Tab"),new pT],[new Y4("Tab",{shift:!0}),new dT],[new Y4("n",{ctrl:!0}),new pT],[new Y4("p",{ctrl:!0}),new dT],[new Y4("Enter"),new f$0],[new Y4("Escape"),new b$0]]),focusNode:this.focusNode,child:q}),W=new S9({actions:new Map([[pT,new s4(this.invoke)],[dT,new s4(this.invoke)],[f$0,new s4(this.invoke)],[b$0,new s4(this.invoke)]]),child:D}),H=new U1({children:[new c0({decoration:{color:Y.background},child:new $0({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=I?X.selectionBackground:void 0,S=I?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:I?X.selectionForeground:Y.success})));return new $O4(new n1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=F?new c0({padding:C0.all(1),child:new fL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:eN4});L=new U1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[U,H,new R0({height:1}),new T1({child:L})]})})}}class UJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UJ._instance)UJ._instance=new UJ;return UJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class QO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){j.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){j.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new o9({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(F,U,q,D)=>{let W=U?Q.selectionBackground:void 0,H=U?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new h({color:H}))})})},filterItem:(F,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(U);let D=U.trim().toLowerCase();return D.length===0||F.name.includes(D)},sortItems:(F,U,q)=>{let D="__isCreateMarker"in F.item&&F.item.__isCreateMarker,W="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(D&&!W)return-1;if(!D&&W)return 1;return U.score-F.score}})}}class Vp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new QO4}}class iV extends d0{props;constructor(J){super();this.props=J}createState(){return new YO4}}class YO4 extends p0{_spinner=new S3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=u1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let F=new c0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var lp={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},h$0=["workspace","global","flag","default","external","skill","other"];function ri5(J){return Array.from(new Set(J))}function XO4(J){return ri5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function cT(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return XO4(J).length>0?"skill":"other"}function Kp0(J){return cT(J)==="skill"}function VO4(J){let Z=XO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=cT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${lp[Y].description}: ${Q}`}function KO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}class u8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new zO4}}class zO4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,X*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),F=X-z,U=Math.max(0,F*G),q=U+z;return J>=U&&J<=q}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),F=V-G;if(F<=0)return;let U=Z-Q,q=F/U,D=K/q,W=Math.max(0,Math.min(U,this._dragStartOffset+D));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,K*z),F=Q-Y,U=K-G,q=Math.max(0,Math.min(1,X/(Q-Y))),D=Math.max(0,U*q),W=D+G;if(Z>=D&&Z<=W)return;if(Z<D)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new n1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new GO4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class GO4 extends pC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new FO4(this)}updateRenderObject(J){J.updateWidget(this)}}class FO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;f4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=["▁","▂","▃","▄","▅","▆","▇","█"],F=Y,U=Y+X;for(let q=0;q<this.size.height;q++){let D="█",W=!0;if(q===Math.floor(F)){let H=1-(F-q),B=Math.floor(H*8);D=G[B]||"█",W=!1}else if(q===Math.floor(U)){let H=1-(U-q),B=Math.floor(H*8);D=G[B]||"█"}else if(q>F&&q<U)W=!1;J.setChar(Z,Q+q,D,{fg:z,bg:K,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),V=Math.min(1,Z/J),K=Math.max(1,Y*V),z=Y-K;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:K,showScrollbar:!0}}}class bL extends d0{props;constructor(J){super();this.props=J}createState(){return new UO4}}class UO4 extends p0{scrollController=new Y5;scrollAreaKey=new m7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof _2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let U=W$0(Q);return{title:U.title,type:U.type,description:U.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=u1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new C2({child:new c0({padding:C0.symmetric(1,0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.scrollController,autofocus:!0,child:z})}),new u8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,q=this.scrollController.offset,D=this.getViewportHeight(),W=U+D;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(D,1),scrollOffset:Math.max(q,0)}}})]})})})}),F=new c0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(U==="help"){let q=new h({color:Z.app.keybind}),D=new h({color:Z.colors.foreground,dim:!0});return new C("",D,[new C("Press ",D),new C("Escape",q),new C(" to close • Use ",D),new C("↑↓",q),new C(" or ",D),new C("j/k",q),new C(" to scroll",D)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,F]})})})}}e9();class qO4 extends d0{props;constructor(J){super();this.props=J}createState(){return new DO4}}class DO4 extends p0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=c8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${m4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${m4(K,"command")}, ${z} ${m4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
|
|
7290
7290
|
|
|
7291
7291
|
`));for(let G of this.plugins){let{icon:F,color:U}=this.statusIcon(G.status),q=this.getRelativePath(G.uri.toString());if(Y.push(new C(`${F} `,new h({color:U}))),Y.push(new C(q,new h({bold:!0}))),Y.push(new C(` ${G.status}`,new h({dim:!0}))),Y.push(new C(`
|
|
7292
7292
|
`)),G.status==="active"&&G.registeredEvents.length>0)Y.push(new C(" Events: ",new h({dim:!0}))),Y.push(new C(G.registeredEvents.join(", "),new h({color:Q.link}))),Y.push(new C(`
|
|
@@ -7502,7 +7502,7 @@ ${Z0.content||""}`:Z0.content||"",a0=[],F1=Z0.baseDir.startsWith("file://")?MJ0(
|
|
|
7502
7502
|
`)}function nM4(J,Z){J.command("usage").description("Show your current Amp usage and credit balance").action(async(Q,Y)=>{let X=Y.optsWithGlobals(),V=await Z(X),K=await V.settings.get("proxy"),z=Uj1({settings:{url:V.ampURL,proxy:K},secrets:{getToken:(F,U)=>V.secrets.get(F,U)}}),G=await A6.userDisplayBalanceInfo({},{config:z});if(!G.ok){if(G.error.code==="auth-required")process.stderr.write(Z1.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(Z1.red("Error: ")+G.error.message+`
|
|
7503
7503
|
`),process.exit(1)}process.stdout.write(await Ps5(G.result.displayText)+`
|
|
7504
7504
|
`),process.exit(0)})}var n13=BB.join(y$,"logs","headless.log"),_l0=BB.join(SC,"device-id.json");async function a13(){for(let J of zN)try{if((await J.listConfigs()).length>0)return J}catch(Z){j.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => D4(w_(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){E7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7505
|
-
`)}function o13(J){process.emitWarning=(Z,Q,Y,X)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:Y})}}function O7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function jR4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function r13(J){try{return await AR4(J,"utf-8")}catch{return J}}async function Sl0(J,Z,Q){let Y=jR4(J,Z);if(!Y)return;let X=y6(Q)?Q.features:[],V=y6(Q)?Q.user.email:void 0;if(!PR4(X,K2.HARNESS_SYSTEM_PROMPT)&&!RR4(V))throw new c1("You are not allowed to do this.",1);u$("systemPrompt",await r13(Y))}function RR4(J){return!!(J&&Mo(J))}function PR4(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function vl0(J){return(J.userEmail?vZ(J.userEmail):!1)||PR4(J.features,K2.DTW_TUI)}function HR4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new c1("This TUI mode is not enabled for your user;",1)}function kl0(J,Z){if(typeof J==="boolean")return J;if(!y6(Z))return!1;return vl0({userEmail:Z.user.email,features:Z.features})}function yl0(J){if(!y6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function s13(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function ul0(J){let Y=s13(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new c1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var BR4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??cY,description:`Custom settings file path (overrides the default location ${cY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${bE})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:a9(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:uK.SMART.key,description:`Set the agent mode (${vX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:vX().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],wR4=(J)=>("deprecated"in J)&&J.deprecated===!0,t13=(J)=>("hidden"in J)&&J.hidden===!0,e13=(J)=>("default"in J),$43=(J)=>("default"in J)?J.default:void 0,CR4=[{name:"toggle-skills-count",entryPoint:ox0}];function J43(J,Z){let Q=Z.args[0],Y=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=Y.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new c1(B8.unknownCommand(Q),1,K)}}async function fl0(J){return{...J,getThreadEnvironment:$J,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JV(J.fileSystem),generateThreadTitle:a00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function TR4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:$J,filesystem:J.fileSystem,threadService:J.threadService}}var qZ0=K1.file(IR4.homedir()),xl0=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(qZ0,".config");function Z43(J){return k24({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){v24(Z);let Q=O90(),Y=Bf0();if((!Q||Y||Oz4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(IU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(IU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(O90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Q43(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function k9(J,Z,Q){let Y=Q?.deferAuth??!1;Yj1("0.0.
|
|
7505
|
+
`)}function o13(J){process.emitWarning=(Z,Q,Y,X)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:Y})}}function O7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function jR4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function r13(J){try{return await AR4(J,"utf-8")}catch{return J}}async function Sl0(J,Z,Q){let Y=jR4(J,Z);if(!Y)return;let X=y6(Q)?Q.features:[],V=y6(Q)?Q.user.email:void 0;if(!PR4(X,K2.HARNESS_SYSTEM_PROMPT)&&!RR4(V))throw new c1("You are not allowed to do this.",1);u$("systemPrompt",await r13(Y))}function RR4(J){return!!(J&&Mo(J))}function PR4(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function vl0(J){return(J.userEmail?vZ(J.userEmail):!1)||PR4(J.features,K2.DTW_TUI)}function HR4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new c1("This TUI mode is not enabled for your user;",1)}function kl0(J,Z){if(typeof J==="boolean")return J;if(!y6(Z))return!1;return vl0({userEmail:Z.user.email,features:Z.features})}function yl0(J){if(!y6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function s13(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function ul0(J){let Y=s13(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new c1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var BR4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??cY,description:`Custom settings file path (overrides the default location ${cY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${bE})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:a9(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:uK.SMART.key,description:`Set the agent mode (${vX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:vX().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],wR4=(J)=>("deprecated"in J)&&J.deprecated===!0,t13=(J)=>("hidden"in J)&&J.hidden===!0,e13=(J)=>("default"in J),$43=(J)=>("default"in J)?J.default:void 0,CR4=[{name:"toggle-skills-count",entryPoint:ox0}];function J43(J,Z){let Q=Z.args[0],Y=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=Y.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new c1(B8.unknownCommand(Q),1,K)}}async function fl0(J){return{...J,getThreadEnvironment:$J,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JV(J.fileSystem),generateThreadTitle:a00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function TR4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:$J,filesystem:J.fileSystem,threadService:J.threadService}}var qZ0=K1.file(IR4.homedir()),xl0=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(qZ0,".config");function Z43(J){return k24({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){v24(Z);let Q=O90(),Y=Bf0();if((!Q||Y||Oz4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(IU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(IU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(O90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Q43(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function k9(J,Z,Q){let Y=Q?.deferAuth??!1;Yj1("0.0.1773418087-gfc6b34");let X=Ur({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([K1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:qZ0,userConfigDir:xl0});Wz4(X);let V=await X.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let{toolService:K,dispose:z}=P24({configService:X}),G=new Map,F=()=>G.clear(),U=new oL0(X,J.settings.getWorkspaceRootPath()),q=Ym1({configService:X,filesystem:r6}),D=lu1({configService:X,trustStore:U,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(w0,a,F0)=>{let z0=`${w0}:${a}`,q0=G.get(z0);if(q0)return j.debug("Reusing existing OAuth provider for server",{serverName:w0,serverUrl:a}),q0;j.debug("Creating OAuth provider for server",{serverName:w0,serverUrl:a});let Q0=(async()=>{let H0=new TN(J.secrets),i=await H0.getClientInfo(w0,a),n=F0?.scopes??i?.scopes,e=BV4();j.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:p6.isTTY});let J0;if(e)J0=J.executeMode?HV4():WV4(w0);let Z0=new DL0({storage:H0,serverName:w0,serverUrl:a,clientId:F0?.clientId??i?.clientId,clientSecret:F0?.clientSecret??i?.clientSecret,authUrl:F0?.authUrl??i?.authUrl,tokenUrl:F0?.tokenUrl??i?.tokenUrl,scopes:n,headlessAuthHandler:J0});return j.debug("OAuth provider created",{serverName:w0,serverUrl:a,hasManualClientId:!!(F0?.clientId??i?.clientId),willUseDCR:!(F0?.clientId??i?.clientId),scopes:n,headlessMode:e,executeMode:J.executeMode}),Z0})();return G.set(z0,Q0),Q0}}),W=sv0({configService:X,filesystem:r6,spawn:s50}),H;if(J.executeMode){let w0=await x84({toolService:K,providers:[D,W],initialTimeout:15000});H=w0.registrations;for(let[a,F0]of w0.initErrors)j.warn(`${a} provider initialization slow or failed:`,F0)}else H=tv0({toolService:K,providers:[D,W]});if(Z.jetbrains)YN("JetBrains");else if(Z.ide&&tV4())YN("VS Code");else if(Z.ide&&eV4())YN("Neovim");else if(Z.ide){let w0=await a13();if(w0){let a=Er(w0.ideName);if(a)YN(a)}}if(J.executeMode)Xj1(!0);let B,w=m8.status.pipe(D1((w0)=>Boolean(w0.connected&&w0.authenticated&&w0.ideName&&fj1(w0.ideName))),M4()).subscribe((w0)=>{if(w0){if(!B)B=K.registerTool(u84)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let w0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new S80(process.cwd(),{alwaysIncludePaths:w0},!0)}else N=new class extends S80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let w0=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(w0),j.info("API key lookup before login",{found:Boolean(w0),ampURL:J.ampURL,deferAuth:Y}),!w0)if(Y)j.info("No API key found, continuing startup with deferred auth");else{p6.write(`No API key found. Starting login flow...
|
|
7506
7506
|
`);let a=await Y43(J),F0=await J.secrets.get("apiKey",J.ampURL);if(j.info("Login flow completed",{success:a,storedKeyPresent:Boolean(F0),ampURL:J.ampURL}),!a)await OU(),process.exit(1);O=!0}}{let w0=await X.getLatest(),a=w0.settings.url,F0=w0.secrets.isSet?.[a];j.info("Config secrets state after login",{configURL:a,apiKeySet:F0?.apiKey??!1})}let E=E1(nJ(X).pipe(F5((w0)=>w0!=="pending"))),L=await Fm1({isDevelopment:!1}),M=Y?"pending":await E;if(!Y)j.info("Server status resolved",{status:"ready",isAuthenticated:y6(M),isError:jD(M),errorMessage:jD(M)?M.error.message:void 0});let A=new rI0(L,X),I=new dA0(L,{lazy:!0,maxThreads:200});j.info("Starting Amp background services");let P=Z.takeMeBack?!1:void 0,_=kl0(P,M),S=Boolean(_||Z.headless);if(S)j.info("DTW mode enabled: thread sync service disabled");let y=S?Q43():yg1({threadService:A,threadHistoryService:I,configService:X,isExtensionDevelopment:!1}),m;m8.status.subscribe((w0)=>{m=w0});let b=new Fw0({workspaceRoots:[K1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?yt:r6,getCurrentFile:()=>{if(!m?.openFile)return;try{return K1.parse(m.openFile)}catch(w0){j.warn("Failed to parse current file URI",{uri:m.openFile,error:w0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let w0=m.openFile;return m.visibleFiles.filter((a)=>a!==w0).map((a)=>{try{return K1.parse(a)}catch(F0){return j.warn("Failed to parse visible file URI",{uri:a,error:F0}),null}}).filter((a)=>a!==null)}}),k=new Of0,f=process.env.PLUGINS??"off",p=Z.headless?$z4():void 0,l=p??new J90({configService:X}),x=l instanceof J90?l:void 0;if(x)x.pluginExecutorKind=_?"local":"unknown";let r=WM0({configService:X,fileSystem:Z.jetbrains||Z.ide?yt:r6,platform:l,internalPlugins:CR4,pluginFilter:f}),c=nx1({pluginService:r,toolService:K}),s={codebaseContextService:b,configService:X,toolService:K,mcpService:D,skillService:q,toolboxService:W,trustStore:U,threadService:A,threadHistoryService:I,threadSyncService:y,threadStorage:L,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:N,fileSystem:Z.jetbrains||Z.ide?yt:r6,terminal:k,pluginService:r,pluginPlatform:x,headlessPluginPlatform:p,serverStatus:M,serverStatusPromise:E,hasAPIKeyAtStartup:O};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let w0 of H.values())w0.dispose();await s.mcpService.dispose(),F(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),z(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),w.unsubscribe(),B?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function Y43(J){if(!J.executeMode){if(!await nx0("Would you like to log in to Amp? [(y)es, (n)o]: "))return p6.write(`Login cancelled. Run the command again to retry.
|
|
7507
7507
|
`),!1}return await _R4(J)}async function _R4(J){let Z=d13(32).toString("hex"),Q=await kC(J.ampURL,Z),Y=new AbortController;try{await fX(Q,Y.signal)}catch(V){j.error("Error opening browser",{error:V})}let X=await kC(J.ampURL,Z,!1);p6.write(`If your browser does not open automatically, visit:
|
|
7508
7508
|
|
|
@@ -7510,7 +7510,7 @@ ${Z1.blue.bold(X)}
|
|
|
7510
7510
|
|
|
7511
7511
|
`);try{return await kK4(J.ampURL,Z,J.secrets,Y),p6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(V){return j.error("Login failed",{error:V}),E7.write(`
|
|
7512
7512
|
Login failed: ${V instanceof Error?V.message:String(V)}
|
|
7513
|
-
`),!1}}function NR4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function X43(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new c1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!D8(Y.threadId))throw new c1("Create response did not include a valid thread ID",1);return Y.threadId}function V43(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function K43(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new c1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function z43(){let J=new rW().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)mE(),process.exit(0);let B=H.originalError??H;LX4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${RD(new Date("2026-03-
|
|
7513
|
+
`),!1}}function NR4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function X43(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new c1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!D8(Y.threadId))throw new c1("Create response did not include a valid thread ID",1);return Y.threadId}function V43(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function K43(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new c1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function z43(){let J=new rW().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)mE(),process.exit(0);let B=H.originalError??H;LX4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${RD(new Date("2026-03-13T16:13:38.110Z"))} ago`}catch{}p6.write(`0.0.1773418087-gfc6b34 (released 2026-03-13T16:13:38.110Z${B??""})
|
|
7514
7514
|
`),process.exit(0)}),J.addHelpText("after",oV4()),J.configureHelp({formatHelp:rV4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await E3(w);await H43(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await E3(w);await W43(N,await Rx0(w,N.settings))}),J.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,B,w)=>{let N=w.optsWithGlobals(),O=await E3(N);await nX4(H??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),J.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,B)=>{let w=B.optsWithGlobals(),N=await E3(w);await aX4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
|
|
7515
7515
|
Actions:
|
|
7516
7516
|
create Create a new DTW thread and print its ID
|
|
@@ -7573,8 +7573,8 @@ ${L}
|
|
|
7573
7573
|
|
|
7574
7574
|
This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function G43(J){j.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Eg({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:$J,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new JV(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw j.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function F43(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await hC()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await hC()).trimEnd(),stdinInput:null}}function U43(J,Z,Q){if(J.remote&&!Z)throw new c1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new c1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new c1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new c1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new c1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new c1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new c1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new c1("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
7575
7575
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function DZ0(J,Z,Q){let Y=process.hrtime.bigint(),X=(z0,q0)=>{let Q0=Number(process.hrtime.bigint()-q0)/1e6,H0=M$4();j.info("Startup phase",{phase:z0,phaseMs:Math.round(Q0),sinceMainMs:H0===null?void 0:Math.round(H0)})},{userInput:V,stdinInput:K}=await F43(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;U43({...Z,streamJson:z},J.executeMode,V),O7(Q,Z);let G=process.hrtime.bigint(),F=Boolean(await J.secrets.get("apiKey",J.ampURL)),U=!J.executeMode&&!Z.headless&&F;j.info("Interactive auth startup mode",{deferInteractiveAuth:U,hasAPIKeyAtStartup:F,executeMode:J.executeMode,headless:Boolean(Z.headless)});let q=await k9(J,Z,{deferAuth:U});X("runMainThread:createThreadDependencies",G),G=process.hrtime.bigint();let D=await fl0(q);X("runMainThread:createWorkerDeps",G);let{serverStatus:W}=q;if(!U&&jD(W)){let z0=km(Error(W.error.message));if(z0.message===B8.networkOffline||z0.message===B8.networkTimeout)throw ul0(J.ampURL);throw new c1(B8.invalidAPIKey,1)}let H=y6(W)?W:null,B=H?.user.email,w=RR4(B),N=vl0({userEmail:B,features:H?.features}),O=Z.takeMeBack?!1:void 0,E=H!==null&&kl0(O,H);if(!U)await Sl0(Q,Z,W);let L=yl0(W),M=L?.features??[],A=L?.team??null,I=e80(Z,L);if(I instanceof Error)G3(I.message);if((J.executeMode||z)&&q8(Z.mode)&&!w)throw new c1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!lq(Z.mode,B))throw new c1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await Qz4(V,K,q.configService),await q.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!vZ(B))throw new c1("Headless DTW mode is only available for Amp employees",1);let z0=await q.secretStorage.get("apiKey",J.ampURL);if(!z0)throw new c1("API key required for headless mode. Please run `amp login` first.",1);let q0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(q0&&!D8(q0))throw new c1(`Invalid thread ID: ${q0}`,1);let Q0=q0??await A43({dependencies:q,visibility:I??void 0}),H0=await EV4(Q0);if(H0.status==="already-running")await q.asyncDispose(),await OU(),process.exit(0);try{await DV4({ampURL:J.ampURL,apiKey:z0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:Q0,initialToolDiscovery:Promise.all([q.mcpService.initialized,q.toolboxService.initialized]).then(()=>{return}),configService:q.configService,mcpService:q.mcpService,toolService:q.toolService,skillService:q.skillService,fileSystem:q.fileSystem,pluginService:q.pluginService,pluginPlatform:q.headlessPluginPlatform})}finally{await H0.release(),await q.asyncDispose()}await OU(),process.exit(0)}let P={threadService:q.threadService,workerDeps:D,createThread:async()=>{let z0=U?await q.serverStatusPromise:W,q0=await B80(J.settings,process.cwd(),yl0(z0),I);if(q0 instanceof Error)G3(q0.message);return ym0(D,{threadMeta:q0?yV(q0):void 0,agentMode:Z.mode,onFirstAssistantMessage:OR4})},validateThreadOwnership:async(z0,q0)=>{if(q0?.nonBlockingOwnershipCheck){ER4(z0,q.configService).catch((Q0)=>{if(Q0 instanceof c1){if(q0.onOwnershipError){q0.onOwnershipError(Q0,z0);return}jC(Q0,z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await ER4(z0,q.configService)}catch(Q0){if(Q0 instanceof c1)throw Q0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:OR4},_=async(z0)=>{try{if(z0==="dtw")return G43({ampURL:J.ampURL,configService:q.configService,threadService:q.threadService,mcpService:q.mcpService,toolboxService:q.toolboxService,toolService:q.toolService,skillService:q.skillService,fileSystem:q.fileSystem,threadId:Z.threadId});return MH4(P,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(q0){if(q0 instanceof c1)throw q0;throw await jC(q0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")E7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7576
|
-
`),await OU(),process.exit(1);let S=(async()=>{if(U){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await q.configService.getLatest(),q0=Tk(z0),Q0=await A6.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(q0)});if(Q0.ok)return j.info("User free tier status:",Q0),Q0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),m=!J.executeMode?new Tf0:null,b,k=null;if(m)b=m,k=(async()=>{let z0=U?await q.serverStatusPromise:q.serverStatus;await Sl0(Q,Z,z0);let q0=process.hrtime.bigint(),Q0=kl0(O,z0),H0=y6(z0)?vl0({userEmail:z0.user.email,features:z0.features}):!1;HR4({dtwEnabled:Q0,hasV2TUIAccess:H0});let i=await _(Q0?"dtw":"worker");if(X("runMainThread:createThreadPool",q0),m.attach(i),V){let n=await E1(i.threadHandles$);if(!n)throw new c1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),k.catch(async(z0)=>{let q0=z0 instanceof Error?z0:Error(String(z0));m.setInitError(q0),await jC(z0,Z.threadId)});else G=process.hrtime.bigint(),HR4({dtwEnabled:E,hasV2TUIAccess:N}),b=await _(E?"dtw":"worker"),X("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let p=await q.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Z43({configService:q.configService,threadService:q.threadService,config:p,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((z0)=>{if(!z0)return v0.of({});return X5(z0.thread$,z0.threadViewState$).pipe(D1(([q0,Q0])=>({[q0.id]:Q0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){lK4(q.mcpService,J.settings);let z0={userInput:V,stdinInput:K,dependencies:q,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},q0=await vX4({threadPool:b,...z0});if(Z.archive)await A6.archiveThread({thread:q0,archived:!0},{config:q.configService});await q.asyncDispose(),process.exit(0)}let l=!1,x=!1;if(Z.jetbrains||Z.ide){await dj1();let z0=await FN({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)l=!await q.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let q0=z0[0];if(q0)m8.selectConfig(q0)}else x=!0}G=process.hrtime.bigint();let r=lx0("0.0.
|
|
7577
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await su1({get:async(z)=>{if(z!==Mu)return;try{let G=await AR4(_l0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Mu)return;await MR4(BB.dirname(_l0),{recursive:!0}),await c13(_l0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:mK()});Vj1(Y);let X=await kV4({...J,workspaceTrust:{current:!0,changes:Dk},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await dK4(J.mcpConfig);X=cK4(X,z)}let V=BB.dirname(X.getSettingsFilePath());S24(SC,V);let K=await X.get("url","global");if(!K)K=J7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!ZD(K))j.info("Targeting custom Amp server",{ampURL:K});return X=rI1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:zz4(await Rx0(J,X))}}function q43(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function D43(){L$4();let J=q43(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));yY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?n13:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)Z1.level=0;if(o13(j),j.info("Starting Amp CLI.",{version:"0.0.
|
|
7576
|
+
`),await OU(),process.exit(1);let S=(async()=>{if(U){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await q.configService.getLatest(),q0=Tk(z0),Q0=await A6.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(q0)});if(Q0.ok)return j.info("User free tier status:",Q0),Q0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),m=!J.executeMode?new Tf0:null,b,k=null;if(m)b=m,k=(async()=>{let z0=U?await q.serverStatusPromise:q.serverStatus;await Sl0(Q,Z,z0);let q0=process.hrtime.bigint(),Q0=kl0(O,z0),H0=y6(z0)?vl0({userEmail:z0.user.email,features:z0.features}):!1;HR4({dtwEnabled:Q0,hasV2TUIAccess:H0});let i=await _(Q0?"dtw":"worker");if(X("runMainThread:createThreadPool",q0),m.attach(i),V){let n=await E1(i.threadHandles$);if(!n)throw new c1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),k.catch(async(z0)=>{let q0=z0 instanceof Error?z0:Error(String(z0));m.setInitError(q0),await jC(z0,Z.threadId)});else G=process.hrtime.bigint(),HR4({dtwEnabled:E,hasV2TUIAccess:N}),b=await _(E?"dtw":"worker"),X("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let p=await q.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Z43({configService:q.configService,threadService:q.threadService,config:p,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((z0)=>{if(!z0)return v0.of({});return X5(z0.thread$,z0.threadViewState$).pipe(D1(([q0,Q0])=>({[q0.id]:Q0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){lK4(q.mcpService,J.settings);let z0={userInput:V,stdinInput:K,dependencies:q,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},q0=await vX4({threadPool:b,...z0});if(Z.archive)await A6.archiveThread({thread:q0,archived:!0},{config:q.configService});await q.asyncDispose(),process.exit(0)}let l=!1,x=!1;if(Z.jetbrains||Z.ide){await dj1();let z0=await FN({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)l=!await q.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let q0=z0[0];if(q0)m8.selectConfig(q0)}else x=!0}G=process.hrtime.bigint();let r=lx0("0.0.1773418087-gfc6b34",q.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let c=new pA0(q.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let s=new ax0(q.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),V&&J.executeMode){let z0=await E1(b.threadHandles$);if(!z0)throw new c1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:V}]})}G=process.hrtime.bigint();let w0=await az();X("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let a={...w0,launchCount:w0.launchCount+1};oz(a);let F0=Z.threadId&&D8(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await _B4({codebaseContextService:q.codebaseContextService,history:new Gx0,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadFuzzyIndexer:c,skillService:q.skillService,configService:q.configService,secretStorage:q.secretStorage,internalAPIClient:A6,threadPool:b,createSystemPromptDeps:async()=>TR4(q),ideClient:m8,mcpService:q.mcpService,toolboxService:q.toolboxService,mcpTrustHandler:s,updateService:r,pluginPlatform:q.pluginPlatform,pluginService:q.pluginService},{initialServerStatus:q.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:q.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:F0,showJetBrainsInstaller:l,showIdePickerHint:x,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:a,freeTierStatusPromise:S,workspace:A??null,features:M,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-13T16:13:38.110Z"},(z0)=>new Vg0({...z0,threadPool:z0.threadPool},(q0)=>new Zc0({...q0,threadState:q0.threadState}))),X("runMainThread:mountApp-returned",G),k)await k}finally{}await q.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E3(J){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)E7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7577
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await su1({get:async(z)=>{if(z!==Mu)return;try{let G=await AR4(_l0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Mu)return;await MR4(BB.dirname(_l0),{recursive:!0}),await c13(_l0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:mK()});Vj1(Y);let X=await kV4({...J,workspaceTrust:{current:!0,changes:Dk},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await dK4(J.mcpConfig);X=cK4(X,z)}let V=BB.dirname(X.getSettingsFilePath());S24(SC,V);let K=await X.get("url","global");if(!K)K=J7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!ZD(K))j.info("Targeting custom Amp server",{ampURL:K});return X=rI1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:zz4(await Rx0(J,X))}}function q43(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function D43(){L$4();let J=q43(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));yY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?n13:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)Z1.level=0;if(o13(j),j.info("Starting Amp CLI.",{version:"0.0.1773418087-gfc6b34",buildTimestamp:"2026-03-13T16:13:38.110Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new c1(B8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await z43().parseAsync(process.argv)}T24().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await D43().catch(jC)});async function W43(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),p6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7578
7578
|
`);else if(!ZD(J.ampURL))p6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7579
7579
|
`);let Y=process.env.AMP_API_KEY;if(Y)p6.write(`API key found in environment variable, storing...
|
|
7580
7580
|
`),await Z.set("apiKey",Y,J.ampURL),p6.write(`API key successfully stored.
|