@sourcegraph/amp 0.0.1759896092-gd52d93 → 0.0.1759910516-g30f449

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.
Files changed (2) hide show
  1. package/dist/main.js +11 -11
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4505,7 +4505,7 @@ Disconnect that client first.`))}});return}U(Error(`Connection failed: ${L.statu
4505
4505
  `),!B.hasAttribute("data-start"))B.setAttribute("data-start",String($+1))}M.textContent=w,k6.highlightElement(M)},function(w){B.setAttribute(Y,G),M.textContent=w})}}),k6.plugins.fileHighlight={highlight:function(B){var M=(B||document).querySelectorAll(z);for(var V=0,N;N=M[V++];)k6.highlightElement(N)}};var F=!1;k6.fileHighlight=function(){if(!F)console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead."),F=!0;k6.plugins.fileHighlight.highlight.apply(this,arguments)}})()});var JY6=t((sv2,eX6)=>{eX6.exports=d71;function d71(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}d71.prototype.go=function(J){if(this.pending<this.max)tX6(this,J);else this.waiting.push(J)};d71.prototype.wait=function(J){if(this.pending===0)J(this.error);else this.listeners.push(J)};d71.prototype.hold=function(){return oX6(this)};function oX6(J){J.pending+=1;var Q=!1;return Z;function Z(Y){if(Q)throw Error("callback called twice");if(Q=!0,J.error=J.error||Y,J.pending-=1,J.waiting.length>0&&J.pending<J.max)tX6(J,J.waiting.shift());else if(J.pending===0){var K=J.listeners;J.listeners=[],K.forEach(X)}}function X(Y){Y(J.error)}}function tX6(J,Q){Q(oX6(J))}});var ZY6=t((JJ9)=>{var Lu=s1("fs"),c71=s1("util"),af1=s1("stream"),QY6=af1.Readable,nf1=af1.Writable,s59=af1.PassThrough,o59=JY6(),l71=s1("events").EventEmitter;JJ9.createFromBuffer=t59;JJ9.createFromFd=e59;JJ9.BufferSlicer=PH;JJ9.FdSlicer=IH;c71.inherits(IH,l71);function IH(J,Q){Q=Q||{},l71.call(this),this.fd=J,this.pend=new o59,this.pend.max=1,this.refCount=0,this.autoClose=!!Q.autoClose}IH.prototype.read=function(J,Q,Z,X,Y){var K=this;K.pend.go(function(q){Lu.read(K.fd,J,Q,Z,X,function(G,z,U){q(),Y(G,z,U)})})};IH.prototype.write=function(J,Q,Z,X,Y){var K=this;K.pend.go(function(q){Lu.write(K.fd,J,Q,Z,X,function(G,z,U){q(),Y(G,z,U)})})};IH.prototype.createReadStream=function(J){return new i71(this,J)};IH.prototype.createWriteStream=function(J){return new a71(this,J)};IH.prototype.ref=function(){this.refCount+=1};IH.prototype.unref=function(){var J=this;if(J.refCount-=1,J.refCount>0)return;if(J.refCount<0)throw Error("invalid unref");if(J.autoClose)Lu.close(J.fd,Q);function Q(Z){if(Z)J.emit("error",Z);else J.emit("close")}};c71.inherits(i71,QY6);function i71(J,Q){Q=Q||{},QY6.call(this,Q),this.context=J,this.context.ref(),this.start=Q.start||0,this.endOffset=Q.end,this.pos=this.start,this.destroyed=!1}i71.prototype._read=function(J){var Q=this;if(Q.destroyed)return;var Z=Math.min(Q._readableState.highWaterMark,J);if(Q.endOffset!=null)Z=Math.min(Z,Q.endOffset-Q.pos);if(Z<=0){Q.destroyed=!0,Q.push(null),Q.context.unref();return}Q.context.pend.go(function(X){if(Q.destroyed)return X();var Y=Buffer.allocUnsafe(Z);Lu.read(Q.context.fd,Y,0,Z,Q.pos,function(K,q){if(K)Q.destroy(K);else if(q===0)Q.destroyed=!0,Q.push(null),Q.context.unref();else Q.pos+=q,Q.push(Y.slice(0,q));X()})})};i71.prototype.destroy=function(J){if(this.destroyed)return;J=J||Error("stream destroyed"),this.destroyed=!0,this.emit("error",J),this.context.unref()};c71.inherits(a71,nf1);function a71(J,Q){Q=Q||{},nf1.call(this,Q),this.context=J,this.context.ref(),this.start=Q.start||0,this.endOffset=Q.end==null?1/0:+Q.end,this.bytesWritten=0,this.pos=this.start,this.destroyed=!1,this.on("finish",this.destroy.bind(this))}a71.prototype._write=function(J,Q,Z){var X=this;if(X.destroyed)return;if(X.pos+J.length>X.endOffset){var Y=Error("maximum file length exceeded");Y.code="ETOOBIG",X.destroy(),Z(Y);return}X.context.pend.go(function(K){if(X.destroyed)return K();Lu.write(X.context.fd,J,0,J.length,X.pos,function(q,G){if(q)X.destroy(),K(),Z(q);else X.bytesWritten+=G,X.pos+=G,X.emit("progress"),K(),Z()})})};a71.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=!0,this.context.unref()};c71.inherits(PH,l71);function PH(J,Q){l71.call(this),Q=Q||{},this.refCount=0,this.buffer=J,this.maxChunkSize=Q.maxChunkSize||Number.MAX_SAFE_INTEGER}PH.prototype.read=function(J,Q,Z,X,Y){if(!(0<=Q&&Q<=J.length))throw RangeError("offset outside buffer: 0 <= "+Q+" <= "+J.length);if(X<0)throw RangeError("position is negative: "+X);if(Q+Z>J.length)Z=J.length-Q;if(X+Z>this.buffer.length)Z=this.buffer.length-X;if(Z<=0){setImmediate(function(){Y(null,0)});return}this.buffer.copy(J,Q,X,X+Z),setImmediate(function(){Y(null,Z)})};PH.prototype.write=function(J,Q,Z,X,Y){J.copy(this.buffer,X,Q,Q+Z),setImmediate(function(){Y(null,Z,J)})};PH.prototype.createReadStream=function(J){J=J||{};var Q=new s59(J);Q.destroyed=!1,Q.start=J.start||0,Q.endOffset=J.end,Q.pos=Q.endOffset||this.buffer.length;var Z=this.buffer.slice(Q.start,Q.pos),X=0;while(!0){var Y=X+this.maxChunkSize;if(Y>=Z.length){if(X<Z.length)Q.write(Z.slice(X,Z.length));break}Q.write(Z.slice(X,Y)),X=Y}return Q.end(),Q.destroy=function(){Q.destroyed=!0},Q};PH.prototype.createWriteStream=function(J){var Q=this;J=J||{};var Z=new nf1(J);return Z.start=J.start||0,Z.endOffset=J.end==null?this.buffer.length:+J.end,Z.bytesWritten=0,Z.pos=Z.start,Z.destroyed=!1,Z._write=function(X,Y,K){if(Z.destroyed)return;var q=Z.pos+X.length;if(q>Z.endOffset){var G=Error("maximum file length exceeded");G.code="ETOOBIG",Z.destroyed=!0,K(G);return}X.copy(Q.buffer,Z.pos,0,X.length),Z.bytesWritten+=X.length,Z.pos=q,Z.emit("progress"),K()},Z.destroy=function(){Z.destroyed=!0},Z};PH.prototype.ref=function(){this.refCount+=1};PH.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")};function t59(J,Q){return new PH(J,Q)}function e59(J,Q){return new IH(J,Q)}});var KY6=t((tv2,YY6)=>{var $V=s1("buffer").Buffer,rf1=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918000,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array<"u")rf1=new Int32Array(rf1);function XY6(J){if($V.isBuffer(J))return J;var Q=typeof $V.alloc==="function"&&typeof $V.from==="function";if(typeof J==="number")return Q?$V.alloc(J):new $V(J);else if(typeof J==="string")return Q?$V.from(J):new $V(J);else throw Error("input must be buffer, number, or string, received "+typeof J)}function KJ9(J){var Q=XY6(4);return Q.writeInt32BE(J,0),Q}function sf1(J,Q){if(J=XY6(J),$V.isBuffer(Q))Q=Q.readUInt32BE(0);var Z=~~Q^-1;for(var X=0;X<J.length;X++)Z=rf1[(Z^J[X])&255]^Z>>>8;return Z^-1}function of1(){return KJ9(sf1.apply(null,arguments))}of1.signed=function(){return sf1.apply(null,arguments)};of1.unsigned=function(){return sf1.apply(null,arguments)>>>0};YY6.exports=of1});import{randomBytes as XQ9}from"node:crypto";import{mkdir as YQ9,readFile as mY6,writeFile as KQ9}from"node:fs/promises";import qQ9 from"node:os";import Dh1 from"node:path";import{stderr as t2,stdout as p2}from"node:process";k0();F0();var Yp1={workspacePaths:[".agents/commands"],globalPaths:["~/.config/amp/commands"],enableWatching:!0};function fG6(J,Q){if(J.length!==Q.length)return!1;for(let Z=0;Z<J.length;Z++){let X=J[Z],Y=Q[Z];if(!X||!Y)return!1;if(X.name!==Y.name||X.available!==Y.available||X.lastModified!==Y.lastModified)return!1}return!0}function tT(J=Yp1,Q=null){let Z=new d2([]),X=!1,Y=null,K,q=Z.pipe(I8(fG6),vK((H)=>{return l.warn("Command stream error, using fallback",{error:H}),J0.of([])}),O9());async function G(){if(Y)return;let H=await Y6(Q);if(!H)return;let{CommandDiscovery:B}=await Promise.resolve().then(() => (Xp1(),Zp1));Y=new B(J,H),K={dispose:Y.commandChanges.subscribe((M)=>{if(!X)Z.next(M)}).unsubscribe}}async function z(){if(await G(),!Y)return l.debug("No workspace roots available, skipping command discovery"),[];return await Y.discoverCommands()}async function U(){if(X)return;try{let H=await z();Z.next(H)}catch(H){l.warn("Failed to refresh commands",{error:H})}}async function W(H){let M=(await Y6(q)).find((A)=>A.name===H);if(!M)return;let{available:V,unavailableReason:N,...L}=M;return L}async function F(H){return(await Y6(q)).find((V)=>V.name===H)?.available??!1}return U(),{commands:q,getCommand:W,refreshCommands:U,isCommandAvailable:F,dispose(){X=!0,K?.dispose(),Y?.dispose()}}}rw();F0();import sw from"node:diagnostics_channel";import{mkdirSync as uG6}from"node:fs";import{writeFile as pG6}from"node:fs/promises";import dG6 from"node:path";var zp1=!1;function Wp1(){if(zp1)return;zp1=!0;try{uG6(LJ1,{recursive:!0})}catch(X){l.error("Failed to create HTTP logs directory",{error:X})}let J=new WeakMap,Q=new WeakMap,Z=new WeakMap;sw.channel("undici:request:create").subscribe((X)=>{let{request:Y}=X,K=`${Y.origin}${Y.path}`,q={};if(Array.isArray(Y.headers))for(let z=0;z<Y.headers.length;z+=2)q[Y.headers[z]||""]=Y.headers[z+1]||"";else if(Y.headers)q=Y.headers;let G={timestamp:new Date().toISOString(),method:Y.method||"UNKNOWN",url:K,headers:q};Z.set(Y,G),J.set(Y,[])}),sw.channel("undici:request:bodyChunkSent").subscribe((X)=>{let{request:Y,chunk:K}=X;if(K&&Y){let q=J.get(Y)||[],G=typeof K==="string"?Buffer.from(K,"utf-8"):K;q.push(G),J.set(Y,q)}}),sw.channel("undici:request:headers").subscribe((X)=>{let{request:Y,response:K}=X,q=Z.get(Y);if(q){q.responseStatus=K.statusCode;let G={};if(Array.isArray(K.headers))for(let z=0;z<K.headers.length;z+=2){let U=K.headers[z],W=K.headers[z+1];if(U&&W){let F=Buffer.isBuffer(U)?U.toString("utf-8"):String(U),H=Buffer.isBuffer(W)?W.toString("utf-8"):String(W);G[F]=H}}q.responseHeaders=G}}),sw.channel("undici:request:bodyChunkReceived").subscribe((X)=>{let{request:Y,chunk:K}=X;if(K&&Y){let q=Q.get(Y)||[];q.push(K),Q.set(Y,q)}}),sw.channel("undici:request:trailers").subscribe((X)=>{let{request:Y}=X,K=Z.get(Y);if(!K)return;Up1(K).catch((q)=>{l.error("Failed to write HTTP request log",{error:q})}),J.delete(Y),Q.delete(Y),Z.delete(Y)}),sw.channel("undici:request:error").subscribe((X)=>{let{request:Y,error:K}=X,q=Z.get(Y);if(q){let G=J.get(Y),z=Q.get(Y);if(G&&G.length>0)q.requestBody=Buffer.concat(G.map((W)=>Buffer.from(W))).toString("utf-8");if(z&&z.length>0)q.responseBody=Buffer.concat(z).toString("utf-8");let U={...q,error:{message:K.message,stack:K.stack}};Up1(U).catch((W)=>{l.error("Failed to write HTTP error log",{error:W})})}J.delete(Y),Q.delete(Y),Z.delete(Y)}),l.info("HTTP request/response logging initialized")}async function Up1(J){let Z=new URL(J.url).pathname.replace(/^\//,"").replace(/\//g,"_")||"root",Y=`${new Date(J.timestamp).getTime()}_${Z}_${J.method}.json`,K=dG6.join(LJ1,Y),q=JSON.stringify(J,null,2);await pG6(K,q,"utf-8")}F0();k0();import aG6 from"node:fs";import nG6 from"node:os";var cG6=/("(?:\\?[^])*?")|(\/\/.*)|(\/\*[^]*?\*\/)/g,lG6=/("(?:\\?[^])*?")|(,\s*)(?=]|})/g,iG6={parse:(J)=>{J=String(J);try{return JSON.parse(J)}catch{return JSON.parse(J.replace(cG6,"$1").replace(lG6,"$1"))}}},Fp1=iG6;F0();k0();F0();class AJ1{options;value;lastError;lastUpdated=0;pendingPromise;eventsSubject=new p8;events=this.eventsSubject;constructor(J){this.options=J}async get(){if(this.lastError)return this.recompute();let Q=Date.now()-this.lastUpdated;if(this.value===void 0||Q>=this.options.hardTTL)return this.recompute();if(Q>=this.options.softTTL&&!this.pendingPromise)this.recompute().catch(()=>{});return this.value}getCached(){return this.value}async refresh(){return this.recompute()}recompute(){if(this.pendingPromise)return this.pendingPromise;return this.pendingPromise=this.performRecomputation(),this.pendingPromise.finally(()=>{this.pendingPromise=void 0}),this.pendingPromise}async performRecomputation(){try{let J=await this.options.compute(),Q=this.value;this.lastError=void 0,this.value=J,this.lastUpdated=Date.now();let Z=this.options.changes(Q,J);if(Z!==void 0)try{this.eventsSubject.next(Z)}catch(X){l.error("Uncaught error for GlobalCachedValue.events subscriber",X)}return J}catch(J){let Q=J instanceof Error?J:Error(String(J));this.lastError=Q;let Z=this.value;this.value=void 0;let X=this.options.changes(Z,void 0);if(X!==void 0)try{this.eventsSubject.next(X)}catch(Y){l.error("Uncaught error for GlobalCachedValue.events subscriber",Y)}throw Q}}}function rG6(J){if(!/^\d{4}-\d{2}-\d{2}$/.test(J))throw Error(`Invalid compatibility date format "${J}". Expected format: YYYY-MM-DD (e.g., "2024-01-15")`);let Z=new Date(J+"T00:00:00.000Z");if(Number.isNaN(Z.getTime()))throw Error(`Invalid compatibility date "${J}". Date could not be parsed.`);let X=J.split("-").map(Number),[Y,K,q]=X;if(X.length!==3||Y===void 0||K===void 0||q===void 0)throw Error(`Invalid compatibility date "${J}". Could not parse date components.`);if(Z.getUTCFullYear()!==Y||Z.getUTCMonth()!==K-1||Z.getUTCDate()!==q)throw Error(`Invalid compatibility date "${J}". Date components are invalid.`);return Z}var Hp1=new AJ1({compute:async()=>{try{let J=await tG6(),Q;try{Q=Fp1.parse(J)}catch(X){throw Error(`Invalid JSON in admin settings: ${X} (content: "${J}")`)}l.debug("Admin settings loaded",{rawConfig:Q});let Z={};for(let[X,Y]of Object.entries(Q))if(X.startsWith("amp.")){let K=X.substring(4);if(K==="admin.compatibilityDate")try{Z.compatibilityDate=rG6(Y)}catch(q){l.warn(`Invalid admin compatibility date: ${q instanceof Error?q.message:String(q)}`)}else Z[K]=Y}return Z}catch(J){if(J.code==="ENOENT")return{};return l.error("Failed to read admin settings",{error:J}),{}}},softTTL:30000,hardTTL:120000,changes:(J,Q)=>{let Z=sG6(J,Q);return Z.length>0?Z:void 0}});function Bp1(J,Q={fetch:()=>Hp1.get(),changes:Hp1.events}){return{...J,async get(Z,X){let Y=await Q.fetch();if(X==="admin"||!X&&Z in Y)return Y[Z];return J.get(Z,X)},async keys(){let Z=await J.keys(),X=await Q.fetch(),Y=Object.keys(X),K=new Set([...Z,...Y]);return Array.from(K)},get changes(){if(Q.changes)return dT(J.changes,Q.changes);return J.changes}}}function sG6(J,Q){let Z=J??{},X=Q??{},Y=JSON.stringify(Z,Object.keys(Z).sort()),K=JSON.stringify(X,Object.keys(X).sort());if(Y===K)return[];let q=new Set([...Object.keys(Z),...Object.keys(X)]);return Array.from(q)}function oG6(){switch(nG6.platform()){case"darwin":return"/Library/Application Support/ampcode/managed-settings.json";case"linux":return"/etc/ampcode/managed-settings.json";case"win32":return"C:\\ProgramData\\ampcode\\managed-settings.json";default:return null}}async function tG6(){let J=oG6();if(!J)return"{}";try{return await aG6.promises.readFile(J,"utf-8")}catch(Q){if(Q.code==="ENOENT")return"{}";throw Q}}j2();k0();var eT=new d2({});function _U(J,Q){let Z=eT.getValue();eT.next({...Z,[J]:Q})}function Vp1(J){return eT.getValue()[J]}s6();k0();fH();BR();rV();Rp();j2();jp();function zQ1({storage:J,secretStorage:Q,workspaceRoots:Z,defaultAmpURL:X=tQ,defaultCacheDirectory:Y,preferThreadEnv:K,homeDir:q,userConfigDir:G}){let z=d8(async()=>{let B=await J.keys();return Object.fromEntries(await Promise.all(B.map(async(V)=>[V,await J.get(V)])))}).pipe(w9((B)=>cT(J0.of(B),J.changes.pipe(vU(async(M)=>{return await Promise.all(M.map(async(V)=>{let N=await J.get(V);B[V]=N})),B})))),S0((B)=>{let M={...B,url:B.url||X,"todos.enabled":B["todos.enabled"]??!0,cacheDirectory:B.cacheDirectory||Y};if(M.permissions)M.permissions=Jp(M.permissions);return M}),O9(),I8()),U=D2(Q.changes.pipe(Y7(void 0)),z.pipe(S0(({url:B})=>B),I8())).pipe(vU(async([,B])=>({getToken:async(M,V)=>{return Q.get(M,V)},isSet:{[B]:Object.fromEntries(await Promise.all(Xc1.map(async(M)=>[M,!!await Q.get(M,B)])))}}))),W=D2(z,U,eT).pipe(S0(([B,M,V])=>({settings:{...B,...V},secrets:M})),O9());Mp1(W);let F=Z.pipe(S0((B)=>({workspaceFolders:B?.map(q8)??null,isWindows:OR().os==="windows",homeDir:typeof process==="object"&&process.env.HOME?q8(x0.file(process.env.HOME)):void 0,preferThreadEnv:K}))),H=F.subscribe((B)=>{Zp(B)});return{get(B,M){return J.get(B,M)},updateSettings(B,M,V){return J.set(B,M,V)},async appendSettings(B,M,V){let N=await J.get(B,V);if(N===void 0)return J.set(B,M,V);else if(!Array.isArray(N))throw Error(`Cannot append to non-array setting: ${B}`);else if(N.length===0)return J.set(B,M,V);else{let L=[...N,...M];return J.set(B,L,V)}},async prependSettings(B,M,V){let N=await J.get(B,V);if(N===void 0)return J.set(B,M,V);else if(!Array.isArray(N))throw Error(`Cannot prepend to non-array setting: ${B}`);else if(N.length===0)return J.set(B,M,V);else{let L=[...M,...N];return J.set(B,L,V)}},updateSecret(B,M,V){return Q.set(B,M,V)},workspaceRoots:Z,displayPathEnvInfo:F,homeDir:q,userConfigDir:G,config:W,async getLatest(B){return Y6(W,B)},unsubscribe(){H.unsubscribe()}}}UQ1();fH();lR();kd();u4();s6();k0();F0();j2();var ea1=100;$2();sU();var oM6=60000;class fq1{constructor(J){this._options=J,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(nd,(Q)=>{let Z=this._requestHandlerAbortControllers.get(Q.params.requestId);Z===null||Z===void 0||Z.abort(Q.params.reason)}),this.setNotificationHandler(sd,(Q)=>{this._onprogress(Q)}),this.setRequestHandler(rd,(Q)=>({}))}_setupTimeout(J,Q,Z,X,Y=!1){this._timeoutInfo.set(J,{timeoutId:setTimeout(X,Q),startTime:Date.now(),timeout:Q,maxTotalTimeout:Z,resetTimeoutOnProgress:Y,onTimeout:X})}_resetTimeout(J){let Q=this._timeoutInfo.get(J);if(!Q)return!1;let Z=Date.now()-Q.startTime;if(Q.maxTotalTimeout&&Z>=Q.maxTotalTimeout)throw this._timeoutInfo.delete(J),new mK(UY.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Q.maxTotalTimeout,totalElapsed:Z});return clearTimeout(Q.timeoutId),Q.timeoutId=setTimeout(Q.onTimeout,Q.timeout),!0}_cleanupTimeout(J){let Q=this._timeoutInfo.get(J);if(Q)clearTimeout(Q.timeoutId),this._timeoutInfo.delete(J)}async connect(J){var Q,Z,X;this._transport=J;let Y=(Q=this.transport)===null||Q===void 0?void 0:Q.onclose;this._transport.onclose=()=>{Y===null||Y===void 0||Y(),this._onclose()};let K=(Z=this.transport)===null||Z===void 0?void 0:Z.onerror;this._transport.onerror=(G)=>{K===null||K===void 0||K(G),this._onerror(G)};let q=(X=this._transport)===null||X===void 0?void 0:X.onmessage;this._transport.onmessage=(G,z)=>{if(q===null||q===void 0||q(G,z),$S(G)||zn1(G))this._onresponse(G);else if(ad(G))this._onrequest(G,z);else if(Kn1(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){var J;let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(J=this.onclose)===null||J===void 0||J.call(this);let Z=new mK(UY.ConnectionClosed,"Connection closed");for(let X of Q.values())X(Z)}_onerror(J){var Q;(Q=this.onerror)===null||Q===void 0||Q.call(this,J)}_onnotification(J){var Q;let Z=(Q=this._notificationHandlers.get(J.method))!==null&&Q!==void 0?Q:this.fallbackNotificationHandler;if(Z===void 0)return;Promise.resolve().then(()=>Z(J)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(J,Q){var Z,X;let Y=(Z=this._requestHandlers.get(J.method))!==null&&Z!==void 0?Z:this.fallbackRequestHandler,K=this._transport;if(Y===void 0){K===null||K===void 0||K.send({jsonrpc:"2.0",id:J.id,error:{code:UY.MethodNotFound,message:"Method not found"}}).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let q=new AbortController;this._requestHandlerAbortControllers.set(J.id,q);let G={signal:q.signal,sessionId:K===null||K===void 0?void 0:K.sessionId,_meta:(X=J.params)===null||X===void 0?void 0:X._meta,sendNotification:(z)=>this.notification(z,{relatedRequestId:J.id}),sendRequest:(z,U,W)=>this.request(z,U,{...W,relatedRequestId:J.id}),authInfo:Q===null||Q===void 0?void 0:Q.authInfo,requestId:J.id,requestInfo:Q===null||Q===void 0?void 0:Q.requestInfo};Promise.resolve().then(()=>Y(J,G)).then((z)=>{if(q.signal.aborted)return;return K===null||K===void 0?void 0:K.send({result:z,jsonrpc:"2.0",id:J.id})},(z)=>{var U;if(q.signal.aborted)return;return K===null||K===void 0?void 0:K.send({jsonrpc:"2.0",id:J.id,error:{code:Number.isSafeInteger(z.code)?z.code:UY.InternalError,message:(U=z.message)!==null&&U!==void 0?U:"Internal error"}})}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{this._requestHandlerAbortControllers.delete(J.id)})}_onprogress(J){let{progressToken:Q,...Z}=J.params,X=Number(Q),Y=this._progressHandlers.get(X);if(!Y){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(J)}`));return}let K=this._responseHandlers.get(X),q=this._timeoutInfo.get(X);if(q&&K&&q.resetTimeoutOnProgress)try{this._resetTimeout(X)}catch(G){K(G);return}Y(Z)}_onresponse(J){let Q=Number(J.id),Z=this._responseHandlers.get(Q);if(Z===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(J)}`));return}if(this._responseHandlers.delete(Q),this._progressHandlers.delete(Q),this._cleanupTimeout(Q),$S(J))Z(J);else{let X=new mK(J.error.code,J.error.message,J.error.data);Z(X)}}get transport(){return this._transport}async close(){var J;await((J=this._transport)===null||J===void 0?void 0:J.close())}request(J,Q,Z){let{relatedRequestId:X,resumptionToken:Y,onresumptiontoken:K}=Z!==null&&Z!==void 0?Z:{};return new Promise((q,G)=>{var z,U,W,F,H,B;if(!this._transport){G(Error("Not connected"));return}if(((z=this._options)===null||z===void 0?void 0:z.enforceStrictCapabilities)===!0)this.assertCapabilityForMethod(J.method);(U=Z===null||Z===void 0?void 0:Z.signal)===null||U===void 0||U.throwIfAborted();let M=this._requestMessageId++,V={...J,jsonrpc:"2.0",id:M};if(Z===null||Z===void 0?void 0:Z.onprogress)this._progressHandlers.set(M,Z.onprogress),V.params={...J.params,_meta:{...((W=J.params)===null||W===void 0?void 0:W._meta)||{},progressToken:M}};let N=(w)=>{var R;this._responseHandlers.delete(M),this._progressHandlers.delete(M),this._cleanupTimeout(M),(R=this._transport)===null||R===void 0||R.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:M,reason:String(w)}},{relatedRequestId:X,resumptionToken:Y,onresumptiontoken:K}).catch((O)=>this._onerror(Error(`Failed to send cancellation: ${O}`))),G(w)};this._responseHandlers.set(M,(w)=>{var R;if((R=Z===null||Z===void 0?void 0:Z.signal)===null||R===void 0?void 0:R.aborted)return;if(w instanceof Error)return G(w);try{let O=Q.parse(w.result);q(O)}catch(O){G(O)}}),(F=Z===null||Z===void 0?void 0:Z.signal)===null||F===void 0||F.addEventListener("abort",()=>{var w;N((w=Z===null||Z===void 0?void 0:Z.signal)===null||w===void 0?void 0:w.reason)});let L=(H=Z===null||Z===void 0?void 0:Z.timeout)!==null&&H!==void 0?H:oM6,A=()=>N(new mK(UY.RequestTimeout,"Request timed out",{timeout:L}));this._setupTimeout(M,L,Z===null||Z===void 0?void 0:Z.maxTotalTimeout,A,(B=Z===null||Z===void 0?void 0:Z.resetTimeoutOnProgress)!==null&&B!==void 0?B:!1),this._transport.send(V,{relatedRequestId:X,resumptionToken:Y,onresumptiontoken:K}).catch((w)=>{this._cleanupTimeout(M),G(w)})})}async notification(J,Q){var Z,X;if(!this._transport)throw Error("Not connected");if(this.assertNotificationCapability(J.method),((X=(Z=this._options)===null||Z===void 0?void 0:Z.debouncedNotificationMethods)!==null&&X!==void 0?X:[]).includes(J.method)&&!J.params&&!(Q===null||Q===void 0?void 0:Q.relatedRequestId)){if(this._pendingDebouncedNotifications.has(J.method))return;this._pendingDebouncedNotifications.add(J.method),Promise.resolve().then(()=>{var G;if(this._pendingDebouncedNotifications.delete(J.method),!this._transport)return;let z={...J,jsonrpc:"2.0"};(G=this._transport)===null||G===void 0||G.send(z,Q).catch((U)=>this._onerror(U))});return}let q={...J,jsonrpc:"2.0"};await this._transport.send(q,Q)}setRequestHandler(J,Q){let Z=J.shape.method.value;this.assertRequestHandlerCapability(Z),this._requestHandlers.set(Z,(X,Y)=>{return Promise.resolve(Q(J.parse(X),Y))})}removeRequestHandler(J){this._requestHandlers.delete(J)}assertCanSetRequestHandler(J){if(this._requestHandlers.has(J))throw Error(`A request handler for ${J} already exists, which would be overridden`)}setNotificationHandler(J,Q){this._notificationHandlers.set(J.shape.method.value,(Z)=>Promise.resolve(Q(J.parse(Z))))}removeNotificationHandler(J){this._notificationHandlers.delete(J)}}function Ln1(J,Q){return Object.entries(Q).reduce((Z,[X,Y])=>{if(Y&&typeof Y==="object")Z[X]=Z[X]?{...Z[X],...Y}:Y;else Z[X]=Y;return Z},{...J})}sU();var ws1=r6(As1(),1);class PS extends fq1{constructor(J,Q){var Z;super(Q);this._clientInfo=J,this._cachedToolOutputValidators=new Map,this._capabilities=(Z=Q===null||Q===void 0?void 0:Q.capabilities)!==null&&Z!==void 0?Z:{},this._ajv=new ws1.default}registerCapabilities(J){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Ln1(this._capabilities,J)}assertCapability(J,Q){var Z;if(!((Z=this._serverCapabilities)===null||Z===void 0?void 0:Z[J]))throw Error(`Server does not support ${J} (required for ${Q})`)}async connect(J,Q){if(await super.connect(J),J.sessionId!==void 0)return;try{let Z=await this.request({method:"initialize",params:{protocolVersion:iR,capabilities:this._capabilities,clientInfo:this._clientInfo}},Rq1,Q);if(Z===void 0)throw Error(`Server sent invalid initialize result: ${Z}`);if(!Jn1.includes(Z.protocolVersion))throw Error(`Server's protocol version is not supported: ${Z.protocolVersion}`);if(this._serverCapabilities=Z.capabilities,this._serverVersion=Z.serverInfo,J.setProtocolVersion)J.setProtocolVersion(Z.protocolVersion);this._instructions=Z.instructions,await this.notification({method:"notifications/initialized"})}catch(Z){throw this.close(),Z}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(J){var Q,Z,X,Y,K;switch(J){case"logging/setLevel":if(!((Q=this._serverCapabilities)===null||Q===void 0?void 0:Q.logging))throw Error(`Server does not support logging (required for ${J})`);break;case"prompts/get":case"prompts/list":if(!((Z=this._serverCapabilities)===null||Z===void 0?void 0:Z.prompts))throw Error(`Server does not support prompts (required for ${J})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!((X=this._serverCapabilities)===null||X===void 0?void 0:X.resources))throw Error(`Server does not support resources (required for ${J})`);if(J==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${J})`);break;case"tools/call":case"tools/list":if(!((Y=this._serverCapabilities)===null||Y===void 0?void 0:Y.tools))throw Error(`Server does not support tools (required for ${J})`);break;case"completion/complete":if(!((K=this._serverCapabilities)===null||K===void 0?void 0:K.completions))throw Error(`Server does not support completions (required for ${J})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(J){var Q;switch(J){case"notifications/roots/list_changed":if(!((Q=this._capabilities.roots)===null||Q===void 0?void 0:Q.listChanged))throw Error(`Client does not support roots list changed notifications (required for ${J})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(J){switch(J){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${J})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${J})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${J})`);break;case"ping":break}}async ping(J){return this.request({method:"ping"},NN,J)}async complete(J,Q){return this.request({method:"completion/complete",params:J},yq1,Q)}async setLoggingLevel(J,Q){return this.request({method:"logging/setLevel",params:{level:J}},NN,Q)}async getPrompt(J,Q){return this.request({method:"prompts/get",params:J},vq1,Q)}async listPrompts(J,Q){return this.request({method:"prompts/list",params:J},Pq1,Q)}async listResources(J,Q){return this.request({method:"resources/list",params:J},jq1,Q)}async listResourceTemplates(J,Q){return this.request({method:"resources/templates/list",params:J},$q1,Q)}async readResource(J,Q){return this.request({method:"resources/read",params:J},Eq1,Q)}async subscribeResource(J,Q){return this.request({method:"resources/subscribe",params:J},NN,Q)}async unsubscribeResource(J,Q){return this.request({method:"resources/unsubscribe",params:J},NN,Q)}async callTool(J,Q=ed,Z){let X=await this.request({method:"tools/call",params:J},Q,Z),Y=this.getToolOutputValidator(J.name);if(Y){if(!X.structuredContent&&!X.isError)throw new mK(UY.InvalidRequest,`Tool ${J.name} has an output schema but did not return structured content`);if(X.structuredContent)try{if(!Y(X.structuredContent))throw new mK(UY.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(Y.errors)}`)}catch(K){if(K instanceof mK)throw K;throw new mK(UY.InvalidParams,`Failed to validate structured content: ${K instanceof Error?K.message:String(K)}`)}}return X}cacheToolOutputSchemas(J){this._cachedToolOutputValidators.clear();for(let Q of J)if(Q.outputSchema)try{let Z=this._ajv.compile(Q.outputSchema);this._cachedToolOutputValidators.set(Q.name,Z)}catch(Z){}}getToolOutputValidator(J){return this._cachedToolOutputValidators.get(J)}async listTools(J,Q){let Z=await this.request({method:"tools/list",params:J},_q1,Q);return this.cacheToolOutputSchemas(Z.tools),Z}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}Nc();class WG1 extends Event{constructor(J,Q){var Z,X;super(J),this.code=(Z=Q==null?void 0:Q.code)!=null?Z:void 0,this.message=(X=Q==null?void 0:Q.message)!=null?X:void 0}[Symbol.for("nodejs.util.inspect.custom")](J,Q,Z){return Z(Rs1(this),Q)}[Symbol.for("Deno.customInspect")](J,Q){return J(Rs1(this),Q)}}function vN6(J){let Q=globalThis.DOMException;return typeof Q=="function"?new Q(J,"SyntaxError"):SyntaxError(J)}function FG1(J){return J instanceof Error?"errors"in J&&Array.isArray(J.errors)?J.errors.map(FG1).join(", "):("cause"in J)&&J.cause instanceof Error?`${J}: ${FG1(J.cause)}`:J.message:`${J}`}function Rs1(J){return{type:J.type,message:J.message,code:J.code,defaultPrevented:J.defaultPrevented,cancelable:J.cancelable,timeStamp:J.timeStamp}}var js1=(J)=>{throw TypeError(J)},AG1=(J,Q,Z)=>Q.has(J)||js1("Cannot "+Z),F9=(J,Q,Z)=>(AG1(J,Q,"read from private field"),Z?Z.call(J):Q.get(J)),p7=(J,Q,Z)=>Q.has(J)?js1("Cannot add the same private member more than once"):Q instanceof WeakSet?Q.add(J):Q.set(J,Z),D4=(J,Q,Z,X)=>(AG1(J,Q,"write to private field"),Q.set(J,Z),Z),oU=(J,Q,Z)=>(AG1(J,Q,"access private method"),Z),KZ,wN,rR,Lc,Ac,SS,tR,vS,XB,sR,eR,oR,TS,uK,HG1,BG1,DG1,Os1,MG1,VG1,CS,NG1,LG1;class JO extends EventTarget{constructor(J,Q){var Z,X;super(),p7(this,uK),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,p7(this,KZ),p7(this,wN),p7(this,rR),p7(this,Lc),p7(this,Ac),p7(this,SS),p7(this,tR),p7(this,vS,null),p7(this,XB),p7(this,sR),p7(this,eR,null),p7(this,oR,null),p7(this,TS,null),p7(this,BG1,async(Y)=>{var K;F9(this,sR).reset();let{body:q,redirected:G,status:z,headers:U}=Y;if(z===204){oU(this,uK,CS).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(G?D4(this,rR,new URL(Y.url)):D4(this,rR,void 0),z!==200){oU(this,uK,CS).call(this,`Non-200 status code (${z})`,z);return}if(!(U.get("content-type")||"").startsWith("text/event-stream")){oU(this,uK,CS).call(this,'Invalid content type, expected "text/event-stream"',z);return}if(F9(this,KZ)===this.CLOSED)return;D4(this,KZ,this.OPEN);let W=new Event("open");if((K=F9(this,TS))==null||K.call(this,W),this.dispatchEvent(W),typeof q!="object"||!q||!("getReader"in q)){oU(this,uK,CS).call(this,"Invalid response body, expected a web ReadableStream",z),this.close();return}let F=new TextDecoder,H=q.getReader(),B=!0;do{let{done:M,value:V}=await H.read();V&&F9(this,sR).feed(F.decode(V,{stream:!M})),M&&(B=!1,F9(this,sR).reset(),oU(this,uK,NG1).call(this))}while(B)}),p7(this,DG1,(Y)=>{D4(this,XB,void 0),!(Y.name==="AbortError"||Y.type==="aborted")&&oU(this,uK,NG1).call(this,FG1(Y))}),p7(this,MG1,(Y)=>{typeof Y.id=="string"&&D4(this,vS,Y.id);let K=new MessageEvent(Y.event||"message",{data:Y.data,origin:F9(this,rR)?F9(this,rR).origin:F9(this,wN).origin,lastEventId:Y.id||""});F9(this,oR)&&(!Y.event||Y.event==="message")&&F9(this,oR).call(this,K),this.dispatchEvent(K)}),p7(this,VG1,(Y)=>{D4(this,SS,Y)}),p7(this,LG1,()=>{D4(this,tR,void 0),F9(this,KZ)===this.CONNECTING&&oU(this,uK,HG1).call(this)});try{if(J instanceof URL)D4(this,wN,J);else if(typeof J=="string")D4(this,wN,new URL(J,kN6()));else throw Error("Invalid URL")}catch{throw vN6("An invalid or illegal string was specified")}D4(this,sR,nR({onEvent:F9(this,MG1),onRetry:F9(this,VG1)})),D4(this,KZ,this.CONNECTING),D4(this,SS,3000),D4(this,Ac,(Z=Q==null?void 0:Q.fetch)!=null?Z:globalThis.fetch),D4(this,Lc,(X=Q==null?void 0:Q.withCredentials)!=null?X:!1),oU(this,uK,HG1).call(this)}get readyState(){return F9(this,KZ)}get url(){return F9(this,wN).href}get withCredentials(){return F9(this,Lc)}get onerror(){return F9(this,eR)}set onerror(J){D4(this,eR,J)}get onmessage(){return F9(this,oR)}set onmessage(J){D4(this,oR,J)}get onopen(){return F9(this,TS)}set onopen(J){D4(this,TS,J)}addEventListener(J,Q,Z){let X=Q;super.addEventListener(J,X,Z)}removeEventListener(J,Q,Z){let X=Q;super.removeEventListener(J,X,Z)}close(){F9(this,tR)&&clearTimeout(F9(this,tR)),F9(this,KZ)!==this.CLOSED&&(F9(this,XB)&&F9(this,XB).abort(),D4(this,KZ,this.CLOSED),D4(this,XB,void 0))}}KZ=new WeakMap,wN=new WeakMap,rR=new WeakMap,Lc=new WeakMap,Ac=new WeakMap,SS=new WeakMap,tR=new WeakMap,vS=new WeakMap,XB=new WeakMap,sR=new WeakMap,eR=new WeakMap,oR=new WeakMap,TS=new WeakMap,uK=new WeakSet,HG1=function(){D4(this,KZ,this.CONNECTING),D4(this,XB,new AbortController),F9(this,Ac)(F9(this,wN),oU(this,uK,Os1).call(this)).then(F9(this,BG1)).catch(F9(this,DG1))},BG1=new WeakMap,DG1=new WeakMap,Os1=function(){var J;let Q={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...F9(this,vS)?{"Last-Event-ID":F9(this,vS)}:void 0},cache:"no-store",signal:(J=F9(this,XB))==null?void 0:J.signal};return"window"in globalThis&&(Q.credentials=this.withCredentials?"include":"same-origin"),Q},MG1=new WeakMap,VG1=new WeakMap,CS=function(J,Q){var Z;F9(this,KZ)!==this.CLOSED&&D4(this,KZ,this.CLOSED);let X=new WG1("error",{code:Q,message:J});(Z=F9(this,eR))==null||Z.call(this,X),this.dispatchEvent(X)},NG1=function(J,Q){var Z;if(F9(this,KZ)===this.CLOSED)return;D4(this,KZ,this.CONNECTING);let X=new WG1("error",{code:Q,message:J});(Z=F9(this,eR))==null||Z.call(this,X),this.dispatchEvent(X),D4(this,tR,setTimeout(F9(this,LG1),F9(this,SS)))},LG1=new WeakMap,JO.CONNECTING=0,JO.OPEN=1,JO.CLOSED=2;function kN6(){let J="document"in globalThis?globalThis.document:void 0;return J&&typeof J=="object"&&"baseURI"in J&&typeof J.baseURI=="string"?J.baseURI:void 0}sU();var wG1;wG1=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((J)=>J.webcrypto);async function _N6(J){return(await wG1).getRandomValues(new Uint8Array(J))}async function xN6(J){let Z="",X=await _N6(J);for(let Y=0;Y<J;Y++){let K=X[Y]%66;Z+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[K]}return Z}async function bN6(J){return await xN6(J)}async function yN6(J){let Q=await(await wG1).subtle.digest("SHA-256",new TextEncoder().encode(J));return btoa(String.fromCharCode(...new Uint8Array(Q))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function RG1(J){if(!J)J=43;if(J<43||J>128)throw`Expected a length between 43 and 128. Received ${J}.`;let Q=await bN6(J),Z=await yN6(Q);return{code_verifier:Q,code_challenge:Z}}sU();fU();var $s1=Q1.object({resource:Q1.string().url(),authorization_servers:Q1.array(Q1.string().url()).optional(),jwks_uri:Q1.string().url().optional(),scopes_supported:Q1.array(Q1.string()).optional(),bearer_methods_supported:Q1.array(Q1.string()).optional(),resource_signing_alg_values_supported:Q1.array(Q1.string()).optional(),resource_name:Q1.string().optional(),resource_documentation:Q1.string().optional(),resource_policy_uri:Q1.string().url().optional(),resource_tos_uri:Q1.string().url().optional(),tls_client_certificate_bound_access_tokens:Q1.boolean().optional(),authorization_details_types_supported:Q1.array(Q1.string()).optional(),dpop_signing_alg_values_supported:Q1.array(Q1.string()).optional(),dpop_bound_access_tokens_required:Q1.boolean().optional()}).passthrough(),OG1=Q1.object({issuer:Q1.string(),authorization_endpoint:Q1.string(),token_endpoint:Q1.string(),registration_endpoint:Q1.string().optional(),scopes_supported:Q1.array(Q1.string()).optional(),response_types_supported:Q1.array(Q1.string()),response_modes_supported:Q1.array(Q1.string()).optional(),grant_types_supported:Q1.array(Q1.string()).optional(),token_endpoint_auth_methods_supported:Q1.array(Q1.string()).optional(),token_endpoint_auth_signing_alg_values_supported:Q1.array(Q1.string()).optional(),service_documentation:Q1.string().optional(),revocation_endpoint:Q1.string().optional(),revocation_endpoint_auth_methods_supported:Q1.array(Q1.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Q1.array(Q1.string()).optional(),introspection_endpoint:Q1.string().optional(),introspection_endpoint_auth_methods_supported:Q1.array(Q1.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Q1.array(Q1.string()).optional(),code_challenge_methods_supported:Q1.array(Q1.string()).optional()}).passthrough(),fN6=Q1.object({issuer:Q1.string(),authorization_endpoint:Q1.string(),token_endpoint:Q1.string(),userinfo_endpoint:Q1.string().optional(),jwks_uri:Q1.string(),registration_endpoint:Q1.string().optional(),scopes_supported:Q1.array(Q1.string()).optional(),response_types_supported:Q1.array(Q1.string()),response_modes_supported:Q1.array(Q1.string()).optional(),grant_types_supported:Q1.array(Q1.string()).optional(),acr_values_supported:Q1.array(Q1.string()).optional(),subject_types_supported:Q1.array(Q1.string()),id_token_signing_alg_values_supported:Q1.array(Q1.string()),id_token_encryption_alg_values_supported:Q1.array(Q1.string()).optional(),id_token_encryption_enc_values_supported:Q1.array(Q1.string()).optional(),userinfo_signing_alg_values_supported:Q1.array(Q1.string()).optional(),userinfo_encryption_alg_values_supported:Q1.array(Q1.string()).optional(),userinfo_encryption_enc_values_supported:Q1.array(Q1.string()).optional(),request_object_signing_alg_values_supported:Q1.array(Q1.string()).optional(),request_object_encryption_alg_values_supported:Q1.array(Q1.string()).optional(),request_object_encryption_enc_values_supported:Q1.array(Q1.string()).optional(),token_endpoint_auth_methods_supported:Q1.array(Q1.string()).optional(),token_endpoint_auth_signing_alg_values_supported:Q1.array(Q1.string()).optional(),display_values_supported:Q1.array(Q1.string()).optional(),claim_types_supported:Q1.array(Q1.string()).optional(),claims_supported:Q1.array(Q1.string()).optional(),service_documentation:Q1.string().optional(),claims_locales_supported:Q1.array(Q1.string()).optional(),ui_locales_supported:Q1.array(Q1.string()).optional(),claims_parameter_supported:Q1.boolean().optional(),request_parameter_supported:Q1.boolean().optional(),request_uri_parameter_supported:Q1.boolean().optional(),require_request_uri_registration:Q1.boolean().optional(),op_policy_uri:Q1.string().optional(),op_tos_uri:Q1.string().optional()}).passthrough(),Es1=fN6.merge(OG1.pick({code_challenge_methods_supported:!0})),jG1=Q1.object({access_token:Q1.string(),id_token:Q1.string().optional(),token_type:Q1.string(),expires_in:Q1.number().optional(),scope:Q1.string().optional(),refresh_token:Q1.string().optional()}).strip(),Is1=Q1.object({error:Q1.string(),error_description:Q1.string().optional(),error_uri:Q1.string().optional()}),hN6=Q1.object({redirect_uris:Q1.array(Q1.string()).refine((J)=>J.every((Q)=>URL.canParse(Q)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:Q1.string().optional(),grant_types:Q1.array(Q1.string()).optional(),response_types:Q1.array(Q1.string()).optional(),client_name:Q1.string().optional(),client_uri:Q1.string().optional(),logo_uri:Q1.string().optional(),scope:Q1.string().optional(),contacts:Q1.array(Q1.string()).optional(),tos_uri:Q1.string().optional(),policy_uri:Q1.string().optional(),jwks_uri:Q1.string().optional(),jwks:Q1.any().optional(),software_id:Q1.string().optional(),software_version:Q1.string().optional(),software_statement:Q1.string().optional()}).strip(),gN6=Q1.object({client_id:Q1.string(),client_secret:Q1.string().optional(),client_id_issued_at:Q1.number().optional(),client_secret_expires_at:Q1.number().optional()}).strip(),Ps1=hN6.merge(gN6),xW9=Q1.object({error:Q1.string(),error_description:Q1.string().optional()}).strip(),bW9=Q1.object({token:Q1.string(),token_type_hint:Q1.string().optional()}).strip();function Ts1(J){let Q=typeof J==="string"?new URL(J):new URL(J.href);return Q.hash="",Q}function Cs1({requestedResource:J,configuredResource:Q}){let Z=typeof J==="string"?new URL(J):new URL(J.href),X=typeof Q==="string"?new URL(Q):new URL(Q.href);if(Z.origin!==X.origin)return!1;if(Z.pathname.length<X.pathname.length)return!1;let Y=Z.pathname.endsWith("/")?Z.pathname:Z.pathname+"/",K=X.pathname.endsWith("/")?X.pathname:X.pathname+"/";return Y.startsWith(K)}class d7 extends Error{constructor(J,Q){super(J);this.errorUri=Q,this.name=this.constructor.name}toResponseObject(){let J={error:this.errorCode,error_description:this.message};if(this.errorUri)J.error_uri=this.errorUri;return J}get errorCode(){return this.constructor.errorCode}}class wc extends d7{}wc.errorCode="invalid_request";class QO extends d7{}QO.errorCode="invalid_client";class ZO extends d7{}ZO.errorCode="invalid_grant";class XO extends d7{}XO.errorCode="unauthorized_client";class Rc extends d7{}Rc.errorCode="unsupported_grant_type";class Oc extends d7{}Oc.errorCode="invalid_scope";class jc extends d7{}jc.errorCode="access_denied";class YB extends d7{}YB.errorCode="server_error";class $c extends d7{}$c.errorCode="temporarily_unavailable";class Ec extends d7{}Ec.errorCode="unsupported_response_type";class Ic extends d7{}Ic.errorCode="unsupported_token_type";class Pc extends d7{}Pc.errorCode="invalid_token";class Tc extends d7{}Tc.errorCode="method_not_allowed";class Cc extends d7{}Cc.errorCode="too_many_requests";class Sc extends d7{}Sc.errorCode="invalid_client_metadata";class vc extends d7{}vc.errorCode="insufficient_scope";var Ss1={[wc.errorCode]:wc,[QO.errorCode]:QO,[ZO.errorCode]:ZO,[XO.errorCode]:XO,[Rc.errorCode]:Rc,[Oc.errorCode]:Oc,[jc.errorCode]:jc,[YB.errorCode]:YB,[$c.errorCode]:$c,[Ec.errorCode]:Ec,[Ic.errorCode]:Ic,[Pc.errorCode]:Pc,[Tc.errorCode]:Tc,[Cc.errorCode]:Cc,[Sc.errorCode]:Sc,[vc.errorCode]:vc};class BX extends Error{constructor(J){super(J!==null&&J!==void 0?J:"Unauthorized")}}function ks1(J,Q){let Z=J.client_secret!==void 0;if(Q.length===0)return Z?"client_secret_post":"none";if(Z&&Q.includes("client_secret_basic"))return"client_secret_basic";if(Z&&Q.includes("client_secret_post"))return"client_secret_post";if(Q.includes("none"))return"none";return Z?"client_secret_post":"none"}function _s1(J,Q,Z,X){let{client_id:Y,client_secret:K}=Q;switch(J){case"client_secret_basic":mN6(Y,K,Z);return;case"client_secret_post":uN6(Y,K,X);return;case"none":pN6(Y,X);return;default:throw Error(`Unsupported client authentication method: ${J}`)}}function mN6(J,Q,Z){if(!Q)throw Error("client_secret_basic authentication requires a client_secret");let X=btoa(`${J}:${Q}`);Z.set("Authorization",`Basic ${X}`)}function uN6(J,Q,Z){if(Z.set("client_id",J),Q)Z.set("client_secret",Q)}function pN6(J,Q){Q.set("client_id",J)}async function EG1(J){let Q=J instanceof Response?J.status:void 0,Z=J instanceof Response?await J.text():J;try{let X=Is1.parse(JSON.parse(Z)),{error:Y,error_description:K,error_uri:q}=X;return new(Ss1[Y]||YB)(K||"",q)}catch(X){let Y=`${Q?`HTTP ${Q}: `:""}Invalid OAuth error response: ${X}. Raw body: ${Z}`;return new YB(Y)}}async function KB(J,Q){var Z,X;try{return await $G1(J,Q)}catch(Y){if(Y instanceof QO||Y instanceof XO)return await((Z=J.invalidateCredentials)===null||Z===void 0?void 0:Z.call(J,"all")),await $G1(J,Q);else if(Y instanceof ZO)return await((X=J.invalidateCredentials)===null||X===void 0?void 0:X.call(J,"tokens")),await $G1(J,Q);throw Y}}async function $G1(J,{serverUrl:Q,authorizationCode:Z,scope:X,resourceMetadataUrl:Y,fetchFn:K}){let q,G;try{if(q=await cN6(Q,{resourceMetadataUrl:Y},K),q.authorization_servers&&q.authorization_servers.length>0)G=q.authorization_servers[0]}catch(V){}if(!G)G=Q;let z=await dN6(Q,J,q),U=await rN6(G,{fetchFn:K}),W=await Promise.resolve(J.clientInformation());if(!W){if(Z!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");if(!J.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let V=await eN6(G,{metadata:U,clientMetadata:J.clientMetadata});await J.saveClientInformation(V),W=V}if(Z!==void 0){let V=await J.codeVerifier(),N=await oN6(G,{metadata:U,clientInformation:W,authorizationCode:Z,codeVerifier:V,redirectUri:J.redirectUrl,resource:z,addClientAuthentication:J.addClientAuthentication,fetchFn:K});return await J.saveTokens(N),"AUTHORIZED"}let F=await J.tokens();if(F===null||F===void 0?void 0:F.refresh_token)try{let V=await tN6(G,{metadata:U,clientInformation:W,refreshToken:F.refresh_token,resource:z,addClientAuthentication:J.addClientAuthentication});return await J.saveTokens(V),"AUTHORIZED"}catch(V){if(!(V instanceof d7)||V instanceof YB);else throw V}let H=J.state?await J.state():void 0,{authorizationUrl:B,codeVerifier:M}=await sN6(G,{metadata:U,clientInformation:W,state:H,redirectUrl:J.redirectUrl,scope:X||J.clientMetadata.scope,resource:z});return await J.saveCodeVerifier(M),await J.redirectToAuthorization(B),"REDIRECT"}async function dN6(J,Q,Z){let X=Ts1(J);if(Q.validateResourceURL)return await Q.validateResourceURL(X,Z===null||Z===void 0?void 0:Z.resource);if(!Z)return;if(!Cs1({requestedResource:X,configuredResource:Z.resource}))throw Error(`Protected resource ${Z.resource} does not match expected ${X} (or origin)`);return new URL(Z.resource)}function kS(J){let Q=J.headers.get("WWW-Authenticate");if(!Q)return;let[Z,X]=Q.split(" ");if(Z.toLowerCase()!=="bearer"||!X)return;let K=/resource_metadata="([^"]*)"/.exec(Q);if(!K)return;try{return new URL(K[1])}catch(q){return}}async function cN6(J,Q,Z=fetch){let X=await aN6(J,"oauth-protected-resource",Z,{protocolVersion:Q===null||Q===void 0?void 0:Q.protocolVersion,metadataUrl:Q===null||Q===void 0?void 0:Q.resourceMetadataUrl});if(!X||X.status===404)throw Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!X.ok)throw Error(`HTTP ${X.status} trying to load well-known OAuth protected resource metadata.`);return $s1.parse(await X.json())}async function IG1(J,Q,Z=fetch){try{return await Z(J,{headers:Q})}catch(X){if(X instanceof TypeError)if(Q)return IG1(J,void 0,Z);else return;throw X}}function lN6(J,Q="",Z={}){if(Q.endsWith("/"))Q=Q.slice(0,-1);return Z.prependPathname?`${Q}/.well-known/${J}`:`/.well-known/${J}${Q}`}async function vs1(J,Q,Z=fetch){return await IG1(J,{"MCP-Protocol-Version":Q},Z)}function iN6(J,Q){return!J||J.status===404&&Q!=="/"}async function aN6(J,Q,Z,X){var Y,K;let q=new URL(J),G=(Y=X===null||X===void 0?void 0:X.protocolVersion)!==null&&Y!==void 0?Y:iR,z;if(X===null||X===void 0?void 0:X.metadataUrl)z=new URL(X.metadataUrl);else{let W=lN6(Q,q.pathname);z=new URL(W,(K=X===null||X===void 0?void 0:X.metadataServerUrl)!==null&&K!==void 0?K:q),z.search=q.search}let U=await vs1(z,G,Z);if(!(X===null||X===void 0?void 0:X.metadataUrl)&&iN6(U,q.pathname)){let W=new URL(`/.well-known/${Q}`,q);U=await vs1(W,G,Z)}return U}function nN6(J){let Q=typeof J==="string"?new URL(J):J,Z=Q.pathname!=="/",X=[];if(!Z)return X.push({url:new URL("/.well-known/oauth-authorization-server",Q.origin),type:"oauth"}),X.push({url:new URL("/.well-known/openid-configuration",Q.origin),type:"oidc"}),X;let Y=Q.pathname;if(Y.endsWith("/"))Y=Y.slice(0,-1);return X.push({url:new URL(`/.well-known/oauth-authorization-server${Y}`,Q.origin),type:"oauth"}),X.push({url:new URL("/.well-known/oauth-authorization-server",Q.origin),type:"oauth"}),X.push({url:new URL(`/.well-known/openid-configuration${Y}`,Q.origin),type:"oidc"}),X.push({url:new URL(`${Y}/.well-known/openid-configuration`,Q.origin),type:"oidc"}),X}async function rN6(J,{fetchFn:Q=fetch,protocolVersion:Z=iR}={}){var X;let Y={"MCP-Protocol-Version":Z},K=nN6(J);for(let{url:q,type:G}of K){let z=await IG1(q,Y,Q);if(!z)continue;if(!z.ok){if(z.status>=400&&z.status<500)continue;throw Error(`HTTP ${z.status} trying to load ${G==="oauth"?"OAuth":"OpenID provider"} metadata from ${q}`)}if(G==="oauth")return OG1.parse(await z.json());else{let U=Es1.parse(await z.json());if(!((X=U.code_challenge_methods_supported)===null||X===void 0?void 0:X.includes("S256")))throw Error(`Incompatible OIDC provider at ${q}: does not support S256 code challenge method required by MCP specification`);return U}}return}async function sN6(J,{metadata:Q,clientInformation:Z,redirectUrl:X,scope:Y,state:K,resource:q}){let U;if(Q){if(U=new URL(Q.authorization_endpoint),!Q.response_types_supported.includes("code"))throw Error("Incompatible auth server: does not support response type code");if(!Q.code_challenge_methods_supported||!Q.code_challenge_methods_supported.includes("S256"))throw Error("Incompatible auth server: does not support code challenge method S256")}else U=new URL("/authorize",J);let W=await RG1(),F=W.code_verifier,H=W.code_challenge;if(U.searchParams.set("response_type","code"),U.searchParams.set("client_id",Z.client_id),U.searchParams.set("code_challenge",H),U.searchParams.set("code_challenge_method","S256"),U.searchParams.set("redirect_uri",String(X)),K)U.searchParams.set("state",K);if(Y)U.searchParams.set("scope",Y);if(Y===null||Y===void 0?void 0:Y.includes("offline_access"))U.searchParams.append("prompt","consent");if(q)U.searchParams.set("resource",q.href);return{authorizationUrl:U,codeVerifier:F}}async function oN6(J,{metadata:Q,clientInformation:Z,authorizationCode:X,codeVerifier:Y,redirectUri:K,resource:q,addClientAuthentication:G,fetchFn:z}){var U;let W="authorization_code",F=(Q===null||Q===void 0?void 0:Q.token_endpoint)?new URL(Q.token_endpoint):new URL("/token",J);if((Q===null||Q===void 0?void 0:Q.grant_types_supported)&&!Q.grant_types_supported.includes("authorization_code"))throw Error("Incompatible auth server: does not support grant type authorization_code");let H=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),B=new URLSearchParams({grant_type:"authorization_code",code:X,code_verifier:Y,redirect_uri:String(K)});if(G)G(H,B,J,Q);else{let V=(U=Q===null||Q===void 0?void 0:Q.token_endpoint_auth_methods_supported)!==null&&U!==void 0?U:[],N=ks1(Z,V);_s1(N,Z,H,B)}if(q)B.set("resource",q.href);let M=await(z!==null&&z!==void 0?z:fetch)(F,{method:"POST",headers:H,body:B});if(!M.ok)throw await EG1(M);return jG1.parse(await M.json())}async function tN6(J,{metadata:Q,clientInformation:Z,refreshToken:X,resource:Y,addClientAuthentication:K,fetchFn:q}){var G;let z="refresh_token",U;if(Q){if(U=new URL(Q.token_endpoint),Q.grant_types_supported&&!Q.grant_types_supported.includes("refresh_token"))throw Error("Incompatible auth server: does not support grant type refresh_token")}else U=new URL("/token",J);let W=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),F=new URLSearchParams({grant_type:"refresh_token",refresh_token:X});if(K)K(W,F,J,Q);else{let B=(G=Q===null||Q===void 0?void 0:Q.token_endpoint_auth_methods_supported)!==null&&G!==void 0?G:[],M=ks1(Z,B);_s1(M,Z,W,F)}if(Y)F.set("resource",Y.href);let H=await(q!==null&&q!==void 0?q:fetch)(U,{method:"POST",headers:W,body:F});if(!H.ok)throw await EG1(H);return jG1.parse({refresh_token:X,...await H.json()})}async function eN6(J,{metadata:Q,clientMetadata:Z,fetchFn:X}){let Y;if(Q){if(!Q.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");Y=new URL(Q.registration_endpoint)}else Y=new URL("/register",J);let K=await(X!==null&&X!==void 0?X:fetch)(Y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!K.ok)throw await EG1(K);return Ps1.parse(await K.json())}class xs1 extends Error{constructor(J,Q,Z){super(`SSE error: ${Q}`);this.code=J,this.event=Z}}class PG1{constructor(J,Q){this._url=J,this._resourceMetadataUrl=void 0,this._eventSourceInit=Q===null||Q===void 0?void 0:Q.eventSourceInit,this._requestInit=Q===null||Q===void 0?void 0:Q.requestInit,this._authProvider=Q===null||Q===void 0?void 0:Q.authProvider,this._fetch=Q===null||Q===void 0?void 0:Q.fetch}async _authThenStart(){var J;if(!this._authProvider)throw new BX("No auth provider");let Q;try{Q=await KB(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(Z){throw(J=this.onerror)===null||J===void 0||J.call(this,Z),Z}if(Q!=="AUTHORIZED")throw new BX;return await this._startOrAuth()}async _commonHeaders(){var J;let Q={};if(this._authProvider){let Z=await this._authProvider.tokens();if(Z)Q.Authorization=`Bearer ${Z.access_token}`}if(this._protocolVersion)Q["mcp-protocol-version"]=this._protocolVersion;return new Headers({...Q,...(J=this._requestInit)===null||J===void 0?void 0:J.headers})}_startOrAuth(){var J,Q,Z;let X=(Z=(Q=(J=this===null||this===void 0?void 0:this._eventSourceInit)===null||J===void 0?void 0:J.fetch)!==null&&Q!==void 0?Q:this._fetch)!==null&&Z!==void 0?Z:fetch;return new Promise((Y,K)=>{this._eventSource=new JO(this._url.href,{...this._eventSourceInit,fetch:async(q,G)=>{let z=await this._commonHeaders();z.set("Accept","text/event-stream");let U=await X(q,{...G,headers:z});if(U.status===401&&U.headers.has("www-authenticate"))this._resourceMetadataUrl=kS(U);return U}}),this._abortController=new AbortController,this._eventSource.onerror=(q)=>{var G;if(q.code===401&&this._authProvider){this._authThenStart().then(Y,K);return}let z=new xs1(q.code,q.message,q);K(z),(G=this.onerror)===null||G===void 0||G.call(this,z)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(q)=>{var G;let z=q;try{if(this._endpoint=new URL(z.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(U){K(U),(G=this.onerror)===null||G===void 0||G.call(this,U),this.close();return}Y()}),this._eventSource.onmessage=(q)=>{var G,z;let U=q,W;try{W=eH.parse(JSON.parse(U.data))}catch(F){(G=this.onerror)===null||G===void 0||G.call(this,F);return}(z=this.onmessage)===null||z===void 0||z.call(this,W)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(J){if(!this._authProvider)throw new BX("No auth provider");if(await KB(this._authProvider,{serverUrl:this._url,authorizationCode:J,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new BX("Failed to authorize")}async close(){var J,Q,Z;(J=this._abortController)===null||J===void 0||J.abort(),(Q=this._eventSource)===null||Q===void 0||Q.close(),(Z=this.onclose)===null||Z===void 0||Z.call(this)}async send(J){var Q,Z,X;if(!this._endpoint)throw Error("Not connected");try{let Y=await this._commonHeaders();Y.set("content-type","application/json");let K={...this._requestInit,method:"POST",headers:Y,body:JSON.stringify(J),signal:(Q=this._abortController)===null||Q===void 0?void 0:Q.signal},q=await((Z=this._fetch)!==null&&Z!==void 0?Z:fetch)(this._endpoint,K);if(!q.ok){if(q.status===401&&this._authProvider){if(this._resourceMetadataUrl=kS(q),await KB(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new BX;return this.send(J)}let G=await q.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${q.status}): ${G}`)}}catch(Y){throw(X=this.onerror)===null||X===void 0||X.call(this,Y),Y}}setProtocolVersion(J){this._protocolVersion=J}}sU();Nc();class TG1 extends TransformStream{constructor({onError:J,onRetry:Q,onComment:Z}={}){let X;super({start(Y){X=nR({onEvent:(K)=>{Y.enqueue(K)},onError(K){J==="terminate"?Y.error(K):typeof J=="function"&&J(K)},onRetry:Q,onComment:Z})},transform(Y){X.feed(Y)}})}}var J36={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class kc extends Error{constructor(J,Q){super(`Streamable HTTP error: ${Q}`);this.code=J}}class CG1{constructor(J,Q){var Z;this._url=J,this._resourceMetadataUrl=void 0,this._requestInit=Q===null||Q===void 0?void 0:Q.requestInit,this._authProvider=Q===null||Q===void 0?void 0:Q.authProvider,this._fetch=Q===null||Q===void 0?void 0:Q.fetch,this._sessionId=Q===null||Q===void 0?void 0:Q.sessionId,this._reconnectionOptions=(Z=Q===null||Q===void 0?void 0:Q.reconnectionOptions)!==null&&Z!==void 0?Z:J36}async _authThenStart(){var J;if(!this._authProvider)throw new BX("No auth provider");let Q;try{Q=await KB(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(Z){throw(J=this.onerror)===null||J===void 0||J.call(this,Z),Z}if(Q!=="AUTHORIZED")throw new BX;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var J;let Q={};if(this._authProvider){let X=await this._authProvider.tokens();if(X)Q.Authorization=`Bearer ${X.access_token}`}if(this._sessionId)Q["mcp-session-id"]=this._sessionId;if(this._protocolVersion)Q["mcp-protocol-version"]=this._protocolVersion;let Z=this._normalizeHeaders((J=this._requestInit)===null||J===void 0?void 0:J.headers);return new Headers({...Q,...Z})}async _startOrAuthSse(J){var Q,Z,X;let{resumptionToken:Y}=J;try{let K=await this._commonHeaders();if(K.set("Accept","text/event-stream"),Y)K.set("last-event-id",Y);let q=await((Q=this._fetch)!==null&&Q!==void 0?Q:fetch)(this._url,{method:"GET",headers:K,signal:(Z=this._abortController)===null||Z===void 0?void 0:Z.signal});if(!q.ok){if(q.status===401&&this._authProvider)return await this._authThenStart();if(q.status===405)return;throw new kc(q.status,`Failed to open SSE stream: ${q.statusText}`)}this._handleSseStream(q.body,J,!0)}catch(K){throw(X=this.onerror)===null||X===void 0||X.call(this,K),K}}_getNextReconnectionDelay(J){let Q=this._reconnectionOptions.initialReconnectionDelay,Z=this._reconnectionOptions.reconnectionDelayGrowFactor,X=this._reconnectionOptions.maxReconnectionDelay;return Math.min(Q*Math.pow(Z,J),X)}_normalizeHeaders(J){if(!J)return{};if(J instanceof Headers)return Object.fromEntries(J.entries());if(Array.isArray(J))return Object.fromEntries(J);return{...J}}_scheduleReconnection(J,Q=0){var Z;let X=this._reconnectionOptions.maxRetries;if(X>0&&Q>=X){(Z=this.onerror)===null||Z===void 0||Z.call(this,Error(`Maximum reconnection attempts (${X}) exceeded.`));return}let Y=this._getNextReconnectionDelay(Q);setTimeout(()=>{this._startOrAuthSse(J).catch((K)=>{var q;(q=this.onerror)===null||q===void 0||q.call(this,Error(`Failed to reconnect SSE stream: ${K instanceof Error?K.message:String(K)}`)),this._scheduleReconnection(J,Q+1)})},Y)}_handleSseStream(J,Q,Z){if(!J)return;let{onresumptiontoken:X,replayMessageId:Y}=Q,K;(async()=>{var G,z,U,W;try{let F=J.pipeThrough(new TextDecoderStream).pipeThrough(new TG1).getReader();while(!0){let{value:H,done:B}=await F.read();if(B)break;if(H.id)K=H.id,X===null||X===void 0||X(H.id);if(!H.event||H.event==="message")try{let M=eH.parse(JSON.parse(H.data));if(Y!==void 0&&$S(M))M.id=Y;(G=this.onmessage)===null||G===void 0||G.call(this,M)}catch(M){(z=this.onerror)===null||z===void 0||z.call(this,M)}}}catch(F){if((U=this.onerror)===null||U===void 0||U.call(this,Error(`SSE stream disconnected: ${F}`)),Z&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:K,onresumptiontoken:X,replayMessageId:Y},0)}catch(H){(W=this.onerror)===null||W===void 0||W.call(this,Error(`Failed to reconnect: ${H instanceof Error?H.message:String(H)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(J){if(!this._authProvider)throw new BX("No auth provider");if(await KB(this._authProvider,{serverUrl:this._url,authorizationCode:J,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new BX("Failed to authorize")}async close(){var J,Q;(J=this._abortController)===null||J===void 0||J.abort(),(Q=this.onclose)===null||Q===void 0||Q.call(this)}async send(J,Q){var Z,X,Y,K;try{let{resumptionToken:q,onresumptiontoken:G}=Q||{};if(q){this._startOrAuthSse({resumptionToken:q,replayMessageId:ad(J)?J.id:void 0}).catch((V)=>{var N;return(N=this.onerror)===null||N===void 0?void 0:N.call(this,V)});return}let z=await this._commonHeaders();z.set("content-type","application/json"),z.set("accept","application/json, text/event-stream");let U={...this._requestInit,method:"POST",headers:z,body:JSON.stringify(J),signal:(Z=this._abortController)===null||Z===void 0?void 0:Z.signal},W=await((X=this._fetch)!==null&&X!==void 0?X:fetch)(this._url,U),F=W.headers.get("mcp-session-id");if(F)this._sessionId=F;if(!W.ok){if(W.status===401&&this._authProvider){if(this._resourceMetadataUrl=kS(W),await KB(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new BX;return this.send(J)}let V=await W.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${W.status}): ${V}`)}if(W.status===202){if(Fn1(J))this._startOrAuthSse({resumptionToken:void 0}).catch((V)=>{var N;return(N=this.onerror)===null||N===void 0?void 0:N.call(this,V)});return}let B=(Array.isArray(J)?J:[J]).filter((V)=>("method"in V)&&("id"in V)&&V.id!==void 0).length>0,M=W.headers.get("content-type");if(B)if(M===null||M===void 0?void 0:M.includes("text/event-stream"))this._handleSseStream(W.body,{onresumptiontoken:G},!1);else if(M===null||M===void 0?void 0:M.includes("application/json")){let V=await W.json(),N=Array.isArray(V)?V.map((L)=>eH.parse(L)):[eH.parse(V)];for(let L of N)(Y=this.onmessage)===null||Y===void 0||Y.call(this,L)}else throw new kc(-1,`Unexpected content type: ${M}`)}catch(q){throw(K=this.onerror)===null||K===void 0||K.call(this,q),q}}get sessionId(){return this._sessionId}async terminateSession(){var J,Q,Z;if(!this._sessionId)return;try{let X=await this._commonHeaders(),Y={...this._requestInit,method:"DELETE",headers:X,signal:(J=this._abortController)===null||J===void 0?void 0:J.signal},K=await((Q=this._fetch)!==null&&Q!==void 0?Q:fetch)(this._url,Y);if(!K.ok&&K.status!==405)throw new kc(K.status,`Failed to terminate session: ${K.statusText}`);this._sessionId=void 0}catch(X){throw(Z=this.onerror)===null||Z===void 0||Z.call(this,X),X}}setProtocolVersion(J){this._protocolVersion=J}get protocolVersion(){return this._protocolVersion}}sU();s6();k0();F0();_S();HY();pc();function dc(J,Q){for(let Z of J??[])if(uc(w36(Q),Z.matches))return Z.action==="allow";return!0}function w36(J){if("command"in J)return{command:J.command,args:J.args?.join(" "),env:J.env};return J}sU();F0();n5();u4();var Zt1=B4.CLAUDE_3_5_SONNET.name;function Xt1(J,Q){J.setRequestHandler(bq1,async(Z,X)=>{try{l.info("MCP sampling request:",Z,X);let Y=Z.params.messages.map((q)=>({role:q.role,content:[{type:"text",text:String(q.content.text||"")}]})),K=await wO(Y,[],Z.params.systemPrompt?[{type:"text",text:Z.params.systemPrompt}]:[],Q,void 0,void 0);if(K.message){let q=K.message.content.find((G)=>G.type==="text");if(q&&q.type==="text")return{content:{type:"text",text:q.text},model:K.message.model,role:"assistant"}}return l.error("MCP sampling missing result"),{content:{type:"text",text:"No response generated"},model:Zt1,role:"assistant"}}catch(Y){return l.error("MCP sampling failed:",Y),{content:{type:"text",text:"Error generating response"},model:Zt1,role:"assistant"}}})}var az1=fc;function GA6(J){return J.map((Q)=>{if(Q.type==="text"){let Z=V2.bufferByteLengthCompat(Q.text);if(Z>az1){let X=V2.utf8Clamp(Q.text,az1),Y=Math.round(Z/1024);return{type:"text",text:`${X}
4506
4506
 
4507
4507
  ... [Tool result truncated - showing first ${Math.round(az1/1024)}KB of ${Y}KB total. The tool result was too long and has been shortened. Consider using more specific queries or parameters to get focused results.]`}}}return Q})}var r5=Symbol.for("disabled-client"),Pl={clientInfo:{name:"amp-mcp-client",version:"0.0.0-dev"},capabilities:{sampling:{},prompts:{listChanged:!0}}};function Ze1(J,Q,Z,X){let Y=new PS(Pl.clientInfo,{capabilities:Pl.capabilities}),K=J0.of(void 0).pipe(kV(()=>cT(d8(async()=>{if(await Y.close(),await new Promise((M)=>setTimeout(M,100)),Z)return r5;return UA6(J,Y,Q,X)}),XY).pipe(OG((M)=>{if(M instanceof PS)M?.close()})),{shouldCountRefs:!1})),q=K.subscribe({}),G=K.pipe(S0((M)=>{if(M===r5)return{type:"disabled"};if(M===RJ)return{type:"connecting"};if(M instanceof Error){let V=M;return{type:"connection-failed",error:{message:V.message,stderr:V.stderr}}}return{type:"connected",capabilities:M.getServerCapabilities(),serverInfo:M.getServerVersion()}})),z=K.pipe(w9((M)=>{if(M===RJ||M instanceof Error||M===r5)return J0.of(M);let V=new p8;return M.setNotificationHandler(xq1,()=>{V.next()}),V.pipe(ku({onUnsubscribe:()=>M.removeNotificationHandler("notifications/tools/list_changed")}),Y7(void 0),S0(()=>M))})),U=K.pipe(w9((M)=>{if(M===RJ||M instanceof Error||M===r5)return J0.of(M);let V=new p8;return M.setNotificationHandler(Iq1,()=>{V.next()}),V.pipe(ku({onUnsubscribe:()=>M.removeNotificationHandler("notifications/resources/list_changed")}),Y7(void 0),S0(()=>M))})),W=z.pipe(kV((M)=>{if(M instanceof Error)return J0.of(M);if(M===r5)return J0.of([]);return d8(async(V)=>{return(await M.listTools({signal:V})).tools})})),H=K.pipe(w9((M)=>{if(M===RJ||M instanceof Error||M===r5)return J0.of(M);let V=new p8;return M.setNotificationHandler(kq1,()=>{V.next()}),V.pipe(ku({onUnsubscribe:()=>M.removeNotificationHandler("notifications/prompts/list_changed")}),Y7(void 0),S0(()=>M))})).pipe(kV((M)=>{if(M instanceof Error)return J0.of(M);if(M===r5)return J0.of([]);return d8(async(V)=>{if(!M.getServerCapabilities()?.prompts)return[];return(await M.listPrompts({signal:V})).prompts})})),B=U.pipe(kV((M)=>{if(M instanceof Error)return J0.of(M);if(M===r5)return J0.of([]);return d8(async(V)=>{if(!M.getServerCapabilities()?.resources)return[];return(await M.listResources({signal:V})).resources})}));return{status:G,tools:W,resources:B,prompts:H,async callTool(M,V,N){let L=await lT(K);if(L===r5)throw Error("cannot call tools for disabled client");Xt1(L,V.thread.id);let A=await L.callTool(M,void 0,{signal:N,timeout:999999000});if(!("content"in A))throw Error("unexpected response");return GA6(A.content)},async listResources(M,V){let N=await lT(K);if(N===r5)throw Error("cannot list resources for disabled client");if(!N.getServerCapabilities()?.resources)return[];return(await N.listResources(M,{signal:V,timeout:999999000})).resources},async readResource(M,V){let N=await lT(K);if(N===r5)throw Error("cannot read resource for disabled client");return(await N.readResource(M,{signal:V,timeout:999999000})).contents},async getPrompt(M,V,N){let L=await lT(K);if(L===r5)return null;try{return await L.getPrompt({name:M,arguments:V},{signal:N,timeout:999999000})}catch(A){return null}},async dispose(){q.unsubscribe();try{await Y.close()}catch(M){l.error("Error closing MCP client:",M)}}}}async function zA6(J,Q,Z){let X=Q?{headers:Q}:void 0;try{let Y=new CG1(J,X?{requestInit:X}:void 0);return await Promise.race([Z.connect(Y),Xe1()]),l.debug("Connected using StreamableHTTPClientTransport"),Z}catch(Y){l.debug(`StreamableHTTPClientTransport failed, falling back to SSE: ${Y}`);try{await Z.close()}catch{}let K=new PS(Pl.clientInfo,{capabilities:Pl.capabilities}),q=new PG1(J,X?{requestInit:X}:void 0);return await Promise.race([K.connect(q)]),l.debug("Connected using SSEClientTransport"),K}}async function UA6(J,Q,Z,X){if(!dc(X,J))throw Error("MCP server is not allowed by MCP permissions");let Y;if("url"in J){let q=new URL(J.url);return await zA6(q,J.headers,Q)}else{let{loadProfileEnvironmentVariables:q}=await Promise.resolve().then(() => ($l(),Kt1)),z={...Z.loadProfile==="never"||!Z.workingDirectory||!kH(Z.workingDirectory)?process.env:await Y6(q(Z.workingDirectory.fsPath,Z.loadProfile)),...J.env};Y=await Promise.resolve().then(() => (Qe1(),Je1)).then(({StdioClientTransport:U})=>{let{AMP_API_KEY:W,...F}=z;return new U({...J,stderr:"pipe",cwd:Z.workingDirectory&&kH(Z.workingDirectory)?Z.workingDirectory.fsPath:void 0,env:F})})}let K=[];if("stderr"in Y&&Y.stderr&&typeof Y.stderr==="object"&&Y.stderr!==null&&"on"in Y.stderr&&typeof Y.stderr.on==="function")Y.stderr.on("data",(q)=>{let G=q.toString().trim();if(G){if(K.push(G),K.length>50)K=["[...]",...K.slice(-49)];l.info("mcp-server-stderr",{stderr:G,spec:J})}});try{let q=Q.connect(Y);return await Promise.race([q,Xe1()]),Q}catch(q){let G=(z)=>{let U=Error(z);if(K.length>0)U.stderr=K.join(`
4508
- `);return U};if(q instanceof Error){if(q.message.includes("Connection closed"))throw G("MCP server connection was closed unexpectedly.");else if(q.message.includes("Invalid content type"))throw G('SSE error: Invalid content type, expected "text/event-stream". Check that the URL is correct and points to a valid MCP SSE endpoint. The server must respond with Content-Type: text/event-stream header.');else if("url"in J&&q.message.includes("fetch failed"))throw G(`Could not connect to MCP server at ${J.url}. Check that the server is running and accessible.`);else if(K.length>0)throw G(q.message)}throw q}}function Xe1(){return new Promise((J,Q)=>{let Z=setTimeout(()=>{clearTimeout(Z),Q(Error("Connection timeout: MCP server did not respond within 60 seconds"))},60000)})}function Ke1({configService:J,toolService:Q,externalMCPServers:Z=J0.of({})}){let X=new qe1,Y=new p8,K=D2(U9,Z).pipe(S0(([{settings:{mcpServers:R,mcpPermissions:O,"terminal.commands.nodeSpawn.loadProfile":$}},j])=>({mcpServers:R,mcpPermissions:O,loadProfile:$,externalMCPServers:j})),I8()),q=J.workspaceRoots.pipe(S0((R)=>R?.at(0))),G=new Map,z,U=D2(K,q,Y.pipe(Y7(void 0))).pipe(SK(300),S0(async([{mcpServers:R,mcpPermissions:O,loadProfile:$,externalMCPServers:j},E,P])=>{let T=X.consume(),v={...R,...j},x=FA6(z,O);z=O;for(let[h,S]of Object.entries(v)){let _=G.get(h);if(!T&&_&&WA6(_.spec,S)&&x)continue;if(G.set(h,{spec:S,client:Ze1(S,{workingDirectory:E,loadProfile:$},!1,O),isExternal:Boolean(j[h])}),_)await _.client.dispose()}for(let[h,{client:S}]of G.entries())if(!v||!(h in v))await S.dispose(),G.delete(h);return Array.from(G.entries())})),W=U.subscribe({}),F=new Map,H=30000,B=(R)=>{if(R)F.delete(R);else F.clear()},M=U.pipe(w9((R)=>R.length===0?J0.of(!0):D2(...R.map(([O,{client:$}])=>$.tools.pipe(wJ((j)=>j!==RJ&&j!==r5),SV(1)))).pipe(S0(()=>!0))),SV(1)),V=D2(U.pipe(w9((R)=>R.length===0?J0.of([]):D2(...R.map(([O,{spec:$,client:j}])=>j.tools.pipe(S0((E)=>({name:O,spec:$,tools:E===RJ||E instanceof Error||E===r5?[]:E,client:j}))))))),U9.pipe(S0((R)=>R.settings.mcpPermissions),I8())).pipe(S0(([R,O])=>({mcpServers:R,mcpPermissions:O}))),N,L=V.subscribe(async({mcpServers:R,mcpPermissions:O})=>{if(N)for(let j of N)j.dispose();N=[];let $=[];for(let{name:j,spec:E,tools:P,client:T}of R){if(!dc(O,E)){if(P.length>0)l.error(`Ignoring ${P.length} tools from MCP server ${j} due to MCP permissions`);else l.debug(`Ignoring tools from MCP server ${j} due to MCP permissions`);continue}for(let v of P){l.debug("mcpService.toolRegisterer",{name:v.name});try{let x=Ye1(v,T,j);N.push(Q.registerTool(x)),$.push(x.spec.name)}catch(x){l.warn(`Failed to register MCP tool ${v.name} from ${j}:`,x)}}}if($.length>0)try{await Y6(Q.tools.pipe(S0((j)=>$.every((E)=>j.some((P)=>P.spec.name===E))),wJ(Boolean),SV(1)),AbortSignal.timeout(5000)),l.debug("mcpService.toolsRegistered",{registeredCount:$.length})}catch(j){l.warn("Failed to verify tool registration:",j)}},(R)=>{l.error("MCP toolRegisterer error",R)}),A=new Promise((R)=>{try{Y6(M,AbortSignal.timeout(1e4)).then(()=>{l.info("mcpService.initialized",{value:Array.from(G.keys())}),R()})}catch(O){l.warn("MCP service initialization failed, but service will continue:",O),R()}}),w=D2(U9,U).pipe(w9(([R,O])=>O.length===0?J0.of([]):D2(...O.map(([$,{spec:j,client:E,isExternal:P}])=>D2(E.status,E.tools,E.prompts).pipe(S0(([T,v,x])=>({name:$,spec:j,isExternal:P,status:T,tools:v instanceof Error?v:v===RJ||v===r5?[]:v.map((h)=>({spec:{name:h.name,description:h.description,inputSchema:h.inputSchema,source:{mcp:$}},...jC({name:h.name,source:{mcp:$}},R)})),prompts:x instanceof Error?x:x===RJ||x===r5?[]:x})))))),O9({shouldCountRefs:!1}));return{initialized:A,servers:w,restartServers(){X.replenish(),Y.next()},getClient(R){return G.get(R)?.client},async searchResources(R){try{let O=await Y6(U),$=Date.now(),j=[];for(let[E,{client:P}]of O){if((await Y6(P.status)).type!=="connected")continue;try{let v,x=F.get(E);if(x&&$<x.expires)v=x.resources;else v=await P.listResources(),F.set(E,{resources:v,timestamp:$,expires:$+30000});for(let h of v){let S=h.title||h.name;if(!R||E.toLowerCase().includes(R.toLowerCase())||S.toLowerCase().includes(R.toLowerCase())||h.description?.toLowerCase().includes(R.toLowerCase())||h.uri.toLowerCase().includes(R.toLowerCase()))j.push({resource:h,serverName:E})}}catch(v){l.warn(`Failed to list resources from MCP server ${E}`,v),B(E)}}return j.slice(0,50)}catch(O){return l.warn("Failed to search MCP resources",O),[]}},async getPrompt(R,O,$,j){let E=G.get(O);if(E)try{return await E.client.getPrompt(R,$,j)}catch(P){return null}return null},async registerToolsWithService(R){return new Promise((O)=>{let $=[],j=!1,E=V.subscribe(({mcpServers:P})=>{for(let T of $)T.dispose();$.length=0;for(let{name:T,tools:v,client:x}of P)for(let h of v)$.push(R.registerTool(Ye1(h,x,T)));if(!j)j=!0,O({dispose:()=>{E.unsubscribe();for(let T of $)T.dispose();$.length=0}})},(P)=>{l.error("MCP external tool registration error",P)})})},async addServer(R,O){let $=(await Z9()).settings.mcpServers;if($&&R in $)throw Error(`MCP server already exists with name ${JSON.stringify(R)}`);if("command"in O&&typeof O.command!=="string")throw Error("Command must be a string");if("url"in O)try{new URL(O.url)}catch(j){throw Error(`Invalid URL: ${O.url}`)}await J.updateSettings("mcpServers",{...$,[R]:O},"global")},async removeServer(R){let O=(await Z9()).settings.mcpServers;if(!O||!(R in O))throw Error(`MCP server does not exist with name ${JSON.stringify(R)}`);let $={...O};delete $[R],await J.updateSettings("mcpServers",$,"global")},async updateServer(R,O){let $=(await Z9()).settings.mcpServers;if(!$||!(R in $))throw Error(`MCP server does not exist with name ${JSON.stringify(R)}`);await J.updateSettings("mcpServers",{...$,[R]:O},"global")},searchPrompts(R){return this.servers.pipe(S0((O)=>{let $=[];for(let j of O)if(j.status.type==="connected"&&Array.isArray(j.prompts)){let E=j.prompts.map((P)=>HA6(P,j.name)).filter((P)=>{if(!R)return!0;let T=R.toLowerCase();return P.label.toLowerCase().includes(T)||P.detail&&P.detail.toLowerCase().includes(T)});$.push(...E)}return $.sort((j,E)=>j.label.localeCompare(E.label)).slice(0,Math.min(10,ea1))}))},async dispose(){L.unsubscribe(),W.unsubscribe();let R=Array.from(G.values()).map(async({client:O})=>{try{await O.dispose()}catch($){l.error("Error disposing MCP client:",$)}});await Promise.all(R),G.clear()}}}function WA6(J,Q){return JSON.stringify(J)===JSON.stringify(Q)}function FA6(J,Q){return JSON.stringify(J)===JSON.stringify(Q)}function Ye1(J,Q,Z){let X=`mcp__${Z.replace(/\s+/g,"_")}__${J.name.replace(/\s+/g,"_")}`;return{spec:{name:X.length>=64?J.name:X,description:J.description??"",inputSchema:J.inputSchema,source:{mcp:Z}},fn:({args:K},q)=>d8((G)=>Q.callTool({name:J.name,arguments:K??void 0},q,G).then((z)=>({status:"done",result:z.map((U)=>{if(U.type==="text"||U.type==="image")return U;throw Error(`unsupported content type: ${U.type}`)})})))}}class qe1{forceRestart=!1;consume(){let J=this.forceRestart;return this.forceRestart=!1,J}replenish(){this.forceRestart=!0}}function HA6(J,Q){let Z=J.arguments?.map((Y)=>({name:Y.name,required:Y.required??!1}))||[],X={uri:q8(`mcp://${Q}/${J.name}`),label:`${Q}/${J.name}`,detail:J.description||`From ${Q}`,insertText:"",filterText:`${J.name} ${J.description||""}`.toLowerCase()};return{...X,kind:"prompt",promptData:{...X,arguments:Z}}}kG();sz1();s6();k0();var Te1=r6(Me1(),1);F0();lR();s6();k0();F0();ZU1();DQ();xS();import*as NX from"node:fs";import*as hl from"node:path";var b9={readFile:async(J,Q)=>{try{return await NX.promises.readFile(X8(J).fsPath,{encoding:"utf8",signal:Q?.signal})}catch(Z){if(HW(Z))throw new s5(J);throw Z}},readBinaryFile:async(J,Q)=>{try{return await NX.promises.readFile(X8(J).fsPath,{signal:Q?.signal})}catch(Z){if(HW(Z))throw new s5(J);throw Z}},getMtime:async(J,Q)=>{try{return(await NX.promises.stat(X8(J).fsPath)).mtimeMs}catch(Z){if(HW(Z))throw new s5(J);throw Z}},stat:async(J,Q)=>{J=X8(J);try{let Z=await NX.promises.stat(J.fsPath);return{name:hl.basename(J.fsPath),size:Z.size,isDirectory:Z.isDirectory()}}catch(Z){if(HW(Z))throw new s5(J);throw Z}},realpath:async(J,Q)=>{return lA6(X8(J))},rename:async(J,Q)=>{try{await NX.promises.rename(X8(J).fsPath,X8(Q).fsPath)}catch(Z){if(HW(Z))throw new s5(J);throw Z}},writeFile:async(J,Q,Z)=>{await NX.promises.writeFile(X8(J).fsPath,Q,{encoding:"utf-8",signal:Z?.signal,flush:!0})},delete:async(J,Q)=>{J=X8(J);try{if(Q?.recursive)await NX.promises.rm(J.fsPath,{recursive:!0,force:!0});else await NX.promises.unlink(J.fsPath)}catch(Z){if(HW(Z))throw new s5(J);throw Z}},mkdirp:async(J)=>{await NX.promises.mkdir(X8(J).fsPath,{recursive:!0})},readdir:async(J,Q)=>{J=X8(J);try{return(await NX.promises.readdir(J.fsPath,{withFileTypes:!0})).map((X)=>({uri:x0.file(hl.join(J.fsPath,X.name)),isDirectory:X.isDirectory()}))}catch(Z){if(HW(Z))throw new s5(J);throw Z}},findFiles:async(J,Q)=>{try{return(await yl(J.base,{pattern:J.pattern,caseInsensitive:!0},{limit:Q?.maxResults,signal:Q?.signal})).files.map((X)=>tU(X)?x0.file(X):p0.joinPath(J.base,X))}catch(Z){return l.error(`Error finding files with pattern ${J.pattern}:`,Z instanceof Error?Z:Error(String(Z))),[]}},watch:()=>XY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{let Z=X8(J);cA6(Z);try{await NX.promises.access(Z.fsPath)}catch(X){if(HW(X))throw new s5(Z);throw X}}};function cA6(J){if(!kH(J))throw Error(`Expected a file URI (got ${J.toString()})`)}function HW(J){return J!==null&&typeof J==="object"&&"code"in J&&J.code==="ENOENT"}async function lA6(J){if(J.scheme!=="file")throw Error("nodeRealpath only supports file URIs");try{return x0.file(await NX.promises.realpath(J.fsPath))}catch(Q){if(HW(Q))throw new s5(J);throw Q}}async function Pe1(J,Q){if(!J.startsWith(process.cwd()))return;if(await j5.isConnected())try{let Z=await j5.sendRequest("readFile",{path:J});if(Z?.content)return Q(Z.content);throw Error(`Failed to readFile via IDE ${J}: ${Z?.message??"unknown cause"}`)}catch(Z){if(process.env.IDE_FS_NO_FALLBACK)throw Z;l.warn("IDE readFile failed, falling back to Node.js filesystem",{path:J,error:Z});return}else return}async function iA6(J,Q){if(!J.startsWith(process.cwd()))return!1;if(await j5.isConnected())try{let Z=await j5.sendRequest("editFile",{path:J,fullContent:Q});if(!Z?.success)throw Error(`Failed to writeFile via IDE ${J}: ${Z?.message??"unknown cause"}`);return!0}catch(Z){if(process.env.IDE_FS_NO_FALLBACK)throw Z;return l.warn("IDE writeFile failed, falling back to Node.js filesystem",{path:J,error:Z}),!1}else return!1}var Ce1={readFile:async(J,Q)=>{let Z=X8(J).fsPath;return l.debug("ide-fs",{method:"readFile",path:Z}),await Pe1(Z,(X)=>X)??await b9.readFile(J,Q).finally(()=>{l.debug("ide-fs",{fallback:"readFile",uri:J})})},readBinaryFile:async(J,Q)=>{let Z=X8(J).fsPath;l.debug("ide-fs",{method:"readBinaryFile",path:Z});let X;if(!await Te1.isBinaryFile(Z))X=await Pe1(Z,(Y)=>Buffer.from(Y,"utf8"));return X??await b9.readBinaryFile(J,Q).finally(()=>{l.debug("ide-fs",{fallback:"readBinaryFile",uri:J})})},getMtime:async(J,Q)=>{return b9.getMtime(J,Q)},stat:async(J,Q)=>{return b9.stat(J,Q)},realpath:async(J,Q)=>{return b9.realpath(J,Q)},rename:async(J,Q)=>{return b9.rename(J,Q)},writeFile:async(J,Q,Z)=>{let X=X8(J).fsPath;if(l.debug("ide-fs",{method:"writeFile",path:X}),await iA6(X,Q))return;return await b9.writeFile(J,Q,Z).finally(()=>{l.debug("ide-fs",{fallback:"writeFile",uri:J})})},delete:async(J,Q)=>{return b9.delete(J,Q)},mkdirp:async(J)=>{return b9.mkdirp(J)},readdir:async(J,Q)=>{return b9.readdir(J,Q)},findFiles:async(J,Q)=>{return b9.findFiles(J,Q)},watch:()=>XY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{return b9.access(J,Q)}};iK();aK();MB();s6();import{homedir as Jw6}from"node:os";import NB from"node:path";import{Worker as Qw6}from"node:worker_threads";var EO=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,fe1=new Set,qU1=typeof process==="object"&&!!process?process:{},he1=(J,Q,Z,X)=>{typeof qU1.emitWarning==="function"?qU1.emitWarning(J,Q,Z,X):console.error(`[${Z}] ${Q}: ${J}`)},ml=globalThis.AbortController,ye1=globalThis.AbortSignal;if(typeof ml>"u"){ye1=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(X,Y){this._onabort.push(Y)}},ml=class{constructor(){Q()}signal=new ye1;abort(X){if(this.signal.aborted)return;this.signal.reason=X,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y(X);this.signal.onabort?.(X)}};let J=qU1.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!J)return;J=!1,he1("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",Q)}}var tA6=(J)=>!fe1.has(J),PN9=Symbol("type"),VB=(J)=>J&&J===Math.floor(J)&&J>0&&isFinite(J),ge1=(J)=>!VB(J)?null:J<=Math.pow(2,8)?Uint8Array:J<=Math.pow(2,16)?Uint16Array:J<=Math.pow(2,32)?Uint32Array:J<=Number.MAX_SAFE_INTEGER?fv:null;class fv extends Array{constructor(J){super(J);this.fill(0)}}class IO{heap;length;static#J=!1;static create(J){let Q=ge1(J);if(!Q)return[];IO.#J=!0;let Z=new IO(J,Q);return IO.#J=!1,Z}constructor(J,Q){if(!IO.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new Q(J),this.length=0}push(J){this.heap[this.length++]=J}pop(){return this.heap[--this.length]}}class ul{#J;#Z;#Y;#X;#G;#I;#T;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#U;#L;#z;#q;#Q;#B;#M;#H;#W;#A;#F;#w;#R;#V;#O;#C;#D;#_;static unsafeExposeInternals(J){return{starts:J.#R,ttls:J.#V,sizes:J.#w,keyMap:J.#z,keyList:J.#q,valList:J.#Q,next:J.#B,prev:J.#M,get head(){return J.#H},get tail(){return J.#W},free:J.#A,isBackgroundFetch:(Q)=>J.#K(Q),backgroundFetch:(Q,Z,X,Y)=>J.#y(Q,Z,X,Y),moveToTail:(Q)=>J.#k(Q),indexes:(Q)=>J.#j(Q),rindexes:(Q)=>J.#$(Q),isStale:(Q)=>J.#N(Q)}}get max(){return this.#J}get maxSize(){return this.#Z}get calculatedSize(){return this.#L}get size(){return this.#U}get fetchMethod(){return this.#I}get memoMethod(){return this.#T}get dispose(){return this.#Y}get onInsert(){return this.#X}get disposeAfter(){return this.#G}constructor(J){let{max:Q=0,ttl:Z,ttlResolution:X=1,ttlAutopurge:Y,updateAgeOnGet:K,updateAgeOnHas:q,allowStale:G,dispose:z,onInsert:U,disposeAfter:W,noDisposeOnSet:F,noUpdateTTL:H,maxSize:B=0,maxEntrySize:M=0,sizeCalculation:V,fetchMethod:N,memoMethod:L,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:O,ignoreFetchAbort:$}=J;if(Q!==0&&!VB(Q))throw TypeError("max option must be a nonnegative integer");let j=Q?ge1(Q):Array;if(!j)throw Error("invalid max value: "+Q);if(this.#J=Q,this.#Z=B,this.maxEntrySize=M||this.#Z,this.sizeCalculation=V,this.sizeCalculation){if(!this.#Z&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(L!==void 0&&typeof L!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#T=L,N!==void 0&&typeof N!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#I=N,this.#C=!!N,this.#z=new Map,this.#q=Array(Q).fill(void 0),this.#Q=Array(Q).fill(void 0),this.#B=new j(Q),this.#M=new j(Q),this.#H=0,this.#W=0,this.#A=IO.create(Q),this.#U=0,this.#L=0,typeof z==="function")this.#Y=z;if(typeof U==="function")this.#X=U;if(typeof W==="function")this.#G=W,this.#F=[];else this.#G=void 0,this.#F=void 0;if(this.#O=!!this.#Y,this.#_=!!this.#X,this.#D=!!this.#G,this.noDisposeOnSet=!!F,this.noUpdateTTL=!!H,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!O,this.ignoreFetchAbort=!!$,this.maxEntrySize!==0){if(this.#Z!==0){if(!VB(this.#Z))throw TypeError("maxSize must be a positive integer if specified")}if(!VB(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#d()}if(this.allowStale=!!G,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!K,this.updateAgeOnHas=!!q,this.ttlResolution=VB(X)||X===0?X:1,this.ttlAutopurge=!!Y,this.ttl=Z||0,this.ttl){if(!VB(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#f()}if(this.#J===0&&this.ttl===0&&this.#Z===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#Z){if(tA6("LRU_CACHE_UNBOUNDED"))fe1.add("LRU_CACHE_UNBOUNDED"),he1("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",ul)}}getRemainingTTL(J){return this.#z.has(J)?1/0:0}#f(){let J=new fv(this.#J),Q=new fv(this.#J);this.#V=J,this.#R=Q,this.#h=(Y,K,q=EO.now())=>{if(Q[Y]=K!==0?q:0,J[Y]=K,K!==0&&this.ttlAutopurge){let G=setTimeout(()=>{if(this.#N(Y))this.#E(this.#q[Y],"expire")},K+1);if(G.unref)G.unref()}},this.#S=(Y)=>{Q[Y]=J[Y]!==0?EO.now():0},this.#P=(Y,K)=>{if(J[K]){let q=J[K],G=Q[K];if(!q||!G)return;Y.ttl=q,Y.start=G,Y.now=Z||X();let z=Y.now-G;Y.remainingTTL=q-z}};let Z=0,X=()=>{let Y=EO.now();if(this.ttlResolution>0){Z=Y;let K=setTimeout(()=>Z=0,this.ttlResolution);if(K.unref)K.unref()}return Y};this.getRemainingTTL=(Y)=>{let K=this.#z.get(Y);if(K===void 0)return 0;let q=J[K],G=Q[K];if(!q||!G)return 1/0;let z=(Z||X())-G;return q-z},this.#N=(Y)=>{let K=Q[Y],q=J[Y];return!!q&&!!K&&(Z||X())-K>q}}#S=()=>{};#P=()=>{};#h=()=>{};#N=()=>!1;#d(){let J=new fv(this.#J);this.#L=0,this.#w=J,this.#v=(Q)=>{this.#L-=J[Q],J[Q]=0},this.#g=(Q,Z,X,Y)=>{if(this.#K(Z))return 0;if(!VB(X))if(Y){if(typeof Y!=="function")throw TypeError("sizeCalculation must be a function");if(X=Y(Z,Q),!VB(X))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return X},this.#x=(Q,Z,X)=>{if(J[Q]=Z,this.#Z){let Y=this.#Z-J[Q];while(this.#L>Y)this.#b(!0)}if(this.#L+=J[Q],X)X.entrySize=Z,X.totalCalculatedSize=this.#L}}#v=(J)=>{};#x=(J,Q,Z)=>{};#g=(J,Q,Z,X)=>{if(Z||X)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#j({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#W;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#H)break;else Q=this.#M[Q]}}*#$({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#H;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#W)break;else Q=this.#B[Q]}}#m(J){return J!==void 0&&this.#z.get(this.#q[J])===J}*entries(){for(let J of this.#j())if(this.#Q[J]!==void 0&&this.#q[J]!==void 0&&!this.#K(this.#Q[J]))yield[this.#q[J],this.#Q[J]]}*rentries(){for(let J of this.#$())if(this.#Q[J]!==void 0&&this.#q[J]!==void 0&&!this.#K(this.#Q[J]))yield[this.#q[J],this.#Q[J]]}*keys(){for(let J of this.#j()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*rkeys(){for(let J of this.#$()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*values(){for(let J of this.#j())if(this.#Q[J]!==void 0&&!this.#K(this.#Q[J]))yield this.#Q[J]}*rvalues(){for(let J of this.#$())if(this.#Q[J]!==void 0&&!this.#K(this.#Q[J]))yield this.#Q[J]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(J,Q={}){for(let Z of this.#j()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;if(J(Y,this.#q[Z],this))return this.get(this.#q[Z],Q)}}forEach(J,Q=this){for(let Z of this.#j()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#q[Z],this)}}rforEach(J,Q=this){for(let Z of this.#$()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#q[Z],this)}}purgeStale(){let J=!1;for(let Q of this.#$({allowStale:!0}))if(this.#N(Q))this.#E(this.#q[Q],"expire"),J=!0;return J}info(J){let Q=this.#z.get(J);if(Q===void 0)return;let Z=this.#Q[Q],X=this.#K(Z)?Z.__staleWhileFetching:Z;if(X===void 0)return;let Y={value:X};if(this.#V&&this.#R){let K=this.#V[Q],q=this.#R[Q];if(K&&q){let G=K-(EO.now()-q);Y.ttl=G,Y.start=Date.now()}}if(this.#w)Y.size=this.#w[Q];return Y}dump(){let J=[];for(let Q of this.#j({allowStale:!0})){let Z=this.#q[Q],X=this.#Q[Q],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0||Z===void 0)continue;let K={value:Y};if(this.#V&&this.#R){K.ttl=this.#V[Q];let q=EO.now()-this.#R[Q];K.start=Math.floor(Date.now()-q)}if(this.#w)K.size=this.#w[Q];J.unshift([Z,K])}return J}load(J){this.clear();for(let[Q,Z]of J){if(Z.start){let X=Date.now()-Z.start;Z.start=EO.now()-X}this.set(Q,Z.value,Z)}}set(J,Q,Z={}){if(Q===void 0)return this.delete(J),this;let{ttl:X=this.ttl,start:Y,noDisposeOnSet:K=this.noDisposeOnSet,sizeCalculation:q=this.sizeCalculation,status:G}=Z,{noUpdateTTL:z=this.noUpdateTTL}=Z,U=this.#g(J,Q,Z.size||0,q);if(this.maxEntrySize&&U>this.maxEntrySize){if(G)G.set="miss",G.maxEntrySizeExceeded=!0;return this.#E(J,"set"),this}let W=this.#U===0?void 0:this.#z.get(J);if(W===void 0){if(W=this.#U===0?this.#W:this.#A.length!==0?this.#A.pop():this.#U===this.#J?this.#b(!1):this.#U,this.#q[W]=J,this.#Q[W]=Q,this.#z.set(J,W),this.#B[this.#W]=W,this.#M[W]=this.#W,this.#W=W,this.#U++,this.#x(W,U,G),G)G.set="add";if(z=!1,this.#_)this.#X?.(Q,J,"add")}else{this.#k(W);let F=this.#Q[W];if(Q!==F){if(this.#C&&this.#K(F)){F.__abortController.abort(Error("replaced"));let{__staleWhileFetching:H}=F;if(H!==void 0&&!K){if(this.#O)this.#Y?.(H,J,"set");if(this.#D)this.#F?.push([H,J,"set"])}}else if(!K){if(this.#O)this.#Y?.(F,J,"set");if(this.#D)this.#F?.push([F,J,"set"])}if(this.#v(W),this.#x(W,U,G),this.#Q[W]=Q,G){G.set="replace";let H=F&&this.#K(F)?F.__staleWhileFetching:F;if(H!==void 0)G.oldValue=H}}else if(G)G.set="update";if(this.#_)this.onInsert?.(Q,J,Q===F?"update":"replace")}if(X!==0&&!this.#V)this.#f();if(this.#V){if(!z)this.#h(W,X,Y);if(G)this.#P(G,W)}if(!K&&this.#D&&this.#F){let F=this.#F,H;while(H=F?.shift())this.#G?.(...H)}return this}pop(){try{while(this.#U){let J=this.#Q[this.#H];if(this.#b(!0),this.#K(J)){if(J.__staleWhileFetching)return J.__staleWhileFetching}else if(J!==void 0)return J}}finally{if(this.#D&&this.#F){let J=this.#F,Q;while(Q=J?.shift())this.#G?.(...Q)}}}#b(J){let Q=this.#H,Z=this.#q[Q],X=this.#Q[Q];if(this.#C&&this.#K(X))X.__abortController.abort(Error("evicted"));else if(this.#O||this.#D){if(this.#O)this.#Y?.(X,Z,"evict");if(this.#D)this.#F?.push([X,Z,"evict"])}if(this.#v(Q),J)this.#q[Q]=void 0,this.#Q[Q]=void 0,this.#A.push(Q);if(this.#U===1)this.#H=this.#W=0,this.#A.length=0;else this.#H=this.#B[Q];return this.#z.delete(Z),this.#U--,Q}has(J,Q={}){let{updateAgeOnHas:Z=this.updateAgeOnHas,status:X}=Q,Y=this.#z.get(J);if(Y!==void 0){let K=this.#Q[Y];if(this.#K(K)&&K.__staleWhileFetching===void 0)return!1;if(!this.#N(Y)){if(Z)this.#S(Y);if(X)X.has="hit",this.#P(X,Y);return!0}else if(X)X.has="stale",this.#P(X,Y)}else if(X)X.has="miss";return!1}peek(J,Q={}){let{allowStale:Z=this.allowStale}=Q,X=this.#z.get(J);if(X===void 0||!Z&&this.#N(X))return;let Y=this.#Q[X];return this.#K(Y)?Y.__staleWhileFetching:Y}#y(J,Q,Z,X){let Y=Q===void 0?void 0:this.#Q[Q];if(this.#K(Y))return Y;let K=new ml,{signal:q}=Z;q?.addEventListener("abort",()=>K.abort(q.reason),{signal:K.signal});let G={signal:K.signal,options:Z,context:X},z=(M,V=!1)=>{let{aborted:N}=K.signal,L=Z.ignoreFetchAbort&&M!==void 0;if(Z.status)if(N&&!V){if(Z.status.fetchAborted=!0,Z.status.fetchError=K.signal.reason,L)Z.status.fetchAbortIgnored=!0}else Z.status.fetchResolved=!0;if(N&&!L&&!V)return W(K.signal.reason);let A=H;if(this.#Q[Q]===H)if(M===void 0)if(A.__staleWhileFetching)this.#Q[Q]=A.__staleWhileFetching;else this.#E(J,"fetch");else{if(Z.status)Z.status.fetchUpdated=!0;this.set(J,M,G.options)}return M},U=(M)=>{if(Z.status)Z.status.fetchRejected=!0,Z.status.fetchError=M;return W(M)},W=(M)=>{let{aborted:V}=K.signal,N=V&&Z.allowStaleOnFetchAbort,L=N||Z.allowStaleOnFetchRejection,A=L||Z.noDeleteOnFetchRejection,w=H;if(this.#Q[Q]===H){if(!A||w.__staleWhileFetching===void 0)this.#E(J,"fetch");else if(!N)this.#Q[Q]=w.__staleWhileFetching}if(L){if(Z.status&&w.__staleWhileFetching!==void 0)Z.status.returnedStale=!0;return w.__staleWhileFetching}else if(w.__returned===w)throw M},F=(M,V)=>{let N=this.#I?.(J,Y,G);if(N&&N instanceof Promise)N.then((L)=>M(L===void 0?void 0:L),V);K.signal.addEventListener("abort",()=>{if(!Z.ignoreFetchAbort||Z.allowStaleOnFetchAbort){if(M(void 0),Z.allowStaleOnFetchAbort)M=(L)=>z(L,!0)}})};if(Z.status)Z.status.fetchDispatched=!0;let H=new Promise(F).then(z,U),B=Object.assign(H,{__abortController:K,__staleWhileFetching:Y,__returned:void 0});if(Q===void 0)this.set(J,B,{...G.options,status:void 0}),Q=this.#z.get(J);else this.#Q[Q]=B;return B}#K(J){if(!this.#C)return!1;let Q=J;return!!Q&&Q instanceof Promise&&Q.hasOwnProperty("__staleWhileFetching")&&Q.__abortController instanceof ml}async fetch(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:K=this.ttl,noDisposeOnSet:q=this.noDisposeOnSet,size:G=0,sizeCalculation:z=this.sizeCalculation,noUpdateTTL:U=this.noUpdateTTL,noDeleteOnFetchRejection:W=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:F=this.allowStaleOnFetchRejection,ignoreFetchAbort:H=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:M,forceRefresh:V=!1,status:N,signal:L}=Q;if(!this.#C){if(N)N.fetch="get";return this.get(J,{allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,status:N})}let A={allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,ttl:K,noDisposeOnSet:q,size:G,sizeCalculation:z,noUpdateTTL:U,noDeleteOnFetchRejection:W,allowStaleOnFetchRejection:F,allowStaleOnFetchAbort:B,ignoreFetchAbort:H,status:N,signal:L},w=this.#z.get(J);if(w===void 0){if(N)N.fetch="miss";let R=this.#y(J,w,A,M);return R.__returned=R}else{let R=this.#Q[w];if(this.#K(R)){let P=Z&&R.__staleWhileFetching!==void 0;if(N){if(N.fetch="inflight",P)N.returnedStale=!0}return P?R.__staleWhileFetching:R.__returned=R}let O=this.#N(w);if(!V&&!O){if(N)N.fetch="hit";if(this.#k(w),X)this.#S(w);if(N)this.#P(N,w);return R}let $=this.#y(J,w,A,M),E=$.__staleWhileFetching!==void 0&&Z;if(N){if(N.fetch=O?"stale":"refresh",E&&O)N.returnedStale=!0}return E?$.__staleWhileFetching:$.__returned=$}}async forceFetch(J,Q={}){let Z=await this.fetch(J,Q);if(Z===void 0)throw Error("fetch() returned undefined");return Z}memo(J,Q={}){let Z=this.#T;if(!Z)throw Error("no memoMethod provided to constructor");let{context:X,forceRefresh:Y,...K}=Q,q=this.get(J,K);if(!Y&&q!==void 0)return q;let G=Z(J,q,{options:K,context:X});return this.set(J,G,K),G}get(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:K}=Q,q=this.#z.get(J);if(q!==void 0){let G=this.#Q[q],z=this.#K(G);if(K)this.#P(K,q);if(this.#N(q)){if(K)K.get="stale";if(!z){if(!Y)this.#E(J,"expire");if(K&&Z)K.returnedStale=!0;return Z?G:void 0}else{if(K&&Z&&G.__staleWhileFetching!==void 0)K.returnedStale=!0;return Z?G.__staleWhileFetching:void 0}}else{if(K)K.get="hit";if(z)return G.__staleWhileFetching;if(this.#k(q),X)this.#S(q);return G}}else if(K)K.get="miss"}#u(J,Q){this.#M[Q]=J,this.#B[J]=Q}#k(J){if(J!==this.#W){if(J===this.#H)this.#H=this.#B[J];else this.#u(this.#M[J],this.#B[J]);this.#u(this.#W,J),this.#W=J}}delete(J){return this.#E(J,"delete")}#E(J,Q){let Z=!1;if(this.#U!==0){let X=this.#z.get(J);if(X!==void 0)if(Z=!0,this.#U===1)this.#p(Q);else{this.#v(X);let Y=this.#Q[X];if(this.#K(Y))Y.__abortController.abort(Error("deleted"));else if(this.#O||this.#D){if(this.#O)this.#Y?.(Y,J,Q);if(this.#D)this.#F?.push([Y,J,Q])}if(this.#z.delete(J),this.#q[X]=void 0,this.#Q[X]=void 0,X===this.#W)this.#W=this.#M[X];else if(X===this.#H)this.#H=this.#B[X];else{let K=this.#M[X];this.#B[K]=this.#B[X];let q=this.#B[X];this.#M[q]=this.#M[X]}this.#U--,this.#A.push(X)}}if(this.#D&&this.#F?.length){let X=this.#F,Y;while(Y=X?.shift())this.#G?.(...Y)}return Z}clear(){return this.#p("delete")}#p(J){for(let Q of this.#$({allowStale:!0})){let Z=this.#Q[Q];if(this.#K(Z))Z.__abortController.abort(Error("deleted"));else{let X=this.#q[Q];if(this.#O)this.#Y?.(Z,X,J);if(this.#D)this.#F?.push([Z,X,J])}}if(this.#z.clear(),this.#Q.fill(void 0),this.#q.fill(void 0),this.#V&&this.#R)this.#V.fill(0),this.#R.fill(0);if(this.#w)this.#w.fill(0);if(this.#H=0,this.#W=0,this.#A.length=0,this.#L=0,this.#U=0,this.#D&&this.#F){let Q=this.#F,Z;while(Z=Q?.shift())this.#G?.(...Z)}}}F0();DQ();s6();k0();F0();DQ();function GU1(J,Q,Z){let X=new p8,K=(()=>{let B=new Map;return(M,V)=>{let L=(B.get(M)?.catch(()=>{})||Promise.resolve()).then(()=>V()).finally(()=>{if(B.get(M)===L)B.delete(M)});return B.set(M,L),L}})(),q=Z?p0.joinPath(Q,Z):Q;function G(B){return p0.joinPath(q,`${B.toString()}.json`)}async function z(B){let M=G(B);try{let V=await J.readBinaryFile(M),N=52428800;if(V.length>52428800){let L=Math.round(V.length/1048576);l.warn(`File too large to load safely: ${String(B)} (${L}MB)`,{key:String(B),size:V.length,maxSize:52428800});return}try{let L=V instanceof Uint8Array?V:new Uint8Array(V);return JSON.parse(new TextDecoder().decode(L))}catch(L){let A=L,{contentLength:w,contentPreview:R}=eA6(V);l.warn("Corrupted JSON detected.",{key:String(B),storageUri:q.toString(),error:A.message,contentLength:w,contentPreview:R});return}}catch(V){if(BQ(V))return;throw V}}async function U(B,M){let V=G(B),N=V.with({path:V.path+".amptmp"}),L=JSON.stringify(M,null,2);await J.mkdirp(p0.joinPath(V,"..")),await K(B,async()=>{await J.writeFile(N,L),await J.rename(N,V)}),X.next(B)}async function W(B){let M=G(B);await K(B,async()=>{await J.delete(M)}),X.next(B)}async function F(){let B;try{B=await J.readdir(q)}catch(M){if(BQ(M))return[];throw M}return B.map((M)=>{let V=M.uri.path.split("/").pop()||"";if(M.isDirectory||!V.endsWith(".json"))return null;return V.slice(0,-5)}).filter((M)=>M!==null)}async function H(B){return G(B).fsPath}return{get:z,set:U,delete:W,keys:F,path:H,changes:X}}function eA6(J){try{let Q=J instanceof Uint8Array?J:new Uint8Array(J),Z=new TextDecoder().decode(Q);return{contentLength:J.length,contentPreview:Z.slice(0,128)}}catch{let Q=J instanceof Uint8Array?J:new Uint8Array(J),X=Array.from(Q.slice(0,64)).map((Y)=>{if(Y>=32&&Y<=126)return String.fromCharCode(Y);return`\\x${Y.toString(16).padStart(2,"0")}`}).join("");return{contentLength:J.length,contentPreview:`${X}${J.length>64?"...":""}`}}}async function me1(J){let Q=J.isDevelopment||!1,Z=Xw6(),X=Q?"threads-development":"threads",Y=GU1(b9,Z,X),K=new ue1(Y);if(!J.vscodeMigrationContext)return l.debug("Using centralized thread storage (CLI)",{storageUri:Z.toString(),storageSubdir:X}),K;let{fileSystem:q,vscodeContext:G}=J.vscodeMigrationContext,z=x0.file(NB.join(Z.path,X)),U=Q?"threads3-development":"threads3",W=x0.file(NB.join(G.globalStorageUri.path,U));if(await Yw6(z,Q,W))return l.debug("Using centralized thread storage (VS Code, migration complete)",{storageUri:Z.toString(),storageSubdir:X}),K;else{l.debug("Using fallback thread storage (VS Code, migration in progress)",{centralizedStorageUri:Z.toString(),legacyStorageUri:G.globalStorageUri.toString(),storageSubdir:X,legacySubdir:U}),Kw6(W,z,Q);let H=GU1(q,G.globalStorageUri,U);return Zw6(K,H)}}class ue1{delegate;cache=new ul({max:30,maxSize:1e8,ttl:600000,sizeCalculation:(J)=>JSON.stringify(J).length});constructor(J){this.delegate=J}async get(J){if(this.cache.has(J))return this.cache.get(J);let Q=await this.delegate.get(J);if(Q!==void 0)this.cache.set(J,Q);return Q}async set(J,Q){await this.delegate.set(J,Q),this.cache.set(J,Q)}async delete(J){await this.delegate.delete(J),this.cache.delete(J)}keys(){return this.delegate.keys()}path(J){return this.delegate.path(J)}get changes(){return this.delegate.changes}}function Zw6(J,Q){return{async get(Z){let X=await J.get(Z);if(X!==void 0)return X;return Q.get(Z)},async set(Z,X){await J.set(Z,X)},async delete(Z){await J.delete(Z).catch(()=>{}),await Q.delete(Z).catch(()=>{})},async keys(){let[Z,X]=await Promise.all([J.keys(),Q.keys()]);return[...new Set([...Z,...X])]},async path(Z){let X=await J.path(Z);if(X)return X;return Q.path(Z)},get changes(){return J.changes}}}function Xw6(){let J=process.env.XDG_DATA_HOME||NB.join(Jw6(),".local","share"),Q=NB.resolve(J,"amp");return x0.file(Q)}async function Yw6(J,Q,Z){let X=x0.file(NB.join(J.path,"..","migration")),Y=qw6(Q),K=x0.file(NB.join(X.path,Y.done));if(await fl(b9,K))return!0;if(Z)try{if((await b9.readdir(Z)).filter((z)=>NB.basename(z.uri.path).endsWith(".json")).length===0){if((await b9.readdir(J)).filter((W)=>NB.basename(W.uri.path).endsWith(".json")).length>0){l.info("Detected completed migration without marker, creating completion marker");try{await b9.mkdirp(X),await b9.writeFile(K,"completed")}catch(W){l.debug("Could not create migration completion marker:",W)}return!0}}}catch(q){l.debug("Could not check legacy directory for completion detection:",q)}return!1}function Kw6(J,Q,Z){try{let X=new Qw6(s1.resolve("/home/runner/work/amp/amp/core/src/storage/migration-worker.node.ts"),{workerData:{legacyDir:J.toString(),centralizedDir:Q.toString(),isDevelopment:Z}});X.on("message",(Y)=>{l.info("Background migration completed:",Y)}),X.on("error",(Y)=>{l.warn("Background migration failed:",Y)}),X.on("exit",(Y)=>{if(Y!==0)l.warn(`Migration worker exited with code ${Y}`)})}catch(X){let Y=X instanceof Error?X.message:String(X);if(Y.includes("Worker is not supported")||Y.includes("Cannot resolve module")||Y.includes("ENOENT")&&Y.includes("migration-worker"))l.debug("Migration worker could not be started (expected in tests):",X);else l.warn("Migration worker failed to start, migration will be skipped:",X)}}function qw6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}import{execFile as zw6}from"node:child_process";import{promises as LB}from"node:fs";import{homedir as zU1}from"node:os";import{join as nK}from"node:path";import{promisify as Uw6}from"node:util";F0();async function PO(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=Gw6(J,q),z=G<0,U,W;if(K.time){let F=K.time[J],H=K.time[q],B=Date.now();if(F)U=Math.floor((B-new Date(F).getTime())/3600000);if(H)W=Math.floor((B-new Date(H).getTime())/3600000)}return l.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return l.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function Gw6(J,Q){let Z=(q)=>{let[G,z]=q.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let q=0;q<K;q++){let G=X.parts[q]||0,z=Y.parts[q]||0;if(G<z)return-1;if(G>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}var TO=Uw6(zw6);class UU1{async collect(){let[J,Q,Z,X,Y]=await Promise.all([this.collectInstallationInfo(),this.collectEnvironmentInfo(),this.collectConfigInfo(),this.collectCliTestInfo(),this.collectLogsInfo()]);return{cliTest:X,config:Z,environment:Q,installation:J,logs:Y}}async collectInstallationInfo(){let J={installMethod:"unknown",packageManager:"unknown"};try{if(J.version=await this.getCliVersion(),J.version)J.versionAge=await this.getCliAge(J.version)}catch{}try{J.installMethod=await this.detectInstallMethod()}catch{}try{J.packageManager=await this.detectPackageManager()}catch{}try{J.executablePath=process.execPath}catch{}return J}async collectEnvironmentInfo(){let J={};for(let[Q,Z]of Object.entries(process.env))if(Q.startsWith("AMP_")&&Z!==void 0)J[Q]=Z;return{variables:J}}async collectConfigInfo(){let J={};try{let Q=this.getSettingsPath(),Z=await LB.readFile(Q,"utf8");J.settings=JSON.parse(Z)}catch(Q){J.configError=Q instanceof Error?Q.message:String(Q)}try{let Q=this.getSecretsPath(),Z=await LB.readFile(Q,"utf8");J.secrets=JSON.parse(Z)}catch(Q){J.secretsError=Q instanceof Error?Q.message:String(Q)}return J}async collectCliTestInfo(){let J=new Date().toISOString();try{await TO("which",["amp"],{timeout:5000})}catch{return{additionalTests:[],executedAt:J,initialTest:{command:`echo "what is today's date" | amp`,error:"amp command not found in PATH",exitCode:127,stderr:"",stdout:""}}}let Q=await this.runCliCommand(`echo "what is today's date" | amp`),Z=[];if(Q.exitCode===0){let X=["amp threads list","amp tools show"];for(let Y of X){let K=await this.runCliCommand(Y);Z.push(K)}}return{additionalTests:Z,executedAt:J,initialTest:Q}}async runCliCommand(J){let Q={command:J,exitCode:-1,stderr:"",stdout:""};try{let{spawn:Z}=await import("node:child_process");return new Promise((X)=>{let Y=Z("sh",["-c",J],{stdio:["pipe","pipe","pipe"],timeout:30000}),K="",q="";Y.stdout?.on("data",(G)=>{K+=G.toString()}),Y.stderr?.on("data",(G)=>{q+=G.toString()}),Y.on("close",(G)=>{Q.stdout=K,Q.stderr=q,Q.exitCode=G??-1,X(Q)}),Y.on("error",(G)=>{Q.error=G.message,Q.exitCode=-1,X(Q)}),setTimeout(()=>{Y.kill("SIGTERM"),Q.error="Command timed out after 30 seconds",Q.exitCode=-1,X(Q)},30000)})}catch(Z){return Q.error=Z instanceof Error?Z.message:String(Z),Q.exitCode=-1,Q}}async collectLogsInfo(){let J={recentLogs:[]};try{let Q=this.getLogPath(),X=(await LB.readFile(Q,"utf8")).split(`
4508
+ `);return U};if(q instanceof Error){if(q.message.includes("Connection closed"))throw G("MCP server connection was closed unexpectedly.");else if(q.message.includes("Invalid content type"))throw G('SSE error: Invalid content type, expected "text/event-stream". Check that the URL is correct and points to a valid MCP SSE endpoint. The server must respond with Content-Type: text/event-stream header.');else if("url"in J&&q.message.includes("fetch failed"))throw G(`Could not connect to MCP server at ${J.url}. Check that the server is running and accessible.`);else if(K.length>0)throw G(q.message)}throw q}}function Xe1(){return new Promise((J,Q)=>{let Z=setTimeout(()=>{clearTimeout(Z),Q(Error("Connection timeout: MCP server did not respond within 60 seconds"))},60000)})}function Ke1({configService:J,toolService:Q,externalMCPServers:Z=J0.of({})}){let X=new qe1,Y=new p8,K=D2(U9,Z).pipe(S0(([{settings:{mcpServers:R,mcpPermissions:O,"terminal.commands.nodeSpawn.loadProfile":$}},j])=>({mcpServers:R,mcpPermissions:O,loadProfile:$,externalMCPServers:j})),I8()),q=J.workspaceRoots.pipe(S0((R)=>R?.at(0))),G=new Map,z,U=D2(K,q,Y.pipe(Y7(void 0))).pipe(SK(300),S0(async([{mcpServers:R,mcpPermissions:O,loadProfile:$,externalMCPServers:j},E,P])=>{let T=X.consume(),v={...R,...j},x=FA6(z,O);z=O;for(let[h,S]of Object.entries(v)){let _=G.get(h);if(!T&&_&&WA6(_.spec,S)&&x)continue;if(G.set(h,{spec:S,client:Ze1(S,{workingDirectory:E,loadProfile:$},!1,O),isExternal:Boolean(j[h])}),_)await _.client.dispose()}for(let[h,{client:S}]of G.entries())if(!v||!(h in v))await S.dispose(),G.delete(h);return Array.from(G.entries())})),W=U.subscribe({}),F=new Map,H=30000,B=(R)=>{if(R)F.delete(R);else F.clear()},M=U.pipe(w9((R)=>R.length===0?J0.of(!0):D2(...R.map(([O,{client:$}])=>$.tools.pipe(wJ((j)=>j!==RJ&&j!==r5),SV(1)))).pipe(S0(()=>!0))),SV(1)),V=D2(U.pipe(w9((R)=>R.length===0?J0.of([]):D2(...R.map(([O,{spec:$,client:j}])=>j.tools.pipe(S0((E)=>({name:O,spec:$,tools:E===RJ||E instanceof Error||E===r5?[]:E,client:j}))))))),U9.pipe(S0((R)=>R.settings.mcpPermissions),I8())).pipe(S0(([R,O])=>({mcpServers:R,mcpPermissions:O}))),N,L=V.subscribe(({mcpServers:R,mcpPermissions:O})=>{if(N)for(let j of N)j.dispose();N=[];let $=[];for(let{name:j,spec:E,tools:P,client:T}of R){if(!dc(O,E)){if(P.length>0)l.error(`Ignoring ${P.length} tools from MCP server ${j} due to MCP permissions`);else l.debug(`Ignoring tools from MCP server ${j} due to MCP permissions`);continue}for(let v of P){l.debug("mcpService.toolRegisterer",{name:v.name});try{let x=Ye1(v,T,j);N.push(Q.registerTool(x)),$.push(x.spec.name)}catch(x){l.warn(`Failed to register MCP tool ${v.name} from ${j}:`,x)}}}if($.length>0)Y6(Q.tools.pipe(S0((j)=>$.every((E)=>j.some((P)=>P.spec.name===E))),wJ(Boolean),SV(1)),AbortSignal.timeout(5000)).then(()=>{l.debug("mcpService.toolsRegistered",{registeredCount:$.length})}).catch((j)=>{l.warn("Failed to verify tool registration:",j)})},(R)=>{l.error("MCP toolRegisterer error",R)}),A=new Promise((R)=>{try{Y6(M,AbortSignal.timeout(1e4)).then(()=>{l.info("mcpService.initialized",{value:Array.from(G.keys())}),R()}).catch((O)=>{l.warn("MCP service initialization failed, but service will continue:",O),R()})}catch(O){l.warn("MCP service initialization failed, but service will continue:",O),R()}}),w=D2(U9,U).pipe(w9(([R,O])=>O.length===0?J0.of([]):D2(...O.map(([$,{spec:j,client:E,isExternal:P}])=>D2(E.status,E.tools,E.prompts).pipe(S0(([T,v,x])=>({name:$,spec:j,isExternal:P,status:T,tools:v instanceof Error?v:v===RJ||v===r5?[]:v.map((h)=>({spec:{name:h.name,description:h.description,inputSchema:h.inputSchema,source:{mcp:$}},...jC({name:h.name,source:{mcp:$}},R)})),prompts:x instanceof Error?x:x===RJ||x===r5?[]:x})))))),O9({shouldCountRefs:!1}));return{initialized:A,servers:w,restartServers(){X.replenish(),Y.next()},getClient(R){return G.get(R)?.client},async searchResources(R){try{let O=await Y6(U),$=Date.now(),j=[];for(let[E,{client:P}]of O){if((await Y6(P.status)).type!=="connected")continue;try{let v,x=F.get(E);if(x&&$<x.expires)v=x.resources;else v=await P.listResources(),F.set(E,{resources:v,timestamp:$,expires:$+30000});for(let h of v){let S=h.title||h.name;if(!R||E.toLowerCase().includes(R.toLowerCase())||S.toLowerCase().includes(R.toLowerCase())||h.description?.toLowerCase().includes(R.toLowerCase())||h.uri.toLowerCase().includes(R.toLowerCase()))j.push({resource:h,serverName:E})}}catch(v){l.warn(`Failed to list resources from MCP server ${E}`,v),B(E)}}return j.slice(0,50)}catch(O){return l.warn("Failed to search MCP resources",O),[]}},async getPrompt(R,O,$,j){let E=G.get(O);if(E)try{return await E.client.getPrompt(R,$,j)}catch(P){return null}return null},async registerToolsWithService(R){return new Promise((O)=>{let $=[],j=!1,E=V.subscribe(({mcpServers:P})=>{for(let T of $)T.dispose();$.length=0;for(let{name:T,tools:v,client:x}of P)for(let h of v)$.push(R.registerTool(Ye1(h,x,T)));if(!j)j=!0,O({dispose:()=>{E.unsubscribe();for(let T of $)T.dispose();$.length=0}})},(P)=>{l.error("MCP external tool registration error",P)})})},async addServer(R,O){let $=(await Z9()).settings.mcpServers;if($&&R in $)throw Error(`MCP server already exists with name ${JSON.stringify(R)}`);if("command"in O&&typeof O.command!=="string")throw Error("Command must be a string");if("url"in O)try{new URL(O.url)}catch(j){throw Error(`Invalid URL: ${O.url}`)}await J.updateSettings("mcpServers",{...$,[R]:O},"global")},async removeServer(R){let O=(await Z9()).settings.mcpServers;if(!O||!(R in O))throw Error(`MCP server does not exist with name ${JSON.stringify(R)}`);let $={...O};delete $[R],await J.updateSettings("mcpServers",$,"global")},async updateServer(R,O){let $=(await Z9()).settings.mcpServers;if(!$||!(R in $))throw Error(`MCP server does not exist with name ${JSON.stringify(R)}`);await J.updateSettings("mcpServers",{...$,[R]:O},"global")},searchPrompts(R){return this.servers.pipe(S0((O)=>{let $=[];for(let j of O)if(j.status.type==="connected"&&Array.isArray(j.prompts)){let E=j.prompts.map((P)=>HA6(P,j.name)).filter((P)=>{if(!R)return!0;let T=R.toLowerCase();return P.label.toLowerCase().includes(T)||P.detail&&P.detail.toLowerCase().includes(T)});$.push(...E)}return $.sort((j,E)=>j.label.localeCompare(E.label)).slice(0,Math.min(10,ea1))}))},async dispose(){L.unsubscribe(),W.unsubscribe();let R=Array.from(G.values()).map(async({client:O})=>{try{await O.dispose()}catch($){l.error("Error disposing MCP client:",$)}});await Promise.all(R),G.clear()}}}function WA6(J,Q){return JSON.stringify(J)===JSON.stringify(Q)}function FA6(J,Q){return JSON.stringify(J)===JSON.stringify(Q)}function Ye1(J,Q,Z){let X=`mcp__${Z.replace(/\s+/g,"_")}__${J.name.replace(/\s+/g,"_")}`;return{spec:{name:X.length>=64?J.name:X,description:J.description??"",inputSchema:J.inputSchema,source:{mcp:Z}},fn:({args:K},q)=>d8((G)=>Q.callTool({name:J.name,arguments:K??void 0},q,G).then((z)=>({status:"done",result:z.map((U)=>{if(U.type==="text"||U.type==="image")return U;throw Error(`unsupported content type: ${U.type}`)})})))}}class qe1{forceRestart=!1;consume(){let J=this.forceRestart;return this.forceRestart=!1,J}replenish(){this.forceRestart=!0}}function HA6(J,Q){let Z=J.arguments?.map((Y)=>({name:Y.name,required:Y.required??!1}))||[],X={uri:q8(`mcp://${Q}/${J.name}`),label:`${Q}/${J.name}`,detail:J.description||`From ${Q}`,insertText:"",filterText:`${J.name} ${J.description||""}`.toLowerCase()};return{...X,kind:"prompt",promptData:{...X,arguments:Z}}}kG();sz1();s6();k0();var Te1=r6(Me1(),1);F0();lR();s6();k0();F0();ZU1();DQ();xS();import*as NX from"node:fs";import*as hl from"node:path";var b9={readFile:async(J,Q)=>{try{return await NX.promises.readFile(X8(J).fsPath,{encoding:"utf8",signal:Q?.signal})}catch(Z){if(HW(Z))throw new s5(J);throw Z}},readBinaryFile:async(J,Q)=>{try{return await NX.promises.readFile(X8(J).fsPath,{signal:Q?.signal})}catch(Z){if(HW(Z))throw new s5(J);throw Z}},getMtime:async(J,Q)=>{try{return(await NX.promises.stat(X8(J).fsPath)).mtimeMs}catch(Z){if(HW(Z))throw new s5(J);throw Z}},stat:async(J,Q)=>{J=X8(J);try{let Z=await NX.promises.stat(J.fsPath);return{name:hl.basename(J.fsPath),size:Z.size,isDirectory:Z.isDirectory()}}catch(Z){if(HW(Z))throw new s5(J);throw Z}},realpath:async(J,Q)=>{return lA6(X8(J))},rename:async(J,Q)=>{try{await NX.promises.rename(X8(J).fsPath,X8(Q).fsPath)}catch(Z){if(HW(Z))throw new s5(J);throw Z}},writeFile:async(J,Q,Z)=>{await NX.promises.writeFile(X8(J).fsPath,Q,{encoding:"utf-8",signal:Z?.signal,flush:!0})},delete:async(J,Q)=>{J=X8(J);try{if(Q?.recursive)await NX.promises.rm(J.fsPath,{recursive:!0,force:!0});else await NX.promises.unlink(J.fsPath)}catch(Z){if(HW(Z))throw new s5(J);throw Z}},mkdirp:async(J)=>{await NX.promises.mkdir(X8(J).fsPath,{recursive:!0})},readdir:async(J,Q)=>{J=X8(J);try{return(await NX.promises.readdir(J.fsPath,{withFileTypes:!0})).map((X)=>({uri:x0.file(hl.join(J.fsPath,X.name)),isDirectory:X.isDirectory()}))}catch(Z){if(HW(Z))throw new s5(J);throw Z}},findFiles:async(J,Q)=>{try{return(await yl(J.base,{pattern:J.pattern,caseInsensitive:!0},{limit:Q?.maxResults,signal:Q?.signal})).files.map((X)=>tU(X)?x0.file(X):p0.joinPath(J.base,X))}catch(Z){return l.error(`Error finding files with pattern ${J.pattern}:`,Z instanceof Error?Z:Error(String(Z))),[]}},watch:()=>XY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{let Z=X8(J);cA6(Z);try{await NX.promises.access(Z.fsPath)}catch(X){if(HW(X))throw new s5(Z);throw X}}};function cA6(J){if(!kH(J))throw Error(`Expected a file URI (got ${J.toString()})`)}function HW(J){return J!==null&&typeof J==="object"&&"code"in J&&J.code==="ENOENT"}async function lA6(J){if(J.scheme!=="file")throw Error("nodeRealpath only supports file URIs");try{return x0.file(await NX.promises.realpath(J.fsPath))}catch(Q){if(HW(Q))throw new s5(J);throw Q}}async function Pe1(J,Q){if(!J.startsWith(process.cwd()))return;if(await j5.isConnected())try{let Z=await j5.sendRequest("readFile",{path:J});if(Z?.content)return Q(Z.content);throw Error(`Failed to readFile via IDE ${J}: ${Z?.message??"unknown cause"}`)}catch(Z){if(process.env.IDE_FS_NO_FALLBACK)throw Z;l.warn("IDE readFile failed, falling back to Node.js filesystem",{path:J,error:Z});return}else return}async function iA6(J,Q){if(!J.startsWith(process.cwd()))return!1;if(await j5.isConnected())try{let Z=await j5.sendRequest("editFile",{path:J,fullContent:Q});if(!Z?.success)throw Error(`Failed to writeFile via IDE ${J}: ${Z?.message??"unknown cause"}`);return!0}catch(Z){if(process.env.IDE_FS_NO_FALLBACK)throw Z;return l.warn("IDE writeFile failed, falling back to Node.js filesystem",{path:J,error:Z}),!1}else return!1}var Ce1={readFile:async(J,Q)=>{let Z=X8(J).fsPath;return l.debug("ide-fs",{method:"readFile",path:Z}),await Pe1(Z,(X)=>X)??await b9.readFile(J,Q).finally(()=>{l.debug("ide-fs",{fallback:"readFile",uri:J})})},readBinaryFile:async(J,Q)=>{let Z=X8(J).fsPath;l.debug("ide-fs",{method:"readBinaryFile",path:Z});let X;if(!await Te1.isBinaryFile(Z))X=await Pe1(Z,(Y)=>Buffer.from(Y,"utf8"));return X??await b9.readBinaryFile(J,Q).finally(()=>{l.debug("ide-fs",{fallback:"readBinaryFile",uri:J})})},getMtime:async(J,Q)=>{return b9.getMtime(J,Q)},stat:async(J,Q)=>{return b9.stat(J,Q)},realpath:async(J,Q)=>{return b9.realpath(J,Q)},rename:async(J,Q)=>{return b9.rename(J,Q)},writeFile:async(J,Q,Z)=>{let X=X8(J).fsPath;if(l.debug("ide-fs",{method:"writeFile",path:X}),await iA6(X,Q))return;return await b9.writeFile(J,Q,Z).finally(()=>{l.debug("ide-fs",{fallback:"writeFile",uri:J})})},delete:async(J,Q)=>{return b9.delete(J,Q)},mkdirp:async(J)=>{return b9.mkdirp(J)},readdir:async(J,Q)=>{return b9.readdir(J,Q)},findFiles:async(J,Q)=>{return b9.findFiles(J,Q)},watch:()=>XY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{return b9.access(J,Q)}};iK();aK();MB();s6();import{homedir as Jw6}from"node:os";import NB from"node:path";import{Worker as Qw6}from"node:worker_threads";var EO=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,fe1=new Set,qU1=typeof process==="object"&&!!process?process:{},he1=(J,Q,Z,X)=>{typeof qU1.emitWarning==="function"?qU1.emitWarning(J,Q,Z,X):console.error(`[${Z}] ${Q}: ${J}`)},ml=globalThis.AbortController,ye1=globalThis.AbortSignal;if(typeof ml>"u"){ye1=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(X,Y){this._onabort.push(Y)}},ml=class{constructor(){Q()}signal=new ye1;abort(X){if(this.signal.aborted)return;this.signal.reason=X,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y(X);this.signal.onabort?.(X)}};let J=qU1.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!J)return;J=!1,he1("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",Q)}}var tA6=(J)=>!fe1.has(J),PN9=Symbol("type"),VB=(J)=>J&&J===Math.floor(J)&&J>0&&isFinite(J),ge1=(J)=>!VB(J)?null:J<=Math.pow(2,8)?Uint8Array:J<=Math.pow(2,16)?Uint16Array:J<=Math.pow(2,32)?Uint32Array:J<=Number.MAX_SAFE_INTEGER?fv:null;class fv extends Array{constructor(J){super(J);this.fill(0)}}class IO{heap;length;static#J=!1;static create(J){let Q=ge1(J);if(!Q)return[];IO.#J=!0;let Z=new IO(J,Q);return IO.#J=!1,Z}constructor(J,Q){if(!IO.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new Q(J),this.length=0}push(J){this.heap[this.length++]=J}pop(){return this.heap[--this.length]}}class ul{#J;#Z;#Y;#X;#G;#I;#T;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#U;#L;#z;#q;#Q;#B;#M;#H;#W;#A;#F;#w;#R;#V;#O;#C;#D;#_;static unsafeExposeInternals(J){return{starts:J.#R,ttls:J.#V,sizes:J.#w,keyMap:J.#z,keyList:J.#q,valList:J.#Q,next:J.#B,prev:J.#M,get head(){return J.#H},get tail(){return J.#W},free:J.#A,isBackgroundFetch:(Q)=>J.#K(Q),backgroundFetch:(Q,Z,X,Y)=>J.#y(Q,Z,X,Y),moveToTail:(Q)=>J.#k(Q),indexes:(Q)=>J.#j(Q),rindexes:(Q)=>J.#$(Q),isStale:(Q)=>J.#N(Q)}}get max(){return this.#J}get maxSize(){return this.#Z}get calculatedSize(){return this.#L}get size(){return this.#U}get fetchMethod(){return this.#I}get memoMethod(){return this.#T}get dispose(){return this.#Y}get onInsert(){return this.#X}get disposeAfter(){return this.#G}constructor(J){let{max:Q=0,ttl:Z,ttlResolution:X=1,ttlAutopurge:Y,updateAgeOnGet:K,updateAgeOnHas:q,allowStale:G,dispose:z,onInsert:U,disposeAfter:W,noDisposeOnSet:F,noUpdateTTL:H,maxSize:B=0,maxEntrySize:M=0,sizeCalculation:V,fetchMethod:N,memoMethod:L,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:O,ignoreFetchAbort:$}=J;if(Q!==0&&!VB(Q))throw TypeError("max option must be a nonnegative integer");let j=Q?ge1(Q):Array;if(!j)throw Error("invalid max value: "+Q);if(this.#J=Q,this.#Z=B,this.maxEntrySize=M||this.#Z,this.sizeCalculation=V,this.sizeCalculation){if(!this.#Z&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(L!==void 0&&typeof L!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#T=L,N!==void 0&&typeof N!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#I=N,this.#C=!!N,this.#z=new Map,this.#q=Array(Q).fill(void 0),this.#Q=Array(Q).fill(void 0),this.#B=new j(Q),this.#M=new j(Q),this.#H=0,this.#W=0,this.#A=IO.create(Q),this.#U=0,this.#L=0,typeof z==="function")this.#Y=z;if(typeof U==="function")this.#X=U;if(typeof W==="function")this.#G=W,this.#F=[];else this.#G=void 0,this.#F=void 0;if(this.#O=!!this.#Y,this.#_=!!this.#X,this.#D=!!this.#G,this.noDisposeOnSet=!!F,this.noUpdateTTL=!!H,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!O,this.ignoreFetchAbort=!!$,this.maxEntrySize!==0){if(this.#Z!==0){if(!VB(this.#Z))throw TypeError("maxSize must be a positive integer if specified")}if(!VB(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#d()}if(this.allowStale=!!G,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!K,this.updateAgeOnHas=!!q,this.ttlResolution=VB(X)||X===0?X:1,this.ttlAutopurge=!!Y,this.ttl=Z||0,this.ttl){if(!VB(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#f()}if(this.#J===0&&this.ttl===0&&this.#Z===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#Z){if(tA6("LRU_CACHE_UNBOUNDED"))fe1.add("LRU_CACHE_UNBOUNDED"),he1("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",ul)}}getRemainingTTL(J){return this.#z.has(J)?1/0:0}#f(){let J=new fv(this.#J),Q=new fv(this.#J);this.#V=J,this.#R=Q,this.#h=(Y,K,q=EO.now())=>{if(Q[Y]=K!==0?q:0,J[Y]=K,K!==0&&this.ttlAutopurge){let G=setTimeout(()=>{if(this.#N(Y))this.#E(this.#q[Y],"expire")},K+1);if(G.unref)G.unref()}},this.#S=(Y)=>{Q[Y]=J[Y]!==0?EO.now():0},this.#P=(Y,K)=>{if(J[K]){let q=J[K],G=Q[K];if(!q||!G)return;Y.ttl=q,Y.start=G,Y.now=Z||X();let z=Y.now-G;Y.remainingTTL=q-z}};let Z=0,X=()=>{let Y=EO.now();if(this.ttlResolution>0){Z=Y;let K=setTimeout(()=>Z=0,this.ttlResolution);if(K.unref)K.unref()}return Y};this.getRemainingTTL=(Y)=>{let K=this.#z.get(Y);if(K===void 0)return 0;let q=J[K],G=Q[K];if(!q||!G)return 1/0;let z=(Z||X())-G;return q-z},this.#N=(Y)=>{let K=Q[Y],q=J[Y];return!!q&&!!K&&(Z||X())-K>q}}#S=()=>{};#P=()=>{};#h=()=>{};#N=()=>!1;#d(){let J=new fv(this.#J);this.#L=0,this.#w=J,this.#v=(Q)=>{this.#L-=J[Q],J[Q]=0},this.#g=(Q,Z,X,Y)=>{if(this.#K(Z))return 0;if(!VB(X))if(Y){if(typeof Y!=="function")throw TypeError("sizeCalculation must be a function");if(X=Y(Z,Q),!VB(X))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return X},this.#x=(Q,Z,X)=>{if(J[Q]=Z,this.#Z){let Y=this.#Z-J[Q];while(this.#L>Y)this.#b(!0)}if(this.#L+=J[Q],X)X.entrySize=Z,X.totalCalculatedSize=this.#L}}#v=(J)=>{};#x=(J,Q,Z)=>{};#g=(J,Q,Z,X)=>{if(Z||X)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#j({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#W;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#H)break;else Q=this.#M[Q]}}*#$({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#H;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#W)break;else Q=this.#B[Q]}}#m(J){return J!==void 0&&this.#z.get(this.#q[J])===J}*entries(){for(let J of this.#j())if(this.#Q[J]!==void 0&&this.#q[J]!==void 0&&!this.#K(this.#Q[J]))yield[this.#q[J],this.#Q[J]]}*rentries(){for(let J of this.#$())if(this.#Q[J]!==void 0&&this.#q[J]!==void 0&&!this.#K(this.#Q[J]))yield[this.#q[J],this.#Q[J]]}*keys(){for(let J of this.#j()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*rkeys(){for(let J of this.#$()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*values(){for(let J of this.#j())if(this.#Q[J]!==void 0&&!this.#K(this.#Q[J]))yield this.#Q[J]}*rvalues(){for(let J of this.#$())if(this.#Q[J]!==void 0&&!this.#K(this.#Q[J]))yield this.#Q[J]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(J,Q={}){for(let Z of this.#j()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;if(J(Y,this.#q[Z],this))return this.get(this.#q[Z],Q)}}forEach(J,Q=this){for(let Z of this.#j()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#q[Z],this)}}rforEach(J,Q=this){for(let Z of this.#$()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#q[Z],this)}}purgeStale(){let J=!1;for(let Q of this.#$({allowStale:!0}))if(this.#N(Q))this.#E(this.#q[Q],"expire"),J=!0;return J}info(J){let Q=this.#z.get(J);if(Q===void 0)return;let Z=this.#Q[Q],X=this.#K(Z)?Z.__staleWhileFetching:Z;if(X===void 0)return;let Y={value:X};if(this.#V&&this.#R){let K=this.#V[Q],q=this.#R[Q];if(K&&q){let G=K-(EO.now()-q);Y.ttl=G,Y.start=Date.now()}}if(this.#w)Y.size=this.#w[Q];return Y}dump(){let J=[];for(let Q of this.#j({allowStale:!0})){let Z=this.#q[Q],X=this.#Q[Q],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0||Z===void 0)continue;let K={value:Y};if(this.#V&&this.#R){K.ttl=this.#V[Q];let q=EO.now()-this.#R[Q];K.start=Math.floor(Date.now()-q)}if(this.#w)K.size=this.#w[Q];J.unshift([Z,K])}return J}load(J){this.clear();for(let[Q,Z]of J){if(Z.start){let X=Date.now()-Z.start;Z.start=EO.now()-X}this.set(Q,Z.value,Z)}}set(J,Q,Z={}){if(Q===void 0)return this.delete(J),this;let{ttl:X=this.ttl,start:Y,noDisposeOnSet:K=this.noDisposeOnSet,sizeCalculation:q=this.sizeCalculation,status:G}=Z,{noUpdateTTL:z=this.noUpdateTTL}=Z,U=this.#g(J,Q,Z.size||0,q);if(this.maxEntrySize&&U>this.maxEntrySize){if(G)G.set="miss",G.maxEntrySizeExceeded=!0;return this.#E(J,"set"),this}let W=this.#U===0?void 0:this.#z.get(J);if(W===void 0){if(W=this.#U===0?this.#W:this.#A.length!==0?this.#A.pop():this.#U===this.#J?this.#b(!1):this.#U,this.#q[W]=J,this.#Q[W]=Q,this.#z.set(J,W),this.#B[this.#W]=W,this.#M[W]=this.#W,this.#W=W,this.#U++,this.#x(W,U,G),G)G.set="add";if(z=!1,this.#_)this.#X?.(Q,J,"add")}else{this.#k(W);let F=this.#Q[W];if(Q!==F){if(this.#C&&this.#K(F)){F.__abortController.abort(Error("replaced"));let{__staleWhileFetching:H}=F;if(H!==void 0&&!K){if(this.#O)this.#Y?.(H,J,"set");if(this.#D)this.#F?.push([H,J,"set"])}}else if(!K){if(this.#O)this.#Y?.(F,J,"set");if(this.#D)this.#F?.push([F,J,"set"])}if(this.#v(W),this.#x(W,U,G),this.#Q[W]=Q,G){G.set="replace";let H=F&&this.#K(F)?F.__staleWhileFetching:F;if(H!==void 0)G.oldValue=H}}else if(G)G.set="update";if(this.#_)this.onInsert?.(Q,J,Q===F?"update":"replace")}if(X!==0&&!this.#V)this.#f();if(this.#V){if(!z)this.#h(W,X,Y);if(G)this.#P(G,W)}if(!K&&this.#D&&this.#F){let F=this.#F,H;while(H=F?.shift())this.#G?.(...H)}return this}pop(){try{while(this.#U){let J=this.#Q[this.#H];if(this.#b(!0),this.#K(J)){if(J.__staleWhileFetching)return J.__staleWhileFetching}else if(J!==void 0)return J}}finally{if(this.#D&&this.#F){let J=this.#F,Q;while(Q=J?.shift())this.#G?.(...Q)}}}#b(J){let Q=this.#H,Z=this.#q[Q],X=this.#Q[Q];if(this.#C&&this.#K(X))X.__abortController.abort(Error("evicted"));else if(this.#O||this.#D){if(this.#O)this.#Y?.(X,Z,"evict");if(this.#D)this.#F?.push([X,Z,"evict"])}if(this.#v(Q),J)this.#q[Q]=void 0,this.#Q[Q]=void 0,this.#A.push(Q);if(this.#U===1)this.#H=this.#W=0,this.#A.length=0;else this.#H=this.#B[Q];return this.#z.delete(Z),this.#U--,Q}has(J,Q={}){let{updateAgeOnHas:Z=this.updateAgeOnHas,status:X}=Q,Y=this.#z.get(J);if(Y!==void 0){let K=this.#Q[Y];if(this.#K(K)&&K.__staleWhileFetching===void 0)return!1;if(!this.#N(Y)){if(Z)this.#S(Y);if(X)X.has="hit",this.#P(X,Y);return!0}else if(X)X.has="stale",this.#P(X,Y)}else if(X)X.has="miss";return!1}peek(J,Q={}){let{allowStale:Z=this.allowStale}=Q,X=this.#z.get(J);if(X===void 0||!Z&&this.#N(X))return;let Y=this.#Q[X];return this.#K(Y)?Y.__staleWhileFetching:Y}#y(J,Q,Z,X){let Y=Q===void 0?void 0:this.#Q[Q];if(this.#K(Y))return Y;let K=new ml,{signal:q}=Z;q?.addEventListener("abort",()=>K.abort(q.reason),{signal:K.signal});let G={signal:K.signal,options:Z,context:X},z=(M,V=!1)=>{let{aborted:N}=K.signal,L=Z.ignoreFetchAbort&&M!==void 0;if(Z.status)if(N&&!V){if(Z.status.fetchAborted=!0,Z.status.fetchError=K.signal.reason,L)Z.status.fetchAbortIgnored=!0}else Z.status.fetchResolved=!0;if(N&&!L&&!V)return W(K.signal.reason);let A=H;if(this.#Q[Q]===H)if(M===void 0)if(A.__staleWhileFetching)this.#Q[Q]=A.__staleWhileFetching;else this.#E(J,"fetch");else{if(Z.status)Z.status.fetchUpdated=!0;this.set(J,M,G.options)}return M},U=(M)=>{if(Z.status)Z.status.fetchRejected=!0,Z.status.fetchError=M;return W(M)},W=(M)=>{let{aborted:V}=K.signal,N=V&&Z.allowStaleOnFetchAbort,L=N||Z.allowStaleOnFetchRejection,A=L||Z.noDeleteOnFetchRejection,w=H;if(this.#Q[Q]===H){if(!A||w.__staleWhileFetching===void 0)this.#E(J,"fetch");else if(!N)this.#Q[Q]=w.__staleWhileFetching}if(L){if(Z.status&&w.__staleWhileFetching!==void 0)Z.status.returnedStale=!0;return w.__staleWhileFetching}else if(w.__returned===w)throw M},F=(M,V)=>{let N=this.#I?.(J,Y,G);if(N&&N instanceof Promise)N.then((L)=>M(L===void 0?void 0:L),V);K.signal.addEventListener("abort",()=>{if(!Z.ignoreFetchAbort||Z.allowStaleOnFetchAbort){if(M(void 0),Z.allowStaleOnFetchAbort)M=(L)=>z(L,!0)}})};if(Z.status)Z.status.fetchDispatched=!0;let H=new Promise(F).then(z,U),B=Object.assign(H,{__abortController:K,__staleWhileFetching:Y,__returned:void 0});if(Q===void 0)this.set(J,B,{...G.options,status:void 0}),Q=this.#z.get(J);else this.#Q[Q]=B;return B}#K(J){if(!this.#C)return!1;let Q=J;return!!Q&&Q instanceof Promise&&Q.hasOwnProperty("__staleWhileFetching")&&Q.__abortController instanceof ml}async fetch(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:K=this.ttl,noDisposeOnSet:q=this.noDisposeOnSet,size:G=0,sizeCalculation:z=this.sizeCalculation,noUpdateTTL:U=this.noUpdateTTL,noDeleteOnFetchRejection:W=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:F=this.allowStaleOnFetchRejection,ignoreFetchAbort:H=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:M,forceRefresh:V=!1,status:N,signal:L}=Q;if(!this.#C){if(N)N.fetch="get";return this.get(J,{allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,status:N})}let A={allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,ttl:K,noDisposeOnSet:q,size:G,sizeCalculation:z,noUpdateTTL:U,noDeleteOnFetchRejection:W,allowStaleOnFetchRejection:F,allowStaleOnFetchAbort:B,ignoreFetchAbort:H,status:N,signal:L},w=this.#z.get(J);if(w===void 0){if(N)N.fetch="miss";let R=this.#y(J,w,A,M);return R.__returned=R}else{let R=this.#Q[w];if(this.#K(R)){let P=Z&&R.__staleWhileFetching!==void 0;if(N){if(N.fetch="inflight",P)N.returnedStale=!0}return P?R.__staleWhileFetching:R.__returned=R}let O=this.#N(w);if(!V&&!O){if(N)N.fetch="hit";if(this.#k(w),X)this.#S(w);if(N)this.#P(N,w);return R}let $=this.#y(J,w,A,M),E=$.__staleWhileFetching!==void 0&&Z;if(N){if(N.fetch=O?"stale":"refresh",E&&O)N.returnedStale=!0}return E?$.__staleWhileFetching:$.__returned=$}}async forceFetch(J,Q={}){let Z=await this.fetch(J,Q);if(Z===void 0)throw Error("fetch() returned undefined");return Z}memo(J,Q={}){let Z=this.#T;if(!Z)throw Error("no memoMethod provided to constructor");let{context:X,forceRefresh:Y,...K}=Q,q=this.get(J,K);if(!Y&&q!==void 0)return q;let G=Z(J,q,{options:K,context:X});return this.set(J,G,K),G}get(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:K}=Q,q=this.#z.get(J);if(q!==void 0){let G=this.#Q[q],z=this.#K(G);if(K)this.#P(K,q);if(this.#N(q)){if(K)K.get="stale";if(!z){if(!Y)this.#E(J,"expire");if(K&&Z)K.returnedStale=!0;return Z?G:void 0}else{if(K&&Z&&G.__staleWhileFetching!==void 0)K.returnedStale=!0;return Z?G.__staleWhileFetching:void 0}}else{if(K)K.get="hit";if(z)return G.__staleWhileFetching;if(this.#k(q),X)this.#S(q);return G}}else if(K)K.get="miss"}#u(J,Q){this.#M[Q]=J,this.#B[J]=Q}#k(J){if(J!==this.#W){if(J===this.#H)this.#H=this.#B[J];else this.#u(this.#M[J],this.#B[J]);this.#u(this.#W,J),this.#W=J}}delete(J){return this.#E(J,"delete")}#E(J,Q){let Z=!1;if(this.#U!==0){let X=this.#z.get(J);if(X!==void 0)if(Z=!0,this.#U===1)this.#p(Q);else{this.#v(X);let Y=this.#Q[X];if(this.#K(Y))Y.__abortController.abort(Error("deleted"));else if(this.#O||this.#D){if(this.#O)this.#Y?.(Y,J,Q);if(this.#D)this.#F?.push([Y,J,Q])}if(this.#z.delete(J),this.#q[X]=void 0,this.#Q[X]=void 0,X===this.#W)this.#W=this.#M[X];else if(X===this.#H)this.#H=this.#B[X];else{let K=this.#M[X];this.#B[K]=this.#B[X];let q=this.#B[X];this.#M[q]=this.#M[X]}this.#U--,this.#A.push(X)}}if(this.#D&&this.#F?.length){let X=this.#F,Y;while(Y=X?.shift())this.#G?.(...Y)}return Z}clear(){return this.#p("delete")}#p(J){for(let Q of this.#$({allowStale:!0})){let Z=this.#Q[Q];if(this.#K(Z))Z.__abortController.abort(Error("deleted"));else{let X=this.#q[Q];if(this.#O)this.#Y?.(Z,X,J);if(this.#D)this.#F?.push([Z,X,J])}}if(this.#z.clear(),this.#Q.fill(void 0),this.#q.fill(void 0),this.#V&&this.#R)this.#V.fill(0),this.#R.fill(0);if(this.#w)this.#w.fill(0);if(this.#H=0,this.#W=0,this.#A.length=0,this.#L=0,this.#U=0,this.#D&&this.#F){let Q=this.#F,Z;while(Z=Q?.shift())this.#G?.(...Z)}}}F0();DQ();s6();k0();F0();DQ();function GU1(J,Q,Z){let X=new p8,K=(()=>{let B=new Map;return(M,V)=>{let L=(B.get(M)?.catch(()=>{})||Promise.resolve()).then(()=>V()).finally(()=>{if(B.get(M)===L)B.delete(M)});return B.set(M,L),L}})(),q=Z?p0.joinPath(Q,Z):Q;function G(B){return p0.joinPath(q,`${B.toString()}.json`)}async function z(B){let M=G(B);try{let V=await J.readBinaryFile(M),N=52428800;if(V.length>52428800){let L=Math.round(V.length/1048576);l.warn(`File too large to load safely: ${String(B)} (${L}MB)`,{key:String(B),size:V.length,maxSize:52428800});return}try{let L=V instanceof Uint8Array?V:new Uint8Array(V);return JSON.parse(new TextDecoder().decode(L))}catch(L){let A=L,{contentLength:w,contentPreview:R}=eA6(V);l.warn("Corrupted JSON detected.",{key:String(B),storageUri:q.toString(),error:A.message,contentLength:w,contentPreview:R});return}}catch(V){if(BQ(V))return;throw V}}async function U(B,M){let V=G(B),N=V.with({path:V.path+".amptmp"}),L=JSON.stringify(M,null,2);await J.mkdirp(p0.joinPath(V,"..")),await K(B,async()=>{await J.writeFile(N,L),await J.rename(N,V)}),X.next(B)}async function W(B){let M=G(B);await K(B,async()=>{await J.delete(M)}),X.next(B)}async function F(){let B;try{B=await J.readdir(q)}catch(M){if(BQ(M))return[];throw M}return B.map((M)=>{let V=M.uri.path.split("/").pop()||"";if(M.isDirectory||!V.endsWith(".json"))return null;return V.slice(0,-5)}).filter((M)=>M!==null)}async function H(B){return G(B).fsPath}return{get:z,set:U,delete:W,keys:F,path:H,changes:X}}function eA6(J){try{let Q=J instanceof Uint8Array?J:new Uint8Array(J),Z=new TextDecoder().decode(Q);return{contentLength:J.length,contentPreview:Z.slice(0,128)}}catch{let Q=J instanceof Uint8Array?J:new Uint8Array(J),X=Array.from(Q.slice(0,64)).map((Y)=>{if(Y>=32&&Y<=126)return String.fromCharCode(Y);return`\\x${Y.toString(16).padStart(2,"0")}`}).join("");return{contentLength:J.length,contentPreview:`${X}${J.length>64?"...":""}`}}}async function me1(J){let Q=J.isDevelopment||!1,Z=Xw6(),X=Q?"threads-development":"threads",Y=GU1(b9,Z,X),K=new ue1(Y);if(!J.vscodeMigrationContext)return l.debug("Using centralized thread storage (CLI)",{storageUri:Z.toString(),storageSubdir:X}),K;let{fileSystem:q,vscodeContext:G}=J.vscodeMigrationContext,z=x0.file(NB.join(Z.path,X)),U=Q?"threads3-development":"threads3",W=x0.file(NB.join(G.globalStorageUri.path,U));if(await Yw6(z,Q,W))return l.debug("Using centralized thread storage (VS Code, migration complete)",{storageUri:Z.toString(),storageSubdir:X}),K;else{l.debug("Using fallback thread storage (VS Code, migration in progress)",{centralizedStorageUri:Z.toString(),legacyStorageUri:G.globalStorageUri.toString(),storageSubdir:X,legacySubdir:U}),Kw6(W,z,Q);let H=GU1(q,G.globalStorageUri,U);return Zw6(K,H)}}class ue1{delegate;cache=new ul({max:30,maxSize:1e8,ttl:600000,sizeCalculation:(J)=>JSON.stringify(J).length});constructor(J){this.delegate=J}async get(J){if(this.cache.has(J))return this.cache.get(J);let Q=await this.delegate.get(J);if(Q!==void 0)this.cache.set(J,Q);return Q}async set(J,Q){await this.delegate.set(J,Q),this.cache.set(J,Q)}async delete(J){await this.delegate.delete(J),this.cache.delete(J)}keys(){return this.delegate.keys()}path(J){return this.delegate.path(J)}get changes(){return this.delegate.changes}}function Zw6(J,Q){return{async get(Z){let X=await J.get(Z);if(X!==void 0)return X;return Q.get(Z)},async set(Z,X){await J.set(Z,X)},async delete(Z){await J.delete(Z).catch(()=>{}),await Q.delete(Z).catch(()=>{})},async keys(){let[Z,X]=await Promise.all([J.keys(),Q.keys()]);return[...new Set([...Z,...X])]},async path(Z){let X=await J.path(Z);if(X)return X;return Q.path(Z)},get changes(){return J.changes}}}function Xw6(){let J=process.env.XDG_DATA_HOME||NB.join(Jw6(),".local","share"),Q=NB.resolve(J,"amp");return x0.file(Q)}async function Yw6(J,Q,Z){let X=x0.file(NB.join(J.path,"..","migration")),Y=qw6(Q),K=x0.file(NB.join(X.path,Y.done));if(await fl(b9,K))return!0;if(Z)try{if((await b9.readdir(Z)).filter((z)=>NB.basename(z.uri.path).endsWith(".json")).length===0){if((await b9.readdir(J)).filter((W)=>NB.basename(W.uri.path).endsWith(".json")).length>0){l.info("Detected completed migration without marker, creating completion marker");try{await b9.mkdirp(X),await b9.writeFile(K,"completed")}catch(W){l.debug("Could not create migration completion marker:",W)}return!0}}}catch(q){l.debug("Could not check legacy directory for completion detection:",q)}return!1}function Kw6(J,Q,Z){try{let X=new Qw6(s1.resolve("/home/runner/work/amp/amp/core/src/storage/migration-worker.node.ts"),{workerData:{legacyDir:J.toString(),centralizedDir:Q.toString(),isDevelopment:Z}});X.on("message",(Y)=>{l.info("Background migration completed:",Y)}),X.on("error",(Y)=>{l.warn("Background migration failed:",Y)}),X.on("exit",(Y)=>{if(Y!==0)l.warn(`Migration worker exited with code ${Y}`)})}catch(X){let Y=X instanceof Error?X.message:String(X);if(Y.includes("Worker is not supported")||Y.includes("Cannot resolve module")||Y.includes("ENOENT")&&Y.includes("migration-worker"))l.debug("Migration worker could not be started (expected in tests):",X);else l.warn("Migration worker failed to start, migration will be skipped:",X)}}function qw6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}import{execFile as zw6}from"node:child_process";import{promises as LB}from"node:fs";import{homedir as zU1}from"node:os";import{join as nK}from"node:path";import{promisify as Uw6}from"node:util";F0();async function PO(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=Gw6(J,q),z=G<0,U,W;if(K.time){let F=K.time[J],H=K.time[q],B=Date.now();if(F)U=Math.floor((B-new Date(F).getTime())/3600000);if(H)W=Math.floor((B-new Date(H).getTime())/3600000)}return l.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return l.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function Gw6(J,Q){let Z=(q)=>{let[G,z]=q.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let q=0;q<K;q++){let G=X.parts[q]||0,z=Y.parts[q]||0;if(G<z)return-1;if(G>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}var TO=Uw6(zw6);class UU1{async collect(){let[J,Q,Z,X,Y]=await Promise.all([this.collectInstallationInfo(),this.collectEnvironmentInfo(),this.collectConfigInfo(),this.collectCliTestInfo(),this.collectLogsInfo()]);return{cliTest:X,config:Z,environment:Q,installation:J,logs:Y}}async collectInstallationInfo(){let J={installMethod:"unknown",packageManager:"unknown"};try{if(J.version=await this.getCliVersion(),J.version)J.versionAge=await this.getCliAge(J.version)}catch{}try{J.installMethod=await this.detectInstallMethod()}catch{}try{J.packageManager=await this.detectPackageManager()}catch{}try{J.executablePath=process.execPath}catch{}return J}async collectEnvironmentInfo(){let J={};for(let[Q,Z]of Object.entries(process.env))if(Q.startsWith("AMP_")&&Z!==void 0)J[Q]=Z;return{variables:J}}async collectConfigInfo(){let J={};try{let Q=this.getSettingsPath(),Z=await LB.readFile(Q,"utf8");J.settings=JSON.parse(Z)}catch(Q){J.configError=Q instanceof Error?Q.message:String(Q)}try{let Q=this.getSecretsPath(),Z=await LB.readFile(Q,"utf8");J.secrets=JSON.parse(Z)}catch(Q){J.secretsError=Q instanceof Error?Q.message:String(Q)}return J}async collectCliTestInfo(){let J=new Date().toISOString();try{await TO("which",["amp"],{timeout:5000})}catch{return{additionalTests:[],executedAt:J,initialTest:{command:`echo "what is today's date" | amp`,error:"amp command not found in PATH",exitCode:127,stderr:"",stdout:""}}}let Q=await this.runCliCommand(`echo "what is today's date" | amp`),Z=[];if(Q.exitCode===0){let X=["amp threads list","amp tools show"];for(let Y of X){let K=await this.runCliCommand(Y);Z.push(K)}}return{additionalTests:Z,executedAt:J,initialTest:Q}}async runCliCommand(J){let Q={command:J,exitCode:-1,stderr:"",stdout:""};try{let{spawn:Z}=await import("node:child_process");return new Promise((X)=>{let Y=Z("sh",["-c",J],{stdio:["pipe","pipe","pipe"],timeout:30000}),K="",q="";Y.stdout?.on("data",(G)=>{K+=G.toString()}),Y.stderr?.on("data",(G)=>{q+=G.toString()}),Y.on("close",(G)=>{Q.stdout=K,Q.stderr=q,Q.exitCode=G??-1,X(Q)}),Y.on("error",(G)=>{Q.error=G.message,Q.exitCode=-1,X(Q)}),setTimeout(()=>{Y.kill("SIGTERM"),Q.error="Command timed out after 30 seconds",Q.exitCode=-1,X(Q)},30000)})}catch(Z){return Q.error=Z instanceof Error?Z.message:String(Z),Q.exitCode=-1,Q}}async collectLogsInfo(){let J={recentLogs:[]};try{let Q=this.getLogPath(),X=(await LB.readFile(Q,"utf8")).split(`
4509
4509
  `).filter((Y)=>Y.trim());J.recentLogs=X.slice(-1000)}catch(Q){J.logError=Q instanceof Error?Q.message:String(Q)}return J}async getCliVersion(){try{let{stdout:J}=await TO("npm",["list","-g","@sourcegraph/amp","--depth=0","--json"],{timeout:5000}),Z=JSON.parse(J).dependencies?.["@sourcegraph/amp"];if(Z?.version)return Z.version}catch{}try{let J=nK(process.cwd(),"node_modules","@sourcegraph","amp","package.json"),Q=await LB.readFile(J,"utf8"),Z=JSON.parse(Q);if(Z.version)return Z.version}catch{}try{let{stdout:J}=await TO("pnpm",["list","-g","@sourcegraph/amp","--depth=0","--json"],{timeout:5000}),Q=JSON.parse(J),Z=Array.isArray(Q)?Q:[Q];for(let X of Z){let Y=X.dependencies?.["@sourcegraph/amp"];if(Y?.version)return Y.version}}catch{}try{let{stdout:J}=await TO("yarn",["global","list","--pattern","@sourcegraph/amp","--json"],{timeout:5000}),Q=J.split(`
4510
4510
  `).filter((Z)=>Z.trim());for(let Z of Q)try{let X=JSON.parse(Z);if(X.type==="info"&&X.data&&typeof X.data==="string"){let Y=X.data.match(/"@sourcegraph\/amp@(.+?)"/);if(Y?.[1])return Y[1]}}catch{}}catch{}try{let{stdout:J}=await TO("amp",["--version"],{timeout:5000}),Q=J.trim().match(/(\d+\.\d+\.\d+[\w\-.]*)/g);if(Q?.[0])return Q[0]}catch{}return}async getCliAge(J){try{let Q=await PO(J);if(Q.currentVersionAge!==void 0)return this.formatAge(Q.currentVersionAge);return}catch{return}}formatAge(J){let Q=Math.floor(J/24),Z=J%24;if(J<24)return`${J} hours`;else if(Z===0)return`${J} hours (${Q} ${Q===1?"day":"days"})`;else return`${J} hours (${Q} ${Q===1?"day":"days"}, ${Z}h)`}async detectInstallMethod(){try{return await TO("npm",["list","-g","@sourcegraph/amp"],{timeout:5000}),"global"}catch{}try{let J=nK(process.cwd(),"node_modules","@sourcegraph","amp");return await LB.access(J),"local"}catch{}if(process.argv[0]?.includes("npx")||process.env.npm_execpath?.includes("npx"))return"npx";return"unknown"}async detectPackageManager(){try{return await LB.access(nK(process.cwd(),"pnpm-lock.yaml")),"pnpm"}catch{}try{return await LB.access(nK(process.cwd(),"yarn.lock")),"yarn"}catch{}try{return await LB.access(nK(process.cwd(),"package-lock.json")),"npm"}catch{}return"unknown"}getSettingsPath(){let J=process.env.XDG_CONFIG_HOME||nK(zU1(),".config");return nK(J,"amp","settings.json")}getSecretsPath(){let J=process.env.XDG_DATA_HOME||nK(zU1(),".local","share");return nK(J,"amp","secrets.json")}getLogPath(){let J=process.env.XDG_CACHE_HOME||nK(zU1(),".cache");return nK(J,"amp","logs","cli.log")}}import{lookup as Ww6}from"node:dns";import{promisify as Fw6}from"node:util";var Hw6=Fw6(Ww6);class WU1{testUrls=["https://ampcode.com","https://sourcegraph.com","https://ampcodestatus.com"];testDomains=["ampcode.com","sourcegraph.com","ampcodestatus.com","github.com"];async collect(){let[J,Q]=await Promise.all([this.runConnectivityTests(),this.runDnsTests()]);return{connectivity:J,dns:Q,proxy:this.detectProxy(),timestamp:new Date().toISOString()}}async runConnectivityTests(){return(await Promise.allSettled(this.testUrls.map((Q)=>this.testConnectivity(Q)))).map((Q,Z)=>{if(Q.status==="fulfilled")return Q.value;else return{error:Q.reason instanceof Error?Q.reason.message:String(Q.reason),responseTime:0,success:!1,url:this.testUrls[Z]}})}async runDnsTests(){return(await Promise.allSettled(this.testDomains.map((Q)=>this.testDnsResolution(Q)))).map((Q,Z)=>{if(Q.status==="fulfilled")return Q.value;else return{domain:this.testDomains[Z],error:Q.reason instanceof Error?Q.reason.message:String(Q.reason),responseTime:0,success:!1}})}async testConnectivity(J){let Q=Date.now();try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),1e4),Y=await fetch(J,{method:"HEAD",signal:Z.signal});clearTimeout(X);let K=Date.now()-Q,q={};return Y.headers.forEach((G,z)=>{q[z]=G}),{headers:q,responseTime:K,status:Y.status,statusText:Y.statusText,success:Y.ok,url:J}}catch(Z){let X=Date.now()-Q;return{error:Z instanceof Error?Z.message:String(Z),responseTime:X,success:!1,url:J}}}async testDnsResolution(J){let Q=Date.now();try{let Z=await Hw6(J,{all:!0}),X=Date.now()-Q;return{addresses:Z.map((Y)=>Y.address),domain:J,responseTime:X,success:!0}}catch(Z){let X=Date.now()-Q;return{domain:J,error:Z instanceof Error?Z.message:String(Z),responseTime:X,success:!1}}}detectProxy(){let J={detected:!1},Q=process.env.HTTP_PROXY||process.env.http_proxy,Z=process.env.HTTPS_PROXY||process.env.https_proxy,X=process.env.NO_PROXY||process.env.no_proxy,Y=process.env.NODE_EXTRA_CA_CERTS;if(Q||Z||Y)J.detected=!0,J.httpProxy=Q,J.httpsProxy=Z,J.nodeExtraCaCerts=Y,J.noProxy=X;return J}}import{execFile as Bw6}from"node:child_process";import{promises as pl}from"node:fs";import{platform as pe1}from"node:os";import{promisify as Dw6}from"node:util";var FU1=Dw6(Bw6);class HU1{testUrls=["https://ampcode.com","https://sourcegraph.com"];async collect(){let[J,Q]=await Promise.all([this.collectTrustedCertificates(),this.testCertificateChains()]);return{trustedCertificates:J,certificateTests:Q,platform:pe1(),timestamp:new Date().toISOString()}}async collectTrustedCertificates(){let J={count:0,sources:[],sampleCertificates:[]};try{let Q=pe1();switch(Q){case"darwin":await this.collectMacOSCertificates(J);break;case"win32":await this.collectWindowsCertificates(J);break;case"linux":await this.collectLinuxCertificates(J);break;default:J.error=`Unsupported platform: ${Q}`}}catch(Q){J.error=Q instanceof Error?Q.message:String(Q)}return J}async testCertificateChains(){return(await Promise.allSettled(this.testUrls.map((Q)=>this.testCertificateChain(Q)))).map((Q,Z)=>{if(Q.status==="fulfilled")return Q.value;else return{url:this.testUrls[Z],success:!1,error:Q.reason instanceof Error?Q.reason.message:String(Q.reason)}})}async collectMacOSCertificates(J){try{let{stdout:Q}=await FU1("security",["find-certificate","-a","-p","/System/Library/Keychains/SystemRootCertificates.keychain"],{timeout:1e4}),Z=this.parsePEMCertificates(Q);J.count=Z.length,J.sources.push("/System/Library/Keychains/SystemRootCertificates.keychain"),J.sampleCertificates=Z.slice(0,3);try{let{stdout:X}=await FU1("security",["find-certificate","-a","-p","login.keychain"],{timeout:5000}),Y=this.parsePEMCertificates(X);if(Y.length>0)J.count+=Y.length,J.sources.push("login.keychain"),J.sampleCertificates.push(...Y.slice(0,2))}catch{}}catch(Q){throw Error(`Failed to collect macOS certificates: ${Q instanceof Error?Q.message:String(Q)}`)}}async collectWindowsCertificates(J){try{let{stdout:Q}=await FU1("powershell",["-Command","Get-ChildItem -Path Cert:\\LocalMachine\\Root | Select-Object Subject, Issuer, SerialNumber, NotBefore, NotAfter, Thumbprint | ConvertTo-Json"],{timeout:1e4}),Z=JSON.parse(Q),X=Array.isArray(Z)?Z:[Z];J.count=X.length,J.sources.push("Cert:\\LocalMachine\\Root"),J.sampleCertificates=X.slice(0,3).map((Y)=>({subject:Y.Subject,issuer:Y.Issuer,serialNumber:Y.SerialNumber,notBefore:Y.NotBefore,notAfter:Y.NotAfter,fingerprint:Y.Thumbprint}))}catch(Q){throw Error(`Failed to collect Windows certificates: ${Q instanceof Error?Q.message:String(Q)}`)}}async collectLinuxCertificates(J){let Q=["/etc/ssl/certs","/usr/local/share/ca-certificates","/etc/pki/tls/certs","/etc/ssl/ca-bundle.pem"],Z=0,X=[],Y=[];for(let K of Q)try{let q=await pl.stat(K);if(q.isDirectory()){let z=(await pl.readdir(K)).filter((U)=>U.endsWith(".crt")||U.endsWith(".pem"));if(z.length>0){if(Z+=z.length,X.push(K),Y.length<3)try{let U=await pl.readFile(`${K}/${z[0]}`,"utf8"),W=this.parsePEMCertificates(U);Y.push(...W.slice(0,1))}catch{}}}else if(q.isFile()){let G=await pl.readFile(K,"utf8"),z=this.parsePEMCertificates(G);if(z.length>0)Z+=z.length,X.push(K),Y.push(...z.slice(0,2))}}catch{}if(J.count=Z,J.sources=X,J.sampleCertificates=Y.slice(0,3),Z===0)throw Error("No certificate sources found")}async testCertificateChain(J){try{let Q=new URL(J),Z=await import("node:https");return new Promise((X,Y)=>{let K=Z.request({hostname:Q.hostname,port:Q.port||443,method:"HEAD",timeout:1e4},(q)=>{if(process.versions.bun)return X({url:J,success:!1,error:"The binary version of Amp does not support certificate testing"});let G=q.socket,z=G.getPeerCertificate(!0),U=G.getCipher();if(z&&Object.keys(z).length>0){let W=this.extractCertificateChain(z);X({url:J,success:!0,certificates:W,tlsVersion:G.getProtocol(),cipherSuite:U?`${U.name} (${U.version})`:void 0})}else X({url:J,success:!1,error:"No certificate information available"})});K.on("error",(q)=>{X({url:J,success:!1,error:q.message})}),K.on("timeout",()=>{K.destroy(),X({url:J,success:!1,error:"Connection timeout"})}),K.end()})}catch(Q){return{url:J,success:!1,error:Q instanceof Error?Q.message:String(Q)}}}parsePEMCertificates(J){let Q=[],Z=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,X=J.match(Z);if(X)for(let Y of X.slice(0,5))try{let K=Y.split(`
4511
4511
  `),q={subject:"Unknown",issuer:"Unknown"};for(let G of K){if(G.includes("Subject:"))q.subject=G.split("Subject:")[1]?.trim()||"Unknown";if(G.includes("Issuer:"))q.issuer=G.split("Issuer:")[1]?.trim()||"Unknown"}Q.push(q)}catch{}return Q}extractCertificateChain(J){let Q=[],Z=J;while(Z&&Q.length<10)if(Q.push({subject:Z.subject?.CN||Z.subject?.O||"Unknown",issuer:Z.issuer?.CN||Z.issuer?.O||"Unknown",serialNumber:Z.serialNumber,notBefore:Z.valid_from,notAfter:Z.valid_to,fingerprint:Z.fingerprint}),Z=Z.issuerCertificate,Z===J)break;return Q}}BU1();import{createWriteStream as Iw6}from"node:fs";import{join as Pw6}from"node:path";import{pipeline as Tw6}from"node:stream/promises";import{createGzip as Cw6}from"node:zlib";import{execFile as Lw6}from"node:child_process";import{promises as Aw6}from"node:fs";import{arch as ww6,cpus as Rw6,freemem as Ow6,platform as cl,release as jw6,totalmem as $w6}from"node:os";import{promisify as Ew6}from"node:util";var DU1=Ew6(Lw6);class MU1{async collect(){let J=Rw6(),Q=$w6(),Z=Ow6(),X={architecture:ww6(),cpu:{cores:J.length,model:J[0]?.model||"Unknown",speed:J[0]?.speed||0},environment:await(async()=>{let[Y,K,q,G,z,U,W,F,H]=await Promise.all([this.collectBrewInfo(),this.collectChocolateyInfo(),this.collectNixInfo(),this.collectNpmInfo(),this.collectNvmInfo(),this.collectPnpmInfo(),this.collectRipgrepBundledInfo(),this.collectRipgrepInfo(),this.collectYarnInfo()]);return{brew:Y,chocolatey:K,nix:q,node:{executablePath:process.execPath,version:process.version},npm:G,nvm:z,pnpm:U,rgBundled:W,rgSystem:F,yarn:H}})(),memory:{free:Z,total:Q,used:Q-Z},platform:cl(),version:jw6()};try{let Y=await this.getDiskSpace();if(Y)X.diskSpace=Y}catch{}return X}async findExecutablePath(J){try{if(cl()==="win32"){let{stdout:Z}=await DU1("where",[J],{timeout:5000});return Z.trim().split(`
@@ -4513,7 +4513,7 @@ Disconnect that client first.`))}});return}U(Error(`Connection failed: ${L.statu
4513
4513
  `),Y instanceof Error)throw Error(`Failed to generate support bundle: ${Y.message}`);throw Error(`Failed to generate support bundle: ${String(Y)}`)}}async collectData(){let J={system:Date.now(),amp:Date.now(),network:Date.now(),ssl:Date.now()},Q=this.systemCollector.collect().then((U)=>{return this.logStepComplete("System information collected",J.system),U}).catch((U)=>{return this.logStepError("System information collection failed",U),null}),Z=this.ampCollector.collect().then((U)=>{return this.logStepComplete("Amp configuration collected",J.amp),U}).catch((U)=>{return this.logStepError("Amp configuration collection failed",U),null}),X=this.networkCollector.collect().then((U)=>{return this.logStepComplete("Network diagnostics completed",J.network),U}).catch((U)=>{return this.logStepError("Network diagnostics failed",U),null}),Y=this.sslCollector.collect().then((U)=>{return this.logStepComplete("SSL certificate info collected",J.ssl),U}).catch((U)=>{return this.logStepError("SSL certificate collection failed",U),null});this.logStep(" → Collecting system information..."),this.logStep(" → Collecting Amp configuration..."),this.logStep(" → Running network diagnostics..."),this.logStep(" → Collecting SSL certificate info...");let[K,q,G,z]=await Promise.all([Q,Z,X,Y]);if(!K&&!q&&!G&&!z)throw Error("All diagnostic collectors failed. Unable to generate support bundle.");return{systemInfo:K||{error:"Collection failed"},ampInfo:q||{error:"Collection failed"},networkDiagnostics:G||{error:"Collection failed"},sslCertificates:z||{error:"Collection failed"},timestamp:new Date().toISOString(),metadata:{generatedAt:new Date().toISOString(),generatedBy:"amp-doctor",redacted:!0}}}async createBundle(J,Q){let Z=JSON.stringify(J,null,2),X=Iw6(Q),Y=Cw6();await Tw6(async function*(){yield Z},Y,X)}logStep(J){process.stderr.write(` ${J}
4514
4514
  `)}logStepComplete(J,Q){let Z=Date.now()-Q,X=Z<1000?`${Z}ms`:`${(Z/1000).toFixed(1)}s`;process.stderr.write(` ✓ ${J} (${X})
4515
4515
  `)}logStepError(J,Q){let Z=Q instanceof Error?Q.message:String(Q);process.stderr.write(` ✗ ${J}: ${Z}
4516
- `)}}il();E2();k0();DQ();MB();k0();function ie1(J){let Q={},Z=!0;return J.changes.pipe(Y7(void 0),vU(async(X,Y)=>{if(X===void 0||Z){let K=await J.keys();Y?.throwIfAborted(),Q=Object.fromEntries(await Promise.all(K.map(async(q)=>[q,await J.get(q)]))),Y?.throwIfAborted(),Z=!1}else{let K=await J.get(X);if(Y?.throwIfAborted(),K===void 0)Q={...Q,[X]:void 0},delete Q[X];else Q={...Q,[X]:K}}return Q}))}class NU1{storage;options;constructor(J,Q={}){this.storage=J;this.options=Q;if(!Q.lazy)this.initializeObservable()}initializeObservable(){if(this._observeHistory)return;this._observeHistory=bh1(ie1(this.storage).pipe(S0((J)=>{let Q=Object.values(J).filter((X)=>X&&("messages"in X)).toSorted((X,Y)=>Y.created-X.created),Z=[];for(let X of Q)if(X.messages.length!==0)Z.push(X);return Z.map((X)=>({id:X.id,v:X.v,created:X.created,title:X.title??null,userLastInteractedAt:al(X),env:X.env,originThreadID:X.originThreadID,mainThreadID:X.mainThreadID})).toSorted((X,Y)=>Y.userLastInteractedAt-X.userLastInteractedAt)}),O9()))}async delete(J){let Q=await this.storage.keys(),Z=[];for(let X of Q){let Y=await this.storage.get(X);if(Y&&Y.mainThreadID===J)Z.push(Y.id)}for(let X of Z)try{await this.storage.delete(X)}catch(Y){if(!BQ(Y))throw Y}try{await this.storage.delete(J)}catch(X){if(!BQ(X))throw X}try{let X=await PJ.deleteThread({thread:J});if(!X.ok&&X.error.code!=="thread-not-found")throw Error(`Error deleting thread from server: ${X.error.message??X.error.code}`)}catch(X){if(X instanceof Error&&X.message.includes("404"))return;throw X}}observeHistory(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory.observable}observeThreadList(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory.observable.pipe(I8((J,Q)=>{if(J.length!==Q.length)return!1;return J.every((Z,X)=>{let Y=Q[X];if(!Y)return!1;return Z.id===Y.id&&Z.title===Y.title&&Z.userLastInteractedAt===Y.userLastInteractedAt&&Z.mainThreadID===Y.mainThreadID&&JSON.stringify(Z.env?.initial?.trees?.map((K)=>K.displayName))===JSON.stringify(Y.env?.initial?.trees?.map((K)=>K.displayName))})}))}_observeHistory;dispose(){this._observeHistory?.subscription.unsubscribe()}}function al(J){return Math.max(J.created,...J.messages.map((Q)=>Q.role==="user"?Q.meta?.sentAt:void 0).filter((Q)=>Q!==void 0))}k0();WQ();WQ();F0();function LU1(J,Q){return new Promise((Z,X)=>{if(Q?.aborted)return X(Q.reason);let Y=setTimeout(Z,J);Q?.addEventListener("abort",()=>{clearTimeout(Y),X(Q.reason)},{once:!0})})}function ae1(){return new Promise((J)=>setTimeout(J,0))}E2();qp();class AU1{storage;exclusiveThreads=new pT;get exclusiveThreadsChanges(){return this.exclusiveThreads.observable}dirtyThreads=new Set;creationPromises=new Map;flushRequests=new p8;flusher=this.flushRequests.pipe(Y7(void 0),SK(100),w9(()=>{let J=Array.from(this.dirtyThreads);if(this.dirtyThreads=new Set,J.length===0)return M51;let Q=J.slice(0,3).map(async(Z)=>{try{this.flushThread(Z)}catch(X){l.error("Error flushing thread to storage:",X,{name:"ThreadService",threadID:Z}),this.dirtyThreads.add(Z)}});if(J.length>3){for(let Z of J.slice(3))this.dirtyThreads.add(Z);setTimeout(()=>this.flushRequests.next(),100)}return d8(async()=>{await Promise.all(Q)})})).subscribe({});constructor(J){this.storage=J}async flushThread(J){let Q=this.exclusiveThreads.get(J);if(!Q)return;let[Z]=Q.getValue();await this.storage.set(J,Z)}observeRaw(J){return this.exclusiveThreads.observable.pipe(S0((Q)=>Q.get(J)),I8(),w9((Q)=>{if(Q!==void 0)return Q;return new J0((Z)=>{this.storage.get(J).then((X)=>{if(X)Z.next([UQ(X,!0),[]])})})}))}async getUnfrozen(J,Q){let Z=this.exclusiveThreads.get(J);if(Z)return Z.getValue()[0];let X=await this.storage.get(J);if(Q?.throwIfAborted(),!X)return null;return X}async get(J,Q){let Z=await this.getUnfrozen(J,Q);if(!Z)return null;return UQ(Z,!0)}async getPrimitiveProperty(J,Q){let Z=await this.getUnfrozen(J);if(!Z)return null;return Z[Q]}observe(J){return this.observeRaw(J).pipe(S0(([Q,Z])=>Q),V51(100,{leading:!0,trailing:!0}))}observePatches(J){return this.observeRaw(J).pipe(S0(([Q,Z],X)=>X===0?Q:Z),kw6(100))}async exclusiveSyncReadWriter(J){if(this.exclusiveThreads.has(J))throw Error(`Thread ${J} already has an exclusive read-writer`);let Q=this.exclusiveThreads.get(J);if(!Q){let X=await this.storage.get(J);if(!X)X=vw6(J),await this.storage.set(J,X);X=UQ(X,!0),Q=new d2([X,[]]),this.exclusiveThreads.set(J,Q),await ae1()}let Z=!1;return{read:()=>{if(Z)throw Error("thread exclusive read-writer was disposed");return Q.getValue()[0]},write:(X)=>{if(Z)throw Error("thread exclusive read-writer was disposed");let[Y,K]=gJ1(Q.getValue()[0],()=>{return X});Q.next([Y,K]),this.dirtyThreads.add(J),this.flushRequests.next()},update:(X)=>{if(Z)throw Error("thread exclusive read-writer was disposed");let[Y,K]=gJ1(Q.getValue()[0],X);return Q.next([Y,K]),this.dirtyThreads.add(J),this.flushRequests.next(),Y},asyncDispose:async()=>{if(Z)return;if(Z=!0,this.dirtyThreads.has(J)){let[X]=Q.getValue();try{await this.storage.set(J,X)}catch(Y){l.error("Error flushing thread on dispose:",Y,{name:"ThreadService",threadID:J})}this.dirtyThreads.delete(J)}this.exclusiveThreads.delete(J)}}}flush(){this.flushRequests.next()}async flushVersion(J,Q,Z=5000){this.flush();let X=Date.now();while(!0){if(Date.now()-X>Z)throw Error(`Timed out waiting for thread ${J} to reach version ${Q}`);let Y=await this.storage.get(J);if(Y&&Y.v>=Q)return;await new Promise((K)=>setTimeout(K,10))}}async forkThread(J,Q){let Z=await this.get(J);if(!Z)throw Error(`Thread ${J} not found`);let X=Z.messages.slice(0,Q+1);return{threadID:await this.createForkedThread(J,X,Q)}}async createForkedThread(J,Q,Z){let X=await this.get(J);if(!X)throw Error(`Thread ${J} not found`);let Y=hK(),K=await this.exclusiveSyncReadWriter(Y),q=`Forked: ${X.title||"Untitled"}`,G=K.update((U)=>{if(U.originThreadID=J,U.forkPointIndex=Z,U.v++,U.title=q,X.env)U.env=a8(X.env);for(let W of Q)U.messages.push(a8(W))});await K.asyncDispose();let z=G.v;return await this.flushVersion(Y,z),Y}getRecentlyActiveThread(){let J=null,Q=0;for(let[,Z]of this.exclusiveThreads.entries()){let[X]=Z.getValue();if(al(X)>Q)J=X,Q=al(X)}return J}async asyncDispose(){this.flusher.unsubscribe(),await Promise.all(Array.from(this.dirtyThreads).map((J)=>this.flushThread(J))),this.exclusiveThreads.dispose()}}function vw6(J){return{v:0,id:J,created:Date.now(),messages:[]}}function kw6(J){return(Q)=>new J0((Z)=>{let X=[],Y=null,K=()=>{if(Y)clearTimeout(Y),Y=null;if(X.length>0)Z.next(X),X=[]};return Q.subscribe({next:(q)=>{if(!(q instanceof Array)){K(),Z.next(q);return}X.push(...q),Y=setTimeout(K,J)},error:(q)=>{K(),Z.error(q)},complete:()=>{K(),Z.complete()}})})}k0();F0();j2();fH();aK();MB();function ne1({threadService:J,threadHistoryService:Q,isExtensionDevelopment:Z=!1}){let X=!1,Y=[],K=new B51,q=new d2(new Map),G=async()=>{if(X)return!1;if(!await Y6(_e1))return!1;let N=await Z9();if(Z&&yH(N.settings.url)&&process.env.FORCE_ENABLE_SYNC!=="1")return l.debug(`Skipping sync to ${tQ} in extension development mode to avoid polluting the production server`,{name:"ThreadSyncService"}),!1;return!0},z=async(N)=>{if(!H(N))return;let L=await J.get(N);if(L&&L.messages.length===0)return;if(!await G())return;let A=new AbortController,w={dispose:()=>A.abort()};Y.push(w);try{try{let R=await PJ.uploadThread({thread:L,createdOnServer:!1},{signal:A.signal});if(!R.ok)throw Error(`Failed to upload thread: ${R.error.code}`)}catch(R){throw l.debug("Failed to upload thread",{error:R}),R}}finally{let R=Y.indexOf(w);if(R!==-1)Y.splice(R,1);if(A.abort(),Y.length>30)l.debug("[AbortController] High disposables count detected: ",Y.length,{name:"ThreadSyncService",operation:"uploadThread"})}},U=new Map,W=new Set,F=60000,H=(N)=>{if(W.has(N))return!1;let L=U.get(N);if(!L)return!0;let A=Date.now()-L,w=A>=F;if(!w)l.debug(`Skipping thread ${N} sync due to backoff (${Math.round(A/1000)}s elapsed of ${F/1000}s backoff)`,{name:"ThreadSyncService"});return w},B=async()=>{for(let N of K){if(!H(N))continue;try{await z(N),K.delete(N),U.delete(N)}catch(L){let A=L instanceof Error?L.message:String(L);if(A.includes("404")&&A.includes("Thread not found"))W.add(N),K.delete(N),U.delete(N),l.warn(`Thread ${N} not found on server, stopping sync attempts`,{name:"ThreadSyncService"});else U.set(N,Date.now()),l.error(`Error syncing thread ${N} (will retry after backoff)`,L,{name:"ThreadSyncService"})}}},M=async(N,L=!1)=>{if(!await G())return;let A;if(N)A=(await Promise.all(N.map((j)=>Y6(J.observe(j).pipe(S0((E)=>E?{id:E.id,v:E.v}:null)))))).filter((j)=>j!==null);else{let j=await Y6(Q.observeHistory().pipe(S0((P)=>P.map((T)=>({id:T.id,v:T.v}))))),E=await Y6(J.exclusiveThreadsChanges.pipe(S0((P)=>Object.values(P).map(([T,v])=>({id:T.id,v:T.v})))));A=j.concat(E)}let w={threadVersions:[],threadMetas:[]},R=new Set;for(let j of A){if(R.has(j.id))continue;if(R.add(j.id),W.has(j.id))continue;if(!L)w.threadVersions.push({id:j.id,v:j.v});let E=q.getValue().get(j.id);w.threadMetas.push({id:j.id,meta:E?.status==="synced"?E.info?.meta:void 0})}if(w.threadVersions.length===0&&w.threadMetas.length===0)return;if(!await G())return;let O=new AbortController,$={dispose:()=>O.abort()};Y.push($);try{l.debug("Sending threads sync request",{name:"ThreadSyncService",source:L?"metadata":"full",threadCount:w.threadVersions.length+w.threadMetas.length,specificThreads:N?.length??"all"});let j=await P5("/api/threads/sync",fetch,{method:"POST",body:JSON.stringify(w),signal:O.signal});if(!j.ok){let T=await j.text().catch(()=>"Unable to read response body");throw l.warn("Threads sync request failed",{name:"ThreadSyncService",status:j.status,text:T}),Error(`Threads sync API responded with status: ${j.status}${T?`: ${T}`:""}`)}l.debug("Got response for threads sync request",{name:"ThreadSyncService",status:j.status});let E=await j.json(),P=0;for(let T of E.threadActions){if(!(("action"in T)&&typeof T.action==="string"))continue;switch(T.action){case"upload":{if(!W.has(T.id))K.add(T.id),P++;break}case"meta":{q.getValue().set(T.id,{status:"synced",info:{meta:T.meta}});break}default:continue}}if(N){for(let T of N)if(q.getValue().get(T)?.status==="unknown")q.getValue().set(T,{status:"synced",info:null})}q.next(q.getValue()),await B(),l.debug(`Sync completed (${N?N.length:"all"} threads checked, ${P} threads needed sync)`,{name:"ThreadSyncService"})}finally{let j=Y.indexOf($);if(j!==-1)Y.splice(j,1);if(O.abort(),Y.length>30)l.debug("[AbortController] High disposables count detected: ",Y.length,{name:"ThreadSyncService",operation:"sync"})}};l.debug("Thread sync service initialized (on-demand sync mode)",{name:"ThreadSyncService"});let V=Promise.resolve();return Y.push(D51(K.observable.pipe(wJ((N)=>N.size>0),SK(3000),vU(()=>B().catch((N)=>l.error("Error processing sync queue:",N,{name:"ThreadSyncService"})))).subscribe({}))),Y.push(D51(J.exclusiveThreadsChanges.pipe(w9((N)=>dT(...Array.from(N.entries()).map(([,L])=>L.pipe(CV(([A,w])=>{if(!W.has(A.id))K.add(A.id)})))))).subscribe({}))),{async sync(){return M()},async uploadThread(N){return z(N)},initialSyncComplete:V,async updateThreadMeta(N,L){let A=q.getValue().get(N),w=new AbortController,R={dispose:()=>w.abort()};Y.push(R);try{q.getValue().set(N,{status:"synced",info:{meta:{visibility:L.visibility,sharedGroupIDs:"sharedGroupIDs"in L?L.sharedGroupIDs:[],public:L.visibility==="public",private:L.visibility==="private"}}}),q.next(q.getValue());let O=await PJ.setThreadMeta({thread:N,meta:L},{signal:w.signal});if(!O.ok)throw l.debug("Failed to update sharing status (USE_NEW_INTERNAL_API=true)",{error:O.error}),Error(`Failed to update sharing status: ${O.error.code}`)}catch(O){if(A)q.getValue().set(N,A);else q.getValue().delete(N);throw q.next(q.getValue()),O}finally{let O=Y.indexOf(R);if(O!==-1)Y.splice(O,1);w.abort(),l.debug(`[AbortController] Cleaned up for updateThreadMeta ${N}, disposables count: ${Y.length}`,{name:"ThreadSyncService",threadID:N,operation:"updateThreadMeta",wasTracked:O!==-1})}},threadSyncInfo(N){let L=[];for(let A of N){if(W.has(A)){if(!q.getValue().has(A))q.getValue().set(A,{status:"synced",info:null});continue}if(!q.getValue().has(A))q.getValue().set(A,{status:"unknown"}),L.push(A)}if(L.length>0)M(L,!0).catch((A)=>l.error("Error syncing thread metadata:",A,{name:"ThreadSyncService"}));return q.pipe(S0((A)=>{let w={};for(let R of N)w[R]=A.get(R)??{status:"synced",info:null};return w}))},dispose(){if(X)return;X=!0;for(let N of Y)N.dispose()}}}n5();iH();E2();async function LY0(J,Q,Z){let X=a5(J.content);if(!X)return;let q=(await(await wl(Z)).messages.create({model:ro1,max_tokens:60,temperature:0.7,system:`You are an assistant that generates short, descriptive titles (maximum 7 words, "Sentence case" with the first word capitalized not "Title Case") based on user's message to an agentic coding tool. Your titles should be concise (max 7 words) and capture the essence of the query or topic. DO NOT ASSUME OR GUESS the user's intent beyond what is in their message. Omit generic words like "question", "request", etc. Be professional and precise. Use common software engineering terms and acronyms if they are helpful. Use the set_title tool to provide your answer.`,messages:[{role:"user",content:`<message>${X}</message>`}],tools:[{name:"set_title",input_schema:{type:"object",properties:{title:{type:"string",description:'The short thread title (maximum 7 words, "Sentence case" with the first word capitalized not "Title Case") that you generated for the message'}},required:["title"]}}],tool_choice:{type:"tool",name:"set_title",disable_parallel_tool_use:!0}},{stream:!1,signal:Z,headers:{[KY]:Q}})).content.at(0);if(!q)throw Error("no content in generateThreadTitle response");if(q.type!=="tool_use"||q.name!=="set_title")throw Error("missing or invalid tool_use in generateThreadTitle response");return q.input&&typeof q.input==="object"&&"title"in q.input&&typeof q.input.title==="string"?q.input.title:void 0}k0();F0();async function AY0(J,Q,Z,X){let Y=await J.forkThread(Z);return await Eo6(Q,J.threadID,Y,X),Y}async function Eo6(J,Q,Z,X={}){let{originMetaTimeout:Y=5000,forkedThreadTimeout:K=1e4,waitForForkedUpload:q=!0}=X;try{let z=(await Y6(J.threadSyncInfo([Q]).pipe(wJ((W)=>W[Q]?.status==="synced"),uw(Y))))[Q];if(z?.status!=="synced"||!z.info?.meta){l.debug("Origin thread has no metadata to inherit",{name:"inheritThreadVisibility",originThreadID:Q,forkedThreadID:Z});return}if(q)await Y6(J.threadSyncInfo([Z]).pipe(wJ((W)=>W[Z]?.status==="synced"),uw(K)));let U=z.info.meta.visibility==="private"?{visibility:z.info.meta.visibility,sharedGroupIDs:z.info.meta.sharedGroupIDs}:{visibility:z.info.meta.visibility};await J.updateThreadMeta(Z,U),l.debug("Successfully inherited thread visibility",{name:"inheritThreadVisibility",originThreadID:Q,forkedThreadID:Z,metadata:z.info.meta})}catch(G){l.debug("Failed to inherit thread visibility settings",{name:"inheritThreadVisibility",error:G,originThreadID:Q,forkedThreadID:Z})}}j3();s6();k0();var EL0=r6(AL0(),1);rw();F0();DQ();MD1();mG();function wL0(J){let Q=J.trim().split(`
4516
+ `)}}il();E2();k0();DQ();MB();k0();function ie1(J){let Q={},Z=!0;return J.changes.pipe(Y7(void 0),vU(async(X,Y)=>{if(X===void 0||Z){let K=await J.keys();Y?.throwIfAborted(),Q=Object.fromEntries(await Promise.all(K.map(async(q)=>[q,await J.get(q)]))),Y?.throwIfAborted(),Z=!1}else{let K=await J.get(X);if(Y?.throwIfAborted(),K===void 0)Q={...Q,[X]:void 0},delete Q[X];else Q={...Q,[X]:K}}return Q}))}class NU1{storage;constructor(J,Q={}){this.storage=J;if(!Q.lazy)this.initializeObservable()}initializeObservable(){if(this._observeHistory)return;this._observeHistory=bh1(ie1(this.storage).pipe(S0((J)=>{let Q=Object.values(J).filter((X)=>X&&("messages"in X)).toSorted((X,Y)=>Y.created-X.created),Z=[];for(let X of Q)if(X.messages.length!==0)Z.push(X);return Z.map((X)=>({id:X.id,v:X.v,created:X.created,title:X.title??null,userLastInteractedAt:al(X),env:X.env,originThreadID:X.originThreadID,mainThreadID:X.mainThreadID})).toSorted((X,Y)=>Y.userLastInteractedAt-X.userLastInteractedAt)}),O9()))}async delete(J){let Q=await this.storage.keys(),Z=[];for(let X of Q){let Y=await this.storage.get(X);if(Y&&Y.mainThreadID===J)Z.push(Y.id)}for(let X of Z)try{await this.storage.delete(X)}catch(Y){if(!BQ(Y))throw Y}try{await this.storage.delete(J)}catch(X){if(!BQ(X))throw X}try{let X=await PJ.deleteThread({thread:J});if(!X.ok&&X.error.code!=="thread-not-found")throw Error(`Error deleting thread from server: ${X.error.message??X.error.code}`)}catch(X){if(X instanceof Error&&X.message.includes("404"))return;throw X}}observeHistory(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory.observable}observeThreadList(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory.observable.pipe(I8((J,Q)=>{if(J.length!==Q.length)return!1;return J.every((Z,X)=>{let Y=Q[X];if(!Y)return!1;return Z.id===Y.id&&Z.title===Y.title&&Z.userLastInteractedAt===Y.userLastInteractedAt&&Z.mainThreadID===Y.mainThreadID&&JSON.stringify(Z.env?.initial?.trees?.map((K)=>K.displayName))===JSON.stringify(Y.env?.initial?.trees?.map((K)=>K.displayName))})}))}_observeHistory;dispose(){this._observeHistory?.subscription.unsubscribe()}}function al(J){return Math.max(J.created,...J.messages.map((Q)=>Q.role==="user"?Q.meta?.sentAt:void 0).filter((Q)=>Q!==void 0))}k0();WQ();WQ();F0();function LU1(J,Q){return new Promise((Z,X)=>{if(Q?.aborted)return X(Q.reason);let Y=setTimeout(Z,J);Q?.addEventListener("abort",()=>{clearTimeout(Y),X(Q.reason)},{once:!0})})}function ae1(){return new Promise((J)=>setTimeout(J,0))}E2();qp();class AU1{storage;exclusiveThreads=new pT;get exclusiveThreadsChanges(){return this.exclusiveThreads.observable}dirtyThreads=new Set;creationPromises=new Map;flushRequests=new p8;flusher=this.flushRequests.pipe(Y7(void 0),SK(100),w9(()=>{let J=Array.from(this.dirtyThreads);if(this.dirtyThreads=new Set,J.length===0)return M51;let Q=J.slice(0,3).map(async(Z)=>{try{this.flushThread(Z)}catch(X){l.error("Error flushing thread to storage:",X,{name:"ThreadService",threadID:Z}),this.dirtyThreads.add(Z)}});if(J.length>3){for(let Z of J.slice(3))this.dirtyThreads.add(Z);setTimeout(()=>this.flushRequests.next(),100)}return d8(async()=>{await Promise.all(Q)})})).subscribe({});constructor(J){this.storage=J}async flushThread(J){let Q=this.exclusiveThreads.get(J);if(!Q)return;let[Z]=Q.getValue();await this.storage.set(J,Z)}observeRaw(J){return this.exclusiveThreads.observable.pipe(S0((Q)=>Q.get(J)),I8(),w9((Q)=>{if(Q!==void 0)return Q;return new J0((Z)=>{this.storage.get(J).then((X)=>{if(X)Z.next([UQ(X,!0),[]])})})}))}async getUnfrozen(J,Q){let Z=this.exclusiveThreads.get(J);if(Z)return Z.getValue()[0];let X=await this.storage.get(J);if(Q?.throwIfAborted(),!X)return null;return X}async get(J,Q){let Z=await this.getUnfrozen(J,Q);if(!Z)return null;return UQ(Z,!0)}async getPrimitiveProperty(J,Q){let Z=await this.getUnfrozen(J);if(!Z)return null;return Z[Q]}observe(J){return this.observeRaw(J).pipe(S0(([Q,Z])=>Q),V51(100,{leading:!0,trailing:!0}))}observePatches(J){return this.observeRaw(J).pipe(S0(([Q,Z],X)=>X===0?Q:Z),kw6(100))}async exclusiveSyncReadWriter(J){if(this.exclusiveThreads.has(J))throw Error(`Thread ${J} already has an exclusive read-writer`);let Q=this.exclusiveThreads.get(J);if(!Q){let X=await this.storage.get(J);if(!X)X=vw6(J),await this.storage.set(J,X);X=UQ(X,!0),Q=new d2([X,[]]),this.exclusiveThreads.set(J,Q),await ae1()}let Z=!1;return{read:()=>{if(Z)throw Error("thread exclusive read-writer was disposed");return Q.getValue()[0]},write:(X)=>{if(Z)throw Error("thread exclusive read-writer was disposed");let[Y,K]=gJ1(Q.getValue()[0],()=>{return X});Q.next([Y,K]),this.dirtyThreads.add(J),this.flushRequests.next()},update:(X)=>{if(Z)throw Error("thread exclusive read-writer was disposed");let[Y,K]=gJ1(Q.getValue()[0],X);return Q.next([Y,K]),this.dirtyThreads.add(J),this.flushRequests.next(),Y},asyncDispose:async()=>{if(Z)return;if(Z=!0,this.dirtyThreads.has(J)){let[X]=Q.getValue();try{await this.storage.set(J,X)}catch(Y){l.error("Error flushing thread on dispose:",Y,{name:"ThreadService",threadID:J})}this.dirtyThreads.delete(J)}this.exclusiveThreads.delete(J)}}}flush(){this.flushRequests.next()}async flushVersion(J,Q,Z=5000){this.flush();let X=Date.now();while(!0){if(Date.now()-X>Z)throw Error(`Timed out waiting for thread ${J} to reach version ${Q}`);let Y=await this.storage.get(J);if(Y&&Y.v>=Q)return;await new Promise((K)=>setTimeout(K,10))}}async forkThread(J,Q){let Z=await this.get(J);if(!Z)throw Error(`Thread ${J} not found`);let X=Z.messages.slice(0,Q+1);return{threadID:await this.createForkedThread(J,X,Q)}}async createForkedThread(J,Q,Z){let X=await this.get(J);if(!X)throw Error(`Thread ${J} not found`);let Y=hK(),K=await this.exclusiveSyncReadWriter(Y),q=`Forked: ${X.title||"Untitled"}`,G=K.update((U)=>{if(U.originThreadID=J,U.forkPointIndex=Z,U.v++,U.title=q,X.env)U.env=a8(X.env);for(let W of Q)U.messages.push(a8(W))});await K.asyncDispose();let z=G.v;return await this.flushVersion(Y,z),Y}getRecentlyActiveThread(){let J=null,Q=0;for(let[,Z]of this.exclusiveThreads.entries()){let[X]=Z.getValue();if(al(X)>Q)J=X,Q=al(X)}return J}async asyncDispose(){this.flusher.unsubscribe(),await Promise.all(Array.from(this.dirtyThreads).map((J)=>this.flushThread(J))),this.exclusiveThreads.dispose()}}function vw6(J){return{v:0,id:J,created:Date.now(),messages:[]}}function kw6(J){return(Q)=>new J0((Z)=>{let X=[],Y=null,K=()=>{if(Y)clearTimeout(Y),Y=null;if(X.length>0)Z.next(X),X=[]};return Q.subscribe({next:(q)=>{if(!(q instanceof Array)){K(),Z.next(q);return}X.push(...q),Y=setTimeout(K,J)},error:(q)=>{K(),Z.error(q)},complete:()=>{K(),Z.complete()}})})}k0();F0();j2();fH();aK();MB();function ne1({threadService:J,threadHistoryService:Q,isExtensionDevelopment:Z=!1}){let X=!1,Y=[],K=new B51,q=new d2(new Map),G=async()=>{if(X)return!1;if(!await Y6(_e1))return!1;let N=await Z9();if(Z&&yH(N.settings.url)&&process.env.FORCE_ENABLE_SYNC!=="1")return l.debug(`Skipping sync to ${tQ} in extension development mode to avoid polluting the production server`,{name:"ThreadSyncService"}),!1;return!0},z=async(N)=>{if(!H(N))return;let L=await J.get(N);if(L&&L.messages.length===0)return;if(!await G())return;let A=new AbortController,w={dispose:()=>A.abort()};Y.push(w);try{try{let R=await PJ.uploadThread({thread:L,createdOnServer:!1},{signal:A.signal});if(!R.ok)throw Error(`Failed to upload thread: ${R.error.code}`)}catch(R){throw l.debug("Failed to upload thread",{error:R}),R}}finally{let R=Y.indexOf(w);if(R!==-1)Y.splice(R,1);if(A.abort(),Y.length>30)l.debug("[AbortController] High disposables count detected: ",Y.length,{name:"ThreadSyncService",operation:"uploadThread"})}},U=new Map,W=new Set,F=60000,H=(N)=>{if(W.has(N))return!1;let L=U.get(N);if(!L)return!0;let A=Date.now()-L,w=A>=F;if(!w)l.debug(`Skipping thread ${N} sync due to backoff (${Math.round(A/1000)}s elapsed of ${F/1000}s backoff)`,{name:"ThreadSyncService"});return w},B=async()=>{for(let N of K){if(!H(N))continue;try{await z(N),K.delete(N),U.delete(N)}catch(L){let A=L instanceof Error?L.message:String(L);if(A.includes("404")&&A.includes("Thread not found"))W.add(N),K.delete(N),U.delete(N),l.warn(`Thread ${N} not found on server, stopping sync attempts`,{name:"ThreadSyncService"});else U.set(N,Date.now()),l.error(`Error syncing thread ${N} (will retry after backoff)`,L,{name:"ThreadSyncService"})}}},M=async(N,L=!1)=>{if(!await G())return;let A;if(N)A=(await Promise.all(N.map((j)=>Y6(J.observe(j).pipe(S0((E)=>E?{id:E.id,v:E.v}:null)))))).filter((j)=>j!==null);else{let j=await Y6(Q.observeHistory().pipe(S0((P)=>P.map((T)=>({id:T.id,v:T.v}))))),E=await Y6(J.exclusiveThreadsChanges.pipe(S0((P)=>Object.values(P).map(([T,v])=>({id:T.id,v:T.v})))));A=j.concat(E)}let w={threadVersions:[],threadMetas:[]},R=new Set;for(let j of A){if(R.has(j.id))continue;if(R.add(j.id),W.has(j.id))continue;if(!L)w.threadVersions.push({id:j.id,v:j.v});let E=q.getValue().get(j.id);w.threadMetas.push({id:j.id,meta:E?.status==="synced"?E.info?.meta:void 0})}if(w.threadVersions.length===0&&w.threadMetas.length===0)return;if(!await G())return;let O=new AbortController,$={dispose:()=>O.abort()};Y.push($);try{l.debug("Sending threads sync request",{name:"ThreadSyncService",source:L?"metadata":"full",threadCount:w.threadVersions.length+w.threadMetas.length,specificThreads:N?.length??"all"});let j=await P5("/api/threads/sync",fetch,{method:"POST",body:JSON.stringify(w),signal:O.signal});if(!j.ok){let T=await j.text().catch(()=>"Unable to read response body");throw l.warn("Threads sync request failed",{name:"ThreadSyncService",status:j.status,text:T}),Error(`Threads sync API responded with status: ${j.status}${T?`: ${T}`:""}`)}l.debug("Got response for threads sync request",{name:"ThreadSyncService",status:j.status});let E=await j.json(),P=0;for(let T of E.threadActions){if(!(("action"in T)&&typeof T.action==="string"))continue;switch(T.action){case"upload":{if(!W.has(T.id))K.add(T.id),P++;break}case"meta":{q.getValue().set(T.id,{status:"synced",info:{meta:T.meta}});break}default:continue}}if(N){for(let T of N)if(q.getValue().get(T)?.status==="unknown")q.getValue().set(T,{status:"synced",info:null})}q.next(q.getValue()),await B(),l.debug(`Sync completed (${N?N.length:"all"} threads checked, ${P} threads needed sync)`,{name:"ThreadSyncService"})}finally{let j=Y.indexOf($);if(j!==-1)Y.splice(j,1);if(O.abort(),Y.length>30)l.debug("[AbortController] High disposables count detected: ",Y.length,{name:"ThreadSyncService",operation:"sync"})}};l.debug("Thread sync service initialized (on-demand sync mode)",{name:"ThreadSyncService"});let V=Promise.resolve();return Y.push(D51(K.observable.pipe(wJ((N)=>N.size>0),SK(3000),vU(()=>B().catch((N)=>l.error("Error processing sync queue:",N,{name:"ThreadSyncService"})))).subscribe({}))),Y.push(D51(J.exclusiveThreadsChanges.pipe(w9((N)=>dT(...Array.from(N.entries()).map(([,L])=>L.pipe(CV(([A,w])=>{if(!W.has(A.id))K.add(A.id)})))))).subscribe({}))),{async sync(){return M()},async uploadThread(N){return z(N)},initialSyncComplete:V,async updateThreadMeta(N,L){let A=q.getValue().get(N),w=new AbortController,R={dispose:()=>w.abort()};Y.push(R);try{q.getValue().set(N,{status:"synced",info:{meta:{visibility:L.visibility,sharedGroupIDs:"sharedGroupIDs"in L?L.sharedGroupIDs:[],public:L.visibility==="public",private:L.visibility==="private"}}}),q.next(q.getValue());let O=await PJ.setThreadMeta({thread:N,meta:L},{signal:w.signal});if(!O.ok)throw l.debug("Failed to update sharing status (USE_NEW_INTERNAL_API=true)",{error:O.error}),Error(`Failed to update sharing status: ${O.error.code}`)}catch(O){if(A)q.getValue().set(N,A);else q.getValue().delete(N);throw q.next(q.getValue()),O}finally{let O=Y.indexOf(R);if(O!==-1)Y.splice(O,1);w.abort(),l.debug(`[AbortController] Cleaned up for updateThreadMeta ${N}, disposables count: ${Y.length}`,{name:"ThreadSyncService",threadID:N,operation:"updateThreadMeta",wasTracked:O!==-1})}},threadSyncInfo(N){let L=[];for(let A of N){if(W.has(A)){if(!q.getValue().has(A))q.getValue().set(A,{status:"synced",info:null});continue}if(!q.getValue().has(A))q.getValue().set(A,{status:"unknown"}),L.push(A)}if(L.length>0)M(L,!0).catch((A)=>l.error("Error syncing thread metadata:",A,{name:"ThreadSyncService"}));return q.pipe(S0((A)=>{let w={};for(let R of N)w[R]=A.get(R)??{status:"synced",info:null};return w}))},dispose(){if(X)return;X=!0;for(let N of Y)N.dispose()}}}n5();iH();E2();async function LY0(J,Q,Z){let X=a5(J.content);if(!X)return;let q=(await(await wl(Z)).messages.create({model:ro1,max_tokens:60,temperature:0.7,system:`You are an assistant that generates short, descriptive titles (maximum 7 words, "Sentence case" with the first word capitalized not "Title Case") based on user's message to an agentic coding tool. Your titles should be concise (max 7 words) and capture the essence of the query or topic. DO NOT ASSUME OR GUESS the user's intent beyond what is in their message. Omit generic words like "question", "request", etc. Be professional and precise. Use common software engineering terms and acronyms if they are helpful. Use the set_title tool to provide your answer.`,messages:[{role:"user",content:`<message>${X}</message>`}],tools:[{name:"set_title",input_schema:{type:"object",properties:{title:{type:"string",description:'The short thread title (maximum 7 words, "Sentence case" with the first word capitalized not "Title Case") that you generated for the message'}},required:["title"]}}],tool_choice:{type:"tool",name:"set_title",disable_parallel_tool_use:!0}},{stream:!1,signal:Z,headers:{[KY]:Q}})).content.at(0);if(!q)throw Error("no content in generateThreadTitle response");if(q.type!=="tool_use"||q.name!=="set_title")throw Error("missing or invalid tool_use in generateThreadTitle response");return q.input&&typeof q.input==="object"&&"title"in q.input&&typeof q.input.title==="string"?q.input.title:void 0}k0();F0();async function AY0(J,Q,Z,X){let Y=await J.forkThread(Z);return await Eo6(Q,J.threadID,Y,X),Y}async function Eo6(J,Q,Z,X={}){let{originMetaTimeout:Y=5000,forkedThreadTimeout:K=1e4,waitForForkedUpload:q=!0}=X;try{let z=(await Y6(J.threadSyncInfo([Q]).pipe(wJ((W)=>W[Q]?.status==="synced"),uw(Y))))[Q];if(z?.status!=="synced"||!z.info?.meta){l.debug("Origin thread has no metadata to inherit",{name:"inheritThreadVisibility",originThreadID:Q,forkedThreadID:Z});return}if(q)await Y6(J.threadSyncInfo([Z]).pipe(wJ((W)=>W[Z]?.status==="synced"),uw(K)));let U=z.info.meta.visibility==="private"?{visibility:z.info.meta.visibility,sharedGroupIDs:z.info.meta.sharedGroupIDs}:{visibility:z.info.meta.visibility};await J.updateThreadMeta(Z,U),l.debug("Successfully inherited thread visibility",{name:"inheritThreadVisibility",originThreadID:Q,forkedThreadID:Z,metadata:z.info.meta})}catch(G){l.debug("Failed to inherit thread visibility settings",{name:"inheritThreadVisibility",error:G,originThreadID:Q,forkedThreadID:Z})}}j3();s6();k0();var EL0=r6(AL0(),1);rw();F0();DQ();MD1();mG();function wL0(J){let Q=J.trim().split(`
4517
4517
  `).map((K)=>K.trim()).filter((K)=>K);if(Q.length===0)return null;let Z="",X=[],Y={};for(let K of Q){let q=K.indexOf(":");if(q===-1)continue;let G=K.substring(0,q).trim(),z=K.substring(q+1).trim();if(!G||!z)continue;if(G==="name")Z=z;else if(G==="description")X.push(z);else{let U=z.indexOf(" ");if(U===-1)Y[G]={type:"string",description:z};else{let W=z.substring(0,U),F=z.substring(U+1).trim();if(["string","boolean","number","integer","array","object"].includes(W.toLowerCase()))Y[G]={type:W,description:F};else Y[G]={type:"string",description:z}}}}if(!Z)return null;return{name:Z,description:X.join(`
4518
4518
  `),parameters:Y}}function RL0(J,Q){let Z={},X=[];for(let[K,q]of Object.entries(J.parameters)){let G;switch(q.type.toLowerCase()){case"boolean":G="boolean";break;case"number":case"integer":G=q.type.toLowerCase();break;case"array":G="array";break;case"object":G="object";break;default:G="string"}Z[K]={type:G,description:q.description},X.push(K)}let Y={type:"object",properties:Z,required:X,additionalProperties:!1};return{name:J.name,description:J.description,inputSchema:Y,source:{toolbox:Q}}}function OL0(J){let Q=[];function Z(X,Y){if(Y===null||Y===void 0)Q.push(`${X}: ${String(Y)}`);else if(typeof Y==="boolean")Q.push(`${X}: ${Y?"true":"false"}`);else if(typeof Y==="number"||typeof Y==="string")Q.push(`${X}: ${String(Y)}`);else if(Array.isArray(Y))for(let K=0;K<Y.length;K++)Z(`${X}_${K}`,Y[K]);else if(typeof Y==="object")for(let[K,q]of Object.entries(Y))Z(`${X}_${K}`,q);else Q.push(`${X}: ${String(Y)}`)}for(let[X,Y]of Object.entries(J))Z(X,Y);return Q.join(`
4519
4519
  `)+`
@@ -5421,8 +5421,8 @@ Command:
5421
5421
 
5422
5422
  ${Te8("\t",$??"(unknown)")}
5423
5423
 
5424
- `)}else process.stderr.write(`Error: The ${O.name} tool is not allowed to run in execute mode. Rerun with --dangerously-allow-all to bypass.`);await N()}}}),A=Y.threadService.observe(Q).subscribe(async(w)=>{if(M=w.v,g46(w.messages)>U){let O=R5(w,"assistant");if(O&&IC(O)){let $=a5(O.content);if(G){let j=O.usage,E={result:$,usage:{input_tokens:j?.inputTokens||0,output_tokens:j?.outputTokens||0,cache_creation_input_tokens:j?.cacheCreationInputTokens||0,cache_read_input_tokens:j?.cacheReadInputTokens||0,credits:j?.credits||0}};process.stdout.write(JSON.stringify(E)+`
5425
- `)}else process.stdout.write($+`
5424
+ `)}else process.stderr.write(`Error: The ${O.name} tool is not allowed to run in execute mode. Rerun with --dangerously-allow-all to bypass.`);await N()}}}),A=Y.threadService.observe(Q).subscribe(async(w)=>{if(M=w.v,g46(w.messages)>U){let O=R5(w,"assistant");if(O&&IC(O)){let $=a5(O.content).trim();if(G){let j=O.usage,E={result:$,usage:{input_tokens:j?.inputTokens||0,output_tokens:j?.outputTokens||0,cache_creation_input_tokens:j?.cacheCreationInputTokens||0,cache_read_input_tokens:j?.cacheReadInputTokens||0,credits:j?.credits||0}};process.stdout.write(JSON.stringify(E)+`
5425
+ `)}else if($)process.stdout.write($+`
5426
5426
  `);await N()}}})})}function g46(J){return J.filter((Q)=>Q.role==="assistant"&&Q.state.type!=="streaming").length}function Pe8(J){if(WT(J))return"Unauthorized. Check your API key.";else if(UT(J))return"Context window limit reached.";else if(FT(J))return"Model provider overloaded. Try again in a few seconds.";else if(zT(J))return"Insufficient credit balance.";else return J.message}function Te8(J,Q){if(!Q)return Q;return J+Q.split(`
5427
5427
  `).join(`
5428
5428
  `+J)}F0();uV();import{mkdir as u46,open as Ce8,readFile as p46,unlink as d46,writeFile as Kx1}from"node:fs/promises";import{homedir as Se8}from"node:os";import Mm from"node:path";var ve8=Mm.join(xH||Mm.join(Se8(),".local/share"),"amp"),ke8=Mm.join(ve8,"history.jsonl"),_e8=1000;class qx1{history=[];index=-1;loaded=!1;historyFile;maxSize;constructor(J){this.historyFile=J?.historyFile||ke8,this.maxSize=J?.maxSize||_e8,this.ensureLoaded()}async ensureLoaded(){if(!this.loaded)await this.cleanupStaleLockFile(),this.history=await this.readHistoryFromDisk(),this.loaded=!0}async cleanupStaleLockFile(){let J=this.historyFile+".lock";try{await d46(J),l.info("Cleaned up stale lock file",{lockFile:J})}catch(Q){if(Q.code!=="ENOENT")l.warn("Failed to clean up stale lock file",{lockFile:J,error:Q.message})}}async readHistoryFromDisk(){try{let J=await p46(this.historyFile,"utf-8");if(!J.trim())return[];return this.parseJsonlContent(J)}catch(J){if(J.code!=="ENOENT")return l.warn("Failed to read history file",{error:J.message}),[];if(this.historyFile.endsWith(".jsonl")){let Q=this.historyFile.replace(".jsonl",".json");try{let Z=await p46(Q,"utf-8");if(Z.trim()){let X=JSON.parse(Z);l.info("Migrating from old history.json to history.jsonl",{oldFile:Q,newFile:this.historyFile,size:X.length}),await this.writeHistoryToDisk(X);try{await import("node:fs/promises").then((Y)=>Y.unlink(Q))}catch{}return X}}catch{}}return[]}}parseJsonlContent(J){let Q=J.trim().split(`
@@ -5804,7 +5804,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||nw}function E56(J,Q){let
5804
5804
  `);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let q=K.optsWithGlobals(),G=await Q(K,q),z=0;await G.mcpService.initialized;let U=K.args.slice(1),W;if(j56()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await R56({toolName:X,rawArgs:U,stdinInput:W,only:Y.only,threadDeps:G,stdout:process.stdout,stderr:process.stderr,exit:(F)=>{z=F}}),await G.asyncDispose(),G.cleanupTerminal(),process.exit(z)})}F0();r$();j2();import{homedir as QQ9}from"node:os";import Ou from"node:path";fj();u4();ON();E2();j3();s6();k0();function I56(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}F0();ON();import R69 from"node:fs";import P56 from"node:path";function T56(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!P56.isAbsolute(Q))return null;return l.debug("Extracted image path",{original:J,extracted:Q}),Q}function C56(J){try{let Q=P56.extname(J).toLowerCase(),Z=gs1(Q);if(!Z)return l.warn("Unsupported image file extension",{ext:Q}),null;try{let X=R69.readFileSync(J);return O69(X,Z)}catch(X){l.error(`Failed to read image file ${J}:`,X)}}catch(Q){l.error("Error handling image file path",{imagePath:J,error:Q})}return null}function O69(J,Q){if(J.length>GO)return l.warn(`Image file too large: ${J.length} bytes (max: ${GO})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as l56}from"node:child_process";import{rmdir as z89}from"node:fs/promises";import{tmpdir as U89}from"node:os";import i56 from"node:path";KO();F0();import{spawn as j69}from"node:child_process";import{promises as $69}from"node:fs";function S56(J){return J.kind==="executable"}function v56(J){return J.kind==="markdown"}var BH=50000,k56=300000;async function yx1(J,Q,Z,X={}){let{timeoutMs:Y=k56,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(l.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),v56(q))return await E69(q,Q);else if(S56(q))return await I69(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return l.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function E69(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await $69.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>BH?Z.slice(0,BH)+`
5805
5805
  ... (output truncated at ${BH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function I69(J,Q,Z=k56,X){return new Promise((Y)=>{let[K,q]=P69(J,Q);l.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=bs1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),l.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=j69(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=BH)F.push(V);else{let N=BH-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=BH)H.push(V);else{let N=BH-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
5806
5806
  ${L}`:L;if(B>BH)A+=`
5807
- ... (output truncated at ${BH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function P69(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return C69(Z,X?[...X]:null,Y,Q);else return T69(Z,X?[...X]:null,Y,Q)}function T69(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function C69(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}F0();r$();j2();fj();u4();rV();aK();iB();s6();k0();import{mkdtemp as W89,readFile as F89,unlink as H89,writeFile as KU2}from"fs/promises";var S41={};L6(S41,{scrollUp:()=>r69,scrollDown:()=>s69,link:()=>Z89,image:()=>X89,iTerm:()=>Y89,exitAlternativeScreen:()=>J89,eraseUp:()=>n69,eraseStartLine:()=>i69,eraseScreen:()=>fx1,eraseLines:()=>c69,eraseLine:()=>y56,eraseEndLine:()=>l69,eraseDown:()=>a69,enterAlternativeScreen:()=>e69,cursorUp:()=>x56,cursorTo:()=>k69,cursorShow:()=>d69,cursorSavePosition:()=>f69,cursorRestorePosition:()=>h69,cursorPrevLine:()=>u69,cursorNextLine:()=>m69,cursorMove:()=>_69,cursorLeft:()=>b56,cursorHide:()=>p69,cursorGetPosition:()=>g69,cursorForward:()=>b69,cursorDown:()=>x69,cursorBackward:()=>y69,clearTerminal:()=>t69,clearScreen:()=>o69,beep:()=>Q89});import hx1 from"node:process";var C41=globalThis.window?.document!==void 0,Fz2=globalThis.process?.versions?.node!==void 0,Hz2=globalThis.process?.versions?.bun!==void 0,Bz2=globalThis.Deno?.version?.deno!==void 0,Dz2=globalThis.process?.versions?.electron!==void 0,Mz2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,Vz2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,Nz2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,Lz2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,Az2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Tm=globalThis.navigator?.userAgentData?.platform,wz2=Tm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",Rz2=Tm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",Oz2=Tm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",jz2=Tm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),$z2=Tm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var z2="\x1B[",Sm="\x1B]",jT="\x07",Cm=";",_56=!C41&&hx1.env.TERM_PROGRAM==="Apple_Terminal",S69=!C41&&hx1.platform==="win32",v69=C41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:hx1.cwd,k69=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return z2+(J+1)+"G";return z2+(Q+1)+Cm+(J+1)+"H"},_69=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=z2+-J+"D";else if(J>0)Z+=z2+J+"C";if(Q<0)Z+=z2+-Q+"A";else if(Q>0)Z+=z2+Q+"B";return Z},x56=(J=1)=>z2+J+"A",x69=(J=1)=>z2+J+"B",b69=(J=1)=>z2+J+"C",y69=(J=1)=>z2+J+"D",b56=z2+"G",f69=_56?"\x1B7":z2+"s",h69=_56?"\x1B8":z2+"u",g69=z2+"6n",m69=z2+"E",u69=z2+"F",p69=z2+"?25l",d69=z2+"?25h",c69=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=y56+(Z<J-1?x56():"");if(J)Q+=b56;return Q},l69=z2+"K",i69=z2+"1K",y56=z2+"2K",a69=z2+"J",n69=z2+"1J",fx1=z2+"2J",r69=z2+"S",s69=z2+"T",o69="\x1Bc",t69=S69?`${fx1}${z2}0f`:`${fx1}${z2}3J${z2}H`,e69=z2+"?1049h",J89=z2+"?1049l",Q89=jT,Z89=(J,Q)=>[Sm,"8",Cm,Cm,Q,jT,J,Sm,"8",Cm,Cm,jT].join(""),X89=(J,Q={})=>{let Z=`${Sm}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+jT},Y89={setCwd:(J=v69())=>`${Sm}50;CurrentDir=${J}${jT}`,annotation(J,Q={}){let Z=`${Sm}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+jT}};var v41=r6(d56(),1);function UV(J,Q,{target:Z="stdout",...X}={}){if(!v41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return S41.link(J,Q)}UV.isSupported=v41.default.stdout;UV.stderr=(J,Q,Z={})=>UV(J,Q,{target:"stderr",...Z});UV.stderr.isSupported=v41.default.stderr;F0();aK();class dx1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;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(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1759896092-gd52d93"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await be1(Q)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}F0();class k41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class YQ{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function c56(J){if(J instanceof k41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof YQ)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var WV=null,B89={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(WV)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (Xx1(),I46)),q=await K({worker:J.worker},{clientId:J.clientId,onUserDisconnect:()=>{WV=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});return WV=q,q.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((G)=>{WV=null,Z.sendStatus({connected:!1,errorMessage:G.message})}),new YQ(`Started connecting to Amp web interface
5807
+ ... (output truncated at ${BH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function P69(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return C69(Z,X?[...X]:null,Y,Q);else return T69(Z,X?[...X]:null,Y,Q)}function T69(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function C69(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}F0();r$();j2();fj();u4();rV();aK();iB();s6();k0();import{mkdtemp as W89,readFile as F89,unlink as H89,writeFile as KU2}from"fs/promises";var S41={};L6(S41,{scrollUp:()=>r69,scrollDown:()=>s69,link:()=>Z89,image:()=>X89,iTerm:()=>Y89,exitAlternativeScreen:()=>J89,eraseUp:()=>n69,eraseStartLine:()=>i69,eraseScreen:()=>fx1,eraseLines:()=>c69,eraseLine:()=>y56,eraseEndLine:()=>l69,eraseDown:()=>a69,enterAlternativeScreen:()=>e69,cursorUp:()=>x56,cursorTo:()=>k69,cursorShow:()=>d69,cursorSavePosition:()=>f69,cursorRestorePosition:()=>h69,cursorPrevLine:()=>u69,cursorNextLine:()=>m69,cursorMove:()=>_69,cursorLeft:()=>b56,cursorHide:()=>p69,cursorGetPosition:()=>g69,cursorForward:()=>b69,cursorDown:()=>x69,cursorBackward:()=>y69,clearTerminal:()=>t69,clearScreen:()=>o69,beep:()=>Q89});import hx1 from"node:process";var C41=globalThis.window?.document!==void 0,Fz2=globalThis.process?.versions?.node!==void 0,Hz2=globalThis.process?.versions?.bun!==void 0,Bz2=globalThis.Deno?.version?.deno!==void 0,Dz2=globalThis.process?.versions?.electron!==void 0,Mz2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,Vz2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,Nz2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,Lz2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,Az2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Tm=globalThis.navigator?.userAgentData?.platform,wz2=Tm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",Rz2=Tm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",Oz2=Tm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",jz2=Tm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),$z2=Tm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var z2="\x1B[",Sm="\x1B]",jT="\x07",Cm=";",_56=!C41&&hx1.env.TERM_PROGRAM==="Apple_Terminal",S69=!C41&&hx1.platform==="win32",v69=C41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:hx1.cwd,k69=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return z2+(J+1)+"G";return z2+(Q+1)+Cm+(J+1)+"H"},_69=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=z2+-J+"D";else if(J>0)Z+=z2+J+"C";if(Q<0)Z+=z2+-Q+"A";else if(Q>0)Z+=z2+Q+"B";return Z},x56=(J=1)=>z2+J+"A",x69=(J=1)=>z2+J+"B",b69=(J=1)=>z2+J+"C",y69=(J=1)=>z2+J+"D",b56=z2+"G",f69=_56?"\x1B7":z2+"s",h69=_56?"\x1B8":z2+"u",g69=z2+"6n",m69=z2+"E",u69=z2+"F",p69=z2+"?25l",d69=z2+"?25h",c69=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=y56+(Z<J-1?x56():"");if(J)Q+=b56;return Q},l69=z2+"K",i69=z2+"1K",y56=z2+"2K",a69=z2+"J",n69=z2+"1J",fx1=z2+"2J",r69=z2+"S",s69=z2+"T",o69="\x1Bc",t69=S69?`${fx1}${z2}0f`:`${fx1}${z2}3J${z2}H`,e69=z2+"?1049h",J89=z2+"?1049l",Q89=jT,Z89=(J,Q)=>[Sm,"8",Cm,Cm,Q,jT,J,Sm,"8",Cm,Cm,jT].join(""),X89=(J,Q={})=>{let Z=`${Sm}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+jT},Y89={setCwd:(J=v69())=>`${Sm}50;CurrentDir=${J}${jT}`,annotation(J,Q={}){let Z=`${Sm}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+jT}};var v41=r6(d56(),1);function UV(J,Q,{target:Z="stdout",...X}={}){if(!v41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return S41.link(J,Q)}UV.isSupported=v41.default.stdout;UV.stderr=(J,Q,Z={})=>UV(J,Q,{target:"stderr",...Z});UV.stderr.isSupported=v41.default.stderr;F0();aK();class dx1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;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(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1759910516-g30f449"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await be1(Q)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}F0();class k41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class YQ{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function c56(J){if(J instanceof k41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof YQ)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var WV=null,B89={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(WV)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (Xx1(),I46)),q=await K({worker:J.worker},{clientId:J.clientId,onUserDisconnect:()=>{WV=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});return WV=q,q.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((G)=>{WV=null,Z.sendStatus({connected:!1,errorMessage:G.message})}),new YQ(`Started connecting to Amp web interface
5808
5808
  Client ID: ${Y}
5809
5809
  You can now send messages from the web interface to this thread`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!WV)return new YQ("Not connected to Amp web interface");try{WV.disconnect();let Z=WV.clientID;return WV=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new YQ(`Disconnected from Amp web interface
5810
5810
  Client ID: ${Z}
@@ -5994,7 +5994,7 @@ ${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTr
5994
5994
  `),J.stdout.write(`Thread: ${H}
5995
5995
  `),J.stdout.write(`Continue this thread with: amp threads continue ${W}
5996
5996
  `)}}function _Y6(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return x1.index(Z[X])}Fb1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){t2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
5997
- `)}var Mh1=Dh1.join(lu1||Dh1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function GQ9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function IV(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")_U("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new A2("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${Q8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")_U("experimental.agentMode",Q.agentMode)}var zQ9=w0.union([w0.object({command:w0.string(),args:w0.array(w0.string()).optional(),env:w0.record(w0.string(),w0.string()).optional()}).strict(),w0.object({url:w0.string()}).strict()]),UQ9=w0.record(w0.string(),zQ9);async function Nh1(J){try{await YQ9(Dh1.dirname(Mh1),{recursive:!0}),await KQ9(Mh1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function WQ9(){try{return(await mY6(Mh1,"utf-8")).trim()}catch(J){return null}}async function FQ9(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return UQ9.parse(Q)}catch(Z){if(Z instanceof w0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function HQ9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var fY6=[{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)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??B5,description:`Custom settings file path (overrides the default location ${B5})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${i_1})`},{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:WG(),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:Ex1(),hidden:!0,description:(J)=>J?"Enable IDE connection. 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:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:YN}],hY6=(J)=>("deprecated"in J)&&J.deprecated===!0,BQ9=(J)=>("hidden"in J)&&J.hidden===!0,DQ9=(J)=>("default"in J),MQ9=(J)=>("default"in J)?J.default:void 0;function VQ9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new A2($K.unknownCommand(Z),1,q)}}var uY6=null;function Ny2(){return uY6}function q51(J){return{...J,getThreadEnvironment:e21,vfs:ke1({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new hv(J.fileSystem),generateThreadTitle:LY0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Lh1=x0.file(qQ9.homedir()),pY6=process.env.XDG_CONFIG_HOME?x0.file(process.env.XDG_CONFIG_HOME):p0.joinPath(Lh1,".config");async function PV(J,Q){sd1("0.0.1759896092-gd52d93");let Z=zQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([x0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:l_1,homeDir:Lh1,userConfigDir:pY6}),X=await Z9();l.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=_l(AR()),K=Ke1({configService:Z,toolService:Y}),q=IL0(Y,b9,Ut).catch((N)=>{l.warn("Toolbox registration failed, continuing anyway:",N)}),G=K.initialized.catch((N)=>{l.warn("MCP service initialization failed, continuing anyway:",N)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)od1(!0);if(Q.ide&&Ex1())td1(!0);if(E06(Y),Q.jetbrains||Q.ide)Y.registerTool(Tn);let z;if(!J.executeMode)z=new B41(process.cwd(),{},!0);else z=new class extends B41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(p2.write(`No API key found. Starting login flow...
5997
+ `)}var Mh1=Dh1.join(lu1||Dh1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function GQ9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function IV(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")_U("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new A2("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${Q8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")_U("experimental.agentMode",Q.agentMode)}var zQ9=w0.union([w0.object({command:w0.string(),args:w0.array(w0.string()).optional(),env:w0.record(w0.string(),w0.string()).optional()}).strict(),w0.object({url:w0.string()}).strict()]),UQ9=w0.record(w0.string(),zQ9);async function Nh1(J){try{await YQ9(Dh1.dirname(Mh1),{recursive:!0}),await KQ9(Mh1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function WQ9(){try{return(await mY6(Mh1,"utf-8")).trim()}catch(J){return null}}async function FQ9(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return UQ9.parse(Q)}catch(Z){if(Z instanceof w0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function HQ9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var fY6=[{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)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??B5,description:`Custom settings file path (overrides the default location ${B5})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${i_1})`},{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:WG(),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:Ex1(),hidden:!0,description:(J)=>J?"Enable IDE connection. 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:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:YN}],hY6=(J)=>("deprecated"in J)&&J.deprecated===!0,BQ9=(J)=>("hidden"in J)&&J.hidden===!0,DQ9=(J)=>("default"in J),MQ9=(J)=>("default"in J)?J.default:void 0;function VQ9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new A2($K.unknownCommand(Z),1,q)}}var uY6=null;function Ny2(){return uY6}function q51(J){return{...J,getThreadEnvironment:e21,vfs:ke1({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new hv(J.fileSystem),generateThreadTitle:LY0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Lh1=x0.file(qQ9.homedir()),pY6=process.env.XDG_CONFIG_HOME?x0.file(process.env.XDG_CONFIG_HOME):p0.joinPath(Lh1,".config");async function PV(J,Q){sd1("0.0.1759910516-g30f449");let Z=zQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([x0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:l_1,homeDir:Lh1,userConfigDir:pY6}),X=await Z9();l.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=_l(AR()),K=Ke1({configService:Z,toolService:Y}),q=IL0(Y,b9,Ut).catch((N)=>{l.warn("Toolbox registration failed, continuing anyway:",N)}),G=K.initialized.catch((N)=>{l.warn("MCP service initialization failed, continuing anyway:",N)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)od1(!0);if(Q.ide&&Ex1())td1(!0);if(E06(Y),Q.jetbrains||Q.ide)Y.registerTool(Tn);let z;if(!J.executeMode)z=new B41(process.cwd(),{},!0);else z=new class extends B41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(p2.write(`No API key found. Starting login flow...
5998
5998
  `),!await NQ9(J))await Ww(),process.exit(1)}let U=await me1({isDevelopment:!1}),W=new AU1(U),F=new NU1(U,{lazy:!0}),H=Q.notifications!==void 0?Q.notifications:!J.executeMode,B=P06({playNotificationSound:async(N)=>{if(H){I06(N);let L=Ub1(),A=Wb1();if((!L||A)&&X.settings["notifications.system.enabled"]!==!1){if(N==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(N==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:W});l.info("Starting Amp background services");let M=ne1({threadService:W,threadHistoryService:F,isExtensionDevelopment:!1}),V={configService:Z,toolService:Y,mcpService:K,threadService:W,threadHistoryService:F,threadSyncService:M,threadStorage:U,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:z,notificationService:B,fileSystem:Q.jetbrains||Q.ide?Ce1:b9};return{...V,async asyncDispose(){await V.mcpService.dispose(),await V.threadService.asyncDispose(),V.configService.unsubscribe(),V.toolService.dispose(),V.fuzzyServer.dispose(),V.threadSyncService.dispose(),V.settingsStorage[Symbol.dispose]()}}}async function NQ9(J){if(!J.executeMode){if(!await kx1("Would you like to log in to Amp? [(y)es, (n)o]: "))return p2.write(`Login cancelled. Run the command again to retry.
5999
5999
  `),!1}return await dY6(J)}async function dY6(J){let Q=XQ9(32).toString("hex"),Z=await vx1(J.ampURL,Q);try{await jU(Z)}catch(Y){l.error("Failed to open browser",{error:Y})}let X=await vx1(J.ampURL,Q,!1);p2.write(`If your browser did not open automatically, visit:
6000
6000
 
@@ -6004,12 +6004,12 @@ ${Q8.blue.bold(X)}
6004
6004
  Login successful! You can now use the Amp CLI.
6005
6005
  `),!0}catch(Y){return l.error("Login failed",{error:Y}),t2.write(`
6006
6006
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6007
- `),!1}}function LQ9(){let J=new hg().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)Hw(),process.exit(0);let H=F.originalError??F;C46(H)}),J.option("-V, --version","output the version number",()=>{p2.write(`0.0.1759896092-gd52d93 (released 2025-10-08T04:06:25.057Z)
6008
- `),process.exit(0)}),J.addHelpText("after",C76()),J.configureHelp({formatHelp:S76}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await OQ9(M)}),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(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await RQ9(M,await Ax1(B,M.settings))});let Q=async(F,H,B)=>{zQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:J0.of([x0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Lh1,userConfigDir:pY6});let M={...H,executeMode:!1};await Vh1(M,{...F,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await gY6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await CQ9(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);if(H.pick)await Q(M,V,B);else await TQ9(M,V,F,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await PQ9(M,V,F,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await gY6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await IQ9(M,V,F,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await EQ9(M,V,F,B)}),E56(J,async(F,H)=>{let B=await QY(H);IV(F,H);let M=await PV(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:Hw,asyncDispose:M.asyncDispose.bind(M)}}),Q56(J),n76(J,async(F)=>{return(await QY(F)).settings}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);IV(H,B);let V=await PV(M,B);try{await Zx1(V,{})}finally{await V.asyncDispose(),await Hw()}});let X=new hg().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(F)=>{await Px1(F.force||!1,F.verbose||!1,"0.0.1759896092-gd52d93"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,B){let V=typeof F.description==="string"?F.description:B===void 0?F.description(!0):F.description(B),N=new sM(H,V),L=MQ9(F);if(L)N.default(L);if(N.hidden=BQ9(F)||hY6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of fY6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new sM("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new sM("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new sM("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1).hideHelp(!0);J.addOption(q);let G=new sM("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1).hideHelp(!0);J.addOption(G);let z=new sM("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let F=new sM("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(F)}J.action(async(F,H)=>{let B=F,M=await QY(B);if(Object.keys(B).forEach((V)=>{let N=fY6.find((L)=>L.name===V);if(N&&hY6(N)&&!DQ9(N))t2.write(Q8.yellow(`Warning: '--${V}' flag is deprecated
6007
+ `),!1}}function LQ9(){let J=new hg().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)Hw(),process.exit(0);let H=F.originalError??F;C46(H)}),J.option("-V, --version","output the version number",()=>{p2.write(`0.0.1759910516-g30f449 (released 2025-10-08T08:07:22.504Z)
6008
+ `),process.exit(0)}),J.addHelpText("after",C76()),J.configureHelp({formatHelp:S76}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await OQ9(M)}),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(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await RQ9(M,await Ax1(B,M.settings))});let Q=async(F,H,B)=>{zQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:J0.of([x0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Lh1,userConfigDir:pY6});let M={...H,executeMode:!1};await Vh1(M,{...F,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await gY6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await CQ9(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);if(H.pick)await Q(M,V,B);else await TQ9(M,V,F,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await PQ9(M,V,F,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await gY6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await IQ9(M,V,F,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await EQ9(M,V,F,B)}),E56(J,async(F,H)=>{let B=await QY(H);IV(F,H);let M=await PV(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:Hw,asyncDispose:M.asyncDispose.bind(M)}}),Q56(J),n76(J,async(F)=>{return(await QY(F)).settings}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);IV(H,B);let V=await PV(M,B);try{await Zx1(V,{})}finally{await V.asyncDispose(),await Hw()}});let X=new hg().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(F)=>{await Px1(F.force||!1,F.verbose||!1,"0.0.1759910516-g30f449"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,B){let V=typeof F.description==="string"?F.description:B===void 0?F.description(!0):F.description(B),N=new sM(H,V),L=MQ9(F);if(L)N.default(L);if(N.hidden=BQ9(F)||hY6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of fY6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new sM("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new sM("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new sM("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1).hideHelp(!0);J.addOption(q);let G=new sM("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1).hideHelp(!0);J.addOption(G);let z=new sM("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let F=new sM("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(F)}J.action(async(F,H)=>{let B=F,M=await QY(B);if(Object.keys(B).forEach((V)=>{let N=fY6.find((L)=>L.name===V);if(N&&hY6(N)&&!DQ9(N))t2.write(Q8.yellow(`Warning: '--${V}' flag is deprecated
6009
6009
  `))}),H.args.length>0)VQ9(M,H);await Vh1(M,B,H)});let U=new hg("doctor").summary("Generate support bundle").description("Generate a support bundle for troubleshooting issues. This collects logs, configuration, and system information into a file that can be shared with Amp support for debugging.").option("--output-dir <path>","Directory to save the support bundle",process.cwd()).option("--include-full-logs","Include full log history",!1).allowUnknownOption(!1).action(async(F)=>{await $Q9(F.outputDir,F.includeFullLogs)});J.addCommand(U);let W=new hg("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("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(F)=>{await jQ9(F.version)});return J.addCommand(W),J}async function K51(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??hK(),K=q51(J);if(Z)await J.threadStorage.set(Y,Z);let q=await _J.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,$41(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(R5(z,"assistant"))await Nh1(Y),G.unsubscribe()});return await q.resume(),q}async function Vh1(J,Q,Z){let X=j41(Q);if(X instanceof Error)tZ(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let w=(await _x1()).trimEnd();if(w)K=w}else Y=(await _x1()).trimEnd();if(Q.remote&&!J.executeMode)throw new A2("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new A2("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new A2("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new A2("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new A2("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new A2("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(J.executeMode&&Y===""&&!Q.streamJsonInput)throw new A2("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"
6010
6010
  Or pipe via stdin: echo "your message" | amp --execute`);IV(Z,Q);let q=await PV(J,Q);uY6=q;let G=q51(q),z=async(w)=>{let R=await mY6(w,"utf-8"),O=JSON.parse(R);if(!hU(O.id))throw new A2($K.invalidThreadId);return K51(q,{visibility:X,thread:O})},U=async(w)=>{if(!hU(w))throw new A2($K.invalidThreadId);let R=await q.threadService.get(w)??void 0;return K51(q,{visibility:X,thread:R})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return K51(q,{visibility:X})}catch(w){if(w instanceof A2)throw w;throw await K41(w,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return K51(q,{visibility:X})};if(Q.format==="jsonl")t2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6011
- `),await Ww(),process.exit(1);if(J.executeMode&&Q.remote)await Z56(Y,K),await q.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await m46(H,H.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await wi1();let w=await fR({jetbrainsOnly:Q.jetbrains});if(w.length===0)if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall");else j5.sendStatus({enabled:!0,connected:!1,authenticated:!1});else if(w.length===1){let R=w[0];if(R)j5.selectConfig(R)}else B=!0}let V=Cx1("0.0.1759896092-gd52d93",q.settingsStorage),N=J0.of([x0.file(process.cwd())]),L=tT(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A=await Z9();await yY6({stdout:process.stdout,history:new qx1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:PJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:j5,connectedClientsService:new $p,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,debugWidgetTree:Q.debugWidgetTree,jetbrainsMode:Q.jetbrains,clientId:Q.clientId}),await q.asyncDispose(),process.exit(0)}async function QY(J){if(J.interactive)t2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6012
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=await wU(J.settingsFile),K=RU({...J,settingsFile:Y,getHook:process.env.AMP_URL?(z,U)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return U()}:void 0});if(await Y56(K),await K56(K),J.mcpConfig){let z=await FQ9(J.mcpConfig);K=HQ9(K,z)}let q=await K.get("url","global");if(!q)q=tQ;if(!yH(q))l.info("Targeting custom Amp server",{ampURL:q});if(K=Bp1(K),await K.get("debug.httpLogging"))Wp1();return{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:q,settings:K,secrets:X56(await Ax1(J,K))}}function AQ9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function wQ9(){let J=AQ9(process.argv);if(F46({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),GQ9(l),l.info("Starting Amp CLI.",{version:"0.0.1759896092-gd52d93",buildTimestamp:"2025-10-08T04:06:25.057Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new A2($K.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await LQ9().parseAsync(process.argv)}wQ9().catch(K41);async function RQ9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),p2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6011
+ `),await Ww(),process.exit(1);if(J.executeMode&&Q.remote)await Z56(Y,K),await q.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await m46(H,H.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await wi1();let w=await fR({jetbrainsOnly:Q.jetbrains});if(w.length===0)if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall");else j5.sendStatus({enabled:!0,connected:!1,authenticated:!1});else if(w.length===1){let R=w[0];if(R)j5.selectConfig(R)}else B=!0}let V=Cx1("0.0.1759910516-g30f449",q.settingsStorage),N=J0.of([x0.file(process.cwd())]),L=tT(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A=await Z9();await yY6({stdout:process.stdout,history:new qx1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:PJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:j5,connectedClientsService:new $p,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,debugWidgetTree:Q.debugWidgetTree,jetbrainsMode:Q.jetbrains,clientId:Q.clientId}),await q.asyncDispose(),process.exit(0)}async function QY(J){if(J.interactive)t2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6012
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=await wU(J.settingsFile),K=RU({...J,settingsFile:Y,getHook:process.env.AMP_URL?(z,U)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return U()}:void 0});if(await Y56(K),await K56(K),J.mcpConfig){let z=await FQ9(J.mcpConfig);K=HQ9(K,z)}let q=await K.get("url","global");if(!q)q=tQ;if(!yH(q))l.info("Targeting custom Amp server",{ampURL:q});if(K=Bp1(K),await K.get("debug.httpLogging"))Wp1();return{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:q,settings:K,secrets:X56(await Ax1(J,K))}}function AQ9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function wQ9(){let J=AQ9(process.argv);if(F46({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),GQ9(l),l.info("Starting Amp CLI.",{version:"0.0.1759910516-g30f449",buildTimestamp:"2025-10-08T08:07:22.504Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new A2($K.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await LQ9().parseAsync(process.argv)}wQ9().catch(K41);async function RQ9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),p2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6013
6013
  `);else if(!yH(J.ampURL))p2.write(`Logging in to ${new URL(J.ampURL).hostname}
6014
6014
  `);let Z=process.env.AMP_API_KEY;if(Z)p2.write(`API key found in environment variable, storing...
6015
6015
  `),await Q.set("apiKey",Z,J.ampURL),p2.write(`API key successfully stored.
@@ -6025,7 +6025,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);IV(Z,Q);let q=await PV(
6025
6025
  `));try{let Q;if(J)Q=J,t2.write(Q8.blue(`Updating to version ${J}...
6026
6026
  `)),await AT(J),t2.write(Q8.green(`✓ Successfully updated to version ${J}
6027
6027
  `));else{t2.write(Q8.blue(`Checking for updates...
6028
- `));let{hasUpdate:X,latestVersion:Y}=await PO("0.0.1759896092-gd52d93");if(!X)t2.write(Q8.green(`✓ Amp CLI is already up to date.
6028
+ `));let{hasUpdate:X,latestVersion:Y}=await PO("0.0.1759910516-g30f449");if(!X)t2.write(Q8.green(`✓ Amp CLI is already up to date.
6029
6029
  `)),process.exit(0);if(!Y)t2.write(Q8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,t2.write(Q8.blue(`Updating to version ${Y}...
6030
6030
  `)),await AT(Y),t2.write(Q8.green(`✓ Successfully updated to version ${Y}
6031
6031
  `))}let Z=await Vw(Q);if(Z.warning)t2.write(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1759896092-gd52d93",
3
+ "version": "0.0.1759910516-g30f449",
4
4
  "description": "CLI for Amp, an agentic coding tool in research preview from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {