@sourcegraph/amp 0.0.1759464081-gf6c1d2 → 0.0.1759469839-g3e7045
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +10 -10
- package/package.json +1 -1
package/dist/main.js
CHANGED
@@ -5439,7 +5439,7 @@ ${J99("\t",I??"(unknown)")}
|
|
5439
5439
|
`;await ab1(this.historyFile,Q,"utf-8")}async add(J){if(!J.trim())return;if(await this.ensureLoaded(),this.history.length>0&&this.history[this.history.length-1]===J)return;try{if(await b56(xm.dirname(this.historyFile),{recursive:!0}),await this.atomicAppend(J),this.history.push(J),this.history.length>this.maxSize){let Q=await this.readHistoryFromDisk();if(Q.length>this.maxSize){let Z=Q.slice(Q.length-this.maxSize);await this.writeHistoryToDisk(Z),this.history=Z}}}catch(Q){a.error(`Failed to save history: ${Q instanceof Error?Q.message:String(Q)}`)}this.reset()}async atomicAppend(J){let Q=JSON.stringify(J)+`
|
5440
5440
|
`,Z=this.historyFile+".lock",X=10,Y=50;for(let K=0;K<10;K++)try{let q=await Q99(Z,"wx");try{await ab1(this.historyFile,Q,{flag:"a",encoding:"utf-8"})}finally{await q.close(),await ab1(Z,"",{flag:"w"});try{await y56(Z)}catch{}}return}catch(q){if(q.code==="EEXIST"&&K<9){await new Promise((G)=>setTimeout(G,50));continue}throw q}throw Error("Failed to acquire lock for history file after multiple attempts")}previous(){if(this.history.length===0)return null;if(this.index===0){let Q=this.history[0];return typeof Q==="string"?Q:null}if(this.index===-1)this.index=this.history.length-1;else this.index--;let J=this.history[this.index];return typeof J==="string"?J:null}next(){if(this.history.length===0||this.index===-1)return null;if(this.index++,this.index>=this.history.length)return this.index=-1,null;let J=this.history[this.index];return typeof J==="string"?J:null}reset(){this.index=-1}}var X99,Y99,K99=1000;var f56=u(()=>{B0();nV();X99=xm.join(dH||xm.join(Z99(),".local/share"),"amp"),Y99=xm.join(X99,"history.jsonl")});class oQ{bits;constructor(J){this.bits=J}static empty(){return new oQ(0n)}static fromString(J){let Q=0n;for(let Z=0;Z<J.length;Z++){let X=J.charCodeAt(Z),Y=oQ.charToBitIndex(X);if(Y>=0)Q|=1n<<BigInt(Y)}return new oQ(Q)}static fromPath(J){let Q=0n,Z=J.split(/[/\\]/);for(let X of Z){if(X===""||X==="."||X==="..")continue;for(let Y=0;Y<X.length;Y++){let K=X.charCodeAt(Y),q=oQ.charToBitIndex(K);if(q>=0)Q|=1n<<BigInt(q)}}return new oQ(Q)}hasChars(J){return(this.bits&J.bits)===J.bits}union(J){return new oQ(this.bits|J.bits)}intersection(J){return new oQ(this.bits&J.bits)}isEmpty(){return this.bits===0n}getCharCount(){return this.bits.toString(2).split("").filter((J)=>J==="1").length}toString(){let J=[];for(let Q=0;Q<64;Q++)if((this.bits&1n<<BigInt(Q))!==0n){let Z=oQ.bitIndexToChar(Q);if(Z)J.push(Z)}return`CharBag{${J.join("")}}`}toJSON(){return{bits:this.bits.toString()}}static fromJSON(J){return new oQ(BigInt(J.bits))}equals(J){return this.bits===J.bits}static charToBitIndex(J){if(J>=65&&J<=90)J+=32;if(J>=48&&J<=57)return J-48;if(J>=97&&J<=122)return J-97+10;return-1}static bitIndexToChar(J){if(J>=0&&J<=9)return String.fromCharCode(48+J);if(J>=10&&J<=35)return String.fromCharCode(97+J-10);return null}}class VV{id;kind;path;uri;charBag;metadata;isIgnored;isExternal;isPrivate;isAlwaysIncluded;constructor(J){this.id=J.id,this.kind=J.kind,this.path=J.path,this.uri=J.uri,this.metadata=J.metadata,this.isIgnored=J.isIgnored??!1,this.isExternal=J.isExternal??!1,this.isPrivate=J.isPrivate??!1,this.isAlwaysIncluded=J.isAlwaysIncluded??!1,this.charBag=oQ.fromPath(this.path)}withUpdates(J){return new VV({id:this.id,kind:J.kind??this.kind,path:this.path,uri:this.uri,metadata:J.metadata??this.metadata,isIgnored:J.isIgnored??this.isIgnored,isExternal:J.isExternal??this.isExternal,isPrivate:J.isPrivate??this.isPrivate,isAlwaysIncluded:J.isAlwaysIncluded??this.isAlwaysIncluded})}isFile(){return this.kind==="file"}isDirectory(){return this.kind==="directory"||this.kind==="unloaded-directory"||this.kind==="pending-directory"}isLoadedDirectory(){return this.kind==="directory"}getFilename(){return this.path.split(/[/\\]/).pop()||this.path}getExtension(){let J=this.getFilename(),Q=J.lastIndexOf(".");return Q>0?J.slice(Q+1):""}getDirectory(){let J=this.path.split(/[/\\]/);return J.length>1?J.slice(0,-1).join("/"):""}shouldIncludeInResults(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;return!0}shouldIncludeInMentions(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;if(this.isFile())return!0;return this.isLoadedDirectory()}getImportanceBoost(){return this.isAlwaysIncluded?0.1:0}toJSON(){return{id:this.id,kind:this.kind,path:this.path,uri:this.uri.toString(),metadata:this.metadata,isIgnored:this.isIgnored,isExternal:this.isExternal,isPrivate:this.isPrivate,isAlwaysIncluded:this.isAlwaysIncluded,charBag:this.charBag.toJSON()}}static fromJSON(J,Q){return new VV({id:J.id,kind:J.kind,path:J.path,uri:Q(J.uri),metadata:J.metadata,isIgnored:J.isIgnored,isExternal:J.isExternal,isPrivate:J.isPrivate,isAlwaysIncluded:J.isAlwaysIncluded})}equals(J){return this.id===J.id&&this.kind===J.kind&&this.path===J.path&&this.metadata.mtime===J.metadata.mtime&&this.metadata.size===J.metadata.size}hashCode(){return`${this.path}:${this.metadata.mtime}:${this.metadata.size}`}toString(){return`Entry{${this.kind}:${this.path}}`}}var rb1=()=>{};var XX;var sb1=u(()=>{XX=class XX{static DEFAULT_PATTERNS=[{pattern:"node_modules",type:"directory",description:"Node.js dependencies"},{pattern:"vendor",type:"directory",description:"PHP/Go/Ruby dependencies"},{pattern:"deps",type:"directory",description:"Elixir dependencies"},{pattern:"packages",type:"directory",description:".NET/NuGet packages"},{pattern:".gradle",type:"directory",description:"Gradle cache"},{pattern:".m2",type:"directory",description:"Maven repository"},{pattern:".dart_tool",type:"directory",description:"Dart/Flutter tools"},{pattern:".stack-work",type:"directory",description:"Haskell Stack build"},{pattern:".bundle",type:"directory",description:"Ruby Bundler cache"},{pattern:"__pycache__",type:"directory",description:"Python bytecode cache"},{pattern:".venv",type:"directory",description:"Python virtual environment"},{pattern:"venv",type:"directory",description:"Python virtual environment"},{pattern:".git",type:"directory",description:"Git repository"},{pattern:".svn",type:"directory",description:"Subversion repository"},{pattern:".hg",type:"directory",description:"Mercurial repository"},{pattern:"dist",type:"directory",description:"Distribution files"},{pattern:"build",type:"directory",description:"Build output"},{pattern:"out",type:"directory",description:"Output directory"},{pattern:"target",type:"directory",description:"Rust/Java build target"},{pattern:"_build",type:"directory",description:"Elixir build output"},{pattern:"dist-newstyle",type:"directory",description:"Haskell Cabal build"},{pattern:"zig-cache",type:"directory",description:"Zig build cache"},{pattern:"zig-out",type:"directory",description:"Zig build output"},{pattern:"nimcache",type:"directory",description:"Nim build cache"},{pattern:".dub",type:"directory",description:"D package manager cache"},{pattern:"bin",type:"directory",description:"Binary output"},{pattern:"obj",type:"directory",description:"Object files"},{pattern:"coverage",type:"directory",description:"Test coverage reports"},{pattern:".nyc_output",type:"directory",description:"NYC coverage output"},{pattern:"reports",type:"directory",description:"Test/build reports"},{pattern:".next",type:"directory",description:"Next.js build output"},{pattern:".nuxt",type:"directory",description:"Nuxt.js build output"},{pattern:".cache",type:"directory",description:"Cache directory"},{pattern:".parcel-cache",type:"directory",description:"Parcel cache"},{pattern:".webpack",type:"directory",description:"Webpack cache"},{pattern:".vscode",type:"directory",description:"VS Code settings"},{pattern:".idea",type:"directory",description:"IntelliJ IDEA settings"},{pattern:".elixir_ls",type:"directory",description:"Elixir Language Server cache"},{pattern:".sublime-project",type:"file",description:"Sublime Text project"},{pattern:".sublime-workspace",type:"file",description:"Sublime Text workspace"},{pattern:".DS_Store",type:"file",description:"macOS metadata"},{pattern:"Thumbs.db",type:"file",description:"Windows thumbnails"},{pattern:"desktop.ini",type:"file",description:"Windows folder settings"},{pattern:"*.log",type:"file",description:"Log files"},{pattern:"*.tmp",type:"file",description:"Temporary files"},{pattern:"*.temp",type:"file",description:"Temporary files"},{pattern:"*.swp",type:"file",description:"Vim swap files"},{pattern:"*.swo",type:"file",description:"Vim swap files"},{pattern:"*~",type:"file",description:"Backup files"},{pattern:"*.zip",type:"file",description:"ZIP archives"},{pattern:"*.tar.gz",type:"file",description:"Tar archives"},{pattern:"*.exe",type:"file",description:"Windows executables"},{pattern:"*.dll",type:"file",description:"Windows libraries"},{pattern:"*.so",type:"file",description:"Shared libraries"},{pattern:"*.dylib",type:"file",description:"macOS dynamic libraries"},{pattern:"*.class",type:"file",description:"Java bytecode"},{pattern:"*.pyc",type:"file",description:"Python bytecode"},{pattern:"*.pyo",type:"file",description:"Python optimized bytecode"}];static customPatterns=[];static shouldIgnore(J,Q){let Z=[...XX.DEFAULT_PATTERNS,...XX.customPatterns];for(let X of Z){if(X.type==="directory"&&!Q)continue;if(X.type==="file"&&Q)continue;if(XX.matchesPattern(J,X.pattern))return!0}return!1}static addCustomPattern(J){XX.customPatterns.push(J)}static clearCustomPatterns(){XX.customPatterns=[]}static getAllPatterns(){return[...XX.DEFAULT_PATTERNS,...XX.customPatterns]}static matchesPattern(J,Q){let X=J.replace(/\\/g,"/").split("/"),Y=X[X.length-1];if(Q.includes("*"))return XX.matchesGlob(Y??"",Q);return X.some((K)=>K===Q)}static matchesGlob(J,Q){let Z=Q.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${Z}$`).test(J)}}});import{spawn as G99}from"node:child_process";import{promises as ob1}from"node:fs";import{realpath as h56}from"node:fs/promises";import{dirname as z99,join as tb1,relative as g56,resolve as U99}from"node:path";class eb1{async scanDirectory(J,Q={respectIgnorePatterns:!0}){let Z=Date.now(),X=U99(J),{respectIgnorePatterns:Y=!0,maxDepth:K=20,maxFiles:q=1e5,onProgress:G,signal:z,forceNodeJS:U=!1,strategy:W="auto",followSymlinks:F=!1}=Q,H="nodejs",B=[],M=!1,V=0,N=await h56(X).catch(()=>X),L=new Set;try{if(U||W==="nodejs")H="nodejs";else{let R=await this.tryExternalTools(X,W,z,{followSymlinks:F});if(R)B=R.entries,H=R.strategy,M=!0;else H="nodejs"}if(H==="nodejs"){let R=await this.scanWithNodeJS(X,{respectIgnorePatterns:Y,maxDepth:K,maxFiles:q,onProgress:G||(()=>{}),signal:z||new AbortController().signal},{followSymlinks:F,rootRealPath:N,visitedRealDirs:L});B=R.entries,V=R.skippedPaths}if(H!=="nodejs"){if(isFinite(q))B=B.slice(0,q);if(G){let R=B.filter((w)=>w.kind==="file").length,I=B.filter((w)=>w.kind==="directory").length;G({scannedFiles:R,scannedDirectories:I,currentPath:X})}}}catch(R){if(R instanceof Error&&(R.name==="AbortError"||R.message==="Scan aborted"))throw R;a.warn("Directory scan completed with errors",{error:R})}let A=Date.now()-Z,O=B.filter((R)=>R.kind==="file").length,j=B.filter((R)=>R.kind==="directory").length;return{entries:B,stats:{totalFiles:O,totalDirectories:j,scanDuration:A,skippedPaths:V,strategy:H,externalToolsAvailable:M}}}async tryExternalTools(J,Q,Z,X){let Y=[];if(Q==="auto")if(X.followSymlinks)Y.push("ripgrep");else Y.push("git","ripgrep");else if(Q==="git"){if(!X.followSymlinks)Y.push("git")}else if(Q==="ripgrep")Y.push("ripgrep");for(let K of Y)try{a.debug("Attempting to use external tool",{tool:K});let q=await this.runExternalTool(K,J,Z,{followSymlinks:X.followSymlinks});if(q.length>0)return{entries:q,strategy:K};else a.debug("External tool returned no entries, trying next",{tool:K})}catch(q){a.debug("External tool failed, trying next",{tool:K,error:q})}return a.debug("All external tools failed, falling back to Node.js scanning"),null}async runExternalTool(J,Q,Z,X){let Y=J==="git"?"git":await xN(),K=J==="git"?["ls-files","--exclude-standard","--cached","--others"]:X.followSymlinks?["--files","--follow"]:["--files"];return a.debug("Running external tool",{command:Y,args:K,rootPath:Q}),new Promise((q,G)=>{let z=G99(Y,K,{cwd:Q,stdio:["ignore","pipe","pipe"]}),U="",W="";if(z.stdout?.on("data",(F)=>{U+=F.toString()}),z.stderr?.on("data",(F)=>{W+=F.toString()}),Z)Z.addEventListener("abort",()=>{z.kill("SIGTERM"),G(Error("Scan aborted"))},{once:!0});z.on("close",(F)=>{if(F!==0){if(!W.trim().split(`
|
5441
5441
|
`).filter((M)=>M.length>0).every((M)=>M.includes("No such file or directory"))){a.debug("External tool failed",{command:Y,code:F,stderr:W}),G(Error(`${Y} exited with code ${F}: ${W}`));return}}try{let H=U.trim().split(`
|
5442
|
-
`).filter((L)=>L.length>0),B=new Set,M=H.map((L)=>{let A=this.createEntryFromPath(tb1(Q,L),{size:0,mtime:new Date,isDirectory:!1,isFile:!0,isSymlink:!1}),O=L;while(O!==""&&O!==".")if(O=z99(O),O&&O!=="."&&!B.has(O))B.add(O);return A}),V=Array.from(B).map((L)=>{return this.createEntryFromPath(tb1(Q,L),{size:0,mtime:new Date,isDirectory:!0,isFile:!1,isSymlink:!1})}),N=[...M,...V];q(N)}catch(H){G(H)}}),z.on("error",(F)=>{G(F)})})}async scanWithNodeJS(J,Q,Z){if(Q.signal?.aborted)throw Error("Scan aborted");let X=[],Y={scannedFiles:0,scannedDirectories:0,skippedPaths:0};return await this.scanDirectoryRecursive(J,J,0,Q,X,Y,Z),{entries:X,skippedPaths:Y.skippedPaths}}async scanDirectoryRecursive(J,Q,Z,X,Y,K,q){if(X.signal?.aborted)throw Error("Scan aborted");if(Z>X.maxDepth)return;if(Y.length>=X.maxFiles)return;let G=g56(Q,J);if(X.respectIgnorePatterns&&G){if(XX.shouldIgnore(G,!0)){K.skippedPaths++;return}}let z;try{z=await ob1.readdir(J,{withFileTypes:!0})}catch(U){if(U instanceof Error){if("code"in U&&(U.code==="EACCES"||U.code==="EPERM")){K.skippedPaths++;return}if("code"in U&&U.code==="ENOENT")return}throw U}for(let U of z){if(X.signal?.aborted)throw Error("Scan aborted");if(Y.length>=X.maxFiles)break;let W=tb1(J,U.name),F=g56(Q,W);if(X.respectIgnorePatterns){if(XX.shouldIgnore(F,U.isDirectory())){K.skippedPaths++;continue}}try{let H,B=!1;if(U.isDirectory())H=this.createEntryFromPath(W,{size:0,mtime:new Date,isDirectory:!0,isFile:!1,isSymlink:!1}),K.scannedDirectories++,B=!0;else if(U.isSymbolicLink()&&q.followSymlinks){let M=await ob1.stat(W).catch(()=>null);if(M&&M.isDirectory())H=this.createEntryFromPath(W,{size:0,mtime:M.mtime,isDirectory:!0,isFile:!1,isSymlink:!0}),K.scannedDirectories++,B=!0;else if(M)H=this.createEntryFromPath(W,{size:M.size,mtime:M.mtime,isDirectory:!1,isFile:!0,isSymlink:!0}),K.scannedFiles++;else{K.skippedPaths++;continue}}else{let M=await ob1.stat(W);H=this.createEntryFromPath(W,{size:M.size,mtime:M.mtime,isDirectory:!1,isFile:!0,isSymlink:M.isSymbolicLink()}),K.scannedFiles++}if(Y.push(H),X.onProgress&&Y.length%100===0)X.onProgress({scannedFiles:K.scannedFiles,scannedDirectories:K.scannedDirectories,currentPath:W});if(B){let M=await h56(W).catch(()=>null);if(!M){K.skippedPaths++;continue}if(q.visitedRealDirs.has(M))continue;q.visitedRealDirs.add(M),await this.scanDirectoryRecursive(W,Q,Z+1,X,Y,K,q)}}catch(H){if(H instanceof Error){if("code"in H&&(H.code==="EACCES"||H.code==="EPERM"||H.code==="ENOENT")){K.skippedPaths++;continue}}a.warn("Error processing file",{error:H}),K.skippedPaths++}}}createEntryFromPath(J,Q){let Z;if(Q.isDirectory)Z="directory";else Z="file";let X={size:Q.size,mtime:Q.mtime.getTime(),isSymlink:Q.isSymlink},Y=J,K=P0.file(J);return new VV({id:Y,kind:Z,path:J,uri:K,metadata:X})}}var m56=u(()=>{n6();B0();hR();rb1();sb1()});import{exec as W99,execFile as F99,execSync as u56}from"node:child_process";import{promises as S41}from"node:fs";import{join as AO}from"node:path";import{promisify as p56}from"node:util";class d56{async watch(J){}unwatch(J){}dispose(){}onFileSystemEvent(J){}offFileSystemEvent(J){}getWatchedPaths(){return[]}isSupported(){return!1}}class c56{watchedPaths=new Map;callbacks=[];pollInterval;constructor(J=1000){this.pollInterval=J}async watch(J){if(this.watchedPaths.has(J))return;let{promises:Q}=await import("node:fs"),Z=new Map;try{await this.scanPath(Q,J,Z)}catch(Y){throw Error(`Failed to watch path ${J}: ${Y}`)}let X=setInterval(async()=>{try{await this.checkForChanges(Q,J,Z)}catch(Y){a.warn("Error polling path",{path:J,error:Y})}},this.pollInterval);this.watchedPaths.set(J,{interval:X,lastModified:Z})}unwatch(J){let Q=this.watchedPaths.get(J);if(Q)clearInterval(Q.interval),this.watchedPaths.delete(J)}dispose(){for(let J of Array.from(this.watchedPaths.keys()))this.unwatch(J);this.callbacks.length=0}onFileSystemEvent(J){this.callbacks.push(J)}offFileSystemEvent(J){let Q=this.callbacks.indexOf(J);if(Q>=0)this.callbacks.splice(Q,1)}getWatchedPaths(){return Array.from(this.watchedPaths.keys())}isSupported(){return!0}async scanPath(J,Q,Z){try{let X=await J.stat(Q);if(Z.set(Q,X.mtime.getTime()),X.isDirectory()){let Y=await J.readdir(Q);for(let K of Y){let q=AO(Q,K);await this.scanPath(J,q,Z)}}}catch(X){}}async checkForChanges(J,Q,Z){let X=[],Y=new Map;await this.scanPath(J,Q,Y);for(let[K,q]of Array.from(Y.entries())){let G=Z.get(K);if(G===void 0)X.push({type:"created",path:K,timestamp:Date.now(),isDirectory:await this.isDirectory(J,K)});else if(q>G)X.push({type:"modified",path:K,timestamp:Date.now(),isDirectory:await this.isDirectory(J,K)})}for(let K of Array.from(Z.keys()))if(!Y.has(K))X.push({type:"deleted",path:K,timestamp:Date.now(),isDirectory:!1});Z.clear();for(let[K,q]of Array.from(Y.entries()))Z.set(K,q);if(X.length>0)for(let K of this.callbacks)try{K(X)}catch(q){a.error("Error in file watcher callback",{error:q})}}async isDirectory(J,Q){try{return(await J.stat(Q)).isDirectory()}catch{return!1}}}class RT{static isRepo(J){try{return u56("git rev-parse --is-inside-work-tree",{cwd:J,stdio:"ignore"}),!0}catch{return!1}}repos=new Map;callbacks=[];ongoingScans=new Map;scanCooldownMs;constructor(J=5000){this.scanCooldownMs=J}async resolveRepoRoot(J){let{stdout:Q}=await v41("git",["rev-parse","--show-toplevel"],{cwd:J});return Q.trim()}async watch(J){let Q=await this.resolveRepoRoot(J);if(this.repos.has(Q))return;await this.initialise(Q)}unwatch(J){if(!this.repos.get(J))return;this.repos.delete(J),this.ongoingScans.delete(J)}dispose(){for(let J of Array.from(this.repos.keys()))this.unwatch(J);this.callbacks.length=0}onFileSystemEvent(J){this.callbacks.push(J)}offFileSystemEvent(J){let Q=this.callbacks.indexOf(J);if(Q!==-1)this.callbacks.splice(Q,1)}getWatchedPaths(){return Array.from(this.repos.keys())}isSupported(){try{return u56("git --version",{stdio:"ignore"}),!0}catch{return!1}}async triggerScan(J,Q=!1){let Z=await this.resolveRepoRoot(J),X=this.repos.get(Z),Y=!X;if(!X){if(a.debug("First time watching repo",{repoRoot:Z}),await this.watch(J),X=this.repos.get(Z),!X)return;return}let K=Date.now(),q=K-X.lastScanTime;if(!Q&&q<this.scanCooldownMs)return;a.debug("Starting scan",{repoRoot:Z,force:Q,timeSinceLastScan:q}),X.lastScanTime=K,await this.scan(Z)}async reset(J){let Q=await this.resolveRepoRoot(J),Z=this.repos.get(Q);if(!Z)return;Z.cancelled=!0;let X=this.ongoingScans.get(Q);if(X)await X.catch(()=>{});this.repos.delete(Q),this.ongoingScans.delete(Q),await this.watch(J)}async initialise(J){let Q=Date.now(),Z=await v41("git",["ls-files","--others","--exclude-standard","-z"],{cwd:J,maxBuffer:67108864}),X=new Set,Y=Z.stdout.split("\x00").filter(Boolean);for(let K of Y){let q=AO(J,K);X.add(q)}this.repos.set(J,{lastScanTime:Q,seenUntracked:X})}async scan(J){let Q=this.repos.get(J);if(!Q||Q.cancelled)return;let Z=this.performScan(J);this.ongoingScans.set(J,Z);try{await Z}finally{if(this.ongoingScans.get(J)===Z)this.ongoingScans.delete(J)}}async performScan(J){let Q=this.repos.get(J);if(!Q||Q.cancelled)return;let Z=Date.now();try{let[X,Y]=await Promise.all([v41("git",["ls-files","--others","--exclude-standard","-z"],{cwd:J,maxBuffer:1/0,timeout:60000}),v41("git",["ls-files","--deleted","-z"],{cwd:J,maxBuffer:1/0,timeout:60000})]),K=X.stdout.split("\x00").filter(Boolean),q=Y.stdout.split("\x00").filter(Boolean),G=K.map((V)=>AO(J,V)),z=q.map((V)=>AO(J,V)),U=[],W=[],F=[],H=this.repos.get(J);if(!H||H.cancelled)return;let B=[],M=new Set;for(let V of K){let N=AO(J,V);M.add(N);try{let L=await S41.stat(N);if(!L.isFile())continue;if(!H.seenUntracked.has(N))U.push(N),B.push({type:"created",path:N,timestamp:L.mtimeMs,isDirectory:!1});else F.push(N)}catch{}}for(let V of Array.from(H.seenUntracked))if(!M.has(V)){if(!await S41.access(V).then(()=>!0).catch(()=>!1))B.push({type:"deleted",path:V,timestamp:Z,isDirectory:!1})}for(let V of q){let N=AO(J,V);B.push({type:"deleted",path:N,timestamp:Z,isDirectory:!1})}if(a.debug("Git status discovery (ls-files)",{repoRoot:J,untrackedDiscovered:G,deletedDiscovered:z,createdNew:U,createdNotNew:W,createdSeen:F,counts:{untracked:G.length,deleted:z.length,createdNew:U.length,createdSeen:F.length},durationMs:Date.now()-Z}),H.seenUntracked=M,H.lastScanTime=Z,B.length)for(let V of this.callbacks)V(B)}catch(X){a.warn("Fast ls-files scan failed, falling back to full status",{repoRoot:J,error:X instanceof Error?X.message:String(X),duration:Date.now()-Z}),await this.performFullStatusScan(J)}}async performFullStatusScan(J){let Q=this.repos.get(J);if(!Q||Q.cancelled)return;let Z=Date.now(),{stdout:X}=await H99(B99,{cwd:J,maxBuffer:16777216}),Y=this.repos.get(J);if(!Y||Y.cancelled)return;let K=[],q=[],G=[],z=[],U=[];for(let W of this.parseStatus(X)){let F=AO(J,W.path);if(W.type==="created"){q.push(F);let H=await S41.stat(F).catch(()=>null);if(!H){U.push(F);continue}if(H.isFile()&&H.mtimeMs>Y.lastScanTime)z.push(F),K.push({type:"created",path:F,timestamp:H.mtimeMs,isDirectory:!1});else U.push(F)}if(W.type==="deleted")G.push(F),K.push({type:"deleted",path:F,timestamp:Z,isDirectory:!1})}if(a.debug("Git status discovery (status)",{repoRoot:J,createdDiscovered:q,deletedDiscovered:G,createdNew:z,createdNotNew:U,counts:{createdDiscovered:q.length,deletedDiscovered:G.length,createdNew:z.length,createdNotNew:U.length}}),K.length)for(let W of this.callbacks)W(K)}parseStatus(J){let Q=[],Z=J.split("\x00");for(let X of Z){if(!X)continue;let Y=X[0];if(Y==="?"){let K=X.slice(2);Q.push({type:"created",path:K});continue}if(Y==="1"){let K=X[2],q=X.substring(X.indexOf("\t")+1);if(K==="D")Q.push({type:"deleted",path:q});else if(K==="A")Q.push({type:"created",path:q})}}return Q}}function k41(J){if(J?.useGit)return new RT(J.pollInterval);if(J?.usePolling)return new c56(J.pollInterval);let Q=J?.rootPath||process.cwd();if(RT.isRepo(Q)){let Z=new RT(J?.pollInterval);if(Z.isSupported())return a.info("Git repository detected, using GitFileWatcher",{rootPath:Q}),Z}return a.info("Not a git repository, using NoOpFileWatcher",{rootPath:Q}),new d56}var H99,v41,B99="git --no-optional-locks status --porcelain=v2 --untracked-files=normal --no-renames -z";var Jx1=u(()=>{B0();H99=p56(W99),v41=p56(F99)});class l56{config;queryChars;queryLower;constructor(J,Q={}){this.config={...D99,...Q};let Z=J.replace(/^[@#]+/,"");if(this.queryChars=Array.from(Z),this.queryLower=Array.from(Z.toLowerCase()),this.config.smartCase)this.config.caseSensitive=Z!==Z.toLowerCase()}match(J){if(this.queryChars.length===0)return J.filter((Z)=>Z.shouldIncludeInResults()).map((Z)=>{let X=this.config.openFiles?.includes(Z.path)?300:0,Y=Z.getImportanceBoost()+X;return{entry:Z,score:Y,matchPositions:[],highlightedPath:Z.path}}).sort((Z,X)=>X.score-Z.score).slice(0,this.config.maxResults);let Q=this.matchWithSemanticScoring(J);if(Q.length>0)return Q;return this.matchWithFuzzyScoring(J)}matchWithSemanticScoring(J){let Q=[],Z=0,X=this.queryChars.join(""),Y=this.queryChars[0],q=this.queryChars.length===1&&Y!==void 0&&/[a-z]/i.test(Y)?1e4:20000;for(let G of J){if(!G.shouldIncludeInResults())continue;if(X.length>5&&!this.passesCharBagFilter(X,G))continue;let z=this.matchEntrySemantic(G);if(z&&z.score>=this.config.minScore)Q.push(z);if(Z++,Q.length>=this.config.maxResults*5||Z>=q)break}return Q.sort((G,z)=>{let U=z.score-G.score;if(Math.abs(U)>0.001)return U;return G.entry.path.length-z.entry.path.length}),Q.slice(0,this.config.maxResults)}matchWithFuzzyScoring(J){let Q=[],Z=0,X=this.queryChars.join(""),Y=this.queryChars[0],q=this.queryChars.length===1&&Y!==void 0&&/[a-z]/i.test(Y)?1e4:20000;for(let G of J){if(!G.shouldIncludeInResults())continue;if(X.length>5&&!this.passesCharBagFilter(X,G))continue;let z=this.matchEntryFuzzy(G);if(z)Q.push(z);if(Z++,Q.length>=this.config.maxResults*5||Z>=q)break}return Q.sort((G,z)=>{let U=z.score-G.score;if(Math.abs(U)>0.001)return U;return G.entry.path.length-z.entry.path.length}),Q.slice(0,this.config.maxResults)}matchEntrySemantic(J){let Q=J.path,Z=this.queryLower.join(""),X=this.calculateSemanticScore(Z,J);if(X===0)return null;let Y=this.applyTieBreakers(X,Z,J),K=this.findMatchPositions(Z,Q),q=this.createHighlightedPath(Q,K);return{entry:J,score:Y,matchPositions:K,highlightedPath:q}}matchEntryFuzzy(J){let Q=J.path,Z=this.queryLower.join(""),X=this.calculateFuzzyScore(Z,J);if(X===0)return null;let Y=this.applyTieBreakers(X,Z,J),K=this.findMatchPositions(Z,Q),q=this.createHighlightedPath(Q,K);return{entry:J,score:Y,matchPositions:K,highlightedPath:q}}calculateSemanticScore(J,Q){let Z=J.toLowerCase(),X=Q.path,Y=X.toLowerCase(),K=this.getFilename(X),q=this.removeExtension(K).toLowerCase(),G=Y.split(/[/.\s-_]/).filter((F)=>F.length>0);if(J.endsWith("/")&&Q.isDirectory()){let F=Z.slice(0,-1);if(Y===F||Y.endsWith("/"+F))return tQ.EXACT_FILENAME+100;if(Y.includes(F))return tQ.SUBSTRING_FILENAME+50}if(q===Z||K.toLowerCase()===Z)return tQ.EXACT_FILENAME;if(q.startsWith(Z))return tQ.PREFIX_FILENAME;if(q.endsWith(Z))return tQ.SUFFIX_FILENAME;if(q.includes(Z))return tQ.SUBSTRING_FILENAME;let z=this.simpleTokens(Z);if(z.length>1){let F=this.matchTokensToSegments(z,G);if(F)return F}if(z.length===1&&Z.length>6){let F=this.progressiveSegmentMatch(Z,G);if(F)return F}if(G.includes(Z))return tQ.SEGMENT_EXACT;if(G.some((F)=>F.includes(Z)))return tQ.SEGMENT_SUBSTRING;if(G.join("").includes(Z))return tQ.SEGMENT_SUBSTRING;if(Y.replace(/[\s-_]/g,"").includes(Z))return tQ.PATH_SUBSTRING;return 0}calculateFuzzyScore(J,Q){let Z=J.toLowerCase(),X=Q.path.toLowerCase();if(this.fuzzyIn(Z,X))return tQ.FUZZY;return 0}applyTieBreakers(J,Q,Z){let X=J,Y=Math.abs(Z.path.length-Q.length);X-=0.01*Y;let K=Z.path.split("/").length-1;X-=0.1*K;let q=this.getFilename(Z.path),G=this.removeExtension(q).toLowerCase();if(/^(license|readme|copy(ing|left))$/i.test(G)&&K===1)X-=200;if(Z.metadata.mtime){let U=(Date.now()-Z.metadata.mtime)/86400000;if(U<30){let W=Math.max(0,1-U/30);X+=50*W}}if(this.config.openFiles?.includes(Z.path))X+=300;return X}simpleTokens(J){return J.replace(/([a-z])([A-Z0-9])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}progressiveSegmentMatch(J,Q){let Z=0,X=0,Y=0;for(let q of Q){if(Z>=J.length)break;let G="",z="none";if(Z+q.length<=J.length){if(J.slice(Z,Z+q.length)===q)G=q,z="exact"}if(!G&&q.length>=3){if(J.slice(Z).startsWith(q))G=q,z="prefix"}if(!G&&q.length>=3){let U=J.slice(Z);if(U.includes(q)&&U.indexOf(q)===0)G=q,z="substring"}if(!G){let U=J.slice(Z);if(U.length>=3&&q.includes(U))G=U,z="substring"}if(G){if(Z+=G.length,X++,z==="exact")Y++}}if(Z/J.length>=0.8&&X>=2)return Y>=2?tQ.SEGMENT_ORDERED_EXACT:tQ.SEGMENT_ORDERED_PARTIAL;return 0}matchTokensToSegments(J,Q){let Z=this.findTokenMatches(J,Q),X=this.getWorstMatchType(Z);return this.scoreFromMatchType(X)}findTokenMatches(J,Q){let Z=0,X=[];for(let Y of J){let K=!1;for(let q=Z;q<Q.length;q++){let G=Q[q];if(!G)continue;if(Y===G){X.push("exact"),Z=q+1,K=!0;break}else if(G.startsWith(Y)||Y.startsWith(G)||G.endsWith(Y)||G.includes(Y)||Y.includes(G)){X.push("partial"),Z=q+1,K=!0;break}}if(!K)return[]}return X}getWorstMatchType(J){if(J.length===0)return"none";if(J.includes("partial"))return"partial";return"exact"}scoreFromMatchType(J){switch(J){case"exact":return tQ.SEGMENT_ORDERED_EXACT;case"partial":return tQ.SEGMENT_ORDERED_PARTIAL;default:return 0}}fuzzyIn(J,Q){let Z=0;for(let X=0;X<Q.length&&Z<J.length;X++)if(Q[X]===J[Z])Z++;return Z===J.length}getFilename(J){return J.split("/").pop()||J}removeExtension(J){let Q=J.lastIndexOf(".");return Q>0?J.substring(0,Q):J}findMatchPositions(J,Q){let Z=[],X=Q.toLowerCase(),Y=J.toLowerCase();if(X.includes(Y)){let q=X.indexOf(Y);for(let G=0;G<Y.length;G++)Z.push(q+G);return Z}let K=0;for(let q of Y){let G=X.indexOf(q,K);if(G!==-1)Z.push(G),K=G+1}return Z}passesCharBagFilter(J,Q){if(J.includes("/")){let Z=J.split("/");for(let X of Z){if(X.trim()==="")continue;let Y=oQ.fromString(X);if(!Q.charBag.hasChars(Y))return!1}return!0}else{let Z=oQ.fromString(J);return Q.charBag.hasChars(Z)}}createHighlightedPath(J,Q){if(Q.length===0)return J;let Z="",X=0;for(let Y of Q){if(Y>=J.length)continue;Z+=J.slice(X,Y),Z+=`**${J[Y]}**`,X=Y+1}return Z+=J.slice(X),Z}}function i56(J,Q,Z){return new l56(J,Z).match(Q)}var D99,tQ;var a56=u(()=>{D99={minScore:400,caseSensitive:!1,penalizeLengthDifference:!0,maxResults:50,smartCase:!0},tQ={EXACT_FILENAME:1000,SEGMENT_ORDERED_EXACT:950,PREFIX_FILENAME:900,SUFFIX_FILENAME:850,SEGMENT_ORDERED_PARTIAL:840,SUBSTRING_FILENAME:800,SEGMENT_EXACT:650,SEGMENT_SUBSTRING:600,PATH_SUBSTRING:500,FUZZY:250}});class ym{metadata;entries;entriesByPath;entriesById;constructor(J,Q=[],Z,X){if(this.metadata=J,this.entries=Q,Z&&X)this.entriesByPath=Z,this.entriesById=X;else{let Y=new Map,K=new Map;for(let q of Q)Y.set(q.path,q),K.set(q.id,q);this.entriesByPath=Y,this.entriesById=K}this.cachedArray=Array.from(this.entriesByPath.values()),this.entriesArrayDirty=!1}static create(J){let Q=Date.now();return new ym({id:Q,createdAt:Q,rootPath:J,entryCount:0,scanStatus:"scanning"},[])}static fromEntries(J,Q){let Z=Date.now(),X={id:Z,createdAt:Z,rootPath:J,entryCount:Q.length,scanStatus:"complete"};return new ym(X,Q)}entriesArrayDirty=!1;cachedArray=[];getAllEntries(){if(this.entriesArrayDirty)this.cachedArray=[...this.entriesByPath.values()],this.entriesArrayDirty=!1;return this.cachedArray}getEntryByPath(J){return this.entriesByPath.get(J)??null}getEntryById(J){return this.entriesById.get(J)??null}applyChanges(J){let{added:Q=[],removed:Z=[],modified:X=[]}=J;for(let Y of Z){let K=this.entriesByPath.get(Y);if(K){if(this.entriesByPath.delete(Y),this.entriesById.delete(K.id),!this.entriesArrayDirty){let q=this.cachedArray.findIndex((G)=>G.path===Y);if(q>=0)this.cachedArray.splice(q,1)}}}for(let Y of[...Q,...X])if(this.entriesByPath.set(Y.path,Y),this.entriesById.set(Y.id,Y),!this.entriesArrayDirty){let K=this.cachedArray.findIndex((q)=>q.path===Y.path);if(K>=0)this.cachedArray.splice(K,1);this.cachedArray.unshift(Y)}this.metadata.entryCount=this.entriesByPath.size}findEntries(J){return this.entries.filter(J)}getFiles(){return this.findEntries((J)=>J.kind==="file")}getDirectories(){return this.findEntries((J)=>J.kind==="directory")}getInDirectory(J){let Q=J.endsWith("/")?J:J+"/";return this.findEntries((Z)=>Z.path.startsWith(Q)&&Z.path!==J)}hasPath(J){return this.entriesByPath.has(J)}getStats(){let J=this.metadata.entryCount||this.entries.length,Q=this.getFiles().length,Z=J-Q,X=J*250;return{totalEntries:J,fileEntries:Q,directoryEntries:Z,memoryUsage:X}}}var n56=()=>{};import{EventEmitter as M99}from"node:events";import{promises as V99}from"node:fs";import{relative as N99}from"node:path";var Qx1;var r56=u(()=>{n6();B0();m56();rb1();Jx1();sb1();a56();n56();Qx1=class Qx1 extends M99{rootPath;currentSnapshot=null;fileWatcher;scanner;isScanning=!1;stats;constructor(J,Q){super();this.rootPath=J;this.fileWatcher=Q??k41(),this.scanner=new eb1,this.stats={totalFiles:0,totalDirectories:0,lastScanDuration:0,lastScanTime:0,memoryUsage:0,status:"idle"},this.fileWatcher.onFileSystemEvent(this.handleFileSystemEvents.bind(this))}async initialize(J){if(this.isScanning)throw Error("Index is already being initialized");try{await this.performFullScan(J),await this.fileWatcher.watch(this.rootPath)}catch(Q){throw this.updateStatus("error"),Q}}async rescan(J){await this.performFullScan(J)}getCurrentSnapshot(){return this.currentSnapshot}getStats(){return{...this.stats}}search(J,Q={}){if(this.fileWatcher.triggerScan)this.fileWatcher.triggerScan(this.rootPath).catch(()=>{});if(!this.currentSnapshot)return[];let{limit:Z=50,minScore:X=0.1,includeDirectories:Y=!0,includeIgnored:K=!1}=Q,q=this.currentSnapshot.getAllEntries(),G=J.replace(/[@/]/g,"");if(G.length>2){if(q.some((F)=>F.path.includes(G))){let F=q.find((H)=>H.path.includes(G));a.debug("Search for existing file",{query:J,matchingFile:F?.path,entryIndex:q.findIndex((H)=>H===F)})}}q=q.filter((W)=>{if(!K&&W.isIgnored)return!1;if(!Y&&W.isDirectory())return!1;return W.shouldIncludeInMentions()});let z=i56(J,q,{minScore:X,openFiles:Q.openFiles});return z.sort((W,F)=>F.score-W.score),z.slice(0,Z)}dispose(){this.fileWatcher.dispose(),this.removeAllListeners()}async performFullScan(J){this.isScanning=!0,this.updateStatus("scanning");let Q=Date.now();try{let Z=await this.scanner.scanDirectory(this.rootPath,{respectIgnorePatterns:!0,...J});this.currentSnapshot=ym.fromEntries(this.rootPath,Z.entries);let X=Date.now()-Q;this.stats={...this.stats,totalFiles:Z.stats.totalFiles,totalDirectories:Z.stats.totalDirectories,lastScanDuration:X,lastScanTime:Q,memoryUsage:this.currentSnapshot.getStats().memoryUsage,status:"idle"},this.emit("scan-complete",{entries:Z.entries.length,duration:X}),this.emit("status-changed",this.getStats())}catch(Z){throw this.updateStatus("error"),this.emit("scan-error",Z),Z}finally{this.isScanning=!1}}async handleFileSystemEvents(J){if(!this.currentSnapshot||this.isScanning)return;this.updateStatus("updating");try{let Q=[],Z=[],X=[];for(let Y of J){let K=Y.path;switch(Y.type){case"deleted":Q.push(K);break;case"created":await this.processCreatedEvent(Y,Z);break;case"modified":await this.processModifiedEvent(Y,X);break;case"renamed":if(Y.oldPath)Q.push(Y.oldPath);await this.processCreatedEvent(Y,Z);break}}if(this.currentSnapshot.applyChanges({removed:Q,added:Z,modified:X}),Q.length>0||Z.length>0||X.length>0)a.debug("Incremental snapshot update",{removed:Q.length,added:Z.length,modified:X.length,totalEntries:this.currentSnapshot.metadata.entryCount,sampleAdded:Z.slice(0,3).map((Y)=>Y.path),sampleRemoved:Q.slice(0,3)});this.stats={...this.stats,memoryUsage:this.currentSnapshot.getStats().memoryUsage,status:"idle"},this.emit("files-updated",{added:Z.length,removed:Q.length,modified:X.length}),this.emit("status-changed",this.getStats())}catch(Q){this.updateStatus("error"),this.emit("scan-error",Q)}}async processCreatedEvent(J,Q){let Z=J.path;try{let X=J.stat||(J.isDirectory?null:await V99.lstat(Z)),Y=J.isDirectory,K=N99(this.rootPath,Z);if(XX.shouldIgnore(K,Y))return;if(Y)Q.push(new VV({id:Z,kind:"directory",path:Z,uri:P0.file(Z),metadata:{size:0,mtime:Date.now(),isSymlink:!1},isIgnored:!1}));else if(X)Q.push(new VV({id:Z,kind:"file",path:Z,uri:P0.file(Z),metadata:{size:X.size,mtime:X.mtimeMs,isSymlink:X.isSymbolicLink()},isIgnored:!1}))}catch{}}async processModifiedEvent(J,Q){let Z=this.currentSnapshot?.getEntryByPath(J.path);if(Z){let X=Z.withUpdates({metadata:{...Z.metadata,mtime:J.timestamp}});Q.push(X)}}updateStatus(J){this.stats={...this.stats,status:J},this.emit("status-changed",this.getStats())}}});import{execFile as L99}from"node:child_process";import{EventEmitter as A99}from"node:events";import{promises as _41,watch as O99}from"node:fs";import{join as wT}from"node:path";import{promisify as j99}from"node:util";async function s56(J,Q){if(!await Zx1.isRepo(J))return null;return new Zx1(J,Q?.pollInterval)}var R99,Zx1;var o56=u(()=>{B0();R99=j99(L99);Zx1=class Zx1 extends A99{repoRoot;pollInterval;on(J,Q){return super.on(J,Q)}emit(J,...Q){return super.emit(J,...Q)}currentSha;disposed=!1;started=!1;running=!1;pendingForce=!1;watchers=new Set;currentRefWatcher;timer;constructor(J,Q=30000){super();this.repoRoot=J;this.pollInterval=Q;this.repoRoot=this.validateRepoRoot(J)}static async isRepo(J){try{let Q=wT(J,".git");return await _41.access(Q),!0}catch{try{let Q=wT(J,"HEAD");return await _41.access(Q),!0}catch{return!1}}}async start(){if(this.disposed)throw Error("GitHeadWatcher has been disposed");if(this.started)throw Error("GitHeadWatcher has already been started");this.started=!0,this.currentSha=await this.getCurrentSha(),this.watch(wT(this.repoRoot,".git/HEAD"),async()=>{await this.updateRefWatcher(),this.scheduleCheck()}),await this.updateRefWatcher();let J=wT(this.repoRoot,".git/logs/HEAD");try{await _41.access(J),this.watch(J,()=>this.scheduleCheck(!0))}catch{}this.timer=setInterval(()=>this.scheduleCheck(),this.pollInterval),a.debug("GitHeadWatcher started",{repoRoot:this.repoRoot})}stop(){for(let J of Array.from(this.watchers))this.cleanupWatcher(J);if(this.timer)clearInterval(this.timer),this.timer=void 0;this.currentRefWatcher=void 0,this.started=!1,this.running=!1,this.pendingForce=!1}dispose(){if(this.disposed)return;this.stop(),this.disposed=!0,this.removeAllListeners()}watch(J,Q){let Z=O99(J);return Z.on("change",Q),Z.on("rename",()=>{this.cleanupWatcher(Z),setTimeout(()=>{if(!this.disposed)this.watch(J,Q),this.scheduleCheck(!0)},50)}),Z.on("error",(X)=>{a.debug("Git file watcher error",{filePath:J,error:X}),this.cleanupWatcher(Z)}),this.watchers.add(Z),Z}cleanupWatcher(J){try{J.removeAllListeners(),J.close()}catch(Q){a.debug("Error during watcher cleanup",{error:Q})}this.watchers.delete(J)}async updateRefWatcher(){if(this.currentRefWatcher)this.cleanupWatcher(this.currentRefWatcher),this.currentRefWatcher=void 0;try{let J=await _41.readFile(wT(this.repoRoot,".git/HEAD"),"utf8");if(!J)return;let Q=J.trim();if(Q.startsWith("ref: ")){let Z=Q.slice(5),X=wT(this.repoRoot,".git",Z);this.currentRefWatcher=this.watch(X,()=>this.scheduleCheck())}}catch(J){a.debug("Failed to update ref watcher",{repoRoot:this.repoRoot,error:J})}}scheduleCheck(J=!1){if(this.disposed)return;if(this.pendingForce||=J,this.running)return;this.running=!0,queueMicrotask(async()=>{if(this.disposed)return;let Q=this.pendingForce;this.pendingForce=!1;try{await this.performCheck(Q)}finally{this.running=!1}})}async checkForChanges(J=!1){this.scheduleCheck(J)}async performCheck(J){if(this.disposed)return;try{let Q=await this.getCurrentSha();if(!Q&&this.currentSha){a.warn("Failed to get current SHA, keeping previous value",{repoRoot:this.repoRoot,previousSha:this.currentSha.slice(0,7)});return}if(Q&&Q!==this.currentSha&&this.currentSha||J){let Z=this.currentSha;this.currentSha=Q??this.currentSha,this.emit("head-change",{oldSha:Z,newSha:this.currentSha,repoRoot:this.repoRoot,force:J})}else if(Q!==this.currentSha)this.currentSha=Q}catch(Q){a.warn("Error checking for git HEAD changes",{repoRoot:this.repoRoot,error:Q})}}async getCurrentSha(){try{let{stdout:J}=await R99("git",["rev-parse","HEAD"],{cwd:this.repoRoot});return J.trim()}catch(J){return}}validateRepoRoot(J){if(!J||typeof J!=="string")throw Error("Repository root must be a valid string path");if(!J.startsWith("/")&&!J.match(/^[A-Za-z]:\\/))throw Error("Repository root must be an absolute path");return J}}});class b41{indexes=new Map;headWatchers=new Map;reindexingWorkspaces=new Set;config;disposed=!1;static forWorkspace(J){return new b41({workspaceRoots:[J],scanOnStartup:!0,maxIndexedFiles:500000,enableFileWatching:!0,usePollingFallback:!1,enableHeadWatching:!0,followSymlinkDirs:!0})}constructor(J){this.config={...J}}async initialize(){if(this.disposed)throw Error("Service has been disposed");if(this.config.scanOnStartup){let J=this.config.workspaceRoots.map((Q)=>this.indexWorkspace(Q));await Promise.allSettled(J)}}async indexWorkspace(J){if(this.disposed)throw Error("Service has been disposed");if(this.indexes.has(J)){await this.indexes.get(J).rescan();return}let Q=this.config.enableFileWatching?k41({rootPath:J,usePolling:this.config.usePollingFallback}):void 0,Z=new Qx1(J,Q);Z.on("scan-error",(Y)=>{a.error("Scan error in workspace",{rootPath:J,error:Y})});let X={respectIgnorePatterns:!0,maxFiles:this.config.maxIndexedFiles,followSymlinks:this.config.followSymlinkDirs};try{if(await Z.initialize(X),this.indexes.set(J,Z),this.config.enableHeadWatching)await this.setupHeadWatching(J,Z,Q)}catch(Y){Z.dispose();let K=this.headWatchers.get(J);if(K)K.dispose(),this.headWatchers.delete(J);throw Y}}async removeWorkspace(J){let Q=this.indexes.get(J);if(Q)Q.dispose(),this.indexes.delete(J);let Z=this.headWatchers.get(J);if(Z)Z.dispose(),this.headWatchers.delete(J)}searchAll(J,Q){let Z=[];for(let X of this.indexes.values())try{let Y=X.search(J,Q);Z.push(...Y)}catch(Y){}return Z.sort((X,Y)=>Y.score-X.score),Q?.limit?Z.slice(0,Q.limit):Z}searchWorkspace(J,Q,Z){let X=this.indexes.get(J);if(!X)return[];try{return X.search(Q,Z)}catch(Y){return a.error(`Search error in workspace ${J}:`,Y),[]}}getIndexStats(J){if(J){let Z=this.indexes.get(J);if(Z)return[{...Z.getStats(),rootPath:J}];return[]}let Q=[];for(let[Z,X]of this.indexes.entries())Q.push({...X.getStats(),rootPath:Z});return Q}getConfig(){return{...this.config}}updateConfig(J){this.config={...this.config,...J}}async rescanAll(){let J=[];for(let[Q,Z]of this.indexes.entries())J.push(Z.rescan().catch((X)=>{a.error(`Rescan error in workspace ${Q}:`,X)}));await Promise.allSettled(J)}getIndexedWorkspaces(){return Array.from(this.indexes.keys())}isWorkspaceIndexed(J){return this.indexes.has(J)}dispose(){if(this.disposed)return;for(let[,J]of this.indexes.entries())J.dispose();for(let[,J]of this.headWatchers.entries())J.dispose();this.indexes.clear(),this.headWatchers.clear(),this.disposed=!0}isDisposed(){return this.disposed}async setupHeadWatching(J,Q,Z){try{let X=await s56(J);if(!X)return;X.on("head-change",async({oldSha:Y,newSha:K})=>{if(this.reindexingWorkspaces.has(J)){a.debug("Re-index already in progress, skipping",{rootPath:J});return}this.reindexingWorkspaces.add(J);try{if(await Q.rescan(),Z&&Z instanceof RT)await Z.reset(J);a.debug("Re-index completed after HEAD change",{rootPath:J})}catch(q){a.error("Failed to re-index after change",{rootPath:J,error:q})}finally{this.reindexingWorkspaces.delete(J)}}),await X.start(),this.headWatchers.set(J,X),a.debug("Git HEAD watching enabled",{rootPath:J})}catch(X){a.warn("Failed to setup git HEAD watching",{rootPath:J,error:X})}}}function Xx1(J,Q){let Z={workspaceRoots:J,scanOnStartup:!0,maxIndexedFiles:500000,enableFileWatching:!0,usePollingFallback:!1,enableHeadWatching:!0,followSymlinkDirs:!0,...Q};return new b41(Z)}var t56=u(()=>{B0();Jx1();r56();o56()});var e56=u(()=>{t56()});import w99 from"node:os";import x41 from"node:path";class y41{rootPath;opts;startInBackground;fuzzyService=null;state="unstarted";initPromise=null;constructor(J=process.cwd(),Q={},Z=!1){this.rootPath=J;this.opts=Q;this.startInBackground=Z;if(Z)this.initPromise=this.init(),this.initPromise.then(()=>{a.debug("Fuzzy service background initialization completed")}).catch((X)=>{a.debug("Fuzzy service background initialization failed",X)})}async start(){if(this.initPromise)return this.initPromise;return this.initPromise=this.init(),this.initPromise}async init(){if(x41.resolve(this.rootPath)===x41.resolve(w99.homedir())){a.debug("Skipping fuzzy service initialization for home directory");return}this.state="initializing";try{this.fuzzyService=Xx1([this.rootPath],{scanOnStartup:!0,enableFileWatching:!0,usePollingFallback:!1,...this.opts}),await this.fuzzyService.initialize(),this.state="ready"}catch(J){throw this.state="failed",a.error("Failed to initialize fuzzy service",J),J}}async query(J,Q=50,Z){if(this.initPromise)try{await this.initPromise}catch(Y){return a.warn("Background fuzzy initialization failed, returning empty results",Y),[]}if(!this.fuzzyService)return a.warn("Fuzzy service not initialized, returning empty results"),[];let X=(Y)=>x41.relative(this.rootPath,Y);try{let Y=J.trim();return this.fuzzyService.searchAll(Y,{limit:Q,minScore:Y?0.1:void 0,openFiles:Z}).map((q)=>X(q.entry.path))}catch(Y){return a.error("Fuzzy search failed",Y),[]}}async queryCompletions(J,Q=50,Z){if(this.initPromise)try{await this.initPromise}catch(Y){return a.warn("Background fuzzy initialization failed, returning empty results",Y),[]}if(!this.fuzzyService)return a.warn("Fuzzy service not initialized, returning empty results"),[];let X=(Y)=>x41.relative(this.rootPath,Y);try{let Y=J.trim();return this.fuzzyService.searchAll(Y,{limit:Q,minScore:Y?0.1:void 0,openFiles:Z}).map((q)=>({path:X(q.entry.path),kind:q.entry.isDirectory()?"folder":"file"}))}catch(Y){return a.error("Fuzzy search failed",Y),[]}}getStats(){return{state:this.state,stats:this.fuzzyService?.getIndexStats()??[]}}dispose(){if(this.fuzzyService)this.fuzzyService.dispose(),this.fuzzyService=null;this.state="unstarted",this.initPromise=null}}var JJ6=u(()=>{B0();e56()});function hm(J,Q=!1){let Z=J.length,X=0,Y="",K=0,q=16,G=0,z=0,U=0,W=0,F=0;function H(O,j){let R=0,I=0;while(R<O||!j){let w=J.charCodeAt(X);if(w>=48&&w<=57)I=I*16+w-48;else if(w>=65&&w<=70)I=I*16+w-65+10;else if(w>=97&&w<=102)I=I*16+w-97+10;else break;X++,R++}if(R<O)I=-1;return I}function B(O){X=O,Y="",K=0,q=16,F=0}function M(){let O=X;if(J.charCodeAt(X)===48)X++;else{X++;while(X<J.length&&IT(J.charCodeAt(X)))X++}if(X<J.length&&J.charCodeAt(X)===46)if(X++,X<J.length&&IT(J.charCodeAt(X))){X++;while(X<J.length&&IT(J.charCodeAt(X)))X++}else return F=3,J.substring(O,X);let j=X;if(X<J.length&&(J.charCodeAt(X)===69||J.charCodeAt(X)===101)){if(X++,X<J.length&&J.charCodeAt(X)===43||J.charCodeAt(X)===45)X++;if(X<J.length&&IT(J.charCodeAt(X))){X++;while(X<J.length&&IT(J.charCodeAt(X)))X++;j=X}else F=3}return J.substring(O,j)}function V(){let O="",j=X;while(!0){if(X>=Z){O+=J.substring(j,X),F=2;break}let R=J.charCodeAt(X);if(R===34){O+=J.substring(j,X),X++;break}if(R===92){if(O+=J.substring(j,X),X++,X>=Z){F=2;break}switch(J.charCodeAt(X++)){case 34:O+='"';break;case 92:O+="\\";break;case 47:O+="/";break;case 98:O+="\b";break;case 102:O+="\f";break;case 110:O+=`
|
5442
|
+
`).filter((L)=>L.length>0),B=new Set,M=H.map((L)=>{let A=this.createEntryFromPath(tb1(Q,L),{size:0,mtime:new Date,isDirectory:!1,isFile:!0,isSymlink:!1}),O=L;while(O!==""&&O!==".")if(O=z99(O),O&&O!=="."&&!B.has(O))B.add(O);return A}),V=Array.from(B).map((L)=>{return this.createEntryFromPath(tb1(Q,L),{size:0,mtime:new Date,isDirectory:!0,isFile:!1,isSymlink:!1})}),N=[...M,...V];q(N)}catch(H){G(H)}}),z.on("error",(F)=>{G(F)})})}async scanWithNodeJS(J,Q,Z){if(Q.signal?.aborted)throw Error("Scan aborted");let X=[],Y={scannedFiles:0,scannedDirectories:0,skippedPaths:0};return await this.scanDirectoryRecursive(J,J,0,Q,X,Y,Z),{entries:X,skippedPaths:Y.skippedPaths}}async scanDirectoryRecursive(J,Q,Z,X,Y,K,q){if(X.signal?.aborted)throw Error("Scan aborted");if(Z>X.maxDepth)return;if(Y.length>=X.maxFiles)return;let G=g56(Q,J);if(X.respectIgnorePatterns&&G){if(XX.shouldIgnore(G,!0)){K.skippedPaths++;return}}let z;try{z=await ob1.readdir(J,{withFileTypes:!0})}catch(U){if(U instanceof Error){if("code"in U&&(U.code==="EACCES"||U.code==="EPERM")){K.skippedPaths++;return}if("code"in U&&U.code==="ENOENT")return}throw U}for(let U of z){if(X.signal?.aborted)throw Error("Scan aborted");if(Y.length>=X.maxFiles)break;let W=tb1(J,U.name),F=g56(Q,W);if(X.respectIgnorePatterns){if(XX.shouldIgnore(F,U.isDirectory())){K.skippedPaths++;continue}}try{let H,B=!1;if(U.isDirectory())H=this.createEntryFromPath(W,{size:0,mtime:new Date,isDirectory:!0,isFile:!1,isSymlink:!1}),K.scannedDirectories++,B=!0;else if(U.isSymbolicLink()&&q.followSymlinks){let M=await ob1.stat(W).catch(()=>null);if(M&&M.isDirectory())H=this.createEntryFromPath(W,{size:0,mtime:M.mtime,isDirectory:!0,isFile:!1,isSymlink:!0}),K.scannedDirectories++,B=!0;else if(M)H=this.createEntryFromPath(W,{size:M.size,mtime:M.mtime,isDirectory:!1,isFile:!0,isSymlink:!0}),K.scannedFiles++;else{K.skippedPaths++;continue}}else{let M=await ob1.stat(W);H=this.createEntryFromPath(W,{size:M.size,mtime:M.mtime,isDirectory:!1,isFile:!0,isSymlink:M.isSymbolicLink()}),K.scannedFiles++}if(Y.push(H),X.onProgress&&Y.length%100===0)X.onProgress({scannedFiles:K.scannedFiles,scannedDirectories:K.scannedDirectories,currentPath:W});if(B){let M=await h56(W).catch(()=>null);if(!M){K.skippedPaths++;continue}if(q.visitedRealDirs.has(M))continue;q.visitedRealDirs.add(M),await this.scanDirectoryRecursive(W,Q,Z+1,X,Y,K,q)}}catch(H){if(H instanceof Error){if("code"in H&&(H.code==="EACCES"||H.code==="EPERM"||H.code==="ENOENT")){K.skippedPaths++;continue}}a.warn("Error processing file",{error:H}),K.skippedPaths++}}}createEntryFromPath(J,Q){let Z;if(Q.isDirectory)Z="directory";else Z="file";let X={size:Q.size,mtime:Q.mtime.getTime(),isSymlink:Q.isSymlink},Y=J,K=P0.file(J);return new VV({id:Y,kind:Z,path:J,uri:K,metadata:X})}}var m56=u(()=>{n6();B0();hR();rb1();sb1()});import{exec as W99,execFile as F99,execSync as u56}from"node:child_process";import{promises as S41}from"node:fs";import{join as AO}from"node:path";import{promisify as p56}from"node:util";class d56{async watch(J){}unwatch(J){}dispose(){}onFileSystemEvent(J){}offFileSystemEvent(J){}getWatchedPaths(){return[]}isSupported(){return!1}}class c56{watchedPaths=new Map;callbacks=[];pollInterval;constructor(J=1000){this.pollInterval=J}async watch(J){if(this.watchedPaths.has(J))return;let{promises:Q}=await import("node:fs"),Z=new Map;try{await this.scanPath(Q,J,Z)}catch(Y){throw Error(`Failed to watch path ${J}: ${Y}`)}let X=setInterval(async()=>{try{await this.checkForChanges(Q,J,Z)}catch(Y){a.warn("Error polling path",{path:J,error:Y})}},this.pollInterval);this.watchedPaths.set(J,{interval:X,lastModified:Z})}unwatch(J){let Q=this.watchedPaths.get(J);if(Q)clearInterval(Q.interval),this.watchedPaths.delete(J)}dispose(){for(let J of Array.from(this.watchedPaths.keys()))this.unwatch(J);this.callbacks.length=0}onFileSystemEvent(J){this.callbacks.push(J)}offFileSystemEvent(J){let Q=this.callbacks.indexOf(J);if(Q>=0)this.callbacks.splice(Q,1)}getWatchedPaths(){return Array.from(this.watchedPaths.keys())}isSupported(){return!0}async scanPath(J,Q,Z){try{let X=await J.stat(Q);if(Z.set(Q,X.mtime.getTime()),X.isDirectory()){let Y=await J.readdir(Q);for(let K of Y){let q=AO(Q,K);await this.scanPath(J,q,Z)}}}catch(X){}}async checkForChanges(J,Q,Z){let X=[],Y=new Map;await this.scanPath(J,Q,Y);for(let[K,q]of Array.from(Y.entries())){let G=Z.get(K);if(G===void 0)X.push({type:"created",path:K,timestamp:Date.now(),isDirectory:await this.isDirectory(J,K)});else if(q>G)X.push({type:"modified",path:K,timestamp:Date.now(),isDirectory:await this.isDirectory(J,K)})}for(let K of Array.from(Z.keys()))if(!Y.has(K))X.push({type:"deleted",path:K,timestamp:Date.now(),isDirectory:!1});Z.clear();for(let[K,q]of Array.from(Y.entries()))Z.set(K,q);if(X.length>0)for(let K of this.callbacks)try{K(X)}catch(q){a.error("Error in file watcher callback",{error:q})}}async isDirectory(J,Q){try{return(await J.stat(Q)).isDirectory()}catch{return!1}}}class RT{static isRepo(J){try{return u56("git rev-parse --is-inside-work-tree",{cwd:J,stdio:"ignore"}),!0}catch{return!1}}repos=new Map;callbacks=[];ongoingScans=new Map;scanCooldownMs;constructor(J=5000){this.scanCooldownMs=J}async resolveRepoRoot(J){let{stdout:Q}=await v41("git",["rev-parse","--show-toplevel"],{cwd:J});return Q.trim()}async watch(J){let Q=await this.resolveRepoRoot(J);if(this.repos.has(Q))return;await this.initialise(Q)}unwatch(J){if(!this.repos.get(J))return;this.repos.delete(J),this.ongoingScans.delete(J)}dispose(){for(let J of Array.from(this.repos.keys()))this.unwatch(J);this.callbacks.length=0}onFileSystemEvent(J){this.callbacks.push(J)}offFileSystemEvent(J){let Q=this.callbacks.indexOf(J);if(Q!==-1)this.callbacks.splice(Q,1)}getWatchedPaths(){return Array.from(this.repos.keys())}isSupported(){try{return u56("git --version",{stdio:"ignore"}),!0}catch{return!1}}async triggerScan(J,Q=!1){let Z=await this.resolveRepoRoot(J),X=this.repos.get(Z),Y=!X;if(!X){if(a.debug("First time watching repo",{repoRoot:Z}),await this.watch(J),X=this.repos.get(Z),!X)return;return}let K=Date.now(),q=K-X.lastScanTime;if(!Q&&q<this.scanCooldownMs)return;a.debug("Starting scan",{repoRoot:Z,force:Q,timeSinceLastScan:q}),X.lastScanTime=K,await this.scan(Z)}async reset(J){let Q=await this.resolveRepoRoot(J),Z=this.repos.get(Q);if(!Z)return;Z.cancelled=!0;let X=this.ongoingScans.get(Q);if(X)await X.catch(()=>{});this.repos.delete(Q),this.ongoingScans.delete(Q),await this.watch(J)}async initialise(J){let Q=Date.now(),Z=await v41("git",["ls-files","--others","--exclude-standard","-z"],{cwd:J,maxBuffer:67108864}),X=new Set,Y=Z.stdout.split("\x00").filter(Boolean);for(let K of Y){let q=AO(J,K);X.add(q)}this.repos.set(J,{lastScanTime:Q,seenUntracked:X})}async scan(J){let Q=this.repos.get(J);if(!Q||Q.cancelled)return;let Z=this.performScan(J);this.ongoingScans.set(J,Z);try{await Z}finally{if(this.ongoingScans.get(J)===Z)this.ongoingScans.delete(J)}}async performScan(J){let Q=this.repos.get(J);if(!Q||Q.cancelled)return;let Z=Date.now();try{let[X,Y]=await Promise.all([v41("git",["ls-files","--others","--exclude-standard","-z"],{cwd:J,maxBuffer:1/0,timeout:60000}),v41("git",["ls-files","--deleted","-z"],{cwd:J,maxBuffer:1/0,timeout:60000})]),K=X.stdout.split("\x00").filter(Boolean),q=Y.stdout.split("\x00").filter(Boolean),G=K.map((V)=>AO(J,V)),z=q.map((V)=>AO(J,V)),U=[],W=[],F=[],H=this.repos.get(J);if(!H||H.cancelled)return;let B=[],M=new Set;for(let V of K){let N=AO(J,V);M.add(N);try{let L=await S41.stat(N);if(!L.isFile())continue;if(!H.seenUntracked.has(N))U.push(N),B.push({type:"created",path:N,timestamp:L.mtimeMs,isDirectory:!1});else F.push(N)}catch{}}for(let V of Array.from(H.seenUntracked))if(!M.has(V)){if(!await S41.access(V).then(()=>!0).catch(()=>!1))B.push({type:"deleted",path:V,timestamp:Z,isDirectory:!1})}for(let V of q){let N=AO(J,V);B.push({type:"deleted",path:N,timestamp:Z,isDirectory:!1})}if(a.debug("Git status discovery (ls-files)",{repoRoot:J,untrackedDiscovered:G,deletedDiscovered:z,createdNew:U,createdNotNew:W,createdSeen:F,counts:{untracked:G.length,deleted:z.length,createdNew:U.length,createdSeen:F.length},durationMs:Date.now()-Z}),H.seenUntracked=M,H.lastScanTime=Z,B.length)for(let V of this.callbacks)V(B)}catch(X){a.warn("Fast ls-files scan failed, falling back to full status",{repoRoot:J,error:X instanceof Error?X.message:String(X),duration:Date.now()-Z}),await this.performFullStatusScan(J)}}async performFullStatusScan(J){let Q=this.repos.get(J);if(!Q||Q.cancelled)return;let Z=Date.now(),{stdout:X}=await H99(B99,{cwd:J,maxBuffer:16777216}),Y=this.repos.get(J);if(!Y||Y.cancelled)return;let K=[],q=[],G=[],z=[],U=[];for(let W of this.parseStatus(X)){let F=AO(J,W.path);if(W.type==="created"){q.push(F);let H=await S41.stat(F).catch(()=>null);if(!H){U.push(F);continue}if(H.isFile()&&H.mtimeMs>Y.lastScanTime)z.push(F),K.push({type:"created",path:F,timestamp:H.mtimeMs,isDirectory:!1});else U.push(F)}if(W.type==="deleted")G.push(F),K.push({type:"deleted",path:F,timestamp:Z,isDirectory:!1})}if(a.debug("Git status discovery (status)",{repoRoot:J,createdDiscovered:q,deletedDiscovered:G,createdNew:z,createdNotNew:U,counts:{createdDiscovered:q.length,deletedDiscovered:G.length,createdNew:z.length,createdNotNew:U.length}}),K.length)for(let W of this.callbacks)W(K)}parseStatus(J){let Q=[],Z=J.split("\x00");for(let X of Z){if(!X)continue;let Y=X[0];if(Y==="?"){let K=X.slice(2);Q.push({type:"created",path:K});continue}if(Y==="1"){let K=X[2],q=X.substring(X.indexOf("\t")+1);if(K==="D")Q.push({type:"deleted",path:q});else if(K==="A")Q.push({type:"created",path:q})}}return Q}}function k41(J){if(J?.useGit)return new RT(J.pollInterval);if(J?.usePolling)return new c56(J.pollInterval);let Q=J?.rootPath||process.cwd();if(RT.isRepo(Q)){let Z=new RT(J?.pollInterval);if(Z.isSupported())return a.info("Git repository detected, using GitFileWatcher",{rootPath:Q}),Z}return a.info("Not a git repository, using NoOpFileWatcher",{rootPath:Q}),new d56}var H99,v41,B99="git --no-optional-locks status --porcelain=v2 --untracked-files=normal --no-renames -z";var Jx1=u(()=>{B0();H99=p56(W99),v41=p56(F99)});class l56{config;queryChars;queryLower;constructor(J,Q={}){this.config={...D99,...Q};let Z=J.replace(/^[@#]+/,"");if(this.queryChars=Array.from(Z),this.queryLower=Array.from(Z.toLowerCase()),this.config.smartCase)this.config.caseSensitive=Z!==Z.toLowerCase()}match(J){if(this.queryChars.length===0)return J.filter((Z)=>Z.shouldIncludeInResults()).map((Z)=>{let X=this.config.openFiles?.includes(Z.path)?300:0,Y=Z.getImportanceBoost()+X;return{entry:Z,score:Y,matchPositions:[],highlightedPath:Z.path}}).sort((Z,X)=>X.score-Z.score).slice(0,this.config.maxResults);let Q=this.matchWithSemanticScoring(J);if(Q.length>0)return Q;return this.matchWithFuzzyScoring(J)}matchWithSemanticScoring(J){let Q=[],Z=0,X=this.queryChars.join(""),Y=this.queryChars[0],q=this.queryChars.length===1&&Y!==void 0&&/[a-z]/i.test(Y)?1e4:20000,G=(W,F)=>{if(!W.shouldIncludeInResults())return!1;if(X.length>5&&!this.passesCharBagFilter(X,W))return!1;let H=this.matchEntrySemantic(W);if(H&&H.score>=this.config.minScore)Q.push(H);if(Z++,Z>=q)return!0;if(F&&Q.length>=this.config.maxResults*5)return!0;return!1},z=(W,F)=>{for(let H of J){if(!W(H))continue;if(G(H,F))return!0}return!1};if(!z((W)=>W.isDirectory(),!1))z((W)=>!W.isDirectory(),!0);return Q.sort((W,F)=>{let H=F.score-W.score;if(Math.abs(H)>0.001)return H;return W.entry.path.length-F.entry.path.length}),Q.slice(0,this.config.maxResults)}matchWithFuzzyScoring(J){let Q=[],Z=0,X=this.queryChars.join(""),Y=this.queryChars[0],q=this.queryChars.length===1&&Y!==void 0&&/[a-z]/i.test(Y)?1e4:20000,G=(W,F)=>{if(!W.shouldIncludeInResults())return!1;if(X.length>5&&!this.passesCharBagFilter(X,W))return!1;let H=this.matchEntryFuzzy(W);if(H)Q.push(H);if(Z++,Z>=q)return!0;if(F&&Q.length>=this.config.maxResults*5)return!0;return!1},z=(W,F)=>{for(let H of J){if(!W(H))continue;if(G(H,F))return!0}return!1};if(!z((W)=>W.isDirectory(),!1))z((W)=>!W.isDirectory(),!0);return Q.sort((W,F)=>{let H=F.score-W.score;if(Math.abs(H)>0.001)return H;return W.entry.path.length-F.entry.path.length}),Q.slice(0,this.config.maxResults)}matchEntrySemantic(J){let Q=J.path,Z=this.queryLower.join(""),X=this.calculateSemanticScore(Z,J);if(X===0)return null;let Y=this.applyTieBreakers(X,Z,J),K=this.findMatchPositions(Z,Q),q=this.createHighlightedPath(Q,K);return{entry:J,score:Y,matchPositions:K,highlightedPath:q}}matchEntryFuzzy(J){let Q=J.path,Z=this.queryLower.join(""),X=this.calculateFuzzyScore(Z,J);if(X===0)return null;let Y=this.applyTieBreakers(X,Z,J),K=this.findMatchPositions(Z,Q),q=this.createHighlightedPath(Q,K);return{entry:J,score:Y,matchPositions:K,highlightedPath:q}}calculateSemanticScore(J,Q){let Z=J.toLowerCase(),X=Q.path,Y=X.toLowerCase(),K=this.getFilename(X),q=this.removeExtension(K).toLowerCase(),G=Y.split(/[/.\s-_]/).filter((F)=>F.length>0);if(J.endsWith("/")&&Q.isDirectory()){let F=Z.slice(0,-1);if(Y===F||Y.endsWith("/"+F))return tQ.EXACT_FILENAME+100;if(Y.includes(F))return tQ.SUBSTRING_FILENAME+50}if(q===Z||K.toLowerCase()===Z)return tQ.EXACT_FILENAME;if(q.startsWith(Z))return tQ.PREFIX_FILENAME;if(q.endsWith(Z))return tQ.SUFFIX_FILENAME;if(q.includes(Z))return tQ.SUBSTRING_FILENAME;let z=this.simpleTokens(Z);if(z.length>1){let F=this.matchTokensToSegments(z,G);if(F)return F}if(z.length===1&&Z.length>6){let F=this.progressiveSegmentMatch(Z,G);if(F)return F}if(G.includes(Z))return tQ.SEGMENT_EXACT;if(G.some((F)=>F.includes(Z)))return tQ.SEGMENT_SUBSTRING;if(G.join("").includes(Z))return tQ.SEGMENT_SUBSTRING;if(Y.replace(/[\s-_]/g,"").includes(Z))return tQ.PATH_SUBSTRING;return 0}calculateFuzzyScore(J,Q){let Z=J.toLowerCase(),X=Q.path.toLowerCase();if(this.fuzzyIn(Z,X))return tQ.FUZZY;return 0}applyTieBreakers(J,Q,Z){let X=J,Y=Math.abs(Z.path.length-Q.length);X-=0.01*Y;let K=Z.path.split("/").length-1;X-=0.1*K;let q=this.getFilename(Z.path),G=this.removeExtension(q).toLowerCase();if(/^(license|readme|copy(ing|left))$/i.test(G)&&K===1)X-=200;if(Z.metadata.mtime){let U=(Date.now()-Z.metadata.mtime)/86400000;if(U<30){let W=Math.max(0,1-U/30);X+=50*W}}if(this.config.openFiles?.includes(Z.path))X+=300;return X}simpleTokens(J){return J.replace(/([a-z])([A-Z0-9])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}progressiveSegmentMatch(J,Q){let Z=0,X=0,Y=0;for(let q of Q){if(Z>=J.length)break;let G="",z="none";if(Z+q.length<=J.length){if(J.slice(Z,Z+q.length)===q)G=q,z="exact"}if(!G&&q.length>=3){if(J.slice(Z).startsWith(q))G=q,z="prefix"}if(!G&&q.length>=3){let U=J.slice(Z);if(U.includes(q)&&U.indexOf(q)===0)G=q,z="substring"}if(!G){let U=J.slice(Z);if(U.length>=3&&q.includes(U))G=U,z="substring"}if(G){if(Z+=G.length,X++,z==="exact")Y++}}if(Z/J.length>=0.8&&X>=2)return Y>=2?tQ.SEGMENT_ORDERED_EXACT:tQ.SEGMENT_ORDERED_PARTIAL;return 0}matchTokensToSegments(J,Q){let Z=this.findTokenMatches(J,Q),X=this.getWorstMatchType(Z);return this.scoreFromMatchType(X)}findTokenMatches(J,Q){let Z=0,X=[];for(let Y of J){let K=!1;for(let q=Z;q<Q.length;q++){let G=Q[q];if(!G)continue;if(Y===G){X.push("exact"),Z=q+1,K=!0;break}else if(G.startsWith(Y)||Y.startsWith(G)||G.endsWith(Y)||G.includes(Y)||Y.includes(G)){X.push("partial"),Z=q+1,K=!0;break}}if(!K)return[]}return X}getWorstMatchType(J){if(J.length===0)return"none";if(J.includes("partial"))return"partial";return"exact"}scoreFromMatchType(J){switch(J){case"exact":return tQ.SEGMENT_ORDERED_EXACT;case"partial":return tQ.SEGMENT_ORDERED_PARTIAL;default:return 0}}fuzzyIn(J,Q){let Z=0;for(let X=0;X<Q.length&&Z<J.length;X++)if(Q[X]===J[Z])Z++;return Z===J.length}getFilename(J){return J.split("/").pop()||J}removeExtension(J){let Q=J.lastIndexOf(".");return Q>0?J.substring(0,Q):J}findMatchPositions(J,Q){let Z=[],X=Q.toLowerCase(),Y=J.toLowerCase();if(X.includes(Y)){let q=X.indexOf(Y);for(let G=0;G<Y.length;G++)Z.push(q+G);return Z}let K=0;for(let q of Y){let G=X.indexOf(q,K);if(G!==-1)Z.push(G),K=G+1}return Z}passesCharBagFilter(J,Q){if(J.includes("/")){let Z=J.split("/");for(let X of Z){if(X.trim()==="")continue;let Y=oQ.fromString(X);if(!Q.charBag.hasChars(Y))return!1}return!0}else{let Z=oQ.fromString(J);return Q.charBag.hasChars(Z)}}createHighlightedPath(J,Q){if(Q.length===0)return J;let Z="",X=0;for(let Y of Q){if(Y>=J.length)continue;Z+=J.slice(X,Y),Z+=`**${J[Y]}**`,X=Y+1}return Z+=J.slice(X),Z}}function i56(J,Q,Z){return new l56(J,Z).match(Q)}var D99,tQ;var a56=u(()=>{D99={minScore:400,caseSensitive:!1,penalizeLengthDifference:!0,maxResults:50,smartCase:!0},tQ={EXACT_FILENAME:1000,SEGMENT_ORDERED_EXACT:950,PREFIX_FILENAME:900,SUFFIX_FILENAME:850,SEGMENT_ORDERED_PARTIAL:840,SUBSTRING_FILENAME:800,SEGMENT_EXACT:650,SEGMENT_SUBSTRING:600,PATH_SUBSTRING:500,FUZZY:250}});class ym{metadata;entries;entriesByPath;entriesById;constructor(J,Q=[],Z,X){if(this.metadata=J,this.entries=Q,Z&&X)this.entriesByPath=Z,this.entriesById=X;else{let Y=new Map,K=new Map;for(let q of Q)Y.set(q.path,q),K.set(q.id,q);this.entriesByPath=Y,this.entriesById=K}this.cachedArray=Array.from(this.entriesByPath.values()),this.entriesArrayDirty=!1}static create(J){let Q=Date.now();return new ym({id:Q,createdAt:Q,rootPath:J,entryCount:0,scanStatus:"scanning"},[])}static fromEntries(J,Q){let Z=Date.now(),X={id:Z,createdAt:Z,rootPath:J,entryCount:Q.length,scanStatus:"complete"};return new ym(X,Q)}entriesArrayDirty=!1;cachedArray=[];getAllEntries(){if(this.entriesArrayDirty)this.cachedArray=[...this.entriesByPath.values()],this.entriesArrayDirty=!1;return this.cachedArray}getEntryByPath(J){return this.entriesByPath.get(J)??null}getEntryById(J){return this.entriesById.get(J)??null}applyChanges(J){let{added:Q=[],removed:Z=[],modified:X=[]}=J;for(let Y of Z){let K=this.entriesByPath.get(Y);if(K){if(this.entriesByPath.delete(Y),this.entriesById.delete(K.id),!this.entriesArrayDirty){let q=this.cachedArray.findIndex((G)=>G.path===Y);if(q>=0)this.cachedArray.splice(q,1)}}}for(let Y of[...Q,...X])if(this.entriesByPath.set(Y.path,Y),this.entriesById.set(Y.id,Y),!this.entriesArrayDirty){let K=this.cachedArray.findIndex((q)=>q.path===Y.path);if(K>=0)this.cachedArray.splice(K,1);this.cachedArray.unshift(Y)}this.metadata.entryCount=this.entriesByPath.size}findEntries(J){return this.entries.filter(J)}getFiles(){return this.findEntries((J)=>J.kind==="file")}getDirectories(){return this.findEntries((J)=>J.kind==="directory")}getInDirectory(J){let Q=J.endsWith("/")?J:J+"/";return this.findEntries((Z)=>Z.path.startsWith(Q)&&Z.path!==J)}hasPath(J){return this.entriesByPath.has(J)}getStats(){let J=this.metadata.entryCount||this.entries.length,Q=this.getFiles().length,Z=J-Q,X=J*250;return{totalEntries:J,fileEntries:Q,directoryEntries:Z,memoryUsage:X}}}var n56=()=>{};import{EventEmitter as M99}from"node:events";import{promises as V99}from"node:fs";import{relative as N99}from"node:path";var Qx1;var r56=u(()=>{n6();B0();m56();rb1();Jx1();sb1();a56();n56();Qx1=class Qx1 extends M99{rootPath;currentSnapshot=null;fileWatcher;scanner;isScanning=!1;stats;constructor(J,Q){super();this.rootPath=J;this.fileWatcher=Q??k41(),this.scanner=new eb1,this.stats={totalFiles:0,totalDirectories:0,lastScanDuration:0,lastScanTime:0,memoryUsage:0,status:"idle"},this.fileWatcher.onFileSystemEvent(this.handleFileSystemEvents.bind(this))}async initialize(J){if(this.isScanning)throw Error("Index is already being initialized");try{await this.performFullScan(J),await this.fileWatcher.watch(this.rootPath)}catch(Q){throw this.updateStatus("error"),Q}}async rescan(J){await this.performFullScan(J)}getCurrentSnapshot(){return this.currentSnapshot}getStats(){return{...this.stats}}search(J,Q={}){if(this.fileWatcher.triggerScan)this.fileWatcher.triggerScan(this.rootPath).catch(()=>{});if(!this.currentSnapshot)return[];let{limit:Z=50,minScore:X=0.1,includeDirectories:Y=!0,includeIgnored:K=!1}=Q,q=this.currentSnapshot.getAllEntries(),G=J.replace(/[@/]/g,"");if(G.length>2){if(q.some((F)=>F.path.includes(G))){let F=q.find((H)=>H.path.includes(G));a.debug("Search for existing file",{query:J,matchingFile:F?.path,entryIndex:q.findIndex((H)=>H===F)})}}q=q.filter((W)=>{if(!K&&W.isIgnored)return!1;if(!Y&&W.isDirectory())return!1;return W.shouldIncludeInMentions()});let z=i56(J,q,{minScore:X,openFiles:Q.openFiles});return z.sort((W,F)=>F.score-W.score),z.slice(0,Z)}dispose(){this.fileWatcher.dispose(),this.removeAllListeners()}async performFullScan(J){this.isScanning=!0,this.updateStatus("scanning");let Q=Date.now();try{let Z=await this.scanner.scanDirectory(this.rootPath,{respectIgnorePatterns:!0,...J});this.currentSnapshot=ym.fromEntries(this.rootPath,Z.entries);let X=Date.now()-Q;this.stats={...this.stats,totalFiles:Z.stats.totalFiles,totalDirectories:Z.stats.totalDirectories,lastScanDuration:X,lastScanTime:Q,memoryUsage:this.currentSnapshot.getStats().memoryUsage,status:"idle"},this.emit("scan-complete",{entries:Z.entries.length,duration:X}),this.emit("status-changed",this.getStats())}catch(Z){throw this.updateStatus("error"),this.emit("scan-error",Z),Z}finally{this.isScanning=!1}}async handleFileSystemEvents(J){if(!this.currentSnapshot||this.isScanning)return;this.updateStatus("updating");try{let Q=[],Z=[],X=[];for(let Y of J){let K=Y.path;switch(Y.type){case"deleted":Q.push(K);break;case"created":await this.processCreatedEvent(Y,Z);break;case"modified":await this.processModifiedEvent(Y,X);break;case"renamed":if(Y.oldPath)Q.push(Y.oldPath);await this.processCreatedEvent(Y,Z);break}}if(this.currentSnapshot.applyChanges({removed:Q,added:Z,modified:X}),Q.length>0||Z.length>0||X.length>0)a.debug("Incremental snapshot update",{removed:Q.length,added:Z.length,modified:X.length,totalEntries:this.currentSnapshot.metadata.entryCount,sampleAdded:Z.slice(0,3).map((Y)=>Y.path),sampleRemoved:Q.slice(0,3)});this.stats={...this.stats,memoryUsage:this.currentSnapshot.getStats().memoryUsage,status:"idle"},this.emit("files-updated",{added:Z.length,removed:Q.length,modified:X.length}),this.emit("status-changed",this.getStats())}catch(Q){this.updateStatus("error"),this.emit("scan-error",Q)}}async processCreatedEvent(J,Q){let Z=J.path;try{let X=J.stat||(J.isDirectory?null:await V99.lstat(Z)),Y=J.isDirectory,K=N99(this.rootPath,Z);if(XX.shouldIgnore(K,Y))return;if(Y)Q.push(new VV({id:Z,kind:"directory",path:Z,uri:P0.file(Z),metadata:{size:0,mtime:Date.now(),isSymlink:!1},isIgnored:!1}));else if(X)Q.push(new VV({id:Z,kind:"file",path:Z,uri:P0.file(Z),metadata:{size:X.size,mtime:X.mtimeMs,isSymlink:X.isSymbolicLink()},isIgnored:!1}))}catch{}}async processModifiedEvent(J,Q){let Z=this.currentSnapshot?.getEntryByPath(J.path);if(Z){let X=Z.withUpdates({metadata:{...Z.metadata,mtime:J.timestamp}});Q.push(X)}}updateStatus(J){this.stats={...this.stats,status:J},this.emit("status-changed",this.getStats())}}});import{execFile as L99}from"node:child_process";import{EventEmitter as A99}from"node:events";import{promises as _41,watch as O99}from"node:fs";import{join as wT}from"node:path";import{promisify as j99}from"node:util";async function s56(J,Q){if(!await Zx1.isRepo(J))return null;return new Zx1(J,Q?.pollInterval)}var R99,Zx1;var o56=u(()=>{B0();R99=j99(L99);Zx1=class Zx1 extends A99{repoRoot;pollInterval;on(J,Q){return super.on(J,Q)}emit(J,...Q){return super.emit(J,...Q)}currentSha;disposed=!1;started=!1;running=!1;pendingForce=!1;watchers=new Set;currentRefWatcher;timer;constructor(J,Q=30000){super();this.repoRoot=J;this.pollInterval=Q;this.repoRoot=this.validateRepoRoot(J)}static async isRepo(J){try{let Q=wT(J,".git");return await _41.access(Q),!0}catch{try{let Q=wT(J,"HEAD");return await _41.access(Q),!0}catch{return!1}}}async start(){if(this.disposed)throw Error("GitHeadWatcher has been disposed");if(this.started)throw Error("GitHeadWatcher has already been started");this.started=!0,this.currentSha=await this.getCurrentSha(),this.watch(wT(this.repoRoot,".git/HEAD"),async()=>{await this.updateRefWatcher(),this.scheduleCheck()}),await this.updateRefWatcher();let J=wT(this.repoRoot,".git/logs/HEAD");try{await _41.access(J),this.watch(J,()=>this.scheduleCheck(!0))}catch{}this.timer=setInterval(()=>this.scheduleCheck(),this.pollInterval),a.debug("GitHeadWatcher started",{repoRoot:this.repoRoot})}stop(){for(let J of Array.from(this.watchers))this.cleanupWatcher(J);if(this.timer)clearInterval(this.timer),this.timer=void 0;this.currentRefWatcher=void 0,this.started=!1,this.running=!1,this.pendingForce=!1}dispose(){if(this.disposed)return;this.stop(),this.disposed=!0,this.removeAllListeners()}watch(J,Q){let Z=O99(J);return Z.on("change",Q),Z.on("rename",()=>{this.cleanupWatcher(Z),setTimeout(()=>{if(!this.disposed)this.watch(J,Q),this.scheduleCheck(!0)},50)}),Z.on("error",(X)=>{a.debug("Git file watcher error",{filePath:J,error:X}),this.cleanupWatcher(Z)}),this.watchers.add(Z),Z}cleanupWatcher(J){try{J.removeAllListeners(),J.close()}catch(Q){a.debug("Error during watcher cleanup",{error:Q})}this.watchers.delete(J)}async updateRefWatcher(){if(this.currentRefWatcher)this.cleanupWatcher(this.currentRefWatcher),this.currentRefWatcher=void 0;try{let J=await _41.readFile(wT(this.repoRoot,".git/HEAD"),"utf8");if(!J)return;let Q=J.trim();if(Q.startsWith("ref: ")){let Z=Q.slice(5),X=wT(this.repoRoot,".git",Z);this.currentRefWatcher=this.watch(X,()=>this.scheduleCheck())}}catch(J){a.debug("Failed to update ref watcher",{repoRoot:this.repoRoot,error:J})}}scheduleCheck(J=!1){if(this.disposed)return;if(this.pendingForce||=J,this.running)return;this.running=!0,queueMicrotask(async()=>{if(this.disposed)return;let Q=this.pendingForce;this.pendingForce=!1;try{await this.performCheck(Q)}finally{this.running=!1}})}async checkForChanges(J=!1){this.scheduleCheck(J)}async performCheck(J){if(this.disposed)return;try{let Q=await this.getCurrentSha();if(!Q&&this.currentSha){a.warn("Failed to get current SHA, keeping previous value",{repoRoot:this.repoRoot,previousSha:this.currentSha.slice(0,7)});return}if(Q&&Q!==this.currentSha&&this.currentSha||J){let Z=this.currentSha;this.currentSha=Q??this.currentSha,this.emit("head-change",{oldSha:Z,newSha:this.currentSha,repoRoot:this.repoRoot,force:J})}else if(Q!==this.currentSha)this.currentSha=Q}catch(Q){a.warn("Error checking for git HEAD changes",{repoRoot:this.repoRoot,error:Q})}}async getCurrentSha(){try{let{stdout:J}=await R99("git",["rev-parse","HEAD"],{cwd:this.repoRoot});return J.trim()}catch(J){return}}validateRepoRoot(J){if(!J||typeof J!=="string")throw Error("Repository root must be a valid string path");if(!J.startsWith("/")&&!J.match(/^[A-Za-z]:\\/))throw Error("Repository root must be an absolute path");return J}}});class b41{indexes=new Map;headWatchers=new Map;reindexingWorkspaces=new Set;config;disposed=!1;static forWorkspace(J){return new b41({workspaceRoots:[J],scanOnStartup:!0,maxIndexedFiles:500000,enableFileWatching:!0,usePollingFallback:!1,enableHeadWatching:!0,followSymlinkDirs:!0})}constructor(J){this.config={...J}}async initialize(){if(this.disposed)throw Error("Service has been disposed");if(this.config.scanOnStartup){let J=this.config.workspaceRoots.map((Q)=>this.indexWorkspace(Q));await Promise.allSettled(J)}}async indexWorkspace(J){if(this.disposed)throw Error("Service has been disposed");if(this.indexes.has(J)){await this.indexes.get(J).rescan();return}let Q=this.config.enableFileWatching?k41({rootPath:J,usePolling:this.config.usePollingFallback}):void 0,Z=new Qx1(J,Q);Z.on("scan-error",(Y)=>{a.error("Scan error in workspace",{rootPath:J,error:Y})});let X={respectIgnorePatterns:!0,maxFiles:this.config.maxIndexedFiles,followSymlinks:this.config.followSymlinkDirs};try{if(await Z.initialize(X),this.indexes.set(J,Z),this.config.enableHeadWatching)await this.setupHeadWatching(J,Z,Q)}catch(Y){Z.dispose();let K=this.headWatchers.get(J);if(K)K.dispose(),this.headWatchers.delete(J);throw Y}}async removeWorkspace(J){let Q=this.indexes.get(J);if(Q)Q.dispose(),this.indexes.delete(J);let Z=this.headWatchers.get(J);if(Z)Z.dispose(),this.headWatchers.delete(J)}searchAll(J,Q){let Z=[];for(let X of this.indexes.values())try{let Y=X.search(J,Q);Z.push(...Y)}catch(Y){}return Z.sort((X,Y)=>Y.score-X.score),Q?.limit?Z.slice(0,Q.limit):Z}searchWorkspace(J,Q,Z){let X=this.indexes.get(J);if(!X)return[];try{return X.search(Q,Z)}catch(Y){return a.error(`Search error in workspace ${J}:`,Y),[]}}getIndexStats(J){if(J){let Z=this.indexes.get(J);if(Z)return[{...Z.getStats(),rootPath:J}];return[]}let Q=[];for(let[Z,X]of this.indexes.entries())Q.push({...X.getStats(),rootPath:Z});return Q}getConfig(){return{...this.config}}updateConfig(J){this.config={...this.config,...J}}async rescanAll(){let J=[];for(let[Q,Z]of this.indexes.entries())J.push(Z.rescan().catch((X)=>{a.error(`Rescan error in workspace ${Q}:`,X)}));await Promise.allSettled(J)}getIndexedWorkspaces(){return Array.from(this.indexes.keys())}isWorkspaceIndexed(J){return this.indexes.has(J)}dispose(){if(this.disposed)return;for(let[,J]of this.indexes.entries())J.dispose();for(let[,J]of this.headWatchers.entries())J.dispose();this.indexes.clear(),this.headWatchers.clear(),this.disposed=!0}isDisposed(){return this.disposed}async setupHeadWatching(J,Q,Z){try{let X=await s56(J);if(!X)return;X.on("head-change",async({oldSha:Y,newSha:K})=>{if(this.reindexingWorkspaces.has(J)){a.debug("Re-index already in progress, skipping",{rootPath:J});return}this.reindexingWorkspaces.add(J);try{if(await Q.rescan(),Z&&Z instanceof RT)await Z.reset(J);a.debug("Re-index completed after HEAD change",{rootPath:J})}catch(q){a.error("Failed to re-index after change",{rootPath:J,error:q})}finally{this.reindexingWorkspaces.delete(J)}}),await X.start(),this.headWatchers.set(J,X),a.debug("Git HEAD watching enabled",{rootPath:J})}catch(X){a.warn("Failed to setup git HEAD watching",{rootPath:J,error:X})}}}function Xx1(J,Q){let Z={workspaceRoots:J,scanOnStartup:!0,maxIndexedFiles:500000,enableFileWatching:!0,usePollingFallback:!1,enableHeadWatching:!0,followSymlinkDirs:!0,...Q};return new b41(Z)}var t56=u(()=>{B0();Jx1();r56();o56()});var e56=u(()=>{t56()});import w99 from"node:os";import x41 from"node:path";class y41{rootPath;opts;startInBackground;fuzzyService=null;state="unstarted";initPromise=null;constructor(J=process.cwd(),Q={},Z=!1){this.rootPath=J;this.opts=Q;this.startInBackground=Z;if(Z)this.initPromise=this.init(),this.initPromise.then(()=>{a.debug("Fuzzy service background initialization completed")}).catch((X)=>{a.debug("Fuzzy service background initialization failed",X)})}async start(){if(this.initPromise)return this.initPromise;return this.initPromise=this.init(),this.initPromise}async init(){if(x41.resolve(this.rootPath)===x41.resolve(w99.homedir())){a.debug("Skipping fuzzy service initialization for home directory");return}this.state="initializing";try{this.fuzzyService=Xx1([this.rootPath],{scanOnStartup:!0,enableFileWatching:!0,usePollingFallback:!1,...this.opts}),await this.fuzzyService.initialize(),this.state="ready"}catch(J){throw this.state="failed",a.error("Failed to initialize fuzzy service",J),J}}async query(J,Q=50,Z){if(this.initPromise)try{await this.initPromise}catch(Y){return a.warn("Background fuzzy initialization failed, returning empty results",Y),[]}if(!this.fuzzyService)return a.warn("Fuzzy service not initialized, returning empty results"),[];let X=(Y)=>x41.relative(this.rootPath,Y);try{let Y=J.trim();return this.fuzzyService.searchAll(Y,{limit:Q,minScore:Y?0.1:void 0,openFiles:Z}).map((q)=>X(q.entry.path))}catch(Y){return a.error("Fuzzy search failed",Y),[]}}async queryCompletions(J,Q=50,Z){if(this.initPromise)try{await this.initPromise}catch(Y){return a.warn("Background fuzzy initialization failed, returning empty results",Y),[]}if(!this.fuzzyService)return a.warn("Fuzzy service not initialized, returning empty results"),[];let X=(Y)=>x41.relative(this.rootPath,Y);try{let Y=J.trim();return this.fuzzyService.searchAll(Y,{limit:Q,minScore:Y?0.1:void 0,openFiles:Z}).map((q)=>({path:X(q.entry.path),kind:q.entry.isDirectory()?"folder":"file"}))}catch(Y){return a.error("Fuzzy search failed",Y),[]}}getStats(){return{state:this.state,stats:this.fuzzyService?.getIndexStats()??[]}}dispose(){if(this.fuzzyService)this.fuzzyService.dispose(),this.fuzzyService=null;this.state="unstarted",this.initPromise=null}}var JJ6=u(()=>{B0();e56()});function hm(J,Q=!1){let Z=J.length,X=0,Y="",K=0,q=16,G=0,z=0,U=0,W=0,F=0;function H(O,j){let R=0,I=0;while(R<O||!j){let w=J.charCodeAt(X);if(w>=48&&w<=57)I=I*16+w-48;else if(w>=65&&w<=70)I=I*16+w-65+10;else if(w>=97&&w<=102)I=I*16+w-97+10;else break;X++,R++}if(R<O)I=-1;return I}function B(O){X=O,Y="",K=0,q=16,F=0}function M(){let O=X;if(J.charCodeAt(X)===48)X++;else{X++;while(X<J.length&&IT(J.charCodeAt(X)))X++}if(X<J.length&&J.charCodeAt(X)===46)if(X++,X<J.length&&IT(J.charCodeAt(X))){X++;while(X<J.length&&IT(J.charCodeAt(X)))X++}else return F=3,J.substring(O,X);let j=X;if(X<J.length&&(J.charCodeAt(X)===69||J.charCodeAt(X)===101)){if(X++,X<J.length&&J.charCodeAt(X)===43||J.charCodeAt(X)===45)X++;if(X<J.length&&IT(J.charCodeAt(X))){X++;while(X<J.length&&IT(J.charCodeAt(X)))X++;j=X}else F=3}return J.substring(O,j)}function V(){let O="",j=X;while(!0){if(X>=Z){O+=J.substring(j,X),F=2;break}let R=J.charCodeAt(X);if(R===34){O+=J.substring(j,X),X++;break}if(R===92){if(O+=J.substring(j,X),X++,X>=Z){F=2;break}switch(J.charCodeAt(X++)){case 34:O+='"';break;case 92:O+="\\";break;case 47:O+="/";break;case 98:O+="\b";break;case 102:O+="\f";break;case 110:O+=`
|
5443
5443
|
`;break;case 114:O+="\r";break;case 116:O+="\t";break;case 117:let w=H(4,!0);if(w>=0)O+=String.fromCharCode(w);else F=4;break;default:F=5}j=X;continue}if(R>=0&&R<=31)if(fm(R)){O+=J.substring(j,X),F=2;break}else F=6;X++}return O}function N(){if(Y="",F=0,K=X,z=G,W=U,X>=Z)return K=Z,q=17;let O=J.charCodeAt(X);if(Yx1(O)){do X++,Y+=String.fromCharCode(O),O=J.charCodeAt(X);while(Yx1(O));return q=15}if(fm(O)){if(X++,Y+=String.fromCharCode(O),O===13&&J.charCodeAt(X)===10)X++,Y+=`
|
5444
5444
|
`;return G++,U=X,q=14}switch(O){case 123:return X++,q=1;case 125:return X++,q=2;case 91:return X++,q=3;case 93:return X++,q=4;case 58:return X++,q=6;case 44:return X++,q=5;case 34:return X++,Y=V(),q=10;case 47:let j=X-1;if(J.charCodeAt(X+1)===47){X+=2;while(X<Z){if(fm(J.charCodeAt(X)))break;X++}return Y=J.substring(j,X),q=12}if(J.charCodeAt(X+1)===42){X+=2;let R=Z-1,I=!1;while(X<R){let w=J.charCodeAt(X);if(w===42&&J.charCodeAt(X+1)===47){X+=2,I=!0;break}if(X++,fm(w)){if(w===13&&J.charCodeAt(X)===10)X++;G++,U=X}}if(!I)X++,F=1;return Y=J.substring(j,X),q=13}return Y+=String.fromCharCode(O),X++,q=16;case 45:if(Y+=String.fromCharCode(O),X++,X===Z||!IT(J.charCodeAt(X)))return q=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return Y+=M(),q=11;default:while(X<Z&&L(O))X++,O=J.charCodeAt(X);if(K!==X){switch(Y=J.substring(K,X),Y){case"true":return q=8;case"false":return q=9;case"null":return q=7}return q=16}return Y+=String.fromCharCode(O),X++,q=16}}function L(O){if(Yx1(O)||fm(O))return!1;switch(O){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function A(){let O;do O=N();while(O>=12&&O<=15);return O}return{setPosition:B,getPosition:()=>X,scan:Q?A:N,getToken:()=>q,getTokenValue:()=>Y,getTokenOffset:()=>K,getTokenLength:()=>X-K,getTokenStartLine:()=>z,getTokenStartCharacter:()=>K-W,getTokenError:()=>F}}function Yx1(J){return J===32||J===9}function fm(J){return J===10||J===13}function IT(J){return J>=48&&J<=57}var QJ6;var f41=u(()=>{(function(J){J[J.lineFeed=10]="lineFeed",J[J.carriageReturn=13]="carriageReturn",J[J.space=32]="space",J[J._0=48]="_0",J[J._1=49]="_1",J[J._2=50]="_2",J[J._3=51]="_3",J[J._4=52]="_4",J[J._5=53]="_5",J[J._6=54]="_6",J[J._7=55]="_7",J[J._8=56]="_8",J[J._9=57]="_9",J[J.a=97]="a",J[J.b=98]="b",J[J.c=99]="c",J[J.d=100]="d",J[J.e=101]="e",J[J.f=102]="f",J[J.g=103]="g",J[J.h=104]="h",J[J.i=105]="i",J[J.j=106]="j",J[J.k=107]="k",J[J.l=108]="l",J[J.m=109]="m",J[J.n=110]="n",J[J.o=111]="o",J[J.p=112]="p",J[J.q=113]="q",J[J.r=114]="r",J[J.s=115]="s",J[J.t=116]="t",J[J.u=117]="u",J[J.v=118]="v",J[J.w=119]="w",J[J.x=120]="x",J[J.y=121]="y",J[J.z=122]="z",J[J.A=65]="A",J[J.B=66]="B",J[J.C=67]="C",J[J.D=68]="D",J[J.E=69]="E",J[J.F=70]="F",J[J.G=71]="G",J[J.H=72]="H",J[J.I=73]="I",J[J.J=74]="J",J[J.K=75]="K",J[J.L=76]="L",J[J.M=77]="M",J[J.N=78]="N",J[J.O=79]="O",J[J.P=80]="P",J[J.Q=81]="Q",J[J.R=82]="R",J[J.S=83]="S",J[J.T=84]="T",J[J.U=85]="U",J[J.V=86]="V",J[J.W=87]="W",J[J.X=88]="X",J[J.Y=89]="Y",J[J.Z=90]="Z",J[J.asterisk=42]="asterisk",J[J.backslash=92]="backslash",J[J.closeBrace=125]="closeBrace",J[J.closeBracket=93]="closeBracket",J[J.colon=58]="colon",J[J.comma=44]="comma",J[J.dot=46]="dot",J[J.doubleQuote=34]="doubleQuote",J[J.minus=45]="minus",J[J.openBrace=123]="openBrace",J[J.openBracket=91]="openBracket",J[J.plus=43]="plus",J[J.slash=47]="slash",J[J.formFeed=12]="formFeed",J[J.tab=9]="tab"})(QJ6||(QJ6={}))});var qY,Kx1,ZJ6;var XJ6=u(()=>{qY=Array(20).fill(0).map((J,Q)=>{return" ".repeat(Q)}),Kx1={" ":{"\n":Array(200).fill(0).map((J,Q)=>{return`
|
5445
5445
|
`+" ".repeat(Q)}),"\r":Array(200).fill(0).map((J,Q)=>{return"\r"+" ".repeat(Q)}),"\r\n":Array(200).fill(0).map((J,Q)=>{return`\r
|
@@ -5798,7 +5798,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||sj}function KZ6(J,Q){let
|
|
5798
5798
|
`);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let q=K.optsWithGlobals(),G=await Q(K,q),z=0;await G.mcpService.initialized;let U=K.args.slice(1),W;if(ZZ6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await JZ6({toolName:X,rawArgs:U,stdinInput:W,only:Y.only,threadDeps:G,stdout:process.stdout,stderr:process.stderr,exit:(F)=>{z=F}}),await G.asyncDispose(),G.cleanupTerminal(),process.exit(z)})}var qZ6=u(()=>{SS();zV();gQ6();dQ6();lQ6();XZ6()});function GZ6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}import n49 from"node:fs";import zZ6 from"node:path";function UZ6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!zZ6.isAbsolute(Q))return null;return a.debug("Extracted image path",{original:J,extracted:Q}),Q}function WZ6(J){try{let Q=zZ6.extname(J).toLowerCase(),Z=At1(Q);if(!Z)return a.warn("Unsupported image file extension",{ext:Q}),null;try{let X=n49.readFileSync(J);return r49(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 r49(J,Q){if(J.length>OR)return a.warn(`Image file too large: ${J.length} bytes (max: ${OR})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}var FZ6=u(()=>{B0();$N()});function HZ6(J){return J.kind==="executable"}function BZ6(J){return J.kind==="markdown"}import{spawn as s49}from"node:child_process";import{promises as o49}from"node:fs";async function _x1(J,Q,Z,X={}){let{timeoutMs:Y=DZ6,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}),BZ6(q))return await t49(q,Q);else if(HZ6(q))return await e49(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 t49(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await o49.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>OH?Z.slice(0,OH)+`
|
5799
5799
|
... (output truncated at ${OH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function e49(J,Q,Z=DZ6,X){return new Promise((Y)=>{let[K,q]=J79(J,Q);a.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=Mt1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),a.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=s49(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=OH)F.push(V);else{let N=OH-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=OH)H.push(V);else{let N=OH-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
|
5800
5800
|
${L}`:L;if(B>OH)A+=`
|
5801
|
-
... (output truncated at ${OH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function J79(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return Z79(Z,X?[...X]:null,Y,Q);else return Q79(Z,X?[...X]:null,Y,Q)}function Q79(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function Z79(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 OH=50000,DZ6=300000;var MZ6=u(()=>{LR();B0()});var VZ6=u(()=>{MZ6();BQ1()});var J71,kF2,_F2,bF2,xF2,yF2,fF2,hF2,gF2,mF2,rm,uF2,pF2,dF2,cF2,lF2;var NZ6=u(()=>{J71=globalThis.window?.document!==void 0,kF2=globalThis.process?.versions?.node!==void 0,_F2=globalThis.process?.versions?.bun!==void 0,bF2=globalThis.Deno?.version?.deno!==void 0,xF2=globalThis.process?.versions?.electron!==void 0,yF2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,fF2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,hF2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,gF2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,mF2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,rm=globalThis.navigator?.userAgentData?.platform,uF2=rm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",pF2=rm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",dF2=rm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",cF2=rm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),lF2=rm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var Q71={};O6(Q71,{scrollUp:()=>R79,scrollDown:()=>w79,link:()=>C79,image:()=>S79,iTerm:()=>v79,exitAlternativeScreen:()=>P79,eraseUp:()=>j79,eraseStartLine:()=>A79,eraseScreen:()=>bx1,eraseLines:()=>N79,eraseLine:()=>jZ6,eraseEndLine:()=>L79,eraseDown:()=>O79,enterAlternativeScreen:()=>$79,cursorUp:()=>AZ6,cursorTo:()=>K79,cursorShow:()=>V79,cursorSavePosition:()=>W79,cursorRestorePosition:()=>F79,cursorPrevLine:()=>D79,cursorNextLine:()=>B79,cursorMove:()=>q79,cursorLeft:()=>OZ6,cursorHide:()=>M79,cursorGetPosition:()=>H79,cursorForward:()=>z79,cursorDown:()=>G79,cursorBackward:()=>U79,clearTerminal:()=>E79,clearScreen:()=>I79,beep:()=>T79});import xx1 from"node:process";var U2="\x1B[",om="\x1B]",bT="\x07",sm=";",LZ6,X79,Y79,K79=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return U2+(J+1)+"G";return U2+(Q+1)+sm+(J+1)+"H"},q79=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=U2+-J+"D";else if(J>0)Z+=U2+J+"C";if(Q<0)Z+=U2+-Q+"A";else if(Q>0)Z+=U2+Q+"B";return Z},AZ6=(J=1)=>U2+J+"A",G79=(J=1)=>U2+J+"B",z79=(J=1)=>U2+J+"C",U79=(J=1)=>U2+J+"D",OZ6,W79,F79,H79,B79,D79,M79,V79,N79=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=jZ6+(Z<J-1?AZ6():"");if(J)Q+=OZ6;return Q},L79,A79,jZ6,O79,j79,bx1,R79,w79,I79="\x1Bc",E79,$79,P79,T79,C79=(J,Q)=>[om,"8",sm,sm,Q,bT,J,om,"8",sm,sm,bT].join(""),S79=(J,Q={})=>{let Z=`${om}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")+bT},v79;var yx1=u(()=>{NZ6();LZ6=!J71&&xx1.env.TERM_PROGRAM==="Apple_Terminal",X79=!J71&&xx1.platform==="win32",Y79=J71?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:xx1.cwd,OZ6=U2+"G",W79=LZ6?"\x1B7":U2+"s",F79=LZ6?"\x1B8":U2+"u",H79=U2+"6n",B79=U2+"E",D79=U2+"F",M79=U2+"?25l",V79=U2+"?25h",L79=U2+"K",A79=U2+"1K",jZ6=U2+"2K",O79=U2+"J",j79=U2+"1J",bx1=U2+"2J",R79=U2+"S",w79=U2+"T",E79=X79?`${bx1}${U2}0f`:`${bx1}${U2}3J${U2}H`,$79=U2+"?1049h",P79=U2+"?1049l",T79=bT,v79={setCwd:(J=Y79())=>`${om}50;CurrentDir=${J}${bT}`,annotation(J,Q={}){let Z=`${om}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+bT}}});var RZ6=u(()=>{yx1();yx1()});var fx1=e((oF2,wZ6)=>{wZ6.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 $Z6=e((tF2,EZ6)=>{var k79=o1("os"),IZ6=o1("tty"),xK=fx1(),{env:n5}=process,LV;if(xK("no-color")||xK("no-colors")||xK("color=false")||xK("color=never"))LV=0;else if(xK("color")||xK("colors")||xK("color=true")||xK("color=always"))LV=1;if("FORCE_COLOR"in n5)if(n5.FORCE_COLOR==="true")LV=1;else if(n5.FORCE_COLOR==="false")LV=0;else LV=n5.FORCE_COLOR.length===0?1:Math.min(parseInt(n5.FORCE_COLOR,10),3);function hx1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function gx1(J,Q){if(LV===0)return 0;if(xK("color=16m")||xK("color=full")||xK("color=truecolor"))return 3;if(xK("color=256"))return 2;if(J&&!Q&&LV===void 0)return 0;let Z=LV||0;if(n5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=k79.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in n5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in n5))||n5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in n5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n5.TEAMCITY_VERSION)?1:0;if(n5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in n5){let X=parseInt((n5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(n5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n5.TERM))return 1;if("COLORTERM"in n5)return 1;return Z}function _79(J){let Q=gx1(J,J&&J.isTTY);return hx1(Q)}EZ6.exports={supportsColor:_79,stdout:hx1(gx1(!0,IZ6.isatty(1))),stderr:hx1(gx1(!0,IZ6.isatty(2)))}});var CZ6=e((eF2,TZ6)=>{var b79=$Z6(),xT=fx1();function PZ6(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 mx1(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(xT("no-hyperlink")||xT("no-hyperlinks")||xT("hyperlink=false")||xT("hyperlink=never"))return!1;if(xT("hyperlink=true")||xT("hyperlink=always"))return!0;if(X)return!0;if(!b79.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=PZ6(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=PZ6(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}TZ6.exports={supportsHyperlink:mx1,stdout:mx1(process.stdout),stderr:mx1(process.stderr)}});function AV(J,Q,{target:Z="stdout",...X}={}){if(!Z71.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return Q71.link(J,Q)}var Z71;var SZ6=u(()=>{RZ6();Z71=p6(CZ6(),1);AV.isSupported=Z71.default.stdout;AV.stderr=(J,Q,Z={})=>AV(J,Q,{target:"stderr",...Z});AV.stderr.isSupported=Z71.default.stderr});class ux1{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.1759464081-gf6c1d2"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await H00(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 vZ6=u(()=>{B0();Xz()});class GY{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function kZ6(J){if(J instanceof X71)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof GY)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 X71;var px1=u(()=>{B0();X71=class X71 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}});import{execSync as _Z6}from"node:child_process";import{rmdir as x79}from"node:fs/promises";import{tmpdir as y79}from"node:os";import bZ6 from"node:path";import{mkdtemp as f79,readFile as h79,unlink as g79,writeFile as $H2}from"fs/promises";class dx1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=MC()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new ux1(async()=>{try{return(await U9()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),_9.pipe(v0((Q)=>Q.settings["internal.modes"]),P8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...m79},J)Object.assign(this.commands,u79)}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 _x1(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 m79,u79;var xZ6=u(()=>{VZ6();B0();aw();p2();VC();iw();G7();QN();Tx1();Xz();XD();n6();b0();SZ6();n41();Cx1();vZ6();px1();m79={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${GJ} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:bK0}]}});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 X71;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 f79(bZ6.join(y79(),"amp-edit-")),Y=bZ6.join(X,"message.amp.md");_Z6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await h79(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 g79(Y),await x79(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 aH("dangerouslyAllowAll",!1),new GY("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 aH("dangerouslyAllowAll",!0),new GY("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 kT();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:kT};await t41(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 GY(`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(`
|
5801
|
+
... (output truncated at ${OH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function J79(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return Z79(Z,X?[...X]:null,Y,Q);else return Q79(Z,X?[...X]:null,Y,Q)}function Q79(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function Z79(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 OH=50000,DZ6=300000;var MZ6=u(()=>{LR();B0()});var VZ6=u(()=>{MZ6();BQ1()});var J71,kF2,_F2,bF2,xF2,yF2,fF2,hF2,gF2,mF2,rm,uF2,pF2,dF2,cF2,lF2;var NZ6=u(()=>{J71=globalThis.window?.document!==void 0,kF2=globalThis.process?.versions?.node!==void 0,_F2=globalThis.process?.versions?.bun!==void 0,bF2=globalThis.Deno?.version?.deno!==void 0,xF2=globalThis.process?.versions?.electron!==void 0,yF2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,fF2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,hF2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,gF2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,mF2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,rm=globalThis.navigator?.userAgentData?.platform,uF2=rm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",pF2=rm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",dF2=rm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",cF2=rm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),lF2=rm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var Q71={};O6(Q71,{scrollUp:()=>R79,scrollDown:()=>w79,link:()=>C79,image:()=>S79,iTerm:()=>v79,exitAlternativeScreen:()=>P79,eraseUp:()=>j79,eraseStartLine:()=>A79,eraseScreen:()=>bx1,eraseLines:()=>N79,eraseLine:()=>jZ6,eraseEndLine:()=>L79,eraseDown:()=>O79,enterAlternativeScreen:()=>$79,cursorUp:()=>AZ6,cursorTo:()=>K79,cursorShow:()=>V79,cursorSavePosition:()=>W79,cursorRestorePosition:()=>F79,cursorPrevLine:()=>D79,cursorNextLine:()=>B79,cursorMove:()=>q79,cursorLeft:()=>OZ6,cursorHide:()=>M79,cursorGetPosition:()=>H79,cursorForward:()=>z79,cursorDown:()=>G79,cursorBackward:()=>U79,clearTerminal:()=>E79,clearScreen:()=>I79,beep:()=>T79});import xx1 from"node:process";var U2="\x1B[",om="\x1B]",bT="\x07",sm=";",LZ6,X79,Y79,K79=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return U2+(J+1)+"G";return U2+(Q+1)+sm+(J+1)+"H"},q79=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=U2+-J+"D";else if(J>0)Z+=U2+J+"C";if(Q<0)Z+=U2+-Q+"A";else if(Q>0)Z+=U2+Q+"B";return Z},AZ6=(J=1)=>U2+J+"A",G79=(J=1)=>U2+J+"B",z79=(J=1)=>U2+J+"C",U79=(J=1)=>U2+J+"D",OZ6,W79,F79,H79,B79,D79,M79,V79,N79=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=jZ6+(Z<J-1?AZ6():"");if(J)Q+=OZ6;return Q},L79,A79,jZ6,O79,j79,bx1,R79,w79,I79="\x1Bc",E79,$79,P79,T79,C79=(J,Q)=>[om,"8",sm,sm,Q,bT,J,om,"8",sm,sm,bT].join(""),S79=(J,Q={})=>{let Z=`${om}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")+bT},v79;var yx1=u(()=>{NZ6();LZ6=!J71&&xx1.env.TERM_PROGRAM==="Apple_Terminal",X79=!J71&&xx1.platform==="win32",Y79=J71?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:xx1.cwd,OZ6=U2+"G",W79=LZ6?"\x1B7":U2+"s",F79=LZ6?"\x1B8":U2+"u",H79=U2+"6n",B79=U2+"E",D79=U2+"F",M79=U2+"?25l",V79=U2+"?25h",L79=U2+"K",A79=U2+"1K",jZ6=U2+"2K",O79=U2+"J",j79=U2+"1J",bx1=U2+"2J",R79=U2+"S",w79=U2+"T",E79=X79?`${bx1}${U2}0f`:`${bx1}${U2}3J${U2}H`,$79=U2+"?1049h",P79=U2+"?1049l",T79=bT,v79={setCwd:(J=Y79())=>`${om}50;CurrentDir=${J}${bT}`,annotation(J,Q={}){let Z=`${om}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+bT}}});var RZ6=u(()=>{yx1();yx1()});var fx1=e((oF2,wZ6)=>{wZ6.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 $Z6=e((tF2,EZ6)=>{var k79=o1("os"),IZ6=o1("tty"),xK=fx1(),{env:n5}=process,LV;if(xK("no-color")||xK("no-colors")||xK("color=false")||xK("color=never"))LV=0;else if(xK("color")||xK("colors")||xK("color=true")||xK("color=always"))LV=1;if("FORCE_COLOR"in n5)if(n5.FORCE_COLOR==="true")LV=1;else if(n5.FORCE_COLOR==="false")LV=0;else LV=n5.FORCE_COLOR.length===0?1:Math.min(parseInt(n5.FORCE_COLOR,10),3);function hx1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function gx1(J,Q){if(LV===0)return 0;if(xK("color=16m")||xK("color=full")||xK("color=truecolor"))return 3;if(xK("color=256"))return 2;if(J&&!Q&&LV===void 0)return 0;let Z=LV||0;if(n5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=k79.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in n5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in n5))||n5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in n5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n5.TEAMCITY_VERSION)?1:0;if(n5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in n5){let X=parseInt((n5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(n5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n5.TERM))return 1;if("COLORTERM"in n5)return 1;return Z}function _79(J){let Q=gx1(J,J&&J.isTTY);return hx1(Q)}EZ6.exports={supportsColor:_79,stdout:hx1(gx1(!0,IZ6.isatty(1))),stderr:hx1(gx1(!0,IZ6.isatty(2)))}});var CZ6=e((eF2,TZ6)=>{var b79=$Z6(),xT=fx1();function PZ6(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 mx1(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(xT("no-hyperlink")||xT("no-hyperlinks")||xT("hyperlink=false")||xT("hyperlink=never"))return!1;if(xT("hyperlink=true")||xT("hyperlink=always"))return!0;if(X)return!0;if(!b79.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=PZ6(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=PZ6(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}TZ6.exports={supportsHyperlink:mx1,stdout:mx1(process.stdout),stderr:mx1(process.stderr)}});function AV(J,Q,{target:Z="stdout",...X}={}){if(!Z71.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return Q71.link(J,Q)}var Z71;var SZ6=u(()=>{RZ6();Z71=p6(CZ6(),1);AV.isSupported=Z71.default.stdout;AV.stderr=(J,Q,Z={})=>AV(J,Q,{target:"stderr",...Z});AV.stderr.isSupported=Z71.default.stderr});class ux1{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.1759469839-g3e7045"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await H00(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 vZ6=u(()=>{B0();Xz()});class GY{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function kZ6(J){if(J instanceof X71)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof GY)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 X71;var px1=u(()=>{B0();X71=class X71 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}});import{execSync as _Z6}from"node:child_process";import{rmdir as x79}from"node:fs/promises";import{tmpdir as y79}from"node:os";import bZ6 from"node:path";import{mkdtemp as f79,readFile as h79,unlink as g79,writeFile as $H2}from"fs/promises";class dx1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=MC()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new ux1(async()=>{try{return(await U9()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),_9.pipe(v0((Q)=>Q.settings["internal.modes"]),P8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...m79},J)Object.assign(this.commands,u79)}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 _x1(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 m79,u79;var xZ6=u(()=>{VZ6();B0();aw();p2();VC();iw();G7();QN();Tx1();Xz();XD();n6();b0();SZ6();n41();Cx1();vZ6();px1();m79={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${GJ} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:bK0}]}});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 X71;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 f79(bZ6.join(y79(),"amp-edit-")),Y=bZ6.join(X,"message.amp.md");_Z6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await h79(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 g79(Y),await x79(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 aH("dangerouslyAllowAll",!1),new GY("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 aH("dangerouslyAllowAll",!0),new GY("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 kT();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:kT};await t41(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 GY(`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(`
|
5802
5802
|
`).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=ev(new URL(Y),Z.id).toString(),G=`Thread URL: ${AV(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 GY(`${G}
|
5803
5803
|
|
5804
5804
|
This thread's visibility has been updated to: ${z}`)}catch(W){let F=W instanceof Error?W.message:String(W);if(F.includes("no-workspace"))return Error("You are not a member of any workspace.");if(F.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(F.includes("no-groups"))return Error("You are not a member of any groups.");return a.error("Unexpected failure to update thread visibility",W),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=ev(new URL(X),Z.id).toString();try{return await vT(Y),new GY("Thread opened in browser")}catch(K){a.error("Failed to open browser",{error:K});let q=AV(Y,Y,{fallback:()=>Y});return new GY(`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 kT();if(Q===null)return Error("No editor found, please set $EDITOR to edit settings");try{_Z6(`${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 GY("No guidance files are currently in use for this thread.");let Z=Q.length,X=`Agent ${DX(Z,"File")} (${Z}):`,Y=Q.map((K)=>` • ${VY(HX(K.uri))} (${K.type})`).join(`
|
@@ -5963,11 +5963,11 @@ Press ? to view full diff`;else return`Invoke tool ${J.name} with input ${JSON.s
|
|
5963
5963
|
`,G)}),...this.buildPrettyHelpSection(MY9,U,W,F),new a0({height:1})]})})}),O=new O5({child:new W0({text:new C1("",H,[new C1("Press ",H),new C1("Escape",z),new C1(" to close • Use ",H),new C1("↑↓",z),new C1(" or ",H),new C1("j/k",z),new C1(" to scroll",H)])})}),j=new P6({crossAxisAlignment:"stretch",children:[new g2({child:A}),O]});return new O5({child:new i6({constraints:new f6(L,L,0,N),decoration:new h2(Z.background,H4.all(new g4(Z.primary,1,"rounded"))),child:j})})}buildPrettyHelpSection(J,Q,Z,X){let Y=[],K=30;for(let q of J){let G=[],z=[];for(let F of q.methods){let H=this.buildCleanKeyCombination(F);z.push(H)}let W=z.join(", ").padEnd(30," ");G.push(new C1(" ",Z)),G.push(new C1(W,Q)),G.push(new C1(" ",Z)),G.push(new C1(q.description,Z)),G.push(new C1(`
|
5964
5964
|
`,Z)),Y.push(new W0({text:new C1("",Z,G)}))}return Y}buildCleanKeyCombination(J){let{keys:Q,input:Z}=J,X=[];if(X.push(...Q),Z)X.push(Z);return X.join("+")}}});var cu,LW6;var Og1=u(()=>{L9();_U();KX();wJ();FY();u7();D2();qX();Mg1();bU();Z2();cu=class cu extends N6{options;onSelect;onChange;title;body;borderColor;selectedIndex;autofocus;showDismissalMessage;enableMouseInteraction;maxVisibleItems;scrollBuffer;constructor({key:J,options:Q,onSelect:Z,onChange:X,title:Y,body:K,borderColor:q=m1.index(8),selectedIndex:G=0,autofocus:z=!0,showDismissalMessage:U=!0,enableMouseInteraction:W=!0,maxVisibleItems:F=20,scrollBuffer:H=3}){super({key:J});this.options=Q,this.onSelect=Z,this.onChange=X,this.title=Y,this.body=K,this.borderColor=q,this.selectedIndex=Math.max(0,Math.min(G,Q.length-1)),this.autofocus=z,this.showDismissalMessage=U,this.enableMouseInteraction=W,this.maxVisibleItems=F,this.scrollBuffer=H}createState(){return new LW6}};LW6=class LW6 extends V6{selectedIndex=0;focusNode=new R2({});scrollOffset=0;initState(){super.initState(),this.selectedIndex=this.widget.selectedIndex,this.focusNode.addKeyHandler(this.handleKeyEvent.bind(this)),this.updateScrollPosition()}dispose(){this.focusNode.dispose(),super.dispose()}handleKeyEvent(J){let Q=(Z,X)=>{return J.key===Z&&J.shiftKey===(X?.shift??!1)&&J.ctrlKey===(X?.ctrl??!1)&&J.altKey===(X?.alt??!1)&&J.metaKey===(X?.meta??!1)};if(Q("ArrowDown")||Q("n",{ctrl:!0})||Q("Tab")||Q("j"))return this.moveSelection(1),"handled";if(Q("ArrowUp")||Q("p",{ctrl:!0})||Q("Tab",{shift:!0})||Q("k"))return this.moveSelection(-1),"handled";if(Q("Enter")){let Z=this.widget.options[this.selectedIndex];if(Z&&(Z.enabled??!0))this.widget.onSelect(Z.value);return"handled"}if(Q("Escape"))return this.widget.onSelect(null),"handled";return"ignored"}handleMouseScroll(J){if(J.direction==="down")this.moveSelection(1);else this.moveSelection(-1)}moveSelection(J){if(this.widget.options.length===0)return;let Q=this.selectedIndex+J;Q=Math.max(0,Math.min(Q,this.widget.options.length-1));let Z=Q,X=0;while(X<this.widget.options.length){let Y=this.widget.options[Q];if(Y&&(Y.enabled??!0))break;if(Q=Q+Math.sign(J),Q<0||Q>=this.widget.options.length){Q=Z;break}X++}if(this.selectedIndex!==Q)this.setState(()=>{if(this.selectedIndex=Q,this.updateScrollPosition(),this.widget.onChange){let Y=this.widget.options[Q];if(Y)this.widget.onChange(Q,Y)}})}updateScrollPosition(){let J=this.widget.maxVisibleItems,Q=this.widget.scrollBuffer,Z=this.selectedIndex,X=Z-this.scrollOffset,Y=this.scrollOffset;if(X>=J-Q)Y=Math.max(0,Z-(J-Q-1));if(X<Q)Y=Math.max(0,Z-Q);let K=Math.max(0,this.widget.options.length-J);if(Y=Math.min(Y,K),Y!==this.scrollOffset)this.scrollOffset=Y}build(J){if(this.widget.options.length===0)return new a0({width:0,height:0});let Q=[];if(this.widget.title)Q.push(new W0({text:new C1(this.widget.title,new g1({bold:!0}))})),Q.push(new a0({height:1}));if(this.widget.body){if(typeof this.widget.body==="string")Q.push(new W0({text:new C1(this.widget.body)}));else Q.push(this.widget.body);Q.push(new a0({height:1}))}let Z=this.scrollOffset,X=Math.min(this.widget.options.length,Z+this.widget.maxVisibleItems);for(let q=Z;q<X;q++){let G=this.widget.options[q],z=q===this.selectedIndex,U=G.enabled??!0,W=new f51({title:G.label,subtitle:G.description,selected:z,enabled:U,onTap:U&&this.widget.enableMouseInteraction?()=>this.widget.onSelect(G.value):void 0});Q.push(W)}if(this.widget.showDismissalMessage)Q.push(new a0({height:1})),Q.push(new W0({text:new C1("Escape to close",new g1({color:m1.index(8)}))}));let Y=new P6({crossAxisAlignment:"stretch",mainAxisSize:"min",children:Q}),K=new i6({child:new E8({padding:new F6(1,0,1,0),child:Y}),decoration:new h2(void 0,H4.all(new g4(this.widget.borderColor,1,"rounded")))});return new v9({focusNode:this.focusNode,autofocus:this.widget.autofocus,child:new A5({onScroll:this.handleMouseScroll.bind(this),child:K})})}}});var AW6=u(()=>{yT();fT();ox1();Yu();L9();K71();RH()});var jg1,OW6;var jW6=u(()=>{B0();Yc();d7();qX();Og1();AW6();jg1=class jg1 extends N6{props;constructor(J){super();this.props=J}createState(){return new OW6}};OW6=class OW6 extends V6{options=[];loading=!0;error=null;async initState(){try{this.loading=!0,this.error=null;let J=await oj({includeAll:!0,jetbrainsOnly:this.widget.props.jetbrainsMode});if(J.length===0){this.error=this.widget.props.jetbrainsMode?"No JetBrains IDE configurations found. Make sure you have a JetBrains IDE with the Amp plugin running.":"No IDE configurations found. Make sure you have an IDE with the Amp plugin running.";return}this.options=J.map((Q)=>{let Z=Q.workspaceFolders.length>0?Q.workspaceFolders[0]:"Unknown project",X=Q.ideName;return{value:{config:Q,label:X},label:X,description:Z}})}catch(J){a.error("Failed to load IDE configurations:",J),this.error="Failed to load IDE configurations"}finally{this.loading=!1,this.setState()}}handleKeyEvent=(J)=>{if(J.key==="Escape"||J.key==="c"&&J.ctrlKey)return this.widget.props.onCancel(),"handled";return"ignored"};build(J){if(this.loading)return new v9({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,child:new W0({text:new C1("Loading available IDEs...",new g1({color:m1.white}))})});if(this.error)return new v9({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,child:new W0({text:new C1(`${this.error}
|
5965
5965
|
|
5966
|
-
Help: https://ampcode.com/manual#
|
5966
|
+
Help: https://ampcode.com/manual#ide
|
5967
5967
|
|
5968
5968
|
Press Escape or Ctrl+C to close`,new g1({color:m1.red}))})});if(this.options.length===0)return new v9({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,child:new W0({text:new C1(`No IDE configurations found. Make sure you have an IDE with the Amp plugin running.
|
5969
5969
|
|
5970
|
-
Help: https://ampcode.com/manual#
|
5970
|
+
Help: https://ampcode.com/manual#ide
|
5971
5971
|
|
5972
5972
|
Press Escape or Ctrl+C to close`,new g1({color:m1.yellow}))})});let Q=p8.sizeOf(J),Z=Math.max(5,Q.height);Z-=6;let X=Math.floor(Math.max(1,Z/2));return new v9({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,child:new cu({title:"Select IDE:",options:this.options,onSelect:(Y)=>{if(Y)this.widget.props.onSelect(Y.config);else this.widget.props.onCancel()},maxVisibleItems:X,autofocus:this.widget.props.autofocus??!0})})}}});var EW6=e((Ix2,IW6)=>{IW6.exports=h51;function h51(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}h51.prototype.go=function(J){if(this.pending<this.max)wW6(this,J);else this.waiting.push(J)};h51.prototype.wait=function(J){if(this.pending===0)J(this.error);else this.listeners.push(J)};h51.prototype.hold=function(){return RW6(this)};function RW6(J){J.pending+=1;var Q=!1;return Z;function Z(Y){if(Q)throw Error("callback called twice");if(Q=!0,J.error=J.error||Y,J.pending-=1,J.waiting.length>0&&J.pending<J.max)wW6(J,J.waiting.shift());else if(J.pending===0){var K=J.listeners;J.listeners=[],K.forEach(X)}}function X(Y){Y(J.error)}}function wW6(J,Q){Q(RW6(J))}});var PW6=e((OY9)=>{var lu=o1("fs"),g51=o1("util"),Rg1=o1("stream"),$W6=Rg1.Readable,wg1=Rg1.Writable,VY9=Rg1.PassThrough,NY9=EW6(),m51=o1("events").EventEmitter;OY9.createFromBuffer=LY9;OY9.createFromFd=AY9;OY9.BufferSlicer=yH;OY9.FdSlicer=xH;g51.inherits(xH,m51);function xH(J,Q){Q=Q||{},m51.call(this),this.fd=J,this.pend=new NY9,this.pend.max=1,this.refCount=0,this.autoClose=!!Q.autoClose}xH.prototype.read=function(J,Q,Z,X,Y){var K=this;K.pend.go(function(q){lu.read(K.fd,J,Q,Z,X,function(G,z,U){q(),Y(G,z,U)})})};xH.prototype.write=function(J,Q,Z,X,Y){var K=this;K.pend.go(function(q){lu.write(K.fd,J,Q,Z,X,function(G,z,U){q(),Y(G,z,U)})})};xH.prototype.createReadStream=function(J){return new u51(this,J)};xH.prototype.createWriteStream=function(J){return new p51(this,J)};xH.prototype.ref=function(){this.refCount+=1};xH.prototype.unref=function(){var J=this;if(J.refCount-=1,J.refCount>0)return;if(J.refCount<0)throw Error("invalid unref");if(J.autoClose)lu.close(J.fd,Q);function Q(Z){if(Z)J.emit("error",Z);else J.emit("close")}};g51.inherits(u51,$W6);function u51(J,Q){Q=Q||{},$W6.call(this,Q),this.context=J,this.context.ref(),this.start=Q.start||0,this.endOffset=Q.end,this.pos=this.start,this.destroyed=!1}u51.prototype._read=function(J){var Q=this;if(Q.destroyed)return;var Z=Math.min(Q._readableState.highWaterMark,J);if(Q.endOffset!=null)Z=Math.min(Z,Q.endOffset-Q.pos);if(Z<=0){Q.destroyed=!0,Q.push(null),Q.context.unref();return}Q.context.pend.go(function(X){if(Q.destroyed)return X();var Y=Buffer.allocUnsafe(Z);lu.read(Q.context.fd,Y,0,Z,Q.pos,function(K,q){if(K)Q.destroy(K);else if(q===0)Q.destroyed=!0,Q.push(null),Q.context.unref();else Q.pos+=q,Q.push(Y.slice(0,q));X()})})};u51.prototype.destroy=function(J){if(this.destroyed)return;J=J||Error("stream destroyed"),this.destroyed=!0,this.emit("error",J),this.context.unref()};g51.inherits(p51,wg1);function p51(J,Q){Q=Q||{},wg1.call(this,Q),this.context=J,this.context.ref(),this.start=Q.start||0,this.endOffset=Q.end==null?1/0:+Q.end,this.bytesWritten=0,this.pos=this.start,this.destroyed=!1,this.on("finish",this.destroy.bind(this))}p51.prototype._write=function(J,Q,Z){var X=this;if(X.destroyed)return;if(X.pos+J.length>X.endOffset){var Y=Error("maximum file length exceeded");Y.code="ETOOBIG",X.destroy(),Z(Y);return}X.context.pend.go(function(K){if(X.destroyed)return K();lu.write(X.context.fd,J,0,J.length,X.pos,function(q,G){if(q)X.destroy(),K(),Z(q);else X.bytesWritten+=G,X.pos+=G,X.emit("progress"),K(),Z()})})};p51.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=!0,this.context.unref()};g51.inherits(yH,m51);function yH(J,Q){m51.call(this),Q=Q||{},this.refCount=0,this.buffer=J,this.maxChunkSize=Q.maxChunkSize||Number.MAX_SAFE_INTEGER}yH.prototype.read=function(J,Q,Z,X,Y){if(!(0<=Q&&Q<=J.length))throw RangeError("offset outside buffer: 0 <= "+Q+" <= "+J.length);if(X<0)throw RangeError("position is negative: "+X);if(Q+Z>J.length)Z=J.length-Q;if(X+Z>this.buffer.length)Z=this.buffer.length-X;if(Z<=0){setImmediate(function(){Y(null,0)});return}this.buffer.copy(J,Q,X,X+Z),setImmediate(function(){Y(null,Z)})};yH.prototype.write=function(J,Q,Z,X,Y){J.copy(this.buffer,X,Q,Q+Z),setImmediate(function(){Y(null,Z,J)})};yH.prototype.createReadStream=function(J){J=J||{};var Q=new VY9(J);Q.destroyed=!1,Q.start=J.start||0,Q.endOffset=J.end,Q.pos=Q.endOffset||this.buffer.length;var Z=this.buffer.slice(Q.start,Q.pos),X=0;while(!0){var Y=X+this.maxChunkSize;if(Y>=Z.length){if(X<Z.length)Q.write(Z.slice(X,Z.length));break}Q.write(Z.slice(X,Y)),X=Y}return Q.end(),Q.destroy=function(){Q.destroyed=!0},Q};yH.prototype.createWriteStream=function(J){var Q=this;J=J||{};var Z=new wg1(J);return Z.start=J.start||0,Z.endOffset=J.end==null?this.buffer.length:+J.end,Z.bytesWritten=0,Z.pos=Z.start,Z.destroyed=!1,Z._write=function(X,Y,K){if(Z.destroyed)return;var q=Z.pos+X.length;if(q>Z.endOffset){var G=Error("maximum file length exceeded");G.code="ETOOBIG",Z.destroyed=!0,K(G);return}X.copy(Q.buffer,Z.pos,0,X.length),Z.bytesWritten+=X.length,Z.pos=q,Z.emit("progress"),K()},Z.destroy=function(){Z.destroyed=!0},Z};yH.prototype.ref=function(){this.refCount+=1};yH.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")};function LY9(J,Q){return new yH(J,Q)}function AY9(J,Q){return new xH(J,Q)}});var SW6=e(($x2,CW6)=>{var bV=o1("buffer").Buffer,Ig1=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918000,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array<"u")Ig1=new Int32Array(Ig1);function TW6(J){if(bV.isBuffer(J))return J;var Q=typeof bV.alloc==="function"&&typeof bV.from==="function";if(typeof J==="number")return Q?bV.alloc(J):new bV(J);else if(typeof J==="string")return Q?bV.from(J):new bV(J);else throw Error("input must be buffer, number, or string, received "+typeof J)}function EY9(J){var Q=TW6(4);return Q.writeInt32BE(J,0),Q}function Eg1(J,Q){if(J=TW6(J),bV.isBuffer(Q))Q=Q.readUInt32BE(0);var Z=~~Q^-1;for(var X=0;X<J.length;X++)Z=Ig1[(Z^J[X])&255]^Z>>>8;return Z^-1}function $g1(){return EY9(Eg1.apply(null,arguments))}$g1.signed=function(){return Eg1.apply(null,arguments)};$g1.unsigned=function(){return Eg1.apply(null,arguments)>>>0};CW6.exports=$g1});function SY9(J,Q,Z){if(typeof Q==="function")Z=Q,Q=null;if(Q==null)Q={};if(Q.autoClose==null)Q.autoClose=!0;if(Q.lazyEntries==null)Q.lazyEntries=!1;if(Q.decodeStrings==null)Q.decodeStrings=!0;if(Q.validateEntrySizes==null)Q.validateEntrySizes=!0;if(Q.strictFileNames==null)Q.strictFileNames=!1;if(Z==null)Z=c51;Pg1.open(J,"r",function(X,Y){if(X)return Z(X);vY9(Y,Q,function(K,q){if(K)Pg1.close(Y,c51);Z(K,q)})})}function vY9(J,Q,Z){if(typeof Q==="function")Z=Q,Q=null;if(Q==null)Q={};if(Q.autoClose==null)Q.autoClose=!1;if(Q.lazyEntries==null)Q.lazyEntries=!1;if(Q.decodeStrings==null)Q.decodeStrings=!0;if(Q.validateEntrySizes==null)Q.validateEntrySizes=!0;if(Q.strictFileNames==null)Q.strictFileNames=!1;if(Z==null)Z=c51;Pg1.fstat(J,function(X,Y){if(X)return Z(X);var K=PY9.createFromFd(J,{autoClose:!0});kY9(K,Y.size,Q,Z)})}function kY9(J,Q,Z,X){if(typeof Z==="function")X=Z,Z=null;if(Z==null)Z={};if(Z.autoClose==null)Z.autoClose=!0;if(Z.lazyEntries==null)Z.lazyEntries=!1;if(Z.decodeStrings==null)Z.decodeStrings=!0;var Y=!!Z.decodeStrings;if(Z.validateEntrySizes==null)Z.validateEntrySizes=!0;if(Z.strictFileNames==null)Z.strictFileNames=!1;if(X==null)X=c51;if(typeof Q!=="number")throw Error("expected totalSize parameter to be a number");if(Q>Number.MAX_SAFE_INTEGER)throw Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");J.ref();var K=22,q=20,G=65535,z=Math.min(q+K+G,Q),U=hH(z),W=Q-U.length;XC(J,U,0,z,W,function(F){if(F)return X(F);for(var H=z-K;H>=0;H-=1){if(U.readUInt32LE(H)!==101010256)continue;var B=U.subarray(H),M=B.readUInt16LE(4),V=B.readUInt16LE(10),N=B.readUInt32LE(16),L=B.readUInt16LE(20),A=B.length-K;if(L!==A)return X(Error("Invalid comment length. Expected: "+A+". Found: "+L+". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?"));var O=Y?d51(B.subarray(22),!1):B.subarray(22);if(H-q>=0&&U.readUInt32LE(H-q)===117853008){var j=U.subarray(H-q,H-q+q),R=ZC(j,8),I=hH(56);return XC(J,I,0,I.length,R,function(w){if(w)return X(w);if(I.readUInt32LE(0)!==101075792)return X(Error("invalid zip64 end of central directory record signature"));if(M=I.readUInt32LE(16),M!==0)return X(Error("multi-disk zip files are not supported: found disk number: "+M));return V=ZC(I,32),N=ZC(I,48),X(null,new fH(J,N,Q,V,O,Z.autoClose,Z.lazyEntries,Y,Z.validateEntrySizes,Z.strictFileNames))})}if(M!==0)return X(Error("multi-disk zip files are not supported: found disk number: "+M));return X(null,new fH(J,N,Q,V,O,Z.autoClose,Z.lazyEntries,Y,Z.validateEntrySizes,Z.strictFileNames))}X(Error("End of central directory record signature not found. Either not a zip file, or file is truncated."))})}function fH(J,Q,Z,X,Y,K,q,G,z,U){var W=this;if(i51.call(W),W.reader=J,W.reader.on("error",function(F){kW6(W,F)}),W.reader.once("close",function(){W.emit("close")}),W.readEntryCursor=Q,W.fileSize=Z,W.entryCount=X,W.comment=Y,W.entriesRead=0,W.autoClose=!!K,W.lazyEntries=!!q,W.decodeStrings=!!G,W.validateEntrySizes=!!z,W.strictFileNames=!!U,W.isOpen=!0,W.emittedError=!1,!W.lazyEntries)W._readEntry()}function uU(J,Q){if(J.autoClose)J.close();kW6(J,Q)}function kW6(J,Q){if(J.emittedError)return;J.emittedError=!0,J.emit("error",Q)}function a51(){}function _Y9(){}function bY9(J,Q,Z){var X=J&31,Y=(J>>5&15)-1,K=(J>>9&127)+1980,q=0,G=(Q&31)*2,z=Q>>5&63,U=Q>>11&31;if(Z==null||Z==="local")return new Date(K,Y,X,U,z,G,q);else if(Z==="UTC")return new Date(Date.UTC(K,Y,X,U,z,G,q));else throw Error("unrecognized options.timezone: "+options.timezone)}function xY9(J,Q,Z,X){var Y=null;for(var K=0;K<Z.length;K++){var q=Z[K];if(q.id===28789){if(q.data.length<6)continue;if(q.data.readUInt8(0)!==1)continue;var G=q.data.readUInt32LE(1);if(TY9.unsigned(Q)!==G)continue;Y=d51(q.data.subarray(5),!0);break}}if(Y==null){var z=(J&2048)!==0;Y=d51(Q,z)}if(!X)Y=Y.replace(/\\/g,"/");return Y}function yY9(J){if(J.indexOf("\\")!==-1)return"invalid characters in fileName: "+J;if(/^[a-zA-Z]:/.test(J)||/^\//.test(J))return"absolute path: "+J;if(J.split("/").indexOf("..")!==-1)return"invalid relative path: "+J;return null}function fY9(J){var Q=[],Z=0;while(Z<J.length-3){var X=J.readUInt16LE(Z+0),Y=J.readUInt16LE(Z+2),K=Z+4,q=K+Y;if(q>J.length)throw Error("extra field length exceeds extra field buffer size");var G=J.subarray(K,q);Q.push({id:X,data:G}),Z=q}return Q}function XC(J,Q,Z,X,Y,K){if(X===0)return setImmediate(function(){K(null,hH(0))});J.read(Q,Z,X,Y,function(q,G){if(q)return K(q);if(G<X)return K(Error("unexpected EOF"));K()})}function iu(J){vW6.call(this),this.actualByteCount=0,this.expectedByteCount=J}function aO(){i51.call(this),this.refCount=0}function n51(J){Cg1.call(this),this.context=J,this.context.ref(),this.unreffedYet=!1}function d51(J,Q){if(Q)return J.toString("utf8");else{var Z="";for(var X=0;X<J.length;X++)Z+=hY9[J[X]];return Z}}function ZC(J,Q){var Z=J.readUInt32LE(Q),X=J.readUInt32LE(Q+4);return X*4294967296+Z}function Tg1(J,Q){if(typeof J.destroy==="function")J._destroy=function(Z,X){if(Q(),X!=null)X(Z)};else J.destroy=Q}function c51(J){if(J)throw J}var Pg1,$Y9,PY9,TY9,l51,i51,vW6,Cg1,CY9,Sg1,hY9="\x00☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ",hH;var _W6=u(()=>{Pg1=o1("fs"),$Y9=o1("zlib"),PY9=PW6(),TY9=SW6(),l51=o1("util"),i51=o1("events").EventEmitter,vW6=o1("stream").Transform,Cg1=o1("stream").PassThrough,CY9=o1("stream").Writable;Sg1=SY9;l51.inherits(fH,i51);fH.prototype.close=function(){if(!this.isOpen)return;this.isOpen=!1,this.reader.unref()};fH.prototype.readEntry=function(){if(!this.lazyEntries)throw Error("readEntry() called without lazyEntries:true");this._readEntry()};fH.prototype._readEntry=function(){var J=this;if(J.entryCount===J.entriesRead){setImmediate(function(){if(J.autoClose)J.close();if(J.emittedError)return;J.emit("end")});return}if(J.emittedError)return;var Q=hH(46);XC(J.reader,Q,0,Q.length,J.readEntryCursor,function(Z){if(Z)return uU(J,Z);if(J.emittedError)return;var X=new a51,Y=Q.readUInt32LE(0);if(Y!==33639248)return uU(J,Error("invalid central directory file header signature: 0x"+Y.toString(16)));if(X.versionMadeBy=Q.readUInt16LE(4),X.versionNeededToExtract=Q.readUInt16LE(6),X.generalPurposeBitFlag=Q.readUInt16LE(8),X.compressionMethod=Q.readUInt16LE(10),X.lastModFileTime=Q.readUInt16LE(12),X.lastModFileDate=Q.readUInt16LE(14),X.crc32=Q.readUInt32LE(16),X.compressedSize=Q.readUInt32LE(20),X.uncompressedSize=Q.readUInt32LE(24),X.fileNameLength=Q.readUInt16LE(28),X.extraFieldLength=Q.readUInt16LE(30),X.fileCommentLength=Q.readUInt16LE(32),X.internalFileAttributes=Q.readUInt16LE(36),X.externalFileAttributes=Q.readUInt32LE(38),X.relativeOffsetOfLocalHeader=Q.readUInt32LE(42),X.generalPurposeBitFlag&64)return uU(J,Error("strong encryption is not supported"));J.readEntryCursor+=46,Q=hH(X.fileNameLength+X.extraFieldLength+X.fileCommentLength),XC(J.reader,Q,0,Q.length,J.readEntryCursor,function(K){if(K)return uU(J,K);if(J.emittedError)return;X.fileNameRaw=Q.subarray(0,X.fileNameLength);var q=X.fileNameLength+X.extraFieldLength;X.extraFieldRaw=Q.subarray(X.fileNameLength,q),X.fileCommentRaw=Q.subarray(q,q+X.fileCommentLength);try{X.extraFields=fY9(X.extraFieldRaw)}catch(V){return uU(J,V)}if(J.decodeStrings){var G=(X.generalPurposeBitFlag&2048)!==0;X.fileComment=d51(X.fileCommentRaw,G),X.fileName=xY9(X.generalPurposeBitFlag,X.fileNameRaw,X.extraFields,J.strictFileNames);var z=yY9(X.fileName);if(z!=null)return uU(J,Error(z))}else X.fileComment=X.fileCommentRaw,X.fileName=X.fileNameRaw;X.comment=X.fileComment,J.readEntryCursor+=Q.length,J.entriesRead+=1;for(var U=0;U<X.extraFields.length;U++){var W=X.extraFields[U];if(W.id!==1)continue;var F=W.data,H=0;if(X.uncompressedSize===4294967295){if(H+8>F.length)return uU(J,Error("zip64 extended information extra field does not include uncompressed size"));X.uncompressedSize=ZC(F,H),H+=8}if(X.compressedSize===4294967295){if(H+8>F.length)return uU(J,Error("zip64 extended information extra field does not include compressed size"));X.compressedSize=ZC(F,H),H+=8}if(X.relativeOffsetOfLocalHeader===4294967295){if(H+8>F.length)return uU(J,Error("zip64 extended information extra field does not include relative header offset"));X.relativeOffsetOfLocalHeader=ZC(F,H),H+=8}break}if(J.validateEntrySizes&&X.compressionMethod===0){var B=X.uncompressedSize;if(X.isEncrypted())B+=12;if(X.compressedSize!==B){var M="compressed/uncompressed size mismatch for stored file: "+X.compressedSize+" != "+X.uncompressedSize;return uU(J,Error(M))}}if(J.emit("entry",X),!J.lazyEntries)J._readEntry()})})};fH.prototype.openReadStream=function(J,Q,Z){var X=this,Y=0,K=J.compressedSize;if(Z==null)Z=Q,Q=null;if(Q==null)Q={};else{if(Q.decrypt!=null){if(!J.isEncrypted())throw Error("options.decrypt can only be specified for encrypted entries");if(Q.decrypt!==!1)throw Error("invalid options.decrypt value: "+Q.decrypt);if(J.isCompressed()){if(Q.decompress!==!1)throw Error("entry is encrypted and compressed, and options.decompress !== false")}}if(Q.decompress!=null){if(!J.isCompressed())throw Error("options.decompress can only be specified for compressed entries");if(!(Q.decompress===!1||Q.decompress===!0))throw Error("invalid options.decompress value: "+Q.decompress)}if(Q.start!=null||Q.end!=null){if(J.isCompressed()&&Q.decompress!==!1)throw Error("start/end range not allowed for compressed entry without options.decompress === false");if(J.isEncrypted()&&Q.decrypt!==!1)throw Error("start/end range not allowed for encrypted entry without options.decrypt === false")}if(Q.start!=null){if(Y=Q.start,Y<0)throw Error("options.start < 0");if(Y>J.compressedSize)throw Error("options.start > entry.compressedSize")}if(Q.end!=null){if(K=Q.end,K<0)throw Error("options.end < 0");if(K>J.compressedSize)throw Error("options.end > entry.compressedSize");if(K<Y)throw Error("options.end < options.start")}}if(!X.isOpen)return Z(Error("closed"));if(J.isEncrypted()){if(Q.decrypt!==!1)return Z(Error("entry is encrypted, and options.decrypt !== false"))}var q;if(J.compressionMethod===0)q=!1;else if(J.compressionMethod===8)q=Q.decompress!=null?Q.decompress:!0;else return Z(Error("unsupported compression method: "+J.compressionMethod));X.readLocalFileHeader(J,{minimal:!0},function(G,z){if(G)return Z(G);X.openReadStreamLowLevel(z.fileDataStart,J.compressedSize,Y,K,q,J.uncompressedSize,Z)})};fH.prototype.openReadStreamLowLevel=function(J,Q,Z,X,Y,K,q){var G=this,z=J+Q,U=G.reader.createReadStream({start:J+Z,end:J+X}),W=U;if(Y){var F=!1,H=$Y9.createInflateRaw();if(U.on("error",function(B){setImmediate(function(){if(!F)H.emit("error",B)})}),U.pipe(H),G.validateEntrySizes)W=new iu(K),H.on("error",function(B){setImmediate(function(){if(!F)W.emit("error",B)})}),H.pipe(W);else W=H;Tg1(W,function(){if(F=!0,H!==W)H.unpipe(W);U.unpipe(H),U.destroy()})}q(null,W)};fH.prototype.readLocalFileHeader=function(J,Q,Z){var X=this;if(Z==null)Z=Q,Q=null;if(Q==null)Q={};X.reader.ref();var Y=hH(30);XC(X.reader,Y,0,Y.length,J.relativeOffsetOfLocalHeader,function(K){try{if(K)return Z(K);var q=Y.readUInt32LE(0);if(q!==67324752)return Z(Error("invalid local file header signature: 0x"+q.toString(16)));var G=Y.readUInt16LE(26),z=Y.readUInt16LE(28),U=J.relativeOffsetOfLocalHeader+30+G+z;if(U+J.compressedSize>X.fileSize)return Z(Error("file data overflows file bounds: "+U+" + "+J.compressedSize+" > "+X.fileSize));if(Q.minimal)return Z(null,{fileDataStart:U});var W=new _Y9;W.fileDataStart=U,W.versionNeededToExtract=Y.readUInt16LE(4),W.generalPurposeBitFlag=Y.readUInt16LE(6),W.compressionMethod=Y.readUInt16LE(8),W.lastModFileTime=Y.readUInt16LE(10),W.lastModFileDate=Y.readUInt16LE(12),W.crc32=Y.readUInt32LE(14),W.compressedSize=Y.readUInt32LE(18),W.uncompressedSize=Y.readUInt32LE(22),W.fileNameLength=G,W.extraFieldLength=z,Y=hH(G+z),X.reader.ref(),XC(X.reader,Y,0,Y.length,J.relativeOffsetOfLocalHeader+30,function(F){try{if(F)return Z(F);return W.fileName=Y.subarray(0,G),W.extraField=Y.subarray(G),Z(null,W)}finally{X.reader.unref()}})}finally{X.reader.unref()}})};a51.prototype.getLastModDate=function(J){if(J==null)J={};if(!J.forceDosFormat)for(var Q=0;Q<this.extraFields.length;Q++){var Z=this.extraFields[Q];if(Z.id===21589){var X=Z.data;if(X.length<5)continue;var Y=X[0],K=1;if(!(Y&K))continue;var q=X.readInt32LE(1);return new Date(q*1000)}else if(Z.id===10){var X=Z.data,G=4;while(G<X.length+4){var z=X.readUInt16LE(G);G+=2;var U=X.readUInt16LE(G);if(G+=2,z!==1){G+=U;continue}if(U<8||G+U>X.length)break;var W=4294967296*X.readInt32LE(G+4)+X.readUInt32LE(G),F=W/1e4-11644473600000;return new Date(F)}}}return bY9(this.lastModFileDate,this.lastModFileTime,J.timezone)};a51.prototype.isEncrypted=function(){return(this.generalPurposeBitFlag&1)!==0};a51.prototype.isCompressed=function(){return this.compressionMethod===8};l51.inherits(iu,vW6);iu.prototype._transform=function(J,Q,Z){if(this.actualByteCount+=J.length,this.actualByteCount>this.expectedByteCount){var X="too many bytes in the stream. expected "+this.expectedByteCount+". got at least "+this.actualByteCount;return Z(Error(X))}Z(null,J)};iu.prototype._flush=function(J){if(this.actualByteCount<this.expectedByteCount){var Q="not enough bytes in the stream. expected "+this.expectedByteCount+". got only "+this.actualByteCount;return J(Error(Q))}J()};l51.inherits(aO,i51);aO.prototype.ref=function(){this.refCount+=1};aO.prototype.unref=function(){var J=this;if(J.refCount-=1,J.refCount>0)return;if(J.refCount<0)throw Error("invalid unref");J.close(Q);function Q(Z){if(Z)return J.emit("error",Z);J.emit("close")}};aO.prototype.createReadStream=function(J){if(J==null)J={};var{start:Q,end:Z}=J;if(Q===Z){var X=new Cg1;return setImmediate(function(){X.end()}),X}var Y=this._readStreamForRange(Q,Z),K=!1,q=new n51(this);Y.on("error",function(z){setImmediate(function(){if(!K)q.emit("error",z)})}),Tg1(q,function(){Y.unpipe(q),q.unref(),Y.destroy()});var G=new iu(Z-Q);return q.on("error",function(z){setImmediate(function(){if(!K)G.emit("error",z)})}),Tg1(G,function(){K=!0,q.unpipe(G),q.destroy()}),Y.pipe(q).pipe(G)};aO.prototype._readStreamForRange=function(J,Q){throw Error("not implemented")};aO.prototype.read=function(J,Q,Z,X,Y){var K=this.createReadStream({start:X,end:X+Z}),q=new CY9,G=0;q._write=function(z,U,W){z.copy(J,Q+G,0,z.length),G+=z.length,W()},q.on("finish",Y),K.on("error",function(z){Y(z)}),K.pipe(q)};aO.prototype.close=function(J){setImmediate(J)};l51.inherits(n51,Cg1);n51.prototype._flush=function(J){this.unref(),J()};n51.prototype.unref=function(J){if(this.unreffedYet)return;this.unreffedYet=!0,this.context.unref()};if(typeof Buffer.allocUnsafe==="function")hH=function(J){return Buffer.allocUnsafe(J)};else hH=function(J){return new Buffer(J)}});import{createWriteStream as gY9,existsSync as mY9,mkdirSync as uY9,readdirSync as pY9,rmSync as dY9}from"node:fs";import{writeFile as cY9}from"node:fs/promises";import au from"node:path";import{pipeline as lY9}from"node:stream/promises";async function bW6(J,Q,Z,X=iY9){a.debug("jetbrains-plugin-install",{pluginDirectory:J});let Y=au.join(J,"lib");if(mY9(Y)){let q=pY9(Y,{withFileTypes:!0}).filter((G)=>G.name.endsWith(".jar"));a.info("jetbrains-plugin-install",{libDirectory:Y,removableJarFiles:q.map((G)=>G.name)}),q.forEach((G)=>{dY9(au.join(G.parentPath,G.name))})}uY9(Y,{recursive:!0});let K=au.join(J,"version.txt");return await cY9(K,Z,"utf8"),X(Q,Y)}function iY9(J,Q){return new Promise((Z,X)=>{Sg1(J,{lazyEntries:!0},(Y,K)=>{if(Y)return X(Y);if(!K)return X(Error("Failed to open ZIP file"));K.readEntry(),K.on("entry",(q)=>{if(q.fileName.startsWith("amp-jetbrains-plugin/lib/"))K.openReadStream(q,async(G,z)=>{if(G)return X(G);if(!z)return X(Error("Failed to open read stream"));let U=au.basename(q.fileName),W=au.join(Q,U);await lY9(z,gY9(W)),K.readEntry()});else K.readEntry()}),K.on("end",Z),K.on("error",X)})})}var xW6=u(()=>{_W6();B0()});import{createHash as aY9}from"node:crypto";import{createWriteStream as nY9,existsSync as r51,readdirSync as rY9,readFileSync as sY9}from"node:fs";import{copyFile as oY9,mkdir as tY9,readFile as eY9,rename as JK9,unlink as QK9}from"node:fs/promises";import{homedir as yW6,platform as kg1}from"node:os";import xV from"node:path";import{Readable as ZK9}from"node:stream";import{pipeline as XK9}from"node:stream/promises";async function vg1(J,Q=3){for(let Z=1;Z<=Q;Z++)try{let X=await fetch(J);if(!X.ok)throw Error(`HTTP ${X.status}: ${X.statusText} for ${J}`);return X}catch(X){let Y=X instanceof Error?X.message:String(X);if(X instanceof Error&&X.message.match(/HTTP 4\d\d:/))throw X;if(Z===Q)throw X;let K=500*Math.pow(2,Z-1);a.warn("fetchWithRetry",{url:J,attempt:Z,maxRetries:Q,message:Y,retryingInMs:K}),await new Promise((q)=>setTimeout(q,K))}throw Error("Unexpected end of retry loop")}async function mW6(){if(nu)return a.debug("jetbrains-plugin-version",{message:"Using cached version info",cachedVersionInfo:nu}),nu;return a.debug("jetbrains-plugin-version",{message:"Fetching version info",url:fW6}),nu=await(await vg1(fW6)).json(),nu}async function _g1(){return(await mW6()).plugin_version}async function uW6(){let J=await _g1();return`${gW6}-${J}.zip`}function YK9(){let J=kg1();return a.debug("jetbrains-plugin-discovery",{os:J}),["darwin","win32"].includes(J)}function KK9(J,Q){if(!J?.pluginVersion)return"unknown";return J?.pluginVersion===Q?"uptodate":"outdated"}function pW6(J,Q){if(a.debug("jetbrains-plugin-discovery",{ideStatus:J}),YK9()){let X=GK9();if(a.debug("jetbrains-plugin-discovery",{discoveryResult:X}),!X.success)return X;let Y=X.products.map((K)=>{let q=hW6(K.pluginDirectory,Q);return{...K,installType:q.installType,installedVersion:q.installedVersion}}).filter((K)=>hW6(K.pluginDirectory,Q).needsInstall);return a.debug("jetbrains-plugin-discovery",{installationTargets:Y}),{success:!0,products:Y}}let Z=KK9(J,Q);if(a.debug("jetbrains-plugin-discovery",{connectedVersionStatus:Z}),Z==="outdated"&&J?.pluginDirectory&&J?.ideName)return{success:!0,products:[{name:J.ideName,version:"",pluginDirectory:J.pluginDirectory,installType:"upgrade",installedVersion:J.pluginVersion}]};if(Z==="uptodate")return{success:!0,products:[]};return{success:!0,requiresManualInstall:!0,products:[]}}async function dW6(J,Q,Z){a.debug("jetbrains-plugin-install",{message:"Starting plugin installation",targetCount:J.length,targets:J.map((Y)=>`${Y.name} ${Y.version}`),cacheDirectory:Q});let X=await o51(Q);for(let Y of J)try{a.debug("jetbrains-plugin-install:start",{product:Y}),await bW6(Y.pluginDirectory,X,Z),a.debug("jetbrains-plugin-install:complete",{product:Y})}catch(K){throw a.error("jetbrains-plugin-install",{product:Y,error:K}),Error(`Failed to install JetBrains plugin to ${Y.name} ${Y.version}: ${K}`)}a.info("jetbrains-plugin-install",{message:"All plugin installations completed successfully",installedCount:J.length})}function s51(J){let Q=kg1(),Z;switch(Q){case"darwin":Z=xV.join(yW6(),"Library","Application Support",J);break;case"win32":{let X=process.env.APPDATA||xV.join(yW6(),"AppData","Roaming");Z=xV.join(X,J);break}default:throw Error(`Unsupported operating system: ${Q}`)}return Z}function qK9(){let J=["bl","crl","consentOptions","PrivacyPolicy","Toolbox","Chrome","Google","RLZ"];return[s51("JetBrains"),s51("Google")].flatMap((Q)=>{if(!r51(Q))return[];return rY9(Q,{withFileTypes:!0})}).filter((Q)=>{if(!Q.isDirectory())return!1;return!J.find((Z)=>Q.name.startsWith(Z))})}function GK9(){try{let J=qK9();if(J.length===0)return{success:!1,products:[],helpMessage:"Directory does not exist. Please ensure you have JetBrains IDEs installed."};a.debug("jetbrains-plugin-discovery",{productDirectories:J});let Q=[];for(let Z of J){let{productName:X,version:Y}=UK9(Z.name);if(["2020","2021","2022","2023","unknown"].find((K)=>Y.startsWith(K))){a.debug("jetbrains-plugin-discovery",{skipped:Z.name});continue}Q.push({name:X,version:Y,pluginDirectory:xV.join(Z.parentPath,Z.name,"plugins",gW6)})}return{success:!0,products:Q.sort((Z,X)=>{return Z.name.localeCompare(X.name)||Z.version.localeCompare(X.version)})}}catch(J){a.error("jetbrains-plugin-discovery",{error:J});let Q=kg1(),X=`Failed to access JetBrains directory at: ${[s51("JetBrains"),s51("Google")].join(", ")}
|
5973
5973
|
`;if(J instanceof Error&&"code"in J)switch(J.code){case"EACCES":X+="Permission denied. Please check directory permissions.";break;default:X+=`Error: ${J.message}`}else X+=`Error: ${String(J)}`;if(Q==="darwin")X+=`
|
@@ -5984,7 +5984,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
5984
5984
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${U}
|
5985
5985
|
`)}}function RK9(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 m1.index(Z[X])}var MF6,VF6;var LF6=u(()=>{B0();aw();p2();VC();iw();G7();$N();Q4();P3();n6();b0();FZ6();xZ6();yZ6();d7();E71();IO();GY6();dT();yU();jy1();wJ();CO();WY6();d9();$71();D2();$Y6();qX();Z2();ry1();j5();Yu();L9();tU6();GX();eY6();YW6();KW6();FW6();MW6();vu();VW6();Nf1();NW6();jW6();nW6();rW6();aU6();oW6();_51();JF6();ZF6();Bf1();oU6();zF6();HF6();DF6();MF6=class MF6 extends N6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new VF6}};VF6=class VF6 extends V6{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!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="hidden";updateServiceSubscription=null;isFreeTierEnabled=!1;isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(Boolean(J.viewState.state==="active"&&J.viewState.inferenceState==="running"))return!0;return[...J.activeTools,...J.subagentActiveTools].filter((Y)=>Y.toolRun.status==="in-progress"||Y.toolRun.status==="queued").length>0}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 C1(this.submitDisabledHint,new g1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new C1("",void 0,[new C1("Ctrl+C",new g1({color:Q.keybind})),new C1(" again to exit",new g1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new C1("",void 0,[new C1("Esc",new g1({color:Q.keybind})),new C1(" again to clear input",new g1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new C1("",void 0,[new C1("Escape",new g1({color:Q.keybind})),new C1(" to close help",new g1({color:J.foreground,dim:!0}))]);if(this.isProcessing()||this.bashInvocations.length>0)return new C1("",void 0,[new C1("Esc",new g1({color:Q.keybind})),new C1(" to cancel",new g1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new C1("Selection copied to clipboard",new g1({color:J.foreground,dim:!0}));let Z=BF6(this.updateState,J);if(Z)return new C1("",void 0,Z);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}textController=new y71;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new $V);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(Jy1(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 X7("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 dx1(this.widget.dependencies.commandRegistry);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Bg1(this.getCommands(),this.widget.dependencies.fuzzyServer,new e51);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.ideClient.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J){await this.widget.dependencies.ideClient.start(J,!0)}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=GZ6(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();r71(z);return}if(J.launchesWindow)EG.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 Cn({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}))},openIdePicker:()=>{this.openIdePicker()}},Q,X.signal);if(J.launchesWindow)EG.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=ug1().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(),r71(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=nT();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=_9.pipe(v0((Q)=>Vz(Q.settings)),P8()).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=UZ6(Q);if(!X)return!0;if(this.imageAttachments.length>=Ot1)return!1;let Y=WZ6(X);if(Y)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return!0},this.updateTerminalTitle();let J=this.widget.dependencies.ideClient.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(Jy1("")),this.shouldUseProgressBar())process.stdout.write(Qy1());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 p8.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(a.info("Progress bar update",{oldState:this.currentProgressBarState,newState:Z,hasConfirmation:!!Q,isProcessing:this.isProcessing()}),Z!==this.currentProgressBarState)this.currentProgressBarState=Z,this.sendProgressReport(Z),this.scheduleProgressReportTimer()}sendProgressReport(J){switch(a.info("Sending progress report to terminal",{state:J}),J){case"indeterminate":process.stdout.write(GX6());break;case"paused":process.stdout.write(zX6());break;case"off":process.stdout.write(Qy1());break}}scheduleProgressReportTimer(){if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null;let J=this.getCurrentConfirmation(),Q=J||this.isProcessing();if(a.info("Schedule progress report timer",{hasConfirmation:!!J,isProcessing:this.isProcessing(),shouldSchedule:Q,currentState:this.currentProgressBarState}),Q)this.progressReportTimer=setTimeout(()=>{a.info("Progress report timer triggered - resending state",{state:this.currentProgressBarState}),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")aH("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 gJ.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 gJ.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,r71(Q),n71()?.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=nT()||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:
|
5986
5986
|
|
5987
|
-
${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;EG.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=OK9();if(J===Q)return"~";if(J.startsWith(Q+ru.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(ru.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(ru.sep),"…",Q.slice(-2).join(ru.sep)].join(ru.sep)}build(J){let Q=p8.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 vH({child:new fg1({onSelect:async(x)=>{if(x)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(x);else process.exit(0)},pageSize:50,threadFetcher:new e51})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,F=this.isTranscriptEmpty()?new y51({useGpt5:this.widget.dependencies.useGpt5}):new Wg1({key:U?new X7(`message-view-${U}`):void 0,items:q.items,activeTools:q.activeTools,subagentToolsByParentID:q.subagentToolsByParentID,controller:U?this.getMessageScrollController(U):new $V,autofocus:!1,onCopy:this._handleTextCopy.bind(this)}),H=Math.max(Math.floor(Q.size.height*0.4),10),B=this.getCurrentEphemeralError(),M=this.buildBottomWidget(B,G,Y,Z,q,z,H),V=Q.size.width<40,N=q.mainThread?Ul1(q.mainThread):void 0,L=new s71({threadViewState:q.viewState,threadTokenUsage:N,threadID:U??null,thread:q.mainThread??void 0,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}),A=new a71({bashInvocations:this.bashInvocations}),O=[];if(this.isFreeTierEnabled)O.push(new i6({decoration:new h2(Y.secondary),child:new E8({padding:F6.horizontal(1),child:new W0({text:new C1("Thank you for trying the ad-supported Amp Free experiment — AD",new g1({color:m1.black})),textAlign:"center"})})}));O.push(new g2({child:F}),A,new i6({constraints:new f6(0,Q.size.width,0,H),child:M}),new a0({height:1,child:new E8({padding:F6.horizontal(1),child:L})}));let j=new P6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:O}),R=new R5(()=>{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.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((b)=>{a.error("Failed to cancel streaming message:",b)}),"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"}),I=new R5(()=>{return this.onExitPressed(),"handled"}),w=new R5(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),E=new R5(()=>{return CG.instance.toggleAll(),"handled"}),$=new R5(()=>{return EG.instance.toggleFrameStatsOverlay(),"handled"}),P=new R5(()=>{return EG.instance.tuiInstance.getScreen().markForRefresh(),eQ.instance.requestFrame(),"handled"}),C=new R5(()=>{let x=this.findElementByKey("message-view-selection-area");if(x?.state){let b=x.state,m=b.controller?.copySelection();if(m&&m.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{b.controller.endCopyHighlight(),b.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),k=new R5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b){let m=this.getMessageScrollController(b),n=Math.max(Math.floor(Q.size.height*0.4),10),p=Q.size.height-n;m.animatePageUp(p,100)}return"handled"}),g=new R5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b){let m=this.getMessageScrollController(b),n=Math.max(Math.floor(Q.size.height*0.4),10),p=Q.size.height-n;m.animatePageDown(p,100)}return"handled"}),T=new R5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b)this.getMessageScrollController(b).animateTo(0,100);return"handled"}),v=new R5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b)this.getMessageScrollController(b).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),f=new Map([[m2.key("Escape"),new Nu],[m2.ctrl("c"),new cT],[m2.ctrl("l"),new ju],[m2.alt("c"),new Lu],[m2.alt("p"),new Ou],[m2.ctrl("r"),new Au],[m2.key("PageUp"),new T71],[m2.key("PageDown"),new C71],[m2.key("Home"),new S71],[m2.key("End"),new v71]]);if(process.platform==="darwin")f.set(m2.meta("c"),new cT);let h=new Map([[Nu,R],[w71,I],[ju,P],[Lu,w],[Au,E],[Ou,$],[cT,C],[T71,k],[C71,g],[S71,T],[v71,v]]),S=j;if(this.isShowingConsoleOverlay)S=new yK({children:[S,new Ng1]});if(this.isShowingHelp)S=new yK({children:[S,new Ag1]});if(this.isShowingFileChangesOverlay)S=new yK({children:[S,new Vf1]});if(this.isShowingConfirmationOverlay)S=new yK({children:[S,new Dg1({details:this.confirmationOverlayContent})]});if(this.isShowingIdePicker)return new vH({child:new fK({actions:h,child:new EV({shortcuts:f,debugLabel:"ide-picker-shortcuts",child:new jg1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode})})})});if(this.isShowingJetBrainsInstaller)return new vH({child:new fK({actions:h,child:new EV({shortcuts:f,debugLabel:"jetbrains-installer-shortcuts",child:new bg1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new vH({child:new fK({actions:h,child:new EV({shortcuts:f,debugLabel:"main-app-shortcuts",child:S})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new Lg1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new hg1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Vg1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new xg1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=jK9(X),U=new h71({key:this.textFieldKey,controller:this.textController,triggers:[ug1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(P)=>Hg1(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:EG.instance.tuiInstance.clipboard},optionViewBuilder:(P,C,k)=>{let g=k?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=Hg1(C);break}let x=XW6(C),b=new C1(h,new g1({color:T})),m=new C1(S,new g1({color:v})),n=[b,m];if(x){let p=new C1(" - ",new g1({color:f,dim:!0})),Q1=new C1(x,new g1({color:f,dim:!0}));n.push(p,Q1)}return new i6({decoration:new h2(g),child:new W0({text:new C1("",void 0,n),maxLines:1,overflow:"ellipsis"})})}}),W=Y.mainThread?.queuedMessages??[],F=new v9({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,B=this.imageAttachments.length>0?new i6({padding:F6.only({bottom:1,left:1}),child:new W0({text:new C1("",void 0,[new C1("Images: ",new g1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((P,C)=>[new C1(`[image ${C+1}]`,new g1({color:Z.success})),...C<this.imageAttachments.length-1?[new C1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(W)&&W.length>0,N=B?new P6({crossAxisAlignment:"start",children:[B,new g2({child:F})]}):F,L=V?new yg1({queuedMessages:W}):void 0,A=M?new Oy1(new Fg1({todos:K}),{clipBehavior:"antiAlias"}):void 0,O=[],j=Y.viewState;if(!this.isSummarizing(j))O.push({text:new C1("",void 0,[new C1("Enter",new g1({color:G.keybind})),new C1(" to send",new g1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)O.push({text:new C1(H==="hidden"?"shell mode (incognito)":"shell mode",new g1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:B?1:0});let R=this.currentAgentMode;if(R&&!["default",xj[0]].includes(R)&&!H){let P=RK9(R);O.push({text:new C1("",void 0,[new C1("agent-mode: ",new g1({color:Z.foreground,dim:!0})),new C1(R,new g1({color:P}))]),position:"top-left",offsetY:0})}let I=Y.mainThread?.metadata?.treeInfo?.uri,w;if(I)w=P0.isUri(I)?I.fsPath:I;else w=process.cwd();let E=this.toHomeRelative(w),$=this.shorten(E);return O.push({text:new C1($,new g1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new Gf1({leftChild:N,rightChild1:L,rightChild2:A,maxHeight:q,overlayTexts:O,borderColor:Z.border})}}});import{randomBytes as wK9}from"node:crypto";import{mkdir as IK9,readFile as RF6,writeFile as EK9}from"node:fs/promises";import $K9 from"node:os";import pg1 from"node:path";import{stderr as t2,stdout as u2}from"node:process";function PK9(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 nO(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aH("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new O2("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${J8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")aH("experimental.agentMode",Q.agentMode)}async function lg1(J){try{await IK9(pg1.dirname(dg1),{recursive:!0}),await EK9(dg1,J,"utf-8")}catch(Q){a.debug("Failed to save last thread ID",Q)}}async function SK9(){try{return(await RF6(dg1,"utf-8")).trim()}catch(J){return null}}async function vK9(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 CK9.parse(Q)}catch(Z){if(Z instanceof C0.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 kK9(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 yK9(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 O2(_K.unknownCommand(Z),1,q)}}function _g2(){return wF6}function QJ1(J){return{...J,getThreadEnvironment:$41,vfs:z00({os:J.fileSystem}),fileChangeTrackerStorage:new Qk(J.fileSystem),generateThreadTitle:_n,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}async function rO(J,Q){jl1("0.0.1759464081-gf6c1d2");let Z=XZ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Z0.of([P0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:ub1,homeDir:ig1,userConfigDir:IF6}),X=await U9();a.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=qi(vj()),K=u10({configService:Z,toolService:Y}),q=dA0(Y,O8,yt).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)Rl1(!0);if(Q.ide&&Lx1())wl1(!0);if(N86(Y),Q.jetbrains)Y.registerTool(Kr);else if(Q.ide)Y.registerTool(xq0);let z;if(!J.executeMode)z=new y41(process.cwd(),{},!0);else z=new class extends y41{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...
|
5987
|
+
${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;EG.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=OK9();if(J===Q)return"~";if(J.startsWith(Q+ru.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(ru.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(ru.sep),"…",Q.slice(-2).join(ru.sep)].join(ru.sep)}build(J){let Q=p8.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 vH({child:new fg1({onSelect:async(x)=>{if(x)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(x);else process.exit(0)},pageSize:50,threadFetcher:new e51})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,F=this.isTranscriptEmpty()?new y51({useGpt5:this.widget.dependencies.useGpt5}):new Wg1({key:U?new X7(`message-view-${U}`):void 0,items:q.items,activeTools:q.activeTools,subagentToolsByParentID:q.subagentToolsByParentID,controller:U?this.getMessageScrollController(U):new $V,autofocus:!1,onCopy:this._handleTextCopy.bind(this)}),H=Math.max(Math.floor(Q.size.height*0.4),10),B=this.getCurrentEphemeralError(),M=this.buildBottomWidget(B,G,Y,Z,q,z,H),V=Q.size.width<40,N=q.mainThread?Ul1(q.mainThread):void 0,L=new s71({threadViewState:q.viewState,threadTokenUsage:N,threadID:U??null,thread:q.mainThread??void 0,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}),A=new a71({bashInvocations:this.bashInvocations}),O=[];if(this.isFreeTierEnabled)O.push(new i6({decoration:new h2(Y.secondary),child:new E8({padding:F6.horizontal(1),child:new W0({text:new C1("Thank you for trying the ad-supported Amp Free experiment — AD",new g1({color:m1.black})),textAlign:"center"})})}));O.push(new g2({child:F}),A,new i6({constraints:new f6(0,Q.size.width,0,H),child:M}),new a0({height:1,child:new E8({padding:F6.horizontal(1),child:L})}));let j=new P6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:O}),R=new R5(()=>{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.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((b)=>{a.error("Failed to cancel streaming message:",b)}),"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"}),I=new R5(()=>{return this.onExitPressed(),"handled"}),w=new R5(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),E=new R5(()=>{return CG.instance.toggleAll(),"handled"}),$=new R5(()=>{return EG.instance.toggleFrameStatsOverlay(),"handled"}),P=new R5(()=>{return EG.instance.tuiInstance.getScreen().markForRefresh(),eQ.instance.requestFrame(),"handled"}),C=new R5(()=>{let x=this.findElementByKey("message-view-selection-area");if(x?.state){let b=x.state,m=b.controller?.copySelection();if(m&&m.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{b.controller.endCopyHighlight(),b.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),k=new R5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b){let m=this.getMessageScrollController(b),n=Math.max(Math.floor(Q.size.height*0.4),10),p=Q.size.height-n;m.animatePageUp(p,100)}return"handled"}),g=new R5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b){let m=this.getMessageScrollController(b),n=Math.max(Math.floor(Q.size.height*0.4),10),p=Q.size.height-n;m.animatePageDown(p,100)}return"handled"}),T=new R5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b)this.getMessageScrollController(b).animateTo(0,100);return"handled"}),v=new R5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b)this.getMessageScrollController(b).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),f=new Map([[m2.key("Escape"),new Nu],[m2.ctrl("c"),new cT],[m2.ctrl("l"),new ju],[m2.alt("c"),new Lu],[m2.alt("p"),new Ou],[m2.ctrl("r"),new Au],[m2.key("PageUp"),new T71],[m2.key("PageDown"),new C71],[m2.key("Home"),new S71],[m2.key("End"),new v71]]);if(process.platform==="darwin")f.set(m2.meta("c"),new cT);let h=new Map([[Nu,R],[w71,I],[ju,P],[Lu,w],[Au,E],[Ou,$],[cT,C],[T71,k],[C71,g],[S71,T],[v71,v]]),S=j;if(this.isShowingConsoleOverlay)S=new yK({children:[S,new Ng1]});if(this.isShowingHelp)S=new yK({children:[S,new Ag1]});if(this.isShowingFileChangesOverlay)S=new yK({children:[S,new Vf1]});if(this.isShowingConfirmationOverlay)S=new yK({children:[S,new Dg1({details:this.confirmationOverlayContent})]});if(this.isShowingIdePicker)return new vH({child:new fK({actions:h,child:new EV({shortcuts:f,debugLabel:"ide-picker-shortcuts",child:new jg1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode})})})});if(this.isShowingJetBrainsInstaller)return new vH({child:new fK({actions:h,child:new EV({shortcuts:f,debugLabel:"jetbrains-installer-shortcuts",child:new bg1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new vH({child:new fK({actions:h,child:new EV({shortcuts:f,debugLabel:"main-app-shortcuts",child:S})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new Lg1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new hg1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Vg1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new xg1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=jK9(X),U=new h71({key:this.textFieldKey,controller:this.textController,triggers:[ug1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(P)=>Hg1(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:EG.instance.tuiInstance.clipboard},optionViewBuilder:(P,C,k)=>{let g=k?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=Hg1(C);break}let x=XW6(C),b=new C1(h,new g1({color:T})),m=new C1(S,new g1({color:v})),n=[b,m];if(x){let p=new C1(" - ",new g1({color:f,dim:!0})),Q1=new C1(x,new g1({color:f,dim:!0}));n.push(p,Q1)}return new i6({decoration:new h2(g),child:new W0({text:new C1("",void 0,n),maxLines:1,overflow:"ellipsis"})})}}),W=Y.mainThread?.queuedMessages??[],F=new v9({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,B=this.imageAttachments.length>0?new i6({padding:F6.only({bottom:1,left:1}),child:new W0({text:new C1("",void 0,[new C1("Images: ",new g1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((P,C)=>[new C1(`[image ${C+1}]`,new g1({color:Z.success})),...C<this.imageAttachments.length-1?[new C1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(W)&&W.length>0,N=B?new P6({crossAxisAlignment:"start",children:[B,new g2({child:F})]}):F,L=V?new yg1({queuedMessages:W}):void 0,A=M?new Oy1(new Fg1({todos:K}),{clipBehavior:"antiAlias"}):void 0,O=[],j=Y.viewState;if(!this.isSummarizing(j))O.push({text:new C1("",void 0,[new C1("Enter",new g1({color:G.keybind})),new C1(" to send",new g1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)O.push({text:new C1(H==="hidden"?"shell mode (incognito)":"shell mode",new g1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:B?1:0});let R=this.currentAgentMode;if(R&&!["default",xj[0]].includes(R)&&!H){let P=RK9(R);O.push({text:new C1("",void 0,[new C1("agent-mode: ",new g1({color:Z.foreground,dim:!0})),new C1(R,new g1({color:P}))]),position:"top-left",offsetY:0})}let I=Y.mainThread?.metadata?.treeInfo?.uri,w;if(I)w=P0.isUri(I)?I.fsPath:I;else w=process.cwd();let E=this.toHomeRelative(w),$=this.shorten(E);return O.push({text:new C1($,new g1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new Gf1({leftChild:N,rightChild1:L,rightChild2:A,maxHeight:q,overlayTexts:O,borderColor:Z.border})}}});import{randomBytes as wK9}from"node:crypto";import{mkdir as IK9,readFile as RF6,writeFile as EK9}from"node:fs/promises";import $K9 from"node:os";import pg1 from"node:path";import{stderr as t2,stdout as u2}from"node:process";function PK9(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 nO(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aH("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new O2("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${J8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")aH("experimental.agentMode",Q.agentMode)}async function lg1(J){try{await IK9(pg1.dirname(dg1),{recursive:!0}),await EK9(dg1,J,"utf-8")}catch(Q){a.debug("Failed to save last thread ID",Q)}}async function SK9(){try{return(await RF6(dg1,"utf-8")).trim()}catch(J){return null}}async function vK9(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 CK9.parse(Q)}catch(Z){if(Z instanceof C0.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 kK9(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 yK9(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 O2(_K.unknownCommand(Z),1,q)}}function _g2(){return wF6}function QJ1(J){return{...J,getThreadEnvironment:$41,vfs:z00({os:J.fileSystem}),fileChangeTrackerStorage:new Qk(J.fileSystem),generateThreadTitle:_n,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}async function rO(J,Q){jl1("0.0.1759469839-g3e7045");let Z=XZ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Z0.of([P0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:ub1,homeDir:ig1,userConfigDir:IF6}),X=await U9();a.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=qi(vj()),K=u10({configService:Z,toolService:Y}),q=dA0(Y,O8,yt).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)Rl1(!0);if(Q.ide&&Lx1())wl1(!0);if(N86(Y),Q.jetbrains)Y.registerTool(Kr);else if(Q.ide)Y.registerTool(xq0);let z;if(!J.executeMode)z=new y41(process.cwd(),{},!0);else z=new class extends y41{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...
|
5988
5988
|
`),!await fK9(J))await NO(),process.exit(1)}let U=await I00({isDevelopment:!1}),W=new NW1(U),F=new DW1(U,{lazy:!0}),H=new UM1(W),B=Q.notifications!==void 0?Q.notifications:!J.executeMode,M=j86({playNotificationSound:async(L)=>{if(B){A86(L);let A=Dy1(),O=My1();if((!A||O)&&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:W});a.info("Starting Amp background services");let V=pK0({threadService:W,threadHistoryService:F,isExtensionDevelopment:!1}),N={configService:Z,toolService:Y,mcpService:K,threadService:W,threadHistoryService:F,threadSummaryService:H,threadSyncService:V,threadStorage:U,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:z,notificationService:M,fileSystem:Q.jetbrains||Q.ide?Y00:O8};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 fK9(J){if(!J.executeMode){if(!await Px1("Would you like to log in to Amp? [(y)es, (n)o]: "))return u2.write(`Login cancelled. Run the command again to retry.
|
5989
5989
|
`),!1}return await EF6(J)}async function EF6(J){let Q=wK9(32).toString("hex"),Z=await $x1(J.ampURL,Q);try{await vT(Z)}catch(Y){a.error("Failed to open browser",{error:Y})}let X=await $x1(J.ampURL,Q,!1);u2.write(`If your browser did not open automatically, visit:
|
5990
5990
|
|
@@ -5994,12 +5994,12 @@ ${J8.blue.bold(X)}
|
|
5994
5994
|
Login successful! You can now use the Amp CLI.
|
5995
5995
|
`),!0}catch(Y){return a.error("Login failed",{error:Y}),t2.write(`
|
5996
5996
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
5997
|
-
`),!1}}function hK9(){let J=new Ym().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)VT(),process.exit(0);let H=F.originalError??F;A56(H)}),J.option("-V, --version","output the version number",()=>{u2.write(`0.0.
|
5998
|
-
`),process.exit(0)}),J.addHelpText("after",pJ6()),J.configureHelp({formatHelp:dJ6}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await hK(B);await pK9(M)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await hK(B);await uK9(M,await Hx1(B,M.settings))});let Q=async(F,H,B)=>{XZ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:Z0.of([P0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:ig1,userConfigDir:IF6});let M={...H,executeMode:!1};await cg1(M,{...F,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await hK(B);await jF6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await hK(B);await rK9(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await hK(M);if(H.pick)await Q(M,V,B);else await nK9(M,V,F,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await hK(M);await aK9(M,V,F,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await hK(B);await jF6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await hK(M);await iK9(M,V,F,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await hK(M);await lK9(M,V,F,B)}),KZ6(J,async(F,H)=>{let B=await hK(H);nO(F,H);let M=await rO(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:VT,asyncDispose:M.asyncDispose.bind(M)}}),IQ6(J),HQ6(J,async(F)=>{return(await hK(F)).settings});let X=new Ym().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(F)=>{await Ox1(F.force||!1,F.verbose||!1,"0.0.
|
5997
|
+
`),!1}}function hK9(){let J=new Ym().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)VT(),process.exit(0);let H=F.originalError??F;A56(H)}),J.option("-V, --version","output the version number",()=>{u2.write(`0.0.1759469839-g3e7045 (released 2025-10-03T05:42:35.248Z)
|
5998
|
+
`),process.exit(0)}),J.addHelpText("after",pJ6()),J.configureHelp({formatHelp:dJ6}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await hK(B);await pK9(M)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await hK(B);await uK9(M,await Hx1(B,M.settings))});let Q=async(F,H,B)=>{XZ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:Z0.of([P0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:ig1,userConfigDir:IF6});let M={...H,executeMode:!1};await cg1(M,{...F,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await hK(B);await jF6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await hK(B);await rK9(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await hK(M);if(H.pick)await Q(M,V,B);else await nK9(M,V,F,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await hK(M);await aK9(M,V,F,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await hK(B);await jF6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await hK(M);await iK9(M,V,F,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await hK(M);await lK9(M,V,F,B)}),KZ6(J,async(F,H)=>{let B=await hK(H);nO(F,H);let M=await rO(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:VT,asyncDispose:M.asyncDispose.bind(M)}}),IQ6(J),HQ6(J,async(F)=>{return(await hK(F)).settings});let X=new Ym().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(F)=>{await Ox1(F.force||!1,F.verbose||!1,"0.0.1759469839-g3e7045"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,B){let V=typeof F.description==="string"?F.description:B===void 0?F.description(!0):F.description(B),N=new qO(H,V),L=xK9(F);if(L)N.default(L);if(N.hidden=_K9(F)||OF6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of AF6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new qO("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new qO("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new qO("--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 qO("--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 qO("--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(F,H)=>{let B=F,M=await hK(B);if(Object.keys(B).forEach((V)=>{let N=AF6.find((L)=>L.name===V);if(N&&OF6(N)&&!bK9(N))t2.write(J8.yellow(`Warning: '--${V}' flag is deprecated
|
5999
5999
|
`))}),H.args.length>0)yK9(M,H);await cg1(M,B,H)});let U=new Ym("doctor").summary("Generate support bundle").description("Generate a support bundle for troubleshooting issues. This collects logs, configuration, and system information into a file that can be shared with Amp support for debugging.").option("--output-dir <path>","Directory to save the support bundle",process.cwd()).option("--include-full-logs","Include full log history",!1).allowUnknownOption(!1).action(async(F)=>{await cK9(F.outputDir,F.includeFullLogs)});J.addCommand(U);let W=new Ym("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(F)=>{await dK9(F.version)});return J.addCommand(W),J}async function JJ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??nK(),K=QJ1(J);if(Z)await J.threadStorage.set(Y,Z);let q=await gJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,s41(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(q7(z,"assistant"))await lg1(Y),G.unsubscribe()});return await q.resume(),q}async function cg1(J,Q,Z){let X=process.stdin,Y=r41(Q);if(Y instanceof Error)zX(Y.message);let K,q=null;if(Q.streamJsonInput)K="";else if(typeof Q.execute==="string"){K=Q.execute;let j=(await Sx1()).trimEnd();if(j)q=j}else K=(await Sx1()).trimEnd();if(Q.remote&&!J.executeMode)throw new O2("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new O2("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new O2("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new O2("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new O2("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 O2("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 O2("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"
|
6000
6000
|
Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMode&&!J.streamJsonMode&&typeof Q.execute!=="string")X=await bQ6();nO(Z,Q);let G=await rO(J,Q);wF6=G;let z=QJ1(G),U=async(j)=>{let R=await RF6(j,"utf-8"),I=JSON.parse(R);if(!nU(I.id))throw new O2(_K.invalidThreadId);return JJ1(G,{visibility:Y,thread:I})},W=async(j)=>{if(!nU(j))throw new O2(_K.invalidThreadId);let R=await G.threadService.get(j)??void 0;return JJ1(G,{visibility:Y,thread:R})},F=async()=>{try{if(Q.threadId)return W(Q.threadId);else return JJ1(G,{visibility:Y})}catch(j){if(j instanceof O2)throw j;throw await P41(j,Q.threadId),Error("handleError should have called process.exit()")}},H=async()=>{return JJ1(G,{visibility:Y})};if(Q.format==="jsonl")t2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
6001
|
-
`),await NO(),process.exit(1);if(J.executeMode&&Q.remote)await $Q6(K,q),await G.asyncDispose(),process.exit(0);let B=await F();if(J.executeMode)await k56(B,B.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1;if(Q.jetbrains||Q.ide){await la1();let j=await oj({jetbrainsOnly:Q.jetbrains});if(j.length===0)if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall");else JJ.sendStatus({enabled:!0,connected:!1,authenticated:!1});else if(j.length===1){let R=j[0];if(R)JJ.selectConfig(R)}else M=!0}let N=Ix1("0.0.
|
6002
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=kU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(await SQ6(Y),await vQ6(Y),J.mcpConfig){let q=await vK9(J.mcpConfig);Y=kK9(Y,q)}let K=await Y.get("url","global");if(!K)K=XZ;if(!lH(K))a.info("Targeting custom Amp server",{ampURL:K});return Y=bd1(Y),{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:TQ6(await Hx1(J,Y))}}function gK9(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 mK9(){let J=gK9(process.argv);if(z56({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),PK9(a),a.info("Starting Amp CLI.",{version:"0.0.
|
6001
|
+
`),await NO(),process.exit(1);if(J.executeMode&&Q.remote)await $Q6(K,q),await G.asyncDispose(),process.exit(0);let B=await F();if(J.executeMode)await k56(B,B.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1;if(Q.jetbrains||Q.ide){await la1();let j=await oj({jetbrainsOnly:Q.jetbrains});if(j.length===0)if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall");else JJ.sendStatus({enabled:!0,connected:!1,authenticated:!1});else if(j.length===1){let R=j[0];if(R)JJ.selectConfig(R)}else M=!0}let N=Ix1("0.0.1759469839-g3e7045",G.settingsStorage),L=Z0.of([P0.file(process.cwd())]),A=MC(void 0,L);if(K)B.handle({type:"user:message",message:{content:[{type:"text",text:K}]}});let O=await U9();await NF6({stdin:X,stdout:process.stdout,history:new nb1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:B.threadID,worker:B,workerDeps:z,configService:G.configService,internalAPIClient:MZ,ampURL:J.ampURL,useGpt5:O.settings.gpt5??!1,startNewThread:H,pickAndContinueThread:async()=>{a.info("Thread picker requested - not yet implemented in TUI")},switchToThread:W,ideClient:JJ,commandRegistry:A,showJetBrainsInstaller:V,showIdePicker:M,startWithPicker:Q.startWithPicker,updateService:N,debugWidgetTree:Q.debugWidgetTree,jetbrainsMode:Q.jetbrains}),await G.asyncDispose(),process.exit(0)}async function hK(J){if(J.interactive)t2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
6002
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=kU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(await SQ6(Y),await vQ6(Y),J.mcpConfig){let q=await vK9(J.mcpConfig);Y=kK9(Y,q)}let K=await Y.get("url","global");if(!K)K=XZ;if(!lH(K))a.info("Targeting custom Amp server",{ampURL:K});return Y=bd1(Y),{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:TQ6(await Hx1(J,Y))}}function gK9(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 mK9(){let J=gK9(process.argv);if(z56({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),PK9(a),a.info("Starting Amp CLI.",{version:"0.0.1759469839-g3e7045",buildTimestamp:"2025-10-03T05:42:35.248Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new O2(_K.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await hK9().parseAsync(process.argv)}async function uK9(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}
|
6003
6003
|
`);else if(!lH(J.ampURL))u2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
6004
6004
|
`);let Z=process.env.AMP_API_KEY;if(Z)u2.write(`API key found in environment variable, storing...
|
6005
6005
|
`),await Q.set("apiKey",Z,J.ampURL),u2.write(`API key successfully stored.
|
@@ -6015,7 +6015,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMo
|
|
6015
6015
|
`));try{let Q;if(J)Q=J,t2.write(J8.blue(`Updating to version ${J}...
|
6016
6016
|
`)),await CT(J),t2.write(J8.green(`✓ Successfully updated to version ${J}
|
6017
6017
|
`));else{t2.write(J8.blue(`Checking for updates...
|
6018
|
-
`));let{hasUpdate:X,latestVersion:Y}=await uR("0.0.
|
6018
|
+
`));let{hasUpdate:X,latestVersion:Y}=await uR("0.0.1759469839-g3e7045");if(!X)t2.write(J8.green(`✓ Amp CLI is already up to date.
|
6019
6019
|
`)),process.exit(0);if(!Y)t2.write(J8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,t2.write(J8.blue(`Updating to version ${Y}...
|
6020
6020
|
`)),await CT(Y),t2.write(J8.green(`✓ Successfully updated to version ${Y}
|
6021
6021
|
`))}let Z=await wO(Q);if(Z.warning)t2.write(`
|
package/package.json
CHANGED