@sourcegraph/amp 0.0.1753445101-g610543 → 0.0.1753448050-g0871b6
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 +17 -17
- package/package.json +1 -1
package/dist/main.js
CHANGED
@@ -4472,7 +4472,7 @@ Please report this to https://github.com/markedjs/marked.`,A){let D="<p>An error
|
|
4472
4472
|
`,B=this.historyFile+".lock",D=10,J=50;for(let z=0;z<10;z++)try{let K=await Jr6(B,"wx");try{await hv1(this.historyFile,Q,{flag:"a",encoding:"utf-8"})}finally{await K.close(),await hv1(B,"",{flag:"w"});try{await o2A(B)}catch{}}return}catch(K){if(K.code==="EEXIST"&&z<9){await new Promise((Z)=>setTimeout(Z,50));continue}throw K}throw new 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 A=this.history[this.index];return typeof A==="string"?A: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 A=this.history[this.index];return typeof A==="string"?A:null}reset(){this.index=-1}}i6();i6();i6();i6();import{join as Xr6}from"node:path";class t2A{async watch(A){}unwatch(A){}dispose(){}onFileSystemEvent(A){}offFileSystemEvent(A){}getWatchedPaths(){return[]}isSupported(){return!1}}class e2A{watchedPaths=new Map;callbacks=[];pollInterval;constructor(A=1000){this.pollInterval=A}async watch(A){if(this.watchedPaths.has(A))return;let{promises:Q}=await import("node:fs"),B=new Map;try{await this.scanPath(Q,A,B)}catch(J){throw new Error(`Failed to watch path ${A}: ${J}`)}let D=setInterval(async()=>{try{await this.checkForChanges(Q,A,B)}catch(J){S1.warn("Error polling path",{path:A,error:J})}},this.pollInterval);this.watchedPaths.set(A,{interval:D,lastModified:B})}unwatch(A){let Q=this.watchedPaths.get(A);if(Q)clearInterval(Q.interval),this.watchedPaths.delete(A)}dispose(){for(let A of this.watchedPaths.keys())this.unwatch(A);this.callbacks.length=0}onFileSystemEvent(A){this.callbacks.push(A)}offFileSystemEvent(A){let Q=this.callbacks.indexOf(A);if(Q>=0)this.callbacks.splice(Q,1)}getWatchedPaths(){return Array.from(this.watchedPaths.keys())}isSupported(){return!0}async scanPath(A,Q,B){try{let D=await A.stat(Q);if(B.set(Q,D.mtime.getTime()),D.isDirectory()){let J=await A.readdir(Q);for(let z of J){let K=Xr6(Q,z);await this.scanPath(A,K,B)}}}catch(D){}}async checkForChanges(A,Q,B){let D=[],J=new Map;await this.scanPath(A,Q,J);for(let[z,K]of J.entries()){let Z=B.get(z);if(Z===void 0)D.push({type:"created",path:z,timestamp:Date.now(),isDirectory:await this.isDirectory(A,z)});else if(K>Z)D.push({type:"modified",path:z,timestamp:Date.now(),isDirectory:await this.isDirectory(A,z)})}for(let z of B.keys())if(!J.has(z))D.push({type:"deleted",path:z,timestamp:Date.now(),isDirectory:!1});B.clear();for(let[z,K]of J.entries())B.set(z,K);if(D.length>0)for(let z of this.callbacks)try{z(D)}catch(K){S1.error("Error in file watcher callback",{error:K})}}async isDirectory(A,Q){try{return(await A.stat(Q)).isDirectory()}catch{return!1}}}function P91(A){if(A?.usePolling)return new e2A(A.pollInterval);return new t2A}import{EventEmitter as Fr6}from"node:events";G9();i6();import{spawn as Yr6}from"node:child_process";import{promises as A8A}from"node:fs";import{join as Q8A,relative as B8A,resolve as Ur6}from"node:path";class eD{bits;constructor(A){this.bits=A}static empty(){return new eD(0n)}static fromString(A){let Q=0n;for(let B=0;B<A.length;B++){let D=A.charCodeAt(B),J=eD.charToBitIndex(D);if(J>=0)Q|=1n<<BigInt(J)}return new eD(Q)}static fromPath(A){let Q=0n,B=A.split(/[/\\]/);for(let D of B){if(D===""||D==="."||D==="..")continue;for(let J=0;J<D.length;J++){let z=D.charCodeAt(J),K=eD.charToBitIndex(z);if(K>=0)Q|=1n<<BigInt(K)}}return new eD(Q)}hasChars(A){return(this.bits&A.bits)===A.bits}union(A){return new eD(this.bits|A.bits)}intersection(A){return new eD(this.bits&A.bits)}isEmpty(){return this.bits===0n}getCharCount(){return this.bits.toString(2).split("").filter((A)=>A==="1").length}toString(){let A=[];for(let Q=0;Q<64;Q++)if((this.bits&1n<<BigInt(Q))!==0n){let B=eD.bitIndexToChar(Q);if(B)A.push(B)}return`CharBag{${A.join("")}}`}toJSON(){return{bits:this.bits.toString()}}static fromJSON(A){return new eD(BigInt(A.bits))}equals(A){return this.bits===A.bits}static charToBitIndex(A){if(A>=65&&A<=90)A+=32;if(A>=48&&A<=57)return A-48;if(A>=97&&A<=122)return A-97+10;return-1}static bitIndexToChar(A){if(A>=0&&A<=9)return String.fromCharCode(48+A);if(A>=10&&A<=35)return String.fromCharCode(97+A-10);return null}}class _p{id;kind;path;uri;charBag;metadata;isIgnored;isExternal;isPrivate;isAlwaysIncluded;constructor(A){this.id=A.id,this.kind=A.kind,this.path=A.path,this.uri=A.uri,this.metadata=A.metadata,this.isIgnored=A.isIgnored??!1,this.isExternal=A.isExternal??!1,this.isPrivate=A.isPrivate??!1,this.isAlwaysIncluded=A.isAlwaysIncluded??!1,this.charBag=eD.fromPath(this.path)}withUpdates(A){return new _p({id:this.id,kind:A.kind??this.kind,path:this.path,uri:this.uri,metadata:A.metadata??this.metadata,isIgnored:A.isIgnored??this.isIgnored,isExternal:A.isExternal??this.isExternal,isPrivate:A.isPrivate??this.isPrivate,isAlwaysIncluded:A.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 A=this.getFilename(),Q=A.lastIndexOf(".");return Q>0?A.slice(Q+1):""}getDirectory(){let A=this.path.split(/[/\\]/);return A.length>1?A.slice(0,-1).join("/"):""}shouldIncludeInResults(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;return!0}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(A,Q){return new _p({id:A.id,kind:A.kind,path:A.path,uri:Q(A.uri),metadata:A.metadata,isIgnored:A.isIgnored,isExternal:A.isExternal,isPrivate:A.isPrivate,isAlwaysIncluded:A.isAlwaysIncluded})}equals(A){return this.id===A.id&&this.kind===A.kind&&this.path===A.path&&this.metadata.mtime===A.metadata.mtime&&this.metadata.size===A.metadata.size}hashCode(){return`${this.path}:${this.metadata.mtime}:${this.metadata.size}`}toString(){return`Entry{${this.kind}:${this.path}}`}}class SZ{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(A,Q){let B=[...SZ.DEFAULT_PATTERNS,...SZ.customPatterns];for(let D of B){if(D.type==="directory"&&!Q)continue;if(D.type==="file"&&Q)continue;if(SZ.matchesPattern(A,D.pattern))return!0}return!1}static addCustomPattern(A){SZ.customPatterns.push(A)}static clearCustomPatterns(){SZ.customPatterns=[]}static getAllPatterns(){return[...SZ.DEFAULT_PATTERNS,...SZ.customPatterns]}static matchesPattern(A,Q){let D=A.replace(/\\/g,"/").split("/"),J=D[D.length-1];if(Q.includes("*"))return SZ.matchesGlob(J??"",Q);return D.some((z)=>z===Q)}static matchesGlob(A,Q){let B=Q.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${B}$`).test(A)}}class uv1{async scanDirectory(A,Q={respectIgnorePatterns:!0}){let B=Date.now(),D=Ur6(A),{respectIgnorePatterns:J=!0,maxDepth:z=20,maxFiles:K=1e5,onProgress:Z,signal:G,forceNodeJS:X=!1,strategy:Y="auto"}=Q,U="nodejs",F=[],E=!1,H=0;try{if(X||Y==="nodejs")U="nodejs";else{let M=await this.tryExternalTools(D,Y,G);if(M)F=M.entries,U=M.strategy,E=!0;else U="nodejs"}if(U==="nodejs"){let M=await this.scanWithNodeJS(D,{respectIgnorePatterns:J,maxDepth:z,maxFiles:K,onProgress:Z||(()=>{}),signal:G||new AbortController().signal});F=M.entries,H=M.skippedPaths}if(U!=="nodejs"){if(isFinite(K))F=F.slice(0,K);if(Z){let M=F.filter((O)=>O.kind==="file").length,N=F.filter((O)=>O.kind==="directory").length;Z({scannedFiles:M,scannedDirectories:N,currentPath:D})}}}catch(M){if(M instanceof Error&&(M.name==="AbortError"||M.message==="Scan aborted"))throw M;S1.warn("Directory scan completed with errors",{error:M})}let w=Date.now()-B,I=F.filter((M)=>M.kind==="file").length,W=F.filter((M)=>M.kind==="directory").length;return{entries:F,stats:{totalFiles:I,totalDirectories:W,scanDuration:w,skippedPaths:H,strategy:U,externalToolsAvailable:E}}}async tryExternalTools(A,Q,B){let D=[];if(Q==="auto")D.push("git","ripgrep");else if(Q==="git")D.push("git");else if(Q==="ripgrep")D.push("ripgrep");for(let J of D)try{S1.debug("Attempting to use external tool",{tool:J});let z=await this.runExternalTool(J,A,B);if(z.length>0)return{entries:z,strategy:J};else S1.debug("External tool returned no entries, trying next",{tool:J})}catch(z){S1.debug("External tool failed, trying next",{tool:J,error:z})}return S1.debug("All external tools failed, falling back to Node.js scanning"),null}async runExternalTool(A,Q,B){let D=A==="git"?"git":"rg",J=A==="git"?["ls-files","--cached","--others","--exclude-standard"]:["--files"];return S1.debug("Running external tool",{command:D,args:J,rootPath:Q}),new Promise((z,K)=>{let Z=Yr6(D,J,{cwd:Q,stdio:["ignore","pipe","pipe"]}),G="",X="";if(Z.stdout?.on("data",(Y)=>{G+=Y.toString()}),Z.stderr?.on("data",(Y)=>{X+=Y.toString()}),B)B.addEventListener("abort",()=>{Z.kill("SIGTERM"),K(new Error("Scan aborted"))},{once:!0});Z.on("close",(Y)=>{if(Y!==0){S1.debug("External tool failed",{command:D,code:Y,stderr:X}),K(new Error(`${D} exited with code ${Y}: ${X}`));return}try{let F=G.trim().split(`
|
4473
4473
|
`).filter((E)=>E.length>0).map((E)=>{return this.createEntryFromPath(Q8A(Q,E),{size:0,mtime:new Date,isDirectory:!1,isFile:!0,isSymlink:!1})});z(F)}catch(U){K(U)}}),Z.on("error",(Y)=>{K(Y)})})}async scanWithNodeJS(A,Q){if(Q.signal?.aborted)throw new Error("Scan aborted");let B=[],D={scannedFiles:0,scannedDirectories:0,skippedPaths:0};return await this.scanDirectoryRecursive(A,A,0,Q,B,D),{entries:B,skippedPaths:D.skippedPaths}}async scanDirectoryRecursive(A,Q,B,D,J,z){if(D.signal?.aborted)throw new Error("Scan aborted");if(B>D.maxDepth)return;if(J.length>=D.maxFiles)return;let K=B8A(Q,A);if(D.respectIgnorePatterns&&K){if(SZ.shouldIgnore(K,!0)){z.skippedPaths++;return}}let Z;try{Z=await A8A.readdir(A,{withFileTypes:!0})}catch(G){if(G instanceof Error){if("code"in G&&(G.code==="EACCES"||G.code==="EPERM")){z.skippedPaths++;return}if("code"in G&&G.code==="ENOENT")return}throw G}for(let G of Z){if(D.signal?.aborted)throw new Error("Scan aborted");if(J.length>=D.maxFiles)break;let X=Q8A(A,G.name),Y=B8A(Q,X);if(D.respectIgnorePatterns){if(SZ.shouldIgnore(Y,G.isDirectory())){z.skippedPaths++;continue}}try{let U=await A8A.stat(X),F=this.createEntryFromPath(X,{size:U.size,mtime:U.mtime,isDirectory:U.isDirectory(),isFile:U.isFile(),isSymlink:U.isSymbolicLink()});if(J.push(F),F.kind==="file")z.scannedFiles++;else z.scannedDirectories++;if(D.onProgress&&J.length%100===0)D.onProgress({scannedFiles:z.scannedFiles,scannedDirectories:z.scannedDirectories,currentPath:X});if(G.isDirectory())await this.scanDirectoryRecursive(X,Q,B+1,D,J,z)}catch(U){if(U instanceof Error){if("code"in U&&(U.code==="EACCES"||U.code==="EPERM"||U.code==="ENOENT")){z.skippedPaths++;continue}}S1.warn("Error processing file",{error:U}),z.skippedPaths++}}}createEntryFromPath(A,Q){let B;if(Q.isDirectory)B="directory";else B="file";let D={size:Q.size,mtime:Q.mtime.getTime(),isSymlink:Q.isSymlink},J=A,z=t6.file(A);return new _p({id:J,kind:B,path:A,uri:z,metadata:D})}}var qr6={minScore:400,caseSensitive:!1,penalizeLengthDifference:!0,maxResults:50,smartCase:!0},$Z={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 D8A{config;queryChars;queryLower;constructor(A,Q={}){this.config={...qr6,...Q};let B=A.replace(/^[@#]+/,"");if(this.queryChars=Array.from(B),this.queryLower=Array.from(B.toLowerCase()),this.config.smartCase)this.config.caseSensitive=B!==B.toLowerCase()}match(A){if(this.queryChars.length===0)return A.filter((B)=>B.shouldIncludeInResults()).sort((B,D)=>D.getImportanceBoost()-B.getImportanceBoost()).slice(0,this.config.maxResults).map((B)=>({entry:B,score:B.getImportanceBoost(),matchPositions:[],highlightedPath:B.path}));let Q=this.matchWithSemanticScoring(A);if(Q.length>0)return Q;return this.matchWithFuzzyScoring(A)}matchWithSemanticScoring(A){let Q=[],B=0,D=this.queryChars.join(""),J=this.queryChars[0],K=this.queryChars.length===1&&J!==void 0&&/[a-z]/i.test(J)?1e4:20000;for(let Z of A){if(!Z.shouldIncludeInResults())continue;if(D.length>5&&!this.passesCharBagFilter(D,Z))continue;let G=this.matchEntrySemantic(Z);if(G&&G.score>=this.config.minScore)Q.push(G);if(B++,Q.length>=this.config.maxResults*5||B>=K)break}return Q.sort((Z,G)=>{let X=G.score-Z.score;if(Math.abs(X)>0.001)return X;return Z.entry.path.length-G.entry.path.length}),Q.slice(0,this.config.maxResults)}matchWithFuzzyScoring(A){let Q=[],B=0,D=this.queryChars.join(""),J=this.queryChars[0],K=this.queryChars.length===1&&J!==void 0&&/[a-z]/i.test(J)?1e4:20000;for(let Z of A){if(!Z.shouldIncludeInResults())continue;if(D.length>5&&!this.passesCharBagFilter(D,Z))continue;let G=this.matchEntryFuzzy(Z);if(G)Q.push(G);if(B++,Q.length>=this.config.maxResults*5||B>=K)break}return Q.sort((Z,G)=>{let X=G.score-Z.score;if(Math.abs(X)>0.001)return X;return Z.entry.path.length-G.entry.path.length}),Q.slice(0,this.config.maxResults)}matchEntrySemantic(A){let Q=A.path,B=this.queryLower.join(""),D=this.calculateSemanticScore(B,A);if(D===0)return null;let J=this.applyTieBreakers(D,B,A),z=this.findMatchPositions(B,Q),K=this.createHighlightedPath(Q,z);return{entry:A,score:J,matchPositions:z,highlightedPath:K}}matchEntryFuzzy(A){let Q=A.path,B=this.queryLower.join(""),D=this.calculateFuzzyScore(B,A);if(D===0)return null;let J=this.applyTieBreakers(D,B,A),z=this.findMatchPositions(B,Q),K=this.createHighlightedPath(Q,z);return{entry:A,score:J,matchPositions:z,highlightedPath:K}}calculateSemanticScore(A,Q){let B=A.toLowerCase(),D=Q.path,J=D.toLowerCase(),z=this.getFilename(D),K=this.removeExtension(z).toLowerCase(),Z=J.split(/[/.]/).filter((X)=>X.length>0),G=this.simpleTokens(B);if(G.length>1){let X=this.matchTokensToSegments(G,Z);if(X)return X}if(G.length===1&&B.length>6){let X=this.progressiveSegmentMatch(B,Z);if(X)return X}if(K===B||z.toLowerCase()===B)return $Z.EXACT_FILENAME;if(K.startsWith(B))return $Z.PREFIX_FILENAME;if(K.endsWith(B))return $Z.SUFFIX_FILENAME;if(K.includes(B))return $Z.SUBSTRING_FILENAME;if(Z.includes(B))return $Z.SEGMENT_EXACT;if(Z.some((X)=>X.includes(B)))return $Z.SEGMENT_SUBSTRING;if(J.includes(B))return $Z.PATH_SUBSTRING;return 0}calculateFuzzyScore(A,Q){let B=A.toLowerCase(),D=Q.path.toLowerCase();if(this.fuzzyIn(B,D))return $Z.FUZZY;return 0}applyTieBreakers(A,Q,B){let D=A,J=Math.abs(B.path.length-Q.length);D-=0.01*J;let z=B.path.split("/").length-1;D-=0.1*z;let K=this.getFilename(B.path),Z=this.removeExtension(K).toLowerCase();if(/^(license|readme|copy(ing|left))$/i.test(Z)&&z===1)D-=200;if(B.metadata.mtime){let X=(Date.now()-B.metadata.mtime)/86400000;if(X<30){let Y=Math.max(0,1-X/30);D+=50*Y}}return D}simpleTokens(A){return A.replace(/([a-z])([A-Z0-9])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}progressiveSegmentMatch(A,Q){let B=0,D=0,J=0;for(let K of Q){if(B>=A.length)break;let Z="",G="none";if(B+K.length<=A.length){if(A.slice(B,B+K.length)===K)Z=K,G="exact"}if(!Z&&K.length>=3){if(A.slice(B).startsWith(K))Z=K,G="prefix"}if(!Z&&K.length>=3){let X=A.slice(B);if(X.includes(K)&&X.indexOf(K)===0)Z=K,G="substring"}if(!Z){let X=A.slice(B);if(X.length>=3&&K.includes(X))Z=X,G="substring"}if(Z){if(B+=Z.length,D++,G==="exact")J++}}if(B/A.length>=0.8&&D>=2)return J>=2?$Z.SEGMENT_ORDERED_EXACT:$Z.SEGMENT_ORDERED_PARTIAL;return 0}matchTokensToSegments(A,Q){let B=this.findTokenMatches(A,Q),D=this.getWorstMatchType(B);return this.scoreFromMatchType(D)}findTokenMatches(A,Q){let B=0,D=[];for(let J of A){let z=!1;for(let K=B;K<Q.length;K++){let Z=Q[K];if(!Z)continue;if(J===Z){D.push("exact"),B=K+1,z=!0;break}else if(Z.startsWith(J)||J.startsWith(Z)||Z.endsWith(J)||Z.includes(J)||J.includes(Z)){D.push("partial"),B=K+1,z=!0;break}}if(!z)return[]}return D}getWorstMatchType(A){if(A.length===0)return"none";if(A.includes("partial"))return"partial";return"exact"}scoreFromMatchType(A){switch(A){case"exact":return $Z.SEGMENT_ORDERED_EXACT;case"partial":return $Z.SEGMENT_ORDERED_PARTIAL;default:return 0}}fuzzyIn(A,Q){let B=0;for(let D=0;D<Q.length&&B<A.length;D++)if(Q[D]===A[B])B++;return B===A.length}getFilename(A){return A.split("/").pop()||A}removeExtension(A){let Q=A.lastIndexOf(".");return Q>0?A.substring(0,Q):A}findMatchPositions(A,Q){let B=[],D=Q.toLowerCase(),J=A.toLowerCase();if(D.includes(J)){let K=D.indexOf(J);for(let Z=0;Z<J.length;Z++)B.push(K+Z);return B}let z=0;for(let K of J){let Z=D.indexOf(K,z);if(Z!==-1)B.push(Z),z=Z+1}return B}passesCharBagFilter(A,Q){if(A.includes("/")){let B=A.split("/");for(let D of B){if(D.trim()==="")continue;let J=eD.fromString(D);if(!Q.charBag.hasChars(J))return!1}return!0}else{let B=eD.fromString(A);return Q.charBag.hasChars(B)}}createHighlightedPath(A,Q){if(Q.length===0)return A;let B="",D=0;for(let J of Q){if(J>=A.length)continue;B+=A.slice(D,J),B+=`**${A[J]}**`,D=J+1}return B+=A.slice(D),B}}function J8A(A,Q,B){return new D8A(A,B).match(Q)}class HV{metadata;entries;entriesByPath;entriesById;constructor(A,Q=[],B,D){if(this.metadata=A,this.entries=Q,B&&D)this.entriesByPath=B,this.entriesById=D;else{let J=new Map,z=new Map;for(let K of Q)J.set(K.path,K),z.set(K.id,K);this.entriesByPath=J,this.entriesById=z}}static create(A){let Q=Date.now();return new HV({id:Q,createdAt:Q,rootPath:A,entryCount:0,scanStatus:"scanning"},[])}static fromEntries(A,Q){let B=Date.now(),D={id:B,createdAt:B,rootPath:A,entryCount:Q.length,scanStatus:"complete"};return new HV(D,Q)}getAllEntries(){return Array.from(this.entries)}getEntryByPath(A){return this.entriesByPath.get(A)??null}getEntryById(A){return this.entriesById.get(A)??null}withAdded(A){if(A.length===0)return this;let Q=new Map(this.entriesByPath),B=new Map(this.entriesById),D=Array.from(this.entries);for(let z of A){let K=Q.get(z.path);if(K){let Z=D.findIndex((G)=>G.path===z.path);if(Z>=0)D.splice(Z,1);Q.delete(z.path),B.delete(K.id)}}for(let z of A)D.push(z),Q.set(z.path,z),B.set(z.id,z);let J={...this.metadata,entryCount:D.length};return new HV(J,D,Q,B)}withRemoved(A){if(A.length===0)return this;let Q=new Set(A),B=this.entries.filter((J)=>!Q.has(J.path));if(B.length===this.entries.length)return this;let D={...this.metadata,entryCount:B.length};return new HV(D,B)}withUpdated(A){return this.withRemoved([A.path]).withAdded([A])}findEntries(A){return this.entries.filter(A)}getFiles(){return this.findEntries((A)=>A.kind==="file")}getDirectories(){return this.findEntries((A)=>A.kind==="directory")}getInDirectory(A){let Q=A.endsWith("/")?A:A+"/";return this.findEntries((B)=>B.path.startsWith(Q)&&B.path!==A)}hasPath(A){return this.entriesByPath.has(A)}getStats(){let A=this.metadata.entryCount||this.entries.length,Q=this.getFiles().length,B=A-Q,D=A*250;return{totalEntries:A,fileEntries:Q,directoryEntries:B,memoryUsage:D}}}class pv1 extends Fr6{rootPath;currentSnapshot=null;fileWatcher;scanner;isScanning=!1;stats;constructor(A,Q){super();this.rootPath=A;this.fileWatcher=Q??P91(),this.scanner=new uv1,this.stats={totalFiles:0,totalDirectories:0,lastScanDuration:0,lastScanTime:0,memoryUsage:0,status:"idle"},this.fileWatcher.onFileSystemEvent(this.handleFileSystemEvents.bind(this))}async initialize(A){if(this.isScanning)throw new Error("Index is already being initialized");try{await this.performFullScan(A),await this.fileWatcher.watch(this.rootPath)}catch(Q){throw this.updateStatus("error"),Q}}async rescan(A){await this.performFullScan(A)}getCurrentSnapshot(){return this.currentSnapshot}getStats(){return{...this.stats}}search(A,Q={}){if(!this.currentSnapshot)return[];let{limit:B=50,minScore:D=0.1,includeDirectories:J=!1,includeIgnored:z=!1}=Q,K=this.currentSnapshot.getAllEntries();if(!J)K=K.filter((X)=>X.kind==="file");if(!z)K=K.filter((X)=>!X.isIgnored);let Z=J8A(A,K,{minScore:D});return Z.sort((X,Y)=>Y.score-X.score),Z.slice(0,B)}dispose(){this.fileWatcher.dispose(),this.removeAllListeners()}async performFullScan(A){this.isScanning=!0,this.updateStatus("scanning");let Q=Date.now();try{let B=await this.scanner.scanDirectory(this.rootPath,{respectIgnorePatterns:!0,...A});this.currentSnapshot=HV.fromEntries(this.rootPath,B.entries);let D=Date.now()-Q;this.stats={...this.stats,totalFiles:B.stats.totalFiles,totalDirectories:B.stats.totalDirectories,lastScanDuration:D,lastScanTime:Q,memoryUsage:this.currentSnapshot.getStats().memoryUsage,status:"idle"},this.emit("scan-complete",{entries:B.entries.length,duration:D}),this.emit("status-changed",this.getStats())}catch(B){throw this.updateStatus("error"),this.emit("scan-error",B),B}finally{this.isScanning=!1}}async handleFileSystemEvents(A){if(!this.currentSnapshot||this.isScanning)return;this.updateStatus("updating");try{let Q=this.currentSnapshot,B=0,D=0,J=0,z=[],K=[],Z=[];for(let G of A){let X=G.path;switch(G.type){case"deleted":z.push(X);break;case"created":K.push(X);break;case"modified":Z.push(X);break;case"renamed":if(G.oldPath)z.push(G.oldPath);K.push(X);break}}if(z.length>0)Q=Q.withRemoved(z),D=z.length;if(K.length>0){let G=[];for(let X of K)try{let Y=await this.scanner.scanDirectory(X,{respectIgnorePatterns:!0,maxDepth:1});G.push(...Y.entries)}catch(Y){}if(G.length>0)Q=Q.withAdded(G),B=G.length}for(let G of Z){let X=Q.getEntryByPath(G);if(X){let Y=X.withUpdates({metadata:{...X.metadata,mtime:Date.now()}});Q=Q.withUpdated(Y),J++}}this.currentSnapshot=Q,this.stats={...this.stats,memoryUsage:this.currentSnapshot.getStats().memoryUsage,status:"idle"},this.emit("files-updated",{added:B,removed:D,modified:J}),this.emit("status-changed",this.getStats())}catch(Q){this.updateStatus("error"),this.emit("scan-error",Q)}}updateStatus(A){this.stats={...this.stats,status:A},this.emit("status-changed",this.getStats())}}class _91{indexes=new Map;config;disposed=!1;static forWorkspace(A){return new _91({workspaceRoots:[A],scanOnStartup:!0,maxIndexedFiles:1e5,enableFileWatching:!0,usePollingFallback:!1})}constructor(A){this.config={...A}}async initialize(){if(this.disposed)throw new Error("Service has been disposed");if(this.config.scanOnStartup){let A=this.config.workspaceRoots.map((Q)=>this.indexWorkspace(Q));await Promise.allSettled(A)}}async indexWorkspace(A){if(this.disposed)throw new Error("Service has been disposed");if(this.indexes.has(A)){await this.indexes.get(A).rescan();return}let Q=this.config.enableFileWatching?P91({usePolling:this.config.usePollingFallback}):void 0,B=new pv1(A,Q);B.on("scan-error",(J)=>{S1.error("Scan error in workspace",{rootPath:A,error:J})});let D={respectIgnorePatterns:!0,maxFiles:this.config.maxIndexedFiles};try{await B.initialize(D),this.indexes.set(A,B)}catch(J){throw B.dispose(),J}}async removeWorkspace(A){let Q=this.indexes.get(A);if(Q)Q.dispose(),this.indexes.delete(A)}searchAll(A,Q){let B=[];for(let D of this.indexes.values())try{let J=D.search(A,Q);B.push(...J)}catch(J){}return B.sort((D,J)=>J.score-D.score),Q?.limit?B.slice(0,Q.limit):B}searchWorkspace(A,Q,B){let D=this.indexes.get(A);if(!D)return[];try{return D.search(Q,B)}catch(J){return S1.error(`Search error in workspace ${A}:`,J),[]}}getIndexStats(A){if(A){let B=this.indexes.get(A);if(B)return[{...B.getStats(),rootPath:A}];return[]}let Q=[];for(let[B,D]of this.indexes.entries())Q.push({...D.getStats(),rootPath:B});return Q}getConfig(){return{...this.config}}updateConfig(A){this.config={...this.config,...A}}async rescanAll(){let A=[];for(let[Q,B]of this.indexes.entries())A.push(B.rescan().catch((D)=>{S1.error(`Rescan error in workspace ${Q}:`,D)}));await Promise.allSettled(A)}getIndexedWorkspaces(){return Array.from(this.indexes.keys())}isWorkspaceIndexed(A){return this.indexes.has(A)}dispose(){if(this.disposed)return;for(let[,A]of this.indexes.entries())A.dispose();this.indexes.clear(),this.disposed=!0}isDisposed(){return this.disposed}}function cv1(A,Q){let B={workspaceRoots:A,scanOnStartup:!0,maxIndexedFiles:1e5,enableFileWatching:!0,usePollingFallback:!1,...Q};return new _91(B)}Df();p6();import{spawn as Z8A}from"node:child_process";import lv1 from"node:fs";import av1 from"node:os";import kE from"node:path";class dv1{cache=new Map;maxSize;constructor(A=100){this.maxSize=A}get(A){let Q=this.cache.get(A);if(Q!==void 0)this.cache.delete(A),this.cache.set(A,Q);return Q}set(A,Q){if(this.cache.has(A))this.cache.delete(A);else if(this.cache.size>=this.maxSize){let B=this.cache.keys().next().value;if(B!==void 0)this.cache.delete(B)}this.cache.set(A,Q)}has(A){return this.cache.has(A)}clear(){this.cache.clear()}get size(){return this.cache.size}}var iv1=500000,z8A=60000,G8A=["!node_modules/","!target/","!build/","!dist/","!out/","!\\.next/","!coverage/","!venv/","!\\.venv/","!vendor/","!deps/","!\\_build/","!\\.elixir_ls/","!\\.elixir-tools/","!\\.git/"],Er6=G8A.map((A)=>A.substring(1).replace(/\\/g,""));function K8A(A){let Q=A.replace(/\\/g,"/");return Er6.some((B)=>{let D=B.endsWith("/")?B.slice(0,-1):B;return Q.startsWith(B)||Q.includes("/"+B)||Q.startsWith(D+"/")||Q.includes("/"+D+"/")})}class X8A{process=null;messageId=0;pendingRequests=new Map;queryCache=new dv1(50);messageSubject=new z7(null);subscription=this.messageSubject.pipe(WD(250),Fz((A)=>A!==null),p9((A)=>{return this.sendMessageObservable(A)})).subscribe((A)=>{this.sendMessageDirect(A)});constructor(){}sendMessageObservable(A){return UA.of(A)}sendMessageDirect(A){if(S1.debug("Sending message directly",{pendingMessage:A}),!this.process?.stdin){A.reject(new Error("Fuzzy server not started"));return}this.pendingRequests.set(A.id,{resolve:A.resolve,reject:A.reject}),this.process.stdin.write(JSON.stringify({...A.message,id:A.id})+`
|
4474
4474
|
`)}async start(){let A=!!process.versions.bun,Q,B;if(S1.info("Starting fuzzy server",{isCompiledBinary:A,argv:process.argv}),A)Q=process.execPath,B=["fuzzy-server"];else if(process.argv[1])Q="node",B=[process.argv[1],"fuzzy-server"];else throw S1.error("Failed to determine command and args for fuzzy server",{argv:process.argv}),new Error("Failed to determine command and args for fuzzy server");if(this.process=Z8A(Q,B,{stdio:["pipe","pipe","inherit"]}),!this.process.stdout)throw new Error("Failed to create fuzzy server process");let D="";this.process.stdout.on("data",(J)=>{D+=J.toString();let z=D.split(`
|
4475
|
-
`);D=z.pop()||"";for(let K of z)if(K.trim())try{let Z=JSON.parse(K),G=this.pendingRequests.get(Z.id);if(G)this.pendingRequests.delete(Z.id),G.resolve(Z)}catch(Z){S1.error("Failed to parse fuzzy server response",Z)}}),this.process.on("error",(J)=>{S1.error("Fuzzy server process error",J)}),this.process.on("exit",(J)=>{S1.debug("Fuzzy server process exited",{code:J})})}async sendMessage(A){let Q=++this.messageId;return new Promise((B,D)=>{this.messageSubject.next({message:A,id:Q,resolve:B,reject:D})})}async addFiles(A){await this.sendMessage({type:"index:add",files:A}),this.queryCache.clear()}async removeFiles(A){await this.sendMessage({type:"index:remove",files:A}),this.queryCache.clear()}async query(A){S1.debug("Processing completion for pattern",{pattern:A});let Q=this.queryCache.get(A);if(Q)return Q;let D=(await this.sendMessage({type:"query",text:A})).results;return this.queryCache.set(A,D),D}dispose(){if(this.subscription.unsubscribe(),this.messageSubject.complete(),this.process)this.process.kill(),this.process=null}}class Y8A{rootPath;fuzzyService=null;isInitialized=!1;isInitializing=!1;constructor(A=process.cwd()){this.rootPath=A}async start(){if(this.isInitialized||this.isInitializing)return;let A=av1.homedir();if(kE.resolve(this.rootPath)===kE.resolve(A)){S1.debug("Skipping fuzzy service initialization for home directory");return}this.isInitializing=!0;try{S1.info("Initializing fuzzy service",{rootPath:this.rootPath}),this.fuzzyService=cv1([this.rootPath],{scanOnStartup:!0,maxIndexedFiles:1/0,enableFileWatching:!1,usePollingFallback:!1}),await this.fuzzyService.initialize();let B=this.fuzzyService.getIndexStats().reduce((D,J)=>D+J.totalFiles,0);S1.info(`Fuzzy service initialized with ${B} files`),this.isInitialized=!0}catch(Q){throw S1.error("Failed to initialize fuzzy service",Q),Q}finally{this.isInitializing=!1}}async query(A,Q=50){if(!this.fuzzyService)return S1.warn("Fuzzy service not initialized, returning empty results"),[];try{if(!A.trim())return this.fuzzyService.searchAll("",{limit:Q}).map((J)=>J.entry.path);return this.fuzzyService.searchAll(A,{limit:Q,minScore:0.1}).map((D)=>D.entry.path)}catch(B){return S1.error("Fuzzy search failed",B),[]}}getStats(){return{isInitialized:this.isInitialized,isInitializing:this.isInitializing,stats:this.fuzzyService?.getIndexStats()||[]}}dispose(){if(this.fuzzyService)this.fuzzyService.dispose(),this.fuzzyService=null;this.isInitialized=!1}}function U8A(A,Q){if(A?.["experimental.fuzzySearch.enabled"]??!1)return new Y8A(Q);else return new X8A}async function q8A(A,Q){if(!("addFiles"in A)||typeof A.addFiles!=="function")return;let B=av1.homedir();if(kE.resolve(Q)===kE.resolve(B)){S1.debug("Skipping indexing for home directory");return}let D=await cM(),J=new Promise((z,K)=>{let Z=["--files","--color","never","--no-require-git","--hidden",...G8A.flatMap((U)=>["--glob",U])],G=Z8A(D,Z,{cwd:Q,stdio:["ignore","pipe","inherit"]}),X="",Y=[];G.stdout.on("data",(U)=>{X+=U.toString();let F=X.split(`
|
4475
|
+
`);D=z.pop()||"";for(let K of z)if(K.trim())try{let Z=JSON.parse(K),G=this.pendingRequests.get(Z.id);if(G)this.pendingRequests.delete(Z.id),G.resolve(Z)}catch(Z){S1.error("Failed to parse fuzzy server response",Z)}}),this.process.on("error",(J)=>{S1.error("Fuzzy server process error",J)}),this.process.on("exit",(J)=>{S1.debug("Fuzzy server process exited",{code:J})})}async sendMessage(A){let Q=++this.messageId;return new Promise((B,D)=>{this.messageSubject.next({message:A,id:Q,resolve:B,reject:D})})}async addFiles(A){await this.sendMessage({type:"index:add",files:A}),this.queryCache.clear()}async removeFiles(A){await this.sendMessage({type:"index:remove",files:A}),this.queryCache.clear()}async query(A){S1.debug("Processing completion for pattern",{pattern:A});let Q=this.queryCache.get(A);if(Q)return Q;let D=(await this.sendMessage({type:"query",text:A})).results;return this.queryCache.set(A,D),D}dispose(){if(this.subscription.unsubscribe(),this.messageSubject.complete(),this.process){let A=this.process,Q=setTimeout(()=>{S1.warn("Fuzzy server process did not exit gracefully, killing forcefully"),A.kill("SIGKILL")},5000);A.once("exit",()=>{clearTimeout(Q)}),A.kill("SIGTERM"),this.process=null}}}class Y8A{rootPath;fuzzyService=null;isInitialized=!1;isInitializing=!1;constructor(A=process.cwd()){this.rootPath=A}async start(){if(this.isInitialized||this.isInitializing)return;let A=av1.homedir();if(kE.resolve(this.rootPath)===kE.resolve(A)){S1.debug("Skipping fuzzy service initialization for home directory");return}this.isInitializing=!0;try{S1.info("Initializing fuzzy service",{rootPath:this.rootPath}),this.fuzzyService=cv1([this.rootPath],{scanOnStartup:!0,maxIndexedFiles:1/0,enableFileWatching:!1,usePollingFallback:!1}),await this.fuzzyService.initialize();let B=this.fuzzyService.getIndexStats().reduce((D,J)=>D+J.totalFiles,0);S1.info(`Fuzzy service initialized with ${B} files`),this.isInitialized=!0}catch(Q){throw S1.error("Failed to initialize fuzzy service",Q),Q}finally{this.isInitializing=!1}}async query(A,Q=50){if(!this.fuzzyService)return S1.warn("Fuzzy service not initialized, returning empty results"),[];try{if(!A.trim())return this.fuzzyService.searchAll("",{limit:Q}).map((J)=>J.entry.path);return this.fuzzyService.searchAll(A,{limit:Q,minScore:0.1}).map((D)=>D.entry.path)}catch(B){return S1.error("Fuzzy search failed",B),[]}}getStats(){return{isInitialized:this.isInitialized,isInitializing:this.isInitializing,stats:this.fuzzyService?.getIndexStats()||[]}}dispose(){if(this.fuzzyService)this.fuzzyService.dispose(),this.fuzzyService=null;this.isInitialized=!1}}function U8A(A,Q){if(A?.["experimental.fuzzySearch.enabled"]??!1)return new Y8A(Q);else return new X8A}async function q8A(A,Q){if(!("addFiles"in A)||typeof A.addFiles!=="function")return;let B=av1.homedir();if(kE.resolve(Q)===kE.resolve(B)){S1.debug("Skipping indexing for home directory");return}let D=await cM(),J=new Promise((z,K)=>{let Z=["--files","--color","never","--no-require-git","--hidden",...G8A.flatMap((U)=>["--glob",U])],G=Z8A(D,Z,{cwd:Q,stdio:["ignore","pipe","inherit"]}),X="",Y=[];G.stdout.on("data",(U)=>{X+=U.toString();let F=X.split(`
|
4476
4476
|
`);X=F.pop()||"";for(let E of F)if(E.trim()&&Y.length<iv1)Y.push(E.trim());if(Y.length>=iv1)G.kill("SIGTERM"),S1.debug(`File indexing stopped at ${iv1} files limit`)}),G.on("error",(U)=>{S1.error("Ripgrep process error",U),K(U)}),G.on("exit",async(U)=>{if(U===null){S1.warn("Ripgrep process was terminated during file indexing");try{if(Y.length>0)await A.addFiles(Y),S1.debug(`Indexed ${Y.length} files before termination`);z()}catch(F){K(F)}return}if(U===0||U===1)try{await A.addFiles(Y),S1.debug(`Indexed ${Y.length} files`),z()}catch(F){K(F)}else K(new Error(`Ripgrep exited with code ${U}`))})});return Promise.race([J,new Promise((z,K)=>setTimeout(()=>K(new Error(`File indexing timed out after ${z8A/1000} seconds`)),z8A))])}function F8A(A,Q){if(!("addFiles"in A)||typeof A.addFiles!=="function")return{[Symbol.dispose]:()=>{}};let B=av1.homedir();if(kE.resolve(Q)===kE.resolve(B))return S1.debug("Skipping file watching for home directory"),{[Symbol.dispose]:()=>{}};let D=[],J=new Set,z=null,K=async()=>{if(J.size===0)return;let X=Array.from(J);J.clear();let Y=[],U=[];for(let F of X){let E=kE.join(Q,F);try{let H=await lv1.promises.lstat(E);if(H.isFile()||H.isSymbolicLink()&&!K8A(F))if(H.isSymbolicLink())try{await lv1.promises.stat(E),Y.push(F)}catch(w){S1.debug("Skipping broken symlink",{file:F,error:w})}else Y.push(F)}catch(H){if(H.code==="ENOENT")S1.debug("File not found during indexing",{file:F});else S1.debug("Error accessing file during indexing",{file:F,error:H});U.push(F)}}try{if(Y.length>0)await A.addFiles(Y),S1.debug(`Added ${Y.length} files to index`);if(U.length>0)await A.removeFiles(U),S1.debug(`Removed ${U.length} files from index`)}catch(F){S1.error("Failed to update fuzzy server index",F)}},Z=()=>{if(z)clearTimeout(z);z=setTimeout(K,100)};return((X)=>{try{let Y=lv1.watch(X,{recursive:!0},(U,F)=>{if(!F)return;if(F.includes(".git/")||F===".git")return;if(S1.debug("File system event",{eventType:U,filename:F,dirPath:X}),U!=="rename"){S1.debug("Ignoring change event",{eventType:U,filename:F});return}if(F.includes("/.")||F.startsWith("."))return;let E=kE.relative(Q,kE.join(X,F));if(E.startsWith(".."))return;if(K8A(E)){S1.debug("Skipping excluded path",{relativePath:E});return}J.add(E),Z()});D.push(Y),Y.on("error",(U)=>{S1.error(`File watcher error for ${X}`,U)})}catch(Y){S1.error(`Failed to watch directory ${X}`,Y)}})(Q),{[Symbol.dispose]:()=>{if(z)clearTimeout(z);for(let X of D)X.close();D.length=0}}}class rv1{client=null;initPromise;settings;rootPath;constructor(A,Q){this.settings=A,this.rootPath=Q,this.initPromise=this.doInitialization()}async start(){}async doInitialization(){try{this.client=U8A(this.settings,this.rootPath),await this.client.start();try{await q8A(this.client,this.rootPath)}catch(A){S1.error("Failed to index files for fuzzy completion",A)}}catch(A){throw S1.error("Failed to initialize fuzzy service in background",A),A}}async query(A,Q){return await this.initPromise,this.client.query(A,Q)}dispose(){this.client?.dispose(),this.client=null}}function fE(A){return!Array.isArray?C8A(A)==="[object Array]":Array.isArray(A)}var Hr6=1/0;function wr6(A){if(typeof A=="string")return A;let Q=A+"";return Q=="0"&&1/A==-Hr6?"-0":Q}function Ir6(A){return A==null?"":wr6(A)}function bU(A){return typeof A==="string"}function M8A(A){return typeof A==="number"}function Wr6(A){return A===!0||A===!1||Mr6(A)&&C8A(A)=="[object Boolean]"}function N8A(A){return typeof A==="object"}function Mr6(A){return N8A(A)&&A!==null}function AK(A){return A!==void 0&&A!==null}function nv1(A){return!A.trim().length}function C8A(A){return A==null?A===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(A)}var Nr6="Incorrect 'index' type",Cr6=(A)=>`Invalid value for key ${A}`,Or6=(A)=>`Pattern length exceeds max of ${A}.`,Vr6=(A)=>`Missing ${A} property in key`,Rr6=(A)=>`Property 'weight' in key '${A}' must be a positive integer`,E8A=Object.prototype.hasOwnProperty;class O8A{constructor(A){this._keys=[],this._keyMap={};let Q=0;A.forEach((B)=>{let D=V8A(B);this._keys.push(D),this._keyMap[D.id]=D,Q+=D.weight}),this._keys.forEach((B)=>{B.weight/=Q})}get(A){return this._keyMap[A]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function V8A(A){let Q=null,B=null,D=null,J=1,z=null;if(bU(A)||fE(A))D=A,Q=H8A(A),B=sv1(A);else{if(!E8A.call(A,"name"))throw new Error(Vr6("name"));let K=A.name;if(D=K,E8A.call(A,"weight")){if(J=A.weight,J<=0)throw new Error(Rr6(K))}Q=H8A(K),B=sv1(K),z=A.getFn}return{path:Q,id:B,weight:J,src:D,getFn:z}}function H8A(A){return fE(A)?A:A.split(".")}function sv1(A){return fE(A)?A.join("."):A}function Lr6(A,Q){let B=[],D=!1,J=(z,K,Z)=>{if(!AK(z))return;if(!K[Z])B.push(z);else{let G=K[Z],X=z[G];if(!AK(X))return;if(Z===K.length-1&&(bU(X)||M8A(X)||Wr6(X)))B.push(Ir6(X));else if(fE(X)){D=!0;for(let Y=0,U=X.length;Y<U;Y+=1)J(X[Y],K,Z+1)}else if(K.length)J(X,K,Z+1)}};return J(A,bU(Q)?Q.split("."):Q,0),D?B:B[0]}var Tr6={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},jr6={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(A,Q)=>A.score===Q.score?A.idx<Q.idx?-1:1:A.score<Q.score?-1:1},Pr6={location:0,threshold:0.6,distance:100},_r6={useExtendedSearch:!1,getFn:Lr6,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},c2={...jr6,...Tr6,...Pr6,..._r6},Sr6=/[^ ]+/g;function $r6(A=1,Q=3){let B=new Map,D=Math.pow(10,Q);return{get(J){let z=J.match(Sr6).length;if(B.has(z))return B.get(z);let K=1/Math.pow(z,0.5*A),Z=parseFloat(Math.round(K*D)/D);return B.set(z,Z),Z},clear(){B.clear()}}}class k91{constructor({getFn:A=c2.getFn,fieldNormWeight:Q=c2.fieldNormWeight}={}){this.norm=$r6(Q,3),this.getFn=A,this.isCreated=!1,this.setIndexRecords()}setSources(A=[]){this.docs=A}setIndexRecords(A=[]){this.records=A}setKeys(A=[]){this.keys=A,this._keysMap={},A.forEach((Q,B)=>{this._keysMap[Q.id]=B})}create(){if(this.isCreated||!this.docs.length)return;if(this.isCreated=!0,bU(this.docs[0]))this.docs.forEach((A,Q)=>{this._addString(A,Q)});else this.docs.forEach((A,Q)=>{this._addObject(A,Q)});this.norm.clear()}add(A){let Q=this.size();if(bU(A))this._addString(A,Q);else this._addObject(A,Q)}removeAt(A){this.records.splice(A,1);for(let Q=A,B=this.size();Q<B;Q+=1)this.records[Q].i-=1}getValueForItemAtKeyId(A,Q){return A[this._keysMap[Q]]}size(){return this.records.length}_addString(A,Q){if(!AK(A)||nv1(A))return;let B={v:A,i:Q,n:this.norm.get(A)};this.records.push(B)}_addObject(A,Q){let B={i:Q,$:{}};this.keys.forEach((D,J)=>{let z=D.getFn?D.getFn(A):this.getFn(A,D.path);if(!AK(z))return;if(fE(z)){let K=[],Z=[{nestedArrIndex:-1,value:z}];while(Z.length){let{nestedArrIndex:G,value:X}=Z.pop();if(!AK(X))continue;if(bU(X)&&!nv1(X)){let Y={v:X,i:G,n:this.norm.get(X)};K.push(Y)}else if(fE(X))X.forEach((Y,U)=>{Z.push({nestedArrIndex:U,value:Y})})}B.$[J]=K}else if(bU(z)&&!nv1(z)){let K={v:z,n:this.norm.get(z)};B.$[J]=K}}),this.records.push(B)}toJSON(){return{keys:this.keys,records:this.records}}}function R8A(A,Q,{getFn:B=c2.getFn,fieldNormWeight:D=c2.fieldNormWeight}={}){let J=new k91({getFn:B,fieldNormWeight:D});return J.setKeys(A.map(V8A)),J.setSources(Q),J.create(),J}function vr6(A,{getFn:Q=c2.getFn,fieldNormWeight:B=c2.fieldNormWeight}={}){let{keys:D,records:J}=A,z=new k91({getFn:Q,fieldNormWeight:B});return z.setKeys(D),z.setIndexRecords(J),z}function S91(A,{errors:Q=0,currentLocation:B=0,expectedLocation:D=0,distance:J=c2.distance,ignoreLocation:z=c2.ignoreLocation}={}){let K=Q/A.length;if(z)return K;let Z=Math.abs(D-B);if(!J)return Z?1:K;return K+Z/J}function kr6(A=[],Q=c2.minMatchCharLength){let B=[],D=-1,J=-1,z=0;for(let K=A.length;z<K;z+=1){let Z=A[z];if(Z&&D===-1)D=z;else if(!Z&&D!==-1){if(J=z-1,J-D+1>=Q)B.push([D,J]);D=-1}}if(A[z-1]&&z-D>=Q)B.push([D,z-1]);return B}var wV=32;function fr6(A,Q,B,{location:D=c2.location,distance:J=c2.distance,threshold:z=c2.threshold,findAllMatches:K=c2.findAllMatches,minMatchCharLength:Z=c2.minMatchCharLength,includeMatches:G=c2.includeMatches,ignoreLocation:X=c2.ignoreLocation}={}){if(Q.length>wV)throw new Error(Or6(wV));let Y=Q.length,U=A.length,F=Math.max(0,Math.min(D,U)),E=z,H=F,w=Z>1||G,I=w?Array(U):[],W;while((W=A.indexOf(Q,H))>-1){let L=S91(Q,{currentLocation:W,expectedLocation:F,distance:J,ignoreLocation:X});if(E=Math.min(L,E),H=W+Y,w){let j=0;while(j<Y)I[W+j]=1,j+=1}}H=-1;let M=[],N=1,O=Y+U,R=1<<Y-1;for(let L=0;L<Y;L+=1){let j=0,P=O;while(j<P){if(S91(Q,{errors:L,currentLocation:F+P,expectedLocation:F,distance:J,ignoreLocation:X})<=E)j=P;else O=P;P=Math.floor((O-j)/2+j)}O=P;let $=Math.max(1,F-P+1),v=K?U:Math.min(F+P,U)+Y,y=Array(v+2);y[v+1]=(1<<L)-1;for(let _=v;_>=$;_-=1){let k=_-1,g=B[A.charAt(k)];if(w)I[k]=+!!g;if(y[_]=(y[_+1]<<1|1)&g,L)y[_]|=(M[_+1]|M[_])<<1|1|M[_+1];if(y[_]&R){if(N=S91(Q,{errors:L,currentLocation:k,expectedLocation:F,distance:J,ignoreLocation:X}),N<=E){if(E=N,H=k,H<=F)break;$=Math.max(1,2*F-H)}}}if(S91(Q,{errors:L+1,currentLocation:F,expectedLocation:F,distance:J,ignoreLocation:X})>E)break;M=y}let T={isMatch:H>=0,score:Math.max(0.001,N)};if(w){let L=kr6(I,Z);if(!L.length)T.isMatch=!1;else if(G)T.indices=L}return T}function yr6(A){let Q={};for(let B=0,D=A.length;B<D;B+=1){let J=A.charAt(B);Q[J]=(Q[J]||0)|1<<D-B-1}return Q}var $91=String.prototype.normalize?(A)=>A.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,""):(A)=>A;class Bk1{constructor(A,{location:Q=c2.location,threshold:B=c2.threshold,distance:D=c2.distance,includeMatches:J=c2.includeMatches,findAllMatches:z=c2.findAllMatches,minMatchCharLength:K=c2.minMatchCharLength,isCaseSensitive:Z=c2.isCaseSensitive,ignoreDiacritics:G=c2.ignoreDiacritics,ignoreLocation:X=c2.ignoreLocation}={}){if(this.options={location:Q,threshold:B,distance:D,includeMatches:J,findAllMatches:z,minMatchCharLength:K,isCaseSensitive:Z,ignoreDiacritics:G,ignoreLocation:X},A=Z?A:A.toLowerCase(),A=G?$91(A):A,this.pattern=A,this.chunks=[],!this.pattern.length)return;let Y=(F,E)=>{this.chunks.push({pattern:F,alphabet:yr6(F),startIndex:E})},U=this.pattern.length;if(U>wV){let F=0,E=U%wV,H=U-E;while(F<H)Y(this.pattern.substr(F,wV),F),F+=wV;if(E){let w=U-wV;Y(this.pattern.substr(w),w)}}else Y(this.pattern,0)}searchIn(A){let{isCaseSensitive:Q,ignoreDiacritics:B,includeMatches:D}=this.options;if(A=Q?A:A.toLowerCase(),A=B?$91(A):A,this.pattern===A){let H={isMatch:!0,score:0};if(D)H.indices=[[0,A.length-1]];return H}let{location:J,distance:z,threshold:K,findAllMatches:Z,minMatchCharLength:G,ignoreLocation:X}=this.options,Y=[],U=0,F=!1;this.chunks.forEach(({pattern:H,alphabet:w,startIndex:I})=>{let{isMatch:W,score:M,indices:N}=fr6(A,H,w,{location:J+I,distance:z,threshold:K,findAllMatches:Z,minMatchCharLength:G,includeMatches:D,ignoreLocation:X});if(W)F=!0;if(U+=M,W&&N)Y=[...Y,...N]});let E={isMatch:F,score:F?U/this.chunks.length:1};if(F&&D)E.indices=Y;return E}}class yE{constructor(A){this.pattern=A}static isMultiMatch(A){return w8A(A,this.multiRegex)}static isSingleMatch(A){return w8A(A,this.singleRegex)}search(){}}function w8A(A,Q){let B=A.match(Q);return B?B[1]:null}class L8A extends yE{constructor(A){super(A)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(A){let Q=A===this.pattern;return{isMatch:Q,score:Q?0:1,indices:[0,this.pattern.length-1]}}}class T8A extends yE{constructor(A){super(A)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(A){let B=A.indexOf(this.pattern)===-1;return{isMatch:B,score:B?0:1,indices:[0,A.length-1]}}}class j8A extends yE{constructor(A){super(A)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(A){let Q=A.startsWith(this.pattern);return{isMatch:Q,score:Q?0:1,indices:[0,this.pattern.length-1]}}}class P8A extends yE{constructor(A){super(A)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(A){let Q=!A.startsWith(this.pattern);return{isMatch:Q,score:Q?0:1,indices:[0,A.length-1]}}}class _8A extends yE{constructor(A){super(A)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(A){let Q=A.endsWith(this.pattern);return{isMatch:Q,score:Q?0:1,indices:[A.length-this.pattern.length,A.length-1]}}}class S8A extends yE{constructor(A){super(A)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(A){let Q=!A.endsWith(this.pattern);return{isMatch:Q,score:Q?0:1,indices:[0,A.length-1]}}}class Dk1 extends yE{constructor(A,{location:Q=c2.location,threshold:B=c2.threshold,distance:D=c2.distance,includeMatches:J=c2.includeMatches,findAllMatches:z=c2.findAllMatches,minMatchCharLength:K=c2.minMatchCharLength,isCaseSensitive:Z=c2.isCaseSensitive,ignoreDiacritics:G=c2.ignoreDiacritics,ignoreLocation:X=c2.ignoreLocation}={}){super(A);this._bitapSearch=new Bk1(A,{location:Q,threshold:B,distance:D,includeMatches:J,findAllMatches:z,minMatchCharLength:K,isCaseSensitive:Z,ignoreDiacritics:G,ignoreLocation:X})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(A){return this._bitapSearch.searchIn(A)}}class Jk1 extends yE{constructor(A){super(A)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(A){let Q=0,B,D=[],J=this.pattern.length;while((B=A.indexOf(this.pattern,Q))>-1)Q=B+J,D.push([B,Q-1]);let z=!!D.length;return{isMatch:z,score:z?0:1,indices:D}}}var ov1=[L8A,Jk1,j8A,P8A,S8A,_8A,T8A,Dk1],I8A=ov1.length,br6=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,gr6="|";function xr6(A,Q={}){return A.split(gr6).map((B)=>{let D=B.trim().split(br6).filter((z)=>z&&!!z.trim()),J=[];for(let z=0,K=D.length;z<K;z+=1){let Z=D[z],G=!1,X=-1;while(!G&&++X<I8A){let Y=ov1[X],U=Y.isMultiMatch(Z);if(U)J.push(new Y(U,Q)),G=!0}if(G)continue;X=-1;while(++X<I8A){let Y=ov1[X],U=Y.isSingleMatch(Z);if(U){J.push(new Y(U,Q));break}}}return J})}var hr6=new Set([Dk1.type,Jk1.type]);class $8A{constructor(A,{isCaseSensitive:Q=c2.isCaseSensitive,ignoreDiacritics:B=c2.ignoreDiacritics,includeMatches:D=c2.includeMatches,minMatchCharLength:J=c2.minMatchCharLength,ignoreLocation:z=c2.ignoreLocation,findAllMatches:K=c2.findAllMatches,location:Z=c2.location,threshold:G=c2.threshold,distance:X=c2.distance}={}){this.query=null,this.options={isCaseSensitive:Q,ignoreDiacritics:B,includeMatches:D,minMatchCharLength:J,findAllMatches:K,ignoreLocation:z,location:Z,threshold:G,distance:X},A=Q?A:A.toLowerCase(),A=B?$91(A):A,this.pattern=A,this.query=xr6(this.pattern,this.options)}static condition(A,Q){return Q.useExtendedSearch}searchIn(A){let Q=this.query;if(!Q)return{isMatch:!1,score:1};let{includeMatches:B,isCaseSensitive:D,ignoreDiacritics:J}=this.options;A=D?A:A.toLowerCase(),A=J?$91(A):A;let z=0,K=[],Z=0;for(let G=0,X=Q.length;G<X;G+=1){let Y=Q[G];K.length=0,z=0;for(let U=0,F=Y.length;U<F;U+=1){let E=Y[U],{isMatch:H,indices:w,score:I}=E.search(A);if(H){if(z+=1,Z+=I,B){let W=E.constructor.type;if(hr6.has(W))K=[...K,...w];else K.push(w)}}else{Z=0,z=0,K.length=0;break}}if(z){let U={isMatch:!0,score:Z/z};if(B)U.indices=K;return U}}return{isMatch:!1,score:1}}}var tv1=[];function mr6(...A){tv1.push(...A)}function ev1(A,Q){for(let B=0,D=tv1.length;B<D;B+=1){let J=tv1[B];if(J.condition(A,Q))return new J(A,Q)}return new Bk1(A,Q)}var v91={AND:"$and",OR:"$or"},Ak1={PATH:"$path",PATTERN:"$val"},Qk1=(A)=>!!(A[v91.AND]||A[v91.OR]),ur6=(A)=>!!A[Ak1.PATH],pr6=(A)=>!fE(A)&&N8A(A)&&!Qk1(A),W8A=(A)=>({[v91.AND]:Object.keys(A).map((Q)=>({[Q]:A[Q]}))});function v8A(A,Q,{auto:B=!0}={}){let D=(J)=>{let z=Object.keys(J),K=ur6(J);if(!K&&z.length>1&&!Qk1(J))return D(W8A(J));if(pr6(J)){let G=K?J[Ak1.PATH]:z[0],X=K?J[Ak1.PATTERN]:J[G];if(!bU(X))throw new Error(Cr6(G));let Y={keyId:sv1(G),pattern:X};if(B)Y.searcher=ev1(X,Q);return Y}let Z={children:[],operator:z[0]};return z.forEach((G)=>{let X=J[G];if(fE(X))X.forEach((Y)=>{Z.children.push(D(Y))})}),Z};if(!Qk1(A))A=W8A(A);return D(A)}function cr6(A,{ignoreFieldNorm:Q=c2.ignoreFieldNorm}){A.forEach((B)=>{let D=1;B.matches.forEach(({key:J,norm:z,score:K})=>{let Z=J?J.weight:null;D*=Math.pow(K===0&&Z?Number.EPSILON:K,(Z||1)*(Q?1:z))}),B.score=D})}function dr6(A,Q){let B=A.matches;if(Q.matches=[],!AK(B))return;B.forEach((D)=>{if(!AK(D.indices)||!D.indices.length)return;let{indices:J,value:z}=D,K={indices:J,value:z};if(D.key)K.key=D.key.src;if(D.idx>-1)K.refIndex=D.idx;Q.matches.push(K)})}function lr6(A,Q){Q.score=A.score}function ir6(A,Q,{includeMatches:B=c2.includeMatches,includeScore:D=c2.includeScore}={}){let J=[];if(B)J.push(dr6);if(D)J.push(lr6);return A.map((z)=>{let{idx:K}=z,Z={item:Q[K],refIndex:K};if(J.length)J.forEach((G)=>{G(z,Z)});return Z})}class wW{constructor(A,Q={},B){this.options={...c2,...Q},this.options.useExtendedSearch,this._keyStore=new O8A(this.options.keys),this.setCollection(A,B)}setCollection(A,Q){if(this._docs=A,Q&&!(Q instanceof k91))throw new Error(Nr6);this._myIndex=Q||R8A(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(A){if(!AK(A))return;this._docs.push(A),this._myIndex.add(A)}remove(A=()=>!1){let Q=[];for(let B=0,D=this._docs.length;B<D;B+=1){let J=this._docs[B];if(A(J,B))this.removeAt(B),B-=1,D-=1,Q.push(J)}return Q}removeAt(A){this._docs.splice(A,1),this._myIndex.removeAt(A)}getIndex(){return this._myIndex}search(A,{limit:Q=-1}={}){let{includeMatches:B,includeScore:D,shouldSort:J,sortFn:z,ignoreFieldNorm:K}=this.options,Z=bU(A)?bU(this._docs[0])?this._searchStringList(A):this._searchObjectList(A):this._searchLogical(A);if(cr6(Z,{ignoreFieldNorm:K}),J)Z.sort(z);if(M8A(Q)&&Q>-1)Z=Z.slice(0,Q);return ir6(Z,this._docs,{includeMatches:B,includeScore:D})}_searchStringList(A){let Q=ev1(A,this.options),{records:B}=this._myIndex,D=[];return B.forEach(({v:J,i:z,n:K})=>{if(!AK(J))return;let{isMatch:Z,score:G,indices:X}=Q.searchIn(J);if(Z)D.push({item:J,idx:z,matches:[{score:G,value:J,norm:K,indices:X}]})}),D}_searchLogical(A){let Q=v8A(A,this.options),B=(K,Z,G)=>{if(!K.children){let{keyId:Y,searcher:U}=K,F=this._findMatches({key:this._keyStore.get(Y),value:this._myIndex.getValueForItemAtKeyId(Z,Y),searcher:U});if(F&&F.length)return[{idx:G,item:Z,matches:F}];return[]}let X=[];for(let Y=0,U=K.children.length;Y<U;Y+=1){let F=K.children[Y],E=B(F,Z,G);if(E.length)X.push(...E);else if(K.operator===v91.AND)return[]}return X},D=this._myIndex.records,J={},z=[];return D.forEach(({$:K,i:Z})=>{if(AK(K)){let G=B(Q,K,Z);if(G.length){if(!J[Z])J[Z]={idx:Z,item:K,matches:[]},z.push(J[Z]);G.forEach(({matches:X})=>{J[Z].matches.push(...X)})}}}),z}_searchObjectList(A){let Q=ev1(A,this.options),{keys:B,records:D}=this._myIndex,J=[];return D.forEach(({$:z,i:K})=>{if(!AK(z))return;let Z=[];if(B.forEach((G,X)=>{Z.push(...this._findMatches({key:G,value:z[X],searcher:Q}))}),Z.length)J.push({idx:K,item:z,matches:Z})}),J}_findMatches({key:A,value:Q,searcher:B}){if(!AK(Q))return[];let D=[];if(fE(Q))Q.forEach(({v:J,i:z,n:K})=>{if(!AK(J))return;let{isMatch:Z,score:G,indices:X}=B.searchIn(J);if(Z)D.push({score:G,key:A,value:J,idx:z,norm:K,indices:X})});else{let{v:J,n:z}=Q,{isMatch:K,score:Z,indices:G}=B.searchIn(J);if(K)D.push({score:Z,key:A,value:J,norm:z,indices:G})}return D}}wW.version="7.1.0";wW.createIndex=R8A;wW.parseIndex=vr6;wW.config=c2;wW.parseQuery=v8A;mr6($8A);import*as k8A from"node:readline";class zk1{fuse;rootLevelFiles=[];constructor(){this.fuse=new wW([],{keys:["value"],includeScore:!0,location:0,threshold:0.7,distance:256,ignoreLocation:!0,findAllMatches:!0,isCaseSensitive:!1})}addFiles(A){for(let Q of A){let B={value:Q.toLowerCase(),original:Q};if(this.fuse.add(B),!Q.includes("/"))this.rootLevelFiles.push(Q)}}removeFiles(A){for(let Q of A)if(this.fuse.remove((B)=>B.value===Q),!Q.includes("/"))this.rootLevelFiles=this.rootLevelFiles.filter((B)=>B!==Q)}query(A,Q=50){if(!A.trim())return this.rootLevelFiles.slice(0,Q);return this.fuse.search(A,{limit:Q}).map((D)=>D.item.original)}handleMessage(A){try{let{id:Q,type:B}=A;switch(B){case"index:add":return this.addFiles(A.files||[]),{id:Q,type:"response",status:"ok"};case"index:remove":return this.removeFiles(A.files||[]),{id:Q,type:"response",status:"ok"};case"query":{let D=this.query(A.text||"");return{id:Q,type:"response",results:D}}default:return{id:Q,type:"error",message:`Unknown type: ${B}`}}}catch(Q){return{id:A.id,type:"error",message:Q instanceof Error?Q.message:String(Q)}}}start(){let A=k8A.createInterface({input:process.stdin,output:process.stdout,terminal:!1});A.on("line",(Q)=>{try{let B=JSON.parse(Q),D=this.handleMessage(B);process.stdout.write(JSON.stringify(D)+`
|
4477
4477
|
`)}catch(B){process.stderr.write(JSON.stringify({id:-1,type:"error",message:`Parse error: ${B instanceof Error?B.message:String(B)}`})+`
|
4478
4478
|
`)}}),A.on("close",()=>{process.exit(0)})}}KM();var f8A={url:{value:"https://ampcode.com",visible:!1,description:"The Amp server URL to connect to"},"anthropic.thinking.enabled":{value:!1,visible:!1,description:"Enable Claude thinking process output for debugging"},"anthropic.interleavedThinking.enabled":{value:!1,visible:!1,description:"Enable interleaved thinking for Claude 4 models (allows reasoning between tool calls)"},"anthropic.temperature":{value:1,visible:!1,description:"Temperature setting for Anthropic models (0.0 = deterministic, 1.0 = creative). Note: Only takes effect when thinking is disabled. Internal use only."},"notifications.enabled":{value:!0,visible:!0,description:"Enable system sound notifications when agent completes tasks"},"todos.enabled":{value:!0,visible:!1,description:"Enable TODO tracking and management features"},mcpServers:{value:{filesystem:{command:"npx",args:["@modelcontextprotocol/server-filesystem","/path/to/allowed/dir"]}},visible:!0,description:"Model Context Protocol servers to connect to for additional tools"},"tools.disable":{value:["browser_navigate","builtin:edit_file"],visible:!0,description:"Array of tool names to disable. Use 'builtin:toolname' to disable only the builtin tool with that name (allowing an MCP server to provide a tool by that name)."},"tools.stopTimeout":{value:300,visible:!1,description:"Timeout for stopping tools"},cacheDirectory:{value:void 0,visible:!1,description:"Directory to use for caching logs or storing other files"},"commands.allowlist":{value:["git status","ls -la","npm run build"],visible:!0,description:"Array of shell commands that can be executed without confirmation"},"commands.strict":{value:!1,visible:!0,description:"Enable strict command validation. When disabled, certain commands like Bazel get relaxed path validation."},dangerouslyAllowAll:{value:!1,visible:!0,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},submitOnEnter:{value:!0,visible:!1,description:"Whether to submit messages on Enter (true) or require Ctrl+Enter (false)"},"terminal.commands.hide":{value:!1,visible:!1,description:"Hide terminal command output from the user"},"terminal.commands.nodeSpawn.loadProfile":{value:"daily",visible:!1,description:"How often to load shell profile in node-spawn mode (always, daily, never)"},"terminal.commands.nodeSpawn.detachedLogsDirectory":{value:void 0,visible:!1,description:"Directory to store detached logs in node-spawn mode"},"tab.enabled":{value:!0,visible:!1,description:"Enable tab completion features"},"tab.disabledLanguages":{value:[],visible:!1,description:"List of language IDs for which tab completion is disabled"},"tab.disableOnComment":{value:!1,visible:!1,description:"Dsiable tab completion on comment lines"},"tab.autoImport.enabled":{value:!1,visible:!1,description:"Enable auto-import feature for tab completion"},"tab.dimissCommandIds":{value:["extension.vim_escape","vim.escape","vscode-neovim.escape","vscode-neovim.escapeKey"],visible:!1,description:"Command IDs to execute when escape key is pressed in modal editors"},"tab.verboseLogs":{value:!1,visible:!1,description:"Enable verbose logging for tab completion"},debugLogs:{value:!1,visible:!1,description:"Enable debug logging output"},hooks:{value:[],visible:!1,description:"Custom hooks for extending Amp functionality"},"internal.primaryModel":{value:void 0,visible:!1,description:"Which model to use for the primary agentic loop"},"anthropic.provider":{value:"anthropic",visible:!1,description:'Which provider to use for Anthropic Claude inference: "anthropic" or "vertex"'},"experimental.fuzzySearch.enabled":{value:!1,visible:!1,description:"Enable new fuzzy file search implementation using core FuzzyService. Provides better performance and accuracy for large repositories, but may use more memory during indexing."},"experimental.run_javascript.enabled":{value:!1,visible:!1,description:"Whether to enable the experimental run_javascript tool"},"experimental.commandApproval.enabled":{value:!1,visible:!1,description:"Enable experimental command approval strategies for bash commands"},"experimental.commandApproval.allow":{value:[],visible:!1,description:"Prefixes of allowed command lines (no approval asked)"},"experimental.commandApproval.deny":{value:[],visible:!1,description:"Prefixes of risky command lines (will always ask approval)"},"jetbrains.enabled":{value:!1,visible:!1,description:"Enable integrated support for JetBrains-based IDE through the official JetBrains MCP plugin. When this setting is enabled, Amp will automatically try to include the currently open file and selected text (if any) before sending messages."},"experimental.reviewTool":{value:!1,visible:!1,description:"Experimental: Enable the summarize_git_diff tool."},"experimental.tools":{value:[],visible:!1,description:"Enable experimental tools by name. Available tools: chat_llm"},"summary.provider":{value:"gemini",visible:!1,description:"Summary provider to use (anthropic or gemini)"},"git.commit.coauthor.enabled":{value:!0,visible:!0,description:"Enable adding Amp as co-author in git commits"},"git.commit.ampThread.enabled":{value:!0,visible:!0,description:"Enable adding Amp-Thread trailer in git commits"},"updates.autoUpdate.enabled":{value:!0,visible:!0,description:"Enable automatic updates of the Amp CLI"}},ar6=Object.fromEntries(Object.entries(f8A).filter(([,A])=>A.visible).map(([A,Q])=>[`amp.${A}`,Q.value])),Sp={examples:[{description:"Start an interactive session:",command:"amp"},{description:"Start an interactive session with a user message:",command:'echo "commit all my unstaged changes" | amp'},{description:"Use execute mode (--execute or -x) to send a command to an agent, have it execute it, print only the agent's last message, and then exit:",command:'amp -x "what file in this folder is in markdown format?"',output:`All Markdown files in this folder:
|
@@ -4627,8 +4627,8 @@ ${Y}`}else Z=z.map((G)=>` ${G}`).join(`
|
|
4627
4627
|
`});return}if(E.trim().length>0)v(E.trim());else return;return}if(!m.ctrl&&!m.meta&&!m.tab&&y)z({type:"insert-text",text:y})});let v=async(y)=>{M(null),Q.add(y),Q.reset();try{A(y)}catch(m){S1.error("Failed to submit message",m)}};return W0(KA,{flexDirection:"column",width:"100%",flexGrow:1,flexShrink:0,ref:G,children:I.lines.map((y,m)=>W0(KA,{flexShrink:0,flexDirection:"row",children:W0(KA,{flexGrow:1,flexShrink:0,width:"100%",children:m===O.line?b6(QK,{children:[W0(TA,{dimColor:B,children:HS.default.substr(y.content,0,O.column)||""}),W0(TA,{inverse:!B,dimColor:B,children:HS.default(y.content)[O.column]??" "}),W0(TA,{dimColor:B,children:HS.default.substr(y.content,O.column+1)||""})]}):W0(TA,{dimColor:B,children:y.content||" "})})},m))})}function he6(A,Q){let B=HS.default(A),D=Q,J=Q;while(D>0&&/\S/.test(B[D-1]||""))D--;while(J<B.length&&/\S/.test(B[J]||""))J++;let z=B.slice(D,J).join("");if(!z.trim())return null;return{word:z,start:D,end:J}}var wS=xA(J8(),1);RH();var l41=xA(J8(),1);function B7A(){let[A,Q]=l41.useState(null);return l41.useEffect(()=>{let B=ll.subscribe(Q);return()=>{B.unsubscribe()}},[]),{jetbrainsState:A}}bQ1();var _f1=xA(J8(),1);function D7A({viewState:A}){let Q=_f1.useMemo(()=>{return A.state==="active"?A.fileChanges:void 0},[A]),B=_f1.useMemo(()=>Sh1(Q),[Q]);if(!Q||B.totalFiles===0)return null;let D=B.totalFiles-B.revertedFiles;return b6(KA,{gap:1,children:[b6(TA,{dimColor:!0,children:[D," ",D===1?"file":"files"," changed"]}),(B.totalAdded>0||B.totalModified>0||B.totalRemoved>0)&&b6(TA,{children:[b6(TA,{color:"green",children:["+",B.totalAdded]}),b6(TA,{color:"yellow",children:[" ~",B.totalModified]}),b6(TA,{color:"red",children:[" -",B.totalRemoved]})]})]})}import J7A from"node:path";function z7A({jetbrainsStatus:A}){if(!A||!A.enabled)return null;let Q=process.cwd(),B=A.productName&&A.openFile&&A.workspace===Q,D;if(!A.productName)D=" IDE Not Running. To fix this problem, start your JetBrains IDE, exit this session and run `amp threads continue`.";else if(!A.workspace&&!A.openFile)D=" No Open File. To fix this problem, open a project and open a file in your JetBrains IDE.";else if(!A.workspace&&A.openFile){let J=J7A.basename(A.openFile);if(A.openFile.includes("!/"))D=` External File Open. The open file '${A.openFile}' does not belong to your project root. To fix this problem, open a file in your project sources and try again.`;else D=` Project Detection Failed. Failed to map your open file '${J}' to a project root directory. Please note that multi-root projects are not supported at the moment. Please report a bug on https://ampcode.com/discord and include relevant logs from ~/.cache/amp/logs/cli.log`}else if(!A.openFile)D=" No Open File. To fix this problem, open a file in your project.";else if(A.workspace!==Q)D=` Project Mismatch. The currently open project "${A.workspace}" does not match the working directory of Amp CLI ("${Q}").`;return W0(KA,{gap:B?1:2,children:b6(TA,{color:B?"green":"red",children:[B?"✓":"×"," ",A.productName??"JetBrains"," ",B?"• "+J7A.basename(A.openFile??""):D]})})}var i41=xA(J8(),1);function K7A(){let[A,Q]=i41.useState(0);i41.useEffect(()=>{let J=setInterval(()=>{Q((z)=>z+1)},200);return()=>clearInterval(J)},[]);let B=[{char:"∿",dim:!1},{char:"∾",dim:!1},{char:"∽",dim:!1},{char:"≋",dim:!1},{char:"≈",dim:!1},{char:"∼",dim:!1}],D=B[A%B.length];return W0(TA,{dimColor:D.dim,children:D.char})}var me6=0.8,ue6=0.9;function Z7A({tokenUsage:A}){let Q=A.totalInputTokens/A.maxInputTokens,B=Math.round(Q*100),J=`${Math.max(0,Math.min(B,100))}%`,z,K=G7A(Q);if(K==="danger")z="red";else if(K==="warning")z="yellow";return W0(TA,{color:z,children:J})}function G7A(A){if(A>=ue6)return"danger";else if(A>=me6)return"warning";return!1}function X7A(A){let Q=A.totalInputTokens/A.maxInputTokens;return G7A(Q)}function Y7A({threadViewState:A,tokenUsage:Q,waitingForConfirmation:B,showingEphemeralError:D}){if(!A||A.state!=="active")return null;let J=null,z=Q?X7A(Q):!1,K=!1;if(A.summaryState==="summarizing")J="Compacting...";else if(A.inferenceState==="running")J="Running inference...";else if(A.interactionState==="tool-running")J="Running tools...";else if(!D&&z==="warning")J="Context window is almost full. Use /compact to trim the thread.",K=!0;else if(!D&&z==="danger")J="Context window is close to full. Use /compact to trim the thread.",K=!0;if(!J)return null;let Z=()=>{if(A.inferenceState==="running"&&A.interactionState!=="tool-running")return"blueBright";if(A.interactionState==="tool-running")return"greenBright";return"default"},G=()=>{if(K&&z==="warning")return"yellow";if(K&&z==="danger")return"red";if(A.inferenceState==="cancelled")return"dim";return"default"},X=A.inferenceState!=="cancelled"&&!K&&!B;return b6(KA,{flexDirection:"row",gap:1,children:[X&&W0(TA,{color:Z(),children:W0(K7A,{})}),W0(TA,{italic:!K&&A.inferenceState==="cancelled",color:G(),children:J})]})}function U7A({view:A,threadViewState:Q,threadTokenUsage:B,hasCompletedMessages:D,width:J}){let{jetbrainsState:z}=B7A(),K=wS.useRef(null),{stdout:Z}=RX(),[G,X]=wS.useState(Z.columns);wS.useEffect(()=>{if(K.current){let{width:F}=CV(K.current);X(F)}},[Z.columns]);let Y=J||G,U=Y&&Y<60;return b6(KA,{gap:2,marginLeft:2,marginRight:2,ref:K,children:[b6(KA,{flexGrow:1,flexDirection:"row",gap:2,children:[W0(Y7A,{threadViewState:Q,tokenUsage:B,waitingForConfirmation:A==="confirming"||A==="ephemeral-error",showingEphemeralError:A==="ephemeral-error"}),b6(KA,{children:[A==="confirming-exit"&&W0(TA,{dimColor:!0,children:"Ctrl+C again to exit"}),A==="help"&&W0(TA,{dimColor:!0,children:"Escape to close help"}),D&&A==="running"&&!U&&W0(TA,{dimColor:!0,children:"Ctrl+R to expand"})]})]}),b6(KA,{flexGrow:0,gap:2,children:[W0(z7A,{jetbrainsStatus:z}),!U&&W0(D7A,{viewState:Q}),B&&W0(Z7A,{tokenUsage:B})]})]})}i6();C0.level=1;var pe6={code:C0.white,codespan:C0.white,blockquote:C0.gray.italic,html:C0.gray,heading:C0.bold,firstHeading:C0.bold,hr:C0.reset,table:C0.reset,paragraph:C0.reset,strong:C0.bold,em:C0.italic,del:C0.dim.gray.strikethrough,link:C0.cyan,href:C0.cyan,text:C0.reset,unescape:!0,emoji:!0,width:80,showSectionPrefix:!0,reflowText:!1,tab:4,tableOptions:{wordWrap:!0,wrapOnWordBoundary:!1,style:{head:["bold"],border:["grey"],compact:!1}}},ce6={keyword:C0.bold,built_in:C0.dim,type:C0.dim,literal:C0.italic,number:C0.reset,regexp:C0.dim.italic,string:C0.dim,subst:C0.reset,symbol:C0.reset,class:C0.bold,function:C0.reset,title:C0.reset,params:C0.reset,comment:C0.dim.italic,doctag:C0.dim.italic,meta:C0.dim,"meta-keyword":C0.reset,"meta-string":C0.reset,section:C0.reset,tag:C0.dim,name:C0.bold,"builtin-name":C0.reset,attr:C0.dim,attribute:C0.reset,variable:C0.reset,bullet:C0.reset,code:C0.reset,emphasis:C0.italic,strong:C0.bold,formula:C0.reset,link:C0.underline,quote:C0.reset,"selector-tag":C0.reset,"selector-id":C0.reset,"selector-class":C0.reset,"selector-attr":C0.reset,"selector-pseudo":C0.reset,"template-tag":C0.reset,"template-variable":C0.reset,addition:C0.bold.underline,deletion:C0.dim.strikethrough,default:C0.reset};E9.use(m81({...pe6,reflowText:!1},{ignoreIllegals:!0,theme:ce6}));function a41({children:A}){let Q;try{Q=E9(A,{async:!1}).trimEnd()}catch(B){S1.error("Markdown rendering failed",B,{input:A}),Q=A}return W0(TA,{children:Q})}function q7A({message:A}){let Q=A.content.filter((B)=>B.type==="thinking"||B.type==="text");if(!Q.length)return null;return W0(KA,{flexDirection:"column",marginBottom:1,children:Q.map((B,D)=>{let J=D>0?1:0;if(B.type==="thinking")return W0(d41,{thinking:B.thinking},D);else return W0(KA,{marginTop:J,children:W0(a41,{children:B.text})},D);return null})})}function F7A({message:A,marginTop:Q=0}){if(!A.content.some((J)=>J.type==="text"||J.type==="thinking"||J.type==="summary"&&J.summary.type==="message"))return null;let D=A.role==="assistant"&&A.state.type==="cancelled";return b6(KA,{flexDirection:"column",gap:1,marginTop:Q,children:[A.content.map((J,z)=>{if(J.type==="text")switch(A.role){case"assistant":return W0(KA,{flexDirection:"column",children:W0(a41,{children:J.text})},z);case"user":return W0(KA,{borderStyle:"bold",borderColor:"green",borderLeft:!0,borderTop:!1,borderBottom:!1,borderRight:!1,paddingLeft:1,children:W0(TA,{color:"green",italic:!0,children:J.text})},z)}else if(J.type==="thinking")return W0(d41,{thinking:J.thinking},z);else if(J.type==="summary"&&J.summary.type==="message")return W0(KA,{children:b6(TA,{color:"grey",italic:!0,children:["Summary: ",J.summary.summary]})},z);else return null}),D&&W0(KA,{children:W0(TA,{italic:!0,dimColor:!0,children:"Cancelled"})})]})}function E7A({todos:A}){if(!Array.isArray(A)||A.length===0)return null;return b6(KA,{borderStyle:"round",borderColor:"dim",paddingX:1,flexDirection:"column",flexGrow:1,flexShrink:0,children:[W0(KA,{children:W0(TA,{dimColor:!0,bold:!0,children:"TODOs"})}),A.map((Q,B)=>W0(KA,{gap:1,children:b6(TA,{dimColor:!0,wrap:"truncate",children:[W0(TA,{children:"• "}),W0(TA,{bold:Q.status==="in-progress",strikethrough:Q.status==="completed",children:Q.content})]})},Q.id))]})}var RW=xA(J8(),1);function Sf1({children:A,dependencies:Q}){let{stdout:B}=RX(),D=RW.useRef(null),[J,z]=RW.useState(B.columns),K=RW.useCallback(()=>{if(D.current){let{width:Z}=CV(D.current);z(Z)}},[D,z]);return RW.useLayoutEffect(K,[K,B.columns,...Q||[]]),W0(KA,{width:"100%",height:"100%",ref:D,children:A(J)})}var r41=xA(J8(),1);function H7A(A){let Q=r41.useMemo(()=>process.cwd().replace(process.env.HOME||"","~"),[]);r41.useEffect(()=>{if(A)process.stdout.write(`\x1B]0;amp - ${A} - ${Q}\x07`);return()=>{process.stdout.write("\x1B]0;\x07")}},[A,Q])}var n41=xA(J8(),1);function w7A(){return W0(KA,{flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:3,marginLeft:4,children:W0(KA,{children:W0(TA,{color:"green",bold:!0,children:"Welcome to Amp"})})})}function I7A(){let[A,Q]=n41.useState(0),B=["Amp","AMP","AmP","amP","aMP","AMp"];return n41.useEffect(()=>{let D=setInterval(()=>{Q((J)=>(J+1)%B.length)},50);return()=>clearInterval(D)},[B.length]),W0(KA,{flexDirection:"column",alignItems:"flex-start",justifyContent:"center",minHeight:3,marginLeft:4,children:W0(KA,{children:b6(TA,{color:"green",bold:!0,children:["Welcome to ",B[A]]})})})}var de6=200;function W7A({threadService:A,history:Q,worker:B,sendToolConfirmation:D,sendUserMessage:J,exit:z,cancel:K,ampURL:Z,commands:G}){let[X]=c41(),{viewState:Y,subagents:U,subagentActiveTools:F,transcript:E,streamingAssistantMessage:H,todosList:w,mainThread:I}=W5A(A,B),W=I5.useMemo(()=>H?E.items.concat({id:"streaming-assistant",type:"message",message:H}):E.items,[H,E.items]),M=I?.title||"Untitled",N=I5.useMemo(()=>I?ch1(I):void 0,[I]);H7A(I?.title);let O=I5.useRef(new r8),[R,T]=I5.useState({baseView:"running",rerendering:!1,resizeCounter:0,dismissedEphemeralError:null,slashCommandQuery:null,uiError:null}),L=I5.useRef(null),j=I5.useRef(null),[P,$]=i5A(),v=I5.useCallback((s)=>{T((Q1)=>({...Q1,slashCommandQuery:s}))},[]),y=I5.useMemo(()=>{if(R.slashCommandQuery===null)return[];return G.query(R.slashCommandQuery)},[R.slashCommandQuery,G]),m=I5.useCallback(()=>{T((s)=>({...s,rerendering:!0})),process.stdout.write("\x1B[2J\x1B[3J\x1B[H"),O.current.next()},[T,O]),_=I5.useCallback(async(s)=>{if(T((W1)=>({...W1,slashCommandQuery:null})),!s||!I)return;let Q1=!1,J1=(W1)=>{Q1=!0,$(W1)},X1=()=>{T((W1)=>({...W1,baseView:"help"}))},L1=await G.get(s).execute({worker:B,thread:I,editorDispatch:J1,exitApp:z,openHelp:X1});if(T((W1)=>({...W1,uiError:L1||null})),!Q1)$({type:"clear"})},[G,$,I,B,z]),k=I5.useCallback((s)=>{$({type:"clear"}),J(s)},[$,J]);I5.useEffect(()=>{return process.stdout.on("resize",m),()=>{process.stdout.off("resize",m)}},[m]),I5.useEffect(()=>{let s=O.current.pipe(WD(de6)).subscribe(()=>{T((Q1)=>({...Q1,rerendering:!1,resizeCounter:Q1.resizeCounter+1}))});return()=>{s.unsubscribe()}},[O,T]),I5.useEffect(()=>{let s=O.current,Q1=L.current;return()=>{if(s.complete(),Q1)clearTimeout(Q1)}},[O]);let g=[...E.activeTools,...F],u=g.filter((s)=>s.toolRun.status==="blocked-on-user"),S=I5.useMemo(()=>v5A(u),[u]),{hasCompletions:h,completions:d,selectCompletion:l}=S41(),D1=I5.useMemo(()=>{if(Y.state!=="active"||!Y.ephemeralError)return null;if(R.dismissedEphemeralError===Y.ephemeralError)return null;return Y.ephemeralError},[Y,R.dismissedEphemeralError]),n=R.uiError!==null?"ui-error":D1!==null?"ephemeral-error":S!==null?"confirming":R.baseView,K1=(s)=>{if(!S||S.type!=="tool-use")return;if(S.tools.length>0){let Q1=S.tools[0],J1=Array.from(s==="always"?Q1.toAllow??[]:[]);D(Q1.useBlock.id,s==="yes"||s==="always",J1,S.subthreadID)}},B1=(s)=>{switch(s){case"compact":T((Q1)=>({...Q1,dismissedEphemeralError:null})),B.summarizeThread();break;case"dismiss":T((Q1)=>({...Q1,dismissedEphemeralError:D1}));break;case"retry":T((Q1)=>({...Q1,dismissedEphemeralError:null})),B.retry();break;default:S1.warn("action:",{action:s})}},Z1=()=>{T((s)=>({...s,uiError:null}))};uE((s,Q1)=>{if(Q1.ctrlC){if(R.baseView==="confirming-exit"){if(L.current)clearTimeout(L.current),L.current=null;z()}else{if(T((X1)=>({...X1,baseView:"confirming-exit"})),L.current)clearTimeout(L.current);let J1=setTimeout(()=>{T((X1)=>({...X1,baseView:"running"})),L.current=null},1000);L.current=J1}return}if(n==="help"){if(Q1.escape)T((J1)=>({...J1,baseView:"running"}));return}if(n==="expanded-view"||n==="confirming"||n==="ephemeral-error")return;if(n==="ui-error")return;if(Q1.escape)if(h||y.length>0)return;else K();else if(Q1.ctrl&&s.toLowerCase()==="r")T((J1)=>({...J1,baseView:"expanded-view"}));else if(Q1.ctrlL)m()});let z1=X>100,R1=R.rerendering&&E.items.length===0?1:"auto",a="resize-key"+R.resizeCounter,r=[{type:"welcome",id:"welcome"},...E.items];if(R.baseView==="expanded-view"){let s=W.filter((Q1)=>Q1.type==="message").map((Q1)=>Q1.message);return W0(n5A,{threadName:M,messages:s,onExit:()=>T((Q1)=>({...Q1,baseView:"running"}))})}return b6(KA,{flexDirection:"column",minHeight:"100%",flexGrow:1,height:R1,children:[W0(T41,{items:r,children:(s,Q1)=>{if(s.type==="welcome")return W0(w7A,{},"welcome");let J1=Q1===0?0:1;return s.type==="message"?W0(F7A,{message:s.message,marginTop:J1},s.id):W0(S5A,{toolUse:s.toolUse,toolResult:s.toolResult,marginTop:J1},s.id)}},a),b6(KA,{flexDirection:"column",marginTop:r.length>1?1:0,children:[H&&W0(q7A,{message:H}),W0(T5A,{activeTools:g,subagents:U}),b6(KA,{flexDirection:z1?"row-reverse":"column",children:[w.length>0&&W0(KA,{ref:j,flexGrow:0,flexShrink:0,width:z1?"50%":"100%",children:W0(E7A,{todos:w})}),n==="ui-error"&&R.uiError?W0(u41,{title:Nf1(R.uiError).title,description:Nf1(R.uiError).description,options:[{value:"dismiss",label:"Dismiss"}],onSelect:Z1}):n==="ephemeral-error"&&D1?W0(r5A,{error:D1,onResponse:B1,ampURL:Z}):n==="confirming"&&S?W0(y5A,{currentConfirmation:S,onConfirmationResponse:K1}):n==="help"?W0(Sf1,{dependencies:[w],children:(s)=>W0(e5A,{width:s})}):W0(KA,{flexGrow:1,borderStyle:"round",paddingX:1,children:W0(Sf1,{dependencies:[w],children:(s)=>W0(Q7A,{onSubmit:k,history:Q,disabled:n==="confirming"||n==="ephemeral-error"||Y.state==="active"&&Y.summaryState==="summarizing",viewState:Y,editorState:P,editorDispatch:$,onSlashCommandQuery:v,width:s})})})]}),W0(U7A,{view:n,threadViewState:Y,threadTokenUsage:N,hasCompletedMessages:E.items.length>0}),W0(le6,{commands:y,onSelect:_}),W0(ie6,{completions:d.options,onSelect:l})]})]})}function le6({commands:A,onSelect:Q}){let D=I5.useMemo(()=>A.slice(0,10).map((J)=>({value:J.name,label:J.name,description:J.description})),[A]);return W0(KA,{marginBottom:1,children:W0(VV,{title:"Select command:",options:D,onSelect:Q})})}function ie6({completions:A,onSelect:Q}){let B=Math.min(10),D=I5.useMemo(()=>A.slice(0,B).map((z)=>({value:z,label:z})),[A,B]),J=I5.useCallback((z)=>{if(z===null)return;let K=A.find((Z)=>Z===z);if(!K)return;Q(K)},[A,Q]);if(D.length===0)return null;return W0(KA,{marginBottom:1,children:W0(VV,{title:"Insert file name:",options:D,onSelect:J})})}function M7A(A){let{worker:Q,threadID:B,settingsStorage:D,pipedInput:J,workerDeps:z,configService:K,fuzzyServer:Z}=A,[G,X]=LX.useState(!1);H5A();let Y=LX.useCallback((I,W,M,N)=>{return ae6(I,W,M,N,D,Q,z)},[D,Q,z]),U=LX.useCallback(async(I)=>{await Q.handle({type:"user:message",message:{content:[{type:"text",text:I}]}})},[Q]),{exit:F}=Wf1(),E=LX.useCallback(()=>{fK.cancel(B)},[B]);LX.useEffect(()=>{let I=setTimeout(()=>{X(!0)},500);return()=>clearTimeout(I)},[]);let H=LX.useRef(!1);if(LX.useEffect(()=>{if(H.current)return;if(J)H.current=!0,U(J),X(!0)},[J,U]),!G)return W0(I7A,{});let w=new Cf1;return W0(G5A,{configService:K,children:W0(K5A,{fuzzyServer:Z,children:W0(W7A,{history:A.history,threadService:A.threadService,worker:Q,sendToolConfirmation:Y,sendUserMessage:U,exit:F,cancel:E,ampURL:A.ampURL,commands:w})})})}async function ae6(A,Q,B,D,J,z,K){let Z=B&&B.length>0||!1;if(B&&B.length>0)await C6(i2).then((X)=>X.settings["experimental.commandApproval.enabled"]?"experimental.commandApproval.allow":"commands.allowlist").then((X)=>{J.get(X,"global").then((Y)=>{let U=[...Y??[],...B];return J.set(X,U,"global")}).catch((Y)=>{S1.error("Failed to update allowlist",Y)})});let G={type:"user:tool-input",toolUse:A,value:{accepted:Q||Z}};if(D)(await fK.getOrCreateForThread(K,D)).handle(G);else z.handle(G)}global.React=$f1.default;function N7A(A){return C0.level=1,If1($f1.default.createElement(M7A,{...A}),{patchConsole:!0,exitOnCtrlC:!1,stdout:A.stdout,stdin:A.stdin}).waitUntilExit().then(async()=>{let{threadID:B,ampURL:D,threadService:J}=A;if((await J.get(B))?.messages.length!==0){let K=`${D.replace(/\/$/,"")}/threads/${B}`;A.stdout.write(`
|
4628
4628
|
`),A.stdout.write(`${C0.dim("Thread:")} ${K}
|
4629
4629
|
`),A.stdout.write(`${C0.dim("Continue this thread with:")} amp threads continue ${B}
|
4630
|
-
`)}})}var yf1=ff1.join(O1A||ff1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function bf1(A){try{await Q12(ff1.dirname(yf1),{recursive:!0}),await D12(yf1,A,"utf-8")}catch(Q){S1.debug("Failed to save last thread ID",Q)}}async function L7A(){try{return(await B12(yf1,"utf-8")).trim()}catch(A){return null}}async function J12(A){let Q=await _Q(`/api/threads/${A}`);if(!Q.ok){let B=await Q.text();if(Q.status===404||B.includes("not found"))throw new Qz(_Z.threadNotFound(A));throw new Qz(`Failed to load thread ${A}`,1,`Use 'amp threads share ${A} --support' to share this with the Amp team if this persists.`)}return await Q.json()}var _7A=process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1,T7A=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??HW,description:`Custom settings file path (overrides the default location ${HW})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S1).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:"Set log file location"},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:_7A,description:(A)=>A?"Enable JetBrains integration. Requires the JetBrains MCP plugin to be installed and you must start Amp in the same directory as your JetBrains project. When enabled, Amp automatically includes your open JetBrains file and text selection with every message, just like it does in VS Code.":"Disable JetBrains integration.",hidden:!0},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0}],j7A=(A)=>("deprecated"in A)&&A.deprecated===!0,z12=(A)=>("hidden"in A)&&A.hidden===!0,K12=(A)=>("default"in A),Z12=(A)=>("default"in A)?A.default:void 0;function G12(A,Q){let B=Q.args[0],D=Q.commands.map((z)=>z.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let z=D.filter((Z)=>B.includes(Z)||Z.includes(B)),K="Run amp --help for a list of available commands.";if(z.length>0)K=`Did you mean: ${z.join(", ")}? Or run amp --help for all commands.`;throw new Qz(_Z.unknownCommand(B),1,K)}}async function IS(A,Q){oh1("0.0.
|
4631
|
-
`),!await X12(A,D))process.exit(1)}let E=Yr1(),H=new HX1(E),w=new qX1(E),I=new nq1(H),W=Q.notifications!==void 0?Q.notifications:!A.executeMode,M=D1A({playNotificationSound:async(
|
4630
|
+
`)}})}var yf1=ff1.join(O1A||ff1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function bf1(A){try{await Q12(ff1.dirname(yf1),{recursive:!0}),await D12(yf1,A,"utf-8")}catch(Q){S1.debug("Failed to save last thread ID",Q)}}async function L7A(){try{return(await B12(yf1,"utf-8")).trim()}catch(A){return null}}async function J12(A){let Q=await _Q(`/api/threads/${A}`);if(!Q.ok){let B=await Q.text();if(Q.status===404||B.includes("not found"))throw new Qz(_Z.threadNotFound(A));throw new Qz(`Failed to load thread ${A}`,1,`Use 'amp threads share ${A} --support' to share this with the Amp team if this persists.`)}return await Q.json()}var _7A=process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1,T7A=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??HW,description:`Custom settings file path (overrides the default location ${HW})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S1).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:"Set log file location"},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:_7A,description:(A)=>A?"Enable JetBrains integration. Requires the JetBrains MCP plugin to be installed and you must start Amp in the same directory as your JetBrains project. When enabled, Amp automatically includes your open JetBrains file and text selection with every message, just like it does in VS Code.":"Disable JetBrains integration.",hidden:!0},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0}],j7A=(A)=>("deprecated"in A)&&A.deprecated===!0,z12=(A)=>("hidden"in A)&&A.hidden===!0,K12=(A)=>("default"in A),Z12=(A)=>("default"in A)?A.default:void 0;function G12(A,Q){let B=Q.args[0],D=Q.commands.map((z)=>z.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let z=D.filter((Z)=>B.includes(Z)||Z.includes(B)),K="Run amp --help for a list of available commands.";if(z.length>0)K=`Did you mean: ${z.join(", ")}? Or run amp --help for all commands.`;throw new Qz(_Z.unknownCommand(B),1,K)}}async function IS(A,Q){oh1("0.0.1753448050-g0871b6");let B=Q.settingsFile;S1.info("Using settings file",{settingsFile:B});let D=xv1(Rp()),J=Vp({settingsFile:B}),z=BB1({storage:J,secretStorage:D,workspaceRoots:UA.of([t6.file(process.cwd())]),defaultAmpURL:A.ampURL}),K=Kv(),Z=oa1({configService:z,toolService:K});try{await Z.initialized}catch(R){S1.warn("Failed to wait for MCP servers, continuing anyway:",R)}let G=await C6(i2);if(Q.dangerouslyAllowAll)G.settings.dangerouslyAllowAll=!0;if(Q.jetbrains){if(G.settings["jetbrains.enabled"]=!0,ll.subscribe((T)=>{S1.info("jetbrains-status",T)}),await VH(),!await op1()){if(_7A)S2.write(A.printer.print("Error: ",{foreground:"red",style:"bold"})+"JetBrains integration failed. Try again with `amp --no-jetbrains` or see setup: https://ampcode.com/manual#jetbrains");else S2.write(A.printer.print("Error: ",{foreground:"red",style:"bold"})+"Cannot connect to JetBrains IDE. Check setup: https://ampcode.com/manual#jetbrains");process.exit(1)}}let X=G.settings["experimental.reviewTool"]??!1,Y=G.settings["experimental.tools"]??[];tP1(K,!1,X,Y);let U,F;if(!A.executeMode)U=new rv1(G.settings,process.cwd()),await U.start(),F=F8A(U,process.cwd());else U=new class{async start(){}async query(){return[]}dispose(){}},F={[Symbol.dispose]:()=>{}};if(!await D.get("apiKey",A.ampURL)){if(Q5.write(`No API key found. Starting login flow...
|
4631
|
+
`),!await X12(A,D))process.exit(1)}let E=Yr1(),H=new HX1(E),w=new qX1(E),I=new nq1(H),W=Q.notifications!==void 0?Q.notifications:!A.executeMode,M=D1A({playNotificationSound:async(R)=>{if(W)B1A(R)},windowFocused:()=>Promise.resolve(!1),threadService:H,notifyForSubagents:!1});S1.info("Starting Amp background services");let N=i80({threadService:H,threadHistoryService:w,isExtensionDevelopment:!1}),O={configService:z,toolService:K,mcpService:Z,threadService:H,threadHistoryService:w,threadSummaryService:I,threadSyncService:N,threadStorage:E,secretStorage:D,settingsStorage:J,fileWatcher:F,fuzzyServer:U,notificationService:M};return{...O,async dispose(){await O.mcpService.dispose(),O.configService.unsubscribe(),O.toolService.dispose(),O.fileWatcher[Symbol.dispose](),O.fuzzyServer.dispose(),O.threadSyncService.dispose()}}}async function X12(A,Q){if(!A.executeMode){if(await g91("Would you like to log in to Amp?",["(y)es","(n)o"])!="y")return Q5.write(`Login cancelled. Run the command again to retry.
|
4632
4632
|
`),!1}return await S7A(A,Q)}async function S7A(A,Q){let B=A12(32).toString("hex"),D=await h8A(A.ampURL,B);Q5.write(`If your browser doesn't open automatically, visit:
|
4633
4633
|
|
4634
4634
|
${C0.blue.bold(D)}
|
@@ -4641,7 +4641,7 @@ ${C0.blue.bold(D)}
|
|
4641
4641
|
Login successful! You can now use the Amp CLI.
|
4642
4642
|
`),!0}catch(J){return S2.write(`
|
4643
4643
|
Login failed: ${J instanceof Error?J.message:String(J)}
|
4644
|
-
`),!1}}function Y12(A){let Q=new eu().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, team)").configureOutput({writeErr:()=>{}});Q.exitOverride((X)=>{if(X.code==="commander.help"||X.code==="commander.version"||X.exitCode===0)Tp(),process.exit(0);let Y=X.originalError??X;n_(A,Y)}),Q.option("-V, --version","output the version number",()=>{Q5.write(`0.0.
|
4644
|
+
`),!1}}function Y12(A){let Q=new eu().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, team)").configureOutput({writeErr:()=>{}});Q.exitOverride((X)=>{if(X.code==="commander.help"||X.code==="commander.version"||X.exitCode===0)Tp(),process.exit(0);let Y=X.originalError??X;n_(A,Y)}),Q.option("-V, --version","output the version number",()=>{Q5.write(`0.0.1753448050-g0871b6 (released 2025-07-25T13:00:19.455Z)
|
4645
4645
|
`),process.exit(0)}),Q.addHelpText("after",y8A()),Q.configureHelp({formatHelp:b8A}),Q.command("logout").description("Log out by removing stored API key").action(async()=>{let X=DK(),Y=Rp();if(process.env.AMP_API_KEY)Q5.write(`API key found in environment variable AMP_API_KEY, unset first before running 'amp logout'
|
4646
4646
|
`),process.exit(0);if(!await Y.get("apiKey",X.ampURL))Q5.write(`Already logged out.
|
4647
4647
|
`),process.exit(0);await Y.set("apiKey","",X.ampURL),Q5.write(`Successfully logged out.
|
@@ -4650,32 +4650,32 @@ Login failed: ${J instanceof Error?J.message:String(J)}
|
|
4650
4650
|
`),process.exit(0);let F=await Y.get("apiKey",X.ampURL);if(F){if(Q5.write(`API key already configured in file: ${F.slice(0,10)}...
|
4651
4651
|
`),await g91("Do you want to log in again?",["(y)es","(n)o"])==="n")process.exit(0);Q5.write(`
|
4652
4652
|
`)}let E=await S7A(X,Y);process.exit(E?0:1)});let B=Q.command("threads").description("Thread management commands");B.command("new").description("Create a new thread and print its ID").option("--visibility <visibility>","Set thread visibility (private, public, team)").action(async(X,Y)=>{let U=Y.optsWithGlobals(),F=DK(),E=await IS(F,U),H=y91(U);if(H instanceof Error)S2.write(F.printer.print("Error: ",{foreground:"red",style:"bold"})+H.message),process.exit(1);try{let w=AY(),I={id:w,messages:[],created:Date.now(),v:0};E.threadStorage.set(w,I);let W=await _Q(`/api/threads/${w}`,{method:"POST",body:JSON.stringify(I)});if(!W.ok){let M=await W.text().catch(()=>"Unable to read response body");throw new Error(`Failed to create thread on server: ${W.status}${M?`: ${M}`:""}`)}if(await bf1(w),H)await E.threadSyncService.updateThreadMeta(w,b91(H));Q5.write(`${w}
|
4653
|
-
`),
|
4654
|
-
`),process.exit(1)}}),B.command("continue [threadId]").description("Continue an existing thread (uses last used thread if no ID provided)").action(async(X,Y,U)=>{let F=U.optsWithGlobals(),E=DK(F),H=X;if(!H){if(H=await L7A(),!H)throw new Qz("No thread ID provided and no previously used thread found.",1,"Provide a thread ID as an argument or run a thread first.")}try{await P7A(E,{...F,threadId:H})}catch(w){n_(E,w,H)}}),B.command("fork [threadId]").description("Create a new thread by forking an existing one and print its ID (uses last used thread if no ID provided)").action(async(X,Y,U)=>{let F=U.optsWithGlobals(),E=DK(),H=await IS(E,F);try{let w=X;if(!w){if(w=await L7A(),!w)S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`No thread ID provided and no previously used thread found.
|
4653
|
+
`),await E.dispose(),process.exit(0)}catch(w){S2.write(`Error creating thread: ${w instanceof Error?w.message:String(w)}
|
4654
|
+
`),await E.dispose(),process.exit(1)}}),B.command("continue [threadId]").description("Continue an existing thread (uses last used thread if no ID provided)").action(async(X,Y,U)=>{let F=U.optsWithGlobals(),E=DK(F),H=X;if(!H){if(H=await L7A(),!H)throw new Qz("No thread ID provided and no previously used thread found.",1,"Provide a thread ID as an argument or run a thread first.")}try{await P7A(E,{...F,threadId:H})}catch(w){n_(E,w,H)}}),B.command("fork [threadId]").description("Create a new thread by forking an existing one and print its ID (uses last used thread if no ID provided)").action(async(X,Y,U)=>{let F=U.optsWithGlobals(),E=DK(),H=await IS(E,F);try{let w=X;if(!w){if(w=await L7A(),!w)S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`No thread ID provided and no previously used thread found.
|
4655
4655
|
Provide a thread ID as an argument or run a thread first.
|
4656
4656
|
`),process.exit(1)}if(!cR(w))throw new Qz(_Z.invalidThreadId);let I=await _Q(`/api/threads/${w}`);if(!I.ok)S2.write(`Failed to load thread ${w}: ${await I.text()}
|
4657
4657
|
`),process.exit(1);let W=await I.json(),M=AY(),N={id:M,messages:W.messages,title:W.title?`(fork) ${W.title}`:void 0,created:Date.now(),v:0};H.threadStorage.set(M,N);let O=await _Q(`/api/threads/${M}`,{method:"POST",body:JSON.stringify(N)});if(!O.ok){let R=await O.text().catch(()=>"Unable to read response body");throw new Error(`Failed to create forked thread on server: ${O.status}${R?`: ${R}`:""}`)}await bf1(M),Q5.write(`${M}
|
4658
|
-
`),
|
4659
|
-
`),process.exit(1)}}),B.command("list").description("List all your threads with their titles and share status").action(async(X,Y)=>{let U=Y.optsWithGlobals(),F=DK(),E=await IS(F,U);try{let H=await _Q("/api/user");if(!H.ok)S2.write(`Failed to get user info: ${H.status} ${await H.text()}
|
4658
|
+
`),await H.dispose(),process.exit(0)}catch(w){S2.write(`Error forking thread: ${w instanceof Error?w.message:String(w)}
|
4659
|
+
`),await H.dispose(),process.exit(1)}}),B.command("list").description("List all your threads with their titles and share status").action(async(X,Y)=>{let U=Y.optsWithGlobals(),F=DK(),E=await IS(F,U);try{let H=await _Q("/api/user");if(!H.ok)S2.write(`Failed to get user info: ${H.status} ${await H.text()}
|
4660
4660
|
`),process.exit(1);let I=(await H.json()).id,W=await _Q(`/api/threads?createdByUserID=${I}`);if(!W.ok)S2.write(`Failed to load threads: ${W.status} ${await W.text()}
|
4661
4661
|
`),process.exit(1);let M=await W.json();if(M.length===0)Q5.write(`No threads found.
|
4662
|
-
`),process.exit(0);let N=["Title","Last Updated","Visibility","Messages","Thread ID"],O=M.map((R)=>{let T=R.title||"Untitled",L="Team";if(R.meta.private)L="Private";else if(R.meta.public)L="Public";let j=q12(new Date(R.updatedAt));return[T,j,L,R.messageCount.toString(),R.id]});F12(N,O,{columnFormatters:[(R,T)=>{return(R.length>T?R.substring(0,T-3)+"...":R).padEnd(T)},void 0,void 0,(R,T)=>R.padStart(T),(R,T)=>F.printer.print(R.padEnd(T),{foreground:"green"})],truncateColumnIndex:0}),
|
4663
|
-
`),process.exit(1)}}),B.command("share <threadId>").description("Change thread visibility or share with support").option("--visibility <visibility>","Set thread visibility (private, public, team)").option("--support","Share thread with Amp support for debugging").action(async(X,Y,U)=>{let F=U.optsWithGlobals(),E=DK(),H=await IS(E,F);try{if(!cR(X))S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Invalid thread ID format.
|
4662
|
+
`),process.exit(0);let N=["Title","Last Updated","Visibility","Messages","Thread ID"],O=M.map((R)=>{let T=R.title||"Untitled",L="Team";if(R.meta.private)L="Private";else if(R.meta.public)L="Public";let j=q12(new Date(R.updatedAt));return[T,j,L,R.messageCount.toString(),R.id]});F12(N,O,{columnFormatters:[(R,T)=>{return(R.length>T?R.substring(0,T-3)+"...":R).padEnd(T)},void 0,void 0,(R,T)=>R.padStart(T),(R,T)=>F.printer.print(R.padEnd(T),{foreground:"green"})],truncateColumnIndex:0}),await E.dispose(),process.exit(0)}catch(H){S2.write(`Error listing threads: ${H instanceof Error?H.message:String(H)}
|
4663
|
+
`),await E.dispose(),process.exit(1)}}),B.command("share <threadId>").description("Change thread visibility or share with support").option("--visibility <visibility>","Set thread visibility (private, public, team)").option("--support","Share thread with Amp support for debugging").action(async(X,Y,U)=>{let F=U.optsWithGlobals(),E=DK(),H=await IS(E,F);try{if(!cR(X))S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Invalid thread ID format.
|
4664
4664
|
`),process.exit(1);let{support:w}=Y,I=y91(Y);if(!I&&!w)S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Must specify either --visibility or --support
|
4665
4665
|
`),process.exit(1);if(I&&w)S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Cannot specify both --visibility and --support at the same time
|
4666
4666
|
`),process.exit(1);if(I instanceof Error)S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+I.message),process.exit(1);let W=null;if(I)await H.threadSyncService.updateThreadMeta(X,b91(I)),Q5.write(E.printer.print("✓ ",{foreground:"green"})+`Thread ${X} visibility changed to ${I}.
|
4667
4667
|
`);if(w){let M=await _Q(`/api/threads/${X}`);if(!M.ok)S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Failed to load thread ${X}: ${await M.text()}
|
4668
4668
|
`),process.exit(1);W=await M.json(),H.threadStorage.set(X,W),await Gr1(H.threadService,X),Q5.write(E.printer.print("✓ ",{foreground:"green"})+`Thread ${X} has been shared with Amp support.
|
4669
|
-
`)}
|
4670
|
-
`),
|
4669
|
+
`)}await H.dispose(),process.exit(0)}catch(w){S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Failed to update thread: ${w instanceof Error?w.message:String(w)}
|
4670
|
+
`),await H.dispose(),process.exit(1)}}),B.command("compact <threadId>").description("Compact a thread by creating a summary to reduce token usage").action(async(X,Y,U)=>{let F=U.optsWithGlobals(),E=DK(),H=await IS(E,F);try{if(!cR(X))S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Invalid thread ID format.
|
4671
4671
|
`),process.exit(1);let w=await _Q(`/api/threads/${X}`);if(!w.ok)S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Failed to load thread ${X}: ${await w.text()}
|
4672
4672
|
`),process.exit(1);let I=await w.json();H.threadStorage.set(X,I),Q5.write(`Compacting thread ${X}...
|
4673
4673
|
`);let W={...H,getThreadEnvironment:gv1,createFileSystem:()=>lM,createFileChangeTrackerForThread:(T)=>{let L=new kL(lM);return UX1(L,lM,T)}},M=await fK.getOrCreateForThread(W,X);try{await M.summarizeThread()}catch(T){S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Failed to compact thread. ${T instanceof Error?T.message:"Unknown error"}
|
4674
4674
|
`),process.exit(1)}let N=WH(M.thread);if(!N||N.summaryBlock.summary.type!=="message")S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Failed to compact thread. No summary produced.
|
4675
4675
|
`),process.exit(1);let O=N.summaryBlock.summary.summary,R=O.length>100?O.slice(0,100)+"...":O;Q5.write(E.printer.print("✓ ",{foreground:"green"})+`Thread ${X} compacted successfully.
|
4676
4676
|
Summary: ${R}
|
4677
|
-
`),await H.
|
4678
|
-
`),
|
4677
|
+
`),await H.dispose(),process.exit(0)}catch(w){S2.write(E.printer.print("Error: ",{foreground:"red",style:"bold"})+`Failed to compact thread: ${w instanceof Error?w.message:String(w)}
|
4678
|
+
`),await H.dispose(),process.exit(1)}}),Q.command("tools").description("Tool management commands").command("show").description("Show available tools").action(async(X,Y)=>{try{let U=Y.optsWithGlobals(),F=DK(),E=Vp({settingsFile:U.settingsFile}),H=xv1(Rp());BB1({storage:E,secretStorage:H,workspaceRoots:UA.of([t6.file(process.cwd())]),defaultAmpURL:F.ampURL});let w=Kv();tP1(w);let I=await C6(w.tools);S2.write(`# ${I.length} tools
|
4679
4679
|
`),S2.write(`
|
4680
4680
|
`);for(let W of I){if(S2.write(`## ${W.spec.name}${!W.enabled?" (disabled)":""}
|
4681
4681
|
`),W.spec.description)S2.write(F.printer.print(`${W.spec.description}`,{foreground:"gray"})+`
|
@@ -4691,16 +4691,16 @@ Summary: ${R}
|
|
4691
4691
|
`),S2.write(`Secrets have been automatically redacted, but please review the file before attaching
|
4692
4692
|
`),S2.write(`it to support requests. Learn more at https://ampcode.com/manual/appendix#support-bundles
|
4693
4693
|
`),process.exit(0)}catch(U){S2.write(A.printer.print("Error generating support bundle: ",{foreground:"red"})+`${U instanceof Error?U.message:String(U)}
|
4694
|
-
`),process.exit(1)}}),Q.addCommand(K);let Z=new eu("update").description("Update Amp CLI to the latest version").option("--version <version>","Update to a specific version").allowUnknownOption(!1);Z.action(async(X,Y)=>{try{let U=Y.optsWithGlobals(),{update:F}=await Promise.resolve().then(() => (R7A(),V7A)),{checkNpmUpdate:E}=await Promise.resolve().then(() => (iG1(),qr1)),H="0.0.
|
4694
|
+
`),process.exit(1)}}),Q.addCommand(K);let Z=new eu("update").description("Update Amp CLI to the latest version").option("--version <version>","Update to a specific version").allowUnknownOption(!1);Z.action(async(X,Y)=>{try{let U=Y.optsWithGlobals(),{update:F}=await Promise.resolve().then(() => (R7A(),V7A)),{checkNpmUpdate:E}=await Promise.resolve().then(() => (iG1(),qr1)),H="0.0.1753448050-g0871b6";if(U.version)S2.write(C0.blue(`Updating to version ${U.version}...
|
4695
4695
|
`)),await F(U.version),S2.write(C0.green(`✓ Successfully updated to version ${U.version}
|
4696
4696
|
`));else{S2.write(C0.blue(`Checking for updates...
|
4697
|
-
`));let w=await E("0.0.
|
4697
|
+
`));let w=await E("0.0.1753448050-g0871b6");if(!w.hasUpdate)S2.write(C0.green(`✓ Amp CLI is already up to date.
|
4698
4698
|
`)),process.exit(0);S2.write(C0.blue(`Updating to version ${w.latestVersion}...
|
4699
4699
|
`)),await F(w.latestVersion),S2.write(C0.green(`✓ Successfully updated to version ${w.latestVersion}
|
4700
4700
|
`))}process.exit(0)}catch(U){S2.write(C0.red("Error updating: ")+`${U instanceof Error?U.message:String(U)}
|
4701
4701
|
`),process.exit(1)}}),Q.addCommand(Z);let G=new eu("fuzzy-server").description("Internal fuzzy server").action(()=>{new zk1().start()});return Q.addCommand(G),Q}async function P7A(A,Q){let B=process.stdin,D=y91(Q);if(D instanceof Error)S2.write(C0.red.bold("Error: ")+D.message),process.exit(1);let J;if(typeof Q.execute==="string")J=Q.execute;else J=(await i8A()).trimEnd();if(A.executeMode&&J==="")throw new Qz("User message must be provided through stdin or as argument when using execute mode",1,`Pipe input to amp: echo "your message" | amp --execute
|
4702
4702
|
Or pass message as argument: amp --execute "your message"`);if(J!==""&&!A.executeMode&&typeof Q.execute!=="string")B=await l8A();let z=await IS(A,Q),K=AY();if(!1)try{}catch(U){}else if(Q.threadId){if(!cR(Q.threadId))throw new Qz(_Z.invalidThreadId);K=Q.threadId;try{let U=await J12(K);z.threadStorage.set(K,U)}catch(U){if(U instanceof Qz)throw U;n_(A,U,K)}}let Z=z.threadService.observe(K).subscribe(async(U)=>{if(ND(U,"assistant"))await bf1(K),Z.unsubscribe()});if(!(await C6(z.threadSyncService.threadSyncInfo([K])))[K])throw new Error(`Thread ${K} not found`);if(D)await z.threadSyncService.updateThreadMeta(K,b91(D));if(Q.format==="jsonl")S2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
4703
|
-
`),process.exit(1);let X={...z,getThreadEnvironment:gv1,createFileSystem:()=>lM,createFileChangeTrackerForThread:(U)=>{return UX1(new kL(lM),lM,U)}},Y=await fK.getOrCreateForThread(X,K);if(await Y.resume(),A.executeMode)await r2A(Y,K,J,z),process.exit(0);await N7A({stdin:B,pipedInput:J,stdout:process.stdout,history:new mv1,fuzzyServer:z.fuzzyServer,settingsStorage:z.settingsStorage,threadService:z.threadService,configService:z.configService,threadID:K,worker:Y,workerDeps:X,ampURL:A.ampURL}),process.exit(0)}function DK(A){if(A?.interactive)S2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
4703
|
+
`),process.exit(1);let X={...z,getThreadEnvironment:gv1,createFileSystem:()=>lM,createFileChangeTrackerForThread:(U)=>{return UX1(new kL(lM),lM,U)}},Y=await fK.getOrCreateForThread(X,K);if(await Y.resume(),A.executeMode)await r2A(Y,K,J,z),await z.dispose(),process.exit(0);await N7A({stdin:B,pipedInput:J,stdout:process.stdout,history:new mv1,fuzzyServer:z.fuzzyServer,settingsStorage:z.settingsStorage,threadService:z.threadService,configService:z.configService,threadID:K,worker:Y,workerDeps:X,ampURL:A.ampURL}),await z.dispose(),process.exit(0)}function DK(A){if(A?.interactive)S2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
4704
4704
|
`);let Q=!!A?.execute||!process.stdout.isTTY,B=process.stdout.isTTY&&process.stderr.isTTY,D=process.env.AMP_URL||qJ;return{executeMode:Q,isTTY:B,printer:B?A1A:Q1A,ampURL:D}}async function U12(){k2A({logLevel:process.env.AMP_LOG_LEVEL,logFile:process.env.AMP_LOG_FILE});let A=DK();if(S1.info("Starting Amp CLI."),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new Qz(_Z.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Y12(A).parseAsync(process.argv)}U12().catch((A)=>{let Q=DK();n_(Q,A)});function q12(A){let B=new Date().getTime()-A.getTime(),D=Math.floor(B/1000),J=Math.floor(D/60),z=Math.floor(J/60),K=Math.floor(z/24),Z=Math.floor(K/7),G=Math.floor(K/30),X=Math.floor(K/365);if(D<60)return D<=1?"now":`${D}s ago`;else if(J<60)return`${J}m ago`;else if(z<24)return`${z}h ago`;else if(K<7)return`${K}d ago`;else if(Z<4)return`${Z}w ago`;else if(G<12)return`${G}mo ago`;else return`${X}y ago`}function F12(A,Q,B={}){let{columnFormatters:D=[],minimumTruncatedColumnWidth:J=20,truncateColumnIndex:z}=B;for(let I=0;I<Q.length;I++)if(Q[I].length!==A.length)throw new Error(`Row ${I} has ${Q[I].length} columns, but headers have ${A.length} columns`);let K=Q5.columns||120,Z=" ",G=A.length-1,X=z??A.length-1,Y=[];for(let I=0;I<A.length;I++)if(I===X)Y.push(0);else Y.push(Math.max(A[I].length,...Q.map((W)=>W[I].length)));let U=Y.reduce((I,W)=>I+W,0)+G*Z.length,F=Math.max(J,K-U);Y[X]=F;let E=Y,H=A.map((I,W)=>I.padEnd(E[W])).join(Z);Q5.write(H+`
|
4705
4705
|
`);let w=E.map((I)=>"─".repeat(I)).join(Z);Q5.write(w+`
|
4706
4706
|
`);for(let I of Q){let W=I.map((M,N)=>{let O=E[N],R=D[N];if(R)return R(M,O);return(M.length>O?M.substring(0,O-3)+"...":M).padEnd(O)});Q5.write(W.join(Z)+`
|
package/package.json
CHANGED