@sourcegraph/amp 0.0.1766217674-gf10025 → 0.0.1766222627-g05555f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +10 -10
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -365,7 +365,7 @@ ${G.content}
365
365
  `);if(!Q)return null;return Q}function ny0(J){let Q=J.filter((Z)=>!Z.frontmatter["disable-model-invocation"]);if(Q.length===0)return null;let Y=Q.map((Z)=>{return[" <skill>",` <name>${Z.name}</name>`,` <description>${Z.description}</description>`,` <location>${Z.baseDir}/SKILL.md</location>`," </skill>"].join(`
366
366
  `)}).join(`
367
367
  `);return["The following skills provide specialized instructions for specific tasks.",`Use the ${Kq} tool to load a skill when the task matches its description.`,"",'Loaded skills appear as `<loaded_skill name="...">` in the conversation.',"","<available_skills>",Y,"</available_skills>"].join(`
368
- `)}var ly0,Sf4,PB=64,XT,aA1=1024,oA1=500,kf4,yf4="mcp.json";var AA=$1(()=>{Y4();N0();W2();x4();Bq1();ly0=Q6(EB(),1),Sf4=new Set(["name","description","license","compatibility","metadata","allowed-tools","argument-hint","model","disable-model-invocation","mode","isolatedContext"]),XT=/^[a-z0-9](?:[a-z0-9]*(?:-[a-z0-9]+)*)?$/;kf4=/^skill\.md$/i});function Nb4(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(J)}class Qf{fs;constructor(J){this.fs=J}async store(J,Q,Y){let Z=this.backupDirForThread(J);if(!Z)return;await this.fs.mkdirp(Z);let X=i0.joinPath(Z,this.filename(Q));await this.fs.writeFile(X,JSON.stringify(Y,null,2))}async load(J,Q){let Y=this.backupDirForThread(J);if(!Y)return null;try{let Z=await this.fs.readFile(i0.joinPath(Y,this.filename(Q)));return JSON.parse(Z)}catch(Z){return v.error(`Error loading backup file ${this.filename(Q)}:`,Z),null}}async list(J){let Q=this.backupDirForThread(J);if(!Q)return[];await this.fs.mkdirp(Q);try{let Y=await this.fs.readdir(Q),Z=[];for(let X of Y){let G=i0.relativePath(Q,X.uri);if(!G)continue;let V=G.split(".");if(V.length===2){let K=V[0],q=V[1];if(K&&Nb4(q))Z.push({toolUseID:K,fileChangeID:q})}}return Z}catch(Y){return v.error("Error listing backup files:",Y),[]}}async cleanup(J){let Q=this.backupDirForThread(J);if(!Q)return;try{await this.fs.delete(Q,{recursive:!0})}catch(Y){if(!UQ(Y))v.error(`Error cleaning up backup files in ${Q}:`,Y)}}filename(J){return`${J.toolUseID}.${J.fileChangeID}`}backupDirForThread(J){let Q=typeof process<"u"?process.env.HOME:null;if(!Q)return null;return i0.joinPath(m0.file(Q),".amp","file-changes",J)}}var QO1;var He=$1(()=>{Y4();N0();tQ();QO1={async store(){},async load(){return null},async list(){return[]},async cleanup(){}}});function XF(J,Q){if(J=J.replace(/\.git$/,""),!URL.canParse(J))return null;let Y=new URL(J);if(Y.protocol!=="https:"||Y.port||Y.username||Y.password)return null;let Z=Y.pathname.replace(/^\//,"").replace(/\/$/,"");if(!Z)return null;let X=`${Y.protocol}//${Y.host}`;if(Y.hostname==="github.com"){if(Q?.provider&&Q.provider!=="github")return null;return{name:Z,instanceURL:"https://github.com",provider:"github"}}if(!Q?.gitlabInstanceURL)return null;let G=new URL(Q.gitlabInstanceURL);if(Y.protocol===G.protocol&&Y.host===G.host){if(Q?.provider&&Q.provider!=="gitlab")return null;return{name:Z,instanceURL:X,provider:"gitlab"}}return null}class JY{bits;constructor(J){this.bits=J}static empty(){return new JY(0n)}static fromString(J){let Q=0n;for(let Y=0;Y<J.length;Y++){let Z=J.charCodeAt(Y),X=JY.charToBitIndex(Z);if(X>=0)Q|=1n<<BigInt(X)}return new JY(Q)}static fromPath(J){let Q=0n,Y=J.split(/[/\\]/);for(let Z of Y){if(Z===""||Z==="."||Z==="..")continue;for(let X=0;X<Z.length;X++){let G=Z.charCodeAt(X),V=JY.charToBitIndex(G);if(V>=0)Q|=1n<<BigInt(V)}}return new JY(Q)}hasChars(J){return(this.bits&J.bits)===J.bits}union(J){return new JY(this.bits|J.bits)}intersection(J){return new JY(this.bits&J.bits)}isEmpty(){return this.bits===0n}getCharCount(){return this.bits.toString(2).split("").filter((J)=>J==="1").length}toString(){let J=[];for(let Q=0;Q<64;Q++)if((this.bits&1n<<BigInt(Q))!==0n){let Y=JY.bitIndexToChar(Q);if(Y)J.push(Y)}return`CharBag{${J.join("")}}`}toJSON(){return{bits:this.bits.toString()}}static fromJSON(J){return new JY(BigInt(J.bits))}equals(J){return this.bits===J.bits}static charToBitIndex(J){if(J>=65&&J<=90)J+=32;if(J>=48&&J<=57)return J-48;if(J>=97&&J<=122)return J-97+10;return-1}static bitIndexToChar(J){if(J>=0&&J<=9)return String.fromCharCode(48+J);if(J>=10&&J<=35)return String.fromCharCode(97+J-10);return null}}class $Z{id;kind;path;uri;charBag;metadata;isIgnored;isExternal;isPrivate;isAlwaysIncluded;constructor(J){this.id=J.id,this.kind=J.kind,this.path=J.path,this.uri=J.uri,this.metadata=J.metadata,this.isIgnored=J.isIgnored??!1,this.isExternal=J.isExternal??!1,this.isPrivate=J.isPrivate??!1,this.isAlwaysIncluded=J.isAlwaysIncluded??!1,this.charBag=JY.fromPath(this.path)}withUpdates(J){return new $Z({id:this.id,kind:J.kind??this.kind,path:this.path,uri:this.uri,metadata:J.metadata??this.metadata,isIgnored:J.isIgnored??this.isIgnored,isExternal:J.isExternal??this.isExternal,isPrivate:J.isPrivate??this.isPrivate,isAlwaysIncluded:J.isAlwaysIncluded??this.isAlwaysIncluded})}isFile(){return this.kind==="file"}isDirectory(){return this.kind==="directory"||this.kind==="unloaded-directory"||this.kind==="pending-directory"}isLoadedDirectory(){return this.kind==="directory"}getFilename(){return this.path.split(/[/\\]/).pop()||this.path}getExtension(){let J=this.getFilename(),Q=J.lastIndexOf(".");return Q>0?J.slice(Q+1):""}getDirectory(){let J=this.path.split(/[/\\]/);return J.length>1?J.slice(0,-1).join("/"):""}shouldIncludeInResults(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;return!0}shouldIncludeInMentions(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;if(this.isFile())return!0;return this.isLoadedDirectory()}getImportanceBoost(){return this.isAlwaysIncluded?0.1:0}toJSON(){return{id:this.id,kind:this.kind,path:this.path,uri:this.uri.toString(),metadata:this.metadata,isIgnored:this.isIgnored,isExternal:this.isExternal,isPrivate:this.isPrivate,isAlwaysIncluded:this.isAlwaysIncluded,charBag:this.charBag.toJSON()}}static fromJSON(J,Q){return new $Z({id:J.id,kind:J.kind,path:J.path,uri:Q(J.uri),metadata:J.metadata,isIgnored:J.isIgnored,isExternal:J.isExternal,isPrivate:J.isPrivate,isAlwaysIncluded:J.isAlwaysIncluded})}equals(J){return this.id===J.id&&this.kind===J.kind&&this.path===J.path&&this.metadata.mtime===J.metadata.mtime&&this.metadata.size===J.metadata.size}hashCode(){return`${this.path}:${this.metadata.mtime}:${this.metadata.size}`}toString(){return`Entry{${this.kind}:${this.path}}`}}var KT=()=>{};class Fe{config;queryChars;queryLower;constructor(J,Q={}){this.config={...Db4,...Q};let Y=J.replace(/^[@#]+/,"");if(this.queryChars=Array.from(Y),this.queryLower=Array.from(Y.toLowerCase()),this.config.smartCase)this.config.caseSensitive=Y!==Y.toLowerCase()}match(J){if(this.queryChars.length===0)return J.filter((Y)=>Y.shouldIncludeInResults()).map((Y)=>{let Z=this.config.openFiles?.includes(Y.path)?500:0,X=this.config.dirtyFiles?.includes(Y.path)?300:0,G=Y.getImportanceBoost()+Z+X;return{entry:Y,score:G,matchPositions:[],highlightedPath:Y.path}}).sort((Y,Z)=>Z.score-Y.score).slice(0,this.config.maxResults);let Q=this.matchWithSemanticScoring(J);if(Q.length>0)return Q;return this.matchWithFuzzyScoring(J)}matchWithSemanticScoring(J){let Q=[],Y=0,Z=50000,X=this.queryChars.join(""),G=J.filter((K)=>K.shouldIncludeInResults()&&this.passesCharBagFilter(X,K)),V=(K)=>{let q=this.matchEntrySemantic(K);if(q&&q.score>=this.config.minScore)Q.push(q);return Y++,Y>=Z};for(let K of G)if(K.isDirectory()){if(V(K))break}if(Y<Z){for(let K of G)if(!K.isDirectory()){if(V(K))break}}return Q.sort((K,q)=>{let W=q.score-K.score;if(Math.abs(W)>0.001)return W;return K.entry.path.length-q.entry.path.length}),Q.slice(0,this.config.maxResults)}matchWithFuzzyScoring(J){let Q=[],Y=0,Z=50000,X=this.queryChars.join(""),G=J.filter((K)=>K.shouldIncludeInResults()&&this.passesCharBagFilter(X,K)),V=(K)=>{let q=this.matchEntryFuzzy(K);if(q)Q.push(q);return Y++,Y>=Z};for(let K of G)if(K.isDirectory()){if(V(K))break}if(Y<Z){for(let K of G)if(!K.isDirectory()){if(V(K))break}}return Q.sort((K,q)=>{let W=q.score-K.score;if(Math.abs(W)>0.001)return W;return K.entry.path.length-q.entry.path.length}),Q.slice(0,this.config.maxResults)}matchEntrySemantic(J){let Q=J.path,Y=this.queryLower.join(""),Z=this.calculateSemanticScore(Y,J);if(Z===0)return null;let X=this.applyTieBreakers(Z,Y,J),G=this.findMatchPositions(Y,Q),V=this.createHighlightedPath(Q,G);return{entry:J,score:X,matchPositions:G,highlightedPath:V}}matchEntryFuzzy(J){let Q=J.path,Y=this.queryLower.join(""),Z=this.calculateFuzzyScore(Y,J);if(Z===0)return null;let X=this.applyTieBreakers(Z,Y,J),G=this.findMatchPositions(Y,Q),V=this.createHighlightedPath(Q,G);return{entry:J,score:X,matchPositions:G,highlightedPath:V}}calculateSemanticScore(J,Q){let Y=J.toLowerCase(),Z=Q.path,X=Z.toLowerCase(),G=this.getFilename(Z),V=this.removeExtension(G).toLowerCase(),K=X.split(/[/\\.\s-_]/).filter((F)=>F.length>0);if(J.endsWith("/")&&Q.isDirectory()){let F=Y.slice(0,-1);if(X===F||X.endsWith("/"+F))return QY.EXACT_FILENAME+100;if(X.includes(F))return QY.SUBSTRING_FILENAME+50}if(V===Y||G.toLowerCase()===Y)return QY.EXACT_FILENAME;if(V.startsWith(Y))return QY.PREFIX_FILENAME;if(V.endsWith(Y))return QY.SUFFIX_FILENAME;if(V.includes(Y))return QY.SUBSTRING_FILENAME;let q=this.simpleTokens(Y);if(q.length>1){let F=this.matchTokensToSegments(q,K);if(F)return F}if(q.length===1&&Y.length>6){let F=this.progressiveSegmentMatch(Y,K);if(F)return F}if(K.includes(Y))return QY.SEGMENT_EXACT;if(K.some((F)=>F.includes(Y)))return QY.SEGMENT_SUBSTRING;if(K.join("").includes(Y))return QY.SEGMENT_SUBSTRING;if(X.replace(/[\s-_]/g,"").includes(Y))return QY.PATH_SUBSTRING;return 0}calculateFuzzyScore(J,Q){let Y=J.toLowerCase(),Z=Q.path.toLowerCase();if(this.fuzzyIn(Y,Z))return QY.FUZZY;return 0}applyTieBreakers(J,Q,Y){let Z=J,X=Math.abs(Y.path.length-Q.length);Z-=0.01*X;let G=Y.path.split(/[/\\]/).length-1;Z-=0.1*G;let V=this.getFilename(Y.path),K=this.removeExtension(V).toLowerCase();if(/^(license|readme|copy(ing|left))$/i.test(K)&&G===1)Z-=200;if(Y.metadata.mtime){let W=(Date.now()-Y.metadata.mtime)/86400000;if(W<30){let H=Math.max(0,1-W/30);Z+=50*H}}if(this.config.openFiles?.includes(Y.path))Z+=500;if(this.config.dirtyFiles?.includes(Y.path))Z+=300;return Z}simpleTokens(J){return J.replace(/([a-z])([A-Z0-9])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}progressiveSegmentMatch(J,Q){let Y=0,Z=0,X=0;for(let V of Q){if(Y>=J.length)break;let K="",q="none";if(Y+V.length<=J.length){if(J.slice(Y,Y+V.length)===V)K=V,q="exact"}if(!K&&V.length>=3){if(J.slice(Y).startsWith(V))K=V,q="prefix"}if(!K&&V.length>=3){let W=J.slice(Y);if(W.includes(V)&&W.indexOf(V)===0)K=V,q="substring"}if(!K){let W=J.slice(Y);if(W.length>=3&&V.includes(W))K=W,q="substring"}if(K){if(Y+=K.length,Z++,q==="exact")X++}}if(Y/J.length>=0.8&&Z>=2)return X>=2?QY.SEGMENT_ORDERED_EXACT:QY.SEGMENT_ORDERED_PARTIAL;return 0}matchTokensToSegments(J,Q){let Y=this.findTokenMatches(J,Q),Z=this.getWorstMatchType(Y);return this.scoreFromMatchType(Z)}findTokenMatches(J,Q){let Y=0,Z=[];for(let X of J){let G=!1;for(let V=Y;V<Q.length;V++){let K=Q[V];if(!K)continue;if(X===K){Z.push("exact"),Y=V+1,G=!0;break}else if(K.startsWith(X)||X.startsWith(K)||K.endsWith(X)||K.includes(X)||X.includes(K)){Z.push("partial"),Y=V+1,G=!0;break}}if(!G)return[]}return Z}getWorstMatchType(J){if(J.length===0)return"none";if(J.includes("partial"))return"partial";return"exact"}scoreFromMatchType(J){switch(J){case"exact":return QY.SEGMENT_ORDERED_EXACT;case"partial":return QY.SEGMENT_ORDERED_PARTIAL;default:return 0}}fuzzyIn(J,Q){let Y=0;for(let Z=0;Z<Q.length&&Y<J.length;Z++)if(Q[Z]===J[Y])Y++;return Y===J.length}getFilename(J){return J.split(/[/\\]/).pop()||J}removeExtension(J){let Q=J.lastIndexOf(".");return Q>0?J.substring(0,Q):J}findMatchPositions(J,Q){let Y=[],Z=Q.toLowerCase(),X=J.toLowerCase();if(Z.includes(X)){let V=Z.indexOf(X);for(let K=0;K<X.length;K++)Y.push(V+K);return Y}let G=0;for(let V of X){let K=Z.indexOf(V,G);if(K!==-1)Y.push(K),G=K+1}return Y}passesCharBagFilter(J,Q){if(J.includes("/")||J.includes("\\")){let Y=J.split(/[/\\]/);for(let Z of Y){if(Z.trim()==="")continue;let X=JY.fromString(Z);if(!Q.charBag.hasChars(X))return!1}return!0}else{let Y=JY.fromString(J);return Q.charBag.hasChars(Y)}}createHighlightedPath(J,Q){if(Q.length===0)return J;let Y="",Z=0;for(let X of Q){if(X>=J.length)continue;Y+=J.slice(Z,X),Y+=`**${J[X]}**`,Z=X+1}return Y+=J.slice(Z),Y}}function qT(J,Q,Y){return new Fe(J,Y).match(Q)}var Db4,QY;var Yf=$1(()=>{Db4={minScore:400,caseSensitive:!1,penalizeLengthDifference:!0,maxResults:50,smartCase:!0},QY={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}});async function a3(J,Q={},Y){let Z=`/api/internal/github-proxy/${J}`,{body:X,headers:G={},method:V="GET",...K}=Q,q=await _L1(Y,Z,{method:V,headers:G,body:X?JSON.stringify(X):void 0,...K});if(q.status===304)return{ok:!0,status:q.status,notModified:!0,headers:{etag:q.headers.get("etag")||void 0}};if(!q.ok)return{ok:!1,status:q.status,statusText:q.statusText};let W=await q.json();return{ok:!0,status:q.status,data:W,headers:{location:q.headers.get("location")||void 0,etag:q.headers.get("etag")||void 0}}}var kq=$1(()=>{BQ()});async function Dx0(J,Q,Y,Z,X){let G=XF(J,{provider:"github"})?.name;if(!G)throw Error("Invalid GitHub repository URL");let{filePattern:V,limit:K,offset:q=0}=Y,W=`repos/${G}/git/trees/${Q??"HEAD"}?recursive=1`,H=await a3(W,{signal:Z},X);if(!H.ok||!H.data)throw Error(`Failed to fetch files: ${H.status} ${H.statusText||"Unknown error"}`);let U=H.data.tree.filter((A)=>A.type==="blob").map((A)=>A.path),B=Nx0.default(V),M=U.filter((A)=>B(A));return{files:K?M.slice(q,q+K):M.slice(q),truncated:H.data.truncated}}var Nx0;var Mx0=$1(()=>{kq();Nx0=Q6(dy(),1)});function Lx0(J,Q,Y,Z){let X=new Map,G=async()=>{try{let H;if(Z)H=await J.get(Z);else H=J.getRecentlyActiveThread();if(H){let F=H.id,U=H.env?.initial.trees||[];if(v.info("Found thread:",F,"trees:",U.length),U.length>0)return v.info("Using trees from thread:",F),{trees:U,threadId:F};else v.info("Thread has no trees")}else v.info("No thread found");return null}catch(H){return v.error("Error getting thread:",H),null}},V=async(H)=>{if(!H.repository||!H.repository.url||!H.repository.sha)return[];let F=H.repository,U=F.sha,B=Date.now(),M=`${F.url}:${U}`,L=X.get(M);if(L&&B-L.timestamp<300000)return L.entries;try{let A=await Dx0(F.url,U,{filePattern:"**/*",limit:1e4},void 0,Y),I=A.files.map((P)=>{let R={mtime:Date.now(),size:0,inode:0,isSymlink:!1},C=m0.file(`/${P}`);return new $Z({id:`github:${F.url}:${U}:${P}`,kind:"file",path:P,uri:C,metadata:R})}),E={entries:I,timestamp:B,repoUrl:F.url,sha:U};if(X.set(M,E),A.truncated)v.warn("GitHub repository file listing was truncated",{repo:F.url,indexedFiles:I.length});return I}catch(A){return v.error("Failed to fetch files from GitHub API",A),[]}},K=async(H)=>{try{return(await Q.searchResources(H)).map(({resource:U,serverName:B})=>Mb4(U,B)).slice(0,Math.min(5,$B))}catch(F){return v.warn("Failed to search MCP resources",F),[]}},q=(H)=>{return Q.searchPrompts(H)},W=(H)=>{return H.map((F)=>{let U=F.path,B=`@${GB(U)}`,M=U.split("/"),L=M[M.length-1]||U,A=M.length>1?M.slice(0,-1).join("/"):"";return{uri:v6(F.uri),label:L,detail:A,insertText:B,filterText:U.toLowerCase(),kind:F.isDirectory()?"folder":"file"}})};return{search(H){let F=q(H),U=J4(async()=>{let B=await G();if(!B)return v.info("No thread with trees found, using MCP resources only"),await K(H);let{trees:M,threadId:L}=B,A=M.find((C)=>C.repository?.url!=null&&C.repository?.sha!=null);if(!A)return v.info("No GitHub repository found in thread trees, using MCP resources only"),await K(H);v.info("Found GitHub repository",{threadId:L,uri:A.uri,repoUrl:A.repository.url,sha:A.repository.sha});let[I,E]=await Promise.all([V(A),K(H)]);if(I.length===0)return E;let P;if(!H)v.info("Empty query, returning first 10 files"),P=I.slice(0,10);else try{P=qT(H,I,{maxResults:50,minScore:400}).map((S)=>S.entry)}catch(C){return v.error("Fuzzy search failed",C),E}return[...W(P),...E]});return h8(F,U).pipe(X6(([B,M])=>{return[...B,...M].slice(0,$B)}))},dispose(){X.clear()}}}function Mb4(J,Q){let Y=J.title||J.name,Z=J.description?`${J.description} (${Q})`:`MCP Resource from ${Q}`,X=`${Q}:${J.uri}`,G="@"+GB(X);return{uri:Ty(X),label:Y,detail:Z,insertText:G,filterText:`${Y} ${Z} ${J.uri}`.toLowerCase()}}var Ax0=$1(()=>{Y4();s0();N0();KT();Yf();Qh();Mx0()});function Zf(J){if(!J.startsWith("refs/heads/"))return null;return J.slice(11)}function Ue(J){let Q=zP(J);if(Object.values(Q).reduce((Y,Z)=>Y+Z,0)>0)return!0;for(let Y of J.messages){if(Y.role!=="assistant")continue;for(let Z of Y.content){if(Z.type==="tool_use"&&Z.name==="delete_file"){if(kH(J,Z.id)?.run.status==="done")return!0}if(Z.type==="tool_use"&&Z.name==="Bash"&&Z.input&&"cmd"in Z.input){if(String(Z.input.cmd).match(/^\s*(rm|mv)\s+/)){if(kH(J,Z.id)?.run.status==="done")return!0}}}}return!1}var YO1=$1(()=>{U8()});function Lb4(J){let Q="id"in J&&typeof J.id==="string"?J.env?.initial?.trees?.find((X)=>X.repository?.url):J;if(!Q?.repository?.url)return null;let Y=XF(Q.repository.url,{provider:"github"});if(!Y||Y.provider!=="github")return null;let Z=Q.repository.headRef?Zf(Q.repository.headRef):null;return{repo:Y.name,branch:Z,provider:"github"}}async function Ab4({repo:J,branch:Q},Y,Z){if(!Q)return null;try{let X=J.split("/")[0],G=`repos/${J}/pulls?head=${encodeURIComponent(X)}:${encodeURIComponent(Q)}&state=all&sort=created&direction=desc&per_page=1&page=1`,V=await a3(G,{signal:Z,cache:"no-cache"},Y);if(!V.ok||!V.data)return null;let K=V.data;if(K.length>0){let q=K[0],W=q.state==="closed"&&q.merged_at!==null;return{url:v6(m0.parse(q.html_url)),number:q.number.toString(),merged:W}}return null}catch(X){return v.debug("Failed to check GitHub pull request status:",X),null}}function Ox0(J,Q,Y,Z){let X=J.observe(Q).pipe(X6((G)=>[{id:G.id,env:G.env},G.messages.length>=2&&Ue(G)]),I4());return h8(X,Z.pipe(d8(void 0),a7((G)=>{return v.error("pullRequestChanges subject error, continuing with undefined",{error:G,threadID:Q}),Q0.of(void 0)}))).pipe(bZ(([[G,V]])=>{if(!G||!V)return Q0.of([]);let K=Lb4(G);if(!K)return Q0.of([]);let W=G.env?.initial?.trees?.find((H)=>H.repository?.url)?.repository?.pullRequestURL;return J4(async(H)=>{if(W&&!K.branch){let U=W.split("/").pop()||"";try{let B=`repos/${K.repo}/pulls/${U}`,M=await a3(B,{signal:H,cache:"no-cache"},Y);if(M.ok&&M.data){let L=M.data;return[{type:L.state==="closed"&&L.merged_at!==null?"view-merged-pull-request":"view-pull-request",url:v6(m0.parse(L.html_url)),number:L.number.toString()}]}}catch(B){v.debug("Failed to fetch specific PR:",B)}}let F=await Ab4(K,Y,H);if(F)return[{type:F.merged?"view-merged-pull-request":"view-pull-request",url:F.url,number:F.number}];return[{type:"create-pull-request"}]})}),z8({shouldCountRefs:!0}))}var Ix0=$1(()=>{Y4();s0();N0();YO1();kq()});async function Xf(J,Q){let Y=Q.config.settings.url;if(!Y)throw Error("amp.url is not set");let Z=await Q.config.secrets.getToken("gitlab-access-token",Y);if(!Z)return{ok:!1,status:401,statusText:"GitLab access token is not set"};let X=await Q.config.secrets.getToken("gitlab-instance-url",Y)??Ob4;return Ib4(J,{...Q,auth:{instanceURL:X,accessToken:Z}})}async function Ib4(J,{auth:Q,...Y}){let Z=`${Q.instanceURL.replace(/\/+$/,"")}/api/v4`,X=J.startsWith("http")?J:`${Z}${J}`,{body:G,headers:V={}}=Y,K={"Content-Type":"application/json",Authorization:`Bearer ${Q.accessToken}`,...V};try{let q=await fetch(X,{...Y,body:G?JSON.stringify(G):void 0,headers:K}),W=void 0,H=void 0;if(Y.method!=="HEAD"&&q.status!==204)try{H=await q.text(),W=JSON.parse(H)}catch(F){v.info("GitLab API response not JSON:",{url:X,status:q.status,responseText:H?.substring(0,200)})}return v.debug("GitLab API response:",{url:X,ok:q.ok,status:q.status,statusText:q.statusText,hasData:!!W,dataKeys:W&&typeof W==="object"?Object.keys(W):void 0,responseTextLength:H?.length}),{data:W,ok:q.ok,status:q.status,statusText:q.statusText}}catch(q){return v.error(`GitLab API request error (${X}):`,q),{ok:!1,status:0,statusText:q instanceof Error?q.message:String(q)}}}var Ob4="https://gitlab.com";var ZO1=$1(()=>{N0()});function wx0(J){let Q=J.replace(/\.git$/,"");try{return new URL(Q).pathname.replace(/^\//,"")}catch{return Q.match(/https?:\/\/[^/]+\/(.+)/)?.[1]??Q}}function wb4(J){if(J.includes("**")){let Q=J.replace(/\*\*\//g,"");if(Q.includes("*"))return Q}if(J.includes("*")&&!J.includes("/"))return J;return null}async function Eb4(J,Q,Y,Z){let{filePattern:X,limit:G=100,offset:V=0}=Y,K=wb4(X);if(!K)return null;let q=encodeURIComponent(J),W=Math.floor(V/G)+1,H=`/projects/${q}/search?scope=blobs&search=path:${encodeURIComponent(K)}&per_page=${G}&page=${W}&ref=${Q}`;try{let F=await Xf(H,{config:Z});if(!F.ok||!F.data)return null;let U=new Set(F.data.map((A)=>A.path)),B=Array.from(U),M=XO1.default(X);return{files:B.filter((A)=>M(A)),truncated:F.data.length===G}}catch(F){return null}}async function Pb4(J,Q,Y,Z){let{filePattern:X,limit:G,offset:V=0}=Y,q=`/projects/${encodeURIComponent(J)}/repository/tree?recursive=true&ref=${Q}&per_page=1000&pagination=keyset`,W=await Xf(q,{config:Z});if(!W.ok||!W.data)throw Error(`Failed to fetch files: ${W.status} ${W.statusText||"Unknown error"}`);let F=W.data.filter((L)=>L.type==="blob").map((L)=>L.path),U=XO1.default(X),B=F.filter((L)=>U(L));return{files:G?B.slice(V,V+G):B.slice(V),truncated:W.data.length===1000}}async function Ex0(J,Q,Y,Z){let X=wx0(J);if(!X)throw Error(`Invalid GitLab repository URL: ${J}`);let G=await Eb4(X,Q,Y,Z);if(G)return G;return Pb4(X,Q,Y,Z)}var XO1;var Px0=$1(()=>{ZO1();XO1=Q6(dy(),1)});function Rx0(J,Q,Y,Z){let X=new Map,G=async()=>{try{let H;if(Z)H=await J.get(Z);else H=J.getRecentlyActiveThread();if(H){let F=H.id,U=H.env?.initial.trees||[];if(v.info("Found thread:",F,"trees:",U.length),U.length>0)return v.info("Using trees from thread:",F),{trees:U,threadId:F};else v.info("Thread has no trees")}else v.info("No thread found");return null}catch(H){return v.error("Error getting thread:",H),null}},V=async(H)=>{if(!H.repository||!H.repository.url||!H.repository.sha)return[];let F=H.repository,U=F.sha,B=Date.now(),M=`${F.url}:${U}`,L=X.get(M);if(L&&B-L.timestamp<300000)return L.entries;try{let A=await Ex0(F.url,U,{filePattern:"**/*",limit:1e4},Y),I=A.files.map((P)=>{let R={mtime:Date.now(),size:0,inode:0,isSymlink:!1},C=m0.file(`/${P}`);return new $Z({id:`gitlab:${F.url}:${U}:${P}`,kind:"file",path:P,uri:C,metadata:R})}),E={entries:I,timestamp:B,repoUrl:F.url,sha:U};if(X.set(M,E),A.truncated)v.warn("GitLab repository file listing was truncated",{repo:F.url,indexedFiles:I.length});return I}catch(A){return v.error("Failed to fetch files from GitLab API",A),[]}},K=async(H)=>{try{return(await Q.searchResources(H)).map(({resource:U,serverName:B})=>Rb4(U,B)).slice(0,Math.min(5,$B))}catch(F){return v.warn("Failed to search MCP resources",F),[]}},q=(H)=>{return Q.searchPrompts(H)},W=(H)=>{return H.map((F)=>{let U=F.path,B=`@${GB(U)}`,M=U.split("/"),L=M[M.length-1]||U,A=M.length>1?M.slice(0,-1).join("/"):"";return{uri:v6(F.uri),label:L,detail:A,insertText:B,filterText:U.toLowerCase(),kind:F.isDirectory()?"folder":"file"}})};return{search(H){let F=q(H),U=J4(async()=>{let B=await G();if(!B)return v.info("No thread with trees found, using MCP resources only"),await K(H);let{trees:M,threadId:L}=B,A=M.find((C)=>C.repository?.url!=null&&C.repository?.sha!=null&&C.fs==="gitlab");if(!A)return v.info("No GitLab repository found in thread trees, using MCP resources only"),await K(H);v.info("Found GitLab repository",{threadId:L,uri:A.uri,repoUrl:A.repository.url,sha:A.repository.sha});let[I,E]=await Promise.all([V(A),K(H)]);if(I.length===0)return E;let P;if(!H)v.info("Empty query, returning first 10 files"),P=I.slice(0,10);else try{P=qT(H,I,{maxResults:50,minScore:400}).map((S)=>S.entry)}catch(C){return v.error("Fuzzy search failed",C),E}return[...W(P),...E]});return h8(F,U).pipe(X6(([B,M])=>{return[...B,...M].slice(0,$B)}))},dispose(){X.clear()}}}function Rb4(J,Q){let Y=J.title||J.name,Z=J.description?`${J.description} (${Q})`:`MCP Resource from ${Q}`,X=`${Q}:${J.uri}`,G="@"+GB(X);return{uri:Ty(X),label:Y,detail:Z,insertText:G,filterText:`${Y} ${Z} ${J.uri}`.toLowerCase()}}var Tx0=$1(()=>{Y4();s0();N0();KT();Yf();Qh();Px0()});function Tb4(J){let Q="id"in J&&typeof J.id==="string"?J.env?.initial?.trees?.find((G)=>G.repository?.url):J;if(!Q?.repository?.url)return null;let Y=new URL(Q.repository.url).origin,Z=XF(Q.repository.url,{gitlabInstanceURL:Y});if(!Z||Z.provider!=="gitlab")return null;let X=Q.repository.headRef?Zf(Q.repository.headRef):Q.repository.ref?Zf(Q.repository.ref):null;return{repo:Z.name,branch:X,provider:"gitlab",instanceURL:Z.instanceURL}}async function Cb4({repo:J,branch:Q,instanceURL:Y},Z,X){if(!Q||!Y)return v.info("GitLab MR check: missing branch or instanceURL",{repo:J,branch:Q,instanceURL:Y}),null;try{let G=encodeURIComponent(J),V=`/projects/${G}/merge_requests?source_branch=${encodeURIComponent(Q)}&state=all&per_page=1&page=1`;v.info("GitLab MR check: making API request",{repo:J,branch:Q,instanceURL:Y,apiEndpoint:V,projectPath:G});let K=await Xf(V,{config:Z,signal:X,cache:"no-cache"});if(!K.ok||!K.data)return v.info("GitLab MR check: API response not ok or no data",{repo:J,branch:Q,response:K}),null;let q=K.data;if(q.length>0){let W=q[0];return{url:v6(m0.parse(W.web_url)),number:W.iid.toString(),merged:W.state==="merged"}}return null}catch(G){return null}}function Cx0(J,Q,Y,Z){v.info("GitLab thread actions: setting up observable for thread",{threadID:Q});let X=J.observe(Q).pipe(X6((G)=>{let V=G.messages.length>=2&&Ue(G);return[{id:G.id,env:G.env},V]}),I4());return h8(X,Z.pipe(d8(void 0),a7((G)=>{return v.error("mergeRequestChanges subject error, continuing with undefined",{error:G,threadID:Q}),Q0.of(void 0)}))).pipe(bZ(([[G,V],K])=>{if(!G||!V)return v.info("GitLab thread actions: no thread or no messages, returning empty",{threadID:Q}),Q0.of([]);let q=Tb4(G);if(!q)return v.info("GitLab thread actions: not a GitLab repository, returning empty",{threadID:Q}),Q0.of([]);return J4(async(W)=>{let H=await Cb4(q,Y,W);if(H)return[{type:H.merged?"view-merged-pull-request":"view-pull-request",url:H.url,number:H.number}];return[{type:"create-pull-request"}]})}),z8({shouldCountRefs:!0}))}var jx0=$1(()=>{Y4();s0();N0();YO1();ZO1()});class $O1{threadService;config;name="github";mentions;pullRequestChanges=new r4;constructor(J,Q,Y,Z){this.threadService=J;this.config=Y;this.mentions=Lx0(J,Q,Y,Z)}getThreadActions(J){return Ox0(this.threadService,J,this.config,this.pullRequestChanges)}canHandle(J){if(!J)return!1;return XF(J,{provider:"github"})?.provider==="github"}dispose(){this.mentions.dispose()}}class Sx0{threadService;config;name="gitlab";mentions;pullRequestChanges=new r4;constructor(J,Q,Y,Z){this.threadService=J;this.config=Y;this.mentions=Rx0(J,Q,Y,Z)}getThreadActions(J){return Cx0(this.threadService,J,this.config,this.pullRequestChanges)}canHandle(J){if(!J)return!1;let Q=new URL(J).origin;return XF(J,{gitlabInstanceURL:Q})?.provider==="gitlab"}dispose(){this.mentions.dispose()}}function _x0(J,Q,Y,Z,X){let G=J.find((q)=>q.repository?.url);if(!G?.repository?.url)return new $O1(Q,Y,Z,X);if(G.repository.url.includes("gitlab.")||G.fs==="gitlab")return new Sx0(Q,Y,Z,X);else return new $O1(Q,Y,Z,X)}var kx0=$1(()=>{s0();Ax0();Ix0();Tx0();jx0()});function G4(J,Q,Y,Z,X){if(Z==="m")throw TypeError("Private method is not writable");if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof Q==="function"?J!==Q||!X:!Q.has(J))throw TypeError("Cannot write private member to an object whose class did not declare it");return Z==="a"?X.call(J,Y):X?X.value=Y:Q.set(J,Y),Y}function T0(J,Q,Y,Z){if(Y==="a"&&!Z)throw TypeError("Private accessor was defined without a getter");if(typeof Q==="function"?J!==Q||!Z:!Q.has(J))throw TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?Z:Y==="a"?Z.call(J):Z?Z.value:Q.get(J)}var $F=()=>{};var GO1=function(){let{crypto:J}=globalThis;if(J?.randomUUID)return GO1=J.randomUUID.bind(J),J.randomUUID();let Q=new Uint8Array(1),Y=J?()=>J.getRandomValues(Q)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Z)=>(+Z^Y()&15>>+Z/4).toString(16))};function GF(J){return typeof J==="object"&&J!==null&&(("name"in J)&&J.name==="AbortError"||("message"in J)&&String(J.message).includes("FetchRequestCanceledException"))}var $f=(J)=>{if(J instanceof Error)return J;if(typeof J==="object"&&J!==null){try{if(Object.prototype.toString.call(J)==="[object Error]"){let Q=Error(J.message,J.cause?{cause:J.cause}:{});if(J.stack)Q.stack=J.stack;if(J.cause&&!Q.cause)Q.cause=J.cause;if(J.name)Q.name=J.name;return Q}}catch{}try{return Error(JSON.stringify(J))}catch{}}return Error(J)};var b4,H2,NQ,IA,Gf,Vf,Kf,qf,Wf,Hf,Ff,zf,Uf;var m$=$1(()=>{b4=class b4 extends Error{};H2=class H2 extends b4{constructor(J,Q,Y,Z){super(`${H2.makeMessage(J,Q,Y)}`);this.status=J,this.headers=Z,this.requestID=Z?.get("request-id"),this.error=Q}static makeMessage(J,Q,Y){let Z=Q?.message?typeof Q.message==="string"?Q.message:JSON.stringify(Q.message):Q?JSON.stringify(Q):Y;if(J&&Z)return`${J} ${Z}`;if(J)return`${J} status code (no body)`;if(Z)return Z;return"(no status code or body)"}static generate(J,Q,Y,Z){if(!J||!Z)return new IA({message:Y,cause:$f(Q)});let X=Q;if(J===400)return new Vf(J,X,Y,Z);if(J===401)return new Kf(J,X,Y,Z);if(J===403)return new qf(J,X,Y,Z);if(J===404)return new Wf(J,X,Y,Z);if(J===409)return new Hf(J,X,Y,Z);if(J===422)return new Ff(J,X,Y,Z);if(J===429)return new zf(J,X,Y,Z);if(J>=500)return new Uf(J,X,Y,Z);return new H2(J,X,Y,Z)}};NQ=class NQ extends H2{constructor({message:J}={}){super(void 0,void 0,J||"Request was aborted.",void 0)}};IA=class IA extends H2{constructor({message:J,cause:Q}){super(void 0,void 0,J||"Connection error.",void 0);if(Q)this.cause=Q}};Gf=class Gf extends IA{constructor({message:J}={}){super({message:J??"Request timed out."})}};Vf=class Vf extends H2{};Kf=class Kf extends H2{};qf=class qf extends H2{};Wf=class Wf extends H2{};Hf=class Hf extends H2{};Ff=class Ff extends H2{};zf=class zf extends H2{};Uf=class Uf extends H2{}});function Be(J){if(typeof J!=="object")return{};return J??{}}function xx0(J){if(!J)return!0;for(let Q in J)return!1;return!0}function vx0(J,Q){return Object.prototype.hasOwnProperty.call(J,Q)}var Sb4,yx0=(J)=>{return Sb4.test(J)},VO1=(J)=>(VO1=Array.isArray,VO1(J)),KO1,hx0=(J,Q)=>{if(typeof Q!=="number"||!Number.isInteger(Q))throw new b4(`${J} must be an integer`);if(Q<0)throw new b4(`${J} must be a positive integer`);return Q},Ne=(J)=>{try{return JSON.parse(J)}catch(Q){return}};var wA=$1(()=>{m$();Sb4=/^[a-z][a-z0-9+.-]*:/i,KO1=VO1});var fx0=(J)=>new Promise((Q)=>setTimeout(Q,J));var TB="0.71.0";function _b4(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}function yb4(){if(typeof navigator>"u"||!navigator)return null;let J=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Q,pattern:Y}of J){let Z=Y.exec(navigator.userAgent);if(Z){let X=Z[1]||0,G=Z[2]||0,V=Z[3]||0;return{browser:Q,version:`${X}.${G}.${V}`}}}return null}var ux0=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},kb4=()=>{let J=_b4();if(J==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":TB,"X-Stainless-OS":gx0(Deno.build.os),"X-Stainless-Arch":bx0(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":TB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(J==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":TB,"X-Stainless-OS":gx0(globalThis.process.platform??"unknown"),"X-Stainless-Arch":bx0(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Q=yb4();if(Q)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":TB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Q.browser}`,"X-Stainless-Runtime-Version":Q.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":TB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},bx0=(J)=>{if(J==="x32")return"x32";if(J==="x86_64"||J==="x64")return"x64";if(J==="arm")return"arm";if(J==="aarch64"||J==="arm64")return"arm64";if(J)return`other:${J}`;return"unknown"},gx0=(J)=>{if(J=J.toLowerCase(),J.includes("ios"))return"iOS";if(J==="android")return"Android";if(J==="darwin")return"MacOS";if(J==="win32")return"Windows";if(J==="freebsd")return"FreeBSD";if(J==="openbsd")return"OpenBSD";if(J==="linux")return"Linux";if(J)return`Other:${J}`;return"Unknown"},mx0,px0=()=>{return mx0??(mx0=kb4())};var qO1=()=>{};function dx0(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function WO1(...J){let Q=globalThis.ReadableStream;if(typeof Q>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Q(...J)}function De(J){let Q=Symbol.asyncIterator in J?J[Symbol.asyncIterator]():J[Symbol.iterator]();return WO1({start(){},async pull(Y){let{done:Z,value:X}=await Q.next();if(Z)Y.close();else Y.enqueue(X)},async cancel(){await Q.return?.()}})}function Bf(J){if(J[Symbol.asyncIterator])return J;let Q=J.getReader();return{async next(){try{let Y=await Q.read();if(Y?.done)Q.releaseLock();return Y}catch(Y){throw Q.releaseLock(),Y}},async return(){let Y=Q.cancel();return Q.releaseLock(),await Y,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function cx0(J){if(J===null||typeof J!=="object")return;if(J[Symbol.asyncIterator]){await J[Symbol.asyncIterator]().return?.();return}let Q=J.getReader(),Y=Q.cancel();Q.releaseLock(),await Y}var lx0=({headers:J,body:Q})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Q)}};function ax0(J){let Q=0;for(let X of J)Q+=X.length;let Y=new Uint8Array(Q),Z=0;for(let X of J)Y.set(X,Z),Z+=X.length;return Y}function Nf(J){let Q;return(nx0??(Q=new globalThis.TextEncoder,nx0=Q.encode.bind(Q)))(J)}function HO1(J){let Q;return(ix0??(Q=new globalThis.TextDecoder,ix0=Q.decode.bind(Q)))(J)}var nx0,ix0;class CB{constructor(){QX.set(this,void 0),YX.set(this,void 0),G4(this,QX,new Uint8Array,"f"),G4(this,YX,null,"f")}decode(J){if(J==null)return[];let Q=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?Nf(J):J;G4(this,QX,ax0([T0(this,QX,"f"),Q]),"f");let Y=[],Z;while((Z=hb4(T0(this,QX,"f"),T0(this,YX,"f")))!=null){if(Z.carriage&&T0(this,YX,"f")==null){G4(this,YX,Z.index,"f");continue}if(T0(this,YX,"f")!=null&&(Z.index!==T0(this,YX,"f")+1||Z.carriage)){Y.push(HO1(T0(this,QX,"f").subarray(0,T0(this,YX,"f")-1))),G4(this,QX,T0(this,QX,"f").subarray(T0(this,YX,"f")),"f"),G4(this,YX,null,"f");continue}let X=T0(this,YX,"f")!==null?Z.preceding-1:Z.preceding,G=HO1(T0(this,QX,"f").subarray(0,X));Y.push(G),G4(this,QX,T0(this,QX,"f").subarray(Z.index),"f"),G4(this,YX,null,"f")}return Y}flush(){if(!T0(this,QX,"f").length)return[];return this.decode(`
368
+ `)}var ly0,Sf4,PB=64,XT,aA1=1024,oA1=500,kf4,yf4="mcp.json";var AA=$1(()=>{Y4();N0();W2();x4();Bq1();ly0=Q6(EB(),1),Sf4=new Set(["name","description","license","compatibility","metadata","allowed-tools","argument-hint","model","disable-model-invocation","mode","isolatedContext"]),XT=/^[a-z0-9](?:[a-z0-9]*(?:-[a-z0-9]+)*)?$/;kf4=/^skill\.md$/i});function Nb4(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(J)}class Qf{fs;constructor(J){this.fs=J}async store(J,Q,Y){let Z=this.backupDirForThread(J);if(!Z)return;await this.fs.mkdirp(Z);let X=i0.joinPath(Z,this.filename(Q));await this.fs.writeFile(X,JSON.stringify(Y,null,2))}async load(J,Q){let Y=this.backupDirForThread(J);if(!Y)return null;try{let Z=await this.fs.readFile(i0.joinPath(Y,this.filename(Q)));return JSON.parse(Z)}catch(Z){return v.error(`Error loading backup file ${this.filename(Q)}:`,Z),null}}async list(J){let Q=this.backupDirForThread(J);if(!Q)return[];await this.fs.mkdirp(Q);try{let Y=await this.fs.readdir(Q),Z=[];for(let X of Y){let G=i0.relativePath(Q,X.uri);if(!G)continue;let V=G.split(".");if(V.length===2){let K=V[0],q=V[1];if(K&&Nb4(q))Z.push({toolUseID:K,fileChangeID:q})}}return Z}catch(Y){return v.error("Error listing backup files:",Y),[]}}async cleanup(J){let Q=this.backupDirForThread(J);if(!Q)return;try{await this.fs.delete(Q,{recursive:!0})}catch(Y){if(!UQ(Y))v.error(`Error cleaning up backup files in ${Q}:`,Y)}}filename(J){return`${J.toolUseID}.${J.fileChangeID}`}backupDirForThread(J){let Q=typeof process<"u"?process.env.HOME:null;if(!Q)return null;return i0.joinPath(m0.file(Q),".amp","file-changes",J)}}var QO1;var He=$1(()=>{Y4();N0();tQ();QO1={async store(){},async load(){return null},async list(){return[]},async cleanup(){}}});function XF(J,Q){if(J=J.replace(/\.git$/,""),!URL.canParse(J))return null;let Y=new URL(J);if(Y.protocol!=="https:"||Y.port||Y.username||Y.password)return null;let Z=Y.pathname.replace(/^\//,"").replace(/\/$/,"");if(!Z)return null;let X=`${Y.protocol}//${Y.host}`;if(Y.hostname==="github.com"){if(Q?.provider&&Q.provider!=="github")return null;return{name:Z,instanceURL:"https://github.com",provider:"github"}}if(!Q?.gitlabInstanceURL)return null;let G=new URL(Q.gitlabInstanceURL);if(Y.protocol===G.protocol&&Y.host===G.host){if(Q?.provider&&Q.provider!=="gitlab")return null;return{name:Z,instanceURL:X,provider:"gitlab"}}return null}class JY{bits;constructor(J){this.bits=J}static empty(){return new JY(0n)}static fromString(J){let Q=0n;for(let Y=0;Y<J.length;Y++){let Z=J.charCodeAt(Y),X=JY.charToBitIndex(Z);if(X>=0)Q|=1n<<BigInt(X)}return new JY(Q)}static fromPath(J){let Q=0n,Y=J.split(/[/\\]/);for(let Z of Y){if(Z===""||Z==="."||Z==="..")continue;for(let X=0;X<Z.length;X++){let G=Z.charCodeAt(X),V=JY.charToBitIndex(G);if(V>=0)Q|=1n<<BigInt(V)}}return new JY(Q)}hasChars(J){return(this.bits&J.bits)===J.bits}union(J){return new JY(this.bits|J.bits)}intersection(J){return new JY(this.bits&J.bits)}isEmpty(){return this.bits===0n}getCharCount(){return this.bits.toString(2).split("").filter((J)=>J==="1").length}toString(){let J=[];for(let Q=0;Q<64;Q++)if((this.bits&1n<<BigInt(Q))!==0n){let Y=JY.bitIndexToChar(Q);if(Y)J.push(Y)}return`CharBag{${J.join("")}}`}toJSON(){return{bits:this.bits.toString()}}static fromJSON(J){return new JY(BigInt(J.bits))}equals(J){return this.bits===J.bits}static charToBitIndex(J){if(J>=65&&J<=90)J+=32;if(J>=48&&J<=57)return J-48;if(J>=97&&J<=122)return J-97+10;return-1}static bitIndexToChar(J){if(J>=0&&J<=9)return String.fromCharCode(48+J);if(J>=10&&J<=35)return String.fromCharCode(97+J-10);return null}}class $Z{id;kind;path;uri;charBag;metadata;isIgnored;isExternal;isPrivate;isAlwaysIncluded;constructor(J){this.id=J.id,this.kind=J.kind,this.path=J.path,this.uri=J.uri,this.metadata=J.metadata,this.isIgnored=J.isIgnored??!1,this.isExternal=J.isExternal??!1,this.isPrivate=J.isPrivate??!1,this.isAlwaysIncluded=J.isAlwaysIncluded??!1,this.charBag=JY.fromPath(this.path)}withUpdates(J){return new $Z({id:this.id,kind:J.kind??this.kind,path:this.path,uri:this.uri,metadata:J.metadata??this.metadata,isIgnored:J.isIgnored??this.isIgnored,isExternal:J.isExternal??this.isExternal,isPrivate:J.isPrivate??this.isPrivate,isAlwaysIncluded:J.isAlwaysIncluded??this.isAlwaysIncluded})}isFile(){return this.kind==="file"}isDirectory(){return this.kind==="directory"||this.kind==="unloaded-directory"||this.kind==="pending-directory"}isLoadedDirectory(){return this.kind==="directory"}getFilename(){return this.path.split(/[/\\]/).pop()||this.path}getExtension(){let J=this.getFilename(),Q=J.lastIndexOf(".");return Q>0?J.slice(Q+1):""}getDirectory(){let J=this.path.split(/[/\\]/);return J.length>1?J.slice(0,-1).join("/"):""}shouldIncludeInResults(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;return!0}shouldIncludeInMentions(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;if(this.isFile())return!0;return this.isLoadedDirectory()}getImportanceBoost(){return this.isAlwaysIncluded?0.1:0}toJSON(){return{id:this.id,kind:this.kind,path:this.path,uri:this.uri.toString(),metadata:this.metadata,isIgnored:this.isIgnored,isExternal:this.isExternal,isPrivate:this.isPrivate,isAlwaysIncluded:this.isAlwaysIncluded,charBag:this.charBag.toJSON()}}static fromJSON(J,Q){return new $Z({id:J.id,kind:J.kind,path:J.path,uri:Q(J.uri),metadata:J.metadata,isIgnored:J.isIgnored,isExternal:J.isExternal,isPrivate:J.isPrivate,isAlwaysIncluded:J.isAlwaysIncluded})}equals(J){return this.id===J.id&&this.kind===J.kind&&this.path===J.path&&this.metadata.mtime===J.metadata.mtime&&this.metadata.size===J.metadata.size}hashCode(){return`${this.path}:${this.metadata.mtime}:${this.metadata.size}`}toString(){return`Entry{${this.kind}:${this.path}}`}}var KT=()=>{};class Fe{config;queryChars;queryLower;constructor(J,Q={}){this.config={...Db4,...Q};let Y=J.replace(/^[@#]+/,"");if(this.queryChars=Array.from(Y),this.queryLower=Array.from(Y.toLowerCase()),this.config.smartCase)this.config.caseSensitive=Y!==Y.toLowerCase()}match(J){if(this.queryChars.length===0)return J.filter((Y)=>Y.shouldIncludeInResults()).map((Y)=>{let Z=this.config.openFiles?.includes(Y.path)?500:0,X=this.config.dirtyFiles?.includes(Y.path)?300:0,G=Y.getImportanceBoost()+Z+X;return{entry:Y,score:G,matchPositions:[],highlightedPath:Y.path}}).sort((Y,Z)=>Z.score-Y.score).slice(0,this.config.maxResults);let Q=this.matchWithSemanticScoring(J);if(Q.length>0)return Q;return this.matchWithFuzzyScoring(J)}matchWithSemanticScoring(J){let Q=[],Y=0,Z=50000,X=this.queryChars.join(""),G=J.filter((K)=>K.shouldIncludeInResults()&&this.passesCharBagFilter(X,K)),V=(K)=>{let q=this.matchEntrySemantic(K);if(q&&q.score>=this.config.minScore)Q.push(q);return Y++,Y>=Z};for(let K of G)if(K.isDirectory()){if(V(K))break}if(Y<Z){for(let K of G)if(!K.isDirectory()){if(V(K))break}}return Q.sort((K,q)=>{let W=q.score-K.score;if(Math.abs(W)>0.001)return W;return K.entry.path.length-q.entry.path.length}),Q.slice(0,this.config.maxResults)}matchWithFuzzyScoring(J){let Q=[],Y=0,Z=50000,X=this.queryChars.join(""),G=J.filter((K)=>K.shouldIncludeInResults()&&this.passesCharBagFilter(X,K)),V=(K)=>{let q=this.matchEntryFuzzy(K);if(q)Q.push(q);return Y++,Y>=Z};for(let K of G)if(K.isDirectory()){if(V(K))break}if(Y<Z){for(let K of G)if(!K.isDirectory()){if(V(K))break}}return Q.sort((K,q)=>{let W=q.score-K.score;if(Math.abs(W)>0.001)return W;return K.entry.path.length-q.entry.path.length}),Q.slice(0,this.config.maxResults)}matchEntrySemantic(J){let Q=J.path,Y=this.queryLower.join(""),Z=this.calculateSemanticScore(Y,J);if(Z===0)return null;let X=this.applyTieBreakers(Z,Y,J),G=this.findMatchPositions(Y,Q),V=this.createHighlightedPath(Q,G);return{entry:J,score:X,matchPositions:G,highlightedPath:V}}matchEntryFuzzy(J){let Q=J.path,Y=this.queryLower.join(""),Z=this.calculateFuzzyScore(Y,J);if(Z===0)return null;let X=this.applyTieBreakers(Z,Y,J),G=this.findMatchPositions(Y,Q),V=this.createHighlightedPath(Q,G);return{entry:J,score:X,matchPositions:G,highlightedPath:V}}calculateSemanticScore(J,Q){let Y=J.toLowerCase(),Z=Q.path,X=Z.toLowerCase(),G=this.getFilename(Z),V=this.removeExtension(G).toLowerCase(),K=X.split(/[/\\.\s-_]/).filter((F)=>F.length>0);if(J.endsWith("/")&&Q.isDirectory()){let F=Y.slice(0,-1);if(X===F||X.endsWith("/"+F))return QY.EXACT_FILENAME+100;if(X.includes(F))return QY.SUBSTRING_FILENAME+50}if(V===Y||G.toLowerCase()===Y)return QY.EXACT_FILENAME;if(V.startsWith(Y))return QY.PREFIX_FILENAME;if(V.endsWith(Y))return QY.SUFFIX_FILENAME;if(V.includes(Y))return QY.SUBSTRING_FILENAME;let q=this.simpleTokens(Y);if(q.length>1){let F=this.matchTokensToSegments(q,K);if(F)return F}if(q.length===1&&Y.length>6){let F=this.progressiveSegmentMatch(Y,K);if(F)return F}if(K.includes(Y))return QY.SEGMENT_EXACT;if(K.some((F)=>F.includes(Y)))return QY.SEGMENT_SUBSTRING;if(K.join("").includes(Y))return QY.SEGMENT_SUBSTRING;if(X.replace(/[\s-_]/g,"").includes(Y))return QY.PATH_SUBSTRING;return 0}calculateFuzzyScore(J,Q){let Y=J.toLowerCase(),Z=Q.path.toLowerCase();if(this.fuzzyIn(Y,Z))return QY.FUZZY;return 0}applyTieBreakers(J,Q,Y){let Z=J,X=Math.abs(Y.path.length-Q.length);Z-=0.01*X;let G=Y.path.split(/[/\\]/).length-1;Z-=0.1*G;let V=this.getFilename(Y.path),K=this.removeExtension(V).toLowerCase();if(/^(license|readme|copy(ing|left))$/i.test(K)&&G===1)Z-=200;if(Y.metadata.mtime){let W=(Date.now()-Y.metadata.mtime)/86400000;if(W<30){let H=Math.max(0,1-W/30);Z+=50*H}}if(this.config.openFiles?.includes(Y.path))Z+=500;if(this.config.dirtyFiles?.includes(Y.path))Z+=300;return Z}simpleTokens(J){return J.replace(/([a-z])([A-Z0-9])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}progressiveSegmentMatch(J,Q){let Y=0,Z=0,X=0;for(let V of Q){if(Y>=J.length)break;let K="",q="none";if(Y+V.length<=J.length){if(J.slice(Y,Y+V.length)===V)K=V,q="exact"}if(!K&&V.length>=3){if(J.slice(Y).startsWith(V))K=V,q="prefix"}if(!K&&V.length>=3){let W=J.slice(Y);if(W.includes(V)&&W.indexOf(V)===0)K=V,q="substring"}if(!K){let W=J.slice(Y);if(W.length>=3&&V.includes(W))K=W,q="substring"}if(K){if(Y+=K.length,Z++,q==="exact")X++}}if(Y/J.length>=0.8&&Z>=2)return X>=2?QY.SEGMENT_ORDERED_EXACT:QY.SEGMENT_ORDERED_PARTIAL;return 0}matchTokensToSegments(J,Q){let Y=this.findTokenMatches(J,Q),Z=this.getWorstMatchType(Y);return this.scoreFromMatchType(Z)}findTokenMatches(J,Q){let Y=0,Z=[];for(let X of J){let G=!1;for(let V=Y;V<Q.length;V++){let K=Q[V];if(!K)continue;if(X===K){Z.push("exact"),Y=V+1,G=!0;break}else if(K.startsWith(X)||X.startsWith(K)||K.endsWith(X)||K.includes(X)||X.includes(K)){Z.push("partial"),Y=V+1,G=!0;break}}if(!G)return[]}return Z}getWorstMatchType(J){if(J.length===0)return"none";if(J.includes("partial"))return"partial";return"exact"}scoreFromMatchType(J){switch(J){case"exact":return QY.SEGMENT_ORDERED_EXACT;case"partial":return QY.SEGMENT_ORDERED_PARTIAL;default:return 0}}fuzzyIn(J,Q){let Y=0;for(let Z=0;Z<Q.length&&Y<J.length;Z++)if(Q[Z]===J[Y])Y++;return Y===J.length}getFilename(J){return J.split(/[/\\]/).pop()||J}removeExtension(J){let Q=J.lastIndexOf(".");return Q>0?J.substring(0,Q):J}findMatchPositions(J,Q){let Y=[],Z=Q.toLowerCase(),X=J.toLowerCase();if(Z.includes(X)){let V=Z.indexOf(X);for(let K=0;K<X.length;K++)Y.push(V+K);return Y}let G=0;for(let V of X){let K=Z.indexOf(V,G);if(K!==-1)Y.push(K),G=K+1}return Y}passesCharBagFilter(J,Q){if(J.includes("/")||J.includes("\\")){let Y=J.split(/[/\\]/);for(let Z of Y){if(Z.trim()==="")continue;let X=JY.fromString(Z);if(!Q.charBag.hasChars(X))return!1}return!0}else{let Y=JY.fromString(J);return Q.charBag.hasChars(Y)}}createHighlightedPath(J,Q){if(Q.length===0)return J;let Y="",Z=0;for(let X of Q){if(X>=J.length)continue;Y+=J.slice(Z,X),Y+=`**${J[X]}**`,Z=X+1}return Y+=J.slice(Z),Y}}function qT(J,Q,Y){return new Fe(J,Y).match(Q)}var Db4,QY;var Yf=$1(()=>{Db4={minScore:400,caseSensitive:!1,penalizeLengthDifference:!0,maxResults:50,smartCase:!0},QY={EXACT_FILENAME:1000,PREFIX_FILENAME:950,SEGMENT_ORDERED_EXACT:900,SUFFIX_FILENAME:850,SEGMENT_ORDERED_PARTIAL:840,SUBSTRING_FILENAME:800,SEGMENT_EXACT:650,SEGMENT_SUBSTRING:600,PATH_SUBSTRING:500,FUZZY:250}});async function a3(J,Q={},Y){let Z=`/api/internal/github-proxy/${J}`,{body:X,headers:G={},method:V="GET",...K}=Q,q=await _L1(Y,Z,{method:V,headers:G,body:X?JSON.stringify(X):void 0,...K});if(q.status===304)return{ok:!0,status:q.status,notModified:!0,headers:{etag:q.headers.get("etag")||void 0}};if(!q.ok)return{ok:!1,status:q.status,statusText:q.statusText};let W=await q.json();return{ok:!0,status:q.status,data:W,headers:{location:q.headers.get("location")||void 0,etag:q.headers.get("etag")||void 0}}}var kq=$1(()=>{BQ()});async function Dx0(J,Q,Y,Z,X){let G=XF(J,{provider:"github"})?.name;if(!G)throw Error("Invalid GitHub repository URL");let{filePattern:V,limit:K,offset:q=0}=Y,W=`repos/${G}/git/trees/${Q??"HEAD"}?recursive=1`,H=await a3(W,{signal:Z},X);if(!H.ok||!H.data)throw Error(`Failed to fetch files: ${H.status} ${H.statusText||"Unknown error"}`);let U=H.data.tree.filter((A)=>A.type==="blob").map((A)=>A.path),B=Nx0.default(V),M=U.filter((A)=>B(A));return{files:K?M.slice(q,q+K):M.slice(q),truncated:H.data.truncated}}var Nx0;var Mx0=$1(()=>{kq();Nx0=Q6(dy(),1)});function Lx0(J,Q,Y,Z){let X=new Map,G=async()=>{try{let H;if(Z)H=await J.get(Z);else H=J.getRecentlyActiveThread();if(H){let F=H.id,U=H.env?.initial.trees||[];if(v.info("Found thread:",F,"trees:",U.length),U.length>0)return v.info("Using trees from thread:",F),{trees:U,threadId:F};else v.info("Thread has no trees")}else v.info("No thread found");return null}catch(H){return v.error("Error getting thread:",H),null}},V=async(H)=>{if(!H.repository||!H.repository.url||!H.repository.sha)return[];let F=H.repository,U=F.sha,B=Date.now(),M=`${F.url}:${U}`,L=X.get(M);if(L&&B-L.timestamp<300000)return L.entries;try{let A=await Dx0(F.url,U,{filePattern:"**/*",limit:1e4},void 0,Y),I=A.files.map((P)=>{let R={mtime:Date.now(),size:0,inode:0,isSymlink:!1},C=m0.file(`/${P}`);return new $Z({id:`github:${F.url}:${U}:${P}`,kind:"file",path:P,uri:C,metadata:R})}),E={entries:I,timestamp:B,repoUrl:F.url,sha:U};if(X.set(M,E),A.truncated)v.warn("GitHub repository file listing was truncated",{repo:F.url,indexedFiles:I.length});return I}catch(A){return v.error("Failed to fetch files from GitHub API",A),[]}},K=async(H)=>{try{return(await Q.searchResources(H)).map(({resource:U,serverName:B})=>Mb4(U,B)).slice(0,Math.min(5,$B))}catch(F){return v.warn("Failed to search MCP resources",F),[]}},q=(H)=>{return Q.searchPrompts(H)},W=(H)=>{return H.map((F)=>{let U=F.path,B=`@${GB(U)}`,M=U.split("/"),L=M[M.length-1]||U,A=M.length>1?M.slice(0,-1).join("/"):"";return{uri:v6(F.uri),label:L,detail:A,insertText:B,filterText:U.toLowerCase(),kind:F.isDirectory()?"folder":"file"}})};return{search(H){let F=q(H),U=J4(async()=>{let B=await G();if(!B)return v.info("No thread with trees found, using MCP resources only"),await K(H);let{trees:M,threadId:L}=B,A=M.find((C)=>C.repository?.url!=null&&C.repository?.sha!=null);if(!A)return v.info("No GitHub repository found in thread trees, using MCP resources only"),await K(H);v.info("Found GitHub repository",{threadId:L,uri:A.uri,repoUrl:A.repository.url,sha:A.repository.sha});let[I,E]=await Promise.all([V(A),K(H)]);if(I.length===0)return E;let P;if(!H)v.info("Empty query, returning first 10 files"),P=I.slice(0,10);else try{P=qT(H,I,{maxResults:50,minScore:400}).map((S)=>S.entry)}catch(C){return v.error("Fuzzy search failed",C),E}return[...W(P),...E]});return h8(F,U).pipe(X6(([B,M])=>{return[...B,...M].slice(0,$B)}))},dispose(){X.clear()}}}function Mb4(J,Q){let Y=J.title||J.name,Z=J.description?`${J.description} (${Q})`:`MCP Resource from ${Q}`,X=`${Q}:${J.uri}`,G="@"+GB(X);return{uri:Ty(X),label:Y,detail:Z,insertText:G,filterText:`${Y} ${Z} ${J.uri}`.toLowerCase()}}var Ax0=$1(()=>{Y4();s0();N0();KT();Yf();Qh();Mx0()});function Zf(J){if(!J.startsWith("refs/heads/"))return null;return J.slice(11)}function Ue(J){let Q=zP(J);if(Object.values(Q).reduce((Y,Z)=>Y+Z,0)>0)return!0;for(let Y of J.messages){if(Y.role!=="assistant")continue;for(let Z of Y.content){if(Z.type==="tool_use"&&Z.name==="delete_file"){if(kH(J,Z.id)?.run.status==="done")return!0}if(Z.type==="tool_use"&&Z.name==="Bash"&&Z.input&&"cmd"in Z.input){if(String(Z.input.cmd).match(/^\s*(rm|mv)\s+/)){if(kH(J,Z.id)?.run.status==="done")return!0}}}}return!1}var YO1=$1(()=>{U8()});function Lb4(J){let Q="id"in J&&typeof J.id==="string"?J.env?.initial?.trees?.find((X)=>X.repository?.url):J;if(!Q?.repository?.url)return null;let Y=XF(Q.repository.url,{provider:"github"});if(!Y||Y.provider!=="github")return null;let Z=Q.repository.headRef?Zf(Q.repository.headRef):null;return{repo:Y.name,branch:Z,provider:"github"}}async function Ab4({repo:J,branch:Q},Y,Z){if(!Q)return null;try{let X=J.split("/")[0],G=`repos/${J}/pulls?head=${encodeURIComponent(X)}:${encodeURIComponent(Q)}&state=all&sort=created&direction=desc&per_page=1&page=1`,V=await a3(G,{signal:Z,cache:"no-cache"},Y);if(!V.ok||!V.data)return null;let K=V.data;if(K.length>0){let q=K[0],W=q.state==="closed"&&q.merged_at!==null;return{url:v6(m0.parse(q.html_url)),number:q.number.toString(),merged:W}}return null}catch(X){return v.debug("Failed to check GitHub pull request status:",X),null}}function Ox0(J,Q,Y,Z){let X=J.observe(Q).pipe(X6((G)=>[{id:G.id,env:G.env},G.messages.length>=2&&Ue(G)]),I4());return h8(X,Z.pipe(d8(void 0),a7((G)=>{return v.error("pullRequestChanges subject error, continuing with undefined",{error:G,threadID:Q}),Q0.of(void 0)}))).pipe(bZ(([[G,V]])=>{if(!G||!V)return Q0.of([]);let K=Lb4(G);if(!K)return Q0.of([]);let W=G.env?.initial?.trees?.find((H)=>H.repository?.url)?.repository?.pullRequestURL;return J4(async(H)=>{if(W&&!K.branch){let U=W.split("/").pop()||"";try{let B=`repos/${K.repo}/pulls/${U}`,M=await a3(B,{signal:H,cache:"no-cache"},Y);if(M.ok&&M.data){let L=M.data;return[{type:L.state==="closed"&&L.merged_at!==null?"view-merged-pull-request":"view-pull-request",url:v6(m0.parse(L.html_url)),number:L.number.toString()}]}}catch(B){v.debug("Failed to fetch specific PR:",B)}}let F=await Ab4(K,Y,H);if(F)return[{type:F.merged?"view-merged-pull-request":"view-pull-request",url:F.url,number:F.number}];return[{type:"create-pull-request"}]})}),z8({shouldCountRefs:!0}))}var Ix0=$1(()=>{Y4();s0();N0();YO1();kq()});async function Xf(J,Q){let Y=Q.config.settings.url;if(!Y)throw Error("amp.url is not set");let Z=await Q.config.secrets.getToken("gitlab-access-token",Y);if(!Z)return{ok:!1,status:401,statusText:"GitLab access token is not set"};let X=await Q.config.secrets.getToken("gitlab-instance-url",Y)??Ob4;return Ib4(J,{...Q,auth:{instanceURL:X,accessToken:Z}})}async function Ib4(J,{auth:Q,...Y}){let Z=`${Q.instanceURL.replace(/\/+$/,"")}/api/v4`,X=J.startsWith("http")?J:`${Z}${J}`,{body:G,headers:V={}}=Y,K={"Content-Type":"application/json",Authorization:`Bearer ${Q.accessToken}`,...V};try{let q=await fetch(X,{...Y,body:G?JSON.stringify(G):void 0,headers:K}),W=void 0,H=void 0;if(Y.method!=="HEAD"&&q.status!==204)try{H=await q.text(),W=JSON.parse(H)}catch(F){v.info("GitLab API response not JSON:",{url:X,status:q.status,responseText:H?.substring(0,200)})}return v.debug("GitLab API response:",{url:X,ok:q.ok,status:q.status,statusText:q.statusText,hasData:!!W,dataKeys:W&&typeof W==="object"?Object.keys(W):void 0,responseTextLength:H?.length}),{data:W,ok:q.ok,status:q.status,statusText:q.statusText}}catch(q){return v.error(`GitLab API request error (${X}):`,q),{ok:!1,status:0,statusText:q instanceof Error?q.message:String(q)}}}var Ob4="https://gitlab.com";var ZO1=$1(()=>{N0()});function wx0(J){let Q=J.replace(/\.git$/,"");try{return new URL(Q).pathname.replace(/^\//,"")}catch{return Q.match(/https?:\/\/[^/]+\/(.+)/)?.[1]??Q}}function wb4(J){if(J.includes("**")){let Q=J.replace(/\*\*\//g,"");if(Q.includes("*"))return Q}if(J.includes("*")&&!J.includes("/"))return J;return null}async function Eb4(J,Q,Y,Z){let{filePattern:X,limit:G=100,offset:V=0}=Y,K=wb4(X);if(!K)return null;let q=encodeURIComponent(J),W=Math.floor(V/G)+1,H=`/projects/${q}/search?scope=blobs&search=path:${encodeURIComponent(K)}&per_page=${G}&page=${W}&ref=${Q}`;try{let F=await Xf(H,{config:Z});if(!F.ok||!F.data)return null;let U=new Set(F.data.map((A)=>A.path)),B=Array.from(U),M=XO1.default(X);return{files:B.filter((A)=>M(A)),truncated:F.data.length===G}}catch(F){return null}}async function Pb4(J,Q,Y,Z){let{filePattern:X,limit:G,offset:V=0}=Y,q=`/projects/${encodeURIComponent(J)}/repository/tree?recursive=true&ref=${Q}&per_page=1000&pagination=keyset`,W=await Xf(q,{config:Z});if(!W.ok||!W.data)throw Error(`Failed to fetch files: ${W.status} ${W.statusText||"Unknown error"}`);let F=W.data.filter((L)=>L.type==="blob").map((L)=>L.path),U=XO1.default(X),B=F.filter((L)=>U(L));return{files:G?B.slice(V,V+G):B.slice(V),truncated:W.data.length===1000}}async function Ex0(J,Q,Y,Z){let X=wx0(J);if(!X)throw Error(`Invalid GitLab repository URL: ${J}`);let G=await Eb4(X,Q,Y,Z);if(G)return G;return Pb4(X,Q,Y,Z)}var XO1;var Px0=$1(()=>{ZO1();XO1=Q6(dy(),1)});function Rx0(J,Q,Y,Z){let X=new Map,G=async()=>{try{let H;if(Z)H=await J.get(Z);else H=J.getRecentlyActiveThread();if(H){let F=H.id,U=H.env?.initial.trees||[];if(v.info("Found thread:",F,"trees:",U.length),U.length>0)return v.info("Using trees from thread:",F),{trees:U,threadId:F};else v.info("Thread has no trees")}else v.info("No thread found");return null}catch(H){return v.error("Error getting thread:",H),null}},V=async(H)=>{if(!H.repository||!H.repository.url||!H.repository.sha)return[];let F=H.repository,U=F.sha,B=Date.now(),M=`${F.url}:${U}`,L=X.get(M);if(L&&B-L.timestamp<300000)return L.entries;try{let A=await Ex0(F.url,U,{filePattern:"**/*",limit:1e4},Y),I=A.files.map((P)=>{let R={mtime:Date.now(),size:0,inode:0,isSymlink:!1},C=m0.file(`/${P}`);return new $Z({id:`gitlab:${F.url}:${U}:${P}`,kind:"file",path:P,uri:C,metadata:R})}),E={entries:I,timestamp:B,repoUrl:F.url,sha:U};if(X.set(M,E),A.truncated)v.warn("GitLab repository file listing was truncated",{repo:F.url,indexedFiles:I.length});return I}catch(A){return v.error("Failed to fetch files from GitLab API",A),[]}},K=async(H)=>{try{return(await Q.searchResources(H)).map(({resource:U,serverName:B})=>Rb4(U,B)).slice(0,Math.min(5,$B))}catch(F){return v.warn("Failed to search MCP resources",F),[]}},q=(H)=>{return Q.searchPrompts(H)},W=(H)=>{return H.map((F)=>{let U=F.path,B=`@${GB(U)}`,M=U.split("/"),L=M[M.length-1]||U,A=M.length>1?M.slice(0,-1).join("/"):"";return{uri:v6(F.uri),label:L,detail:A,insertText:B,filterText:U.toLowerCase(),kind:F.isDirectory()?"folder":"file"}})};return{search(H){let F=q(H),U=J4(async()=>{let B=await G();if(!B)return v.info("No thread with trees found, using MCP resources only"),await K(H);let{trees:M,threadId:L}=B,A=M.find((C)=>C.repository?.url!=null&&C.repository?.sha!=null&&C.fs==="gitlab");if(!A)return v.info("No GitLab repository found in thread trees, using MCP resources only"),await K(H);v.info("Found GitLab repository",{threadId:L,uri:A.uri,repoUrl:A.repository.url,sha:A.repository.sha});let[I,E]=await Promise.all([V(A),K(H)]);if(I.length===0)return E;let P;if(!H)v.info("Empty query, returning first 10 files"),P=I.slice(0,10);else try{P=qT(H,I,{maxResults:50,minScore:400}).map((S)=>S.entry)}catch(C){return v.error("Fuzzy search failed",C),E}return[...W(P),...E]});return h8(F,U).pipe(X6(([B,M])=>{return[...B,...M].slice(0,$B)}))},dispose(){X.clear()}}}function Rb4(J,Q){let Y=J.title||J.name,Z=J.description?`${J.description} (${Q})`:`MCP Resource from ${Q}`,X=`${Q}:${J.uri}`,G="@"+GB(X);return{uri:Ty(X),label:Y,detail:Z,insertText:G,filterText:`${Y} ${Z} ${J.uri}`.toLowerCase()}}var Tx0=$1(()=>{Y4();s0();N0();KT();Yf();Qh();Px0()});function Tb4(J){let Q="id"in J&&typeof J.id==="string"?J.env?.initial?.trees?.find((G)=>G.repository?.url):J;if(!Q?.repository?.url)return null;let Y=new URL(Q.repository.url).origin,Z=XF(Q.repository.url,{gitlabInstanceURL:Y});if(!Z||Z.provider!=="gitlab")return null;let X=Q.repository.headRef?Zf(Q.repository.headRef):Q.repository.ref?Zf(Q.repository.ref):null;return{repo:Z.name,branch:X,provider:"gitlab",instanceURL:Z.instanceURL}}async function Cb4({repo:J,branch:Q,instanceURL:Y},Z,X){if(!Q||!Y)return v.info("GitLab MR check: missing branch or instanceURL",{repo:J,branch:Q,instanceURL:Y}),null;try{let G=encodeURIComponent(J),V=`/projects/${G}/merge_requests?source_branch=${encodeURIComponent(Q)}&state=all&per_page=1&page=1`;v.info("GitLab MR check: making API request",{repo:J,branch:Q,instanceURL:Y,apiEndpoint:V,projectPath:G});let K=await Xf(V,{config:Z,signal:X,cache:"no-cache"});if(!K.ok||!K.data)return v.info("GitLab MR check: API response not ok or no data",{repo:J,branch:Q,response:K}),null;let q=K.data;if(q.length>0){let W=q[0];return{url:v6(m0.parse(W.web_url)),number:W.iid.toString(),merged:W.state==="merged"}}return null}catch(G){return null}}function Cx0(J,Q,Y,Z){v.info("GitLab thread actions: setting up observable for thread",{threadID:Q});let X=J.observe(Q).pipe(X6((G)=>{let V=G.messages.length>=2&&Ue(G);return[{id:G.id,env:G.env},V]}),I4());return h8(X,Z.pipe(d8(void 0),a7((G)=>{return v.error("mergeRequestChanges subject error, continuing with undefined",{error:G,threadID:Q}),Q0.of(void 0)}))).pipe(bZ(([[G,V],K])=>{if(!G||!V)return v.info("GitLab thread actions: no thread or no messages, returning empty",{threadID:Q}),Q0.of([]);let q=Tb4(G);if(!q)return v.info("GitLab thread actions: not a GitLab repository, returning empty",{threadID:Q}),Q0.of([]);return J4(async(W)=>{let H=await Cb4(q,Y,W);if(H)return[{type:H.merged?"view-merged-pull-request":"view-pull-request",url:H.url,number:H.number}];return[{type:"create-pull-request"}]})}),z8({shouldCountRefs:!0}))}var jx0=$1(()=>{Y4();s0();N0();YO1();ZO1()});class $O1{threadService;config;name="github";mentions;pullRequestChanges=new r4;constructor(J,Q,Y,Z){this.threadService=J;this.config=Y;this.mentions=Lx0(J,Q,Y,Z)}getThreadActions(J){return Ox0(this.threadService,J,this.config,this.pullRequestChanges)}canHandle(J){if(!J)return!1;return XF(J,{provider:"github"})?.provider==="github"}dispose(){this.mentions.dispose()}}class Sx0{threadService;config;name="gitlab";mentions;pullRequestChanges=new r4;constructor(J,Q,Y,Z){this.threadService=J;this.config=Y;this.mentions=Rx0(J,Q,Y,Z)}getThreadActions(J){return Cx0(this.threadService,J,this.config,this.pullRequestChanges)}canHandle(J){if(!J)return!1;let Q=new URL(J).origin;return XF(J,{gitlabInstanceURL:Q})?.provider==="gitlab"}dispose(){this.mentions.dispose()}}function _x0(J,Q,Y,Z,X){let G=J.find((q)=>q.repository?.url);if(!G?.repository?.url)return new $O1(Q,Y,Z,X);if(G.repository.url.includes("gitlab.")||G.fs==="gitlab")return new Sx0(Q,Y,Z,X);else return new $O1(Q,Y,Z,X)}var kx0=$1(()=>{s0();Ax0();Ix0();Tx0();jx0()});function G4(J,Q,Y,Z,X){if(Z==="m")throw TypeError("Private method is not writable");if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof Q==="function"?J!==Q||!X:!Q.has(J))throw TypeError("Cannot write private member to an object whose class did not declare it");return Z==="a"?X.call(J,Y):X?X.value=Y:Q.set(J,Y),Y}function T0(J,Q,Y,Z){if(Y==="a"&&!Z)throw TypeError("Private accessor was defined without a getter");if(typeof Q==="function"?J!==Q||!Z:!Q.has(J))throw TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?Z:Y==="a"?Z.call(J):Z?Z.value:Q.get(J)}var $F=()=>{};var GO1=function(){let{crypto:J}=globalThis;if(J?.randomUUID)return GO1=J.randomUUID.bind(J),J.randomUUID();let Q=new Uint8Array(1),Y=J?()=>J.getRandomValues(Q)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Z)=>(+Z^Y()&15>>+Z/4).toString(16))};function GF(J){return typeof J==="object"&&J!==null&&(("name"in J)&&J.name==="AbortError"||("message"in J)&&String(J.message).includes("FetchRequestCanceledException"))}var $f=(J)=>{if(J instanceof Error)return J;if(typeof J==="object"&&J!==null){try{if(Object.prototype.toString.call(J)==="[object Error]"){let Q=Error(J.message,J.cause?{cause:J.cause}:{});if(J.stack)Q.stack=J.stack;if(J.cause&&!Q.cause)Q.cause=J.cause;if(J.name)Q.name=J.name;return Q}}catch{}try{return Error(JSON.stringify(J))}catch{}}return Error(J)};var b4,H2,NQ,IA,Gf,Vf,Kf,qf,Wf,Hf,Ff,zf,Uf;var m$=$1(()=>{b4=class b4 extends Error{};H2=class H2 extends b4{constructor(J,Q,Y,Z){super(`${H2.makeMessage(J,Q,Y)}`);this.status=J,this.headers=Z,this.requestID=Z?.get("request-id"),this.error=Q}static makeMessage(J,Q,Y){let Z=Q?.message?typeof Q.message==="string"?Q.message:JSON.stringify(Q.message):Q?JSON.stringify(Q):Y;if(J&&Z)return`${J} ${Z}`;if(J)return`${J} status code (no body)`;if(Z)return Z;return"(no status code or body)"}static generate(J,Q,Y,Z){if(!J||!Z)return new IA({message:Y,cause:$f(Q)});let X=Q;if(J===400)return new Vf(J,X,Y,Z);if(J===401)return new Kf(J,X,Y,Z);if(J===403)return new qf(J,X,Y,Z);if(J===404)return new Wf(J,X,Y,Z);if(J===409)return new Hf(J,X,Y,Z);if(J===422)return new Ff(J,X,Y,Z);if(J===429)return new zf(J,X,Y,Z);if(J>=500)return new Uf(J,X,Y,Z);return new H2(J,X,Y,Z)}};NQ=class NQ extends H2{constructor({message:J}={}){super(void 0,void 0,J||"Request was aborted.",void 0)}};IA=class IA extends H2{constructor({message:J,cause:Q}){super(void 0,void 0,J||"Connection error.",void 0);if(Q)this.cause=Q}};Gf=class Gf extends IA{constructor({message:J}={}){super({message:J??"Request timed out."})}};Vf=class Vf extends H2{};Kf=class Kf extends H2{};qf=class qf extends H2{};Wf=class Wf extends H2{};Hf=class Hf extends H2{};Ff=class Ff extends H2{};zf=class zf extends H2{};Uf=class Uf extends H2{}});function Be(J){if(typeof J!=="object")return{};return J??{}}function xx0(J){if(!J)return!0;for(let Q in J)return!1;return!0}function vx0(J,Q){return Object.prototype.hasOwnProperty.call(J,Q)}var Sb4,yx0=(J)=>{return Sb4.test(J)},VO1=(J)=>(VO1=Array.isArray,VO1(J)),KO1,hx0=(J,Q)=>{if(typeof Q!=="number"||!Number.isInteger(Q))throw new b4(`${J} must be an integer`);if(Q<0)throw new b4(`${J} must be a positive integer`);return Q},Ne=(J)=>{try{return JSON.parse(J)}catch(Q){return}};var wA=$1(()=>{m$();Sb4=/^[a-z][a-z0-9+.-]*:/i,KO1=VO1});var fx0=(J)=>new Promise((Q)=>setTimeout(Q,J));var TB="0.71.0";function _b4(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}function yb4(){if(typeof navigator>"u"||!navigator)return null;let J=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Q,pattern:Y}of J){let Z=Y.exec(navigator.userAgent);if(Z){let X=Z[1]||0,G=Z[2]||0,V=Z[3]||0;return{browser:Q,version:`${X}.${G}.${V}`}}}return null}var ux0=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},kb4=()=>{let J=_b4();if(J==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":TB,"X-Stainless-OS":gx0(Deno.build.os),"X-Stainless-Arch":bx0(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":TB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(J==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":TB,"X-Stainless-OS":gx0(globalThis.process.platform??"unknown"),"X-Stainless-Arch":bx0(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Q=yb4();if(Q)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":TB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Q.browser}`,"X-Stainless-Runtime-Version":Q.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":TB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},bx0=(J)=>{if(J==="x32")return"x32";if(J==="x86_64"||J==="x64")return"x64";if(J==="arm")return"arm";if(J==="aarch64"||J==="arm64")return"arm64";if(J)return`other:${J}`;return"unknown"},gx0=(J)=>{if(J=J.toLowerCase(),J.includes("ios"))return"iOS";if(J==="android")return"Android";if(J==="darwin")return"MacOS";if(J==="win32")return"Windows";if(J==="freebsd")return"FreeBSD";if(J==="openbsd")return"OpenBSD";if(J==="linux")return"Linux";if(J)return`Other:${J}`;return"Unknown"},mx0,px0=()=>{return mx0??(mx0=kb4())};var qO1=()=>{};function dx0(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function WO1(...J){let Q=globalThis.ReadableStream;if(typeof Q>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Q(...J)}function De(J){let Q=Symbol.asyncIterator in J?J[Symbol.asyncIterator]():J[Symbol.iterator]();return WO1({start(){},async pull(Y){let{done:Z,value:X}=await Q.next();if(Z)Y.close();else Y.enqueue(X)},async cancel(){await Q.return?.()}})}function Bf(J){if(J[Symbol.asyncIterator])return J;let Q=J.getReader();return{async next(){try{let Y=await Q.read();if(Y?.done)Q.releaseLock();return Y}catch(Y){throw Q.releaseLock(),Y}},async return(){let Y=Q.cancel();return Q.releaseLock(),await Y,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function cx0(J){if(J===null||typeof J!=="object")return;if(J[Symbol.asyncIterator]){await J[Symbol.asyncIterator]().return?.();return}let Q=J.getReader(),Y=Q.cancel();Q.releaseLock(),await Y}var lx0=({headers:J,body:Q})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Q)}};function ax0(J){let Q=0;for(let X of J)Q+=X.length;let Y=new Uint8Array(Q),Z=0;for(let X of J)Y.set(X,Z),Z+=X.length;return Y}function Nf(J){let Q;return(nx0??(Q=new globalThis.TextEncoder,nx0=Q.encode.bind(Q)))(J)}function HO1(J){let Q;return(ix0??(Q=new globalThis.TextDecoder,ix0=Q.decode.bind(Q)))(J)}var nx0,ix0;class CB{constructor(){QX.set(this,void 0),YX.set(this,void 0),G4(this,QX,new Uint8Array,"f"),G4(this,YX,null,"f")}decode(J){if(J==null)return[];let Q=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?Nf(J):J;G4(this,QX,ax0([T0(this,QX,"f"),Q]),"f");let Y=[],Z;while((Z=hb4(T0(this,QX,"f"),T0(this,YX,"f")))!=null){if(Z.carriage&&T0(this,YX,"f")==null){G4(this,YX,Z.index,"f");continue}if(T0(this,YX,"f")!=null&&(Z.index!==T0(this,YX,"f")+1||Z.carriage)){Y.push(HO1(T0(this,QX,"f").subarray(0,T0(this,YX,"f")-1))),G4(this,QX,T0(this,QX,"f").subarray(T0(this,YX,"f")),"f"),G4(this,YX,null,"f");continue}let X=T0(this,YX,"f")!==null?Z.preceding-1:Z.preceding,G=HO1(T0(this,QX,"f").subarray(0,X));Y.push(G),G4(this,QX,T0(this,QX,"f").subarray(Z.index),"f"),G4(this,YX,null,"f")}return Y}flush(){if(!T0(this,QX,"f").length)return[];return this.decode(`
369
369
  `)}}function hb4(J,Q){for(let X=Q??0;X<J.length;X++){if(J[X]===10)return{preceding:X,index:X+1,carriage:!1};if(J[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function ox0(J){for(let Z=0;Z<J.length-1;Z++){if(J[Z]===10&&J[Z+1]===10)return Z+2;if(J[Z]===13&&J[Z+1]===13)return Z+2;if(J[Z]===13&&J[Z+1]===10&&Z+3<J.length&&J[Z+2]===13&&J[Z+3]===10)return Z+4}return-1}var QX,YX;var FO1=$1(()=>{$F();QX=new WeakMap,YX=new WeakMap;CB.NEWLINE_CHARS=new Set([`
370
370
  `,"\r"]);CB.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Df(){}function Me(J,Q,Y){if(!Q||Le[J]>Le[Y])return Df;else return Q[J].bind(Q)}function c2(J){let Q=J.logger,Y=J.logLevel??"off";if(!Q)return fb4;let Z=rx0.get(Q);if(Z&&Z[0]===Y)return Z[1];let X={error:Me("error",Q,Y),warn:Me("warn",Q,Y),info:Me("info",Q,Y),debug:Me("debug",Q,Y)};return rx0.set(Q,[Y,X]),X}var Le,zO1=(J,Q,Y)=>{if(!J)return;if(vx0(Le,J))return J;c2(Y).warn(`${Q} was set to ${JSON.stringify(J)}, expected one of ${JSON.stringify(Object.keys(Le))}`);return},fb4,rx0,VF=(J)=>{if(J.options)J.options={...J.options},delete J.options.headers;if(J.headers)J.headers=Object.fromEntries((J.headers instanceof Headers?[...J.headers]:Object.entries(J.headers)).map(([Q,Y])=>[Q,Q.toLowerCase()==="x-api-key"||Q.toLowerCase()==="authorization"||Q.toLowerCase()==="cookie"||Q.toLowerCase()==="set-cookie"?"***":Y]));if("retryOfRequestLogID"in J){if(J.retryOfRequestLogID)J.retryOf=J.retryOfRequestLogID;delete J.retryOfRequestLogID}return J};var Ae=$1(()=>{wA();Le={off:0,error:200,warn:300,info:400,debug:500};fb4={error:Df,warn:Df,info:Df,debug:Df},rx0=new WeakMap});async function*bb4(J,Q){if(!J.body){if(Q.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new b4("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new b4("Attempted to iterate over a response with no body")}let Y=new sx0,Z=new CB,X=Bf(J.body);for await(let G of gb4(X))for(let V of Z.decode(G)){let K=Y.decode(V);if(K)yield K}for(let G of Z.flush()){let V=Y.decode(G);if(V)yield V}}async function*gb4(J){let Q=new Uint8Array;for await(let Y of J){if(Y==null)continue;let Z=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?Nf(Y):Y,X=new Uint8Array(Q.length+Z.length);X.set(Q),X.set(Z,Q.length),Q=X;let G;while((G=ox0(Q))!==-1)yield Q.slice(0,G),Q=Q.slice(G)}if(Q.length>0)yield Q}class sx0{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(J){if(J.endsWith("\r"))J=J.substring(0,J.length-1);if(!J){if(!this.event&&!this.data.length)return null;let X={event:this.event,data:this.data.join(`
371
371
  `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push(J),J.startsWith(":"))return null;let[Q,Y,Z]=mb4(J,":");if(Z.startsWith(" "))Z=Z.substring(1);if(Q==="event")this.event=Z;else if(Q==="data")this.data.push(Z);return null}}function mb4(J,Q){let Y=J.indexOf(Q);if(Y!==-1)return[J.substring(0,Y),Q,J.substring(Y+Q.length)];return[J,"",""]}var Mf,ZX;var UO1=$1(()=>{$F();m$();FO1();wA();Ae();m$();ZX=class ZX{constructor(J,Q,Y){this.iterator=J,Mf.set(this,void 0),this.controller=Q,G4(this,Mf,Y,"f")}static fromSSEResponse(J,Q,Y){let Z=!1,X=Y?c2(Y):console;async function*G(){if(Z)throw new b4("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let V=!1;try{for await(let K of bb4(J,Q)){if(K.event==="completion")try{yield JSON.parse(K.data)}catch(q){throw X.error("Could not parse message into JSON:",K.data),X.error("From chunk:",K.raw),q}if(K.event==="message_start"||K.event==="message_delta"||K.event==="message_stop"||K.event==="content_block_start"||K.event==="content_block_delta"||K.event==="content_block_stop")try{yield JSON.parse(K.data)}catch(q){throw X.error("Could not parse message into JSON:",K.data),X.error("From chunk:",K.raw),q}if(K.event==="ping")continue;if(K.event==="error")throw new H2(void 0,Ne(K.data)??K.data,void 0,J.headers)}V=!0}catch(K){if(GF(K))return;throw K}finally{if(!V)Q.abort()}}return new ZX(G,Q,Y)}static fromReadableStream(J,Q,Y){let Z=!1;async function*X(){let V=new CB,K=Bf(J);for await(let q of K)for(let W of V.decode(q))yield W;for(let q of V.flush())yield q}async function*G(){if(Z)throw new b4("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let V=!1;try{for await(let K of X()){if(V)continue;if(K)yield JSON.parse(K)}V=!0}catch(K){if(GF(K))return;throw K}finally{if(!V)Q.abort()}}return new ZX(G,Q,Y)}[(Mf=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let J=[],Q=[],Y=this.iterator(),Z=(X)=>{return{next:()=>{if(X.length===0){let G=Y.next();J.push(G),Q.push(G)}return X.shift()}}};return[new ZX(()=>Z(J),this.controller,T0(this,Mf,"f")),new ZX(()=>Z(Q),this.controller,T0(this,Mf,"f"))]}toReadableStream(){let J=this,Q;return WO1({async start(){Q=J[Symbol.asyncIterator]()},async pull(Y){try{let{value:Z,done:X}=await Q.next();if(X)return Y.close();let G=Nf(JSON.stringify(Z)+`
@@ -3989,11 +3989,11 @@ Actual: ${X}`)}async function LU8(J,Q,Y){let{execSync:Z}=await import("node:ch
3989
3989
  ${B}`;if(X==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
3990
3990
 
3991
3991
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
3992
- npm install -g @sourcegraph/amp`;K(Error(M))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}N0();N0();async function Y51(J,Q){let Z=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Z}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=EU8(J,q),H=W<0,F,U;if(K.time){let B=K.time[J],M=K.time[q],L=Date.now();if(B)F=Math.floor((L-new Date(B).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return v.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:F,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:F,latestVersionAge:U,source:"npm"}}catch(X){return v.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function EU8(J,Q){let Y=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Z=Y(J),X=Y(Q),G=Math.max(Z.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Z.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Z.label===X.label)return 0;if(!Z.label&&X.label)return 1;if(Z.label&&!X.label)return-1;if(Z.label&&X.label)return Z.label<X.label?-1:1;return 0}s0();function Z51(J,Q){let Y=new r4,Z=Y.pipe(z8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new Zq().scoped("update"),G=Z.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await eC(500),Y.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=LI(),W=await Y51(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,B=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},F=await Q51();if(!K)K=F==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:K});if(K==="warn"){if(!H())Y.next("update-available");return}if(!F){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(F==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Kp(W.latestVersion,F);let U=await sN(W.latestVersion),B={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",B),Y.next("updated");else X.warn("success with warning",B),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await eC(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:Z}}ns();import{stderr as MW}from"node:process";function mJ6(J){let Q=new tV().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Z)=>{await Oy1(Z.force||!1,Z.verbose||!1,"0.0.1766217674-gf10025"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new tV("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Z)=>{await PU8(Z.targetVersion)});J.addCommand(Y)}async function PU8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")MW.write(V6.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
3992
+ npm install -g @sourcegraph/amp`;K(Error(M))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}N0();N0();async function Y51(J,Q){let Z=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Z}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=EU8(J,q),H=W<0,F,U;if(K.time){let B=K.time[J],M=K.time[q],L=Date.now();if(B)F=Math.floor((L-new Date(B).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return v.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:F,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:F,latestVersionAge:U,source:"npm"}}catch(X){return v.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function EU8(J,Q){let Y=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Z=Y(J),X=Y(Q),G=Math.max(Z.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Z.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Z.label===X.label)return 0;if(!Z.label&&X.label)return 1;if(Z.label&&!X.label)return-1;if(Z.label&&X.label)return Z.label<X.label?-1:1;return 0}s0();function Z51(J,Q){let Y=new r4,Z=Y.pipe(z8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new Zq().scoped("update"),G=Z.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await eC(500),Y.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=LI(),W=await Y51(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,B=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},F=await Q51();if(!K)K=F==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:K});if(K==="warn"){if(!H())Y.next("update-available");return}if(!F){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(F==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Kp(W.latestVersion,F);let U=await sN(W.latestVersion),B={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",B),Y.next("updated");else X.warn("success with warning",B),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await eC(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:Z}}ns();import{stderr as MW}from"node:process";function mJ6(J){let Q=new tV().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Z)=>{await Oy1(Z.force||!1,Z.verbose||!1,"0.0.1766222627-g05555f"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new tV("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Z)=>{await PU8(Z.targetVersion)});J.addCommand(Y)}async function PU8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")MW.write(V6.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
3993
3993
 
3994
3994
  `));try{if(!J){MW.write(V6.blue(`Checking for updates...
3995
- `));let Y=LI(),{hasUpdate:Z,latestVersion:X}=await Y51("0.0.1766217674-gf10025",Y);if(!Z){MW.write(V6.green(`✓ Amp CLI is already up to date: ${"0.0.1766217674-gf10025"} (${"released"} ${"2025-12-20T08:06:30.612Z"}${`, ${kR(new Date("2025-12-20T08:06:30.612Z"))} ago`})
3996
- `));let V=await sN("0.0.1766217674-gf10025");if(V.warning)MW.write(`
3995
+ `));let Y=LI(),{hasUpdate:Z,latestVersion:X}=await Y51("0.0.1766222627-g05555f",Y);if(!Z){MW.write(V6.green(`✓ Amp CLI is already up to date: ${"0.0.1766222627-g05555f"} (${"released"} ${"2025-12-20T09:28:57.003Z"}${`, ${kR(new Date("2025-12-20T09:28:57.003Z"))} ago`})
3996
+ `));let V=await sN("0.0.1766222627-g05555f");if(V.warning)MW.write(`
3997
3997
  `+V6.yellow(V.warning)+`
3998
3998
  `);process.exit(0)}if(!X)MW.write(V6.yellow("[WARN] could not find latest version")),process.exit(0);J=X}MW.write(V6.blue(`Updating to version ${J}...
3999
3999
  `)),await Kp(J,void 0,(Y)=>{MW.write(V6.dim(`Running: ${Y}
@@ -4713,7 +4713,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let c=W.text.replace(/`([^`]+)`/g,"$1")+`
4713
4713
  `,A)])}),S];if(!q&&!U&&W.url){let b=W.url.replace(/^https?:\/\//,"");f.push(new Q7({uri:W.url,text:b,style:new J1({color:Y.secondary,underline:!0})}))}if(C&&!U)f.push(C);let m=new Z0({width:40,child:new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:f})});return j4.child(new U6({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new hx1({width:Lf1,height:Af1,agentMode:this.widget.agentMode,glow:this._glow,t:H,fps:0,shockwaves:this._shockwaves,onShockwave:P,...V==="disabled"&&{seed:42}}),new Z0({width:2}),m]}))}}N0();U8();x4();L7();U8();s0();function xP8(J,Q){return`${J}:${Q}`}class Of1{threadService;workers=new Map;threadsMap=new Map;subthreadsMap=new Map;mainThreadSubs=new Map;subthreadsSubs=new Map;workerStatusSubs=new Map;subthreadPatchSubs=new Map;mainThreadObservable;subthreadObservable;workerStatusObservable;emitMainThread=null;emitSubthread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new Q0((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.subthreadObservable=new Q0((Q)=>{return this.emitSubthread=(Y)=>Q.next(Y),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new Q0((Q)=>{return this.emitWorkerStatus=(Y)=>Q.next(Y),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.subthreadsMap.set(Q,[]),this.workers.set(Q,{state:"initial"});let Y=this.threadService.observePatches(Q).pipe(PL()).subscribe((G)=>{this.threadsMap.set(Q,G);let V=this.subthreadsMap.get(Q)||[],K=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:G,subthreads:V,workerStatus:K})});this.mainThreadSubs.set(Q,Y);let Z=J.status.subscribe((G)=>{if(this.workers.set(Q,G),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:G})});this.workerStatusSubs.set(Q,Z);let X=J.subthreads.subscribe((G)=>{this.subthreadsMap.set(Q,G);for(let V of G){let K=xP8(Q,V.toolUse.id);if(this.subthreadPatchSubs.has(K))continue;let q=this.threadService.observePatches(V.threadID).pipe(PL()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:V})});this.subthreadPatchSubs.set(K,q)}});this.subthreadsSubs.set(Q,X)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Y=this.workerStatusSubs.get(J);if(Y)Y.unsubscribe(),this.workerStatusSubs.delete(J);let Z=this.subthreadsSubs.get(J);if(Z)Z.unsubscribe(),this.subthreadsSubs.delete(J);for(let[X,G]of this.subthreadPatchSubs.entries())if(X.startsWith(`${J}:`))G.unsubscribe(),this.subthreadPatchSubs.delete(X);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new Q0((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),subthreads:new Q0((Q)=>{return this.subthreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new Q0((Q)=>{return this.workerStatusObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})})}}get threadViewStates(){let J={};for(let[Q,Y]of this.threadsMap){let Z=this.workers.get(Q);if(Z)J[Q]=fO(Y,Z)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.subthreadsSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();for(let J of this.subthreadPatchSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.subthreadsSubs.clear(),this.workerStatusSubs.clear(),this.subthreadPatchSubs.clear(),this.workers.clear(),this.threadsMap.clear(),this.subthreadsMap.clear()}}function vP8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Y,subthread:Z}=Q,X=J.subagents[Z.threadID];if(!X){if(X={subThreadID:Y.id,parentToolID:Z.toolUse.id,taskDescription:Z.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=GQ(J.mainThread);X.isCompleted=iV6(W,Z.toolUse.id)}}let G=hP8(Y,X.agentState),V=X.agentState===G?X:{...X,agentState:G},K={...J.tools},q=AS(Y).items.filter((W)=>W.type==="toolResult");for(let W of q)K[W.id]={id:W.id,subthreadID:Y.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[Z.threadID]:V},tools:K,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Y,subthreads:Z,workerStatus:X}=Q,G=GQ(Y),V={...J.subagents};for(let F of Z){let U=V[F.threadID];if(!U)continue;let B=iV6(G,F.toolUse.id);V[F.threadID]={...U,isCompleted:B}}let{items:K}=AS(Y),q=fO(Y,X),W=SU({messages:Y.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:V,items:K,viewState:q,todosList:H,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=fO(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function AS(J){let Q=[],Y=new Map,Z=new Set;for(let[X,G]of J.messages.entries()){let V=`${G.role}-${X}`;switch(G.role){case"assistant":{let K=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(Y.set(W.id,W),K)Z.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,message:G});for(let W of G.content)if(W.type==="tool_use"){let H=!1;for(let F=X+1;F<J.messages.length;F++){let U=J.messages[F];if(U){for(let B of U.content)if(B.type==="tool_result"&&B.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:K?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:V,message:G});break;case"user":{let K=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=Y.get(q.toolUseID)??dZ(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(K)Q.push({type:"message",id:V,message:G});break}}}return{items:Q}}function iV6(J,Q){let Y=J.get(Q);return(Y&&y7(Y.run))??!1}function hP8(J,Q){let Y=J.messages.at(-1);if(Y?.content.some((X)=>X.type==="tool_result"&&X.run.status==="blocked-on-user"))return v.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(AS(J).items.some((X)=>X.type==="toolResult"&&X.toolResult.run.status==="in-progress")){let X=Q?.type==="running-tools"?Q.startTime:Date.now();return v.info("Subagent status: running-tools",{threadID:J.id,startTime:X,hasStartTime:!!X}),{type:"running-tools",startTime:X}}if(Y&&Y.role==="assistant"&&Y.state.type==="streaming")switch(Y.content.at(-1)?.type){case"text":return v.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return v.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let G=Q?.type==="running-tools"?Q.startTime:Date.now();return v.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}default:return v.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return v.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class If1 extends d0{props;constructor(J){super();this.props=J}createState(){return new aV6}}class aV6 extends p0{state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new Of1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Y=Q.mainThread.subscribe((G)=>{this.dispatch({type:"main-thread-patch",thread:G.mainThread,subthreads:G.subthreads,workerStatus:G.workerStatus})});this.subscriptions.push(Y);let Z=Q.subthreads.subscribe((G)=>{this.dispatch({type:"subthread-patch",thread:G.thread,subthread:G.subthread})});this.subscriptions.push(Z);let X=Q.workerStatus.subscribe((G)=>{this.dispatch({type:"worker-status-change",workerStatus:G.status})});this.subscriptions.push(X)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=vP8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((G)=>({toolUse:G.toolUse,toolRun:G.toolRun,subthreadID:G.subthreadID})),Q={};for(let G of Object.values(this.state.subagents)){let V=J.filter((K)=>K.subthreadID===G.subThreadID);Q[G.parentToolID]=V}let Y=(G)=>G===r5||G===A9||G===Vq,Z=new Map;for(let G of this.state.items)if(G.type==="toolResult"&&Y(G.toolUse.name))Z.set(G.toolUse.id,{toolUseId:G.toolUse.id,toolName:G.toolUse.name,toolRun:G.toolResult.run});let X=Array.from(Z.values());for(let{toolUseId:G,toolRun:V}of X){let K=[],q;if(V.status==="in-progress"||V.status==="done"||V.status==="error"||V.status==="cancelled")q=V.progress;if(q){let W=0;for(let H of q)if(H.tool_uses)for(let F of H.tool_uses){let U=`${G}:progress:${W++}`;K.push({toolUse:qP(F.tool_name,F.input,U),toolRun:{status:F.status}})}}Q[G]=K}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker,this.recentThreadIDs)}}class wf1 extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new oV6}}class oV6 extends p0{build(J){let Y=q6.of(J).colors,{todos:Z,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Z)||Z.length===0)return new Z0({width:0,height:0});let G=Z.map((V)=>this.buildTodoItem(V,Y));return new g0({child:new B6({padding:z0.symmetric(1,0),child:new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new j1({text:new d(X,new J1({bold:!0,color:Y.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),Z=J.status==="completed",X=new J1({bold:J.status==="in-progress",color:Q.foreground,dim:Z}),G=new J1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Z});return new U6({crossAxisAlignment:"start",children:[new j1({text:new d(Y,X)}),new Z0({width:1}),new a6({child:new j1({text:new d(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Ef1 extends l6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Y,onButtonClick:Z}){super({key:J});this.ad=Q,this.onDismiss=Y,this.onButtonClick=Z}build(J){let Q=q6.of(J),Y=Q.colors.primary,Z=Q.colors.foreground;return new g0({decoration:new T8(void 0,new B4(new W4(Y,1,"rounded"),new W4(Y,1,"rounded"),void 0,new W4(Y,1,"rounded"))),child:new B6({padding:z0.horizontal(1),child:new x0({children:[new U6({crossAxisAlignment:"start",children:[new a6({child:new j1({text:new d(this.ad.content,new J1({color:Z}))})}),new Z0({width:4}),new Q7({uri:"https://ampcode.com/free",text:"Ad",style:new J1({color:Z,dim:!0})})]}),new U6({crossAxisAlignment:"start",children:[new nx1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:z0.horizontal(1),color:Y,reverse:!0}),new Z0({width:2}),new j1({text:new d(this.ad.destinationUrlHostname,new J1({color:Z,dim:!0}))})]})]})})})}}class Pf1 extends d0{props;constructor(J){super();this.props=J}createState(){return new rV6(this.props.autofocus??!0)}}class rV6 extends p0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(K)=>{if(K.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(K.ctrlKey&&K.key==="c"||K.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=C4.sizeOf(J),Z=Math.min(60,Y.width-4),X=Y.height-4,G=[];if(this.widget.props.title)G.push(new j1({text:new d(this.widget.props.title,new J1({bold:!0,color:N1.blue}))}),new Z0({height:1}));if(this.widget.props.message)G.push(new j1({text:new d(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)G.push(new Z0({height:1}));let V=[];if(this.widget.props.showCopyOption)V.push(new j1({text:new d("Enter to copy",new J1({dim:!0}))}));return V.push(new j1({text:new d("Escape to close",new J1({dim:!0}))})),G.push(new U6({children:V.flatMap((K,q)=>q<V.length-1?[K,new Z0({width:1}),new j1({text:new d("•",new J1({dim:!0}))}),new Z0({width:1})]:[K]),mainAxisSize:"min"})),new j4({child:new g0({constraints:new I6(Z,Z,0,X),decoration:new T8(N1.default(),new B4(new W4(N1.blue,1,"rounded"),new W4(N1.blue,1,"rounded"),new W4(N1.blue,1,"rounded"),new W4(N1.blue,1,"rounded"))),padding:new z0(2,2,2,2),child:new w8({autofocus:this.autofocus,onKey:Q,child:new x0({children:G,mainAxisSize:"min"})})})})}}function Rf1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Y)=>{if(Y.startsWith('"')&&Y.endsWith('"')||Y.startsWith("'")&&Y.endsWith("'"))return Y.slice(1,-1);return Y})}oH();N0();import{spawn as fP8}from"node:child_process";import{promises as bP8}from"node:fs";function sV6(J){return J.kind==="executable"}function tV6(J){return J.kind==="markdown"}var Bz=50000,eV6=300000;async function Tf1(J,Q,Y,Z={}){let{timeoutMs:X=eV6,signal:G,source:V}=Z;try{let K=await Y.getCommand(J,V);if(!K)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Y.isCommandAvailable(J,V))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(v.debug("Executing command",{commandName:J,filePath:K.filePath,args:Q}),tV6(K))return await gP8(K,Q);else if(sV6(K))return await mP8(K,Q,X,G);else return{success:!1,output:"",error:"Unsupported command type"}}catch(K){return v.error("Failed to execute command",{commandName:J,error:K}),{success:!1,output:"",error:K instanceof Error?K.message:"Unknown error occurred"}}}async function gP8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await bP8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>Bz?Y.slice(0,Bz)+`
4714
4714
  ... (output truncated at ${Bz} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function mP8(J,Q,Y=eV6,Z){return new Promise((X)=>{let[G,V]=uP8(J,Q);v.debug("Spawning command",{spawnCommand:G,spawnArgs:V.slice(0,10),filePath:J.filePath,timeoutMs:Y});let K=QC0(Z),q=!1,W=setTimeout(()=>{q=!0,K.abort(),v.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=fP8(G,V,{stdio:["pipe","pipe","pipe"],signal:K.signal,detached:!0}),F=[],U=[],B=0;H.stdout?.on("data",(M)=>{let L=M.toString();if(B+=L.length,B<=Bz)F.push(L);else{let A=Bz-(B-L.length);if(A>0)F.push(L.slice(0,A))}}),H.stderr?.on("data",(M)=>{let L=M.toString();if(B+=L.length,B<=Bz)U.push(L);else{let A=Bz-(B-L.length);if(A>0)U.push(L.slice(0,A))}}),H.on("close",(M)=>{if(clearTimeout(W),q){X({success:!1,output:F.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(K.signal.aborted){X({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let L=M===0||M===1,A=F.join(""),I=U.join(""),E=A;if(!L&&!A.trim()&&I.trim())E=I;else if(I.trim())E+=A?`
4715
4715
  ${I}`:I;if(B>Bz)E+=`
4716
- ... (output truncated at ${Bz} characters)`;X({success:L,output:E.trim(),error:!L?I.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(q)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";X({success:!1,output:F.join(""),error:L})})})}function uP8(J,Q){let{filePath:Y,interpreter:Z,extension:X}=J;if(process.platform==="win32")return dP8(Y,Z?[...Z]:null,X,Q);else return pP8(Y,Z?[...Z]:null,X,Q)}function pP8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];else return[J,Z]}function dP8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Z]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Z]];case".exe":return[J,Z];default:return[J,Z]}}N0();A$();q7();CR();hH();BQ();f$();rH();hq();U8();Am();L7();Cy();s0();var SK6=Q6(EB(),1);import{writeFile as PK6}from"fs/promises";import RK6 from"path";N0();BQ();class Cf1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1766217674-gf10025"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Wt(Q,this.configService)}catch(Q){v.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class AD extends d0{props;constructor(J){super();this.props=J}createState(){return new JK6}}class JK6 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class QK6 extends p0{controller=new LZ;focusNode=new D8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=q6.of(J),{colors:Y,app:Z}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=B4.all(new W4(Y.foreground,1,"solid")),q=new qz({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(B)=>{let M=B.trim();if(X&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new U6({children:[new g0({decoration:{color:N1.default()},child:new j1({text:new d(">",new J1({color:Y.foreground}))})}),new a6({child:q})]}),H=new g0({padding:z0.symmetric(1,0),child:new j1({text:new d("",void 0,[new d("Command: ",new J1({color:Y.foreground})),new d(this.widget.props.commandName,new J1({color:N1.yellow,bold:!0}))])})}),F=[];if(V)F.push(new d("Enter",new J1({color:Z.keybind}))),F.push(new d(" to submit, ",new J1({color:Y.foreground,dim:!0})));F.push(new d("Esc",new J1({color:Z.keybind}))),F.push(new d(" to cancel",new J1({color:Y.foreground,dim:!0})));let U=new g0({padding:z0.symmetric(1,0),child:new j1({text:new d("",void 0,F)})});return new g0({decoration:{border:K,color:N1.default()},padding:z0.all(1),child:new x0({children:[H,new Z0({height:1}),W,new c5,U]})})}}class Gd extends d0{props;constructor(J){super();this.props=J}createState(){return new QK6}}rH();class YK6 extends p0{controller=new LZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new D8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=XB)return!1;let Q=JS(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=q6.of(J),{colors:Y,app:Z}=Q,G=C4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new cI({controller:this.controller,triggers:[new SW],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(B)=>{this.widget.props.onSubmit(B.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:y8.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new w8({focusNode:this.focusNode,child:K}),W=new g0({constraints:new I6({maxHeight:V}),padding:z0.symmetric(1,0),child:q}),H=new g0({padding:z0.symmetric(1,0),child:new j1({text:new d("",void 0,[new d("Command: ",new J1({color:Y.foreground})),new d(this.widget.props.commandName,new J1({color:N1.yellow,bold:!0}))])})}),F=new g0({padding:z0.symmetric(1,0),child:new j1({text:this.isConfirmingClearInput?new d("",void 0,[new d("Esc",new J1({color:Z.keybind})),new d(" again to clear input",new J1({color:Y.foreground,dim:!0}))]):new d("",void 0,[new d("Press ",new J1({color:Y.foreground,dim:!0})),new d("Enter",new J1({color:Z.keybind})),new d(" to submit, ",new J1({color:Y.foreground,dim:!0})),new d("Esc",new J1({color:Z.keybind})),new d(" to clear",new J1({color:Y.foreground,dim:!0}))])})}),U=[H,new Z0({height:1}),new a6({child:W}),new Z0({height:1}),F];return new g0({decoration:{border:B4.all(new W4(Y.foreground,1,"solid")),color:N1.default()},padding:z0.all(1),child:new x0({children:U})})}}class jf1 extends d0{props;constructor(J){super();this.props=J}createState(){return new YK6}}import{isDeepStrictEqual as iP8}from"node:util";var cP8=/[\\/_ +.#"@[({&]/,lP8=/[\\/_ +.#"@[({&]/g,nP8=/[\s-]/,ZK6=/[\s-]/g;function x31(J,Q,Y,Z,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Z.charAt(G),W=Y.indexOf(q,X),H=0,F,U,B,M;while(W>=0){if(F=x31(J,Q,Y,Z,W+1,G+1,V),F>H){if(W===X)F*=1;else if(nP8.test(J.charAt(W-1))){if(F*=0.9,M=J.slice(X,W-1).match(ZK6),M&&X>0)F*=Math.pow(0.999,M.length)}else if(cP8.test(J.charAt(W-1))){if(F*=0.8,B=J.slice(X,W-1).match(lP8),B&&X>0)F*=Math.pow(0.999,B.length)}else if(F*=0.3,X>0)F*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))F*=0.9999}if(F<0.1&&(Y.charAt(W-1)===Z.charAt(G+1)||Z.charAt(G+1)===Z.charAt(G)&&Y.charAt(W-1)!==Z.charAt(G))){if(U=x31(J,Q,Y,Z,W+1,G+2,V),U*0.1>F)F=U*0.1}if(F>H)H=F;W=Y.indexOf(q,W+1)}return V[K]=H,H}function y31(J){return J.toLowerCase().replace(ZK6," ")}function XK6(J,Q){let Y=x31(J,Q,y31(J),y31(Q),0,0,{}),Z=Q.trim().split(/\s+/);if(Z.length>1){let X=0,G=0;for(let K of Z){let q=x31(J,K,y31(J),y31(K),0,0,{});if(q===0)return Y;X+=q,G+=K.length}let V=X/Z.length*0.95;return Math.max(Y,V)}return Y}class OS{}class IS{}class v31{}class h31{}class $K6 extends d0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new GK6}}class GK6 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function aP8(J,Q){if(J==="")return{matches:!0,score:1};let Y=XK6(Q,J);return{matches:Y>0.15,score:Y}}class e2 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new VK6}}class VK6 extends p0{controller=new LZ;focusNode;scrollController=new O5;selectedIndex=0;itemContexts=[];cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new D8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),n8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[0]??null)}),this.recomputeFilteredItems();let J=this.cachedFiltered;this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!iP8(J.props.items,this.widget.props.items)){this.recomputeFilteredItems(),this.ensureSelectedItemVisible();let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof OS){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),n8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof IS){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),n8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof v31){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Y=Q[this.selectedIndex];if(Y){if(!(this.widget.props.isItemDisabled?.(Y)??!1))this.widget.props.onAccept(Y)}}return"handled"}if(J instanceof h31)return this.widget.props.onDismiss?.(),"handled";return"ignored"};recomputeFilteredItems(){let J=this.controller.text,Q=this.widget.props.items,Y=Q.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...aP8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,X)=>this.widget.props.sortItems(Z,X,J):(Z,X)=>X.score-Z.score).map((Z)=>Z.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;E71(J,{top:Y,bottom:Z},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),n8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Y=this.getFilteredItems();if(J>=0&&J<Y.length){let Z=Y[J],X=Z?this.widget.props.isItemDisabled?.(Z)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!X){if(Z)this.widget.props.onAccept(Z)}}};build(J){let Q=q6.of(J),{colors:Y}=Q,Z=this.getFilteredItems(),X=B4.all(new W4(Y.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new qz({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Y.foreground,border:null},maxLines:1}),K=new xX({shortcuts:new Map([[new N4("ArrowDown"),new OS],[new N4("ArrowUp"),new IS],[new N4("Tab"),new OS],[new N4("Tab",{shift:!0}),new IS],[new N4("n",{ctrl:!0}),new OS],[new N4("p",{ctrl:!0}),new IS],[new N4("Enter"),new v31],[new N4("Escape"),new h31]]),focusNode:this.focusNode,child:V}),q=new kJ({actions:new Map([[OS,new C8(this.invoke)],[IS,new C8(this.invoke)],[v31,new C8(this.invoke)],[h31,new C8(this.invoke)]]),child:K}),W=new U6({children:[new g0({decoration:{color:N1.default()},child:new j1({text:new d(">",new J1({color:Y.foreground}))})}),new a6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new Z0({height:10,child:new j4({child:new j1({text:new d(L,new J1({color:Y.foreground}))})})})}else if(Z.length===0&&this.widget.props.emptyStateText)H=new a6({child:new j4({child:new j1({text:new d(this.widget.props.emptyStateText,new J1({color:Y.foreground,dim:!0}))})})});else{let L=Z.map((A,I)=>{let E=I===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,R;if(this.widget.props.renderItem)R=this.widget.props.renderItem(A,E,P,J);else{let C=E?N1.yellow:void 0,S=E?N1.black:Y.foreground;R=new g0({decoration:C?{color:C}:void 0,padding:z0.symmetric(2,0),child:new j1({text:new d(this.widget.props.getLabel(A),new J1({color:S,dim:P}))})})}return new $K6(new M8({onClick:(C)=>this.handleItemClick(I,C.clickCount),child:R}),(C)=>{this.itemContexts[I]=C})});H=new x0({children:L,crossAxisAlignment:"start"})}let F=new a6({child:new M8({onScroll:this.handleScroll,opaque:!1,child:new J5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new g0({padding:z0.symmetric(1,0),child:new j1({text:new d(this.widget.props.title,new J1({color:N1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new Z0({height:1}),F),this.controller.text!==""){let L=Z.length>0?Z[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new g0({padding:z0.vertical(1),child:new j4({child:A})}));else U.push(new Z0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new g0({decoration:{border:X,color:N1.default()},padding:z0.symmetric(1,0),child:new x0({children:U})})}}function KK6(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/60000),X=Math.floor(Y/3600000),G=Math.floor(Y/86400000);if(Z<1)return"just now";if(Z<60)return`${Z}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class Sf1 extends l6{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Y=Math.max(0,...Q.map((X)=>KK6(X.pubDate).length));return new e2({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=q6.of(K),{colors:W}=q,H=G?N1.yellow:void 0,F=G?N1.black:W.foreground,U=N1.index(8),B=(M,L)=>new Z0({width:L,child:U6.end([new j1({text:new d(M,new J1({color:U}))})])});return new g0({decoration:H?{color:H}:void 0,padding:z0.symmetric(2,0),child:new U6({children:[new a6({child:new j1({text:new d(X.title,new J1({color:F})),overflow:"ellipsis",maxLines:1})}),new Z0({width:2}),B(KK6(X.pubDate),Y)]})})}})}}class _f1 extends d0{createState(){return new qK6}}class qK6 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){return new j1({text:new d("●",new J1({color:this.isGreen?N1.green:N1.index(8),bold:!0})),maxLines:1})}}function oP8(J){let Q=new Map,Y=new Map,Z=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Z.set(V.id,K.type);let q=K.threadID,W=Y.get(q)||[];W.push(V),Y.set(q,W)}else X.push(V)}return hX.flatten(X,(V)=>Y.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Z.get(V.item.id)}))}function kf1(J,Q,Y){return new j1({text:new d(`${J}${Q}`,new J1({color:Y})),maxLines:1})}function rP8(J,Q,Y,Z){return[kf1("+",J,Z.success),c5.horizontal(1),kf1("~",Q,Z.warning),c5.horizontal(1),kf1("-",Y,Z.destructive)]}class f31 extends l6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((F)=>F.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((F)=>F.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],Z=new Set(Y),X=this.props.currentThreadID,G=[...Q].sort((F,U)=>{if(X){if(F.id===X)return-1;if(U.id===X)return 1}let B=Y.indexOf(F.id),M=Y.indexOf(U.id);if(B!==-1&&M!==-1)return B-M;if(B!==-1)return-1;if(M!==-1)return 1;return 0}),V=oP8(G),K=Math.max(0,...V.map((F)=>F.description.timeAgo.length)),q=q6.of(J),W=new B6({padding:z0.symmetric(0,1),child:new j4({child:new j1({text:new d("",new J1({color:q.colors.foreground,dim:!0}),[new d("Ctrl+T",new J1({color:N1.blue,dim:!0})),new d(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new J1({color:q.colors.foreground,dim:!0}))])})})});return new e2({items:V,getLabel:(F)=>F.title,onAccept:(F)=>this.props.onSelect?.(F.id),onDismiss:this.props.onDismiss,onSelectionChange:(F)=>{if(this.props.previewController){if(F)this.props.previewController.select(F.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(F,U,B,M)=>{let L=q6.of(M),{colors:A}=L,I=U?N1.yellow:void 0,E=U?N1.black:A.foreground,P=N1.index(8),R=(r,p)=>new Z0({width:p,child:U6.end([new j1({text:new d(r,new J1({color:P}))})])}),C=this.props.threadViewStates[F.id],S=[],k=F.relationshipType==="handoff",f=new y71;if(F.depth>0){let r=[],p=F.ancestorsAreLast.slice(1);for(let Y1 of p)r.push(new d(f.getAncestorPrefix(Y1),new J1({color:f.connectorColor,dim:f.connectorDim})));let s=F.isLast?f.elbow:f.tee,Q1=f.getConnectorText(s);r.push(new d(Q1,new J1({color:f.connectorColor,dim:f.connectorDim}))),S.push(new j1({text:new d("",void 0,r)}))}let m=[],b=X===F.id?new d("(current) ",new J1({color:N1.green})):Z.has(F.id)?new d("(visited) ",new J1({color:A.foreground,dim:!0})):null;if(b)m.push(new j1({text:b}));if(C){if(C.state==="active"&&(C.interactionState==="tool-running"||C.inferenceState==="running"))m.push(new _f1),m.push(new Z0({width:1}))}let c=F.title;if(F.relationshipType==="fork"){let r=c.match(/^Forked\((\d+)\): /);if(r)c=c.slice(r[0].length);else while(c.startsWith("Forked: "))c=c.slice(8);m.push(new j1({text:new d("[fork] ",new J1({color:N1.blue}))}))}else if(k)m.push(new j1({text:new d("[handoff] ",new J1({color:N1.index(208)}))}));if(m.push(new a6({child:new j1({text:new d(c,new J1({color:E})),overflow:"ellipsis",maxLines:1})})),m.push(new Z0({width:2})),F.diffStats&&(F.diffStats.added>0||F.diffStats.changed>0||F.diffStats.deleted>0)){let r=U?{success:P,warning:P,destructive:P}:A;m.push(...rP8(F.diffStats.added,F.diffStats.changed,F.diffStats.deleted,r)),m.push(new Z0({width:2}))}return m.push(R(F.description.timeAgo,K)),new g0({decoration:I?{color:I}:void 0,padding:z0.symmetric(2,0),child:new U6({children:[...S,...m]})})}})}}class yf1 extends l6{props;constructor(J){super();this.props=J}build(){return new j4({child:new j1({text:new d("",void 0,[new d(`Forked to new thread:
4716
+ ... (output truncated at ${Bz} characters)`;X({success:L,output:E.trim(),error:!L?I.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(q)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";X({success:!1,output:F.join(""),error:L})})})}function uP8(J,Q){let{filePath:Y,interpreter:Z,extension:X}=J;if(process.platform==="win32")return dP8(Y,Z?[...Z]:null,X,Q);else return pP8(Y,Z?[...Z]:null,X,Q)}function pP8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];else return[J,Z]}function dP8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Z]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Z]];case".exe":return[J,Z];default:return[J,Z]}}N0();A$();q7();CR();hH();BQ();f$();rH();hq();U8();Am();L7();Cy();s0();var SK6=Q6(EB(),1);import{writeFile as PK6}from"fs/promises";import RK6 from"path";N0();BQ();class Cf1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1766222627-g05555f"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Wt(Q,this.configService)}catch(Q){v.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class AD extends d0{props;constructor(J){super();this.props=J}createState(){return new JK6}}class JK6 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class QK6 extends p0{controller=new LZ;focusNode=new D8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=q6.of(J),{colors:Y,app:Z}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=B4.all(new W4(Y.foreground,1,"solid")),q=new qz({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(B)=>{let M=B.trim();if(X&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new U6({children:[new g0({decoration:{color:N1.default()},child:new j1({text:new d(">",new J1({color:Y.foreground}))})}),new a6({child:q})]}),H=new g0({padding:z0.symmetric(1,0),child:new j1({text:new d("",void 0,[new d("Command: ",new J1({color:Y.foreground})),new d(this.widget.props.commandName,new J1({color:N1.yellow,bold:!0}))])})}),F=[];if(V)F.push(new d("Enter",new J1({color:Z.keybind}))),F.push(new d(" to submit, ",new J1({color:Y.foreground,dim:!0})));F.push(new d("Esc",new J1({color:Z.keybind}))),F.push(new d(" to cancel",new J1({color:Y.foreground,dim:!0})));let U=new g0({padding:z0.symmetric(1,0),child:new j1({text:new d("",void 0,F)})});return new g0({decoration:{border:K,color:N1.default()},padding:z0.all(1),child:new x0({children:[H,new Z0({height:1}),W,new c5,U]})})}}class Gd extends d0{props;constructor(J){super();this.props=J}createState(){return new QK6}}rH();class YK6 extends p0{controller=new LZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new D8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=XB)return!1;let Q=JS(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=q6.of(J),{colors:Y,app:Z}=Q,G=C4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new cI({controller:this.controller,triggers:[new SW],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(B)=>{this.widget.props.onSubmit(B.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:y8.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new w8({focusNode:this.focusNode,child:K}),W=new g0({constraints:new I6({maxHeight:V}),padding:z0.symmetric(1,0),child:q}),H=new g0({padding:z0.symmetric(1,0),child:new j1({text:new d("",void 0,[new d("Command: ",new J1({color:Y.foreground})),new d(this.widget.props.commandName,new J1({color:N1.yellow,bold:!0}))])})}),F=new g0({padding:z0.symmetric(1,0),child:new j1({text:this.isConfirmingClearInput?new d("",void 0,[new d("Esc",new J1({color:Z.keybind})),new d(" again to clear input",new J1({color:Y.foreground,dim:!0}))]):new d("",void 0,[new d("Press ",new J1({color:Y.foreground,dim:!0})),new d("Enter",new J1({color:Z.keybind})),new d(" to submit, ",new J1({color:Y.foreground,dim:!0})),new d("Esc",new J1({color:Z.keybind})),new d(" to clear",new J1({color:Y.foreground,dim:!0}))])})}),U=[H,new Z0({height:1}),new a6({child:W}),new Z0({height:1}),F];return new g0({decoration:{border:B4.all(new W4(Y.foreground,1,"solid")),color:N1.default()},padding:z0.all(1),child:new x0({children:U})})}}class jf1 extends d0{props;constructor(J){super();this.props=J}createState(){return new YK6}}import{isDeepStrictEqual as iP8}from"node:util";var cP8=/[\\/_ +.#"@[({&]/,lP8=/[\\/_ +.#"@[({&]/g,nP8=/[\s-]/,ZK6=/[\s-]/g;function x31(J,Q,Y,Z,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Z.charAt(G),W=Y.indexOf(q,X),H=0,F,U,B,M;while(W>=0){if(F=x31(J,Q,Y,Z,W+1,G+1,V),F>H){if(W===X)F*=1;else if(nP8.test(J.charAt(W-1))){if(F*=0.9,M=J.slice(X,W-1).match(ZK6),M&&X>0)F*=Math.pow(0.999,M.length)}else if(cP8.test(J.charAt(W-1))){if(F*=0.8,B=J.slice(X,W-1).match(lP8),B&&X>0)F*=Math.pow(0.999,B.length)}else if(F*=0.3,X>0)F*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))F*=0.9999}if(F<0.1&&(Y.charAt(W-1)===Z.charAt(G+1)||Z.charAt(G+1)===Z.charAt(G)&&Y.charAt(W-1)!==Z.charAt(G))){if(U=x31(J,Q,Y,Z,W+1,G+2,V),U*0.1>F)F=U*0.1}if(F>H)H=F;W=Y.indexOf(q,W+1)}return V[K]=H,H}function y31(J){return J.toLowerCase().replace(ZK6," ")}function XK6(J,Q){let Y=x31(J,Q,y31(J),y31(Q),0,0,{}),Z=Q.trim().split(/\s+/);if(Z.length>1){let X=0,G=0;for(let K of Z){let q=x31(J,K,y31(J),y31(K),0,0,{});if(q===0)return Y;X+=q,G+=K.length}let V=X/Z.length*0.95;return Math.max(Y,V)}return Y}class OS{}class IS{}class v31{}class h31{}class $K6 extends d0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new GK6}}class GK6 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function aP8(J,Q){if(J==="")return{matches:!0,score:1};let Y=XK6(Q,J);return{matches:Y>0.15,score:Y}}class e2 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new VK6}}class VK6 extends p0{controller=new LZ;focusNode;scrollController=new O5;selectedIndex=0;itemContexts=[];cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new D8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),n8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[0]??null)}),this.recomputeFilteredItems();let J=this.cachedFiltered;this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!iP8(J.props.items,this.widget.props.items)){this.recomputeFilteredItems(),this.ensureSelectedItemVisible();let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof OS){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),n8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof IS){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),n8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof v31){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Y=Q[this.selectedIndex];if(Y){if(!(this.widget.props.isItemDisabled?.(Y)??!1))this.widget.props.onAccept(Y)}}return"handled"}if(J instanceof h31)return this.widget.props.onDismiss?.(),"handled";return"ignored"};recomputeFilteredItems(){let J=this.controller.text,Q=this.widget.props.items,Y=Q.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...aP8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,X)=>this.widget.props.sortItems(Z,X,J):(Z,X)=>X.score-Z.score).map((Z)=>Z.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;E71(J,{top:Y,bottom:Z},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),n8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Y=this.getFilteredItems();if(J>=0&&J<Y.length){let Z=Y[J],X=Z?this.widget.props.isItemDisabled?.(Z)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!X){if(Z)this.widget.props.onAccept(Z)}}};build(J){let Q=q6.of(J),{colors:Y}=Q,Z=this.getFilteredItems(),X=B4.all(new W4(Y.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new qz({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Y.foreground,border:null},maxLines:1}),K=new xX({shortcuts:new Map([[new N4("ArrowDown"),new OS],[new N4("ArrowUp"),new IS],[new N4("Tab"),new OS],[new N4("Tab",{shift:!0}),new IS],[new N4("n",{ctrl:!0}),new OS],[new N4("p",{ctrl:!0}),new IS],[new N4("Enter"),new v31],[new N4("Escape"),new h31]]),focusNode:this.focusNode,child:V}),q=new kJ({actions:new Map([[OS,new C8(this.invoke)],[IS,new C8(this.invoke)],[v31,new C8(this.invoke)],[h31,new C8(this.invoke)]]),child:K}),W=new U6({children:[new g0({decoration:{color:N1.default()},child:new j1({text:new d(">",new J1({color:Y.foreground}))})}),new a6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new Z0({height:10,child:new j4({child:new j1({text:new d(L,new J1({color:Y.foreground}))})})})}else if(Z.length===0&&this.widget.props.emptyStateText)H=new a6({child:new j4({child:new j1({text:new d(this.widget.props.emptyStateText,new J1({color:Y.foreground,dim:!0}))})})});else{let L=Z.map((A,I)=>{let E=I===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,R;if(this.widget.props.renderItem)R=this.widget.props.renderItem(A,E,P,J);else{let C=E?N1.yellow:void 0,S=E?N1.black:Y.foreground;R=new g0({decoration:C?{color:C}:void 0,padding:z0.symmetric(2,0),child:new j1({text:new d(this.widget.props.getLabel(A),new J1({color:S,dim:P}))})})}return new $K6(new M8({onClick:(C)=>this.handleItemClick(I,C.clickCount),child:R}),(C)=>{this.itemContexts[I]=C})});H=new x0({children:L,crossAxisAlignment:"start"})}let F=new a6({child:new M8({onScroll:this.handleScroll,opaque:!1,child:new J5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new g0({padding:z0.symmetric(1,0),child:new j1({text:new d(this.widget.props.title,new J1({color:N1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new Z0({height:1}),F),this.controller.text!==""){let L=Z.length>0?Z[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new g0({padding:z0.vertical(1),child:new j4({child:A})}));else U.push(new Z0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new g0({decoration:{border:X,color:N1.default()},padding:z0.symmetric(1,0),child:new x0({children:U})})}}function KK6(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/60000),X=Math.floor(Y/3600000),G=Math.floor(Y/86400000);if(Z<1)return"just now";if(Z<60)return`${Z}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class Sf1 extends l6{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Y=Math.max(0,...Q.map((X)=>KK6(X.pubDate).length));return new e2({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=q6.of(K),{colors:W}=q,H=G?N1.yellow:void 0,F=G?N1.black:W.foreground,U=N1.index(8),B=(M,L)=>new Z0({width:L,child:U6.end([new j1({text:new d(M,new J1({color:U}))})])});return new g0({decoration:H?{color:H}:void 0,padding:z0.symmetric(2,0),child:new U6({children:[new a6({child:new j1({text:new d(X.title,new J1({color:F})),overflow:"ellipsis",maxLines:1})}),new Z0({width:2}),B(KK6(X.pubDate),Y)]})})}})}}class _f1 extends d0{createState(){return new qK6}}class qK6 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){return new j1({text:new d("●",new J1({color:this.isGreen?N1.green:N1.index(8),bold:!0})),maxLines:1})}}function oP8(J){let Q=new Map,Y=new Map,Z=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Z.set(V.id,K.type);let q=K.threadID,W=Y.get(q)||[];W.push(V),Y.set(q,W)}else X.push(V)}return hX.flatten(X,(V)=>Y.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Z.get(V.item.id)}))}function kf1(J,Q,Y){return new j1({text:new d(`${J}${Q}`,new J1({color:Y})),maxLines:1})}function rP8(J,Q,Y,Z){return[kf1("+",J,Z.success),c5.horizontal(1),kf1("~",Q,Z.warning),c5.horizontal(1),kf1("-",Y,Z.destructive)]}class f31 extends l6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((F)=>F.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((F)=>F.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],Z=new Set(Y),X=this.props.currentThreadID,G=[...Q].sort((F,U)=>{if(X){if(F.id===X)return-1;if(U.id===X)return 1}let B=Y.indexOf(F.id),M=Y.indexOf(U.id);if(B!==-1&&M!==-1)return B-M;if(B!==-1)return-1;if(M!==-1)return 1;return 0}),V=oP8(G),K=Math.max(0,...V.map((F)=>F.description.timeAgo.length)),q=q6.of(J),W=new B6({padding:z0.symmetric(0,1),child:new j4({child:new j1({text:new d("",new J1({color:q.colors.foreground,dim:!0}),[new d("Ctrl+T",new J1({color:N1.blue,dim:!0})),new d(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new J1({color:q.colors.foreground,dim:!0}))])})})});return new e2({items:V,getLabel:(F)=>F.title,onAccept:(F)=>this.props.onSelect?.(F.id),onDismiss:this.props.onDismiss,onSelectionChange:(F)=>{if(this.props.previewController){if(F)this.props.previewController.select(F.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(F,U,B,M)=>{let L=q6.of(M),{colors:A}=L,I=U?N1.yellow:void 0,E=U?N1.black:A.foreground,P=N1.index(8),R=(r,p)=>new Z0({width:p,child:U6.end([new j1({text:new d(r,new J1({color:P}))})])}),C=this.props.threadViewStates[F.id],S=[],k=F.relationshipType==="handoff",f=new y71;if(F.depth>0){let r=[],p=F.ancestorsAreLast.slice(1);for(let Y1 of p)r.push(new d(f.getAncestorPrefix(Y1),new J1({color:f.connectorColor,dim:f.connectorDim})));let s=F.isLast?f.elbow:f.tee,Q1=f.getConnectorText(s);r.push(new d(Q1,new J1({color:f.connectorColor,dim:f.connectorDim}))),S.push(new j1({text:new d("",void 0,r)}))}let m=[],b=X===F.id?new d("(current) ",new J1({color:N1.green})):Z.has(F.id)?new d("(visited) ",new J1({color:A.foreground,dim:!0})):null;if(b)m.push(new j1({text:b}));if(C){if(C.state==="active"&&(C.interactionState==="tool-running"||C.inferenceState==="running"))m.push(new _f1),m.push(new Z0({width:1}))}let c=F.title;if(F.relationshipType==="fork"){let r=c.match(/^Forked\((\d+)\): /);if(r)c=c.slice(r[0].length);else while(c.startsWith("Forked: "))c=c.slice(8);m.push(new j1({text:new d("[fork] ",new J1({color:N1.blue}))}))}else if(k)m.push(new j1({text:new d("[handoff] ",new J1({color:N1.index(208)}))}));if(m.push(new a6({child:new j1({text:new d(c,new J1({color:E})),overflow:"ellipsis",maxLines:1})})),m.push(new Z0({width:2})),F.diffStats&&(F.diffStats.added>0||F.diffStats.changed>0||F.diffStats.deleted>0)){let r=U?{success:P,warning:P,destructive:P}:A;m.push(...rP8(F.diffStats.added,F.diffStats.changed,F.diffStats.deleted,r)),m.push(new Z0({width:2}))}return m.push(R(F.description.timeAgo,K)),new g0({decoration:I?{color:I}:void 0,padding:z0.symmetric(2,0),child:new U6({children:[...S,...m]})})}})}}class yf1 extends l6{props;constructor(J){super();this.props=J}build(){return new j4({child:new j1({text:new d("",void 0,[new d(`Forked to new thread:
4717
4717
 
4718
4718
  `,new J1({color:N1.white,dim:!0})),new d(`"${this.props.newThreadTitle||"Untitled"}"`,new J1({color:N1.white}))]),textAlign:"center"})})}}N0();class WK6 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){v.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){v.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){if(J.length===0)return null;if(J.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(J))return"Label must be lowercase alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!J.includes(Q.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Q=J.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let Y=this.widget.props.currentLabels||[],Z=this.labels.some((G)=>G.name===Q),X=Y.includes(Q);return!Z&&!X}build(J){let Q=q6.of(J),{colors:Y}=Q,Z=this.currentQuery.trim().toLowerCase(),X=Z.length>0?this.getValidationError(Z):null,G=this.getAvailableLabels(),K=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...G];return new e2({title:"Add Label",items:K,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:X||"Type to create a new label",renderItem:(q,W,H,F)=>{let U=W?N1.yellow:void 0,B=W?N1.black:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let L=this.currentQuery.trim().toLowerCase();return new g0({decoration:U?{color:U}:void 0,padding:z0.symmetric(2,0),child:new j1({text:new d("",void 0,[new d("Create new label: ",new J1({color:B})),new d(L,new J1({color:B,bold:!0}))])})})}return new g0({decoration:U?{color:U}:void 0,padding:z0.symmetric(2,0),child:new j1({text:new d(q.name,new J1({color:B}))})})},filterItem:(q,W)=>{if(this.currentQuery!==W)this.currentQuery=W,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(W);let F=W.trim().toLowerCase();return F.length===0||q.name.includes(F)},sortItems:(q,W,H)=>{let F="__isCreateMarker"in q.item&&q.item.__isCreateMarker,U="__isCreateMarker"in W.item&&W.item.__isCreateMarker;if(F&&!U)return-1;if(!F&&U)return 1;return W.score-q.score}})}}class xf1 extends d0{props;constructor(J){super();this.props=J}createState(){return new WK6}}class OD extends d0{props;constructor(J){super();this.props=J}createState(){return new HK6}}class HK6 extends p0{_spinner=new MY;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=q6.of(J),{colors:Y}=Q,Z=B4.all(new W4(Y.foreground,1,"solid")),X=this._spinner.toBraille(),G=new j1({textAlign:"center",text:new d("",void 0,[new d(X,new J1({color:N1.yellow})),new d(" ",void 0),new d(this.widget.props.message,new J1({color:Y.foreground}))])}),K=[new a6({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[G]})})];if(this.widget.props.onAbort)K.push(new Z0({height:2,child:new g0({padding:z0.symmetric(2,0),child:new j1({text:new d("",new J1({dim:!0}),[new d("Press ",new J1({color:Y.foreground})),new d("Esc",new J1({color:Y.info})),new d(" to cancel",new J1({color:Y.foreground}))])})})}));let q=new g0({decoration:new T8(N1.default(),Z),child:new Z0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:K})})});if(this.widget.props.onAbort)return new w8({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}class lI extends d0{props;constructor(J){super();this.props=J}createState(){return new FK6}}class FK6 extends p0{scrollController=new O5;scrollAreaKey=new PQ("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof vX}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let Y=Q.size;if(typeof Y.height==="number"&&Y.height>0)return this.viewportHeight=Y.height,Y.height}return this.viewportHeight}build(J){let Q=q6.of(J),Y=this.widget.props.message,Z=(()=>{if(this.isWidgetMessage(Y))return{title:Y.title,type:Y.type};if(Y instanceof Error&&Y.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Y.message};if(Y instanceof Error&&Y.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Y.message};let H=j71(Y);return{title:H.title,type:H.type,description:H.description}})(),X=Z.type==="error"?N1.red:N1.yellow,G=B4.all(new W4(N1.default(),1,"solid")),V=new g0({padding:z0.symmetric(1,0),child:new j1({text:new d(Z.title,new J1({color:X,bold:!0}))})}),K=this.isWidgetMessage(Y)?Y.widget:new j1({text:new d(Z.description,new J1({color:N1.default()})),selectable:!0}),q=new a6({child:new Vz({child:new g0({padding:z0.symmetric(1,0),child:new U6({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new a6({child:new J5({controller:this.scrollController,autofocus:!0,child:K})}),new E2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let H=this.scrollController.maxScrollExtent,F=this.scrollController.offset,U=this.getViewportHeight(),B=H+U;return{totalContentHeight:Math.max(B,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(F,0)}}})]})})})}),W=new g0({padding:z0.symmetric(1,0),child:new j1({text:this.widget.props.onRetry?new d("",void 0,[new d("Press ",new J1({color:N1.default(),dim:!0})),new d("R",new J1({color:N1.yellow})),new d(" to retry, ",new J1({color:N1.default(),dim:!0})),new d("Esc",new J1({color:N1.yellow})),new d(" to cancel",new J1({color:N1.default(),dim:!0}))]):new d("Press any key to close",new J1({color:N1.default(),dim:!0,italic:!0}))})});return new w8({onKey:(H)=>{if(this.widget.props.onRetry&&H.key==="r")return this.widget.props.onRetry(),"handled";if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new g0({decoration:{border:G,color:N1.default()},padding:z0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new Z0({height:1}),q,W]})})})}}class vf1 extends l6{build(){return new j4({child:new j1({text:new d("",void 0,[new d(`✓ Thread Shared
4719
4719
 
@@ -4824,7 +4824,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
4824
4824
  `)?`${K}...`:X,W=new J1({color:N1.index(8)}),H=[new d(q,W)];if(V>0){let F=new J1({color:Y.success});for(let U=1;U<=V;U++)H.push(new d(" ")),H.push(new d(`[${U}]`,F))}return new B6({padding:z0.only({bottom:0}),child:new U6({crossAxisAlignment:"start",children:[new B6({padding:z0.only({right:1}),child:new j1({text:new d("•",new J1({color:N1.index(8)}))})}),new a6({child:new j1({text:new d("",void 0,H)})})]})})}}class zg1 extends d0{createState(){return new SH6}}class SH6 extends p0{_animationTimer;_visible=!0;initState(){super.initState(),this._startAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._visible=!this._visible})},500)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=new J1({color:N1.red}),Y=new J1({color:this._visible?N1.red:N1.transparent()});return new U6({children:[new j1({text:new d("⏺",Y)}),new Z0({width:1}),new j1({text:new d("Replay",Q)})]})}}s0();function qS8(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/3600000),X=Math.floor(Z/24),G=Math.floor(X/7),V=Math.floor(X/30);if(Z<1)return"Just now";if(Z<24)return`${Z}h ago`;if(X<7)return`${X}d ago`;if(G<=4)return`${G}w ago`;return`${V}mo ago`}class Ug1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Y)=>{let Z=this.threadHistoryService.observeThreadList().subscribe((X)=>{Z.unsubscribe(),Y(X)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(X6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((Z)=>{if(Z.mainThreadID)return!1;if(!Q.trim())return!0;let X=Z.title?.toLowerCase()||"untitled",G=Z.id.toLowerCase(),V=Q.toLowerCase();return X.includes(V)||G.includes(V)}).map((Z)=>{let X=new Date(Z.userLastInteractedAt),G=qS8(X),V=Z.id.slice(-8),K=Z.env?.initial.trees?.[0]?.uri;return{id:Z.id,title:Z.title||"Untitled",updatedAt:new Date(Z.userLastInteractedAt).toISOString(),description:{timeAgo:G,title:Z.title||"Untitled",shortThreadID:V},diffStats:Z.summaryStats?.diffStats,workspaceURI:K,parentRelationships:Z.parentRelationships,agentMode:Z.agentMode,details:{messageCount:Z.summaryStats?.messageCount}}})}}N0();U8();U8();kb();function _H6(J){let Q=yD0(J),Y=Array.from(Q.entries()).map(([V,K])=>({path:V,diffStats:K})),Z=em0(J),G=WP(J)?.totalInputTokens??0;return{filesAffected:Y,totalTokens:G,totalCredits:Z}}class Bg1{currentId=null;current=null;statsCache=new Map;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new O5;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){v.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}getCurrentThread(){return this.current}getCurrentStats(){if(!this.current)return null;let J=this.statsCache.get(this.current.id);if(J&&J.version===this.current.v)return J.stats;let Q=_H6(this.current);return this.statsCache.set(this.current.id,{stats:Q,version:this.current.v}),Q}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){v.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(PL()).subscribe((Q)=>{if(this.currentId===J)this.current=Q,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}function kH6(J,Q){switch(J){case"update-available":return[new d("A newer Amp is available. Run ",new J1({color:Q.foreground,dim:!0})),new d("amp update",new J1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new d("Update complete, run ",new J1({color:Q.foreground,dim:!0})),new d("amp update",new J1({color:Q.warning})),new d(" to see warnings",new J1({color:Q.foreground,dim:!0}))];case"update-error":return[new d("Update failed, run ",new J1({color:Q.foreground,dim:!0})),new d("amp update",new J1({color:Q.warning})),new d(" to see warnings",new J1({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function US8(J){return new Promise((Q)=>{HS8("git",["branch","--show-current"],{cwd:J},(Y,Z)=>{if(Y){Q(null);return}let X=Z.trim();Q(X||null)})})}class fH6 extends d0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new T21}}class T21 extends p0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;randomAd=null;adSubscription=null;adReadinessTimeout=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;threadCostInfoLastUsageLedgerLength=0;lastInferenceState=void 0;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];pendingSkills=[];pendingSkillsSubscription=null;displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;paletteShowOptions=null;threadsForPicker=[];clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new Bg1;previewThread=null;todoScrollController=(()=>{let J=new O5;return J.followMode=!1,J})();filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new D8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new D8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;imagePreviewIndex=null;adActionModal=null;newsFeedReader=null;newsFeedEntries=[];newsFeedSubscription=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;previousThreadIdForHint=null;handoffController=null;handoffState={isInHandoffMode:!1,isGeneratingHandoff:!1,isConfirmingAbortHandoff:!1,pendingHandoffPrompt:null,spinner:null};pendingMCPServers=[];mcpTrustSubscription=null;pendingOAuthRequest=null;mcpServers=[];mcpServersSubscription=null;agentModeController=null;freeTierStatus={canUseAmpFree:!1};agentModePulseSeq=0;agentModeSlideProgress=null;agentModeSlideTimer=null;updateState="hidden";updateServiceSubscription=null;toastController=new Jv1;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];userDisplayBalanceInfo=null;balanceInfoSubscription=null;async initNewsFeed(){let J=async(Y)=>{return D5(Y,void 0,this.widget.dependencies.configService)},Q=os0();this.newsFeedReader=new Ix1(Q,J,"/news.rss"),this.newsFeedSubscription=this.newsFeedReader.stream().subscribe({next:(Y)=>{if(Y.length>0)this.setState(()=>{this.newsFeedEntries=[...Y,...this.newsFeedEntries]})},error:(Y)=>{v.error("News feed error:",Y)}})}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};onThreadSwitch(){this.handoffController?.resetUIState(),this.isMessageViewInSelectionMode=!1}startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.worker.thread.id;this.recordNavigation(J);let Q=await this.widget.dependencies.startNewThread();return this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,this.widget.dependencies.switchWorker(Q),this.setState(()=>{this.onThreadSwitch(),this.previousThreadIdForHint=J}),Q};async startReplay(){let J=this.widget.dependencies.replayMode;if(!J)return;let{thread:Q,typingEnabled:Y,baseWpm:Z}=J,X=Q.messages;for(let G=0;G<X.length;G++){if(this.replayAbortController.signal.aborted)break;let V=X[G];if(!V)continue;if(G>0)await this.replaySleep(J.messageDelayMs);if(V.role==="user"&&Y){let W=V.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
4825
4825
  `);if(W)await this.replayTypeMessage(W,Z)}if(V.role==="assistant"){let W=V.content.some((U)=>U.type==="tool_use"),H=X[G+1],F=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&F){let U={...V,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let B=J.thread.id;this.getMessageScrollController(B).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),V]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,V],this.textController.clear()});let K=J.thread.id;this.getMessageScrollController(K).scrollToBottom()}await this.replaySleep(J.exitDelayMs),y8.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Y=J.split(/(?<=\s)/),Z=60000/Q;for(let X of Y){if(this.replayAbortController.signal.aborted)break;if(this.looksLikePastedContent(X.trim())){await this.replaySleep(150),this.textController.text=this.textController.text+X,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{}),await this.replaySleep(300);continue}let G=Z/X.length;for(let V of X){this.textController.text=this.textController.text+V,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let K=0.8+Math.random()*0.4,q=G*K;await this.replaySleep(q)}}}looksLikePastedContent(J){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(J))return!0;if(J.startsWith("/")&&J.length>10)return!0;if(/^[a-z]:\\/i.test(J))return!0;if(/^[a-f0-9]{7,40}$/i.test(J))return!0;if(/^T-[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(J))return!0;return!1}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return this.agentModeController?.getEffectiveMode()??"smart"}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Y=J.items.filter((G)=>G.type==="toolResult").filter((G)=>G.toolResult.run.status==="in-progress"||G.toolResult.run.status==="queued"),Z=J.subagentActiveTools.filter((G)=>G.toolRun.status==="in-progress"||G.toolRun.status==="queued");return[...Y,...Z].length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new d(this.submitDisabledHint,new J1({color:J.foreground,dim:!0}));if(this.isExiting)return new d("Exiting...",new J1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new d("",void 0,[new d("Ctrl+C",new J1({color:Q.keybind})),new d(" again to exit",new J1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new d("",void 0,[new d("Esc",new J1({color:Q.keybind})),new d(" again to clear input",new J1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new d("",void 0,[new d("Escape",new J1({color:Q.keybind})),new d(" to close help",new J1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let Z=this.getEffectiveAgentMode(),X=R21(Z);return new d("",void 0,[new d("Images aren't supported in ",new J1({color:J.warning,dim:!1})),new d(Z,new J1({color:X})),new d(" mode.",new J1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new d("",void 0,[new d("Esc",new J1({color:Q.keybind})),new d(" again to cancel",new J1({color:J.foreground,dim:!0}))]);return new d("",void 0,[new d("Esc",new J1({color:Q.keybind})),new d(" to cancel",new J1({color:J.foreground,dim:!0}))])}if(this.statusMessage)return new d(this.statusMessage,new J1({color:J.foreground,dim:!0}));let Y=kH6(this.updateState,J);if(Y)return new d("",void 0,Y);return null}getParentThreadInfo(){let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;let Q=RL(J).filter((V)=>V.type==="fork"||V.type==="handoff");if(Q.length===0)return null;let Y=Q[0],Z=Y.threadID,G=this.threadsForPicker.find((V)=>V.id===Z)?.title??Z.slice(-8);return{type:Y.type==="handoff"?"handoff":"fork",title:G}}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Y}=this.widget.dependencies;if(!Q.mainThread?.id)return;let X=Q.mainThread?.messages.findIndex((G)=>G===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),await Y.handle({type:"thread:truncate",fromIndex:X}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(G){v.error("Failed to edit message:",G)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Y,threadSyncService:Z}=this.widget.dependencies,X=Q.mainThread?.id;if(!X)return;let G=Q.mainThread?.messages.findIndex((V)=>V===J);if(G===void 0||G<=0)return;try{let V=await s3.getOrCreateForThread(Y,X),K=await Kj(V,Z,G-1);await this.switchToExistingThread(K)}catch(V){v.error("Failed to fork thread:",V),this.showErrorMessage(`Failed to fork thread: ${V}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Y,worker:Z}=this.widget.dependencies,X=Y.mainThread;if(!X)return;let G=X.messages.findIndex((V)=>V.messageId!==void 0&&V.messageId===J.messageId);if(G===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),this.widget.dependencies.history.add(Q);let V=KD(Q);if(V)await Z.handle({type:"thread:truncate",fromIndex:G}),this.invokeBashCommand(V.cmd,{visibility:V.visibility});else{let K=[{type:"text",text:Q}];if(this.imageAttachments.length>0)K.push(...this.imageAttachments);let q={content:K,agentMode:X.agentMode},W=G===0;if(X.agentMode&&!W&&q.agentMode!==X.agentMode){v.error(`Cannot edit message: This thread uses ${X.agentMode} mode. To change mode, create a new thread.`);return}await Z.handle({type:"user:message",message:q,index:G})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){v.error("Failed to edit message:",V)}};getAffectedFiles=async(J)=>{let{worker:Q,threadState:Y}=this.widget.dependencies;try{let Z=Y.mainThread;if(!Z)return[];let X=Z.messages.findIndex((V)=>V===J);if(X===-1)return[];return(await Q.getFilesAffectedByTruncation(X)).map(u3)}catch(Z){return v.error("Failed to get affected files:",Z),[]}};textController=new LZ;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new O5);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let Z=this.searchElementTreeByKey(J.child,Q);if(Z)return Z}if(J?.children)for(let Z of J.children){let X=this.searchElementTreeByKey(Z,Q);if(X)return X}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{this.toastController.show("Selection copied to clipboard","success",2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Y=process.cwd().replace(process.env.HOME||"","~"),Z=Q?`amp - ${Q} - ${Y}`:"";process.stdout.write(hy1(Z))}}_handleTextCopy(J){if(J&&J.length>0)this.toastController.show("Selection copied to clipboard","success",2000)}textFieldKey=new V3("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"&&!this.handoffState.isGeneratingHandoff){this.showCommandPalette(),this.textController.clear();return}let Q=KD(J);this.currentShellModeStatus=this.handoffState.isInHandoffMode?void 0:Q?.visibility,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),n8.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Q)}catch(Y){let Z=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.showCommandPalette({type:"standalone",commandId:"continue",onSubmit:()=>{this.threadPreviewController.clear(),this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null}),n8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};showCommandPalette(J){if(this.handoffState.isGeneratingHandoff)return;if(this.setState(()=>{this.isShowingPalette=!this.isShowingPalette,this.paletteShowOptions=J??null}),this.isShowingPalette)this.loadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new af1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.widget.dependencies.isDogfooding,this.paletteConfig)}return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new sf1(this.widget.dependencies.fuzzyServer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})};getCommandPaletteContext=(J)=>{let{threadState:Q,recentThreadIDs:Y}=this.widget.dependencies;if(!Q.mainThread)return null;let Z=m0.file(process.cwd()),X=v6(Z);return{recentThreadIDs:Y,currentThreadID:Q.mainThread.id,context:J,worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadService:this.widget.dependencies.threadService,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,skillService:this.widget.dependencies.skillService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let G=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),G},setImageAttachments:(G)=>{this.setState(()=>{this.imageAttachments=G})},editorDispatch:(G)=>{switch(G.type){case"set-input":this.textController.clear(),this.textController.insertText(G.input);break;case"insert-text":this.textController.insertText(G.text);break;case"clear":this.textController.clear();break}},submitMessage:(G)=>{return this.proceedWithUserMessage(G)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,mcpService:this.widget.dependencies.mcpService,toolboxService:this.widget.dependencies.toolboxService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus.canUseAmpFree,switchToThread:async(G)=>{return await this.switchToExistingThread(G),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(G,V,K)=>{let q=this.widget.dependencies.threadState.mainThread?.id;if(!q)throw Error("No active thread");let W=setTimeout(()=>{K.throwIfAborted()},60000);try{let H=await this.widget.dependencies.threadService.generateHandoffPrompt(q,G,V,this.widget.dependencies.configService,K,this.widget.dependencies.worker.fs.fileSystemReader());return clearTimeout(W),H}catch(H){throw clearTimeout(W),H}},handleHandoff:async(G,V)=>{let{goal:K,generatedPrompt:q,images:W}=V;if(!K&&!q)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let H=this.widget.dependencies.threadState.mainThread?.id;if(!H)return{ok:!1,error:Error("No active thread")};let F=setTimeout(()=>G.abort(new KS("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let U=await this.widget.dependencies.threadService.createHandoffThread(H,{goal:K,generatedPrompt:q,images:W,filesystem:this.widget.dependencies.worker.fs.fileSystemReader()},this.widget.dependencies.configService,G.signal);return clearTimeout(F),await this.switchToExistingThread(U),{ok:!0}}catch(U){if(clearTimeout(F),U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")))throw G.signal.reason;throw U}}catch(H){return v.error("Failed to create handoff thread",H),{ok:!1,error:H instanceof Error?H:Error(String(H))}}},getGuidanceFiles:async(G)=>{if(!Q.mainThread)return[];return(await Qe({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,G)).map((K)=>({uri:K.uri,type:K.type}))},openIdePicker:()=>{this.openIdePicker()},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(G)=>{this.agentModeController?.setMode(G)},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.clustersForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:X,threadViewStates:this.widget.dependencies.workerController.threadViewStates,newsFeedEntries:this.newsFeedEntries,showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:this.widget.dependencies.features,showStatusMessage:(G,V=2000)=>{if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=G}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},V)},showToast:(G,V="success",K)=>{this.toastController.show(G,V,K)},enterHandoffMode:this.enterHandoffMode,addPendingSkill:(G)=>{(this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker).addPendingSkill(G)}}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new Ug1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.clustersForPicker=EK6(Q),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await US8(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{visibility:Q})=>{let Y=Date.now(),Z=`bash-${Y}-${Math.random().toString(36).substring(7)}`,X={cmd:J},G=new AbortController;this.widget.dependencies.worker.invokeBashTool(X,G.signal,Q===VD).subscribe({next:(V)=>{this.setState(()=>{if(this.bashInvocations.find((q)=>q.id===Z))this.bashInvocations=this.bashInvocations.map((q)=>q.id===Z?{...q,toolRun:V}:q);else{let q={id:Z,args:X,toolRun:V,startTime:Y,abortController:G,hidden:Q===VD};this.bashInvocations=[...this.bashInvocations,q]}})},error:()=>this.removeBashInvocation(Z),complete:()=>this.removeBashInvocation(Z)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=NY6(()=>{let J=this.widget.dependencies.threadID;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(Q.ok)this.setState(()=>{this.threadCostInfo=Q.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J,Q)=>{let Y=J!==this.threadCostInfoLastUsageLedgerLength,Z=Q==="idle"&&this.lastInferenceState==="running";if(this.threadCostInfoLastUsageLedgerLength=J,this.lastInferenceState=Q,Y||Z)this.fetchThreadCostInfo()};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.agentModeController.toggle())this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};startAgentModeSlide=()=>{if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer);this.setState(()=>{this.agentModeSlideProgress=0});let J=400,Q=16,Y=Q/J;this.agentModeSlideTimer=setInterval(()=>{this.setState(()=>{if(this.agentModeSlideProgress!==null){if(this.agentModeSlideProgress=Math.min(1,this.agentModeSlideProgress+Y),this.agentModeSlideProgress>=1){if(this.agentModeSlideProgress=null,this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null}}})},Q)};handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!cy(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=XB)return!1;let Y=JS(J);if(typeof Y==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Y}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{this.setState(()=>{this.imagePreviewIndex=J})};handleImagePreviewDismiss=()=>{this.setState(()=>{this.imagePreviewIndex=null})};handleImageRemove=(J)=>{this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Q,Y)=>Y!==J),this.imagePreviewIndex=null})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(!Q.ok)v.error("Failed to destruct mysterious message",Q.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Q)=>{v.error("Failed to destruct mysterious message",Q)})};enterHandoffMode=()=>{this.handoffController?.enter(),this.dismissPalette()};exitHandoffMode=()=>{this.handoffController?.exit()};submitHandoff=async(J)=>{let Q=this.imageAttachments;if(this.resetHistory(),this.setState(()=>{this.imageAttachments=[]}),!this.handoffController){this.showSubmitDisabledHint("Handoff controller not initialized");return}let Y=await this.handoffController.submit(J,Q);if(!Y.ok&&Y.error.message!=="Cancelled")this.displayMessage=Y.error,this.setState(()=>{})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Y,unlink:Z,rmdir:X,writeFile:G}=await import("node:fs/promises"),{tmpdir:V}=await import("node:os"),K=await import("node:path");try{let q=await Q(K.join(V(),"amp-edit-")),W=K.join(q,"message.amp.md");await G(W,J,"utf-8"),await MG(W);try{let H=await Y(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")v.error("Failed to read temporary file",H)}try{await Z(W),await X(q)}catch(H){v.warn("Failed to clean up temporary file",H)}}catch(q){v.error("Error opening editor:",q)}};onTextSubmitted=async(J)=>{if(!J.trim()&&this.imageAttachments.length===0)return;if(this.handoffState.isInHandoffMode){await this.submitHandoff(J);return}let Q=KD(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{this.setState(()=>{})};handoffListener=(J)=>{this.setState(()=>{this.handoffState=J})};initState(){if(CX.getInstance().interceptConsole(),this.freeTierStatus=this.widget.dependencies.freeTierStatus,this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.handoffController=new Xv1({threadService:this.widget.dependencies.threadService,configService:this.widget.dependencies.configService,getMainThread:()=>this.widget.dependencies.threadState.mainThread,getFilesystemReader:()=>this.widget.dependencies.worker.fs.fileSystemReader(),switchToThread:(Y)=>this.switchToExistingThread(Y)}),this.handoffController.addListener(this.handoffListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();y8.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),y8.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),y8.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Y)=>{n8.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})})}),D6(this.widget.dependencies.configService.config).then((Y)=>{this.paletteConfig=Y,this.agentModeController=new wx1({initialCliMode:this.widget.dependencies.initialAgentMode,sessionState:this.widget.dependencies.sessionState??null,freeTierStatus:this.freeTierStatus,initialSettings:Y.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.getCurrentWorker()?.thread??this.widget.dependencies.worker.thread}),this.agentModeController.addListener(this.agentModeListener)}),this.updateGitBranch(),this.loadThreadsForPicker(),this.balanceInfoSubscription=ir0(async()=>{let Y=await this.widget.dependencies.internalAPIClient.userDisplayBalanceInfo({},{config:this.widget.dependencies.configService});if(!Y.ok)throw Y.error;return Y.result}).subscribe({next:(Y)=>{this.setState(()=>{this.userDisplayBalanceInfo=Y})},error:(Y)=>{v.debug("Failed to fetch user balance info",Y)}}),this.scheduleAdSubscriptionWithIdeReadiness();let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Y)=>{this.setState(()=>{this.pendingMCPServers=Y})}),Fy1((Y)=>{this.setState(()=>{this.pendingOAuthRequest=Y})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((Y)=>{this.setState(()=>{this.mcpServers=Y})}),this.pendingSkillsSubscription=this.widget.dependencies.worker.pendingSkills.subscribe((Y)=>{this.setState(()=>{this.pendingSkills=Y})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Y)=>{let Z=this.isIdeReadyForAdContext();if(this.setState(()=>{this.ideStatus=Y}),!Z&&this.isIdeReadyForAdContext()){if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(!this.adSubscription)this.subscribeToAds()}}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Y)=>{let Z=this.widget.dependencies.getCurrentWorker();if(!Z){v.warn("No active thread worker found to handle IDE message");return}await new Promise((X)=>setTimeout(X,50)),await Z.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}}),v.debug("Message sent from IDE to agent",{message:Y.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Y)=>{this.textController.insertText(Y),v.debug("Appended text to CLI prompt from IDE",{text:Y.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Y)=>{this.setState(()=>{this.updateState=Y})}),this.mysteriousMessageSubscription=dR(this.widget.dependencies.configService).pipe(B5((Y)=>Y!=="pending"),X6((Y)=>cR(Y)?Y.mysteriousMessage??null:null),I4((Y,Z)=>Y?.id===Z?.id)).subscribe((Y)=>{this.setState(()=>{if(Y?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=Y,Y&&!this.mysterySequenceManager)this.mysterySequenceManager=new N71(new Map([[new B71(T21.MYSTERY_SEQUENCE),new mp]])),this.mysteryKeyInterceptorUnsubscribe=y8.instance.addKeyInterceptor((Z)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let X=this.mysterySequenceManager.handleKeyEvent(Z);if(X.consumed){if(X.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=X.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!Y)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Y)=>{let Z=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initNewsFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener();let Q=this.widget.dependencies.threadID;if(this.threadCostInfoThreadID!==void 0&&this.threadCostInfoThreadID!==Q)this.threadCostInfo=void 0,this.threadCostInfoThreadID=void 0,this.threadCostInfoLastUsageLedgerLength=0,this.fetchThreadCostInfo();let{threadState:Y}=this.widget.dependencies;this.maybeRefetchThreadCostInfo(Y.mainThread?.usageLedger?.events.length??0,Y.viewState.state==="active"?Y.viewState.inferenceState:void 0)}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.handoffController)this.handoffController.removeListener(this.handoffListener),this.handoffController.dispose();if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(this.adSubscription)this.adSubscription.unsubscribe();if(this.balanceInfoSubscription)this.balanceInfoSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(Fy1(null),this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.pendingSkillsSubscription)this.pendingSkillsSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.newsFeedSubscription)this.newsFeedSubscription.unsubscribe();if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null;if(this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(hy1("")),this.shouldUseProgressBar())process.stdout.write(kQ6())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,Z=[...J.items.filter((K)=>K.type==="toolResult").map((K)=>({toolUse:K.toolUse,toolRun:K.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((K)=>K.toolRun.status==="blocked-on-user");if(Z.length===0)return null;let X=Z[0],G=X.toolRun.status==="blocked-on-user"?X.toolRun.toAllow??[]:[],V=X.toolRun.status==="blocked-on-user"?X.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:X.toolUse,toAllow:G}],subthreadID:X.subthreadID,reason:V}}shouldUseProgressBar(){return!1}updateProgressBar(){}static AD_READINESS_TIMEOUT_MS=1000;scheduleAdSubscriptionWithIdeReadiness(){if(this.isIdeReadyForAdContext()){this.subscribeToAds();return}this.adReadinessTimeout=setTimeout(()=>{if(this.adReadinessTimeout=null,!this.adSubscription)this.subscribeToAds()},T21.AD_READINESS_TIMEOUT_MS)}isIdeReadyForAdContext(){let J=this.ideStatus;if(!J||!J.enabled)return!1;return Boolean(J.openFile||J.visibleFiles&&J.visibleFiles.length>0)}subscribeToAds(){if(this.adSubscription)return;this.adSubscription=Yx1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{let J=this.agentModeController?.getMode();return(J&&O9(J)||this.randomAd===null)&&Qx1(this.lastUserInteractionTime)},this.widget.dependencies.codebaseContextService,()=>this.widget.dependencies.worker.thread).subscribe({next:(J)=>{if(J){let Q=FS8(16).toString("hex");if(this.lastAdImpressionId=Q,Promise.resolve().then(() => (P21(),E21)).then(({recordAdEvent:Y})=>{let Z=this.widget.dependencies.worker.thread,X=Z.messages[Z.messages.length-1];Y("viewed",{adId:J.id,advertiserId:J.advertiserId,threadId:Z.id,messageId:X?.messageId,impressionId:Q,placement:"tui",matchType:J.metadata?.matchType,matchedPatterns:J.metadata?.matchedPatterns,candidateAdPoolCount:J.metadata?.candidateAdPoolCount,clientRegion:J.metadata?.clientRegion})}),J.externalImpressionUrl)this.widget.dependencies.internalAPIClient.recordAdImpression({adId:J.id,externalImpressionUrl:J.externalImpressionUrl},{config:this.widget.dependencies.configService}).catch(()=>{})}this.setState(()=>{this.randomAd=J}),n8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}})}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){v.error("No current tool confirmation found");return}let Y=Q.tools[0]?.useBlock;if(!Y){v.error("No tool use block found in confirmation");return}if(J==="allow-all-session")GV("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(X){if(X&&X instanceof Error)this.setState(()=>{this.displayMessage=X});else v.error("Failed to write dangerouslyAllowAll setting:",X);return}if(J==="always-guarded"){let X=Q.tools[0]?.toAllow??[],G=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],V=[...X,...G];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",V,"global")}if(J==="connect-github"){let X=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await AZ(this.context,X);return}if(J==="disable-librarian"){let X=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!X.includes(Vq))await this.widget.dependencies.settingsStorage.set("tools.disable",[...X,Vq],"global")}let Z=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let X={type:"user:tool-input",toolUse:Y.id,value:{accepted:Z}};if(Q.subthreadID)await(await s3.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(X);else await this.widget.dependencies.worker.handle(X)}catch(X){v.error("Failed to send tool confirmation:",X)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.widget.dependencies.worker;switch(J){case"retry":await Q.retry();break;case"dismiss":Q.dismissEphemeralError();break;case"new-thread":Q.dismissEphemeralError(),await this.startAndSwitchToNewThread();break;case"new-smart-thread":this.agentModeController?.setMode("smart"),Q.dismissEphemeralError(),K51({agentMode:"smart"}),await this.startAndSwitchToNewThread();break;case"handoff":Q.dismissEphemeralError(),this.showCommandPalette({type:"normal",commandId:"handoff"});break}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Q}=this.widget.dependencies;await J.deny();try{await MG(Q.getSettingsFilePath())}catch(Y){let Z=Y instanceof Error?Y.message:String(Y);await this.showErrorMessage(`Failed to open settings: ${Z}`)}};cancelStreamingMessage=async()=>{await s3.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Y=J.messages[Q];if(Y?.role==="user"&&!Y.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J,Q={})=>{let{recordInNavigationHistory:Y=!0}=Q;if(Y){let Z=this.widget.dependencies.worker.thread.id;if(Z!==J)this.recordNavigation(Z)}try{v.info(`[switchToExistingThread] Switching to thread: ${J}`);let Z=await this.widget.dependencies.switchToThread(J);if(v.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${Z.thread.agentMode}`),this.widget.dependencies.worker=Z,this.widget.dependencies.threadID=Z.thread.id,this.widget.dependencies.switchWorker(Z),v.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null),this.onThreadSwitch(),Z.thread.draft)if(v.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof Z.thread.draft==="string")this.textController.insertText(Z.thread.draft);else{let X=Z.thread.draft.filter((K)=>K.type==="text"),G=Z.thread.draft.filter((K)=>K.type==="image"),V=X.map((K)=>K.text).join(`
4826
4826
  `);if(V)this.textController.insertText(V);if(G.length>0)this.setState(()=>{this.imageAttachments=G})}}catch(Z){throw v.error("Failed to switch to thread:",J,Z),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.handoffController?.clearPendingPrompt(),this.widget.dependencies.history.add(J);let Q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,Y=V2(Q.thread)===0,Z=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Y&&Z!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let X=[{type:"text",text:J}];if(this.imageAttachments.length>0)X.push(...this.imageAttachments);if(Y)this.startAgentModeSlide();if(await Q.handle({type:"user:message",message:{content:X,agentMode:Z}}),Y)K51({agentMode:Z});this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]}),n8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((Z)=>Z.type==="handoff"&&Z.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();K51({agentMode:Q}).catch((Y)=>{v.warn("Failed to save session state on exit:",Y)}).finally(()=>{y8.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=zS8();if(J===Q)return"~";if(J.startsWith(Q+Pd.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Pd.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Pd.sep),"…",Q.slice(-2).join(Pd.sep)].join(Pd.sep)}build(J){let Q=C4.of(J),Y=q6.of(J),Z=Y.base;this.themeColors=Z;let{colors:X,app:G}=Y;this.themeApp=G;let V=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,K=V.thread.agentMode&&O9(V.thread.agentMode),q=this.widget.dependencies.features.some((_6)=>_6.name===BY6.UBI&&_6.enabled),W=this.widget.dependencies.freeTierStatus.canUseAmpFree&&q,H=(K||W)&&this.randomAd!==null,F=Boolean(H),{threadState:U}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let B=this.getCurrentConfirmation(),M=this.widget.dependencies.replayMode,L=Boolean(M),A=U.items,I=U.mainThread||void 0,E=U.subagentToolsByParentID,P=U.todosList;if(L){let _6={...M.thread,messages:this.replayDisplayedMessages};A=AS(_6).items,I=_6,E={};let O6=SU({messages:this.replayDisplayedMessages});P=Array.isArray(O6)?O6:[]}let R=I?.id,C=I,S=L?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),k=(_6)=>new j31({key:new V3(`preview-message-view-${_6.id}`),items:AS(_6).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:_6,focusNode:new D8({debugLabel:"PreviewFocus"})}),f=this.previewThread,m=f?f.messages.length>2000?new x0({mainAxisSize:"max",children:[new a6({child:new Z0}),new B6({padding:z0.all(2),child:new j4({child:new j1({text:new d("Thread too long for preview",new J1({color:X.mutedForeground,dim:!0}))})})})]}):k(f):S?new k31({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal,userDisplayBalanceInfo:this.userDisplayBalanceInfo}):new j31({key:R?new V3(`message-view-${R}`):void 0,items:A,subagentToolsByParentID:E,controller:R?this.getMessageScrollController(R):new O5,autofocus:!1,onCopy:L?void 0:this._handleTextCopy.bind(this),thread:C,onMessageEditSubmit:L?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:L?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:L?void 0:this.forkMessage,getAffectedFiles:L?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode,isInHandoffMode:this.handoffState.isInHandoffMode,completionBuilder:L?void 0:this.getCompletionBuilder()}),b=Math.max(Math.floor(Q.size.height*0.4),12),c=this.getCurrentEphemeralError(),Z1=Q.size.width<40,r=U.mainThread?WP(U.mainThread):void 0,p=M31(J),s=this.buildBottomWidget(c,B,X,Y,U,P,b,F,L,r,Q,p),Q1=new c71({threadViewState:U.viewState,threadTokenUsage:r,threadID:R??null,thread:U.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,mcpServers:this.mcpServers,isNarrow:Z1,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!B,showingEphemeralError:Boolean(U.viewState.state==="active"&&U.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),Y1=new x71({bashInvocations:this.bashInvocations}),n=[],o=this.getEffectiveAgentMode(),i=this.currentShellModeStatus,q1=R21(o),T1=!i?o.length+1:0,e=Q.capabilities.animationSupport,D1=e==="disabled"?0:e==="slow"?30:60,L1=XV(o)?.uiHints?.fasterAnimation?3:1,t1=D1>0&&this.agentModePulseSeq>0?new $5({children:[s,new A5({top:0,left:1,right:1,height:1,child:new Vg1({color:q1,trigger:this.agentModePulseSeq,fps:D1,speed:L1,leftOffset:T1})})]}):s;n.push(new a6({child:m}),Y1);let R1=new $5({children:[new x0({mainAxisSize:"min",children:[H?new Ef1({ad:this.randomAd,onButtonClick:async()=>{let _6=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (P21(),E21)).then(({recordAdEvent:Z8})=>{let j8=this.widget.dependencies.worker.thread,W3=j8.messages[j8.messages.length-1];Z8("clicked",{adId:_6.id,advertiserId:_6.advertiserId,threadId:j8.id,messageId:W3?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:_6.metadata?.matchType,matchedPatterns:_6.metadata?.matchedPatterns,candidateAdPoolCount:_6.metadata?.candidateAdPoolCount,clientRegion:_6.metadata?.clientRegion})});if(!await AZ(this.context,_6.shortDestinationUrl)){let j8=y8.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:j8,url:_6.shortDestinationUrl}})}}}):new Z0({height:0}),new g0({constraints:new I6(0,Q.size.width,0,b),child:t1})]}),F?new A5({top:0,left:0,right:0,child:new mH6({userHeight:this.bottomGridUserHeight,maxHeight:b,onInitializeHeight:(_6)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(_6,b)})},onDrag:(_6)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(_6.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let O6=Math.floor(_6.localPosition.y)-this.bottomGridDragStartY,Z8=Math.max(4,this.bottomGridDragStartHeight-O6),j8=Math.min(Z8,b),W3=Math.floor(j8);if(this.bottomGridUserHeight!==W3)this.setState(()=>{this.bottomGridUserHeight=W3})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new Z0({height:0})]}),f1=this.getParentThreadInfo();if(f1&&!L){let _6=f1.type==="handoff"?"Handed off from":"Forked from",O6=f1.type==="handoff"?G.handoffMode:X.primary,Z8=40,j8=B9(f1.title),W3=j8.length>40?j8.slice(0,39).join("")+"…":f1.title;n.push(new Z0({height:1,child:new U6({mainAxisAlignment:"end",children:[new M8({cursor:"pointer",onClick:()=>{this.showCommandPalette({type:"standalone",commandId:"thread-map",onSubmit:this.dismissPalette,onCancel:this.dismissPalette})},child:new B6({padding:z0.only({right:2}),child:new j1({text:new d("",void 0,[new d("↳ ",new J1({color:O6})),new d(`${_6}: `,new J1({color:X.mutedForeground,dim:!0})),new d(W3,new J1({color:X.foreground}))])})})})]})}))}n.push(R1,new Z0({height:1,child:new B6({padding:z0.horizontal(1),child:Q1})}));let V1=new x0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:n}),B1=L&&M?.showIndicator!==!1?new $5({children:[V1,new A5({top:0,left:0,child:new zg1})]}):V1,F1=new C8(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.handoffState.isInHandoffMode){if(this.handoffState.isGeneratingHandoff)this.handoffController?.cancelGeneration();else this.exitHandoffMode();return"handled"}if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.handoffState.isConfirmingAbortHandoff&&this.handoffController){let O6=this.handoffController.getPendingPrompt();return this.textController.clear(),this.setState(()=>{this.imageAttachments=[]}),this.handoffController.confirmAbort().then((Z8)=>{if(Z8&&O6)this.textController.text=O6,this.handoffController?.clearPendingPrompt()}),"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((O6)=>{v.error("Failed to mark message as interrupted:",O6)}),this.cancelStreamingMessage().catch((O6)=>{v.error("Failed to cancel streaming message:",O6)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return v.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.handoffController?.getEmptyHandoffParentThreadID())return this.handoffController.startAbortConfirmation(),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),E1=new C8(()=>{return this.onExitPressed(),"handled"}),I1=new C8(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),h1=new C8(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),g1=new C8(()=>{return hJ.instance.toggleAll(),"handled"}),o1=new C8(()=>{return this.widget.dependencies.configService.getLatest().then((_6)=>{GV("internal.showDetailedCosts",!(_6.settings["internal.showDetailedCosts"]??!1))}),"handled"}),x1=new C8(()=>{return y8.instance.toggleFrameStatsOverlay(),"handled"}),r1=new C8(()=>{return y8.instance.tuiInstance.getScreen().markForRefresh(),n8.instance.requestFrame(),"handled"}),V0=new C8(()=>{return this.toggleAgentMode(),"handled"}),l0=new C8(()=>{let O6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:Z8}=this.widget.dependencies,j8=Z8.mainThread?.id;return j8?this.getMessageScrollController(j8):null})();if(O6){let Z8=Math.max(Math.floor(Q.size.height*0.4),10),j8=Q.size.height-Z8;O6.animatePageUp(j8,100)}return"handled"}),e0=new C8(()=>{let O6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:Z8}=this.widget.dependencies,j8=Z8.mainThread?.id;return j8?this.getMessageScrollController(j8):null})();if(O6){let Z8=Math.max(Math.floor(Q.size.height*0.4),10),j8=Q.size.height-Z8;O6.animatePageDown(j8,100)}return"handled"}),M6=new C8(()=>{let O6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:Z8}=this.widget.dependencies,j8=Z8.mainThread?.id;return j8?this.getMessageScrollController(j8):null})();if(O6)O6.animateTo(0,100);return"handled"}),A6=new C8(()=>{let O6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:Z8}=this.widget.dependencies,j8=Z8.mainThread?.id;return j8?this.getMessageScrollController(j8):null})();if(O6)O6.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),F4=new C8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";if(this.handoffState.isInHandoffMode)return"ignored";let{threadState:_6}=this.widget.dependencies;if(!_6.mainThread?.messages.some((Z8)=>Z8.role==="user"||FP(Z8)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),H0=new C8((_6)=>{if(_6.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),j0=new C8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return T71().then(async(_6)=>{if(_6)try{this.handleInsertImage(_6)}finally{try{let{unlink:O6}=await import("node:fs/promises");await O6(_6)}catch{}}}),"handled"}),R0=new Map([[N4.ctrl("c"),new yp],[N4.ctrl("l"),new bp],[N4.ctrl("o"),new I71],[N4.ctrl("v"),new _p],[N4.alt("s"),new XS],[N4.ctrl("s"),new XS],[N4.alt("p"),new fp],[N4.ctrl("r"),new vp],[N4.alt("d"),new hp],[N4.ctrl("t"),new gp],[N4.key("PageUp"),new M71],[N4.key("PageDown"),new L71],[N4.key("Home"),new A71],[N4.key("End"),new O71],[N4.key("Escape"),new kp],[N4.ctrl("p"),new $S("previous")],[N4.ctrl("n"),new $S("next")],[N4.key("Tab"),new up]]);if(!J2())R0.set(N4.key("ArrowUp"),new up);if(!1)R0.set(N4.alt("c"),new xp);let u6=new C8(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),W8=new C8(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),U4=new C8(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),R4=new Map([[kp,F1],[bp,r1],[XS,V0],[I71,u6],[_p,j0],[xp,I1],[F71,h1],[vp,g1],[hp,o1],[fp,x1],[gp,W8],[yp,E1],[M71,l0],[L71,e0],[A71,M6],[O71,A6],[up,F4],[$S,H0],[mp,U4]]),z4=[B1];if(this.isShowingConsoleOverlay)z4.push(new Jb1);if(this.isShowingHelp&&this.paletteConfig)z4.push(new Zb1({commands:this.getPaletteCommands().getAllCommands()}));if(this.isShowingMCPStatusModal)z4.push(new dh1({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)z4.push(new Wg1({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.adActionModal)z4.push(new Pf1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(_6)=>{let O6=this.adActionModal.url;if(_6==="copy")try{await y8.instance.tuiInstance.clipboard.writeText(O6),this.setState(()=>{this.displayMessage=new LY("Link copied to clipboard")})}catch(Z8){v.error("Failed to copy to clipboard",{error:Z8}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:_6}=this.widget.dependencies;z4.push(new Kg1({servers:this.pendingMCPServers,onAlwaysTrust:_6.trustAlways.bind(_6),onTrustOnce:_6.trustOnce.bind(_6),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:_6.deny.bind(_6)}))}if(this.pendingOAuthRequest)z4.push(new Hg1({request:this.pendingOAuthRequest,onDismiss:()=>{this.setState(()=>{this.pendingOAuthRequest=null})}}));if(this.isShowingFileChangesOverlay)z4.push(new Bv1({threadData:U}));if(this.isShowingContextDetailOverlay){let _6=this.threadCostInfo?.costBreakdownURL;z4.push(new Qb1({thread:U.mainThread??void 0,tokenUsage:r??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:_6?()=>{AZ(J,_6)}:void 0}))}if(this.isShowingConfirmationOverlay)z4.push(new tf1({details:this.confirmationOverlayContent}));if(this.imagePreviewIndex!==null&&this.imagePreviewIndex<this.imageAttachments.length){let _6=this.imageAttachments[this.imagePreviewIndex];if(_6)z4.push(new j4({child:new ib1({image:_6,imageIndex:this.imagePreviewIndex,onDismiss:this.handleImagePreviewDismiss,onRemove:()=>this.handleImageRemove(this.imagePreviewIndex)})}))}let r6=this.getCommandPaletteContext(J);if(r6&&this.isShowingPalette&&this.paletteConfig)z4.push(new j4({child:new rf1({commandContext:r6,mainThread:U.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)z4.push(new $b1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let n6=new $5({children:z4});if(this.isShowingJetBrainsInstaller)return new _I({child:new kJ({actions:R4,child:new xX({shortcuts:R0,debugLabel:"jetbrains-installer-shortcuts",child:new Gg1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new Kz({controller:this.toastController,child:new _I({child:new Qv1({controller:this.toastController,child:new kJ({actions:R4,child:new xX({shortcuts:R0,debugLabel:"main-app-shortcuts",child:n6})})})})})}buildScrollableTodoList(J,Q,Y){return new bH6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Y})}buildBottomWidget(J,Q,Y,Z,X,G,V,K,q,W,H,F){if(J)return new Yb1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new ef1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new qg1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let U=this.handoffState.isInHandoffMode?[]:k71(Z),B=this.agentModeController?.isInRestrictedFreeMode()??!1,M=new cI({key:this.textFieldKey,controller:this.textController,triggers:q?[]:[new SW],completionBuilder:q?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:q?void 0:this.onTextSubmitted,theme:Y,placeholder:q?"Press Ctrl+C to exit":B?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!B&&!this.isShowingStandalonePalette()&&!this.handoffState.isGeneratingHandoff,shellPromptRules:U,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker,clipboard:y8.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,onImageClick:this.handleImageClick,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let Y1=this.previousThreadIdForHint;if(Y1)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${Y1} `},onDoubleAtTrigger:q?void 0:()=>{let Y1=this.textController.text,n=this.textController.cursorPosition,i=Y1.slice(0,n).lastIndexOf("@@");this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:()=>{if(i!==-1){let q1=this.textController.text,T1=q1.slice(0,i)+q1.slice(i+2);this.textController.text=T1,this.textController.cursorPosition=i}},onSubmit:()=>{this.dismissPalette()},onCancel:()=>{this.dismissPalette()}})},pendingSkills:this.pendingSkills,onClearPendingSkill:(Y1)=>{(this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker).removePendingSkill(Y1)},popSkill:()=>{let Y1=this.pendingSkills[this.pendingSkills.length-1];if(Y1)(this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker).removePendingSkill(Y1.name)}}),L=X.mainThread?.queuedMessages??[],A=Array.isArray(G)&&G.length>0,E=Array.isArray(L)&&L.length>0?new Fg1({queuedMessages:L}):void 0,P=A?this.buildScrollableTodoList(G,this.isTextfieldAndAutocompleteFocused&&!B,Z):void 0,R=[],C=this.currentShellModeStatus;if(C)R.push({child:new j1({text:new d(C==="hidden"?"shell mode (incognito)":"shell mode",new J1({color:C==="hidden"?Z.app.shellModeHidden:Z.app.shellMode}))}),position:"top-left"});if(this.handoffState.isInHandoffMode){let Y1=new J1({color:Z.app.handoffMode}),n=this.handoffState.isGeneratingHandoff&&this.handoffState.spinner?new d("",void 0,[new d("handoff ",Y1),new d(this.handoffState.spinner.toBraille(),Y1)]):new d("handoff (submit a goal for the new thread)",Y1);if(R.push({child:new j1({text:n}),position:"top-left"}),this.handoffState.isGeneratingHandoff)R.push({child:new j1({text:new d("",void 0,[new d("Esc",new J1({color:Z.app.keybind})),new d(" to cancel",new J1({color:Y.foreground,dim:!0}))])}),position:"bottom-left"})}let S=this.handoffController?.getEmptyHandoffParentThreadID()??null,k=this.agentModeController?.getVisibleModes()??[];if(!C&&!this.handoffState.isInHandoffMode&&!S&&k.length>1){let Y1=this.previewThread,n=Y1?Y1.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),o=R21(n),i=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,q1=Y1??i.thread,T1=V2(q1)>0,e=this.agentModeSlideProgress!==null,D1,L1,t1=(V1)=>Math.pow(V1,4);if(e){D1="top-left";let X1=H.size.width-n.length-4,B1=t1(this.agentModeSlideProgress);L1=Math.floor(B1*X1)}else if(T1)D1="top-right",L1=0;else D1="top-left",L1=void 0;let R1=T1&&!e,f1;if(e){let V1=t1(this.agentModeSlideProgress??0);f1=new J1({color:o,dim:V1>0.3})}else if(R1)f1=new J1({color:Y.foreground,dim:!0});else f1=new J1({color:o});if(Y1)R.push({child:new j1({text:new d(n,f1)}),position:D1,offsetX:L1});else{let V1=!T1&&!e,X1=new j1({text:new d(n,f1)});R.push({child:V1?new M8({child:X1,onClick:this.toggleAgentMode,cursor:"pointer"}):X1,position:D1,offsetX:L1})}}let f=q?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:X.mainThread?.env?.initial.trees?.[0]?.uri,m;if(f)m=m0.parse(f).fsPath;else m=process.cwd();let b=this.toHomeRelative(m),c=this.shorten(b),Z1=!q&&this.currentGitBranch?`${c} (${this.currentGitBranch})`:c;if(R.push({child:new j1({text:new d(Z1,new J1({color:Y.foreground,dim:!0}))}),position:"bottom-right"}),S){let Y1=this.getEffectiveAgentMode(),n=R21(Y1);R.push({child:new j1({text:new d(Y1,new J1({color:n}))}),position:"top-left"});let o=this.handoffState.isConfirmingAbortHandoff?" again to abort ":" to abort ";R.push({child:new j1({text:new d("",void 0,[new d("Esc",new J1({color:Z.app.keybind})),new d(o,new J1({color:Y.foreground,dim:!0})),new d("handoff",new J1({color:Z.app.handoffMode}))])}),position:"bottom-left"})}if(!S&&this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0&&this.textController.text.trim()==="")R.push({child:new j1({text:new d("",void 0,[new d("press ",new J1({color:Y.foreground,dim:!0})),new d("enter",new J1({color:Z.app.keybind})),new d(" to reference the previous thread",new J1({color:Y.foreground,dim:!0}))])}),position:"bottom-left"});let p=this.previewThread,s=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(V2(s.thread)>0&&!C&&!this.handoffState.isInHandoffMode&&!p){let Y1=[],n=new J1({color:Y.foreground,dim:!0}),o=new d(" · ",n);if(W){let i=W.totalInputTokens/W.maxInputTokens,q1=Math.round(i*100),T1=Math.max(0,Math.min(q1,100)),e=d71(i,W.maxInputTokens),D1=n;if(e==="danger")D1=new J1({color:Y.destructive});else if(e==="warning")D1=new J1({color:Y.warning});else if(e==="recommendation")D1=new J1({color:Z.app.recommendation});let L1=Math.round(W.maxInputTokens/1000);Y1.push(new d(`${T1}% of ${L1}k`,D1))}if(F&&this.threadCostInfo){let i=c31(this.threadCostInfo,{colors:{foreground:Y.foreground},dim:!0});if(i.length>0){if(Y1.length>0)Y1.push(o);Y1.push(...i)}}if(Y1.length>0){let i=new j1({text:new d("",void 0,Y1)});R.push({child:F?new M8({child:i,onClick:this.showContextDetailOverlay,cursor:"pointer"}):i,position:"top-left"})}}return new Wv1({leftChild:new a6({child:M}),rightChild1:E,rightChild2:P,maxHeight:V,overlayTexts:R,borderColor:B||!this.isTextfieldAndAutocompleteFocused||this.handoffState.isGeneratingHandoff?N1.index(8):void 0,hasBanner:K,userHeight:this.bottomGridUserHeight,onInitializeHeight:(Y1)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(Y1,V)})},onDrag:(Y1)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(Y1.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let n=Math.floor(Y1.localPosition.y)-this.bottomGridDragStartY,o=Math.max(4,this.bottomGridDragStartHeight-n),i=Math.min(o,V),q1=Math.floor(i);if(this.bottomGridUserHeight!==q1)this.setState(()=>{this.bottomGridUserHeight=q1})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!K})}}async function Lg1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)y8.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let Z=()=>null,G=!1;if(G)process.env.AMP_INSPECTOR_ENABLED="1";let V=new Qz(G,1000,J.inspectorPort),K=new If1({threadService:J.threadService,worker:J.worker,builder:(L,A,I,E,P,R)=>{Z=P;let C=P(),S={...J,worker:C,threadID:C.thread.id};return new fH6({...S,threadState:A,workerController:I,switchWorker:E,getCurrentWorker:P,recentThreadIDs:R})}}),q=new Hv1({configService:J.configService,child:K}),W=new ch1({configService:J.configService,child:q}),H=new ix1(W),F=new q6({data:GS.fromBaseTheme(LG.default()),child:H});try{await sy1(F,{onRootElementMounted:(L)=>{if(v.info("TUI input ready for user interaction"),G)V.start(L),CZ6(L)}})}finally{if(G)V.stop(),jZ6()}let B=Z()?.thread.id||J.threadID,M=await J.threadService.get(B);if(M&&M.messages.length>0){let L=`${J.ampURL.replace(/\/$/,"")}/threads/${B}`;sZ6(M,L,J.stdout)}}function R21(J){let Y=XV(J)?.uiHints?.secondaryColor;if(Y)return N1.rgb(Y.r,Y.g,Y.b);return BS8(J)}class bH6 extends d0{props;constructor(J){super();this.props=J}createState(){return new gH6}}class gH6 extends p0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,controller:Y,appTheme:Z}=this.widget.props;return new U6({crossAxisAlignment:"stretch",children:[new a6({child:new J5({controller:Y,autofocus:!1,child:new wf1({todos:Q})})}),new E2({controller:Y,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:G}=Y,V=this.viewportHeight,K=X+V;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(V,1),scrollOffset:Math.max(G,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(Z,X=0)=>{if(Z&&"size"in Z&&"children"in Z){let G=Z.children||[];for(let V of G){if(V&&"size"in V){let q=V.size;if(typeof q?.height==="number"&&q.height>0)return q.height}let K=Q(V,X+1);if(K>0)return K}}return 0},Y=Q(J);if(Y>0)return Y;if("size"in J){let Z=J.size;if(typeof Z?.height==="number"&&Z.height>0)return Z.height}return this.viewportHeight}}class mH6 extends l6{props;constructor(J){super();this.props=J}build(J){return new M8({child:new Z0({height:1}),cursor:E9.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let Z=J.findRenderObject()?.size.height??0;if(Z>0){this.props.onInitializeHeight(Z);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function BS8(J){let Q=0;for(let X=0;X<J.length;X++){let G=J.charCodeAt(X);Q=(Q<<5)-Q+G,Q=Q&Q}let Y=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],Z=Math.abs(Q)%Y.length;return N1.index(Y[Z])}ry1();try{if(process.platform==="win32")await Promise.resolve().then(() => Q6(rS(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){TY.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
4827
- `)}var am1=im1.join(CB0||im1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function hx8(J){process.emitWarning=function(Q,Y,Z,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Y||"Warning",K=!1;J.warn(G,{name:V,code:Z})}}function SG(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")GV("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")GV("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")GV("model.sonnet",Q.useSonnet)}async function rm1(J){try{await yx8(im1.dirname(am1),{recursive:!0}),await xx8(am1,J,"utf-8")}catch(Q){v.debug("Failed to save last thread ID",Q)}}async function fx8(){try{return(await zB6(am1,"utf-8")).trim()}catch(J){return null}}function bx8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}async function gx8(J){try{let Q=await _9.getUserInfo({},{config:J,signal:AbortSignal.timeout(5000)});if(Q.ok)return Q.result}catch(Q){v.debug("Failed to fetch user info:",Q)}return}var WB6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??FG,description:`Custom settings file path (overrides the default location ${FG})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(v).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${BI})`},{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:J2(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:VP.SMART.key,description:`Set the agent mode (${L$().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:L$().map((J)=>J.mode).concat("large")}],HB6=(J)=>("deprecated"in J)&&J.deprecated===!0,mx8=(J)=>("hidden"in J)&&J.hidden===!0,ux8=(J)=>("default"in J),px8=(J)=>("default"in J)?J.default:void 0;function dx8(J,Q){let Y=Q.args[0],Z=Q.commands.map((G)=>G.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let G=Z.filter((K)=>Y.includes(K)||K.includes(Y)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new b8(HG.unknownCommand(Y),1,V)}}var UB6=null;function Lg5(){return UB6}function ad(J){return{...J,getThreadEnvironment:f91,vfs:aj0({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new Qf(J.fileSystem),generateThreadTitle:$16,deleteThread:(Q)=>J.threadService.delete(Q),getServerStatus:()=>dR(J.configService)}}var sm1=m0.file(vx8.homedir()),BB6=process.env.XDG_CONFIG_HOME?m0.file(process.env.XDG_CONFIG_HOME):i0.joinPath(sm1,".config");async function pX(J,Q){SA0("0.0.1766217674-gf10025");let Y=cU1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([m0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:sm1,userConfigDir:BB6}),{initializeCLITelemetry:Z}=await Promise.resolve().then(() => (P21(),E21));Z(Y);let X=await Y.getLatest();v.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=N86({configService:Y}),K=new Map,q=()=>K.clear(),W=new lM1(Y,J.settings.getWorkspaceRootPath()),H=Kx0({configService:Y,filesystem:s9}),F=wj0({configService:Y,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(r,p,s)=>{let Q1=`${r}:${p}`,Y1=K.get(Q1);if(Y1)return v.debug("Reusing existing OAuth provider for server",{serverName:r,serverUrl:p}),Y1;v.debug("Creating OAuth provider for server",{serverName:r,serverUrl:p});let n=(async()=>{let o=new ZA(J.secrets),i=await o.getClientInfo(r,p),q1=s?.scopes??i?.scopes,T1=m26();v.info("OAuth headless mode check",{useHeadless:T1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:G5.isTTY});let e=void 0;if(T1)e=J.executeMode?g26():b26(r);let D1=new uM1({storage:o,serverName:r,serverUrl:p,clientId:s?.clientId??i?.clientId,clientSecret:s?.clientSecret??i?.clientSecret,authUrl:s?.authUrl??i?.authUrl,tokenUrl:s?.tokenUrl??i?.tokenUrl,scopes:q1,headlessAuthHandler:e});return v.debug("OAuth provider created",{serverName:r,serverUrl:p,hasManualClientId:!!(s?.clientId??i?.clientId),willUseDCR:!(s?.clientId??i?.clientId),scopes:q1,headlessMode:T1,executeMode:J.executeMode}),D1})();return K.set(Q1,n),n}}),U=Vu({configService:Y,filesystem:s9,spawn:fN,skillToolboxDirs:H.skillToolboxDirs}),{initializeToolProviders:B,startToolProviders:M}=await Promise.resolve().then(() => (qB6(),KB6)),L;if(J.executeMode){let r=await B({toolService:G,providers:[F,U],initialTimeout:15000});L=r.registrations;for(let[p,s]of r.initErrors)v.warn(`${p} provider initialization slow or failed:`,s)}else L=M({toolService:G,providers:[F,U]});if(Q.jetbrains)vP("JetBrains");else if(Q.ide&&LJ6())vP("VS Code");else if(Q.ide&&AJ6())vP("Neovim");if(J.executeMode)_A0(!0);let A,I=v7.status.pipe(X6((r)=>Boolean(r.connected&&r.authenticated)),I4()).subscribe((r)=>{if(r){if(!A)A=G.registerTool($66)}else A?.dispose(),A=void 0}),E;if(!J.executeMode){let r=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new i91(process.cwd(),{alwaysIncludePaths:r},!0)}else E=new class extends i91{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(G5.write(`No API key found. Starting login flow...
4827
+ `)}var am1=im1.join(CB0||im1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function hx8(J){process.emitWarning=function(Q,Y,Z,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Y||"Warning",K=!1;J.warn(G,{name:V,code:Z})}}function SG(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")GV("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")GV("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")GV("model.sonnet",Q.useSonnet)}async function rm1(J){try{await yx8(im1.dirname(am1),{recursive:!0}),await xx8(am1,J,"utf-8")}catch(Q){v.debug("Failed to save last thread ID",Q)}}async function fx8(){try{return(await zB6(am1,"utf-8")).trim()}catch(J){return null}}function bx8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}async function gx8(J){try{let Q=await _9.getUserInfo({},{config:J,signal:AbortSignal.timeout(5000)});if(Q.ok)return Q.result}catch(Q){v.debug("Failed to fetch user info:",Q)}return}var WB6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??FG,description:`Custom settings file path (overrides the default location ${FG})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(v).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${BI})`},{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:J2(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:VP.SMART.key,description:`Set the agent mode (${L$().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:L$().map((J)=>J.mode).concat("large")}],HB6=(J)=>("deprecated"in J)&&J.deprecated===!0,mx8=(J)=>("hidden"in J)&&J.hidden===!0,ux8=(J)=>("default"in J),px8=(J)=>("default"in J)?J.default:void 0;function dx8(J,Q){let Y=Q.args[0],Z=Q.commands.map((G)=>G.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let G=Z.filter((K)=>Y.includes(K)||K.includes(Y)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new b8(HG.unknownCommand(Y),1,V)}}var UB6=null;function Lg5(){return UB6}function ad(J){return{...J,getThreadEnvironment:f91,vfs:aj0({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new Qf(J.fileSystem),generateThreadTitle:$16,deleteThread:(Q)=>J.threadService.delete(Q),getServerStatus:()=>dR(J.configService)}}var sm1=m0.file(vx8.homedir()),BB6=process.env.XDG_CONFIG_HOME?m0.file(process.env.XDG_CONFIG_HOME):i0.joinPath(sm1,".config");async function pX(J,Q){SA0("0.0.1766222627-g05555f");let Y=cU1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([m0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:sm1,userConfigDir:BB6}),{initializeCLITelemetry:Z}=await Promise.resolve().then(() => (P21(),E21));Z(Y);let X=await Y.getLatest();v.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=N86({configService:Y}),K=new Map,q=()=>K.clear(),W=new lM1(Y,J.settings.getWorkspaceRootPath()),H=Kx0({configService:Y,filesystem:s9}),F=wj0({configService:Y,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(r,p,s)=>{let Q1=`${r}:${p}`,Y1=K.get(Q1);if(Y1)return v.debug("Reusing existing OAuth provider for server",{serverName:r,serverUrl:p}),Y1;v.debug("Creating OAuth provider for server",{serverName:r,serverUrl:p});let n=(async()=>{let o=new ZA(J.secrets),i=await o.getClientInfo(r,p),q1=s?.scopes??i?.scopes,T1=m26();v.info("OAuth headless mode check",{useHeadless:T1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:G5.isTTY});let e=void 0;if(T1)e=J.executeMode?g26():b26(r);let D1=new uM1({storage:o,serverName:r,serverUrl:p,clientId:s?.clientId??i?.clientId,clientSecret:s?.clientSecret??i?.clientSecret,authUrl:s?.authUrl??i?.authUrl,tokenUrl:s?.tokenUrl??i?.tokenUrl,scopes:q1,headlessAuthHandler:e});return v.debug("OAuth provider created",{serverName:r,serverUrl:p,hasManualClientId:!!(s?.clientId??i?.clientId),willUseDCR:!(s?.clientId??i?.clientId),scopes:q1,headlessMode:T1,executeMode:J.executeMode}),D1})();return K.set(Q1,n),n}}),U=Vu({configService:Y,filesystem:s9,spawn:fN,skillToolboxDirs:H.skillToolboxDirs}),{initializeToolProviders:B,startToolProviders:M}=await Promise.resolve().then(() => (qB6(),KB6)),L;if(J.executeMode){let r=await B({toolService:G,providers:[F,U],initialTimeout:15000});L=r.registrations;for(let[p,s]of r.initErrors)v.warn(`${p} provider initialization slow or failed:`,s)}else L=M({toolService:G,providers:[F,U]});if(Q.jetbrains)vP("JetBrains");else if(Q.ide&&LJ6())vP("VS Code");else if(Q.ide&&AJ6())vP("Neovim");if(J.executeMode)_A0(!0);let A,I=v7.status.pipe(X6((r)=>Boolean(r.connected&&r.authenticated)),I4()).subscribe((r)=>{if(r){if(!A)A=G.registerTool($66)}else A?.dispose(),A=void 0}),E;if(!J.executeMode){let r=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new i91(process.cwd(),{alwaysIncludePaths:r},!0)}else E=new class extends i91{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(G5.write(`No API key found. Starting login flow...
4828
4828
  `),!await cx8(J))await NI(),process.exit(1)}let P=await Ux0({isDevelopment:!1}),R=new ZS1(P,Y),C=new Hj1(P,{lazy:!0}),S=Q.notifications!==void 0?Q.notifications:!J.executeMode,k=M86({playNotificationSound:async(r)=>{if(S){D86(r);let p=ay1(),s=oy1();if((!p||s)&&X.settings["notifications.system.enabled"]!==!1){if(r==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(r==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:R,configService:Y});v.info("Starting Amp background services");let f=V16({threadService:R,threadHistoryService:C,configService:Y,isExtensionDevelopment:!1}),m;v7.status.subscribe((r)=>{m=r});let b=new Pq1({workspaceRoots:[m0.file(process.cwd())],getCurrentFile:()=>{if(!m?.openFile)return;try{return m0.parse(m.openFile)}catch(r){v.warn("Failed to parse current file URI",{uri:m.openFile,error:r});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let r=m.openFile;return m.visibleFiles.filter((p)=>p!==r).map((p)=>{try{return m0.parse(p)}catch(s){return v.warn("Failed to parse visible file URI",{uri:p,error:s}),null}}).filter((p)=>p!==null)}}),c=new ty1,Z1={codebaseContextService:b,configService:Y,toolService:G,mcpService:F,skillService:H,toolboxService:U,trustStore:W,threadService:R,threadHistoryService:C,threadSyncService:f,threadStorage:P,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,notificationService:k,fileSystem:Q.jetbrains||Q.ide?lj0:s9,terminal:c};return{...Z1,async asyncDispose(){if(Z1.mcpService.hasAuthenticatingClients())v.info("Waiting for OAuth authentication to complete before exit..."),await Z1.mcpService.waitForAuthentication();for(let r of L.values())r.dispose();await Z1.mcpService.dispose(),q(),await Z1.threadService.asyncDispose(),Z1.configService.unsubscribe(),V(),Z1.fuzzyServer.dispose(),Z1.threadSyncService.dispose(),Z1.settingsStorage[Symbol.dispose](),I.unsubscribe(),A?.dispose()}}}async function cx8(J){if(!J.executeMode){if(!await Ry1("Would you like to log in to Amp? [(y)es, (n)o]: "))return G5.write(`Login cancelled. Run the command again to retry.
4829
4829
  `),!1}return await NB6(J)}async function NB6(J){let Q=kx8(32).toString("hex"),Y=await Py1(J.ampURL,Q),Z=new AbortController;try{await _U(Y,Z.signal)}catch(G){v.error("Error opening browser",{error:G})}let X=await Py1(J.ampURL,Q,!1);G5.write(`If your browser does not open automatically, visit:
4830
4830
 
@@ -4834,7 +4834,7 @@ ${V6.blue.bold(X)}
4834
4834
  Login successful! You can now use the Amp CLI.
4835
4835
  `),!0}catch(G){return v.error("Login failed",{error:G}),TY.write(`
4836
4836
  Login failed: ${G instanceof Error?G.message:String(G)}
4837
- `),!1}}function lx8(){let J=new tV().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)Sj(),process.exit(0);let F=H.originalError??H;U26(F)}),J.option("-V, --version","Print the version number and exit",()=>{let F;try{F=`, ${kR(new Date("2025-12-20T08:06:30.612Z"))} ago`}catch{}G5.write(`0.0.1766217674-gf10025 (released 2025-12-20T08:06:30.612Z${F??""})
4837
+ `),!1}}function lx8(){let J=new tV().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)Sj(),process.exit(0);let F=H.originalError??H;U26(F)}),J.option("-V, --version","Print the version number and exit",()=>{let F;try{F=`, ${kR(new Date("2025-12-20T09:28:57.003Z"))} ago`}catch{}G5.write(`0.0.1766222627-g05555f (released 2025-12-20T09:28:57.003Z${F??""})
4838
4838
  `),process.exit(0)}),J.addHelpText("after",NJ6()),J.configureHelp({formatHelp:DJ6}),J.command("logout").description("Log out by removing stored API key").action(async(H,F)=>{let U=F.optsWithGlobals(),B=await uJ(U);await ox8(B)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,F)=>{let U=F.optsWithGlobals(),B=await uJ(U);await ax8(B,await Uy1(U,B.settings))});let Q=async(H,F,U)=>{cU1({storage:F.settings,secretStorage:F.secrets,workspaceRoots:Q0.of([m0.file(process.cwd())]),defaultAmpURL:F.ampURL,homeDir:sm1,userConfigDir:BB6});let B={...F,executeMode:!1};await om1(B,{...H,openThreadSwitcher:!0},U)},Y=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(H,F)=>{let U=F.optsWithGlobals(),B=await uJ(U);await FB6(U,B,F)});Y.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(H,F)=>{let U=F.optsWithGlobals(),B=await uJ(U);await Yv8(U,B,F)}),Y.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,F,U)=>{let B=U.optsWithGlobals(),M=await uJ(B);if(F.pick)TY.write(`${V6.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
4839
4839
  `);if(F.last||H||M.executeMode)await Qv8(B,M,H,U);else await Q(B,M,U)}),Y.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,F,U)=>{let B=U.optsWithGlobals(),M=await uJ(B);await Jv8(B,M,H,U)}),Y.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,F)=>{let U=F.optsWithGlobals(),B=await uJ(U);await FB6(U,B,F)}),Y.command("search <query>").alias("find").summary("Search threads").description(`Search for threads using a query DSL.
4840
4840
 
@@ -4850,8 +4850,8 @@ All matching is case-insensitive. File paths use partial matching.`).option("-n,
4850
4850
  Or pipe via stdin: echo "your message" | amp --execute`);SG(Y,Q);let V=await pX(J,Q);UB6=V;let K=ad(V),q=await gx8(V.configService),W=bx8(q?.email);if((J.executeMode||Q.streamJson)&&O9(Q.mode)&&!W)throw new b8(`Execute mode is not permitted with --mode '${Q.mode}'`,1);let H=async(b)=>{let c=await zB6(b,"utf-8"),Z1=JSON.parse(c);if(!I$(Z1.id))throw new b8(HG.invalidThreadId);return BJ1(V,{visibility:Z,agentMode:Q.mode,thread:Z1})},F=async(b)=>{if(!I$(b))throw new b8(HG.invalidThreadId);try{let[Z1,r]=await Promise.all([_9.getThreadLinkInfo({thread:b},{config:V.configService}),_9.getUserInfo({},{config:V.configService})]);if(Z1.ok&&r.ok){let p=Z1.result.creatorUserID,s=r.result.id;if(p&&p!==s&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new b8(`Cannot resume thread created by another user.
4851
4851
 
4852
4852
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}catch(Z1){if(Z1 instanceof b8)throw Z1;v.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Z1})}let c=await V.threadService.get(b)??void 0;return v.info(`[fetchAndStartThread] Loaded thread ${b}, agentMode: ${c?.agentMode??"undefined"}`),BJ1(V,{visibility:Z,agentMode:c?void 0:Q.mode,thread:c})},U=async()=>{try{if(Q.threadId)return F(Q.threadId);else return BJ1(V,{visibility:Z,agentMode:Q.mode})}catch(b){if(b instanceof b8)throw b;throw await iu(b,Q.threadId),Error("handleError should have called process.exit()")}},B=async()=>{return BJ1(V,{visibility:Z,agentMode:Q.mode})};if(Q.format==="jsonl")TY.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
4853
- `),await NI(),process.exit(1);if(J.executeMode&&Q.remote)await GQ6(X,G,V.configService),await V.asyncDispose(),process.exit(0);let M=await U();if(J.executeMode)tJ6(V.mcpService,J.settings),await E26(M,M.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,W,Q.mode),await V.asyncDispose(),process.exit(0);let L=!1,A=!1,I=!1;if(Q.jetbrains||Q.ide){await pA0();let b=bP({jetbrainsOnly:Q.jetbrains});if(b.length===0){if(Q.jetbrains)A=!await V.configService.get("jetbrains.skipInstall")}else if(b.length===1){let c=b[0];if(c)v7.selectConfig(c)}else I=!0}let E=Z51("0.0.1766217674-gf10025",V.settingsStorage),P=new p41(V.threadStorage),R=Q0.of([m0.file(process.cwd())]),C=Rq1(void 0,R),S=new X51(V.mcpService,J.settings.getWorkspaceRootPath());if(X)M.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let f=await(async()=>{try{let b=await _9.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(b.ok)return v.info("User free tier status:",b),b.result}catch(b){throw v.error("Failed to fetch free tier status:",b),b}})(),m=await WQ6();v.info("Loaded session state:",m),await Lg1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new m91,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,threadID:M.threadID,threadFuzzyIndexer:P,worker:M,workerDeps:K,skillService:K.skillService,configService:V.configService,internalAPIClient:_9,ampURL:J.ampURL,startNewThread:B,switchToThread:F,ideClient:v7,commandRegistry:C,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:S,showJetBrainsInstaller:A,showIdePicker:L,showIdePickerHint:I,openThreadSwitcher:Q.openThreadSwitcher,updateService:E,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:m,freeTierStatus:{canUseAmpFree:f.canUseAmpFree},workspace:q?.team??null,features:q?.features??[],isDogfooding:W,threadDependencies:V,initialAgentMode:Y.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function uJ(J){if(J.interactive)TY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4854
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,Z=await JJ6({...J,workspaceTrust:{current:!0,changes:Sy},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await rJ6(J.mcpConfig);Z=sJ6(Z,G)}let X=await Z.get("url","global");if(!X)X=dY;if(!kU(X))v.info("Targeting custom Amp server",{ampURL:X});return Z=QM0(Z),{executeMode:Q,isTTY:Y,ampURL:X,settings:Z,secrets:VQ6(await Uy1(J,Z))}}function nx8(J){let Q={};for(let Y=0;Y<J.length;Y++){let Z=J[Y];if(Z?.startsWith("--")){let G=Z.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Y+1];if(V&&!V.startsWith("--"))Q[G]=V,Y++}}return Q}async function ix8(){let J=nx8(process.argv);if($26({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),hx8(v),v.info("Starting Amp CLI.",{version:"0.0.1766217674-gf10025",buildTimestamp:"2025-12-20T08:06:30.612Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new b8(HG.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await lx8().parseAsync(process.argv)}Qj1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ix8().catch(iu)});async function ax8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),G5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4853
+ `),await NI(),process.exit(1);if(J.executeMode&&Q.remote)await GQ6(X,G,V.configService),await V.asyncDispose(),process.exit(0);let M=await U();if(J.executeMode)tJ6(V.mcpService,J.settings),await E26(M,M.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,W,Q.mode),await V.asyncDispose(),process.exit(0);let L=!1,A=!1,I=!1;if(Q.jetbrains||Q.ide){await pA0();let b=bP({jetbrainsOnly:Q.jetbrains});if(b.length===0){if(Q.jetbrains)A=!await V.configService.get("jetbrains.skipInstall")}else if(b.length===1){let c=b[0];if(c)v7.selectConfig(c)}else I=!0}let E=Z51("0.0.1766222627-g05555f",V.settingsStorage),P=new p41(V.threadStorage),R=Q0.of([m0.file(process.cwd())]),C=Rq1(void 0,R),S=new X51(V.mcpService,J.settings.getWorkspaceRootPath());if(X)M.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let f=await(async()=>{try{let b=await _9.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(b.ok)return v.info("User free tier status:",b),b.result}catch(b){throw v.error("Failed to fetch free tier status:",b),b}})(),m=await WQ6();v.info("Loaded session state:",m),await Lg1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new m91,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,threadID:M.threadID,threadFuzzyIndexer:P,worker:M,workerDeps:K,skillService:K.skillService,configService:V.configService,internalAPIClient:_9,ampURL:J.ampURL,startNewThread:B,switchToThread:F,ideClient:v7,commandRegistry:C,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:S,showJetBrainsInstaller:A,showIdePicker:L,showIdePickerHint:I,openThreadSwitcher:Q.openThreadSwitcher,updateService:E,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:m,freeTierStatus:{canUseAmpFree:f.canUseAmpFree},workspace:q?.team??null,features:q?.features??[],isDogfooding:W,threadDependencies:V,initialAgentMode:Y.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function uJ(J){if(J.interactive)TY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4854
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,Z=await JJ6({...J,workspaceTrust:{current:!0,changes:Sy},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await rJ6(J.mcpConfig);Z=sJ6(Z,G)}let X=await Z.get("url","global");if(!X)X=dY;if(!kU(X))v.info("Targeting custom Amp server",{ampURL:X});return Z=QM0(Z),{executeMode:Q,isTTY:Y,ampURL:X,settings:Z,secrets:VQ6(await Uy1(J,Z))}}function nx8(J){let Q={};for(let Y=0;Y<J.length;Y++){let Z=J[Y];if(Z?.startsWith("--")){let G=Z.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Y+1];if(V&&!V.startsWith("--"))Q[G]=V,Y++}}return Q}async function ix8(){let J=nx8(process.argv);if($26({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),hx8(v),v.info("Starting Amp CLI.",{version:"0.0.1766222627-g05555f",buildTimestamp:"2025-12-20T09:28:57.003Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new b8(HG.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await lx8().parseAsync(process.argv)}Qj1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ix8().catch(iu)});async function ax8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),G5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4855
4855
  `);else if(!kU(J.ampURL))G5.write(`Logging in to ${new URL(J.ampURL).hostname}
4856
4856
  `);let Y=process.env.AMP_API_KEY;if(Y)G5.write(`API key found in environment variable, storing...
4857
4857
  `),await Q.set("apiKey",Y,J.ampURL),G5.write(`API key successfully stored.
@@ -4864,7 +4864,7 @@ This thread belongs to a different user and cannot be continued for security rea
4864
4864
  `);else G5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
4865
4865
  `);process.exit(0)}async function rx8(J,Q,Y,Z,X){SG(X,J);let G=await pX(Q,J);try{let V=NJ1(Y);if(!V)DJ1(Y);let K=V,q=Z.trim();if(q.length===0)uX("Thread name cannot be empty");if(q.length>256)uX("Thread name cannot exceed 256 characters");if(!(await sS(K,G)).messages.length)uX("Cannot rename an empty thread.");let H=ad(G);await(await s3.getOrCreateForThread(H,K)).handle({type:"title",value:q}),v.info("GOT HERE"),await G.threadSyncService.sync(),v.info("GOT THERE"),G5.write(V6.green(`✓ Thread ${K} renamed to "${q}"
4866
4866
  `)),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose();let K=`Failed to rename thread: ${V instanceof Error?V.message:String(V)}`;uX(K)}}async function sx8(J,Q,Y,Z){SG(Z,J);let X=await pX(Q,J);try{let G=NJ1(Y);if(!G)DJ1(Y);let K=await sS(G,X),q=Jj(K);G5.write(q+`
4867
- `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;uX(V)}}async function tx8(J,Q,Y,Z,X){SG(X,J);let G=await pX(Q,J);try{let V=await tm1(Y),K=await sS(V,G),q=Z.typing!==!1,W=parseInt(Z.wpm||"120",10),H=parseInt(Z.messageDelay||"1000",10),F=parseInt(Z.toolProgressDelay||"800",10),U=parseInt(Z.exitDelay||"3",10)*1000,B=Z.indicator!==!1,M=ad(G),L=K.id;await G.threadStorage.set(L,K);let A=await s3.getOrCreateForThread(M,L);await A.resume();let I=u41.fromWorker(A),E=new p41(G.threadStorage),P=Q0.of([m0.file(process.cwd())]),R=Rq1(void 0,P),C=new X51(G.mcpService,Q.settings.getWorkspaceRootPath()),S=Z51("0.0.1766217674-gf10025",G.settingsStorage),k=Vu({configService:G.configService,filesystem:s9,spawn:fN,skillToolboxDirs:G.skillService.skillToolboxDirs});await Lg1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new m91,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,threadID:L,threadFuzzyIndexer:E,worker:I,workerDeps:M,skillService:M.skillService,configService:G.configService,internalAPIClient:_9,ampURL:Q.ampURL,startNewThread:async()=>I,switchToThread:async()=>I,ideClient:v7,commandRegistry:R,mcpService:G.mcpService,toolboxService:k,mcpTrustHandler:C,showJetBrainsInstaller:!1,updateService:S,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:F,exitDelayMs:U,showIndicator:B},freeTierStatus:{canUseAmpFree:!0},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await iu(V,Y)}}async function ex8(J,Q,Y,Z,X){SG(Z,J);let G=await pX(Q,J);try{let V=NJ1(Y);if(!V)DJ1(Y);let K=V,q=await _9.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=$51(J,W);if(!H&&!X)uX("Must specify either --visibility or --support");if(H&&X)uX("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)uX(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,G51(H)),G5.write(V6.green("✓ ")+`Thread ${K} visibility changed to ${H}.
4867
+ `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;uX(V)}}async function tx8(J,Q,Y,Z,X){SG(X,J);let G=await pX(Q,J);try{let V=await tm1(Y),K=await sS(V,G),q=Z.typing!==!1,W=parseInt(Z.wpm||"120",10),H=parseInt(Z.messageDelay||"1000",10),F=parseInt(Z.toolProgressDelay||"800",10),U=parseInt(Z.exitDelay||"3",10)*1000,B=Z.indicator!==!1,M=ad(G),L=K.id;await G.threadStorage.set(L,K);let A=await s3.getOrCreateForThread(M,L);await A.resume();let I=u41.fromWorker(A),E=new p41(G.threadStorage),P=Q0.of([m0.file(process.cwd())]),R=Rq1(void 0,P),C=new X51(G.mcpService,Q.settings.getWorkspaceRootPath()),S=Z51("0.0.1766222627-g05555f",G.settingsStorage),k=Vu({configService:G.configService,filesystem:s9,spawn:fN,skillToolboxDirs:G.skillService.skillToolboxDirs});await Lg1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new m91,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,threadID:L,threadFuzzyIndexer:E,worker:I,workerDeps:M,skillService:M.skillService,configService:G.configService,internalAPIClient:_9,ampURL:Q.ampURL,startNewThread:async()=>I,switchToThread:async()=>I,ideClient:v7,commandRegistry:R,mcpService:G.mcpService,toolboxService:k,mcpTrustHandler:C,showJetBrainsInstaller:!1,updateService:S,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:F,exitDelayMs:U,showIndicator:B},freeTierStatus:{canUseAmpFree:!0},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await iu(V,Y)}}async function ex8(J,Q,Y,Z,X){SG(Z,J);let G=await pX(Q,J);try{let V=NJ1(Y);if(!V)DJ1(Y);let K=V,q=await _9.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=$51(J,W);if(!H&&!X)uX("Must specify either --visibility or --support");if(H&&X)uX("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)uX(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,G51(H)),G5.write(V6.green("✓ ")+`Thread ${K} visibility changed to ${H}.
4868
4868
  `);if(X){await sS(K,G);let F=typeof X==="string"?X:void 0;await L_0(G.threadService,K,G.configService,F),G5.write(V6.green("✓ ")+`Thread ${K} has been shared with Amp support. These thread reports will be aggregated and analysed.
4869
4869
  `)}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),uX(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function Jv8(J,Q,Y,Z){SG(Z,J);let X=await pX(Q,J),G=ad(X);try{let V=await tm1(Y),q=(await sS(V,X)).messages.length-1,W=await s3.getOrCreateForThread(G,V),H=await Kj(W,X.threadSyncService,q);await Promise.all([X.threadSyncService.uploadThread(V),X.threadSyncService.uploadThread(H)]),await rm1(H),G5.write(`${H}
4870
4870
  `),await X.asyncDispose(),process.exit(0)}catch(V){TY.write(`Error forking thread: ${V instanceof Error?V.message:String(V)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1766217674-gf10025",
3
+ "version": "0.0.1766222627-g05555f",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {