@sourcegraph/amp 0.0.1759132892-gf2cb87 → 0.0.1759147319-g41306c

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 +8 -8
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -138,7 +138,7 @@ ${gw6(Q.progress)}
138
138
  ${F}`)}let U=`${J}.${process.pid}.${Date.now()}.tmp`;try{await aI6(pl.dirname(J),{recursive:!0});let F=iI6(U),W=tI6.fromWeb(z.body);await eI6(W,F);let H=await ZE6(U);if(H!==G)throw Error(`ripgrep checksum validation failed: expected ${G}, got ${H}`);if(process.platform!=="win32")await nI6(U,493);try{await sI6(U,J)}catch(D){if(D instanceof Error&&"code"in D&&D.code==="EEXIST")return;throw D}}finally{await oI6(U).catch(()=>{})}}async function ZE6(J){let Q=lI6("sha256"),Z=await rI6(J);return Q.update(Z),Q.digest("hex")}function XE6(){let J=process.env.npm_config_arch||jU1.arch();switch(jU1.platform()){case"darwin":return J==="arm64"?"aarch64-apple-darwin":"x86_64-apple-darwin";case"win32":return J==="x64"?"x86_64-pc-windows-msvc":J==="arm64"?"aarch64-pc-windows-msvc":"i686-pc-windows-msvc";case"linux":return J==="x64"?"x86_64-unknown-linux-musl":J==="arm"?"arm-unknown-linux-gnueabihf":J==="armv7l"?"arm-unknown-linux-gnueabihf":J==="arm64"?"aarch64-unknown-linux-musl":J==="ppc64"?"powerpc64le-unknown-linux-gnu":J==="riscv64"?"riscv64gc-unknown-linux-gnu":J==="s390x"?"s390x-unknown-linux-gnu":"i686-unknown-linux-musl";default:throw Error("Unknown platform: "+jU1.platform())}}async function YE6(){if(pv!==void 0)return pv;try{return pv=(await te1.promisify(cI6)("rg --version")).stdout.includes("ripgrep"),pv}catch{return pv=!1,!1}}var J10,pv;var cv=p(()=>{B0();V4();J10=oe1(async(J)=>{if(ee1(J))return J;let Q=3;for(let Z=1;Z<=Q;Z++)try{return await QE6(J),a.info("ripgrep binary downloaded successfully",{path:J}),J}catch(X){let Y=X instanceof Error?X.message:String(X);if(Z===Q){a.error("ripgrep download failed after all attempts",{error:Y});return}a.warn(`ripgrep download attempt ${Z}/${Q} failed: ${Y}`),await new Promise((K)=>setTimeout(K,500*Math.pow(2,Z-1)))}return})});var Y10={};N6(Y10,{ripgrepFiles:()=>dl,nodeGlobTool:()=>qE6,globFilesWithRipgrep:()=>X10});import{spawn as KE6}from"node:child_process";function X10(J,Q,Z){return J4(...J.map((X)=>GE6(X,Q,Z))).pipe(g0((X)=>{let Y=[];for(let G of X)if(G.status==="in-progress")Y.push(...G?.progress??[]);else if(G.status==="done")Y.push(...G.result);else if(G.status==="error")Y.push(...G.progress??[]);else if(G.status==="cancelled")Y.push(...G.progress??[]);let K=X.filter((G)=>G.status==="error");if(K.length>0)return{status:"error",progress:Y,error:{message:K.map((G)=>G?.error?.message??"").join(`
139
139
  `)}};return{status:X.every((G)=>G.status==="done")?"done":X.some((G)=>G.status==="cancelled")?"cancelled":"in-progress",progress:Y,result:Y}}))}function GE6(J,Q,Z){return new K0((X)=>{X.next({status:"in-progress",progress:[]}),dl(J,Q?{pattern:Q,caseInsensitive:!0}:null,Z??{}).then(({files:Y,remaining:K})=>{if(K>0)Y.push(`--- ${K} more files not shown ---`);X.next({status:"done",progress:Y,result:Y})}).catch((Y)=>{let K=Y instanceof Error?Y.message:String(Y);X.next({status:"error",progress:[],error:{message:K}})}).finally(()=>X.complete())})}async function dl(J,Q,Z){let X=Z.limit??wU1,Y=["--files","--color","never","--no-require-git","--hidden","--glob","!\\.git/","--glob","!\\.jj/"];if(Z.maxDepth!==void 0)Y.push("--max-depth",Z.maxDepth.toString());let K;if(Z.basePath)ac(Z.basePath),K=FF(Z.basePath)?Z.basePath:u0.joinPath(J,Z.basePath).fsPath;else K=J.fsPath;if(Y.push(K),Q?.pattern&&Q.pattern==="*")Q.pattern="**";let q=Q?.pattern?Z10.default(Q.pattern,{nocase:Q.caseInsensitive,dot:!0}):void 0,G=KE6(await dv(),Y,{stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",env:{...process.env,NONINTERACTIVE:"1",DEBIAN_FRONTEND:"noninteractive"}});return new Promise((z,U)=>{let F=[],W="",H="",D=Z.offset??0,M=!1,V=()=>{if(M)return;if(!H)return;let N=H.startsWith(K)?H.slice(K.length+1):H;if(q&&!q(N))return;let L=H;if(H="",D>0){D--;return}if(F.push(L),F.length>=wU1)a.warn("Glob limit reached. Returning partial results.",{glob:Q?.pattern,limit:wU1,dir:J}),G.kill(),M=!0,z({files:F,remaining:0,aborted:!0})};G.stdout?.on("data",(N)=>{for(let L of String(N)){if(L==="\r")continue;if(L===`
140
140
  `)V(),H="";else H+=L}}),G?.stderr?.on("data",(N)=>{W+=String(N)}),G.on("exit",(N)=>{if(N&&N>=2){U(Error(`ripgrep exited with code ${N}:
141
- ${W}`));return}V();let L=F.slice(0,X);z({files:L,remaining:F.length-L.length})})})}var Z10,qE6=({args:J},{dirs:Q})=>{if(Q.length===0)return new K0((X)=>{X.next({status:"error",error:{message:"No directory provided"}}),X.complete()});let Z={};if(J.limit!==void 0)Z.limit=J.limit;if(J.offset!==void 0)Z.offset=J.offset;return X10(Q,J.filePattern,Z)},wU1=500000;var IU1=p(()=>{K8();i0();Z10=u6(Cj(),1);B0();aS();cv();rG()});function wQ(J){return J instanceof YJ||J instanceof Error&&J.name==="FileNotExistError"||typeof J==="object"&&J!==null&&"code"in J&&typeof J.code==="string"&&["ENOENT","FileNotFound"].includes(J.code)}function K10(J){return typeof J==="object"&&J!==null&&"base"in J&&"pattern"in J&&typeof J.pattern==="string"}function q10(J){return{readFile:J.readFile,readBinaryFile:J.readBinaryFile,stat:J.stat,getMtime:J.getMtime,realpath:J.realpath,readdir:J.readdir,findFiles:J.findFiles,access:J.access,watch:J.watch}}function G10(J){return{...J,writeFile:()=>Promise.reject(Error("Write operations not implemented")),delete:()=>Promise.reject(Error("Write operations not implemented")),mkdirp:()=>Promise.reject(Error("Write operations not implemented")),rename:()=>Promise.reject(Error("Write operations not implemented")),isExclusiveWriterFor:()=>Promise.resolve(!1)}}function Jq(J){return"__isImmutableBaseFileSystem"in J&&J.__isImmutableBaseFileSystem===!0}async function lv(J,Q,Z){try{return await J.readFile(Q,Z)}catch(X){if(X instanceof YJ)return null;throw X}}async function iv(J,Q,Z){try{return await J.access(Q,Z),!0}catch(X){if(wQ(X))return!1;throw X}}var YJ;var hJ=p(()=>{YJ=class YJ extends Error{constructor(J){let Q=typeof J==="string"?J:J.toString();super(`File not found: ${Q}`);this.name="FileNotExistError"}}});import*as vX from"node:fs";import*as cl from"node:path";function zE6(J){if(!dH(J))throw Error(`Expected a file URI (got ${J.toString()})`)}function RF(J){return J!==null&&typeof J==="object"&&"code"in J&&J.code==="ENOENT"}async function UE6(J){if(J.scheme!=="file")throw Error("nodeRealpath only supports file URIs");try{return S0.file(await vX.promises.realpath(J.fsPath))}catch(Q){if(RF(Q))throw new YJ(J);throw Q}}var R8;var xN=p(()=>{K8();i0();B0();IU1();hJ();aS();R8={readFile:async(J,Q)=>{try{return await vX.promises.readFile(Y8(J).fsPath,{encoding:"utf8",signal:Q?.signal})}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},readBinaryFile:async(J,Q)=>{try{return await vX.promises.readFile(Y8(J).fsPath,{signal:Q?.signal})}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},getMtime:async(J,Q)=>{try{return(await vX.promises.stat(Y8(J).fsPath)).mtimeMs}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},stat:async(J,Q)=>{J=Y8(J);try{let Z=await vX.promises.stat(J.fsPath);return{name:cl.basename(J.fsPath),size:Z.size,isDirectory:Z.isDirectory()}}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},realpath:async(J,Q)=>{return UE6(Y8(J))},rename:async(J,Q)=>{try{await vX.promises.rename(Y8(J).fsPath,Y8(Q).fsPath)}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},writeFile:async(J,Q,Z)=>{await vX.promises.writeFile(Y8(J).fsPath,Q,{encoding:"utf-8",signal:Z?.signal,flush:!0})},delete:async(J,Q)=>{J=Y8(J);try{if(Q?.recursive)await vX.promises.rm(J.fsPath,{recursive:!0,force:!0});else await vX.promises.unlink(J.fsPath)}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},mkdirp:async(J)=>{await vX.promises.mkdir(Y8(J).fsPath,{recursive:!0})},readdir:async(J,Q)=>{J=Y8(J);try{return(await vX.promises.readdir(J.fsPath,{withFileTypes:!0})).map((X)=>({uri:S0.file(cl.join(J.fsPath,X.name)),isDirectory:X.isDirectory()}))}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},findFiles:async(J,Q)=>{try{return(await dl(J.base,{pattern:J.pattern,caseInsensitive:!0},{limit:Q?.maxResults,signal:Q?.signal})).files.map((X)=>FF(X)?S0.file(X):u0.joinPath(J.base,X))}catch(Z){return a.error(`Error finding files with pattern ${J.pattern}:`,Z instanceof Error?Z:Error(String(Z))),[]}},watch:()=>DY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{let Z=Y8(J);zE6(Z);try{await vX.promises.access(Z.fsPath)}catch(X){if(RF(X))throw new YJ(Z);throw X}}}});async function FE6(J,Q){let Z=Y8(J).fsPath;if(!Z.startsWith(process.cwd()))return;if(a.debug("ide-fs",{method:"readFile",path:Z}),await RQ.isConnected())try{let X=await RQ.sendRequest("readFile",{path:Z});if(X?.content)return Q(X.content);if(process.env.IDE_FS_NO_FALLBACK)throw Error(`Failed to readFile via IDE: ${X?.message??"unknown cause"}`);a.warn(`Failed to readFile via IDE: ${X?.message??"unknown cause"}`);return}catch(X){if(process.env.IDE_FS_NO_FALLBACK)throw X;a.warn("IDE readFile failed, falling back to Node.js filesystem",{path:Z,error:X});return}else return}async function WE6(J,Q){let Z=Y8(J).fsPath;if(!Z.startsWith(process.cwd()))return!1;if(a.debug("ide-fs",{method:"writeFile",path:Z}),await RQ.isConnected())try{let X=await RQ.sendRequest("editFile",{path:Y8(J).fsPath,fullContent:Q});if(!X?.success){if(process.env.IDE_FS_NO_FALLBACK)throw Error(`Failed to writeFile via IDE: ${X?.message??"unknown cause"}`);return a.warn(`Failed to writeFile via IDE: ${X?.message??"unknown cause"}`),!1}return!0}catch(X){if(process.env.IDE_FS_NO_FALLBACK)throw X;return a.warn("IDE writeFile failed, falling back to Node.js filesystem",{path:Z,error:X}),!1}else return!1}var z10;var U10=p(()=>{K8();i0();B0();ej();xN();z10={readFile:async(J,Q)=>{return await FE6(J,(Z)=>Z)??await R8.readFile(J,Q).finally(()=>{a.debug("ide-fs",{fallback:"readFile"})})},readBinaryFile:async(J,Q)=>{return a.debug("ide-fs",{fallback:"readBinaryFile"}),R8.readBinaryFile(J,Q)},getMtime:async(J,Q)=>{return R8.getMtime(J,Q)},stat:async(J,Q)=>{return R8.stat(J,Q)},realpath:async(J,Q)=>{return R8.realpath(J,Q)},rename:async(J,Q)=>{return R8.rename(J,Q)},writeFile:async(J,Q,Z)=>{if(await WE6(J,Q))return;return await R8.writeFile(J,Q,Z).finally(()=>{a.debug("ide-fs",{fallback:"writeFile"})})},delete:async(J,Q)=>{return R8.delete(J,Q)},mkdirp:async(J)=>{return R8.mkdirp(J)},readdir:async(J,Q)=>{return R8.readdir(J,Q)},findFiles:async(J,Q)=>{return R8.findFiles(J,Q)},watch:()=>DY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{return R8.access(J,Q)}}});function $U1(J){return"__isFileSystemWithMountedTrees"in J&&J.__isFileSystemWithMountedTrees===!0}function EU1(J,Q){Q=Y8(Q);let Z,X;for(let Y of J.trees){if(!Y.uri)continue;let K=MX(Y.uri);if(u0.hasPrefix(Q,K)){let q=u0.relativePath(K,Q);if(q===null)continue;if(X===void 0||q.length<X.length)X=q,Z=Y}}if(!Z||X===void 0)return null;return{tree:Z,filePath:X}}function BE6(J){return Array.isArray(J)}function DE6(J){let Q;if(J===void 0)Q=void 0;else if(BE6(J))Q=J;else Q=J?.env?.initial?.trees;return Q?.filter((Z)=>Z.uri!==void 0)??HE6}function F10(J,Q){for(let X of J.trees){if(!X.uri)continue;let Y=MX(X.uri);if(u0.hasPrefix(Q,Y))return{isImplied:!1,childMountPoints:[]}}let Z=[];for(let X of J.trees){if(!X.uri)continue;let Y=MX(X.uri);if(u0.hasPrefix(Y,Q))Z.push(Y)}return{isImplied:Z.length>0,childMountPoints:Z}}function nv(J){return{trees:DE6(J)}}function H10(J){let Q={...J.os,mountedTree:W10},Z=new Map;function X(q){if(!q.fs||q.fs==="os")return Q;if(!q.uri)throw Error("Tree URI is required");if(!q.repository)throw Error(`Tree with FS type ${q.fs} requires repository field`);let G={uri:q.uri,repository:q.repository,fs:q.fs},z=`${q.fs}:${JSON.stringify(q)}`,U=Z.get(z);if(!U){let F=J[q.fs];if(!F)throw Error(`No file system implementation found for: ${q.fs}`);U={...F(G),mountedTree:G},Z.set(z,U)}return U}function Y(q){return q.trees.some((G)=>G.fs&&G.fs!=="os")}function K(q,G){let z=q.trees.map((F)=>({mountPoint:F.uri,fs:X(F)}));function U(F){if(!Y(q))return G?{...G(Q),mountedTree:Q.mountedTree}:Q;let W=EU1(q,F)?.tree;if(!W)throw new YJ(F);let H=z.find((D)=>u0.equalURIs(D.mountPoint,W.uri))?.fs;if(!H)throw Error(`No file system found for URI: ${F}`);return G?{...G(H),mountedTree:H.mountedTree}:H}return{map(F){if(G)throw Error("Cannot use both prepare and prepare2");return K(q,F)},mapReader(F){if(G)throw Error("Cannot use both prepare and prepare2");let W=K(q,F);return{...q10(W),mountedFileSystemForURI:W.mountedFileSystemForURI,map:()=>{throw Error("not implemented")},mapReader:W.mapReader,__isFileSystemWithMountedTrees:W.__isFileSystemWithMountedTrees,__isImmutableBaseFileSystem:W.__isImmutableBaseFileSystem}},mountedFileSystemForURI(F){return U(F)},readFile:async(F,W)=>U(F).readFile(F,W),readBinaryFile:async(F,W)=>U(F).readBinaryFile(F,W),getMtime:async(F,W)=>U(F).getMtime(F,W),realpath:async(F,W)=>U(F).realpath(F,W),access:async(F,W)=>U(F).access(F,W),findFiles:async(F,W)=>U(F.base).findFiles(F,W),stat:async(F,W)=>{let H=Y8(F),{isImplied:D}=F10(q,H);if(D)return{size:0,isDirectory:!0};return U(F).stat(F,W)},rename:async(F,W)=>{let H=U(F);if(Jq(H))throw Error(`rename(${F}) is not supported by this file system`);return H.rename(F,W)},writeFile:async(F,W,H)=>{let D=U(F);if(Jq(D))throw Error(`writeFile(${F}) is not supported by this file system`);return D.writeFile(F,W,H)},mkdirp:async(F,W)=>{let H=U(F);if(Jq(H))throw Error(`mkdirp(${F}) is not supported by this file system`);return H.mkdirp(F,W)},delete:async(F,W)=>{let H=U(F);if(Jq(H))throw Error(`delete(${F}) is not supported by this file system`);return H.delete(F,W)},readdir:async(F,W)=>{F=Y8(F);let{isImplied:H,childMountPoints:D}=F10(q,F);if(H){let V=new Set;for(let N of D){let L=u0.relativePath(F,N);if(L){let O=L.split("/")[0];if(O)V.add(O)}}return Array.from(V).map((N)=>({uri:u0.joinPath(F,N),isDirectory:!0}))}return U(F).readdir(F,W)},watch:(F,W)=>{if(!Y(q))return Q.watch(F,W);if(!S0.isUri(F))throw Error("Watch with glob is not yet implemented in the file system router");let H=U(F);if(Jq(H))return DY;return H.watch(F,W)},isExclusiveWriterFor:async(F,W)=>{let H=U(F);if(Jq(H))throw Error(`isExclusiveWriterFor(${F}) is not supported by this file system`);return H.isExclusiveWriterFor(F,W)},__isImmutableBaseFileSystem:!1,__isFileSystemWithMountedTrees:!0}}return{fileSystemWithMountedTrees:K,fileSystemForURI:(q,G)=>X(EU1(q,G)?.tree??W10),osFileSystem:Q}}function $B(J){if(!Object.values(J).some((Q)=>!!Q))return null;return(Q,Z)=>{if(!Z.dir)throw Error("No directory provided");let X=EU1(nv(Z.thread),Z.dir)?.tree.fs??"os",Y=J[X];if(Y)return pH(Y()).pipe(S9((K)=>K(Q,Z)));throw Error(`Unsupported file system: ${X}`)}}var HE6,W10;var wF=p(()=>{K8();i0();hJ();HE6=[];W10={fs:"os",uri:"file:///"}});function ME6(){return new Proxy({},{get:(J,Q)=>{return async(...Z)=>{let X=Z.at(1),Y=Z.at(0),K=await LZ("/api/internal?"+encodeURIComponent(Q),{method:"POST",body:JSON.stringify({method:Q,params:Y}),signal:X?.signal});if(!K.ok)throw Error(`API request failed: ${K.status}`);return await K.json()}}})}var NZ;var yN=p(()=>{PB();NZ=ME6()});function VE6(J){if(J.proxy&&!process.env.HTTP_PROXY&&!process.env.http_proxy)process.env.HTTP_PROXY=J.proxy;if(J.proxy&&!process.env.HTTPS_PROXY&&!process.env.https_proxy)process.env.HTTPS_PROXY=J.proxy}function av(J,Q){return new URL(`/threads/${Q}`,J)}async function LZ(J,Q){let Z=await A9(Q?.signal??void 0);return NE6(Z,J,Q)}async function D10(J,Q){let Z=await J.get(Q);if(!Z)throw Error(`Thread not found: ${Q}`);let X=await NZ.shareThreadWithOperator({threadData:Z});if(!X.ok)throw Error(`Failed to share thread: ${X.error.message}`)}async function M10(J){let Q=await LZ("/api/telemetry",{method:"POST",headers:{"Content-Type":"application/json"},body:J});if(!Q.ok){let Z=await Q.text(),X;try{X=JSON.parse(Z).error||`HTTP ${Q.status}`}catch{X=Z||`HTTP ${Q.status}`}throw Error(`Failed to submit telemetry: ${X}`)}}async function NE6(J,Q,Z){if(Q.startsWith("http:")||Q.startsWith("https:"))throw Error("input must be a path, not an absolute URL");if(!Q.startsWith("/"))throw Error("pathAndQuery must start with /");let X=J.settings.url;if(!X)throw Error("amp.url is not set");let Y=await J.secrets.getToken("apiKey",X);if(!Y||Y.trim()===""){let K=Error("Amp API key is not set");throw K.name="MissingApiKeyError",K}return VE6({proxy:J.settings.proxy}),fetch(new URL(Q,X),{...Z,headers:{...Z?.headers,...uG(),"Content-Type":"application/json",Authorization:`Bearer ${Y}`}})}var B10;var PB=p(()=>{i0();V4();rU();yN();B10=Q2.pipe(S9(({settings:J,secrets:Q})=>{return p8(async()=>{return await Q.getToken("apiKey",J.url)!==void 0})}))});class fR{heap;length;static#J=!1;static create(J){let Q=O10(J);if(!Q)return[];fR.#J=!0;let Z=new fR(J,Q);return fR.#J=!1,Z}constructor(J,Q){if(!fR.#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]}}var yR,N10,PU1,L10=(J,Q,Z,X)=>{typeof PU1.emitWarning==="function"?PU1.emitWarning(J,Q,Z,X):console.error(`[${Z}] ${Q}: ${J}`)},ll,V10,LE6=(J)=>!N10.has(J),ZO9,TB=(J)=>J&&J===Math.floor(J)&&J>0&&isFinite(J),O10=(J)=>!TB(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?rv:null,rv,il;var A10=p(()=>{yR=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,N10=new Set,PU1=typeof process==="object"&&!!process?process:{},ll=globalThis.AbortController,V10=globalThis.AbortSignal;if(typeof ll>"u"){V10=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(X,Y){this._onabort.push(Y)}},ll=class{constructor(){Q()}signal=new V10;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=PU1.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!J)return;J=!1,L10("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)}}ZO9=Symbol("type");rv=class rv extends Array{constructor(J){super(J);this.fill(0)}};il=class il{#J;#Z;#Y;#X;#G;#$;#T;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#U;#L;#z;#q;#Q;#B;#M;#H;#F;#O;#W;#A;#j;#V;#R;#C;#D;#_;static unsafeExposeInternals(J){return{starts:J.#j,ttls:J.#V,sizes:J.#A,keyMap:J.#z,keyList:J.#q,valList:J.#Q,next:J.#B,prev:J.#M,get head(){return J.#H},get tail(){return J.#F},free:J.#O,isBackgroundFetch:(Q)=>J.#K(Q),backgroundFetch:(Q,Z,X,Y)=>J.#y(Q,Z,X,Y),moveToTail:(Q)=>J.#k(Q),indexes:(Q)=>J.#w(Q),rindexes:(Q)=>J.#I(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.#$}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:F,noDisposeOnSet:W,noUpdateTTL:H,maxSize:D=0,maxEntrySize:M=0,sizeCalculation:V,fetchMethod:N,memoMethod:L,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:j,allowStaleOnFetchAbort:R,ignoreFetchAbort:I}=J;if(Q!==0&&!TB(Q))throw TypeError("max option must be a nonnegative integer");let w=Q?O10(Q):Array;if(!w)throw Error("invalid max value: "+Q);if(this.#J=Q,this.#Z=D,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.#$=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 w(Q),this.#M=new w(Q),this.#H=0,this.#F=0,this.#O=fR.create(Q),this.#U=0,this.#L=0,typeof z==="function")this.#Y=z;if(typeof U==="function")this.#X=U;if(typeof F==="function")this.#G=F,this.#W=[];else this.#G=void 0,this.#W=void 0;if(this.#R=!!this.#Y,this.#_=!!this.#X,this.#D=!!this.#G,this.noDisposeOnSet=!!W,this.noUpdateTTL=!!H,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!j,this.allowStaleOnFetchAbort=!!R,this.ignoreFetchAbort=!!I,this.maxEntrySize!==0){if(this.#Z!==0){if(!TB(this.#Z))throw TypeError("maxSize must be a positive integer if specified")}if(!TB(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#d()}if(this.allowStale=!!G,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!K,this.updateAgeOnHas=!!q,this.ttlResolution=TB(X)||X===0?X:1,this.ttlAutopurge=!!Y,this.ttl=Z||0,this.ttl){if(!TB(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(LE6("LRU_CACHE_UNBOUNDED"))N10.add("LRU_CACHE_UNBOUNDED"),L10("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",il)}}getRemainingTTL(J){return this.#z.has(J)?1/0:0}#f(){let J=new rv(this.#J),Q=new rv(this.#J);this.#V=J,this.#j=Q,this.#h=(Y,K,q=yR.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?yR.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=yR.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 rv(this.#J);this.#L=0,this.#A=J,this.#v=(Q)=>{this.#L-=J[Q],J[Q]=0},this.#g=(Q,Z,X,Y)=>{if(this.#K(Z))return 0;if(!TB(X))if(Y){if(typeof Y!=="function")throw TypeError("sizeCalculation must be a function");if(X=Y(Z,Q),!TB(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.#b=(Q,Z,X)=>{if(J[Q]=Z,this.#Z){let Y=this.#Z-J[Q];while(this.#L>Y)this.#x(!0)}if(this.#L+=J[Q],X)X.entrySize=Z,X.totalCalculatedSize=this.#L}}#v=(J)=>{};#b=(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};*#w({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#F;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#H)break;else Q=this.#M[Q]}}*#I({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.#F)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.#w())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.#I())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.#w()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*rkeys(){for(let J of this.#I()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*values(){for(let J of this.#w())if(this.#Q[J]!==void 0&&!this.#K(this.#Q[J]))yield this.#Q[J]}*rvalues(){for(let J of this.#I())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.#w()){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.#w()){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.#I()){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.#I({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.#j){let K=this.#V[Q],q=this.#j[Q];if(K&&q){let G=K-(yR.now()-q);Y.ttl=G,Y.start=Date.now()}}if(this.#A)Y.size=this.#A[Q];return Y}dump(){let J=[];for(let Q of this.#w({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.#j){K.ttl=this.#V[Q];let q=yR.now()-this.#j[Q];K.start=Math.floor(Date.now()-q)}if(this.#A)K.size=this.#A[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=yR.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 F=this.#U===0?void 0:this.#z.get(J);if(F===void 0){if(F=this.#U===0?this.#F:this.#O.length!==0?this.#O.pop():this.#U===this.#J?this.#x(!1):this.#U,this.#q[F]=J,this.#Q[F]=Q,this.#z.set(J,F),this.#B[this.#F]=F,this.#M[F]=this.#F,this.#F=F,this.#U++,this.#b(F,U,G),G)G.set="add";if(z=!1,this.#_)this.#X?.(Q,J,"add")}else{this.#k(F);let W=this.#Q[F];if(Q!==W){if(this.#C&&this.#K(W)){W.__abortController.abort(Error("replaced"));let{__staleWhileFetching:H}=W;if(H!==void 0&&!K){if(this.#R)this.#Y?.(H,J,"set");if(this.#D)this.#W?.push([H,J,"set"])}}else if(!K){if(this.#R)this.#Y?.(W,J,"set");if(this.#D)this.#W?.push([W,J,"set"])}if(this.#v(F),this.#b(F,U,G),this.#Q[F]=Q,G){G.set="replace";let H=W&&this.#K(W)?W.__staleWhileFetching:W;if(H!==void 0)G.oldValue=H}}else if(G)G.set="update";if(this.#_)this.onInsert?.(Q,J,Q===W?"update":"replace")}if(X!==0&&!this.#V)this.#f();if(this.#V){if(!z)this.#h(F,X,Y);if(G)this.#P(G,F)}if(!K&&this.#D&&this.#W){let W=this.#W,H;while(H=W?.shift())this.#G?.(...H)}return this}pop(){try{while(this.#U){let J=this.#Q[this.#H];if(this.#x(!0),this.#K(J)){if(J.__staleWhileFetching)return J.__staleWhileFetching}else if(J!==void 0)return J}}finally{if(this.#D&&this.#W){let J=this.#W,Q;while(Q=J?.shift())this.#G?.(...Q)}}}#x(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.#R||this.#D){if(this.#R)this.#Y?.(X,Z,"evict");if(this.#D)this.#W?.push([X,Z,"evict"])}if(this.#v(Q),J)this.#q[Q]=void 0,this.#Q[Q]=void 0,this.#O.push(Q);if(this.#U===1)this.#H=this.#F=0,this.#O.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 ll,{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 F(K.signal.reason);let O=H;if(this.#Q[Q]===H)if(M===void 0)if(O.__staleWhileFetching)this.#Q[Q]=O.__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 F(M)},F=(M)=>{let{aborted:V}=K.signal,N=V&&Z.allowStaleOnFetchAbort,L=N||Z.allowStaleOnFetchRejection,O=L||Z.noDeleteOnFetchRejection,A=H;if(this.#Q[Q]===H){if(!O||A.__staleWhileFetching===void 0)this.#E(J,"fetch");else if(!N)this.#Q[Q]=A.__staleWhileFetching}if(L){if(Z.status&&A.__staleWhileFetching!==void 0)Z.status.returnedStale=!0;return A.__staleWhileFetching}else if(A.__returned===A)throw M},W=(M,V)=>{let N=this.#$?.(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(W).then(z,U),D=Object.assign(H,{__abortController:K,__staleWhileFetching:Y,__returned:void 0});if(Q===void 0)this.set(J,D,{...G.options,status:void 0}),Q=this.#z.get(J);else this.#Q[Q]=D;return D}#K(J){if(!this.#C)return!1;let Q=J;return!!Q&&Q instanceof Promise&&Q.hasOwnProperty("__staleWhileFetching")&&Q.__abortController instanceof ll}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:F=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:W=this.allowStaleOnFetchRejection,ignoreFetchAbort:H=this.ignoreFetchAbort,allowStaleOnFetchAbort:D=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 O={allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,ttl:K,noDisposeOnSet:q,size:G,sizeCalculation:z,noUpdateTTL:U,noDeleteOnFetchRejection:F,allowStaleOnFetchRejection:W,allowStaleOnFetchAbort:D,ignoreFetchAbort:H,status:N,signal:L},A=this.#z.get(J);if(A===void 0){if(N)N.fetch="miss";let j=this.#y(J,A,O,M);return j.__returned=j}else{let j=this.#Q[A];if(this.#K(j)){let $=Z&&j.__staleWhileFetching!==void 0;if(N){if(N.fetch="inflight",$)N.returnedStale=!0}return $?j.__staleWhileFetching:j.__returned=j}let R=this.#N(A);if(!V&&!R){if(N)N.fetch="hit";if(this.#k(A),X)this.#S(A);if(N)this.#P(N,A);return j}let I=this.#y(J,A,O,M),E=I.__staleWhileFetching!==void 0&&Z;if(N){if(N.fetch=R?"stale":"refresh",E&&R)N.returnedStale=!0}return E?I.__staleWhileFetching:I.__returned=I}}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.#F){if(J===this.#H)this.#H=this.#B[J];else this.#u(this.#M[J],this.#B[J]);this.#u(this.#F,J),this.#F=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.#R||this.#D){if(this.#R)this.#Y?.(Y,J,Q);if(this.#D)this.#W?.push([Y,J,Q])}if(this.#z.delete(J),this.#q[X]=void 0,this.#Q[X]=void 0,X===this.#F)this.#F=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.#O.push(X)}}if(this.#D&&this.#W?.length){let X=this.#W,Y;while(Y=X?.shift())this.#G?.(...Y)}return Z}clear(){return this.#p("delete")}#p(J){for(let Q of this.#I({allowStale:!0})){let Z=this.#Q[Q];if(this.#K(Z))Z.__abortController.abort(Error("deleted"));else{let X=this.#q[Q];if(this.#R)this.#Y?.(Z,X,J);if(this.#D)this.#W?.push([Z,X,J])}}if(this.#z.clear(),this.#Q.fill(void 0),this.#q.fill(void 0),this.#V&&this.#j)this.#V.fill(0),this.#j.fill(0);if(this.#A)this.#A.fill(0);if(this.#H=0,this.#F=0,this.#O.length=0,this.#L=0,this.#U=0,this.#D&&this.#W){let Q=this.#W,Z;while(Z=Q?.shift())this.#G?.(...Z)}}}});function TU1(J,Q,Z){let X=new b8,K=(()=>{let D=new Map;return(M,V)=>{let L=(D.get(M)?.catch(()=>{})||Promise.resolve()).then(()=>V()).finally(()=>{if(D.get(M)===L)D.delete(M)});return D.set(M,L),L}})(),q=Z?u0.joinPath(Q,Z):Q;function G(D){return u0.joinPath(q,`${D.toString()}.json`)}async function z(D){let M=G(D);try{let V=await J.readBinaryFile(M),N=20971520;if(V.length>20971520){let L=Math.round(V.length/1048576);a.warn(`File too large to load safely: ${String(D)} (${L}MB)`,{key:String(D),size:V.length,maxSize:20971520});return}try{let L=V instanceof Uint8Array?V:new Uint8Array(V);return JSON.parse(new TextDecoder().decode(L))}catch(L){let O=L,{contentLength:A,contentPreview:j}=OE6(V);a.warn("Corrupted JSON detected.",{key:String(D),storageUri:q.toString(),error:O.message,contentLength:A,contentPreview:j});return}}catch(V){if(wQ(V))return;throw V}}async function U(D,M){let V=G(D),N=V.with({path:V.path+".amptmp"}),L=JSON.stringify(M,null,2);await J.mkdirp(u0.joinPath(V,"..")),await K(D,async()=>{await J.writeFile(N,L),await J.rename(N,V)}),X.next(D)}async function F(D){let M=G(D);await K(D,async()=>{await J.delete(M)}),X.next(D)}async function W(){let D;try{D=await J.readdir(q)}catch(M){if(wQ(M))return[];throw M}return D.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(D){return G(D).fsPath}return{get:z,set:U,delete:F,keys:W,path:H,changes:X}}function OE6(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?"...":""}`}}}var j10=p(()=>{K8();i0();B0();hJ()});var CE6={};import CB from"node:path";import{parentPort as CU1,workerData as AE6}from"node:worker_threads";function RE6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}async function wE6(J,Q,Z,X,Y){try{await R8.mkdirp(Z),await I10(Z)}catch(K){throw a.error("Cannot create migration directory, aborting migration:",K),K}if(await iv(R8,Y)){a.debug("Migration already completed by another process");return}try{await w10(X),a.info("Starting thread migration")}catch(K){if(PE6(K))if(await TE6(X))a.info("Removing stale migration lock and retrying"),await R8.delete(X),await w10(X),a.info("Starting thread migration (after stale lock cleanup)");else{a.debug("Another process is running migration");return}else throw a.error("Failed to acquire migration lock:",K),K}try{await IE6(J,Q),await(await import("node:fs/promises")).rename(X.fsPath,Y.fsPath),a.info("Thread migration completed")}catch(K){try{await R8.delete(X)}catch{}throw K}}async function IE6(J,Q){await R8.mkdirp(Q),await I10(Q);try{let X=(await R8.readdir(J)).filter((K)=>CB.basename(K.uri.path).endsWith(".json"));a.info(`Migrating ${X.length} threads to centralized storage`);let Y=0;for(let K=0;K<X.length;K+=R10){let q=X.slice(K,K+R10);await Promise.all(q.map(async(G)=>{let z=CB.basename(G.uri.path),U=G.uri,F=S0.file(CB.join(Q.path,z));if(await iv(R8,F))return;await EE6(U,F),Y++}))}a.info(`Migration completed: ${Y} threads migrated`)}catch(Z){a.debug("No legacy threads to migrate:",Z)}}async function EE6(J,Q){let Z=await import("node:fs/promises");try{await Z.rename(J.fsPath,Q.fsPath)}catch(X){if(X.code==="EXDEV")await $E6(J,Q),await R8.delete(J);else throw X}}async function $E6(J,Q){let Z=await R8.readFile(J);await R8.writeFile(Q,Z);try{let X=await import("node:fs/promises"),Y=await X.stat(J.fsPath);await X.utimes(Q.fsPath,Y.atime,Y.mtime)}catch(X){a.debug(`Could not preserve timestamp for ${CB.basename(Q.path)}:`,X)}}async function w10(J){let Q=await import("node:fs/promises");try{let Z=JSON.stringify({pid:process.pid,startTime:Date.now()});await Q.writeFile(J.fsPath,Z,{flag:"wx"})}catch(Z){if(Z.code==="EEXIST"){let X=Error(`File already exists: ${J.toString()}`);throw X.code="EEXIST",X}throw Z}}function PE6(J){return J instanceof Error&&(("code"in J)&&J.code==="EEXIST"||J.message.includes("already exists"))}async function I10(J){try{await(await import("node:fs/promises")).chmod(J.fsPath,448)}catch(Q){a.debug("Could not set secure permissions:",Q)}}async function TE6(J){try{let Q=await R8.readFile(J),Z=JSON.parse(Q),X=Date.now()-Z.startTime;if(X>jE6)return a.debug(`Migration lock is stale (${Math.round(X/1000/60)}min old)`),!0;return!1}catch(Q){return a.debug("Could not read migration lock file, considering stale:",Q),!0}}var R10=25,jE6=300000;var E10=p(()=>{K8();B0();hJ();xN();if(CU1){let{legacyDir:J,centralizedDir:Q,isDevelopment:Z}=AE6,X=S0.parse(J),Y=S0.parse(Q),K=S0.file(CB.join(Y.path,"..","migration")),q=RE6(Z),G=S0.file(CB.join(K.path,q.progress)),z=S0.file(CB.join(K.path,q.done));wE6(X,Y,K,G,z).then(async()=>{try{let F=(await R8.readdir(Y)).filter((W)=>CB.basename(W.uri.path).endsWith(".json")).length;CU1?.postMessage({migratedCount:F})}catch{CU1?.postMessage({migratedCount:0})}}).catch((U)=>{throw U})}});import{homedir as SE6}from"node:os";import SB from"node:path";import{Worker as vE6}from"node:worker_threads";async function $10(J){let Q=J.isDevelopment||!1,Z=_E6(),X=Q?"threads-development":"threads",Y=TU1(R8,Z,X),K=new P10(Y);if(!J.vscodeMigrationContext)return a.debug("Using centralized thread storage (CLI)",{storageUri:Z.toString(),storageSubdir:X}),K;let{fileSystem:q,vscodeContext:G}=J.vscodeMigrationContext,z=S0.file(SB.join(Z.path,X)),U=Q?"threads3-development":"threads3",F=S0.file(SB.join(G.globalStorageUri.path,U));if(await bE6(z,Q,F))return a.debug("Using centralized thread storage (VS Code, migration complete)",{storageUri:Z.toString(),storageSubdir:X}),K;else{a.debug("Using fallback thread storage (VS Code, migration in progress)",{centralizedStorageUri:Z.toString(),legacyStorageUri:G.globalStorageUri.toString(),storageSubdir:X,legacySubdir:U}),xE6(F,z,Q);let H=TU1(q,G.globalStorageUri,U);return kE6(K,H)}}class P10{delegate;cache=new il({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 kE6(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 _E6(){let J=process.env.XDG_DATA_HOME||SB.join(SE6(),".local","share"),Q=SB.resolve(J,"amp");return S0.file(Q)}async function bE6(J,Q,Z){let X=S0.file(SB.join(J.path,"..","migration")),Y=yE6(Q),K=S0.file(SB.join(X.path,Y.done));if(await iv(R8,K))return!0;if(Z)try{if((await R8.readdir(Z)).filter((z)=>SB.basename(z.uri.path).endsWith(".json")).length===0){if((await R8.readdir(J)).filter((F)=>SB.basename(F.uri.path).endsWith(".json")).length>0){a.info("Detected completed migration without marker, creating completion marker");try{await R8.mkdirp(X),await R8.writeFile(K,"completed")}catch(F){a.debug("Could not create migration completion marker:",F)}return!0}}}catch(q){a.debug("Could not check legacy directory for completion detection:",q)}return!1}function xE6(J,Q,Z){try{let X=new vE6(o1.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)=>{a.info("Background migration completed:",Y)}),X.on("error",(Y)=>{a.warn("Background migration failed:",Y)}),X.on("exit",(Y)=>{if(Y!==0)a.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"))a.debug("Migration worker could not be started (expected in tests):",X);else a.warn("Migration worker failed to start, migration will be skipped:",X)}}function yE6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}var T10=p(()=>{K8();A10();B0();hJ();xN();j10()});async function hR(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=fE6(J,q),z=G<0,U,F;if(K.time){let W=K.time[J],H=K.time[q],D=Date.now();if(W)U=Math.floor((D-new Date(W).getTime())/3600000);if(H)F=Math.floor((D-new Date(H).getTime())/3600000)}return a.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:z,currentVersionAge:U,latestVersionAge:F}),{hasUpdate:z,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:F,source:"npm"}}catch(Z){return a.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function fE6(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 nl=p(()=>{B0()});import{execFile as hE6}from"node:child_process";import{promises as vB}from"node:fs";import{homedir as SU1}from"node:os";import{join as Qq}from"node:path";import{promisify as gE6}from"node:util";class vU1{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 vB.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 vB.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 gR("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 vB.readFile(Q,"utf8")).split(`
141
+ ${W}`));return}V();let L=F.slice(0,X);z({files:L,remaining:F.length-L.length})})})}var Z10,qE6=({args:J},{dirs:Q})=>{if(Q.length===0)return new K0((X)=>{X.next({status:"error",error:{message:"No directory provided"}}),X.complete()});let Z={};if(J.limit!==void 0)Z.limit=J.limit;if(J.offset!==void 0)Z.offset=J.offset;return X10(Q,J.filePattern,Z)},wU1=500000;var IU1=p(()=>{K8();i0();Z10=u6(Cj(),1);B0();aS();cv();rG()});function wQ(J){return J instanceof YJ||J instanceof Error&&J.name==="FileNotExistError"||typeof J==="object"&&J!==null&&"code"in J&&typeof J.code==="string"&&["ENOENT","FileNotFound"].includes(J.code)}function K10(J){return typeof J==="object"&&J!==null&&"base"in J&&"pattern"in J&&typeof J.pattern==="string"}function q10(J){return{readFile:J.readFile,readBinaryFile:J.readBinaryFile,stat:J.stat,getMtime:J.getMtime,realpath:J.realpath,readdir:J.readdir,findFiles:J.findFiles,access:J.access,watch:J.watch}}function G10(J){return{...J,writeFile:()=>Promise.reject(Error("Write operations not implemented")),delete:()=>Promise.reject(Error("Write operations not implemented")),mkdirp:()=>Promise.reject(Error("Write operations not implemented")),rename:()=>Promise.reject(Error("Write operations not implemented")),isExclusiveWriterFor:()=>Promise.resolve(!1)}}function Jq(J){return"__isImmutableBaseFileSystem"in J&&J.__isImmutableBaseFileSystem===!0}async function lv(J,Q,Z){try{return await J.readFile(Q,Z)}catch(X){if(X instanceof YJ)return null;throw X}}async function iv(J,Q,Z){try{return await J.access(Q,Z),!0}catch(X){if(wQ(X))return!1;throw X}}var YJ;var hJ=p(()=>{YJ=class YJ extends Error{constructor(J){let Q=typeof J==="string"?J:J.toString();super(`File not found: ${Q}`);this.name="FileNotExistError"}}});import*as vX from"node:fs";import*as cl from"node:path";function zE6(J){if(!dH(J))throw Error(`Expected a file URI (got ${J.toString()})`)}function RF(J){return J!==null&&typeof J==="object"&&"code"in J&&J.code==="ENOENT"}async function UE6(J){if(J.scheme!=="file")throw Error("nodeRealpath only supports file URIs");try{return S0.file(await vX.promises.realpath(J.fsPath))}catch(Q){if(RF(Q))throw new YJ(J);throw Q}}var R8;var xN=p(()=>{K8();i0();B0();IU1();hJ();aS();R8={readFile:async(J,Q)=>{try{return await vX.promises.readFile(Y8(J).fsPath,{encoding:"utf8",signal:Q?.signal})}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},readBinaryFile:async(J,Q)=>{try{return await vX.promises.readFile(Y8(J).fsPath,{signal:Q?.signal})}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},getMtime:async(J,Q)=>{try{return(await vX.promises.stat(Y8(J).fsPath)).mtimeMs}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},stat:async(J,Q)=>{J=Y8(J);try{let Z=await vX.promises.stat(J.fsPath);return{name:cl.basename(J.fsPath),size:Z.size,isDirectory:Z.isDirectory()}}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},realpath:async(J,Q)=>{return UE6(Y8(J))},rename:async(J,Q)=>{try{await vX.promises.rename(Y8(J).fsPath,Y8(Q).fsPath)}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},writeFile:async(J,Q,Z)=>{await vX.promises.writeFile(Y8(J).fsPath,Q,{encoding:"utf-8",signal:Z?.signal,flush:!0})},delete:async(J,Q)=>{J=Y8(J);try{if(Q?.recursive)await vX.promises.rm(J.fsPath,{recursive:!0,force:!0});else await vX.promises.unlink(J.fsPath)}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},mkdirp:async(J)=>{await vX.promises.mkdir(Y8(J).fsPath,{recursive:!0})},readdir:async(J,Q)=>{J=Y8(J);try{return(await vX.promises.readdir(J.fsPath,{withFileTypes:!0})).map((X)=>({uri:S0.file(cl.join(J.fsPath,X.name)),isDirectory:X.isDirectory()}))}catch(Z){if(RF(Z))throw new YJ(J);throw Z}},findFiles:async(J,Q)=>{try{return(await dl(J.base,{pattern:J.pattern,caseInsensitive:!0},{limit:Q?.maxResults,signal:Q?.signal})).files.map((X)=>FF(X)?S0.file(X):u0.joinPath(J.base,X))}catch(Z){return a.error(`Error finding files with pattern ${J.pattern}:`,Z instanceof Error?Z:Error(String(Z))),[]}},watch:()=>DY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{let Z=Y8(J);zE6(Z);try{await vX.promises.access(Z.fsPath)}catch(X){if(RF(X))throw new YJ(Z);throw X}}}});async function FE6(J,Q){let Z=Y8(J).fsPath;if(!Z.startsWith(process.cwd()))return;if(a.debug("ide-fs",{method:"readFile",path:Z}),await RQ.isConnected())try{let X=await RQ.sendRequest("readFile",{path:Z});if(X?.content)return Q(X.content);throw Error(`Failed to readFile via IDE ${Z}: ${X?.message??"unknown cause"}`)}catch(X){if(process.env.IDE_FS_NO_FALLBACK)throw X;a.warn("IDE readFile failed, falling back to Node.js filesystem",{path:Z,error:X});return}else return}async function WE6(J,Q){let Z=Y8(J).fsPath;if(!Z.startsWith(process.cwd()))return!1;if(a.debug("ide-fs",{method:"writeFile",path:Z}),await RQ.isConnected())try{let X=await RQ.sendRequest("editFile",{path:Y8(J).fsPath,fullContent:Q});if(!X?.success)throw Error(`Failed to writeFile via IDE ${Z}: ${X?.message??"unknown cause"}`);return!0}catch(X){if(process.env.IDE_FS_NO_FALLBACK)throw X;return a.warn("IDE writeFile failed, falling back to Node.js filesystem",{path:Z,error:X}),!1}else return!1}var z10;var U10=p(()=>{K8();i0();B0();ej();xN();z10={readFile:async(J,Q)=>{return await FE6(J,(Z)=>Z)??await R8.readFile(J,Q).finally(()=>{a.debug("ide-fs",{fallback:"readFile"})})},readBinaryFile:async(J,Q)=>{return a.debug("ide-fs",{fallback:"readBinaryFile"}),R8.readBinaryFile(J,Q)},getMtime:async(J,Q)=>{return R8.getMtime(J,Q)},stat:async(J,Q)=>{return R8.stat(J,Q)},realpath:async(J,Q)=>{return R8.realpath(J,Q)},rename:async(J,Q)=>{return R8.rename(J,Q)},writeFile:async(J,Q,Z)=>{if(await WE6(J,Q))return;return await R8.writeFile(J,Q,Z).finally(()=>{a.debug("ide-fs",{fallback:"writeFile"})})},delete:async(J,Q)=>{return R8.delete(J,Q)},mkdirp:async(J)=>{return R8.mkdirp(J)},readdir:async(J,Q)=>{return R8.readdir(J,Q)},findFiles:async(J,Q)=>{return R8.findFiles(J,Q)},watch:()=>DY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{return R8.access(J,Q)}}});function $U1(J){return"__isFileSystemWithMountedTrees"in J&&J.__isFileSystemWithMountedTrees===!0}function EU1(J,Q){Q=Y8(Q);let Z,X;for(let Y of J.trees){if(!Y.uri)continue;let K=MX(Y.uri);if(u0.hasPrefix(Q,K)){let q=u0.relativePath(K,Q);if(q===null)continue;if(X===void 0||q.length<X.length)X=q,Z=Y}}if(!Z||X===void 0)return null;return{tree:Z,filePath:X}}function BE6(J){return Array.isArray(J)}function DE6(J){let Q;if(J===void 0)Q=void 0;else if(BE6(J))Q=J;else Q=J?.env?.initial?.trees;return Q?.filter((Z)=>Z.uri!==void 0)??HE6}function F10(J,Q){for(let X of J.trees){if(!X.uri)continue;let Y=MX(X.uri);if(u0.hasPrefix(Q,Y))return{isImplied:!1,childMountPoints:[]}}let Z=[];for(let X of J.trees){if(!X.uri)continue;let Y=MX(X.uri);if(u0.hasPrefix(Y,Q))Z.push(Y)}return{isImplied:Z.length>0,childMountPoints:Z}}function nv(J){return{trees:DE6(J)}}function H10(J){let Q={...J.os,mountedTree:W10},Z=new Map;function X(q){if(!q.fs||q.fs==="os")return Q;if(!q.uri)throw Error("Tree URI is required");if(!q.repository)throw Error(`Tree with FS type ${q.fs} requires repository field`);let G={uri:q.uri,repository:q.repository,fs:q.fs},z=`${q.fs}:${JSON.stringify(q)}`,U=Z.get(z);if(!U){let F=J[q.fs];if(!F)throw Error(`No file system implementation found for: ${q.fs}`);U={...F(G),mountedTree:G},Z.set(z,U)}return U}function Y(q){return q.trees.some((G)=>G.fs&&G.fs!=="os")}function K(q,G){let z=q.trees.map((F)=>({mountPoint:F.uri,fs:X(F)}));function U(F){if(!Y(q))return G?{...G(Q),mountedTree:Q.mountedTree}:Q;let W=EU1(q,F)?.tree;if(!W)throw new YJ(F);let H=z.find((D)=>u0.equalURIs(D.mountPoint,W.uri))?.fs;if(!H)throw Error(`No file system found for URI: ${F}`);return G?{...G(H),mountedTree:H.mountedTree}:H}return{map(F){if(G)throw Error("Cannot use both prepare and prepare2");return K(q,F)},mapReader(F){if(G)throw Error("Cannot use both prepare and prepare2");let W=K(q,F);return{...q10(W),mountedFileSystemForURI:W.mountedFileSystemForURI,map:()=>{throw Error("not implemented")},mapReader:W.mapReader,__isFileSystemWithMountedTrees:W.__isFileSystemWithMountedTrees,__isImmutableBaseFileSystem:W.__isImmutableBaseFileSystem}},mountedFileSystemForURI(F){return U(F)},readFile:async(F,W)=>U(F).readFile(F,W),readBinaryFile:async(F,W)=>U(F).readBinaryFile(F,W),getMtime:async(F,W)=>U(F).getMtime(F,W),realpath:async(F,W)=>U(F).realpath(F,W),access:async(F,W)=>U(F).access(F,W),findFiles:async(F,W)=>U(F.base).findFiles(F,W),stat:async(F,W)=>{let H=Y8(F),{isImplied:D}=F10(q,H);if(D)return{size:0,isDirectory:!0};return U(F).stat(F,W)},rename:async(F,W)=>{let H=U(F);if(Jq(H))throw Error(`rename(${F}) is not supported by this file system`);return H.rename(F,W)},writeFile:async(F,W,H)=>{let D=U(F);if(Jq(D))throw Error(`writeFile(${F}) is not supported by this file system`);return D.writeFile(F,W,H)},mkdirp:async(F,W)=>{let H=U(F);if(Jq(H))throw Error(`mkdirp(${F}) is not supported by this file system`);return H.mkdirp(F,W)},delete:async(F,W)=>{let H=U(F);if(Jq(H))throw Error(`delete(${F}) is not supported by this file system`);return H.delete(F,W)},readdir:async(F,W)=>{F=Y8(F);let{isImplied:H,childMountPoints:D}=F10(q,F);if(H){let V=new Set;for(let N of D){let L=u0.relativePath(F,N);if(L){let O=L.split("/")[0];if(O)V.add(O)}}return Array.from(V).map((N)=>({uri:u0.joinPath(F,N),isDirectory:!0}))}return U(F).readdir(F,W)},watch:(F,W)=>{if(!Y(q))return Q.watch(F,W);if(!S0.isUri(F))throw Error("Watch with glob is not yet implemented in the file system router");let H=U(F);if(Jq(H))return DY;return H.watch(F,W)},isExclusiveWriterFor:async(F,W)=>{let H=U(F);if(Jq(H))throw Error(`isExclusiveWriterFor(${F}) is not supported by this file system`);return H.isExclusiveWriterFor(F,W)},__isImmutableBaseFileSystem:!1,__isFileSystemWithMountedTrees:!0}}return{fileSystemWithMountedTrees:K,fileSystemForURI:(q,G)=>X(EU1(q,G)?.tree??W10),osFileSystem:Q}}function $B(J){if(!Object.values(J).some((Q)=>!!Q))return null;return(Q,Z)=>{if(!Z.dir)throw Error("No directory provided");let X=EU1(nv(Z.thread),Z.dir)?.tree.fs??"os",Y=J[X];if(Y)return pH(Y()).pipe(S9((K)=>K(Q,Z)));throw Error(`Unsupported file system: ${X}`)}}var HE6,W10;var wF=p(()=>{K8();i0();hJ();HE6=[];W10={fs:"os",uri:"file:///"}});function ME6(){return new Proxy({},{get:(J,Q)=>{return async(...Z)=>{let X=Z.at(1),Y=Z.at(0),K=await LZ("/api/internal?"+encodeURIComponent(Q),{method:"POST",body:JSON.stringify({method:Q,params:Y}),signal:X?.signal});if(!K.ok)throw Error(`API request failed: ${K.status}`);return await K.json()}}})}var NZ;var yN=p(()=>{PB();NZ=ME6()});function VE6(J){if(J.proxy&&!process.env.HTTP_PROXY&&!process.env.http_proxy)process.env.HTTP_PROXY=J.proxy;if(J.proxy&&!process.env.HTTPS_PROXY&&!process.env.https_proxy)process.env.HTTPS_PROXY=J.proxy}function av(J,Q){return new URL(`/threads/${Q}`,J)}async function LZ(J,Q){let Z=await A9(Q?.signal??void 0);return NE6(Z,J,Q)}async function D10(J,Q){let Z=await J.get(Q);if(!Z)throw Error(`Thread not found: ${Q}`);let X=await NZ.shareThreadWithOperator({threadData:Z});if(!X.ok)throw Error(`Failed to share thread: ${X.error.message}`)}async function M10(J){let Q=await LZ("/api/telemetry",{method:"POST",headers:{"Content-Type":"application/json"},body:J});if(!Q.ok){let Z=await Q.text(),X;try{X=JSON.parse(Z).error||`HTTP ${Q.status}`}catch{X=Z||`HTTP ${Q.status}`}throw Error(`Failed to submit telemetry: ${X}`)}}async function NE6(J,Q,Z){if(Q.startsWith("http:")||Q.startsWith("https:"))throw Error("input must be a path, not an absolute URL");if(!Q.startsWith("/"))throw Error("pathAndQuery must start with /");let X=J.settings.url;if(!X)throw Error("amp.url is not set");let Y=await J.secrets.getToken("apiKey",X);if(!Y||Y.trim()===""){let K=Error("Amp API key is not set");throw K.name="MissingApiKeyError",K}return VE6({proxy:J.settings.proxy}),fetch(new URL(Q,X),{...Z,headers:{...Z?.headers,...uG(),"Content-Type":"application/json",Authorization:`Bearer ${Y}`}})}var B10;var PB=p(()=>{i0();V4();rU();yN();B10=Q2.pipe(S9(({settings:J,secrets:Q})=>{return p8(async()=>{return await Q.getToken("apiKey",J.url)!==void 0})}))});class fR{heap;length;static#J=!1;static create(J){let Q=O10(J);if(!Q)return[];fR.#J=!0;let Z=new fR(J,Q);return fR.#J=!1,Z}constructor(J,Q){if(!fR.#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]}}var yR,N10,PU1,L10=(J,Q,Z,X)=>{typeof PU1.emitWarning==="function"?PU1.emitWarning(J,Q,Z,X):console.error(`[${Z}] ${Q}: ${J}`)},ll,V10,LE6=(J)=>!N10.has(J),ZO9,TB=(J)=>J&&J===Math.floor(J)&&J>0&&isFinite(J),O10=(J)=>!TB(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?rv:null,rv,il;var A10=p(()=>{yR=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,N10=new Set,PU1=typeof process==="object"&&!!process?process:{},ll=globalThis.AbortController,V10=globalThis.AbortSignal;if(typeof ll>"u"){V10=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(X,Y){this._onabort.push(Y)}},ll=class{constructor(){Q()}signal=new V10;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=PU1.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!J)return;J=!1,L10("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)}}ZO9=Symbol("type");rv=class rv extends Array{constructor(J){super(J);this.fill(0)}};il=class il{#J;#Z;#Y;#X;#G;#$;#T;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#U;#L;#z;#q;#Q;#B;#M;#H;#F;#O;#W;#A;#j;#V;#R;#C;#D;#_;static unsafeExposeInternals(J){return{starts:J.#j,ttls:J.#V,sizes:J.#A,keyMap:J.#z,keyList:J.#q,valList:J.#Q,next:J.#B,prev:J.#M,get head(){return J.#H},get tail(){return J.#F},free:J.#O,isBackgroundFetch:(Q)=>J.#K(Q),backgroundFetch:(Q,Z,X,Y)=>J.#y(Q,Z,X,Y),moveToTail:(Q)=>J.#k(Q),indexes:(Q)=>J.#w(Q),rindexes:(Q)=>J.#I(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.#$}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:F,noDisposeOnSet:W,noUpdateTTL:H,maxSize:D=0,maxEntrySize:M=0,sizeCalculation:V,fetchMethod:N,memoMethod:L,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:j,allowStaleOnFetchAbort:R,ignoreFetchAbort:I}=J;if(Q!==0&&!TB(Q))throw TypeError("max option must be a nonnegative integer");let w=Q?O10(Q):Array;if(!w)throw Error("invalid max value: "+Q);if(this.#J=Q,this.#Z=D,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.#$=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 w(Q),this.#M=new w(Q),this.#H=0,this.#F=0,this.#O=fR.create(Q),this.#U=0,this.#L=0,typeof z==="function")this.#Y=z;if(typeof U==="function")this.#X=U;if(typeof F==="function")this.#G=F,this.#W=[];else this.#G=void 0,this.#W=void 0;if(this.#R=!!this.#Y,this.#_=!!this.#X,this.#D=!!this.#G,this.noDisposeOnSet=!!W,this.noUpdateTTL=!!H,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!j,this.allowStaleOnFetchAbort=!!R,this.ignoreFetchAbort=!!I,this.maxEntrySize!==0){if(this.#Z!==0){if(!TB(this.#Z))throw TypeError("maxSize must be a positive integer if specified")}if(!TB(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#d()}if(this.allowStale=!!G,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!K,this.updateAgeOnHas=!!q,this.ttlResolution=TB(X)||X===0?X:1,this.ttlAutopurge=!!Y,this.ttl=Z||0,this.ttl){if(!TB(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(LE6("LRU_CACHE_UNBOUNDED"))N10.add("LRU_CACHE_UNBOUNDED"),L10("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",il)}}getRemainingTTL(J){return this.#z.has(J)?1/0:0}#f(){let J=new rv(this.#J),Q=new rv(this.#J);this.#V=J,this.#j=Q,this.#h=(Y,K,q=yR.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?yR.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=yR.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 rv(this.#J);this.#L=0,this.#A=J,this.#v=(Q)=>{this.#L-=J[Q],J[Q]=0},this.#g=(Q,Z,X,Y)=>{if(this.#K(Z))return 0;if(!TB(X))if(Y){if(typeof Y!=="function")throw TypeError("sizeCalculation must be a function");if(X=Y(Z,Q),!TB(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.#b=(Q,Z,X)=>{if(J[Q]=Z,this.#Z){let Y=this.#Z-J[Q];while(this.#L>Y)this.#x(!0)}if(this.#L+=J[Q],X)X.entrySize=Z,X.totalCalculatedSize=this.#L}}#v=(J)=>{};#b=(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};*#w({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#F;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#H)break;else Q=this.#M[Q]}}*#I({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.#F)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.#w())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.#I())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.#w()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*rkeys(){for(let J of this.#I()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*values(){for(let J of this.#w())if(this.#Q[J]!==void 0&&!this.#K(this.#Q[J]))yield this.#Q[J]}*rvalues(){for(let J of this.#I())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.#w()){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.#w()){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.#I()){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.#I({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.#j){let K=this.#V[Q],q=this.#j[Q];if(K&&q){let G=K-(yR.now()-q);Y.ttl=G,Y.start=Date.now()}}if(this.#A)Y.size=this.#A[Q];return Y}dump(){let J=[];for(let Q of this.#w({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.#j){K.ttl=this.#V[Q];let q=yR.now()-this.#j[Q];K.start=Math.floor(Date.now()-q)}if(this.#A)K.size=this.#A[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=yR.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 F=this.#U===0?void 0:this.#z.get(J);if(F===void 0){if(F=this.#U===0?this.#F:this.#O.length!==0?this.#O.pop():this.#U===this.#J?this.#x(!1):this.#U,this.#q[F]=J,this.#Q[F]=Q,this.#z.set(J,F),this.#B[this.#F]=F,this.#M[F]=this.#F,this.#F=F,this.#U++,this.#b(F,U,G),G)G.set="add";if(z=!1,this.#_)this.#X?.(Q,J,"add")}else{this.#k(F);let W=this.#Q[F];if(Q!==W){if(this.#C&&this.#K(W)){W.__abortController.abort(Error("replaced"));let{__staleWhileFetching:H}=W;if(H!==void 0&&!K){if(this.#R)this.#Y?.(H,J,"set");if(this.#D)this.#W?.push([H,J,"set"])}}else if(!K){if(this.#R)this.#Y?.(W,J,"set");if(this.#D)this.#W?.push([W,J,"set"])}if(this.#v(F),this.#b(F,U,G),this.#Q[F]=Q,G){G.set="replace";let H=W&&this.#K(W)?W.__staleWhileFetching:W;if(H!==void 0)G.oldValue=H}}else if(G)G.set="update";if(this.#_)this.onInsert?.(Q,J,Q===W?"update":"replace")}if(X!==0&&!this.#V)this.#f();if(this.#V){if(!z)this.#h(F,X,Y);if(G)this.#P(G,F)}if(!K&&this.#D&&this.#W){let W=this.#W,H;while(H=W?.shift())this.#G?.(...H)}return this}pop(){try{while(this.#U){let J=this.#Q[this.#H];if(this.#x(!0),this.#K(J)){if(J.__staleWhileFetching)return J.__staleWhileFetching}else if(J!==void 0)return J}}finally{if(this.#D&&this.#W){let J=this.#W,Q;while(Q=J?.shift())this.#G?.(...Q)}}}#x(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.#R||this.#D){if(this.#R)this.#Y?.(X,Z,"evict");if(this.#D)this.#W?.push([X,Z,"evict"])}if(this.#v(Q),J)this.#q[Q]=void 0,this.#Q[Q]=void 0,this.#O.push(Q);if(this.#U===1)this.#H=this.#F=0,this.#O.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 ll,{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 F(K.signal.reason);let O=H;if(this.#Q[Q]===H)if(M===void 0)if(O.__staleWhileFetching)this.#Q[Q]=O.__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 F(M)},F=(M)=>{let{aborted:V}=K.signal,N=V&&Z.allowStaleOnFetchAbort,L=N||Z.allowStaleOnFetchRejection,O=L||Z.noDeleteOnFetchRejection,A=H;if(this.#Q[Q]===H){if(!O||A.__staleWhileFetching===void 0)this.#E(J,"fetch");else if(!N)this.#Q[Q]=A.__staleWhileFetching}if(L){if(Z.status&&A.__staleWhileFetching!==void 0)Z.status.returnedStale=!0;return A.__staleWhileFetching}else if(A.__returned===A)throw M},W=(M,V)=>{let N=this.#$?.(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(W).then(z,U),D=Object.assign(H,{__abortController:K,__staleWhileFetching:Y,__returned:void 0});if(Q===void 0)this.set(J,D,{...G.options,status:void 0}),Q=this.#z.get(J);else this.#Q[Q]=D;return D}#K(J){if(!this.#C)return!1;let Q=J;return!!Q&&Q instanceof Promise&&Q.hasOwnProperty("__staleWhileFetching")&&Q.__abortController instanceof ll}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:F=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:W=this.allowStaleOnFetchRejection,ignoreFetchAbort:H=this.ignoreFetchAbort,allowStaleOnFetchAbort:D=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 O={allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,ttl:K,noDisposeOnSet:q,size:G,sizeCalculation:z,noUpdateTTL:U,noDeleteOnFetchRejection:F,allowStaleOnFetchRejection:W,allowStaleOnFetchAbort:D,ignoreFetchAbort:H,status:N,signal:L},A=this.#z.get(J);if(A===void 0){if(N)N.fetch="miss";let j=this.#y(J,A,O,M);return j.__returned=j}else{let j=this.#Q[A];if(this.#K(j)){let $=Z&&j.__staleWhileFetching!==void 0;if(N){if(N.fetch="inflight",$)N.returnedStale=!0}return $?j.__staleWhileFetching:j.__returned=j}let R=this.#N(A);if(!V&&!R){if(N)N.fetch="hit";if(this.#k(A),X)this.#S(A);if(N)this.#P(N,A);return j}let I=this.#y(J,A,O,M),E=I.__staleWhileFetching!==void 0&&Z;if(N){if(N.fetch=R?"stale":"refresh",E&&R)N.returnedStale=!0}return E?I.__staleWhileFetching:I.__returned=I}}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.#F){if(J===this.#H)this.#H=this.#B[J];else this.#u(this.#M[J],this.#B[J]);this.#u(this.#F,J),this.#F=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.#R||this.#D){if(this.#R)this.#Y?.(Y,J,Q);if(this.#D)this.#W?.push([Y,J,Q])}if(this.#z.delete(J),this.#q[X]=void 0,this.#Q[X]=void 0,X===this.#F)this.#F=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.#O.push(X)}}if(this.#D&&this.#W?.length){let X=this.#W,Y;while(Y=X?.shift())this.#G?.(...Y)}return Z}clear(){return this.#p("delete")}#p(J){for(let Q of this.#I({allowStale:!0})){let Z=this.#Q[Q];if(this.#K(Z))Z.__abortController.abort(Error("deleted"));else{let X=this.#q[Q];if(this.#R)this.#Y?.(Z,X,J);if(this.#D)this.#W?.push([Z,X,J])}}if(this.#z.clear(),this.#Q.fill(void 0),this.#q.fill(void 0),this.#V&&this.#j)this.#V.fill(0),this.#j.fill(0);if(this.#A)this.#A.fill(0);if(this.#H=0,this.#F=0,this.#O.length=0,this.#L=0,this.#U=0,this.#D&&this.#W){let Q=this.#W,Z;while(Z=Q?.shift())this.#G?.(...Z)}}}});function TU1(J,Q,Z){let X=new b8,K=(()=>{let D=new Map;return(M,V)=>{let L=(D.get(M)?.catch(()=>{})||Promise.resolve()).then(()=>V()).finally(()=>{if(D.get(M)===L)D.delete(M)});return D.set(M,L),L}})(),q=Z?u0.joinPath(Q,Z):Q;function G(D){return u0.joinPath(q,`${D.toString()}.json`)}async function z(D){let M=G(D);try{let V=await J.readBinaryFile(M),N=20971520;if(V.length>20971520){let L=Math.round(V.length/1048576);a.warn(`File too large to load safely: ${String(D)} (${L}MB)`,{key:String(D),size:V.length,maxSize:20971520});return}try{let L=V instanceof Uint8Array?V:new Uint8Array(V);return JSON.parse(new TextDecoder().decode(L))}catch(L){let O=L,{contentLength:A,contentPreview:j}=OE6(V);a.warn("Corrupted JSON detected.",{key:String(D),storageUri:q.toString(),error:O.message,contentLength:A,contentPreview:j});return}}catch(V){if(wQ(V))return;throw V}}async function U(D,M){let V=G(D),N=V.with({path:V.path+".amptmp"}),L=JSON.stringify(M,null,2);await J.mkdirp(u0.joinPath(V,"..")),await K(D,async()=>{await J.writeFile(N,L),await J.rename(N,V)}),X.next(D)}async function F(D){let M=G(D);await K(D,async()=>{await J.delete(M)}),X.next(D)}async function W(){let D;try{D=await J.readdir(q)}catch(M){if(wQ(M))return[];throw M}return D.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(D){return G(D).fsPath}return{get:z,set:U,delete:F,keys:W,path:H,changes:X}}function OE6(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?"...":""}`}}}var j10=p(()=>{K8();i0();B0();hJ()});var CE6={};import CB from"node:path";import{parentPort as CU1,workerData as AE6}from"node:worker_threads";function RE6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}async function wE6(J,Q,Z,X,Y){try{await R8.mkdirp(Z),await I10(Z)}catch(K){throw a.error("Cannot create migration directory, aborting migration:",K),K}if(await iv(R8,Y)){a.debug("Migration already completed by another process");return}try{await w10(X),a.info("Starting thread migration")}catch(K){if(PE6(K))if(await TE6(X))a.info("Removing stale migration lock and retrying"),await R8.delete(X),await w10(X),a.info("Starting thread migration (after stale lock cleanup)");else{a.debug("Another process is running migration");return}else throw a.error("Failed to acquire migration lock:",K),K}try{await IE6(J,Q),await(await import("node:fs/promises")).rename(X.fsPath,Y.fsPath),a.info("Thread migration completed")}catch(K){try{await R8.delete(X)}catch{}throw K}}async function IE6(J,Q){await R8.mkdirp(Q),await I10(Q);try{let X=(await R8.readdir(J)).filter((K)=>CB.basename(K.uri.path).endsWith(".json"));a.info(`Migrating ${X.length} threads to centralized storage`);let Y=0;for(let K=0;K<X.length;K+=R10){let q=X.slice(K,K+R10);await Promise.all(q.map(async(G)=>{let z=CB.basename(G.uri.path),U=G.uri,F=S0.file(CB.join(Q.path,z));if(await iv(R8,F))return;await EE6(U,F),Y++}))}a.info(`Migration completed: ${Y} threads migrated`)}catch(Z){a.debug("No legacy threads to migrate:",Z)}}async function EE6(J,Q){let Z=await import("node:fs/promises");try{await Z.rename(J.fsPath,Q.fsPath)}catch(X){if(X.code==="EXDEV")await $E6(J,Q),await R8.delete(J);else throw X}}async function $E6(J,Q){let Z=await R8.readFile(J);await R8.writeFile(Q,Z);try{let X=await import("node:fs/promises"),Y=await X.stat(J.fsPath);await X.utimes(Q.fsPath,Y.atime,Y.mtime)}catch(X){a.debug(`Could not preserve timestamp for ${CB.basename(Q.path)}:`,X)}}async function w10(J){let Q=await import("node:fs/promises");try{let Z=JSON.stringify({pid:process.pid,startTime:Date.now()});await Q.writeFile(J.fsPath,Z,{flag:"wx"})}catch(Z){if(Z.code==="EEXIST"){let X=Error(`File already exists: ${J.toString()}`);throw X.code="EEXIST",X}throw Z}}function PE6(J){return J instanceof Error&&(("code"in J)&&J.code==="EEXIST"||J.message.includes("already exists"))}async function I10(J){try{await(await import("node:fs/promises")).chmod(J.fsPath,448)}catch(Q){a.debug("Could not set secure permissions:",Q)}}async function TE6(J){try{let Q=await R8.readFile(J),Z=JSON.parse(Q),X=Date.now()-Z.startTime;if(X>jE6)return a.debug(`Migration lock is stale (${Math.round(X/1000/60)}min old)`),!0;return!1}catch(Q){return a.debug("Could not read migration lock file, considering stale:",Q),!0}}var R10=25,jE6=300000;var E10=p(()=>{K8();B0();hJ();xN();if(CU1){let{legacyDir:J,centralizedDir:Q,isDevelopment:Z}=AE6,X=S0.parse(J),Y=S0.parse(Q),K=S0.file(CB.join(Y.path,"..","migration")),q=RE6(Z),G=S0.file(CB.join(K.path,q.progress)),z=S0.file(CB.join(K.path,q.done));wE6(X,Y,K,G,z).then(async()=>{try{let F=(await R8.readdir(Y)).filter((W)=>CB.basename(W.uri.path).endsWith(".json")).length;CU1?.postMessage({migratedCount:F})}catch{CU1?.postMessage({migratedCount:0})}}).catch((U)=>{throw U})}});import{homedir as SE6}from"node:os";import SB from"node:path";import{Worker as vE6}from"node:worker_threads";async function $10(J){let Q=J.isDevelopment||!1,Z=_E6(),X=Q?"threads-development":"threads",Y=TU1(R8,Z,X),K=new P10(Y);if(!J.vscodeMigrationContext)return a.debug("Using centralized thread storage (CLI)",{storageUri:Z.toString(),storageSubdir:X}),K;let{fileSystem:q,vscodeContext:G}=J.vscodeMigrationContext,z=S0.file(SB.join(Z.path,X)),U=Q?"threads3-development":"threads3",F=S0.file(SB.join(G.globalStorageUri.path,U));if(await bE6(z,Q,F))return a.debug("Using centralized thread storage (VS Code, migration complete)",{storageUri:Z.toString(),storageSubdir:X}),K;else{a.debug("Using fallback thread storage (VS Code, migration in progress)",{centralizedStorageUri:Z.toString(),legacyStorageUri:G.globalStorageUri.toString(),storageSubdir:X,legacySubdir:U}),xE6(F,z,Q);let H=TU1(q,G.globalStorageUri,U);return kE6(K,H)}}class P10{delegate;cache=new il({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 kE6(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 _E6(){let J=process.env.XDG_DATA_HOME||SB.join(SE6(),".local","share"),Q=SB.resolve(J,"amp");return S0.file(Q)}async function bE6(J,Q,Z){let X=S0.file(SB.join(J.path,"..","migration")),Y=yE6(Q),K=S0.file(SB.join(X.path,Y.done));if(await iv(R8,K))return!0;if(Z)try{if((await R8.readdir(Z)).filter((z)=>SB.basename(z.uri.path).endsWith(".json")).length===0){if((await R8.readdir(J)).filter((F)=>SB.basename(F.uri.path).endsWith(".json")).length>0){a.info("Detected completed migration without marker, creating completion marker");try{await R8.mkdirp(X),await R8.writeFile(K,"completed")}catch(F){a.debug("Could not create migration completion marker:",F)}return!0}}}catch(q){a.debug("Could not check legacy directory for completion detection:",q)}return!1}function xE6(J,Q,Z){try{let X=new vE6(o1.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)=>{a.info("Background migration completed:",Y)}),X.on("error",(Y)=>{a.warn("Background migration failed:",Y)}),X.on("exit",(Y)=>{if(Y!==0)a.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"))a.debug("Migration worker could not be started (expected in tests):",X);else a.warn("Migration worker failed to start, migration will be skipped:",X)}}function yE6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}var T10=p(()=>{K8();A10();B0();hJ();xN();j10()});async function hR(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=fE6(J,q),z=G<0,U,F;if(K.time){let W=K.time[J],H=K.time[q],D=Date.now();if(W)U=Math.floor((D-new Date(W).getTime())/3600000);if(H)F=Math.floor((D-new Date(H).getTime())/3600000)}return a.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:z,currentVersionAge:U,latestVersionAge:F}),{hasUpdate:z,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:F,source:"npm"}}catch(Z){return a.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function fE6(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 nl=p(()=>{B0()});import{execFile as hE6}from"node:child_process";import{promises as vB}from"node:fs";import{homedir as SU1}from"node:os";import{join as Qq}from"node:path";import{promisify as gE6}from"node:util";class vU1{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 vB.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 vB.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 gR("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 vB.readFile(Q,"utf8")).split(`
142
142
  `).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 gR("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=Qq(process.cwd(),"node_modules","@sourcegraph","amp","package.json"),Q=await vB.readFile(J,"utf8"),Z=JSON.parse(Q);if(Z.version)return Z.version}catch{}try{let{stdout:J}=await gR("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 gR("yarn",["global","list","--pattern","@sourcegraph/amp","--json"],{timeout:5000}),Q=J.split(`
143
143
  `).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 gR("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 hR(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 gR("npm",["list","-g","@sourcegraph/amp"],{timeout:5000}),"global"}catch{}try{let J=Qq(process.cwd(),"node_modules","@sourcegraph","amp");return await vB.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 vB.access(Qq(process.cwd(),"pnpm-lock.yaml")),"pnpm"}catch{}try{return await vB.access(Qq(process.cwd(),"yarn.lock")),"yarn"}catch{}try{return await vB.access(Qq(process.cwd(),"package-lock.json")),"npm"}catch{}return"unknown"}getSettingsPath(){let J=process.env.XDG_CONFIG_HOME||Qq(SU1(),".config");return Qq(J,"amp","settings.json")}getSecretsPath(){let J=process.env.XDG_DATA_HOME||Qq(SU1(),".local","share");return Qq(J,"amp","secrets.json")}getLogPath(){let J=process.env.XDG_CACHE_HOME||Qq(SU1(),".cache");return Qq(J,"amp","logs","cli.log")}}var gR;var C10=p(()=>{nl();gR=gE6(hE6)});import{lookup as mE6}from"node:dns";import{promisify as uE6}from"node:util";class kU1{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 pE6(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}}var pE6;var S10=p(()=>{pE6=uE6(mE6)});import{execFile as dE6}from"node:child_process";import{promises as al}from"node:fs";import{platform as v10}from"node:os";import{promisify as cE6}from"node:util";class bU1{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:v10(),timestamp:new Date().toISOString()}}async collectTrustedCertificates(){let J={count:0,sources:[],sampleCertificates:[]};try{let Q=v10();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 _U1("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 _U1("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 _U1("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 al.stat(K);if(q.isDirectory()){let z=(await al.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 al.readFile(`${K}/${z[0]}`,"utf8"),F=this.parsePEMCertificates(U);Y.push(...F.slice(0,1))}catch{}}}else if(q.isFile()){let G=await al.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 F=this.extractCertificateChain(z);X({url:J,success:!0,certificates:F,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(`
144
144
  `),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}}var _U1;var k10=p(()=>{_U1=cE6(dE6)});function _10(J){if(!J._regex)try{J._regex=new RegExp(J.pattern,J.caseInsensitive?"gi":"g")}catch(Q){a.warn("Error compiling regex",{pattern:J.id,error:Q}),J._regex=new RegExp("$^")}return J._regex}var b10;var x10=p(()=>{B0();b10=[{id:"sourcegraph-access-token-v3",category:"sourcegraph",title:"Sourcegraph Access Token (v3)",pattern:String.raw`(sgp_(?:[a-fA-F0-9]{16}|local)_[a-fA-F0-9]{40})`,keywords:["sgp_"]},{id:"sourcegraph-access-token-v2",category:"sourcegraph",title:"Sourcegraph Access Token (v2, deprecated)",pattern:String.raw`(sgp_[a-fA-F0-9]{40})`,keywords:["sgp_"]},{id:"sourcegraph-dotcom-user-gateway",category:"sourcegraph",title:"Sourcegraph Dotcom User Gateway Access Token",pattern:String.raw`(sgd_[a-fA-F0-9]{64})`,keywords:["sgd_"]},{id:"sourcegraph-license-key",category:"sourcegraph",title:"Sourcegraph License Key Token",pattern:String.raw`(slk_[a-fA-F0-9]{64})`,keywords:["slk_"]},{id:"sourcegraph-enterprise-subscription",category:"sourcegraph",title:"Sourcegraph Enterprise subscription Token",pattern:String.raw`(sgs_[a-fA-F0-9]{64})`,keywords:["sgs_"]},{id:"sourcegraph-amp",category:"sourcegraph",title:"Sourcegraph Amp Access Token",pattern:String.raw`(sgamp_user_[A-Z0-9]{26}_[a-f0-9]{64})`,keywords:["sgamp_user_"]},{id:"sourcegraph-amp-auth-bypass",category:"sourcegraph",title:"Sourcegraph Amp Auth Bypass Token",pattern:String.raw`(sgamp_user_auth-bypass_[a-zA-Z0-9_-]+)`,keywords:["sgamp_user_auth-bypass_"]},{id:"sourcegraph-workspace-token",category:"sourcegraph",title:"Sourcegraph Workspace Access Token",pattern:String.raw`(sgp_ws[a-fA-F0-9]{32}_[a-fA-F0-9]{40})`,keywords:["sgp_ws"]},{id:"github-pat",category:"github",title:"GitHub Personal Access Token",pattern:String.raw`(ghp_[0-9a-zA-Z]{36})`,keywords:["ghp_"]},{id:"github-oauth",category:"github",title:"GitHub OAuth Access Token",pattern:String.raw`(gho_[0-9a-zA-Z]{36})`,keywords:["gho_"]},{id:"github-app-token",category:"github",title:"GitHub App Token",pattern:String.raw`((ghu|ghs)_[0-9a-zA-Z]{36})`,keywords:["ghu_","ghs_"]},{id:"github-refresh-token",category:"github",title:"GitHub Refresh Token",pattern:String.raw`(ghr_[0-9a-zA-Z]{76})`,keywords:["ghr_"]},{id:"github-fine-grained-pat",category:"github",title:"GitHub Fine-grained personal access tokens",pattern:String.raw`(github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})`,keywords:["github_pat_"]},{id:"gitlab-pat",category:"gitlab",title:"GitLab Personal Access Token",pattern:String.raw`(glpat-[0-9a-zA-Z_-]{20})`,keywords:["glpat-"]},{id:"aws-access-key-id",category:"aws",title:"AWS Access Key ID",pattern:String.raw`((A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16})`,keywords:["AKIA","AGPA","AIDA","AROA","AIPA","ANPA","ANVA","ASIA"]},{id:"hugging-face-access-token",category:"huggingface",title:"Hugging Face Access Token",pattern:String.raw`(hf_[A-Za-z0-9]{34,40})`,keywords:["hf_"]},{id:"private-key",category:"asymmetric-private-key",title:"Asymmetric Private Key",pattern:String.raw`-----\s*?BEGIN[ A-Z0-9_-]*?PRIVATE KEY( BLOCK)?\s*?-----[\s]*?([A-Za-z0-9=+/\\\\r\n][A-Za-z0-9=+/\\\\s]+)[\s]*?-----\s*?END[ A-Z0-9_-]*? PRIVATE KEY( BLOCK)?\s*?-----`,keywords:["-----"],caseInsensitive:!0},{id:"shopify-token",category:"shopify",title:"Shopify token",pattern:String.raw`(shp(ss|at|ca|pa)_[a-fA-F0-9]{32})`,keywords:["shpss_","shpat_","shpca_","shppa_"]},{id:"slack-access-token",category:"slack",title:"Slack token",pattern:String.raw`((xox[baoprs]-|xapp-|xwfp-)([0-9a-zA-Z-]{10,100}))`,keywords:["xoxb-","xoxa-","xoxp-","xoxr-","xoxs-","xoxo-","xapp-","xwfp-"]},{id:"slack-config-refresh-token",category:"slack",title:"Slack config refresh token",pattern:String.raw`(xoxe-\d-[a-zA-Z0-9]{146})`,caseInsensitive:!0,keywords:["xoxe-"]},{id:"slack-config-access-token",category:"slack",title:"Slack config access token",pattern:String.raw`(xoxe.xox[bp]-\d-[A-Z0-9]{163,166})`,caseInsensitive:!0,keywords:["xoxe.xoxb-","xoxe.xoxp-"]},{id:"slack-web-hook",category:"slack",title:"Slack Webhook",pattern:String.raw`(https:\/\/hooks\.slack\.com\/(services|triggers|workflows)\/[A-Za-z0-9+\/]{43,56})`,caseInsensitive:!0,keywords:["hooks.slack.com"]},{id:"stripe-secret-token",category:"stripe",title:"Stripe Secret Key",pattern:String.raw`(sk_(test|live)_[0-9a-z]{10,99})`,keywords:["sk_test_","sk_live_"],caseInsensitive:!0},{id:"supabase-service-key",category:"supabase",title:"Supabase Service Key",pattern:String.raw`(sbp_[a-fA-F0-9]{40})`,keywords:["sbp_"]},{id:"pypi-upload-token",category:"pypi",title:"PyPI upload token",pattern:String.raw`(pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,1000})`,keywords:["pypi-AgEIcHlwaS5vcmc"]},{id:"gcp-service-account",category:"google",title:"Google (GCP) Service-account",pattern:String.raw`("type": "service_account")`,keywords:['"type": "service_account"']},{id:"heroku-api-key",category:"heroku",title:"Heroku API Key",pattern:String.raw`(?:heroku[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](\d[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})['"]`,keywords:["heroku"],caseInsensitive:!0},{id:"twilio-api-key",category:"twilio",title:"Twilio API Key",pattern:String.raw`(SK[0-9a-fA-F]{32})`,keywords:["SK"]},{id:"age-secret-key",category:"age",title:"Age secret key",pattern:String.raw`(AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58})`,keywords:["AGE-SECRET-KEY-1"]},{id:"jwt-token",category:"jwt",title:"JWT token",pattern:String.raw`(ey[a-zA-Z0-9]{17,}\.ey[a-zA-Z0-9/\\_-]{17,}\.(?:[a-zA-Z0-9/\\_-]{10,}={0,2})?)`,keywords:[".eyJ"]},{id:"npm-access-token",category:"npm",title:"npm access token",pattern:String.raw`(npm_[a-z0-9]{36})`,keywords:["npm_"],caseInsensitive:!0},{id:"sendgrid-api-token",category:"sendgrid",title:"SendGrid API token",pattern:String.raw`(SG\.[a-z0-9_.-]{66})`,keywords:["SG."],caseInsensitive:!0},{id:"aws-secret-access-key",category:"aws",title:"AWS Secret Access Key",pattern:String.raw`(aws[_-]secret[_-]access[_-]key[_-][A-Za-z0-9/+=]{40})`,keywords:["key"],caseInsensitive:!0},{id:"dockerconfig-secret",category:"docker",title:"Dockerconfig secret exposed",pattern:String.raw`((\.dockerconfigjson|dockercfg):\s*\|*\s*((ey|ew)+[A-Za-z0-9/+=]+))`,keywords:["dockerc"],caseInsensitive:!0},{id:"linear-api-token",category:"linear",title:"Linear API token",pattern:String.raw`(lin_api_[a-z0-9]{40})`,keywords:["lin_api_"],caseInsensitive:!0},{id:"sendinblue-api-token",category:"sendinblue",title:"Sendinblue API token",pattern:String.raw`(xkeysib-[a-f0-9]{64}-[a-z0-9]{16})`,keywords:["xkeysib-"],caseInsensitive:!0},{id:"planetscale-api-token",category:"planetscale",title:"PlanetScale API token",pattern:String.raw`(pscale_tkn_[a-z0-9_.-]{43})`,keywords:["pscale_tkn_"],caseInsensitive:!0},{id:"doppler-api-token",category:"doppler",title:"Doppler API token",pattern:String.raw`(dp\.pt\.[a-z0-9]{43})`,keywords:["dp.pt."],caseInsensitive:!0},{id:"discord-api-token",category:"discord",title:"Discord API key",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{64})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"pulumi-api-token",category:"pulumi",title:"Pulumi API token",pattern:String.raw`(pul-[a-f0-9]{40})`,keywords:["pul-"]},{id:"postman-api-token",category:"postman",title:"Postman API token",pattern:String.raw`(PMAK-[a-f0-9]{24}-[a-f0-9]{34})`,keywords:["PMAK-"],caseInsensitive:!0},{id:"facebook-token",category:"facebook",title:"Facebook token",pattern:String.raw`(?:facebook[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["facebook"],caseInsensitive:!0},{id:"twitter-token",category:"twitter",title:"Twitter token",pattern:String.raw`(?:twitter[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{35,44})['"]`,keywords:["twitter"],caseInsensitive:!0},{id:"adobe-client-id",category:"adobe",title:"Adobe Client ID (Oauth Web)",pattern:String.raw`(?:adobe[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["adobe"],caseInsensitive:!0},{id:"adobe-client-secret",category:"adobe",title:"Adobe Client Secret",pattern:String.raw`(p8e-[a-z0-9]{32})`,keywords:["p8e-"],caseInsensitive:!0},{id:"alibaba-access-key-id",category:"alibaba",title:"Alibaba AccessKey ID",pattern:String.raw`((LTAI)[a-z0-9]{20})`,keywords:["LTAI"],caseInsensitive:!0},{id:"alibaba-secret-key",category:"alibaba",title:"Alibaba Secret Key",pattern:String.raw`(?:alibaba[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{30})['"]`,keywords:["alibaba"],caseInsensitive:!0},{id:"asana-client-id",category:"asana",title:"Asana Client ID",pattern:String.raw`(?:asana[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([0-9]{16})['"]`,keywords:["asana"],caseInsensitive:!0},{id:"asana-client-secret",category:"asana",title:"Asana Client Secret",pattern:String.raw`(?:asana[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{32})['"]`,keywords:["asana"],caseInsensitive:!0},{id:"atlassian-api-token",category:"atlassian",title:"Atlassian API token",pattern:String.raw`(?:atlassian[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{24})['"]`,keywords:["atlassian"],caseInsensitive:!0},{id:"bitbucket-client-id",category:"bitbucket",title:"Bitbucket client ID",pattern:String.raw`(?:bitbucket[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{32})['"]`,keywords:["bitbucket"],caseInsensitive:!0},{id:"bitbucket-client-secret",category:"bitbucket",title:"Bitbucket client secret",pattern:String.raw`(?:bitbucket[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9_-]{64})['"]`,keywords:["bitbucket"],caseInsensitive:!0},{id:"beamer-api-token",category:"beamer",title:"Beamer API token",pattern:String.raw`(?:beamer[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](b_[a-z0-9=_-]{44})['"]`,keywords:["beamer"],caseInsensitive:!0},{id:"buildkite-agent-token",category:"buildkite",title:"Buildkite API Token V2",pattern:String.raw`(bkua_[a-fA-F0-9]{40})`,keywords:["bkua_"]},{id:"clojars-api-token",category:"clojars",title:"Clojars API token",pattern:String.raw`(CLOJARS_[a-z0-9]{60})`,keywords:["CLOJARS_"],caseInsensitive:!0},{id:"contentful-delivery-api-token",category:"contentful-delivery",title:"Contentful delivery API token",pattern:String.raw`(?:contentful[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{43})['"]`,keywords:["contentful"],caseInsensitive:!0},{id:"databricks-api-token",category:"databricks",title:"Databricks API token",pattern:String.raw`(dapi[a-h0-9]{32})`,keywords:["dapi"]},{id:"discord-client-id",category:"discord",title:"Discord client ID",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([0-9]{18})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"discord-client-secret",category:"discord",title:"Discord client secret",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{32})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"dropbox-api-secret",category:"dropbox",title:"Dropbox API secret/key",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{15})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"dropbox-short-lived-api-token",category:"dropbox",title:"Dropbox short lived API token",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](sl\.[a-z0-9=_-]{135})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"dropbox-long-lived-api-token",category:"dropbox",title:"Dropbox long lived API token",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{11}(AAAAAAAAAA)[a-z0-9_=-]{43})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"duffel-api-token",category:"duffel",title:"Duffel API token",pattern:String.raw`(duffel_(test|live)_[a-z0-9_-]{43})`,keywords:["duffel_test_","duffel_live_"],caseInsensitive:!0},{id:"dynatrace-api-token",category:"dynatrace",title:"Dynatrace API token",pattern:String.raw`(dt0c01\.[a-z0-9]{24}\.[a-z0-9]{64})`,keywords:["dt0c01."],caseInsensitive:!0},{id:"easypost-api-token",category:"easypost",title:"EasyPost API token",pattern:String.raw`(EZ[AT]K[a-z0-9]{54})`,keywords:["EZAK","EZAT"],caseInsensitive:!0},{id:"fastly-api-token",category:"fastly",title:"Fastly API token",pattern:String.raw`(?:fastly[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{32})['"]`,keywords:["fastly"],caseInsensitive:!0},{id:"finicity-client-secret",category:"finicity",title:"Finicity client secret",pattern:String.raw`(?:finicity[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{20})['"]`,keywords:["finicity"],caseInsensitive:!0},{id:"finicity-api-token",category:"finicity",title:"Finicity API token",pattern:String.raw`(?:finicity[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["finicity"],caseInsensitive:!0},{id:"flutterwave-public-key",category:"flutterwave",title:"Flutterwave public/secret key",pattern:String.raw`(FLW(PUB|SEC)K_TEST-[a-h0-9]{32}-X)`,keywords:["FLWSECK_TEST-","FLWPUBK_TEST-"],caseInsensitive:!0},{id:"flutterwave-enc-key",category:"flutterwave",title:"Flutterwave encrypted key",pattern:String.raw`(FLWSECK_TEST[a-h0-9]{12})`,keywords:["FLWSECK_TEST"]},{id:"frameio-api-token",category:"frameio",title:"Frame.io API token",pattern:String.raw`(fio-u-[a-z0-9_=-]{64})`,keywords:["fio-u-"],caseInsensitive:!0},{id:"gocardless-api-token",category:"gocardless",title:"GoCardless API token",pattern:String.raw`(live_[a-z0-9_=-]{40})`,keywords:["live_"],caseInsensitive:!0},{id:"grafana-api-token",category:"grafana",title:"Grafana API token",pattern:String.raw`(eyJrIjoi[a-z0-9_=-]{72,92})`,keywords:["eyJrIjoi"],caseInsensitive:!0},{id:"hashicorp-tf-api-token",category:"hashicorp",title:"HashiCorp Terraform user/org API token",pattern:String.raw`([a-z0-9]{14}\.atlasv1\.[a-z0-9_=-]{60,70})`,keywords:["atlasv1."],caseInsensitive:!0},{id:"hubspot-api-token",category:"hubspot",title:"HubSpot API token",pattern:String.raw`(?:hubspot[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["hubspot"],caseInsensitive:!0},{id:"intercom-api-token",category:"intercom",title:"Intercom API token",pattern:String.raw`(?:intercom[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_]{60})['"]`,keywords:["intercom"],caseInsensitive:!0},{id:"intercom-client-secret",category:"intercom",title:"Intercom client secret/ID",pattern:String.raw`(?:intercom[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["intercom"],caseInsensitive:!0},{id:"ionic-api-token",category:"ionic",title:"Ionic API token",pattern:String.raw`(?:ionic[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](ion_[a-z0-9]{42})['"]`,keywords:["ionic"],caseInsensitive:!0},{id:"linear-client-secret",category:"linear",title:"Linear client secret/ID",pattern:String.raw`(?:linear[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["linear"],caseInsensitive:!0},{id:"lob-api-key",category:"lob",title:"Lob API Key",pattern:String.raw`(?:lob[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]((live|test)_[a-f0-9]{35})['"]`,keywords:["lob"],caseInsensitive:!0},{id:"mailchimp-api-key",category:"mailchimp",title:"Mailchimp API key",pattern:String.raw`(?:mailchimp[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32}-us20)['"]`,keywords:["mailchimp"],caseInsensitive:!0},{id:"mailgun-token",category:"mailgun",title:"Mailgun private API token",pattern:String.raw`(?:mailgun[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]((pub)?key-[a-f0-9]{32})['"]`,keywords:["mailgun"],caseInsensitive:!0},{id:"mailgun-signing-key",category:"mailgun",title:"Mailgun webhook signing key",pattern:String.raw`(?:mailgun[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8})['"]`,keywords:["mailgun"],caseInsensitive:!0},{id:"mapbox-api-token",category:"mapbox",title:"Mapbox API token",pattern:String.raw`(pk\.[a-z0-9]{60}\.[a-z0-9]{22})`,keywords:["pk."],caseInsensitive:!0},{id:"messagebird-api-token",category:"messagebird",title:"MessageBird API token",pattern:String.raw`(?:messagebird[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{25})['"]`,keywords:["messagebird"],caseInsensitive:!0},{id:"messagebird-client-id",category:"messagebird",title:"MessageBird API client ID",pattern:String.raw`(?:messagebird[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["messagebird"],caseInsensitive:!0},{id:"new-relic-user-api-key",category:"newrelic",title:"New Relic user API Key",pattern:String.raw`(NRAK-[A-Z0-9]{27})`,keywords:["NRAK-"]},{id:"new-relic-user-api-id",category:"newrelic",title:"New Relic user API ID",pattern:String.raw`(?:newrelic[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([A-Z0-9]{64})['"]`,keywords:["newrelic"],caseInsensitive:!0},{id:"new-relic-browser-api-token",category:"newrelic",title:"New Relic ingest browser API token",pattern:String.raw`(NRJS-[a-f0-9]{19})`,keywords:["NRJS-"]},{id:"planetscale-password",category:"planetscale",title:"PlanetScale password",pattern:String.raw`(pscale_pw_[a-z0-9_.-]{43})`,keywords:["pscale_pw_"],caseInsensitive:!0},{id:"private-packagist-token",category:"private-packagist",title:"Private Packagist token",pattern:String.raw`(packagist_[ou][ru]t_[a-f0-9]{68})`,keywords:["packagist_uut_","packagist_ort_","packagist_out_"],caseInsensitive:!0},{id:"rubygems-api-token",category:"rubygems",title:"Rubygem API token",pattern:String.raw`(rubygems_[a-f0-9]{48})`,keywords:["rubygems_"]},{id:"shippo-api-token",category:"shippo",title:"Shippo API token",pattern:String.raw`(shippo_(live|test)_[a-f0-9]{40})`,keywords:["shippo_live_","shippo_test_"]},{id:"linkedin-client-secret",category:"linkedin",title:"LinkedIn Client secret",pattern:String.raw`(?:linkedin[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z]{16})['"]`,keywords:["linkedin"],caseInsensitive:!0},{id:"linkedin-client-id",category:"linkedin",title:"LinkedIn Client ID",pattern:String.raw`(?:linkedin[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{14})['"]`,keywords:["linkedin"],caseInsensitive:!0},{id:"twitch-api-token",category:"twitch",title:"Twitch API token",pattern:String.raw`(?:twitch[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{30})['"]`,keywords:["twitch"],caseInsensitive:!0},{id:"typeform-api-token",category:"typeform",title:"Typeform API token",pattern:String.raw`(?:typeform[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}(tfp_[a-z0-9_.=-]{59})`,keywords:["typeform"],caseInsensitive:!0},{id:"todoist-api-token",category:"todoist",title:"Todoist API token",pattern:String.raw`(?:todoist[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:)[\s'"]{0,3}([0-9a-f]{40})`,keywords:["todoist"],caseInsensitive:!0},{id:"openai-api-key",category:"openai",title:"OpenAI API Key",pattern:String.raw`(sk-[a-zA-Z0-9]{50})`,caseInsensitive:!1,keywords:["sk-"]},{id:"openai-api-key-project",category:"openai",title:"OpenAI Project-scoped API Key",pattern:String.raw`(sk-proj-[A-Za-z0-9]{24}-[A-Za-z0-9]{40,128})`,caseInsensitive:!0,keywords:["sk-proj-"]},{id:"openai-api-key-env",category:"openai",title:"OpenAI Environment-scoped API Key",pattern:String.raw`(sk-(?:live|test)-[A-Za-z0-9]{24}-[A-Za-z0-9]{40,128})`,caseInsensitive:!0,keywords:["sk-live-","sk-test-"]},{id:"anthropic-api-key",category:"anthropic",title:"Anthropic API Key",pattern:String.raw`(sk-ant-([a-zA-Z0-9]{1,10}-)?[a-zA-Z0-9_-]{32,128})`,caseInsensitive:!1,keywords:["sk-ant-"]},{id:"canva-token",category:"canva",title:"Canva Token",pattern:String.raw`\b(cnv[a-z0-9]{2}[A-Za-z0-9_=-]+[a-f0-9]{8})\b`,caseInsensitive:!1,keywords:["cnv"]},{id:"api-key",category:"unknown",title:"Unknown API Key",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}api[-_](?:key|token)(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token))[a-z0-9+/_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["api-key","api_key","api-token","api_token"],caseInsensitive:!0},{id:"webhook-secret",category:"unknown",title:"Unknown Webhook Secret",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}webhook[-_]secret(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token|webhook))[a-z0-9+/=_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["webhook-secret","webhook_secret"],caseInsensitive:!0},{id:"password",category:"unknown",title:"Unknown Password",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}password(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token|password|pass|pwd))[a-z0-9+/=_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["password"],caseInsensitive:!0},{id:"sk-secret",category:"unknown",title:"Unknown SK Secret",pattern:String.raw`(?:^|['"\s])(sk(?:[-_][a-z0-9]{1,10})?[-_][a-z0-9]{10,99})(?:$|['"\s])`,caseInsensitive:!0,keywords:["sk-","sk_"]}]});function iE6(J){if(!J||typeof J!=="string")return J;let Q=J.replace(lE6,"");if(Q.length!==J.length){let Z=J.length-Q.length;a.info("Invisible Unicode tag characters removed during sanitization",{removedCount:Z})}return Q}function nE6(J){if(!J||typeof J!=="string")return J;let Q=iE6(J);for(let Z of b10){if(!Z.keywords.some((Y)=>Z.caseInsensitive?Q.toLowerCase().includes(Y.toLowerCase()):Q.includes(Y)))continue;let X=_10(Z);Q=Q.replace(X,(Y,K)=>{return Y.replace(K,`[REDACTED:${Z.id}]`)})}return Q}function rl(J,Q){if(!J||typeof J==="number"||typeof J==="boolean")return J;if(typeof J==="string")return Q(J);if(Array.isArray(J))return J.map((Z)=>{if(typeof Z==="string")return Q(Z);else if(Z&&typeof Z==="object")return rl(Z,Q);return Z});if(J&&typeof J==="object"){if("type"in J&&(J.type==="base64"||J.type==="image")&&"data"in J)return{...J};if("isImage"in J&&J.isImage===!0&&"content"in J&&typeof J.content==="string"){let Z={};for(let[X,Y]of Object.entries(J))if(X==="content")Z[X]=Y;else Z[X]=rl(Y,Q);return Z}}return Object.fromEntries(Object.entries(J).map(([Z,X])=>[Z,rl(X,Q)]))}function mR(J){return rl(J,nE6)}var lE6;var xU1=p(()=>{B0();x10();lE6=/[\uDB40][\uDC00-\uDC7F]/g});import{execFile as aE6}from"node:child_process";import{promises as rE6}from"node:fs";import{arch as sE6,cpus as oE6,freemem as tE6,platform as sl,release as eE6,totalmem as J$6}from"node:os";import{promisify as Q$6}from"node:util";class fU1{async collect(){let J=oE6(),Q=J$6(),Z=tE6(),X={architecture:sE6(),cpu:{cores:J.length,model:J[0]?.model||"Unknown",speed:J[0]?.speed||0},environment:await(async()=>{let[Y,K,q,G,z,U,F,W,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:F,rgSystem:W,yarn:H}})(),memory:{free:Z,total:Q,used:Q-Z},platform:sl(),version:eE6()};try{let Y=await this.getDiskSpace();if(Y)X.diskSpace=Y}catch{}return X}async findExecutablePath(J){try{if(sl()==="win32"){let{stdout:Z}=await yU1("where",[J],{timeout:5000});return Z.trim().split(`
@@ -5440,7 +5440,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||QR}function iJ6(J,Q){let
5440
5440
  `);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),F;if(dJ6()){let W=[];for await(let H of process.stdin)W.push(H);F=Buffer.concat(W).toString("utf-8").trim()}await uJ6({toolName:X,rawArgs:U,stdinInput:F,only:Y.only,threadDeps:G,stdout:process.stdout,stderr:process.stderr,exit:(W)=>{z=W}}),await G.asyncDispose(),G.cleanupTerminal(),process.exit(z)})}var nJ6=p(()=>{yS();WV();$J6();SJ6();kJ6();cJ6()});function aJ6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}import R29 from"node:fs";import rJ6 from"node:path";function sJ6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!rJ6.isAbsolute(Q))return null;return a.debug("Extracted image path",{original:J,extracted:Q}),Q}function oJ6(J){try{let Q=rJ6.extname(J).toLowerCase(),Z=Eo1(Q);if(!Z)return a.warn("Unsupported image file extension",{ext:Q}),null;try{let X=R29.readFileSync(J);return w29(X,Z)}catch(X){a.error(`Failed to read image file ${J}:`,X)}}catch(Q){a.error("Error handling image file path",{imagePath:J,error:Q})}return null}function w29(J,Q){if(J.length>NR)return a.warn(`Image file too large: ${J.length} bytes (max: ${NR})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}var tJ6=p(()=>{B0();TN()});function eJ6(J){return J.kind==="executable"}function JQ6(J){return J.kind==="markdown"}import{spawn as I29}from"node:child_process";import{promises as E29}from"node:fs";async function tb1(J,Q,Z,X={}){let{timeoutMs:Y=QQ6,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(a.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),JQ6(q))return await $29(q,Q);else if(eJ6(q))return await P29(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return a.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function $29(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await E29.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>jH?Z.slice(0,jH)+`
5441
5441
  ... (output truncated at ${jH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function P29(J,Q,Z=QQ6,X){return new Promise((Y)=>{let[K,q]=T29(J,Q);a.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=jo1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),a.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),F=I29(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),W=[],H=[],D=0;F.stdout?.on("data",(M)=>{let V=M.toString();if(D+=V.length,D<=jH)W.push(V);else{let N=jH-(D-V.length);if(N>0)W.push(V.slice(0,N))}}),F.stderr?.on("data",(M)=>{let V=M.toString();if(D+=V.length,D<=jH)H.push(V);else{let N=jH-(D-V.length);if(N>0)H.push(V.slice(0,N))}}),F.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:W.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:W.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=W.join(""),L=H.join(""),O=N;if(!V&&!N.trim()&&L.trim())O=L;else if(L.trim())O+=N?`
5442
5442
  ${L}`:L;if(D>jH)O+=`
5443
- ... (output truncated at ${jH} characters)`;Y({success:V,output:O.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),F.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:W.join(""),error:V})})})}function T29(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return S29(Z,X?[...X]:null,Y,Q);else return C29(Z,X?[...X]:null,Y,Q)}function C29(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function S29(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]}}var jH=50000,QQ6=300000;var ZQ6=p(()=>{MR();B0()});var XQ6=p(()=>{ZQ6();lJ1()});var k41,mz2,uz2,pz2,dz2,cz2,lz2,iz2,nz2,az2,dm,rz2,sz2,oz2,tz2,ez2;var YQ6=p(()=>{k41=globalThis.window?.document!==void 0,mz2=globalThis.process?.versions?.node!==void 0,uz2=globalThis.process?.versions?.bun!==void 0,pz2=globalThis.Deno?.version?.deno!==void 0,dz2=globalThis.process?.versions?.electron!==void 0,cz2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,lz2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,iz2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,nz2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,az2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,dm=globalThis.navigator?.userAgentData?.platform,rz2=dm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",sz2=dm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",oz2=dm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",tz2=dm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),ez2=dm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var _41={};N6(_41,{scrollUp:()=>s29,scrollDown:()=>o29,link:()=>X49,image:()=>Y49,iTerm:()=>K49,exitAlternativeScreen:()=>Q49,eraseUp:()=>r29,eraseStartLine:()=>n29,eraseScreen:()=>eb1,eraseLines:()=>l29,eraseLine:()=>zQ6,eraseEndLine:()=>i29,eraseDown:()=>a29,enterAlternativeScreen:()=>J49,cursorUp:()=>qQ6,cursorTo:()=>_29,cursorShow:()=>c29,cursorSavePosition:()=>h29,cursorRestorePosition:()=>g29,cursorPrevLine:()=>p29,cursorNextLine:()=>u29,cursorMove:()=>b29,cursorLeft:()=>GQ6,cursorHide:()=>d29,cursorGetPosition:()=>m29,cursorForward:()=>y29,cursorDown:()=>x29,cursorBackward:()=>f29,clearTerminal:()=>e29,clearScreen:()=>t29,beep:()=>Z49});import Jx1 from"node:process";var z2="\x1B[",lm="\x1B]",ST="\x07",cm=";",KQ6,v29,k29,_29=(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"},b29=(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},qQ6=(J=1)=>z2+J+"A",x29=(J=1)=>z2+J+"B",y29=(J=1)=>z2+J+"C",f29=(J=1)=>z2+J+"D",GQ6,h29,g29,m29,u29,p29,d29,c29,l29=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=zQ6+(Z<J-1?qQ6():"");if(J)Q+=GQ6;return Q},i29,n29,zQ6,a29,r29,eb1,s29,o29,t29="\x1Bc",e29,J49,Q49,Z49,X49=(J,Q)=>[lm,"8",cm,cm,Q,ST,J,lm,"8",cm,cm,ST].join(""),Y49=(J,Q={})=>{let Z=`${lm}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")+ST},K49;var Qx1=p(()=>{YQ6();KQ6=!k41&&Jx1.env.TERM_PROGRAM==="Apple_Terminal",v29=!k41&&Jx1.platform==="win32",k29=k41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Jx1.cwd,GQ6=z2+"G",h29=KQ6?"\x1B7":z2+"s",g29=KQ6?"\x1B8":z2+"u",m29=z2+"6n",u29=z2+"E",p29=z2+"F",d29=z2+"?25l",c29=z2+"?25h",i29=z2+"K",n29=z2+"1K",zQ6=z2+"2K",a29=z2+"J",r29=z2+"1J",eb1=z2+"2J",s29=z2+"S",o29=z2+"T",e29=v29?`${eb1}${z2}0f`:`${eb1}${z2}3J${z2}H`,J49=z2+"?1049h",Q49=z2+"?1049l",Z49=ST,K49={setCwd:(J=k29())=>`${lm}50;CurrentDir=${J}${ST}`,annotation(J,Q={}){let Z=`${lm}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+ST}}});var UQ6=p(()=>{Qx1();Qx1()});var Zx1=e((KU2,FQ6)=>{FQ6.exports=(J,Q=process.argv)=>{let Z=J.startsWith("-")?"":J.length===1?"-":"--",X=Q.indexOf(Z+J),Y=Q.indexOf("--");return X!==-1&&(Y===-1||X<Y)}});var BQ6=e((qU2,HQ6)=>{var q49=o1("os"),WQ6=o1("tty"),_K=Zx1(),{env:o5}=process,jV;if(_K("no-color")||_K("no-colors")||_K("color=false")||_K("color=never"))jV=0;else if(_K("color")||_K("colors")||_K("color=true")||_K("color=always"))jV=1;if("FORCE_COLOR"in o5)if(o5.FORCE_COLOR==="true")jV=1;else if(o5.FORCE_COLOR==="false")jV=0;else jV=o5.FORCE_COLOR.length===0?1:Math.min(parseInt(o5.FORCE_COLOR,10),3);function Xx1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function Yx1(J,Q){if(jV===0)return 0;if(_K("color=16m")||_K("color=full")||_K("color=truecolor"))return 3;if(_K("color=256"))return 2;if(J&&!Q&&jV===void 0)return 0;let Z=jV||0;if(o5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=q49.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in o5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in o5))||o5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in o5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o5.TEAMCITY_VERSION)?1:0;if(o5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in o5){let X=parseInt((o5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(o5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o5.TERM))return 1;if("COLORTERM"in o5)return 1;return Z}function G49(J){let Q=Yx1(J,J&&J.isTTY);return Xx1(Q)}HQ6.exports={supportsColor:G49,stdout:Xx1(Yx1(!0,WQ6.isatty(1))),stderr:Xx1(Yx1(!0,WQ6.isatty(2)))}});var VQ6=e((GU2,MQ6)=>{var z49=BQ6(),vT=Zx1();function DQ6(J){if(/^\d{3,4}$/.test(J)){let Z=/(\d{1,2})(\d{2})/.exec(J)||[];return{major:0,minor:parseInt(Z[1],10),patch:parseInt(Z[2],10)}}let Q=(J||"").split(".").map((Z)=>parseInt(Z,10));return{major:Q[0],minor:Q[1],patch:Q[2]}}function Kx1(J){let{CI:Q,FORCE_HYPERLINK:Z,NETLIFY:X,TEAMCITY_VERSION:Y,TERM_PROGRAM:K,TERM_PROGRAM_VERSION:q,VTE_VERSION:G,TERM:z}=process.env;if(Z)return!(Z.length>0&&parseInt(Z,10)===0);if(vT("no-hyperlink")||vT("no-hyperlinks")||vT("hyperlink=false")||vT("hyperlink=never"))return!1;if(vT("hyperlink=true")||vT("hyperlink=always"))return!0;if(X)return!0;if(!z49.supportsColor(J))return!1;if(J&&!J.isTTY)return!1;if("WT_SESSION"in process.env)return!0;if(process.platform==="win32")return!1;if(Q)return!1;if(Y)return!1;if(K){let U=DQ6(q||"");switch(K){case"iTerm.app":if(U.major===3)return U.minor>=1;return U.major>3;case"WezTerm":return U.major>=20200620;case"vscode":return U.major>1||U.major===1&&U.minor>=72;case"ghostty":return!0}}if(G){if(G==="0.50.0")return!1;let U=DQ6(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}MQ6.exports={supportsHyperlink:Kx1,stdout:Kx1(process.stdout),stderr:Kx1(process.stderr)}});function RV(J,Q,{target:Z="stdout",...X}={}){if(!b41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return _41.link(J,Q)}var b41;var NQ6=p(()=>{UQ6();b41=u6(VQ6(),1);RV.isSupported=b41.default.stdout;RV.stderr=(J,Q,Z={})=>RV(J,Q,{target:"stderr",...Z});RV.stderr.isSupported=b41.default.stderr});class qx1{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.1759132892-gf2cb87"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await M10(Q)}catch(Q){a.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}}var LQ6=p(()=>{B0();PB()});class zY{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function OQ6(J){if(J instanceof x41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof zY)return{title:"Info",description:J.message,type:"info"};return a.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 x41;var Gx1=p(()=>{B0();x41=class x41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}});import{execSync as AQ6}from"node:child_process";import{rmdir as U49}from"node:fs/promises";import{tmpdir as F49}from"node:os";import jQ6 from"node:path";import{mkdtemp as W49,readFile as H49,unlink as B49,writeFile as _U2}from"fs/promises";class zx1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=BC()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new qx1(async()=>{try{return(await A9()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),Q2.pipe(g0((Q)=>Q.settings["internal.modes"]),d8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...D49},J)Object.assign(this.commands,M49)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{a.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await tb1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.worker.handle({type:"user:message",message:{content:[{type:"text",text:q.output}]}});return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var D49,M49;var RQ6=p(()=>{XQ6();B0();V4();DC();dw();p4();lU();nb1();PB();qD();K8();i0();NQ6();$41();ab1();LQ6();Gx1();D49={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${h5} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:xY0}]}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new x41;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread()}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await W49(jQ6.join(F49(),"amp-edit-")),Y=jQ6.join(X,"message.amp.md");AQ6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await H49(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return a.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await B49(Y),await U49(X)}catch(K){a.warn("Failed to clean up temporary file",K)}return}catch(Z){return a.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return uU("dangerouslyAllowAll",!1),new zY("Amp is now following permissions rules for this session")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return uU("dangerouslyAllowAll",!0),new zY("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await TT();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw a.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:TT};await S41(Y);return}catch(Y){a.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return a.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new zY(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return a.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
5443
+ ... (output truncated at ${jH} characters)`;Y({success:V,output:O.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),F.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:W.join(""),error:V})})})}function T29(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return S29(Z,X?[...X]:null,Y,Q);else return C29(Z,X?[...X]:null,Y,Q)}function C29(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function S29(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]}}var jH=50000,QQ6=300000;var ZQ6=p(()=>{MR();B0()});var XQ6=p(()=>{ZQ6();lJ1()});var k41,mz2,uz2,pz2,dz2,cz2,lz2,iz2,nz2,az2,dm,rz2,sz2,oz2,tz2,ez2;var YQ6=p(()=>{k41=globalThis.window?.document!==void 0,mz2=globalThis.process?.versions?.node!==void 0,uz2=globalThis.process?.versions?.bun!==void 0,pz2=globalThis.Deno?.version?.deno!==void 0,dz2=globalThis.process?.versions?.electron!==void 0,cz2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,lz2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,iz2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,nz2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,az2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,dm=globalThis.navigator?.userAgentData?.platform,rz2=dm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",sz2=dm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",oz2=dm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",tz2=dm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),ez2=dm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var _41={};N6(_41,{scrollUp:()=>s29,scrollDown:()=>o29,link:()=>X49,image:()=>Y49,iTerm:()=>K49,exitAlternativeScreen:()=>Q49,eraseUp:()=>r29,eraseStartLine:()=>n29,eraseScreen:()=>eb1,eraseLines:()=>l29,eraseLine:()=>zQ6,eraseEndLine:()=>i29,eraseDown:()=>a29,enterAlternativeScreen:()=>J49,cursorUp:()=>qQ6,cursorTo:()=>_29,cursorShow:()=>c29,cursorSavePosition:()=>h29,cursorRestorePosition:()=>g29,cursorPrevLine:()=>p29,cursorNextLine:()=>u29,cursorMove:()=>b29,cursorLeft:()=>GQ6,cursorHide:()=>d29,cursorGetPosition:()=>m29,cursorForward:()=>y29,cursorDown:()=>x29,cursorBackward:()=>f29,clearTerminal:()=>e29,clearScreen:()=>t29,beep:()=>Z49});import Jx1 from"node:process";var z2="\x1B[",lm="\x1B]",ST="\x07",cm=";",KQ6,v29,k29,_29=(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"},b29=(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},qQ6=(J=1)=>z2+J+"A",x29=(J=1)=>z2+J+"B",y29=(J=1)=>z2+J+"C",f29=(J=1)=>z2+J+"D",GQ6,h29,g29,m29,u29,p29,d29,c29,l29=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=zQ6+(Z<J-1?qQ6():"");if(J)Q+=GQ6;return Q},i29,n29,zQ6,a29,r29,eb1,s29,o29,t29="\x1Bc",e29,J49,Q49,Z49,X49=(J,Q)=>[lm,"8",cm,cm,Q,ST,J,lm,"8",cm,cm,ST].join(""),Y49=(J,Q={})=>{let Z=`${lm}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")+ST},K49;var Qx1=p(()=>{YQ6();KQ6=!k41&&Jx1.env.TERM_PROGRAM==="Apple_Terminal",v29=!k41&&Jx1.platform==="win32",k29=k41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Jx1.cwd,GQ6=z2+"G",h29=KQ6?"\x1B7":z2+"s",g29=KQ6?"\x1B8":z2+"u",m29=z2+"6n",u29=z2+"E",p29=z2+"F",d29=z2+"?25l",c29=z2+"?25h",i29=z2+"K",n29=z2+"1K",zQ6=z2+"2K",a29=z2+"J",r29=z2+"1J",eb1=z2+"2J",s29=z2+"S",o29=z2+"T",e29=v29?`${eb1}${z2}0f`:`${eb1}${z2}3J${z2}H`,J49=z2+"?1049h",Q49=z2+"?1049l",Z49=ST,K49={setCwd:(J=k29())=>`${lm}50;CurrentDir=${J}${ST}`,annotation(J,Q={}){let Z=`${lm}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+ST}}});var UQ6=p(()=>{Qx1();Qx1()});var Zx1=e((KU2,FQ6)=>{FQ6.exports=(J,Q=process.argv)=>{let Z=J.startsWith("-")?"":J.length===1?"-":"--",X=Q.indexOf(Z+J),Y=Q.indexOf("--");return X!==-1&&(Y===-1||X<Y)}});var BQ6=e((qU2,HQ6)=>{var q49=o1("os"),WQ6=o1("tty"),_K=Zx1(),{env:o5}=process,jV;if(_K("no-color")||_K("no-colors")||_K("color=false")||_K("color=never"))jV=0;else if(_K("color")||_K("colors")||_K("color=true")||_K("color=always"))jV=1;if("FORCE_COLOR"in o5)if(o5.FORCE_COLOR==="true")jV=1;else if(o5.FORCE_COLOR==="false")jV=0;else jV=o5.FORCE_COLOR.length===0?1:Math.min(parseInt(o5.FORCE_COLOR,10),3);function Xx1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function Yx1(J,Q){if(jV===0)return 0;if(_K("color=16m")||_K("color=full")||_K("color=truecolor"))return 3;if(_K("color=256"))return 2;if(J&&!Q&&jV===void 0)return 0;let Z=jV||0;if(o5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=q49.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in o5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in o5))||o5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in o5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o5.TEAMCITY_VERSION)?1:0;if(o5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in o5){let X=parseInt((o5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(o5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o5.TERM))return 1;if("COLORTERM"in o5)return 1;return Z}function G49(J){let Q=Yx1(J,J&&J.isTTY);return Xx1(Q)}HQ6.exports={supportsColor:G49,stdout:Xx1(Yx1(!0,WQ6.isatty(1))),stderr:Xx1(Yx1(!0,WQ6.isatty(2)))}});var VQ6=e((GU2,MQ6)=>{var z49=BQ6(),vT=Zx1();function DQ6(J){if(/^\d{3,4}$/.test(J)){let Z=/(\d{1,2})(\d{2})/.exec(J)||[];return{major:0,minor:parseInt(Z[1],10),patch:parseInt(Z[2],10)}}let Q=(J||"").split(".").map((Z)=>parseInt(Z,10));return{major:Q[0],minor:Q[1],patch:Q[2]}}function Kx1(J){let{CI:Q,FORCE_HYPERLINK:Z,NETLIFY:X,TEAMCITY_VERSION:Y,TERM_PROGRAM:K,TERM_PROGRAM_VERSION:q,VTE_VERSION:G,TERM:z}=process.env;if(Z)return!(Z.length>0&&parseInt(Z,10)===0);if(vT("no-hyperlink")||vT("no-hyperlinks")||vT("hyperlink=false")||vT("hyperlink=never"))return!1;if(vT("hyperlink=true")||vT("hyperlink=always"))return!0;if(X)return!0;if(!z49.supportsColor(J))return!1;if(J&&!J.isTTY)return!1;if("WT_SESSION"in process.env)return!0;if(process.platform==="win32")return!1;if(Q)return!1;if(Y)return!1;if(K){let U=DQ6(q||"");switch(K){case"iTerm.app":if(U.major===3)return U.minor>=1;return U.major>3;case"WezTerm":return U.major>=20200620;case"vscode":return U.major>1||U.major===1&&U.minor>=72;case"ghostty":return!0}}if(G){if(G==="0.50.0")return!1;let U=DQ6(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}MQ6.exports={supportsHyperlink:Kx1,stdout:Kx1(process.stdout),stderr:Kx1(process.stderr)}});function RV(J,Q,{target:Z="stdout",...X}={}){if(!b41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return _41.link(J,Q)}var b41;var NQ6=p(()=>{UQ6();b41=u6(VQ6(),1);RV.isSupported=b41.default.stdout;RV.stderr=(J,Q,Z={})=>RV(J,Q,{target:"stderr",...Z});RV.stderr.isSupported=b41.default.stderr});class qx1{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.1759147319-g41306c"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await M10(Q)}catch(Q){a.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}}var LQ6=p(()=>{B0();PB()});class zY{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function OQ6(J){if(J instanceof x41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof zY)return{title:"Info",description:J.message,type:"info"};return a.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 x41;var Gx1=p(()=>{B0();x41=class x41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}});import{execSync as AQ6}from"node:child_process";import{rmdir as U49}from"node:fs/promises";import{tmpdir as F49}from"node:os";import jQ6 from"node:path";import{mkdtemp as W49,readFile as H49,unlink as B49,writeFile as _U2}from"fs/promises";class zx1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=BC()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new qx1(async()=>{try{return(await A9()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),Q2.pipe(g0((Q)=>Q.settings["internal.modes"]),d8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...D49},J)Object.assign(this.commands,M49)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{a.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await tb1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.worker.handle({type:"user:message",message:{content:[{type:"text",text:q.output}]}});return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var D49,M49;var RQ6=p(()=>{XQ6();B0();V4();DC();dw();p4();lU();nb1();PB();qD();K8();i0();NQ6();$41();ab1();LQ6();Gx1();D49={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${h5} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:xY0}]}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new x41;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread()}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await W49(jQ6.join(F49(),"amp-edit-")),Y=jQ6.join(X,"message.amp.md");AQ6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await H49(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return a.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await B49(Y),await U49(X)}catch(K){a.warn("Failed to clean up temporary file",K)}return}catch(Z){return a.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return uU("dangerouslyAllowAll",!1),new zY("Amp is now following permissions rules for this session")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return uU("dangerouslyAllowAll",!0),new zY("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await TT();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw a.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:TT};await S41(Y);return}catch(Y){a.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return a.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new zY(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return a.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
5444
5444
  `).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=av(new URL(Y),Z.id).toString(),G=`Thread URL: ${RV(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new zY(`${G}
5445
5445
 
5446
5446
  This thread's visibility has been updated to: ${z}`)}catch(F){let W=F instanceof Error?F.message:String(F);if(W.includes("no-workspace"))return Error("You are not a member of any workspace.");if(W.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(W.includes("no-groups"))return Error("You are not a member of any groups.");return a.error("Unexpected failure to update thread visibility",F),Error(`Failed to update thread visibility for ${Z.id}`)}}},browser:{name:"browser",description:"Open the current thread in your browser",requiresArgs:!1,execute:async(J,Q)=>{let{thread:Z,ampURL:X}=J,Y=av(new URL(X),Z.id).toString();try{return await PT(Y),new zY("Thread opened in browser")}catch(K){a.error("Failed to open browser",{error:K});let q=RV(Y,Y,{fallback:()=>Y});return new zY(`Could not open browser automatically. Thread URL: ${q}`)}},isVisible:(J)=>J.messages.length!==0},settings:{name:"settings",description:"Open CLI settings file in $EDITOR",launchesWindow:!0,execute:async(J)=>{let Q=await TT();if(Q===null)return Error("No editor found, please set $EDITOR to edit settings");try{AQ6(`${Q} "${J.settingsFilePath}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");return}catch(Z){return a.error("Failed to open settings in editor",Z),Error(`Failed to open ${Q}`)}}},"agent-files":{name:"agent-files",description:"List AGENTS.md guidance files in use for the current thread",execute:async(J)=>{try{let Q=await J.getGuidanceFiles();if(Q.length===0)return new zY("No guidance files are currently in use for this thread.");let Z=Q.length,X=`Agent ${NX(Z,"File")} (${Z}):`,Y=Q.map((K)=>` • ${QJ(MX(K.uri))} (${K.type})`).join(`
@@ -5619,7 +5619,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
5619
5619
  `),J.stdout.write(`Continue this thread with: amp threads continue ${q}
5620
5620
  `)}}function JY9(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 l1.index(Z[X])}var UF6,FF6;var HF6=p(()=>{B0();V4();DC();dw();p4();TN();Z4();$3();K8();i0();tJ6();RQ6();p7();J71();RA();cZ6();em();vU();hx1();t5();mT();TA();nZ6();m9();Q71();D2();UX6();UX();C9();Wy1();j7();om();V9();cz6();iz6();MQ();hX6();tz6();ez6();KU6();UU6();WU6();cT();HU6();ky1();BU6();NU6();cU6();lU6();fz6();nU6();Ah1();sU6();tU6();$71();dz6();YF6();zF6();UF6=class UF6 extends R6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new FF6}};FF6=class FF6 extends j6{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingDebugOverlay=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;currentProgressBarState="off";progressReportTimer=null;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;submitDisabledHint=null;submitDisabledHintTimer=null;isShowingTrainingModeDialog=!1;pendingTrainingMode=null;currentAgentMode=void 0;agentModeSubscription=null;updateState=null;updateServiceSubscription=null;isFreeTierEnabled=!1;isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;return Boolean(J.viewState.state==="active"&&(J.viewState.interactionState==="tool-running"||J.viewState.inferenceState==="running"))}isSummarizing(J){return J.state==="active"&&J.summaryState!=="idle"}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}isSlashCommand(J){if(!J.startsWith("/"))return!1;if((J.split(" ")[0]?.slice(1)||"").includes("/"))return!1;return!0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new w1(this.submitDisabledHint,new v1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new w1("",void 0,[new w1("Ctrl+C",new v1({color:Q.keybind})),new w1(" again to exit",new v1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new w1("",void 0,[new w1("Esc",new v1({color:Q.keybind})),new w1(" again to clear input",new v1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new w1("",void 0,[new w1("Escape",new v1({color:Q.keybind})),new w1(" to close help",new v1({color:J.foreground,dim:!0}))]);if(this.isProcessing()||this.bashInvocations.length>0)return new w1("",void 0,[new w1("Esc",new v1({color:Q.keybind})),new w1(" to cancel",new v1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new w1("Selection copied to clipboard",new v1({color:J.foreground,dim:!0}));return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}textController=new H71;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new CV);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(Nx1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new $J("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;commands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text,Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};getCommands(){if(!this.commands)this.commands=new zx1(this.widget.dependencies.commandRegistry);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Ch1(this.getCommands(),this.widget.dependencies.fuzzyServer,new v51);return this.completionBuilder}navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.widget.dependencies.ideClient.sendStatus({enabled:!1}),this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J)=>{try{await this.connectToSelectedIde(J)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})}this.widget.dependencies.lockfileManager.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J){await this.widget.dependencies.ideClient.start(J)}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:q}:z);else{let z={id:X,args:Y,toolRun:q,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};handleHistoryNavigation=(J)=>{if(J.key==="p"&&J.ctrlKey)return this.navigateHistoryPrevious(),"handled";if(J.key==="n"&&J.ctrlKey)return this.navigateHistoryNext(),"handled";return"ignored"};onTextSubmitted=async(J)=>{let{threadState:Q}=this.widget.dependencies;if(this.isSummarizing(Q.viewState)){this.showSubmitDisabledHint("Unable to submit while compacting.");return}if(!J.trim())return;let Z=this.parseShellModeInput(J);if(Z){if(Z.cmd&&!this.isProcessing())this.invokeBashCommand(Z.cmd,{hidden:Z.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let X=aJ6(J);if(this.isSlashCommand(X)&&Q.mainThread){let Y=X.slice(1).split(" "),K=Y[0],q=Y.slice(1).filter((G)=>G.trim()!=="");if(K){let G=Q.viewState,z=this.getCommands().query(K,Q.mainThread,G).filter((U)=>U.name===K).pop();if(z){if((z.requiresArgs||z.requiresPicker)&&q.length===0){this.textController.clear(),this.textController.insertText(`/${K} `);return}this.textController.clear(),this.resetHistory(),await this.executeCommand(z,q)}return}}this.textController.clear(),this.resetHistory(),await this.sendUserMessage(X)};onOptionSelected=(J)=>{switch(J.type){case"command":{let Q=`/${J.name} `;this.onTextSubmitted(Q);break}case"file":{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),q=Q.slice(Z),G=K+`@${J.path} `+q;this.textController.clear(),this.textController.insertText(G),this.textController.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]==="/continue"){let X=`/continue ${J.threadId} `;this.onTextSubmitted(X)}break}case"argument":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]?.startsWith("/")){let Y=`${Z[0]} ${J.value} `;this.onTextSubmitted(Y)}break}}};executeCommand=async(J,Q)=>{let{threadState:Z}=this.widget.dependencies;if(!Z.mainThread||!J)return;let X=new AbortController,Y=Date.now(),q={id:`command-${Y}-${Math.random().toString(36).substring(7)}`,name:J.name,startTime:Y,abortController:X};this.setState(()=>{this.executingCommand=q});try{if(J.name==="new"){let z=await this.widget.dependencies.startNewThread();E71(z);return}if(J.launchesWindow)TU.instance.tuiInstance.suspend();let G=await this.getCommands().execute(J.name,{worker:this.widget.dependencies.worker,thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,takeImageAttachments:()=>{let z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),z},editorDispatch:(z)=>{if(z.type==="set-input")this.textController.clear(),this.textController.insertText(z.input);else if(z.type==="clear")this.textController.clear()},exitApp:()=>{process.exit(0)},openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},showCommandOverlay:(z)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=z})},settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,startNewThread:async()=>{await this.widget.dependencies.startNewThread()},pickAndContinueThread:this.widget.dependencies.pickAndContinueThread,switchToThread:async(z)=>{await this.switchToExistingThread(z)},getGuidanceFiles:async()=>{if(!Z.mainThread)return[];return(await Ua({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Z.mainThread,X.signal)).map((U)=>({uri:U.uri,type:U.type}))}},Q,X.signal);if(J.launchesWindow)TU.instance.tuiInstance.resume();if(G)this.setState(()=>{this.displayMessage=G})}catch(G){a.error("Error executing command:",G)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Yg1().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if(PG.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;this.checkFreeTierStatus(),E71(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Q)=>{this.setState(()=>{this.ideStatus=Q})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Q)=>{let Z=lT();if(!Z){a.warn("No active thread worker found to handle IDE message");return}await new Promise((X)=>setTimeout(X,50)),await Z.handle({type:"user:message",message:{content:[{type:"text",text:Q}]}}),a.debug("Message sent from IDE to agent",{message:Q.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Q)=>{this.textController.insertText(Q),a.debug("Appended text to CLI prompt from IDE",{text:Q.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Q)=>{this.setState(()=>{this.updateState=Q})}),this.agentModeSubscription=Q2.pipe(g0((Q)=>Q.settings["experimental.agentMode"]),d8()).subscribe((Q)=>{this.setState(()=>{this.currentAgentMode=Q})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(Q,Z)=>{if(Q.length<=3)return!0;let X=sJ6(Q);if(!X)return!0;if(this.imageAttachments.length>=$o1)return!1;let Y=oJ6(X);if(Y)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return!0},this.updateTerminalTitle();let J=this.widget.dependencies.lockfileManager.getSelectedConfig();if(J)this.connectToSelectedIde(J).catch((Q)=>{let Z=Q instanceof Error?Q.message:String(Q);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.textController.removeListener(this.textChangeListener),this.commands)this.commands.cleanup().catch((J)=>{a.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(Nx1("")),this.shouldUseProgressBar())process.stdout.write(Lx1());if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,Z=[...J.activeTools,...J.subagentActiveTools].filter((q)=>q.toolRun.status==="blocked-on-user");if(Z.length===0)return null;let X=Z[0],Y=X.toolRun.status==="blocked-on-user"?X.toolRun.toAllow??[]:[],K=X.toolRun.status==="blocked-on-user"?X.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:X.toolUse,toAllow:Y}],subthreadID:X.subthreadID,reason:K}}shouldUseProgressBar(){return m8.of(this.context).capabilities.xtversion?.toLowerCase().startsWith("ghostty")??!1}updateProgressBar(){if(!this.shouldUseProgressBar())return;let{threadState:J}=this.widget.dependencies,Q=this.getCurrentConfirmation(),Z="off";if(Q)Z="paused";else if(this.isProcessing())Z="indeterminate";if(Z!==this.currentProgressBarState)this.currentProgressBarState=Z,this.sendProgressReport(Z);this.scheduleProgressReportTimer()}sendProgressReport(J){switch(J){case"indeterminate":process.stdout.write(iQ6());break;case"paused":process.stdout.write(nQ6());break;case"off":process.stdout.write(Lx1());break}}scheduleProgressReportTimer(){if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null;if(this.currentProgressBarState!=="off")this.progressReportTimer=setTimeout(()=>{if(this.currentProgressBarState!=="off")this.sendProgressReport(this.currentProgressBarState),this.scheduleProgressReportTimer()},1e4)}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){a.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){a.error("No tool use block found in confirmation");return}if(J==="allow-all-session")uU("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0)}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else a.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q)}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await dJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){a.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"compact":this.dismissedEphemeralErrorKey=null,await Z.summarizeThread();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await dJ.cancel(this.widget.dependencies.threadID)};switchToExistingThread=async(J)=>{try{let Q=await this.widget.dependencies.switchToThread(J);this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,E71(Q),I71()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{})}catch(Q){throw a.error("Failed to switch to thread:",J,Q),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=lT()||this.widget.dependencies.worker,Z=[{type:"text",text:J}];if(this.imageAttachments.length>0)Z.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Z}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};onTrainingModeDialogResponse=async(J)=>{if(this.setState(()=>{this.isShowingTrainingModeDialog=!1}),J&&this.pendingTrainingMode)try{let Q=await this.widget.dependencies.internalAPIClient.updateUserTrainingMode({enabled:!0});if(!Q.ok){let Z=Q.error.message||"Failed to enable training mode";await this.showErrorMessage(Z),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else await this.proceedWithUserMessage(this.pendingTrainingMode)}catch(Q){await this.showErrorMessage(`Failed to enable training mode:
5621
5621
 
5622
- ${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else if(!J&&this.pendingTrainingMode)this.textController.clear(),this.textController.insertText(this.pendingTrainingMode);this.setState(()=>{this.pendingTrainingMode=null})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}async checkFreeTierStatus(){try{let J=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({});if(J.ok)this.setState(()=>{this.isFreeTierEnabled=J.result.enabled})}catch(J){a.debug("Failed to check free tier status:",J)}}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;TU.instance.stop()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=tX9();if(J===Q)return"~";if(J.startsWith(Q+fu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(fu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(fu.sep),"…",Q.slice(-2).join(fu.sep)].join(fu.sep)}build(J){let Q=m8.of(J),Z=I8.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let{threadState:q}=this.widget.dependencies;if(this.isShowingThreadPicker)return new _H({child:new Jg1({onSelect:async(b)=>{if(b)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(b);else process.exit(0)},pageSize:50,threadFetcher:new v51})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,W=this.isTranscriptEmpty()?new D51({useGpt5:this.widget.dependencies.useGpt5,updateState:this.updateState??void 0}):new Eh1({key:U?new $J(`message-view-${U}`):void 0,items:q.items,activeTools:q.activeTools,controller:U?this.getMessageScrollController(U):new CV,autofocus:!1,onCopy:this._handleTextCopy.bind(this)}),H=Math.max(Math.floor(Q.size.height*0.4),10),D=this.getCurrentEphemeralError(),M=this.buildBottomWidget(D,G,Y,Z,q,z,H),V=Q.size.width<40,N=q.mainThread?Nc1(q.mainThread):void 0,L=new P71({threadViewState:q.viewState,threadTokenUsage:N,threadID:U??null,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},ideStatus:this.ideStatus,isNarrow:V,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!G,showingEphemeralError:Boolean(q.viewState.state==="active"&&q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null}),O=new Ph1({activeTools:[...q.activeTools,...q.subagentActiveTools],subagents:q.subagents}),A=new w71({bashInvocations:this.bashInvocations}),j=[];if(this.isFreeTierEnabled)j.push(new c6({decoration:new j2(Y.secondary),child:new P8({padding:W6.horizontal(1),child:new q0({text:new w1("Thank you for trying the ad-supported Amp Free experiment — AD",new v1({color:l1.black})),textAlign:"center"})})}));j.push(new $2({child:W}),O,A,new c6({constraints:new y6(0,Q.size.width,0,H),child:M}),new r0({height:1,child:new P8({padding:W6.horizontal(1),child:L})}));let R=new O6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:j}),I=new E5(()=>{if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingDebugOverlay)return this.setState(()=>{this.isShowingDebugOverlay=!1}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.clearActiveSelection())return"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return a.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.cancelStreamingMessage().catch((m)=>{a.error("Failed to cancel streaming message:",m)}),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),w=new E5(()=>{return this.onExitPressed(),"handled"}),E=new E5(()=>{return this.setState(()=>{this.isShowingDebugOverlay=!this.isShowingDebugOverlay}),"handled"}),$=new E5(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),P=new E5(()=>{return yV.instance.toggleAll(),"handled"}),C=new E5(()=>{return TU.instance.tuiInstance.getScreen().markForRefresh(),EJ.instance.requestFrame(),"handled"}),_=new E5(()=>{let b=this.findElementByKey("message-view-selection-area");if(b?.state){let m=b.state,n=m.controller?.copySelection();if(n&&n.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{m.controller.endCopyHighlight(),m.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),g=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageUp(Q1,100)}return"handled"}),T=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageDown(Q1,100)}return"handled"}),v=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(0,100);return"handled"}),f=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),h=new Map([[m2.key("Escape"),new Ku],[m2.ctrl("c"),new uT],[m2.ctrl("l"),new Uu],[m2.alt("d"),new qu],[m2.alt("c"),new Gu],[m2.ctrl("r"),new zu],[m2.key("PageUp"),new Y71],[m2.key("PageDown"),new K71],[m2.key("Home"),new q71],[m2.key("End"),new G71]]);if(process.platform==="darwin")h.set(m2.meta("c"),new uT);let S=new Map([[Ku,I],[t41,w],[Uu,C],[qu,E],[Gu,$],[zu,P],[uT,_],[Y71,g],[K71,T],[q71,v],[G71,f]]),y=R;if(this.isShowingDebugOverlay)y=new WY({children:[y,new TH({top:2,right:2,child:new bh1})]});if(this.isShowingConsoleOverlay)y=new WY({children:[y,new _h1]});if(this.isShowingHelp)y=new WY({children:[y,new yh1]});if(this.isShowingFileChangesOverlay)y=new WY({children:[y,new vy1]});if(this.isShowingConfirmationOverlay)y=new WY({children:[y,new Sh1({details:this.confirmationOverlayContent})]});if(this.isShowingIdePicker)return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"ide-picker-shortcuts",child:new hh1({lockfileManager:this.widget.dependencies.lockfileManager,onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection})})})});if(this.isShowingJetBrainsInstaller)return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"jetbrains-installer-shortcuts",child:new oh1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"main-app-shortcuts",child:y})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new xh1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new Qg1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new kh1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new th1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=eX9(X),U=new D71({key:this.textFieldKey,controller:this.textController,triggers:[Yg1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(P)=>Th1(P),overlayBorderColor:Z.border,textFieldProps:{placeholder:"Type your message... (use / for commands, @ for files)",wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!0,onSubmitted:this.onTextSubmitted,submitKey:{character:"Enter"},prompts:z,style:{border:null},clipboard:TU.instance.tuiInstance.clipboard},optionViewBuilder:(P,C,_)=>{let g=_?Z.selection:void 0,T=C.type==="command"?Z.warning:Z.secondary,v=Z.foreground,f=Z.foreground,h,S;switch(C.type){case"command":h="/",S=C.name;break;case"file":h="@",S=C.path;break;case"thread":h="",S=C.title;break;default:h="",S=Th1(C);break}let y=oz6(C),b=new w1(h,new v1({color:T})),m=new w1(S,new v1({color:v})),n=[b,m];if(y){let u=new w1(" - ",new v1({color:f,dim:!0})),Q1=new w1(y,new v1({color:f,dim:!0}));n.push(u,Q1)}return new c6({decoration:new j2(g),child:new q0({text:new w1("",void 0,n),maxLines:1,overflow:"ellipsis"})})}}),F=Y.mainThread?.queuedMessages??[],W=new J2({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,D=this.imageAttachments.length>0?new c6({padding:W6.only({bottom:1,left:1}),child:new q0({text:new w1("",void 0,[new w1("Images: ",new v1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((P,C)=>[new w1(`[image ${C+1}]`,new v1({color:Z.success})),...C<this.imageAttachments.length-1?[new w1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(F)&&F.length>0,N=D?new O6({crossAxisAlignment:"start",children:[D,W]}):W,L=V?new eh1({queuedMessages:F}):void 0,O=M?new fx1(new $h1({todos:K}),{clipBehavior:"antiAlias"}):void 0,A=[],j=Y.viewState;if(!this.isSummarizing(j))A.push({text:new w1("",void 0,[new w1("Enter",new v1({color:G.keybind})),new w1(" to send",new v1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)A.push({text:new w1(H==="hidden"?"shell mode (incognito)":"shell mode",new v1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:D?1:0});let R=this.currentAgentMode;if(R&&!["default",sU[0]].includes(R)&&!H){let P=JY9(R);A.push({text:new w1("",void 0,[new w1("agent-mode: ",new v1({color:Z.foreground,dim:!0})),new w1(R,new v1({color:P}))]),position:"top-left",offsetY:0})}let I=Y.mainThread?.metadata?.treeInfo?.uri,w;if(I)w=S0.isUri(I)?I.fsPath:I;else w=process.cwd();let E=this.toHomeRelative(w),$=this.shorten(E);return A.push({text:new w1($,new v1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new wy1({leftChild:N,rightChild1:L,rightChild2:O,maxHeight:q,overlayTexts:A,borderColor:Z.border})}}});import{randomBytes as QY9}from"node:crypto";import{mkdir as ZY9,readFile as VF6,writeFile as XY9}from"node:fs/promises";import YY9 from"node:os";import Kg1 from"node:path";import{stderr as o2,stdout as u2}from"node:process";function KY9(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 iA(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")uU("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")uU("gpt5",Q.tryGpt5);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")uU("experimental.agentMode",Q.agentMode)}async function zg1(J){try{await ZY9(Kg1.dirname(qg1),{recursive:!0}),await XY9(qg1,J,"utf-8")}catch(Q){a.debug("Failed to save last thread ID",Q)}}async function zY9(){try{return(await VF6(qg1,"utf-8")).trim()}catch(J){return null}}async function UY9(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 GY9.parse(Q)}catch(Z){if(Z instanceof T0.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 FY9(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]()}}}function DY9(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 E2(vK.unknownCommand(Z),1,q)}}function ey2(){return NF6}function _51(J){return{...J,getThreadEnvironment:Y41,vfs:H10({os:J.fileSystem}),fileChangeTrackerStorage:new sv(J.fileSystem),generateThreadTitle:Ha,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}async function nA(J,Q){Cc1("0.0.1759132892-gf2cb87");let Z=xQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:qb1,homeDir:Ug1,userConfigDir:LF6}),X=await A9();a.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=ul(Tp()),K=le1({configService:Z,toolService:Y}),q=iL0(Y,R8,Dt).catch((L)=>{a.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{a.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)Sc1(!0);if(Q.ide&&fb1())vc1(!0);if(Y66(Y,X.settings),Q.jetbrains)Y.registerTool(fa);else if(Q.ide)Y.registerTool(hK0);let z;if(!J.executeMode)z=new D41(process.cwd(),{},!0);else z=new class extends D41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(u2.write(`No API key found. Starting login flow...
5622
+ ${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else if(!J&&this.pendingTrainingMode)this.textController.clear(),this.textController.insertText(this.pendingTrainingMode);this.setState(()=>{this.pendingTrainingMode=null})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}async checkFreeTierStatus(){try{let J=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({});if(J.ok)this.setState(()=>{this.isFreeTierEnabled=J.result.enabled})}catch(J){a.debug("Failed to check free tier status:",J)}}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;TU.instance.stop()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=tX9();if(J===Q)return"~";if(J.startsWith(Q+fu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(fu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(fu.sep),"…",Q.slice(-2).join(fu.sep)].join(fu.sep)}build(J){let Q=m8.of(J),Z=I8.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let{threadState:q}=this.widget.dependencies;if(this.isShowingThreadPicker)return new _H({child:new Jg1({onSelect:async(b)=>{if(b)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(b);else process.exit(0)},pageSize:50,threadFetcher:new v51})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,W=this.isTranscriptEmpty()?new D51({useGpt5:this.widget.dependencies.useGpt5,updateState:this.updateState??void 0}):new Eh1({key:U?new $J(`message-view-${U}`):void 0,items:q.items,activeTools:q.activeTools,controller:U?this.getMessageScrollController(U):new CV,autofocus:!1,onCopy:this._handleTextCopy.bind(this)}),H=Math.max(Math.floor(Q.size.height*0.4),10),D=this.getCurrentEphemeralError(),M=this.buildBottomWidget(D,G,Y,Z,q,z,H),V=Q.size.width<40,N=q.mainThread?Nc1(q.mainThread):void 0,L=new P71({threadViewState:q.viewState,threadTokenUsage:N,threadID:U??null,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},ideStatus:this.ideStatus,isNarrow:V,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!G,showingEphemeralError:Boolean(q.viewState.state==="active"&&q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null}),O=new Ph1({activeTools:[...q.activeTools,...q.subagentActiveTools],subagents:q.subagents}),A=new w71({bashInvocations:this.bashInvocations}),j=[];if(this.isFreeTierEnabled)j.push(new c6({decoration:new j2(Y.secondary),child:new P8({padding:W6.horizontal(1),child:new q0({text:new w1("Thank you for trying the ad-supported Amp Free experiment — AD",new v1({color:l1.black})),textAlign:"center"})})}));j.push(new $2({child:W}),O,A,new c6({constraints:new y6(0,Q.size.width,0,H),child:M}),new r0({height:1,child:new P8({padding:W6.horizontal(1),child:L})}));let R=new O6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:j}),I=new E5(()=>{if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingDebugOverlay)return this.setState(()=>{this.isShowingDebugOverlay=!1}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.clearActiveSelection())return"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return a.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.cancelStreamingMessage().catch((m)=>{a.error("Failed to cancel streaming message:",m)}),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),w=new E5(()=>{return this.onExitPressed(),"handled"}),E=new E5(()=>{return this.setState(()=>{this.isShowingDebugOverlay=!this.isShowingDebugOverlay}),"handled"}),$=new E5(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),P=new E5(()=>{return yV.instance.toggleAll(),"handled"}),C=new E5(()=>{return TU.instance.tuiInstance.getScreen().markForRefresh(),EJ.instance.requestFrame(),"handled"}),_=new E5(()=>{let b=this.findElementByKey("message-view-selection-area");if(b?.state){let m=b.state,n=m.controller?.copySelection();if(n&&n.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{m.controller.endCopyHighlight(),m.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),g=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageUp(Q1,100)}return"handled"}),T=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageDown(Q1,100)}return"handled"}),v=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(0,100);return"handled"}),f=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),h=new Map([[m2.key("Escape"),new Ku],[m2.ctrl("c"),new uT],[m2.ctrl("l"),new Uu],[m2.alt("d"),new qu],[m2.alt("c"),new Gu],[m2.ctrl("r"),new zu],[m2.key("PageUp"),new Y71],[m2.key("PageDown"),new K71],[m2.key("Home"),new q71],[m2.key("End"),new G71]]);if(process.platform==="darwin")h.set(m2.meta("c"),new uT);let S=new Map([[Ku,I],[t41,w],[Uu,C],[qu,E],[Gu,$],[zu,P],[uT,_],[Y71,g],[K71,T],[q71,v],[G71,f]]),y=R;if(this.isShowingDebugOverlay)y=new WY({children:[y,new TH({top:2,right:2,child:new bh1})]});if(this.isShowingConsoleOverlay)y=new WY({children:[y,new _h1]});if(this.isShowingHelp)y=new WY({children:[y,new yh1]});if(this.isShowingFileChangesOverlay)y=new WY({children:[y,new vy1]});if(this.isShowingConfirmationOverlay)y=new WY({children:[y,new Sh1({details:this.confirmationOverlayContent})]});if(this.isShowingIdePicker)return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"ide-picker-shortcuts",child:new hh1({lockfileManager:this.widget.dependencies.lockfileManager,onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection})})})});if(this.isShowingJetBrainsInstaller)return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"jetbrains-installer-shortcuts",child:new oh1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"main-app-shortcuts",child:y})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new xh1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new Qg1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new kh1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new th1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=eX9(X),U=new D71({key:this.textFieldKey,controller:this.textController,triggers:[Yg1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(P)=>Th1(P),overlayBorderColor:Z.border,textFieldProps:{placeholder:"Type your message... (use / for commands, @ for files)",wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!0,onSubmitted:this.onTextSubmitted,submitKey:{character:"Enter"},prompts:z,style:{border:null},clipboard:TU.instance.tuiInstance.clipboard},optionViewBuilder:(P,C,_)=>{let g=_?Z.selection:void 0,T=C.type==="command"?Z.warning:Z.secondary,v=Z.foreground,f=Z.foreground,h,S;switch(C.type){case"command":h="/",S=C.name;break;case"file":h="@",S=C.path;break;case"thread":h="",S=C.title;break;default:h="",S=Th1(C);break}let y=oz6(C),b=new w1(h,new v1({color:T})),m=new w1(S,new v1({color:v})),n=[b,m];if(y){let u=new w1(" - ",new v1({color:f,dim:!0})),Q1=new w1(y,new v1({color:f,dim:!0}));n.push(u,Q1)}return new c6({decoration:new j2(g),child:new q0({text:new w1("",void 0,n),maxLines:1,overflow:"ellipsis"})})}}),F=Y.mainThread?.queuedMessages??[],W=new J2({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,D=this.imageAttachments.length>0?new c6({padding:W6.only({bottom:1,left:1}),child:new q0({text:new w1("",void 0,[new w1("Images: ",new v1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((P,C)=>[new w1(`[image ${C+1}]`,new v1({color:Z.success})),...C<this.imageAttachments.length-1?[new w1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(F)&&F.length>0,N=D?new O6({crossAxisAlignment:"start",children:[D,W]}):W,L=V?new eh1({queuedMessages:F}):void 0,O=M?new fx1(new $h1({todos:K}),{clipBehavior:"antiAlias"}):void 0,A=[],j=Y.viewState;if(!this.isSummarizing(j))A.push({text:new w1("",void 0,[new w1("Enter",new v1({color:G.keybind})),new w1(" to send",new v1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)A.push({text:new w1(H==="hidden"?"shell mode (incognito)":"shell mode",new v1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:D?1:0});let R=this.currentAgentMode;if(R&&!["default",sU[0]].includes(R)&&!H){let P=JY9(R);A.push({text:new w1("",void 0,[new w1("agent-mode: ",new v1({color:Z.foreground,dim:!0})),new w1(R,new v1({color:P}))]),position:"top-left",offsetY:0})}let I=Y.mainThread?.metadata?.treeInfo?.uri,w;if(I)w=S0.isUri(I)?I.fsPath:I;else w=process.cwd();let E=this.toHomeRelative(w),$=this.shorten(E);return A.push({text:new w1($,new v1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new wy1({leftChild:N,rightChild1:L,rightChild2:O,maxHeight:q,overlayTexts:A,borderColor:Z.border})}}});import{randomBytes as QY9}from"node:crypto";import{mkdir as ZY9,readFile as VF6,writeFile as XY9}from"node:fs/promises";import YY9 from"node:os";import Kg1 from"node:path";import{stderr as o2,stdout as u2}from"node:process";function KY9(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 iA(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")uU("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")uU("gpt5",Q.tryGpt5);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")uU("experimental.agentMode",Q.agentMode)}async function zg1(J){try{await ZY9(Kg1.dirname(qg1),{recursive:!0}),await XY9(qg1,J,"utf-8")}catch(Q){a.debug("Failed to save last thread ID",Q)}}async function zY9(){try{return(await VF6(qg1,"utf-8")).trim()}catch(J){return null}}async function UY9(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 GY9.parse(Q)}catch(Z){if(Z instanceof T0.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 FY9(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]()}}}function DY9(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 E2(vK.unknownCommand(Z),1,q)}}function ey2(){return NF6}function _51(J){return{...J,getThreadEnvironment:Y41,vfs:H10({os:J.fileSystem}),fileChangeTrackerStorage:new sv(J.fileSystem),generateThreadTitle:Ha,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}async function nA(J,Q){Cc1("0.0.1759147319-g41306c");let Z=xQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:qb1,homeDir:Ug1,userConfigDir:LF6}),X=await A9();a.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=ul(Tp()),K=le1({configService:Z,toolService:Y}),q=iL0(Y,R8,Dt).catch((L)=>{a.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{a.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)Sc1(!0);if(Q.ide&&fb1())vc1(!0);if(Y66(Y,X.settings),Q.jetbrains)Y.registerTool(fa);else if(Q.ide)Y.registerTool(hK0);let z;if(!J.executeMode)z=new D41(process.cwd(),{},!0);else z=new class extends D41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(u2.write(`No API key found. Starting login flow...
5623
5623
  `),!await MY9(J))await MA(),process.exit(1)}let U=await $10({isDevelopment:!1}),F=new uU1(U),W=new gU1(U,{lazy:!0}),H=new SD1(F),D=Q.notifications!==void 0?Q.notifications:!J.executeMode,M=z66({playNotificationSound:async(L)=>{if(D){q66(L);let O=kx1(),A=_x1();if((!O||A)&&X.settings["notifications.system.enabled"]!==!1){if(L==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(L==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:F});a.info("Starting Amp background services");let V=dY0({threadService:F,threadHistoryService:W,isExtensionDevelopment:!1}),N={configService:Z,toolService:Y,mcpService:K,threadService:F,threadHistoryService:W,threadSummaryService:H,threadSyncService:V,threadStorage:U,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:z,notificationService:M,fileSystem:Q.jetbrains||Q.ide?z10:R8};return{...N,async asyncDispose(){await N.mcpService.dispose(),await N.threadService.asyncDispose(),N.configService.unsubscribe(),N.toolService.dispose(),N.fuzzyServer.dispose(),N.threadSyncService.dispose(),N.settingsStorage[Symbol.dispose]()}}}async function MY9(J){if(!J.executeMode){if(!await ib1("Would you like to log in to Amp? [(y)es, (n)o]: "))return u2.write(`Login cancelled. Run the command again to retry.
5624
5624
  `),!1}return await OF6(J)}async function OF6(J){let Q=QY9(32).toString("hex"),Z=await lb1(J.ampURL,Q);try{await PT(Z)}catch(Y){a.error("Failed to open browser",{error:Y})}let X=await lb1(J.ampURL,Q,!1);u2.write(`If your browser did not open automatically, visit:
5625
5625
 
@@ -5629,12 +5629,12 @@ ${Q8.blue.bold(X)}
5629
5629
  Login successful! You can now use the Amp CLI.
5630
5630
  `),!0}catch(Y){return a.error("Login failed",{error:Y}),o2.write(`
5631
5631
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
5632
- `),!1}}function VY9(){let J=new tg().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)HT(),process.exit(0);let H=W.originalError??W;q76(H)}),J.option("-V, --version","output the version number",()=>{u2.write(`0.0.1759132892-gf2cb87 (released 2025-09-29T08:06:57.483Z)
5633
- `),process.exit(0)}),J.addHelpText("after",C56()),J.configureHelp({formatHelp:S56}),J.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await AY9(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(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await OY9(M,await vb1(D,M.settings))});let Q=async(W,H,D)=>{xQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Ug1,userConfigDir:LF6});let M={...H,executeMode:!1};await Gg1(M,{...W,startWithPicker:!0},D)},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(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await MF6(D,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(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await PY9(D,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(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);if(H.pick)await Q(M,V,D);else await $Y9(M,V,W,D)}),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(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await EY9(M,V,W,D)}),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(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await MF6(D,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(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await IY9(M,V,W,D,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(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await wY9(M,V,W,D)}),iJ6(J,async(W,H)=>{let D=await yK(H);iA(W,H);let M=await nA(D,H);return{context:D,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:HT,asyncDispose:M.asyncDispose.bind(M)}}),WJ6(J),e56(J,async(W)=>{return(await yK(W)).settings});let X=new tg().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(W)=>{await gb1(W.force||!1,W.verbose||!1,"0.0.1759132892-gf2cb87"),process.exit()});J.addCommand(X,{hidden:!0});function Y(W,H,D){let V=typeof W.description==="string"?W.description:D===void 0?W.description(!0):W.description(D),N=new YA(H,V),L=BY9(W);if(L)N.default(L);if(N.hidden=WY9(W)||DF6(W),"choices"in W)N.choices([...W.choices]);return N}for(let W of BF6)switch(W.type){case"flag":{J.addOption(Y(W,`--${W.long}`)),J.addOption(Y(W,`--no-${W.long}`,!1));break}case"switch":{J.addOption(Y(W,`--${W.long}`,!0));break}default:{J.addOption(Y(W,`--${W.long} <value>`));break}}let K=new YA("-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 W=new YA("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(W)}let q=new YA("--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 YA("--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 YA("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);J.addOption(z),J.action(async(W,H)=>{let D=W,M=await yK(D);if(Object.keys(D).forEach((V)=>{let N=BF6.find((L)=>L.name===V);if(N&&DF6(N)&&!HY9(N))o2.write(Q8.yellow(`Warning: '--${V}' flag is deprecated
5632
+ `),!1}}function VY9(){let J=new tg().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)HT(),process.exit(0);let H=W.originalError??W;q76(H)}),J.option("-V, --version","output the version number",()=>{u2.write(`0.0.1759147319-g41306c (released 2025-09-29T12:06:59.114Z)
5633
+ `),process.exit(0)}),J.addHelpText("after",C56()),J.configureHelp({formatHelp:S56}),J.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await AY9(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(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await OY9(M,await vb1(D,M.settings))});let Q=async(W,H,D)=>{xQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Ug1,userConfigDir:LF6});let M={...H,executeMode:!1};await Gg1(M,{...W,startWithPicker:!0},D)},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(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await MF6(D,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(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await PY9(D,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(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);if(H.pick)await Q(M,V,D);else await $Y9(M,V,W,D)}),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(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await EY9(M,V,W,D)}),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(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await MF6(D,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(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await IY9(M,V,W,D,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(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await wY9(M,V,W,D)}),iJ6(J,async(W,H)=>{let D=await yK(H);iA(W,H);let M=await nA(D,H);return{context:D,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:HT,asyncDispose:M.asyncDispose.bind(M)}}),WJ6(J),e56(J,async(W)=>{return(await yK(W)).settings});let X=new tg().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(W)=>{await gb1(W.force||!1,W.verbose||!1,"0.0.1759147319-g41306c"),process.exit()});J.addCommand(X,{hidden:!0});function Y(W,H,D){let V=typeof W.description==="string"?W.description:D===void 0?W.description(!0):W.description(D),N=new YA(H,V),L=BY9(W);if(L)N.default(L);if(N.hidden=WY9(W)||DF6(W),"choices"in W)N.choices([...W.choices]);return N}for(let W of BF6)switch(W.type){case"flag":{J.addOption(Y(W,`--${W.long}`)),J.addOption(Y(W,`--no-${W.long}`,!1));break}case"switch":{J.addOption(Y(W,`--${W.long}`,!0));break}default:{J.addOption(Y(W,`--${W.long} <value>`));break}}let K=new YA("-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 W=new YA("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(W)}let q=new YA("--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 YA("--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 YA("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);J.addOption(z),J.action(async(W,H)=>{let D=W,M=await yK(D);if(Object.keys(D).forEach((V)=>{let N=BF6.find((L)=>L.name===V);if(N&&DF6(N)&&!HY9(N))o2.write(Q8.yellow(`Warning: '--${V}' flag is deprecated
5634
5634
  `))}),H.args.length>0)DY9(M,H);await Gg1(M,D,H)});let U=new tg("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(W)=>{await RY9(W.outputDir,W.includeFullLogs)});J.addCommand(U);let F=new tg("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(W)=>{await jY9(W.version)});return J.addCommand(F),J}async function k51(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??aK(),K=_51(J);if(Z)await J.threadStorage.set(Y,Z);let q=await dJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,T41(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(G7(z,"assistant"))await zg1(Y),G.unsubscribe()});return await q.resume(),q}async function Gg1(J,Q,Z){let X=process.stdin,Y=P41(Q);if(Y instanceof Error)FX(Y.message);let K,q=null;if(Q.streamJsonInput)K="";else if(typeof Q.execute==="string"){K=Q.execute;let R=(await rb1()).trimEnd();if(R)q=R}else K=(await rb1()).trimEnd();if(Q.remote&&!J.executeMode)throw new E2("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new E2("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new E2("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new E2("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new E2("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 E2("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&&K===""&&!Q.streamJsonInput)throw new E2("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"
5635
5635
  Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMode&&!J.streamJsonMode&&typeof Q.execute!=="string")X=await jJ6();iA(Z,Q);let G=await nA(J,Q);NF6=G;let z=_51(G),U=async(R)=>{let I=await VF6(R,"utf-8"),w=JSON.parse(I);if(!aU(w.id))throw new E2(vK.invalidThreadId);return k51(G,{visibility:Y,thread:w})},F=async(R)=>{if(!aU(R))throw new E2(vK.invalidThreadId);let I=await G.threadService.get(R)??void 0;return k51(G,{visibility:Y,thread:I})},W=async()=>{try{if(Q.threadId)return F(Q.threadId);else return k51(G,{visibility:Y})}catch(R){if(R instanceof E2)throw R;throw await K41(R,Q.threadId),Error("handleError should have called process.exit()")}},H=async()=>{return k51(G,{visibility:Y})};if(Q.format==="jsonl")o2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
5636
- `),await MA(),process.exit(1);if(J.executeMode&&Q.remote)await BJ6(K,q),await G.asyncDispose(),process.exit(0);let D=await W();if(J.executeMode)await O76(D,D.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1,N=new aq1;if(Q.jetbrains||Q.ide){await N.cleanUpLockfiles();let R=await N.getConfigs();if(R.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let I=R[0];if(I)N.selectConfig(I)}else M=!0}let L=db1("0.0.1759132892-gf2cb87",G.settingsStorage),O=K0.of([S0.file(process.cwd())]),A=BC(void 0,O);if(K)D.handle({type:"user:message",message:{content:[{type:"text",text:K}]}});let j=await A9();await WF6({stdin:X,stdout:process.stdout,history:new Bb1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:D.threadID,worker:D,workerDeps:z,configService:G.configService,internalAPIClient:NZ,ampURL:J.ampURL,useGpt5:j.settings.gpt5??!1,startNewThread:H,pickAndContinueThread:async()=>{a.info("Thread picker requested - not yet implemented in TUI")},switchToThread:F,ideClient:RQ,commandRegistry:A,showJetBrainsInstaller:V,showIdePicker:M,lockfileManager:N,startWithPicker:Q.startWithPicker,updateService:L}),await G.asyncDispose(),process.exit(0)}async function yK(J){if(J.interactive)o2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5637
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=EU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(await NJ6(Y),await LJ6(Y),J.mcpConfig){let q=await UY9(J.mcpConfig);Y=FY9(Y,q)}let K=await Y.get("url","global");if(!K)K=GZ;if(!nH(K))a.info("Targeting custom Amp server",{ampURL:K});return Y=sp1(Y),{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:MJ6(await vb1(J,Y))}}function NY9(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 LY9(){let J=NY9(process.argv);if(r46({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),KY9(a),a.info("Starting Amp CLI.",{version:"0.0.1759132892-gf2cb87",buildTimestamp:"2025-09-29T08:06:57.483Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new E2(vK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await VY9().parseAsync(process.argv)}async function OY9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),u2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5636
+ `),await MA(),process.exit(1);if(J.executeMode&&Q.remote)await BJ6(K,q),await G.asyncDispose(),process.exit(0);let D=await W();if(J.executeMode)await O76(D,D.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1,N=new aq1;if(Q.jetbrains||Q.ide){await N.cleanUpLockfiles();let R=await N.getConfigs();if(R.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let I=R[0];if(I)N.selectConfig(I)}else M=!0}let L=db1("0.0.1759147319-g41306c",G.settingsStorage),O=K0.of([S0.file(process.cwd())]),A=BC(void 0,O);if(K)D.handle({type:"user:message",message:{content:[{type:"text",text:K}]}});let j=await A9();await WF6({stdin:X,stdout:process.stdout,history:new Bb1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:D.threadID,worker:D,workerDeps:z,configService:G.configService,internalAPIClient:NZ,ampURL:J.ampURL,useGpt5:j.settings.gpt5??!1,startNewThread:H,pickAndContinueThread:async()=>{a.info("Thread picker requested - not yet implemented in TUI")},switchToThread:F,ideClient:RQ,commandRegistry:A,showJetBrainsInstaller:V,showIdePicker:M,lockfileManager:N,startWithPicker:Q.startWithPicker,updateService:L}),await G.asyncDispose(),process.exit(0)}async function yK(J){if(J.interactive)o2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5637
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=EU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(await NJ6(Y),await LJ6(Y),J.mcpConfig){let q=await UY9(J.mcpConfig);Y=FY9(Y,q)}let K=await Y.get("url","global");if(!K)K=GZ;if(!nH(K))a.info("Targeting custom Amp server",{ampURL:K});return Y=sp1(Y),{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:MJ6(await vb1(J,Y))}}function NY9(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 LY9(){let J=NY9(process.argv);if(r46({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),KY9(a),a.info("Starting Amp CLI.",{version:"0.0.1759147319-g41306c",buildTimestamp:"2025-09-29T12:06:59.114Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new E2(vK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await VY9().parseAsync(process.argv)}async function OY9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),u2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5638
5638
  `);else if(!nH(J.ampURL))u2.write(`Logging in to ${new URL(J.ampURL).hostname}
5639
5639
  `);let Z=process.env.AMP_API_KEY;if(Z)u2.write(`API key found in environment variable, storing...
5640
5640
  `),await Q.set("apiKey",Z,J.ampURL),u2.write(`API key successfully stored.
@@ -5650,7 +5650,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMo
5650
5650
  `));try{let Q;if(J)Q=J,o2.write(Q8.blue(`Updating to version ${J}...
5651
5651
  `)),await ET(J),o2.write(Q8.green(`✓ Successfully updated to version ${J}
5652
5652
  `));else{o2.write(Q8.blue(`Checking for updates...
5653
- `));let{hasUpdate:X,latestVersion:Y}=await hR("0.0.1759132892-gf2cb87");if(!X)o2.write(Q8.green(`✓ Amp CLI is already up to date.
5653
+ `));let{hasUpdate:X,latestVersion:Y}=await hR("0.0.1759147319-g41306c");if(!X)o2.write(Q8.green(`✓ Amp CLI is already up to date.
5654
5654
  `)),process.exit(0);if(!Y)o2.write(Q8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,o2.write(Q8.blue(`Updating to version ${Y}...
5655
5655
  `)),await ET(Y),o2.write(Q8.green(`✓ Successfully updated to version ${Y}
5656
5656
  `))}let Z=await jA(Q);if(Z.warning)o2.write(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1759132892-gf2cb87",
3
+ "version": "0.0.1759147319-g41306c",
4
4
  "description": "CLI for Amp, an agentic coding tool in research preview from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {