@sourcegraph/amp 0.0.1768204893-g301329 → 0.0.1768218876-g7c0d4d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +12 -12
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -730,7 +730,7 @@ description: Your skill description
|
|
|
730
730
|
`);return["The following skills provide specialized instructions for specific tasks.",`Use the ${L2} 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(`
|
|
731
731
|
`)}var zT0,JE4,aH=64,HI,sD1=1024,tD1=500,XE4,$E4="mcp.json";var hB=l(()=>{r0();v1();z5();z7();j6();xq1();zT0=H0(iH(),1),JE4=new Set(["name","description","license","compatibility","metadata","allowed-tools","argument-hint","model","disable-model-invocation","mode","isolatedContext"]),HI=/^[a-z0-9](?:[a-z0-9]*(?:-[a-z0-9]+)*)?$/;XE4=/^skill\.md$/i});function $B1(J,Q,Y=()=>!0){let Z=Q();for(let[X,G]of J){if(!Y(G,X))continue;let V=Z.get(X);if(!V||G.timestamp>=V.timestamp)Z.set(X,G)}return Z}function Go(J,Q=()=>!0){function*Y(){for(let Z of J.values())yield*Z}return $B1(Y(),()=>new H7,Q)}async function Vo(J,Q,Y){if(Q<=0)throw Error("chunkSize must be greater than 0");if(J.length===0)return;for(let Z=0;Z<J.length;Z+=Q)await Promise.all(J.slice(Z,Z+Q).map(Y))}var tk=l(()=>{hX()});async function hT0(J,Q=()=>!0){let Y=await J.getAllRecords(),Z=Go(Y,(G,V)=>!G.reverted&&Q(V)),X=[];for(let[G,V]of Z.entries()){let{added:K,removed:q,modified:W,created:H,reverted:z}=GB1(V);if(!K&&!q&&!W)continue;X.push({created:H,uri:h0(G),reverted:z,diff:void 0,after:void 0,diffStat:{added:K,removed:q,modified:W}})}return X}function GB1(J){let Q=J.diff.split(`
|
|
732
732
|
`),Y=0,Z=0,X=0;for(let K of Q){if(K.startsWith("+")&&!K.startsWith("+++"))Y++;if(K.startsWith("-")&&!K.startsWith("---"))Z++;if(K.startsWith("@"))X++}let G=J.reverted,V=J.isNewFile===!0;if(V)Y=J.after.split(`
|
|
733
|
-
`).length,Z=0,X=0;return{added:Y,removed:Z,modified:X,created:V,reverted:G}}var Ko=".backfill-complete",D49;var qo=l(()=>{r0();W5();tk();D49=K1.object({id:K1.string(),uri:K1.string(),before:K1.string(),after:K1.string(),diff:K1.string(),isNewFile:K1.boolean().optional(),reverted:K1.boolean(),timestamp:K1.number()})});import nE4 from"node:os";function aE4(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 DI{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=s1.joinPath(Z,this.filename(Q));await this.fs.writeFile(X,JSON.stringify(Y,null,2)),await this.invalidateBackfillMarker(Z)}async invalidateBackfillMarker(J){let Q=s1.joinPath(J,Ko);try{await this.fs.delete(Q)}catch{}}async load(J,Q){let Y=this.backupDirForThread(J);if(!Y)return null;try{let Z=await this.fs.readFile(s1.joinPath(Y,this.filename(Q)));return JSON.parse(Z)}catch(Z){return P.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=s1.relativePath(Q,X.uri);if(!G)continue;let V=G.split(".");if(V.length===2){let K=V[0],q=V[1];if(K&&aE4(q))Z.push({toolUseID:K,fileChangeID:q})}}return Z}catch(Y){return P.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(!E9(Y))P.error(`Error cleaning up backup files in ${Q}:`,Y)}}getRootURI(){let J=typeof process<"u"?nE4.homedir():null;if(!J)return null;return s1.joinPath(Q0.file(J),".amp","file-changes")}filename(J){return`${J.toolUseID}.${J.fileChangeID}`}backupDirForThread(J){let Q=this.getRootURI();if(!Q)return null;return s1.joinPath(Q,J)}}var VB1;var Wo=l(()=>{r0();v1();z7();qo();VB1={async store(){},async load(){return null},async list(){return[]},async cleanup(){},getRootURI(){return null}}});function sK(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 k2{bits;constructor(J){this.bits=J}static empty(){return new k2(0n)}static fromString(J){let Q=0n;for(let Y=0;Y<J.length;Y++){let Z=J.charCodeAt(Y),X=k2.charToBitIndex(Z);if(X>=0)Q|=1n<<BigInt(X)}return new k2(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=k2.charToBitIndex(G);if(V>=0)Q|=1n<<BigInt(V)}}return new k2(Q)}hasChars(J){return(this.bits&J.bits)===J.bits}union(J){return new k2(this.bits|J.bits)}intersection(J){return new k2(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=k2.bitIndexToChar(Q);if(Y)J.push(Y)}return`CharBag{${J.join("")}}`}toJSON(){return{bits:this.bits.toString()}}static fromJSON(J){return new k2(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 xJ{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=k2.fromPath(this.path)}withUpdates(J){return new xJ({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 xJ({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 BI=()=>{};class Ho{config;queryChars;queryLower;constructor(J,Q={}){this.config={...sE4,...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((z)=>z.length>0);if(J.endsWith("/")&&Q.isDirectory()){let z=Y.slice(0,-1);if(X===z||X.endsWith("/"+z))return y2.EXACT_FILENAME+100;if(X.includes(z))return y2.SUBSTRING_FILENAME+50}if(V===Y||G.toLowerCase()===Y)return y2.EXACT_FILENAME;if(V.startsWith(Y))return y2.PREFIX_FILENAME;if(V.endsWith(Y))return y2.SUFFIX_FILENAME;if(V.includes(Y))return y2.SUBSTRING_FILENAME;let q=this.simpleTokens(Y);if(q.length>1){let z=this.matchTokensToSegments(q,K);if(z)return z}if(q.length===1&&Y.length>6){let z=this.progressiveSegmentMatch(Y,K);if(z)return z}if(K.includes(Y))return y2.SEGMENT_EXACT;if(K.some((z)=>z.includes(Y)))return y2.SEGMENT_SUBSTRING;if(K.join("").includes(Y))return y2.SEGMENT_SUBSTRING;if(X.replace(/[\s-_]/g,"").includes(Y))return y2.PATH_SUBSTRING;return 0}calculateFuzzyScore(J,Q){let Y=J.toLowerCase(),Z=Q.path.toLowerCase();if(this.fuzzyIn(Y,Z))return y2.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?y2.SEGMENT_ORDERED_EXACT:y2.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 y2.SEGMENT_ORDERED_EXACT;case"partial":return y2.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=k2.fromString(Z);if(!Q.charBag.hasChars(X))return!1}return!0}else{let Y=k2.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 NI(J,Q,Y){return new Ho(J,Y).match(Q)}var sE4,y2;var ek=l(()=>{sE4={minScore:400,caseSensitive:!1,penalizeLengthDifference:!0,maxResults:50,smartCase:!0},y2={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 o5(J,Q={},Y){let Z=`/api/internal/github-proxy/${J}`,{body:X,headers:G={},method:V="GET",...K}=Q,q=await mR0(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 bG=l(()=>{N3()});async function pT0(J,Q,Y,Z,X){let G=sK(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 o5(W,{signal:Z},X);if(!H.ok||!H.data)throw Error(`Failed to fetch files: ${H.status} ${H.statusText||"Unknown error"}`);let F=H.data.tree.filter((N)=>N.type==="blob").map((N)=>N.path),U=uT0.default(V),D=F.filter((N)=>U(N));return{files:K?D.slice(q,q+K):D.slice(q),truncated:H.data.truncated}}var uT0;var dT0=l(()=>{bG();uT0=H0(vC(),1)});function cT0(J,Q,Y){let Z=new Map,X=async()=>{try{let K;if(Y)K=await J.get(Y);else K=J.getRecentlyActiveThread();if(K){let q=K.id,W=K.env?.initial.trees||[];if(P.info("Found thread:",q,"trees:",W.length),W.length>0)return P.info("Using trees from thread:",q),{trees:W,threadId:q}}else P.info("No thread found");return null}catch(K){return P.error("Error getting thread:",K),null}},G=async(K)=>{if(!K.repository||!K.repository.url||!K.repository.sha)return[];let q=K.repository,W=q.sha,H=Date.now(),z=`${q.url}:${W}`,F=Z.get(z);if(F&&H-F.timestamp<300000)return F.entries;try{let U=await pT0(q.url,W,{filePattern:"**/*",limit:1e4},void 0,Q),D=U.files.map((N)=>{let w={mtime:Date.now(),size:0,inode:0,isSymlink:!1},M=Q0.file(`/${N}`);return new xJ({id:`github:${q.url}:${W}:${N}`,kind:"file",path:N,uri:M,metadata:w})}),B={entries:D,timestamp:H,repoUrl:q.url,sha:W};if(Z.set(z,B),U.truncated)P.warn("GitHub repository file listing was truncated",{repo:q.url,indexedFiles:D.length});return D}catch(U){return P.error("Failed to fetch files from GitHub API",U),[]}},V=(K)=>{return K.map((q)=>{let W=q.path,H=`@${pA(W)}`,z=W.split("/"),F=z[z.length-1]||W,U=z.length>1?z.slice(0,-1).join("/"):"";return{uri:h0(q.uri),label:F,detail:U,insertText:H,filterText:W.toLowerCase(),kind:q.isDirectory()?"folder":"file"}})};return{search(K){return n0(async()=>{let q=await X();if(!q)return[];let{trees:W,threadId:H}=q,z=W.find((B)=>B.repository?.url!=null&&B.repository?.sha!=null);if(!z)return[];P.info("Found GitHub repository",{threadId:H,uri:z.uri,repoUrl:z.repository.url,sha:z.repository.sha});let F=await G(z);if(F.length===0)return[];let U;if(!K)P.info("Empty query, returning first 10 files"),U=F.slice(0,10);else try{U=NI(K,F,{maxResults:50,minScore:400}).map((N)=>N.entry)}catch(B){return P.error("Fuzzy search failed",B),[]}return V(U).slice(0,uA)})},dispose(){Z.clear()}}}var lT0=l(()=>{r0();K0();v1();BI();ek();Jk();dT0()});function Jy(J){if(!J.startsWith("refs/heads/"))return null;return J.slice(11)}function Fo(J){let Q=mO(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(CK(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(CK(J,Z.id)?.run.status==="done")return!0}}}}return!1}var KB1=l(()=>{n6()});function tE4(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=sK(Q.repository.url,{provider:"github"});if(!Y||Y.provider!=="github")return null;let Z=Q.repository.headRef?Jy(Q.repository.headRef):null;return{repo:Y.name,branch:Z,provider:"github"}}async function eE4({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 o5(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:h0(Q0.parse(q.html_url)),number:q.number.toString(),merged:W}}return null}catch(X){return P.debug("Failed to check GitHub pull request status:",X),null}}function iT0(J,Q,Y,Z){let X=J.observe(Q).pipe(q0((G)=>[{id:G.id,env:G.env},G.messages.length>=2&&Fo(G)]),q6());return v4(X,Z.pipe(H4(void 0),k9((G)=>{return P.error("pullRequestChanges subject error, continuing with undefined",{error:G,threadID:Q}),T1.of(void 0)}))).pipe(WQ(([[G,V]])=>{if(!G||!V)return T1.of([]);let K=tE4(G);if(!K)return T1.of([]);let W=G.env?.initial?.trees?.find((H)=>H.repository?.url)?.repository?.pullRequestURL;return n0(async(H)=>{if(W&&!K.branch){let F=W.split("/").pop()||"";try{let U=`repos/${K.repo}/pulls/${F}`,D=await o5(U,{signal:H,cache:"no-cache"},Y);if(D.ok&&D.data){let B=D.data;return[{type:B.state==="closed"&&B.merged_at!==null?"view-merged-pull-request":"view-pull-request",url:h0(Q0.parse(B.html_url)),number:B.number.toString()}]}}catch(U){P.debug("Failed to fetch specific PR:",U)}}let z=await eE4(K,Y,H);if(z)return[{type:z.merged?"view-merged-pull-request":"view-pull-request",url:z.url,number:z.number}];return[{type:"create-pull-request"}]})}),$4({shouldCountRefs:!0}))}var nT0=l(()=>{r0();K0();v1();KB1();bG()});async function Qy(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)??JR4;return QR4(J,{...Q,auth:{instanceURL:X,accessToken:Z}})}async function QR4(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,H;if(Y.method!=="HEAD"&&q.status!==204)try{H=await q.text(),W=JSON.parse(H)}catch(z){P.info("GitLab API response not JSON:",{url:X,status:q.status,responseText:H?.substring(0,200)})}return P.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 P.error(`GitLab API request error (${X}):`,q),{ok:!1,status:0,statusText:q instanceof Error?q.message:String(q)}}}var JR4="https://gitlab.com";var qB1=l(()=>{v1()});function aT0(J){let Q=J.replace(/\.git$/,"");try{return new URL(Q).pathname.replace(/^\//,"")}catch{return Q.match(/https?:\/\/[^/]+\/(.+)/)?.[1]??Q}}function YR4(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 ZR4(J,Q,Y,Z){let{filePattern:X,limit:G=100,offset:V=0}=Y,K=YR4(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 z=await Qy(H,{config:Z});if(!z.ok||!z.data)return null;let F=new Set(z.data.map((N)=>N.path)),U=Array.from(F),D=WB1.default(X);return{files:U.filter((N)=>D(N)),truncated:z.data.length===G}}catch(z){return null}}async function XR4(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 Qy(q,{config:Z});if(!W.ok||!W.data)throw Error(`Failed to fetch files: ${W.status} ${W.statusText||"Unknown error"}`);let z=W.data.filter((B)=>B.type==="blob").map((B)=>B.path),F=WB1.default(X),U=z.filter((B)=>F(B));return{files:G?U.slice(V,V+G):U.slice(V),truncated:W.data.length===1000}}async function oT0(J,Q,Y,Z){let X=aT0(J);if(!X)throw Error(`Invalid GitLab repository URL: ${J}`);let G=await ZR4(X,Q,Y,Z);if(G)return G;return XR4(X,Q,Y,Z)}var WB1;var rT0=l(()=>{qB1();WB1=H0(vC(),1)});function sT0(J,Q,Y){let Z=new Map,X=async()=>{try{let K;if(Y)K=await J.get(Y);else K=J.getRecentlyActiveThread();if(K){let q=K.id,W=K.env?.initial.trees||[];if(P.info("Found thread:",q,"trees:",W.length),W.length>0)return P.info("Using trees from thread:",q),{trees:W,threadId:q}}else P.info("No thread found");return null}catch(K){return P.error("Error getting thread:",K),null}},G=async(K)=>{if(!K.repository||!K.repository.url||!K.repository.sha)return[];let q=K.repository,W=q.sha,H=Date.now(),z=`${q.url}:${W}`,F=Z.get(z);if(F&&H-F.timestamp<300000)return F.entries;try{let U=await oT0(q.url,W,{filePattern:"**/*",limit:1e4},Q),D=U.files.map((N)=>{let w={mtime:Date.now(),size:0,inode:0,isSymlink:!1},M=Q0.file(`/${N}`);return new xJ({id:`gitlab:${q.url}:${W}:${N}`,kind:"file",path:N,uri:M,metadata:w})}),B={entries:D,timestamp:H,repoUrl:q.url,sha:W};if(Z.set(z,B),U.truncated)P.warn("GitLab repository file listing was truncated",{repo:q.url,indexedFiles:D.length});return D}catch(U){return P.error("Failed to fetch files from GitLab API",U),[]}},V=(K)=>{return K.map((q)=>{let W=q.path,H=`@${pA(W)}`,z=W.split("/"),F=z[z.length-1]||W,U=z.length>1?z.slice(0,-1).join("/"):"";return{uri:h0(q.uri),label:F,detail:U,insertText:H,filterText:W.toLowerCase(),kind:q.isDirectory()?"folder":"file"}})};return{search(K){return n0(async()=>{let q=await X();if(!q)return[];let{trees:W,threadId:H}=q,z=W.find((B)=>B.repository?.url!=null&&B.repository?.sha!=null&&B.fs==="gitlab");if(!z)return[];P.info("Found GitLab repository",{threadId:H,uri:z.uri,repoUrl:z.repository.url,sha:z.repository.sha});let F=await G(z);if(F.length===0)return[];let U;if(!K)P.info("Empty query, returning first 10 files"),U=F.slice(0,10);else try{U=NI(K,F,{maxResults:50,minScore:400}).map((N)=>N.entry)}catch(B){return P.error("Fuzzy search failed",B),[]}return V(U).slice(0,uA)})},dispose(){Z.clear()}}}var tT0=l(()=>{r0();K0();v1();BI();ek();Jk();rT0()});function $R4(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=sK(Q.repository.url,{gitlabInstanceURL:Y});if(!Z||Z.provider!=="gitlab")return null;let X=Q.repository.headRef?Jy(Q.repository.headRef):Q.repository.ref?Jy(Q.repository.ref):null;return{repo:Z.name,branch:X,provider:"gitlab",instanceURL:Z.instanceURL}}async function GR4({repo:J,branch:Q,instanceURL:Y},Z,X){if(!Q||!Y)return P.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`;P.info("GitLab MR check: making API request",{repo:J,branch:Q,instanceURL:Y,apiEndpoint:V,projectPath:G});let K=await Qy(V,{config:Z,signal:X,cache:"no-cache"});if(!K.ok||!K.data)return P.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:h0(Q0.parse(W.web_url)),number:W.iid.toString(),merged:W.state==="merged"}}return null}catch(G){return null}}function eT0(J,Q,Y,Z){P.info("GitLab thread actions: setting up observable for thread",{threadID:Q});let X=J.observe(Q).pipe(q0((G)=>{let V=G.messages.length>=2&&Fo(G);return[{id:G.id,env:G.env},V]}),q6());return v4(X,Z.pipe(H4(void 0),k9((G)=>{return P.error("mergeRequestChanges subject error, continuing with undefined",{error:G,threadID:Q}),T1.of(void 0)}))).pipe(WQ(([[G,V],K])=>{if(!G||!V)return P.info("GitLab thread actions: no thread or no messages, returning empty",{threadID:Q}),T1.of([]);let q=$R4(G);if(!q)return P.info("GitLab thread actions: not a GitLab repository, returning empty",{threadID:Q}),T1.of([]);return n0(async(W)=>{let H=await GR4(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"}]})}),$4({shouldCountRefs:!0}))}var JC0=l(()=>{r0();K0();v1();KB1();qB1()});class HB1{threadService;config;name="github";mentionFilesDataSource;pullRequestChanges=new E6;constructor(J,Q,Y){this.threadService=J;this.config=Q;this.mentionFilesDataSource=cT0(J,Q,Y)}getThreadActions(J){return iT0(this.threadService,J,this.config,this.pullRequestChanges)}canHandle(J){if(!J)return!1;return sK(J,{provider:"github"})?.provider==="github"}dispose(){this.mentionFilesDataSource.dispose()}}class QC0{threadService;config;name="gitlab";mentionFilesDataSource;pullRequestChanges=new E6;constructor(J,Q,Y){this.threadService=J;this.config=Q;this.mentionFilesDataSource=sT0(J,Q,Y)}getThreadActions(J){return eT0(this.threadService,J,this.config,this.pullRequestChanges)}canHandle(J){if(!J)return!1;let Q=new URL(J).origin;return sK(J,{gitlabInstanceURL:Q})?.provider==="gitlab"}dispose(){this.mentionFilesDataSource.dispose()}}function YC0(J,Q,Y,Z){let X=J.find((K)=>K.repository?.url);if(!X?.repository?.url)return new HB1(Q,Y,Z);if(X.repository.url.includes("gitlab.")||X.fs==="gitlab")return new QC0(Q,Y,Z);else return new HB1(Q,Y,Z)}var ZC0=l(()=>{K0();lT0();nT0();tT0();JC0()});function a0(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 a1(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 tK=()=>{};var zB1=function(){let{crypto:J}=globalThis;if(J?.randomUUID)return zB1=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 eK(J){return typeof J==="object"&&J!==null&&(("name"in J)&&J.name==="AbortError"||("message"in J)&&String(J.message).includes("FetchRequestCanceledException"))}var Yy=(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 L6,U7,a3,mB,Zy,Xy,$y,Gy,Vy,Ky,qy,Wy,Hy;var qZ=l(()=>{L6=class L6 extends Error{};U7=class U7 extends L6{constructor(J,Q,Y,Z){super(`${U7.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 mB({message:Y,cause:Yy(Q)});let X=Q;if(J===400)return new Xy(J,X,Y,Z);if(J===401)return new $y(J,X,Y,Z);if(J===403)return new Gy(J,X,Y,Z);if(J===404)return new Vy(J,X,Y,Z);if(J===409)return new Ky(J,X,Y,Z);if(J===422)return new qy(J,X,Y,Z);if(J===429)return new Wy(J,X,Y,Z);if(J>=500)return new Hy(J,X,Y,Z);return new U7(J,X,Y,Z)}};a3=class a3 extends U7{constructor({message:J}={}){super(void 0,void 0,J||"Request was aborted.",void 0)}};mB=class mB extends U7{constructor({message:J,cause:Q}){super(void 0,void 0,J||"Connection error.",void 0);if(Q)this.cause=Q}};Zy=class Zy extends mB{constructor({message:J}={}){super({message:J??"Request timed out."})}};Xy=class Xy extends U7{};$y=class $y extends U7{};Gy=class Gy extends U7{};Vy=class Vy extends U7{};Ky=class Ky extends U7{};qy=class qy extends U7{};Wy=class Wy extends U7{};Hy=class Hy extends U7{}});function Uo(J){if(typeof J!=="object")return{};return J??{}}function $C0(J){if(!J)return!0;for(let Q in J)return!1;return!0}function GC0(J,Q){return Object.prototype.hasOwnProperty.call(J,Q)}var KR4,XC0=(J)=>{return KR4.test(J)},FB1=(J)=>(FB1=Array.isArray,FB1(J)),UB1,VC0=(J,Q)=>{if(typeof Q!=="number"||!Number.isInteger(Q))throw new L6(`${J} must be an integer`);if(Q<0)throw new L6(`${J} must be a positive integer`);return Q},Do=(J)=>{try{return JSON.parse(J)}catch(Q){return}};var uB=l(()=>{qZ();KR4=/^[a-z][a-z0-9+.-]*:/i,UB1=FB1});var KC0=(J)=>new Promise((Q)=>setTimeout(Q,J));var rH="0.71.2";function qR4(){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 HR4(){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 zC0=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},WR4=()=>{let J=qR4();if(J==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":rH,"X-Stainless-OS":WC0(Deno.build.os),"X-Stainless-Arch":qC0(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":rH,"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":rH,"X-Stainless-OS":WC0(globalThis.process.platform??"unknown"),"X-Stainless-Arch":qC0(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Q=HR4();if(Q)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":rH,"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":rH,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},qC0=(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"},WC0=(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"},HC0,FC0=()=>{return HC0??(HC0=WR4())};var DB1=()=>{};function UC0(){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 BB1(...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 Bo(J){let Q=Symbol.asyncIterator in J?J[Symbol.asyncIterator]():J[Symbol.iterator]();return BB1({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 zy(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 DC0(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 BC0=({headers:J,body:Q})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Q)}};function MC0(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 Fy(J){let Q;return(NC0??(Q=new globalThis.TextEncoder,NC0=Q.encode.bind(Q)))(J)}function NB1(J){let Q;return(wC0??(Q=new globalThis.TextDecoder,wC0=Q.decode.bind(Q)))(J)}var NC0,wC0;class sH{constructor(){PQ.set(this,void 0),TQ.set(this,void 0),a0(this,PQ,new Uint8Array,"f"),a0(this,TQ,null,"f")}decode(J){if(J==null)return[];let Q=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?Fy(J):J;a0(this,PQ,MC0([a1(this,PQ,"f"),Q]),"f");let Y=[],Z;while((Z=UR4(a1(this,PQ,"f"),a1(this,TQ,"f")))!=null){if(Z.carriage&&a1(this,TQ,"f")==null){a0(this,TQ,Z.index,"f");continue}if(a1(this,TQ,"f")!=null&&(Z.index!==a1(this,TQ,"f")+1||Z.carriage)){Y.push(NB1(a1(this,PQ,"f").subarray(0,a1(this,TQ,"f")-1))),a0(this,PQ,a1(this,PQ,"f").subarray(a1(this,TQ,"f")),"f"),a0(this,TQ,null,"f");continue}let X=a1(this,TQ,"f")!==null?Z.preceding-1:Z.preceding,G=NB1(a1(this,PQ,"f").subarray(0,X));Y.push(G),a0(this,PQ,a1(this,PQ,"f").subarray(Z.index),"f"),a0(this,TQ,null,"f")}return Y}flush(){if(!a1(this,PQ,"f").length)return[];return this.decode(`
|
|
733
|
+
`).length,Z=0,X=0;return{added:Y,removed:Z,modified:X,created:V,reverted:G}}var Ko=".backfill-complete",D49;var qo=l(()=>{r0();W5();tk();D49=K1.object({id:K1.string(),uri:K1.string(),before:K1.string(),after:K1.string(),diff:K1.string(),isNewFile:K1.boolean().optional(),reverted:K1.boolean(),timestamp:K1.number()})});import nE4 from"node:os";function aE4(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 DI{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=s1.joinPath(Z,this.filename(Q));await this.fs.writeFile(X,JSON.stringify(Y,null,2)),await this.invalidateBackfillMarker(Z)}async invalidateBackfillMarker(J){let Q=s1.joinPath(J,Ko);try{await this.fs.delete(Q)}catch{}}async load(J,Q){let Y=this.backupDirForThread(J);if(!Y)return null;try{let Z=await this.fs.readFile(s1.joinPath(Y,this.filename(Q)));return JSON.parse(Z)}catch(Z){return P.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=s1.relativePath(Q,X.uri);if(!G)continue;let V=G.split(".");if(V.length===2){let K=V[0],q=V[1];if(K&&aE4(q))Z.push({toolUseID:K,fileChangeID:q})}}return Z}catch(Y){return P.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(!E9(Y))P.error(`Error cleaning up backup files in ${Q}:`,Y)}}getRootURI(){let J=typeof process<"u"?nE4.homedir():null;if(!J)return null;return s1.joinPath(Q0.file(J),".amp","file-changes")}filename(J){return`${J.toolUseID}.${J.fileChangeID}`}backupDirForThread(J){let Q=this.getRootURI();if(!Q)return null;return s1.joinPath(Q,J)}}var VB1;var Wo=l(()=>{r0();v1();z7();qo();VB1={async store(){},async load(){return null},async list(){return[]},async cleanup(){},getRootURI(){return null}}});function sK(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 k2{bits;constructor(J){this.bits=J}static empty(){return new k2(0n)}static fromString(J){let Q=0n;for(let Y=0;Y<J.length;Y++){let Z=J.charCodeAt(Y),X=k2.charToBitIndex(Z);if(X>=0)Q|=1n<<BigInt(X)}return new k2(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=k2.charToBitIndex(G);if(V>=0)Q|=1n<<BigInt(V)}}return new k2(Q)}hasChars(J){return(this.bits&J.bits)===J.bits}union(J){return new k2(this.bits|J.bits)}intersection(J){return new k2(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=k2.bitIndexToChar(Q);if(Y)J.push(Y)}return`CharBag{${J.join("")}}`}toJSON(){return{bits:this.bits.toString()}}static fromJSON(J){return new k2(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 xJ{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=k2.fromPath(this.path)}withUpdates(J){return new xJ({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 xJ({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 BI=()=>{};class Ho{config;queryChars;queryLower;constructor(J,Q={}){this.config={...sE4,...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((z)=>z.length>0);if(J.endsWith("/")&&Q.isDirectory()){let z=Y.slice(0,-1);if(X===z||X.endsWith("/"+z))return y2.EXACT_FILENAME+100;if(X.includes(z))return y2.SUBSTRING_FILENAME+50}if(V===Y||G.toLowerCase()===Y)return y2.EXACT_FILENAME;if(V.startsWith(Y))return y2.PREFIX_FILENAME;if(V.endsWith(Y))return y2.SUFFIX_FILENAME;if(V.includes(Y))return y2.SUBSTRING_FILENAME;let q=this.simpleTokens(Y);if(q.length>1){let z=this.matchTokensToSegments(q,K);if(z)return z}if(q.length===1&&Y.length>6){let z=this.progressiveSegmentMatch(Y,K);if(z)return z}if(K.includes(Y))return y2.SEGMENT_EXACT;if(K.some((z)=>z.includes(Y)))return y2.SEGMENT_SUBSTRING;if(K.join("").includes(Y))return y2.SEGMENT_SUBSTRING;if(X.replace(/[\s-_]/g,"").includes(Y))return y2.PATH_SUBSTRING;return 0}calculateFuzzyScore(J,Q){let Y=J.toLowerCase(),Z=Q.path.toLowerCase();if(this.fuzzyIn(Y,Z))return y2.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?y2.SEGMENT_ORDERED_EXACT:y2.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 y2.SEGMENT_ORDERED_EXACT;case"partial":return y2.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=k2.fromString(Z);if(!Q.charBag.hasChars(X))return!1}return!0}else{let Y=k2.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 NI(J,Q,Y){return new Ho(J,Y).match(Q)}var sE4,y2;var ek=l(()=>{sE4={minScore:400,caseSensitive:!1,penalizeLengthDifference:!0,maxResults:50,smartCase:!0},y2={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 o5(J,Q={},Y){let Z=`/api/internal/github-proxy/${J}`,{body:X,headers:G={},method:V="GET",...K}=Q,q=await mR0(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 bG=l(()=>{N3()});async function pT0(J,Q,Y,Z,X){let G=sK(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 o5(W,{signal:Z},X);if(!H.ok||!H.data)throw Error(`Failed to fetch files: ${H.status} ${H.statusText||"Unknown error"}`);let F=H.data.tree.filter((N)=>N.type==="blob").map((N)=>N.path),U=uT0.default(V),D=F.filter((N)=>U(N));return{files:K?D.slice(q,q+K):D.slice(q),truncated:H.data.truncated}}var uT0;var dT0=l(()=>{bG();uT0=H0(vC(),1)});function cT0(J,Q,Y){let Z=new Map,X=async()=>{try{let K;if(Y)K=await J.get(Y);else K=J.getRecentlyActiveThread();if(K){let q=K.id,W=K.env?.initial.trees||[];if(P.info("Found thread:",q,"trees:",W.length),W.length>0)return P.info("Using trees from thread:",q),{trees:W,threadId:q}}else P.info("No thread found");return null}catch(K){return P.error("Error getting thread:",K),null}},G=async(K)=>{if(!K.repository||!K.repository.url||!K.repository.sha)return[];let q=K.repository,W=q.sha,H=Date.now(),z=`${q.url}:${W}`,F=Z.get(z);if(F&&H-F.timestamp<300000)return F.entries;try{let U=await pT0(q.url,W,{filePattern:"**/*",limit:1e4},void 0,Q),D=U.files.map((N)=>{let w={mtime:Date.now(),size:0,inode:0,isSymlink:!1},M=Q0.file(`/${N}`);return new xJ({id:`github:${q.url}:${W}:${N}`,kind:"file",path:N,uri:M,metadata:w})}),B={entries:D,timestamp:H,repoUrl:q.url,sha:W};if(Z.set(z,B),U.truncated)P.warn("GitHub repository file listing was truncated",{repo:q.url,indexedFiles:D.length});return D}catch(U){return P.error("Failed to fetch files from GitHub API",U),[]}},V=(K)=>{return K.map((q)=>{let W=q.path,H=`@${pA(W)}`,z=W.split("/"),F=z[z.length-1]||W,U=z.length>1?z.slice(0,-1).join("/"):"";return{uri:h0(q.uri),label:F,detail:U,insertText:H,filterText:W.toLowerCase(),kind:q.isDirectory()?"folder":"file"}})};return{search(K){return n0(async()=>{let q=await X();if(!q)return[];let{trees:W,threadId:H}=q,z=W.find((B)=>B.repository?.url!=null&&B.repository?.sha!=null);if(!z)return[];P.info("Found GitHub repository",{threadId:H,uri:z.uri,repoUrl:z.repository.url,sha:z.repository.sha});let F=await G(z);if(F.length===0)return[];let U;if(!K)P.info("Empty query, returning first 10 files"),U=F.slice(0,10);else try{U=NI(K,F,{maxResults:50,minScore:400}).map((N)=>N.entry)}catch(B){return P.error("Fuzzy search failed",B),[]}return V(U).slice(0,uA)})},dispose(){Z.clear()}}}var lT0=l(()=>{r0();K0();v1();BI();ek();Jk();dT0()});function Jy(J){if(!J.startsWith("refs/heads/"))return null;return J.slice(11)}function Fo(J){let Q=mO(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(CK(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(CK(J,Z.id)?.run.status==="done")return!0}}}}return!1}var KB1=l(()=>{n6()});function tE4(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=sK(Q.repository.url,{provider:"github"});if(!Y||Y.provider!=="github")return null;let Z=Q.repository.headRef?Jy(Q.repository.headRef):null;return{repo:Y.name,branch:Z,provider:"github"}}async function eE4({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 o5(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:h0(Q0.parse(q.html_url)),number:q.number.toString(),merged:W}}return null}catch(X){return P.debug("Failed to check GitHub pull request status:",X),null}}function iT0(J,Q,Y,Z){let X=J.observe(Q).pipe(q0((G)=>[{id:G.id,env:G.env},G.messages.length>=2&&Fo(G)]),q6());return v4(X,Z.pipe(H4(void 0),k9((G)=>{return P.error("pullRequestChanges subject error, continuing with undefined",{error:G,threadID:Q}),T1.of(void 0)}))).pipe(WQ(([[G,V]])=>{if(!G||!V)return T1.of([]);let K=tE4(G);if(!K)return T1.of([]);let W=G.env?.initial?.trees?.find((H)=>H.repository?.url)?.repository?.pullRequestURL;return n0(async(H)=>{if(W&&!K.branch){let F=W.split("/").pop()||"";try{let U=`repos/${K.repo}/pulls/${F}`,D=await o5(U,{signal:H,cache:"no-cache"},Y);if(D.ok&&D.data){let B=D.data;return[{type:B.state==="closed"&&B.merged_at!==null?"view-merged-pull-request":"view-pull-request",url:h0(Q0.parse(B.html_url)),number:B.number.toString()}]}}catch(U){P.debug("Failed to fetch specific PR:",U)}}let z=await eE4(K,Y,H);if(z)return[{type:z.merged?"view-merged-pull-request":"view-pull-request",url:z.url,number:z.number}];return[{type:"create-pull-request"}]})}),$4({shouldCountRefs:!0}))}var nT0=l(()=>{r0();K0();v1();KB1();bG()});async function Qy(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)??JR4;return QR4(J,{...Q,auth:{instanceURL:X,accessToken:Z}})}async function QR4(J,{auth:Q,fetcher:Y=fetch,...Z}){let X=`${Q.instanceURL.replace(/\/+$/,"")}/api/v4`,G=J.startsWith("http")?J:`${X}${J}`,{body:V,headers:K={}}=Z,q={"Content-Type":"application/json",Authorization:`Bearer ${Q.accessToken}`,...K};try{let W=await Y(G,{...Z,body:V?JSON.stringify(V):void 0,headers:q}),H,z;if(Z.method!=="HEAD"&&W.status!==204)try{z=await W.text(),H=JSON.parse(z)}catch(F){P.info("GitLab API response not JSON:",{url:G,status:W.status,responseText:z?.substring(0,200)})}return P.debug("GitLab API response:",{url:G,ok:W.ok,status:W.status,statusText:W.statusText,hasData:!!H,dataKeys:H&&typeof H==="object"?Object.keys(H):void 0,responseTextLength:z?.length}),{data:H,ok:W.ok,status:W.status,statusText:W.statusText}}catch(W){if(W instanceof Error&&W.name==="SSRFBlockedError")return P.warn("SSRF blocked during GitLab API request",{message:W.message}),{ok:!1,status:0,statusText:"Request blocked"};let H=W instanceof Error?W.message:String(W);return P.error(`GitLab API request error (${G}):`,W),{ok:!1,status:0,statusText:H}}}var JR4="https://gitlab.com";var qB1=l(()=>{v1()});function aT0(J){let Q=J.replace(/\.git$/,"");try{return new URL(Q).pathname.replace(/^\//,"")}catch{return Q.match(/https?:\/\/[^/]+\/(.+)/)?.[1]??Q}}function YR4(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 ZR4(J,Q,Y,Z){let{filePattern:X,limit:G=100,offset:V=0}=Y,K=YR4(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 z=await Qy(H,{config:Z});if(!z.ok||!z.data)return null;let F=new Set(z.data.map((N)=>N.path)),U=Array.from(F),D=WB1.default(X);return{files:U.filter((N)=>D(N)),truncated:z.data.length===G}}catch(z){return null}}async function XR4(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 Qy(q,{config:Z});if(!W.ok||!W.data)throw Error(`Failed to fetch files: ${W.status} ${W.statusText||"Unknown error"}`);let z=W.data.filter((B)=>B.type==="blob").map((B)=>B.path),F=WB1.default(X),U=z.filter((B)=>F(B));return{files:G?U.slice(V,V+G):U.slice(V),truncated:W.data.length===1000}}async function oT0(J,Q,Y,Z){let X=aT0(J);if(!X)throw Error(`Invalid GitLab repository URL: ${J}`);let G=await ZR4(X,Q,Y,Z);if(G)return G;return XR4(X,Q,Y,Z)}var WB1;var rT0=l(()=>{qB1();WB1=H0(vC(),1)});function sT0(J,Q,Y){let Z=new Map,X=async()=>{try{let K;if(Y)K=await J.get(Y);else K=J.getRecentlyActiveThread();if(K){let q=K.id,W=K.env?.initial.trees||[];if(P.info("Found thread:",q,"trees:",W.length),W.length>0)return P.info("Using trees from thread:",q),{trees:W,threadId:q}}else P.info("No thread found");return null}catch(K){return P.error("Error getting thread:",K),null}},G=async(K)=>{if(!K.repository||!K.repository.url||!K.repository.sha)return[];let q=K.repository,W=q.sha,H=Date.now(),z=`${q.url}:${W}`,F=Z.get(z);if(F&&H-F.timestamp<300000)return F.entries;try{let U=await oT0(q.url,W,{filePattern:"**/*",limit:1e4},Q),D=U.files.map((N)=>{let w={mtime:Date.now(),size:0,inode:0,isSymlink:!1},M=Q0.file(`/${N}`);return new xJ({id:`gitlab:${q.url}:${W}:${N}`,kind:"file",path:N,uri:M,metadata:w})}),B={entries:D,timestamp:H,repoUrl:q.url,sha:W};if(Z.set(z,B),U.truncated)P.warn("GitLab repository file listing was truncated",{repo:q.url,indexedFiles:D.length});return D}catch(U){return P.error("Failed to fetch files from GitLab API",U),[]}},V=(K)=>{return K.map((q)=>{let W=q.path,H=`@${pA(W)}`,z=W.split("/"),F=z[z.length-1]||W,U=z.length>1?z.slice(0,-1).join("/"):"";return{uri:h0(q.uri),label:F,detail:U,insertText:H,filterText:W.toLowerCase(),kind:q.isDirectory()?"folder":"file"}})};return{search(K){return n0(async()=>{let q=await X();if(!q)return[];let{trees:W,threadId:H}=q,z=W.find((B)=>B.repository?.url!=null&&B.repository?.sha!=null&&B.fs==="gitlab");if(!z)return[];P.info("Found GitLab repository",{threadId:H,uri:z.uri,repoUrl:z.repository.url,sha:z.repository.sha});let F=await G(z);if(F.length===0)return[];let U;if(!K)P.info("Empty query, returning first 10 files"),U=F.slice(0,10);else try{U=NI(K,F,{maxResults:50,minScore:400}).map((N)=>N.entry)}catch(B){return P.error("Fuzzy search failed",B),[]}return V(U).slice(0,uA)})},dispose(){Z.clear()}}}var tT0=l(()=>{r0();K0();v1();BI();ek();Jk();rT0()});function $R4(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=sK(Q.repository.url,{gitlabInstanceURL:Y});if(!Z||Z.provider!=="gitlab")return null;let X=Q.repository.headRef?Jy(Q.repository.headRef):Q.repository.ref?Jy(Q.repository.ref):null;return{repo:Z.name,branch:X,provider:"gitlab",instanceURL:Z.instanceURL}}async function GR4({repo:J,branch:Q,instanceURL:Y},Z,X){if(!Q||!Y)return P.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`;P.info("GitLab MR check: making API request",{repo:J,branch:Q,instanceURL:Y,apiEndpoint:V,projectPath:G});let K=await Qy(V,{config:Z,signal:X,cache:"no-cache"});if(!K.ok||!K.data)return P.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:h0(Q0.parse(W.web_url)),number:W.iid.toString(),merged:W.state==="merged"}}return null}catch(G){return null}}function eT0(J,Q,Y,Z){P.info("GitLab thread actions: setting up observable for thread",{threadID:Q});let X=J.observe(Q).pipe(q0((G)=>{let V=G.messages.length>=2&&Fo(G);return[{id:G.id,env:G.env},V]}),q6());return v4(X,Z.pipe(H4(void 0),k9((G)=>{return P.error("mergeRequestChanges subject error, continuing with undefined",{error:G,threadID:Q}),T1.of(void 0)}))).pipe(WQ(([[G,V],K])=>{if(!G||!V)return P.info("GitLab thread actions: no thread or no messages, returning empty",{threadID:Q}),T1.of([]);let q=$R4(G);if(!q)return P.info("GitLab thread actions: not a GitLab repository, returning empty",{threadID:Q}),T1.of([]);return n0(async(W)=>{let H=await GR4(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"}]})}),$4({shouldCountRefs:!0}))}var JC0=l(()=>{r0();K0();v1();KB1();qB1()});class HB1{threadService;config;name="github";mentionFilesDataSource;pullRequestChanges=new E6;constructor(J,Q,Y){this.threadService=J;this.config=Q;this.mentionFilesDataSource=cT0(J,Q,Y)}getThreadActions(J){return iT0(this.threadService,J,this.config,this.pullRequestChanges)}canHandle(J){if(!J)return!1;return sK(J,{provider:"github"})?.provider==="github"}dispose(){this.mentionFilesDataSource.dispose()}}class QC0{threadService;config;name="gitlab";mentionFilesDataSource;pullRequestChanges=new E6;constructor(J,Q,Y){this.threadService=J;this.config=Q;this.mentionFilesDataSource=sT0(J,Q,Y)}getThreadActions(J){return eT0(this.threadService,J,this.config,this.pullRequestChanges)}canHandle(J){if(!J)return!1;let Q=new URL(J).origin;return sK(J,{gitlabInstanceURL:Q})?.provider==="gitlab"}dispose(){this.mentionFilesDataSource.dispose()}}function YC0(J,Q,Y,Z){let X=J.find((K)=>K.repository?.url);if(!X?.repository?.url)return new HB1(Q,Y,Z);if(X.repository.url.includes("gitlab.")||X.fs==="gitlab")return new QC0(Q,Y,Z);else return new HB1(Q,Y,Z)}var ZC0=l(()=>{K0();lT0();nT0();tT0();JC0()});function a0(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 a1(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 tK=()=>{};var zB1=function(){let{crypto:J}=globalThis;if(J?.randomUUID)return zB1=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 eK(J){return typeof J==="object"&&J!==null&&(("name"in J)&&J.name==="AbortError"||("message"in J)&&String(J.message).includes("FetchRequestCanceledException"))}var Yy=(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 L6,U7,a3,mB,Zy,Xy,$y,Gy,Vy,Ky,qy,Wy,Hy;var qZ=l(()=>{L6=class L6 extends Error{};U7=class U7 extends L6{constructor(J,Q,Y,Z){super(`${U7.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 mB({message:Y,cause:Yy(Q)});let X=Q;if(J===400)return new Xy(J,X,Y,Z);if(J===401)return new $y(J,X,Y,Z);if(J===403)return new Gy(J,X,Y,Z);if(J===404)return new Vy(J,X,Y,Z);if(J===409)return new Ky(J,X,Y,Z);if(J===422)return new qy(J,X,Y,Z);if(J===429)return new Wy(J,X,Y,Z);if(J>=500)return new Hy(J,X,Y,Z);return new U7(J,X,Y,Z)}};a3=class a3 extends U7{constructor({message:J}={}){super(void 0,void 0,J||"Request was aborted.",void 0)}};mB=class mB extends U7{constructor({message:J,cause:Q}){super(void 0,void 0,J||"Connection error.",void 0);if(Q)this.cause=Q}};Zy=class Zy extends mB{constructor({message:J}={}){super({message:J??"Request timed out."})}};Xy=class Xy extends U7{};$y=class $y extends U7{};Gy=class Gy extends U7{};Vy=class Vy extends U7{};Ky=class Ky extends U7{};qy=class qy extends U7{};Wy=class Wy extends U7{};Hy=class Hy extends U7{}});function Uo(J){if(typeof J!=="object")return{};return J??{}}function $C0(J){if(!J)return!0;for(let Q in J)return!1;return!0}function GC0(J,Q){return Object.prototype.hasOwnProperty.call(J,Q)}var KR4,XC0=(J)=>{return KR4.test(J)},FB1=(J)=>(FB1=Array.isArray,FB1(J)),UB1,VC0=(J,Q)=>{if(typeof Q!=="number"||!Number.isInteger(Q))throw new L6(`${J} must be an integer`);if(Q<0)throw new L6(`${J} must be a positive integer`);return Q},Do=(J)=>{try{return JSON.parse(J)}catch(Q){return}};var uB=l(()=>{qZ();KR4=/^[a-z][a-z0-9+.-]*:/i,UB1=FB1});var KC0=(J)=>new Promise((Q)=>setTimeout(Q,J));var rH="0.71.2";function qR4(){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 HR4(){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 zC0=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},WR4=()=>{let J=qR4();if(J==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":rH,"X-Stainless-OS":WC0(Deno.build.os),"X-Stainless-Arch":qC0(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":rH,"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":rH,"X-Stainless-OS":WC0(globalThis.process.platform??"unknown"),"X-Stainless-Arch":qC0(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Q=HR4();if(Q)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":rH,"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":rH,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},qC0=(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"},WC0=(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"},HC0,FC0=()=>{return HC0??(HC0=WR4())};var DB1=()=>{};function UC0(){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 BB1(...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 Bo(J){let Q=Symbol.asyncIterator in J?J[Symbol.asyncIterator]():J[Symbol.iterator]();return BB1({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 zy(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 DC0(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 BC0=({headers:J,body:Q})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Q)}};function MC0(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 Fy(J){let Q;return(NC0??(Q=new globalThis.TextEncoder,NC0=Q.encode.bind(Q)))(J)}function NB1(J){let Q;return(wC0??(Q=new globalThis.TextDecoder,wC0=Q.decode.bind(Q)))(J)}var NC0,wC0;class sH{constructor(){PQ.set(this,void 0),TQ.set(this,void 0),a0(this,PQ,new Uint8Array,"f"),a0(this,TQ,null,"f")}decode(J){if(J==null)return[];let Q=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?Fy(J):J;a0(this,PQ,MC0([a1(this,PQ,"f"),Q]),"f");let Y=[],Z;while((Z=UR4(a1(this,PQ,"f"),a1(this,TQ,"f")))!=null){if(Z.carriage&&a1(this,TQ,"f")==null){a0(this,TQ,Z.index,"f");continue}if(a1(this,TQ,"f")!=null&&(Z.index!==a1(this,TQ,"f")+1||Z.carriage)){Y.push(NB1(a1(this,PQ,"f").subarray(0,a1(this,TQ,"f")-1))),a0(this,PQ,a1(this,PQ,"f").subarray(a1(this,TQ,"f")),"f"),a0(this,TQ,null,"f");continue}let X=a1(this,TQ,"f")!==null?Z.preceding-1:Z.preceding,G=NB1(a1(this,PQ,"f").subarray(0,X));Y.push(G),a0(this,PQ,a1(this,PQ,"f").subarray(Z.index),"f"),a0(this,TQ,null,"f")}return Y}flush(){if(!a1(this,PQ,"f").length)return[];return this.decode(`
|
|
734
734
|
`)}}function UR4(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 LC0(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 PQ,TQ;var wB1=l(()=>{tK();PQ=new WeakMap,TQ=new WeakMap;sH.NEWLINE_CHARS=new Set([`
|
|
735
735
|
`,"\r"]);sH.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Uy(){}function No(J,Q,Y){if(!Q||wo[J]>wo[Y])return Uy;else return Q[J].bind(Q)}function m7(J){let Q=J.logger,Y=J.logLevel??"off";if(!Q)return DR4;let Z=OC0.get(Q);if(Z&&Z[0]===Y)return Z[1];let X={error:No("error",Q,Y),warn:No("warn",Q,Y),info:No("info",Q,Y),debug:No("debug",Q,Y)};return OC0.set(Q,[Y,X]),X}var wo,MB1=(J,Q,Y)=>{if(!J)return;if(GC0(wo,J))return J;m7(Y).warn(`${Q} was set to ${JSON.stringify(J)}, expected one of ${JSON.stringify(Object.keys(wo))}`);return},DR4,OC0,Jq=(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 Mo=l(()=>{uB();wo={off:0,error:200,warn:300,info:400,debug:500};DR4={error:Uy,warn:Uy,info:Uy,debug:Uy},OC0=new WeakMap});async function*BR4(J,Q){if(!J.body){if(Q.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new L6("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 L6("Attempted to iterate over a response with no body")}let Y=new AC0,Z=new sH,X=zy(J.body);for await(let G of NR4(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*NR4(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"?Fy(Y):Y,X=new Uint8Array(Q.length+Z.length);X.set(Q),X.set(Z,Q.length),Q=X;let G;while((G=LC0(Q))!==-1)yield Q.slice(0,G),Q=Q.slice(G)}if(Q.length>0)yield Q}class AC0{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(`
|
|
736
736
|
`),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]=wR4(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 wR4(J,Q){let Y=J.indexOf(Q);if(Y!==-1)return[J.substring(0,Y),Q,J.substring(Y+Q.length)];return[J,"",""]}var Dy,CQ;var LB1=l(()=>{tK();qZ();wB1();uB();Mo();qZ();CQ=class CQ{constructor(J,Q,Y){this.iterator=J,Dy.set(this,void 0),this.controller=Q,a0(this,Dy,Y,"f")}static fromSSEResponse(J,Q,Y){let Z=!1,X=Y?m7(Y):console;async function*G(){if(Z)throw new L6("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let V=!1;try{for await(let K of BR4(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 U7(void 0,Do(K.data)??K.data,void 0,J.headers)}V=!0}catch(K){if(eK(K))return;throw K}finally{if(!V)Q.abort()}}return new CQ(G,Q,Y)}static fromReadableStream(J,Q,Y){let Z=!1;async function*X(){let V=new sH,K=zy(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 L6("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(eK(K))return;throw K}finally{if(!V)Q.abort()}}return new CQ(G,Q,Y)}[(Dy=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 CQ(()=>Z(J),this.controller,a1(this,Dy,"f")),new CQ(()=>Z(Q),this.controller,a1(this,Dy,"f"))]}toReadableStream(){let J=this,Q;return BB1({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=Fy(JSON.stringify(Z)+`
|
|
@@ -4280,11 +4280,11 @@ Actual: ${X}`)}async function DZ8(J,Q,Y){let Z=RV(Q,"package.tgz");P.debug("Do
|
|
|
4280
4280
|
${U}`;if(X==="pnpm"&&U.includes("Unable to find the global bin directory"))D+=`
|
|
4281
4281
|
|
|
4282
4282
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4283
|
-
npm install -g @sourcegraph/amp`;K(Error(D))}},error:(F)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${F.message}`))},complete:()=>{if(!H)H=!0,V()}})})}v1();v1();async function V61(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=LZ8(J,q),H=W<0,z,F;if(K.time){let U=K.time[J],D=K.time[q],B=Date.now();if(U)z=Math.floor((B-new Date(U).getTime())/3600000);if(D)F=Math.floor((B-new Date(D).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:F}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:F,source:"npm"}}catch(X){return P.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function LZ8(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}K0();function K61(J,Q){let Y=new E6,Z=Y.pipe($4({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new $G().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 $R(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=nw(),W=await V61(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 F=W.currentVersionAge-W.latestVersionAge,U=0.5;if(Math.abs(F)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:F}),!0}return!1},z=await G61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Y.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(z==="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 Hh(W.latestVersion,z);let F=await CF(W.latestVersion),U={from:W.currentVersion,to:W.latestVersion,...F};if(F.status==="same")X.info("success",U),Y.next("updated");else X.warn("success with warning",U),Y.next("updated-with-warning")}catch(F){Y.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await $R(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:Z}}fn();import{stderr as jV}from"node:process";function C56(J){let Q=new U$().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 FC1(Z.force||!1,Z.verbose||!1,"0.0.
|
|
4283
|
+
npm install -g @sourcegraph/amp`;K(Error(D))}},error:(F)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${F.message}`))},complete:()=>{if(!H)H=!0,V()}})})}v1();v1();async function V61(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=LZ8(J,q),H=W<0,z,F;if(K.time){let U=K.time[J],D=K.time[q],B=Date.now();if(U)z=Math.floor((B-new Date(U).getTime())/3600000);if(D)F=Math.floor((B-new Date(D).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:F}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:F,source:"npm"}}catch(X){return P.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function LZ8(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}K0();function K61(J,Q){let Y=new E6,Z=Y.pipe($4({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new $G().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 $R(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=nw(),W=await V61(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 F=W.currentVersionAge-W.latestVersionAge,U=0.5;if(Math.abs(F)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:F}),!0}return!1},z=await G61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Y.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(z==="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 Hh(W.latestVersion,z);let F=await CF(W.latestVersion),U={from:W.currentVersion,to:W.latestVersion,...F};if(F.status==="same")X.info("success",U),Y.next("updated");else X.warn("success with warning",U),Y.next("updated-with-warning")}catch(F){Y.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await $R(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:Z}}fn();import{stderr as jV}from"node:process";function C56(J){let Q=new U$().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 FC1(Z.force||!1,Z.verbose||!1,"0.0.1768218876-g7c0d4d"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new U$("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 OZ8(Z.targetVersion)});J.addCommand(Y)}async function OZ8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")jV.write(Z0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4284
4284
|
|
|
4285
4285
|
`));try{if(!J){jV.write(Z0.blue(`Checking for updates...
|
|
4286
|
-
`));let Y=nw(),{hasUpdate:Z,latestVersion:X}=await V61("0.0.
|
|
4287
|
-
`));let V=await CF("0.0.
|
|
4286
|
+
`));let Y=nw(),{hasUpdate:Z,latestVersion:X}=await V61("0.0.1768218876-g7c0d4d",Y);if(!Z){jV.write(Z0.green(`✓ Amp CLI is already up to date: ${"0.0.1768218876-g7c0d4d"} (${"released"} ${"2026-01-12T11:59:31.016Z"}${`, ${dA(new Date("2026-01-12T11:59:31.016Z"))} ago`})
|
|
4287
|
+
`));let V=await CF("0.0.1768218876-g7c0d4d");if(V.warning)jV.write(`
|
|
4288
4288
|
`+Z0.yellow(V.warning)+`
|
|
4289
4289
|
`);process.exit(0)}if(!X)jV.write(Z0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}jV.write(Z0.blue(`Updating to version ${J}...
|
|
4290
4290
|
`)),await Hh(J,void 0,(Y)=>{jV.write(Z0.dim(`Running: ${Y}
|
|
@@ -4337,7 +4337,7 @@ ${cq1(J)}
|
|
|
4337
4337
|
|
|
4338
4338
|
${Y}`}async function IV8(J,Q){let Y=Q0.parse(J).fsPath;if(!Q?.forceExternal&&Q?.onShowImagePreview&&W26(Y)){Q.onShowImagePreview(Y);return}if(await f9.openURIInIDE(J).catch(()=>{return}))return;if(await s56(Y).catch(()=>!1)){await WH(J);return}try{await pZ(Y)}catch{await WH(J)}}async function e2(J,Q,Y){Q=typeof Q==="string"?Q:Q.toString();try{if(Q.startsWith("file://")||Q.startsWith("/")){let X=Q.startsWith("file://")?Q:Q0.file(Q).toString();if(!await z26(X))throw Error(`File does not exist: ${Q}`);await IV8(X,Y)}else await WH(Q);return!0}catch(Z){P.error("Failed to open link",{uri:Q,error:Z});let X=await AV8(Q,Z);return eq.error(J,X),!1}}class w9 extends S0{uri;text;style;maxLines;overflow;constructor({uri:J,text:Q,style:Y,maxLines:Z,overflow:X,key:G}){super({key:G});this.uri=J,this.text=Q,this.style=Y,this.maxLines=Z,this.overflow=X}build(J){return w9.createWidget(J,this.uri,this.text,this.style,this.maxLines,this.overflow)}static createWidget(J,Q,Y,Z,X,G){let V=new e({text:w9.createSpan(Q,Y,Z),selectable:!0,maxLines:X,overflow:G}),K=Yj.of(J);return new H6({onClick:(W)=>{let H=W.modifiers.ctrl||W.modifiers.meta;e2(J,Q,{forceExternal:H,onShowImagePreview:K})},cursor:"pointer",child:V})}static createSpan(J,Q,Y){let Z=J7(),X=Z?J:Q,G=Z?new f({color:Y?.color,dim:!0}):Y||new f({underline:!0}),V=Z?void 0:O86(J);return new S(X,G,void 0,V)}}function C_1(J,Q,Y){return J+(Q-J)*Y}function g61(J,Q,Y){let Z=Math.max(0,Math.min(1,Y));return{r:Math.round(C_1(J.r,Q.r,Z)),g:Math.round(C_1(J.g,Q.g,Z)),b:Math.round(C_1(J.b,Q.b,Z))}}RX();var P26=H0(R26(),1);var j26=20;function b_1(J){let Q=EX(J??"smart")??EX("smart");if(Q?.uiHints?.primaryColor&&Q.uiHints.secondaryColor)return{primary:Q.uiHints.primaryColor,secondary:Q.uiHints.secondaryColor};return{primary:OH0,secondary:AH0}}function f_1(J,Q,Y){let Z=Math.max(0,Math.min(1,J)),{primary:X,secondary:G}=Y??b_1(Q),V=g61(X,G,Z);return o.rgb(V.r,V.g,V.b)}class hF{_noise2D;_seed;constructor(J){this._seed=J??Date.now(),this._noise2D=P26.makeNoise2D(this._seed)}get seed(){return this._seed}sample(J,Q,Y,Z=1){return(this._noise2D(J/j26,Q/j26+Y*Z)+1)*0.5}sampleEdge(J,Q,Y,Z,X=1){let G=J-1,V=Q/2+Y*(Q/2);return this.sample(G,V,Z,X)}getColor(J,Q,Y){return f_1(J,Q,Y)}}var T26=" .:-=+*#%@",pV8=" ",n61=0.5,gF=1,h_1=30,uh=3;class g_1 extends p1{width;height;minWidth;minHeight;maxWidth;maxHeight;agentMode;primaryColor;secondaryColor;t;onFrame;fps;seed;glow;shockwaves;onShockwave;constructor({key:J,width:Q=40,height:Y=40,minWidth:Z,minHeight:X,maxWidth:G,maxHeight:V,agentMode:K,primaryColor:q,secondaryColor:W,t:H,onFrame:z,fps:F=60,seed:U,glow:D,shockwaves:B,onShockwave:N}){super(J?{key:J}:{});this.width=Q,this.height=Y,this.minWidth=Z??8,this.minHeight=X??8,this.maxWidth=G??40,this.maxHeight=V??40,this.agentMode=K,this.primaryColor=q,this.secondaryColor=W,this.t=H,this.onFrame=z,this.fps=F,this.seed=U,this.glow=D,this.shockwaves=B,this.onShockwave=N}createState(){return new C26}}class C26 extends u1{_t=0;_timer=null;_internalShockwaves=[];_glow;initState(){if(super.initState(),this._glow=this.widget.glow??new hF(this.widget.seed),this.widget.t!==void 0||this.widget.fps===0){this._t=this.widget.t??0;return}if(this.widget.fps==0)return;this._timer=setInterval(()=>{if(this._t+=1/this.widget.fps,this.widget.onFrame){let J=this._t;setImmediate(()=>this.widget.onFrame?.(J))}this._internalShockwaves=this._internalShockwaves.filter((J)=>this._t-J.startTime<gF),this.setState(()=>{})},1000/this.widget.fps)}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.glow!==J.glow)this._glow=this.widget.glow??new hF(this.widget.seed);if(this.widget.t!==void 0&&this.widget.t!==J.t)this._t=this.widget.t,this.setState(()=>{})}dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;super.dispose()}handleClick=(J)=>{let Q={x:J.localPosition.x,y:J.localPosition.y,startTime:this._t};if(this.widget.onShockwave)this.widget.onShockwave(Q);else this._internalShockwaves.push(Q);this.setState(()=>{})};build(J){let Q=new _26({width:this.widget.width,height:this.widget.height,minWidth:this.widget.minWidth,minHeight:this.widget.minHeight,maxWidth:this.widget.maxWidth,maxHeight:this.widget.maxHeight,time:this._t,agentMode:this.widget.agentMode,primaryColor:this.widget.primaryColor,secondaryColor:this.widget.secondaryColor,glow:this._glow,shockwaves:this.widget.shockwaves??this._internalShockwaves});return new H6({onClick:this.handleClick,child:Q})}}class _26 extends E${props;constructor(J,Q){super(Q?{key:Q}:{});this.props=J}createElement(){return new IV(this)}createRenderObject(){return new a61(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.agentMode,this.props.primaryColor,this.props.secondaryColor,this.props.glow,this.props.shockwaves)}updateRenderObject(J){J.update(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.agentMode,this.props.primaryColor,this.props.secondaryColor,this.props.glow,this.props.shockwaves)}}class a61 extends W6{_width;_height;_minWidth;_minHeight;_maxWidth;_maxHeight;_time;_agentMode;_primaryColor;_secondaryColor;_glow;_shockwaves;constructor(J,Q,Y,Z,X,G,V,K,q,W,H,z=[]){super();this._width=J;this._height=Q;this._minWidth=Y;this._minHeight=Z;this._maxWidth=X;this._maxHeight=G;this._time=V;this._agentMode=K;this._primaryColor=q;this._secondaryColor=W;this._glow=H;this._shockwaves=z}getMinIntrinsicWidth(J){return this._minWidth}getMaxIntrinsicWidth(J){return this._maxWidth}getMinIntrinsicHeight(J){return this._minHeight}getMaxIntrinsicHeight(J){return this._maxHeight}update(J,Q,Y,Z,X,G,V,K,q,W,H,z=[]){let F=!1;if(J!==this._width||Q!==this._height||Y!==this._minWidth||Z!==this._minHeight||X!==this._maxWidth||G!==this._maxHeight)this._width=J,this._height=Q,this._minWidth=Y,this._minHeight=Z,this._maxWidth=X,this._maxHeight=G,F=!0;if(this._time=V,this._agentMode=K,this._primaryColor=q,this._secondaryColor=W,this._glow=H,this._shockwaves=z,F)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;U6(!!J,"performLayout called without constraints");let Q=J.constrain(this._width,this._height);this.setSize(Q.width,Q.height),super.performLayout()}paint(J,Q=0,Y=0){let Z=Q+this.offset.x,X=Y+this.offset.y,G=Math.floor(this.size.width),V=Math.floor(this.size.height),K=G/2,q=V/2,W=Math.max(1,G/2-1),H=Math.max(1,V/(2*n61)-1),z=Math.min(W,H);for(let F=0;F<V;F++){let U=X+F,D=!0;if(F>0){D=!0;for(let N=0;N<G;N++){let w=N-K,M=(F-1-q)/n61;if(Math.sqrt(w*w+M*M)/z<1){D=!1;break}}}let B=!0;for(let N=0;N<G;N++){let w=N-K,M=(F-q)/n61,L=Math.sqrt(w*w+M*M),O=L/z;if(O>=1)continue;let A=1-O*O,I=this._agentMode==="rush"?2.5:1,C=this._glow.sample(N,F,this._time,I)*A;for(let m of this._shockwaves){let v=this._time-m.startTime;if(v<0||v>gF)continue;let x=N-m.x,g=(F-m.y)/n61,d=Math.sqrt(x*x+g*g),h=v*h_1,i=Math.abs(d-h);if(i<uh){let u=L/z;if(u<0.95){let V1=1-v/gF,O1=(1-i/uh)*V1,n=1-u**3;C=Math.min(1,C+O1*0.8*n)}}}let y=T26[Math.floor(C*T26.length)]||pV8,k=this._primaryColor&&this._secondaryColor?{primary:this._primaryColor,secondary:this._secondaryColor}:void 0,b=f_1(C,this._agentMode,k),c=Z+N;if(c<0||c>=J.getSize().width)continue;J.setCell(c,U,{char:y,width:1,style:{fg:b}}),B=!1}}}}class o61 extends E${text;baseColor;glow;time;agentMode;orbWidth;orbHeight;glowIntensity;shockwaves;constructor({key:J,text:Q,baseColor:Y,glow:Z,time:X,agentMode:G,orbWidth:V=40,orbHeight:K=40,glowIntensity:q=0.4,shockwaves:W=[]}){super(J?{key:J}:{});this.text=Q,this.baseColor=Y,this.glow=Z,this.time=X,this.agentMode=G,this.orbWidth=V,this.orbHeight=K,this.glowIntensity=q,this.shockwaves=W}createElement(){return new IV(this)}createRenderObject(){return new S26(this.text,this.baseColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}updateRenderObject(J){J.update(this.text,this.baseColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}}var dV8=0.5;class S26 extends W6{_text;_baseColor;_glow;_time;_agentMode;_orbWidth;_orbHeight;_glowIntensity;_shockwaves;constructor(J,Q,Y,Z,X,G,V,K,q){super();this._text=J;this._baseColor=Q;this._glow=Y;this._time=Z;this._agentMode=X;this._orbWidth=G;this._orbHeight=V;this._glowIntensity=K;this._shockwaves=q}update(J,Q,Y,Z,X,G,V,K,q){let W=J!==this._text;if(this._text=J,this._baseColor=Q,this._glow=Y,this._time=Z,this._agentMode=X,this._orbWidth=G,this._orbHeight=V,this._glowIntensity=K,this._shockwaves=q,W)this.markNeedsLayout();this.markNeedsPaint()}getMinIntrinsicWidth(J){return j3(this._text,!1)}getMaxIntrinsicWidth(J){return j3(this._text,!1)}getMinIntrinsicHeight(J){return 1}getMaxIntrinsicHeight(J){return 1}performLayout(){let J=this._lastConstraints;U6(!!J,"performLayout called without constraints");let Q=j3(this._text,!1),Y=J.constrain(Q,1);this.setSize(Y.width,Y.height),super.performLayout()}paint(J,Q=0,Y=0){let Z=Q+this.offset.x,X=Y+this.offset.y,G=n4(this._text),V=this._agentMode==="rush"?2.5:1,{primary:K,secondary:q}=b_1(this._agentMode),W=Z;for(let H=0;H<G.length;H++){let z=G[H],F=B9(z,!1),D=(1-H/Math.max(G.length-1,1)*0.7)**1.2,B=this._glow.sample(this._orbWidth-2+H*0.5,this._orbHeight/2,this._time,V),N=0;for(let O of this._shockwaves){let A=this._time-O.startTime;if(A<0||A>gF)continue;let I=this._orbWidth*0.7+H,j=this._orbHeight/2,C=I-O.x,y=(j-O.y)/dV8,k=Math.sqrt(C*C+y*y),b=A*h_1,c=Math.abs(k-b);if(c<uh){let m=1-A/gF,v=(1-c/uh)*m;N=Math.max(N,v*0.6)}}let w=B**0.7,M=Math.min(1,w*D+N),L=this.blendWithGlow(this._baseColor,M,K,q);J.setCell(W,X,{char:z,width:F,style:{fg:L}}),W+=F}}blendWithGlow(J,Q,Y,Z){let X=g61(Y,Z,Q),G=Q*this._glowIntensity;if(J.type==="rgb"){let V=J.value,K=Math.round(V.r*(1-G)+X.r*G),q=Math.round(V.g*(1-G)+X.g*G),W=Math.round(V.b*(1-G)+X.b*G);return o.rgb(K,q,W)}if(G>0.15)return o.rgb(X.r,X.g,X.b);return J}}var k26=["ctrl+x","y","z"],y26=1.5,r61="!@#$%^&*()_+-=[]{}|;:,.<>?/~`0123456789";function cV8(J,Q,Y){let Z=Math.max(J.length,Q.length),X=[];for(let G=0;G<Z;G++){let V=J[G]??" ",K=Q[G]??" ",q=V===" "||V===`
|
|
4339
4339
|
`||V==="\t",W=K===" "||K===`
|
|
4340
|
-
`||K==="\t";if(q&&W){X.push(Y<0.5?V:K);continue}let H=G/Z*0.4,z=Math.max(0,Math.min(1,(Y-H)/(1-H)));if(z===0)X.push(V);else if(z>=1)X.push(K);else if(q)X.push(z<0.7?" ":K);else if(W)X.push(z<0.3?V:" ");else if(z<0.5){let F=z*2;if(Math.random()<F)X.push(r61[Math.floor(Math.random()*r61.length)]);else X.push(V)}else{let F=(z-0.5)*2;if(Math.random()<F)X.push(K);else X.push(r61[Math.floor(Math.random()*r61.length)])}}return X.join("").trimEnd()}var x26=[{type:"command",text:'amp -x "What package manager do we use here?"'},{type:"command",text:'amp -x "Run the linter and fix the errors"'},{type:"hint",text:"Use Ctrl+O to open the command palette"},{type:"hint",text:"Use Ctrl+G to edit the prompt in your $EDITOR"},{type:"hint",text:"Use the `prompt: queue` command to enqueue messages without interrupting the agent"},{type:"hint",text:"Use the `thread: browser` command to open your thread in the browser"},{type:"hint",text:"Use the `thread: new` command to start a fresh thread"},{type:"hint",text:"Use the `thread: handoff` command to draft a new thread with relevant context"},{type:"hint",text:"Use the `thread: visibility` command to change thread visibility settings"},{type:"hint",text:"Use the `settings: open in editor` command to configure Amp"},{type:"hint",text:"Use the `agents-md: generate` command to create an AGENTS.md"},{type:"hint",text:"Use Tab/Shift+Tab to navigate to previous messages to edit or restore to a previous state"},{type:"prompt",text:'"Use the oracle to review the code we just wrote."'},{type:"prompt",text:'"Use subagents to update these components to use the new attribute we added."'},{type:"prompt",text:'"Do not write any code yet. Plan first."'},{type:"prompt",text:'"Think hard before you start implementing."'},{type:"prompt",text:`"Use 'psql' to change all blog_posts to have comments"`},{type:"prompt",text:'"Run <build command> and fix all the errors"'},{type:"quote",text:`"We are at the 'introduction of photography' period of programming. Painting by hand just doesn't have the same appeal anymore" - Orta Therox`},{type:"quote",text:'"Programming in the normal way feels like walking. You type out each expression, stepping incrementally toward your goal. When programming with AI, each move is bigger than a step. You lift off the ground." - Mary Rose Cook'},{type:"quote",text:'"Tomorrow all this may change, but right now after daily experience writing code with LLMs I strongly believe the maximum quality of work is reached using the human+LLM equation." - antirez'},{type:"quote",text:`"The magic that's coming now is the most powerful yet. And that means that we're beginning a profound period of exploration and creativity, trying to understand how to make that magic work and to derive new advantages from its power." - Tim O'Reilly`},{type:"quote",text:`"They're applying years of hard-won engineering wisdom to shape and constrain the AI's output. The AI is accelerating their implementation, but their expertise is what keeps the code maintainable." - Addy Osmani`}],m_1=40,u_1=40;class Uj extends p1{agentMode;mysteriousMessage;mysterySequenceProgress;onShowMysteryModal;constructor(J={}){super(J.key?{key:J.key}:{});this.agentMode=J.agentMode,this.mysteriousMessage=J.mysteriousMessage,this.mysterySequenceProgress=J.mysterySequenceProgress,this.onShowMysteryModal=J.onShowMysteryModal}createState(){return new v26}}class v26 extends u1{_glow;_t=0;_timer=null;_fps=0;_shockwaves=[];_suggestion;_morphStartTime=null;_previousHasMystery=!1;initState(){super.initState(),this._glow=new hF,this._suggestion=x26[Math.floor(Math.random()*x26.length)],this._previousHasMystery=!!this.widget.mysteriousMessage}getMorphProgress(J){if(this._morphStartTime===null)return null;let Q=J-this._morphStartTime;if(Q>=y26)return null;return Q/y26}dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;super.dispose()}startAnimation(J){if(this._timer)clearInterval(this._timer),this._timer=null;if(this._fps=J,J>0)this._timer=setInterval(()=>{this._t+=1/J,this._shockwaves=this._shockwaves.filter((Q)=>this._t-Q.startTime<gF),this.setState(()=>{})},1000/J)}build(J){let Y=x0.of(J).colorScheme,X=W0.of(J).app,V=t0.of(J).capabilities.animationSupport,K=V==="fast"?60:V==="slow"?15:0;if(K!==this._fps)this.startAnimation(K);let q=!!this.widget.mysteriousMessage,W=this._suggestion,H=V==="disabled"?3:this._t;if(q&&!this._previousHasMystery&&V!=="disabled")this._morphStartTime=H;this._previousHasMystery=q;let z=this.getMorphProgress(H),F=z!==null,U=W.type==="quote"||W.type==="news"?new f({color:Y.foreground,dim:!0}):W.type==="hint"?new f({color:Y.secondary}):new f({color:W.type==="prompt"||W.type==="note"?Y.primary:Y.warning}),D=new f({color:X.keybind}),B=new f({color:X.command}),N=new f({color:Y.foreground,dim:!0}),w=[];if(W.type==="hint"){let k=W.text.split(/(`[^`]+`)/g);for(let b of k)if(b.startsWith("`")&&b.endsWith("`")){let c=b.slice(1,-1);w.push(new S(c,B))}else w.push(new S(b,U))}else w.push(new S(W.text,U));let M=V==="fast",L=(k)=>{this._shockwaves.push(k),this.setState(()=>{})},O=M?new o61({text:"Welcome to Amp",baseColor:Y.foreground,glow:this._glow,time:H,agentMode:this.widget.agentMode,orbWidth:m_1,orbHeight:u_1,glowIntensity:1,shockwaves:this._shockwaves}):new e({text:new S("Welcome to Amp",new f({color:Y.foreground}))}),A=null;if(q){let b=0.3+(Math.sin(H*0.5)*0.5+0.5)*0.4,c=new f({color:Y.primary,italic:!0,dim:b<0.5}),v=this.widget.mysterySequenceProgress?.matched.length??0,x=v>0?"Keep going...":"A message awaits...",g=[];for(let d=0;d<k26.length;d++){let h=k26[d],i=h==="ctrl+x"?"Ctrl-X":h.toUpperCase(),V1=d<v?new f({color:Y.primary,bold:!0}):D;if(d>0)g.push(new S(", ",N));g.push(new S(i,V1))}A=new k1({crossAxisAlignment:"start",mainAxisSize:"min",children:[M?new o61({text:x,baseColor:Y.primary,glow:this._glow,time:H,agentMode:this.widget.agentMode,orbWidth:m_1,orbHeight:u_1,glowIntensity:0.6,shockwaves:this._shockwaves}):new e({text:new S(x,c)}),new e({text:new S("",void 0,[...g,new S(" to unlock",N)])})]})}let I,j=`A message awaits...
|
|
4340
|
+
`||K==="\t";if(q&&W){X.push(Y<0.5?V:K);continue}let H=G/Z*0.4,z=Math.max(0,Math.min(1,(Y-H)/(1-H)));if(z===0)X.push(V);else if(z>=1)X.push(K);else if(q)X.push(z<0.7?" ":K);else if(W)X.push(z<0.3?V:" ");else if(z<0.5){let F=z*2;if(Math.random()<F)X.push(r61[Math.floor(Math.random()*r61.length)]);else X.push(V)}else{let F=(z-0.5)*2;if(Math.random()<F)X.push(K);else X.push(r61[Math.floor(Math.random()*r61.length)])}}return X.join("").trimEnd()}var x26=[{type:"command",text:'amp -x "What package manager do we use here?"'},{type:"command",text:'amp -x "Run the linter and fix the errors"'},{type:"hint",text:"Use Ctrl+O to open the command palette"},{type:"hint",text:"Use Ctrl+G to edit the prompt in your $EDITOR"},{type:"hint",text:"Use the `prompt: queue` command to enqueue messages without interrupting the agent"},{type:"hint",text:"Use the `thread: browser` command to open your thread in the browser"},{type:"hint",text:"Use the `thread: new` command to start a fresh thread"},{type:"hint",text:"Use the `thread: handoff` command to draft a new thread with relevant context"},{type:"hint",text:"Use the `thread: visibility` command to change thread visibility settings"},{type:"hint",text:"Use the `settings: open in editor` command to configure Amp"},{type:"hint",text:"Use the `agents-md: generate` command to create an AGENTS.md"},{type:"hint",text:"Use Tab/Shift+Tab to navigate to previous messages to edit or restore to a previous state"},{type:"prompt",text:'"Use the oracle to review the code we just wrote."'},{type:"prompt",text:'"Use subagents to update these components to use the new attribute we added."'},{type:"prompt",text:'"Do not write any code yet. Plan first."'},{type:"prompt",text:'"Think hard before you start implementing."'},{type:"prompt",text:`"Use 'psql' to change all blog_posts to have comments"`},{type:"prompt",text:'"Run <build command> and fix all the errors"'},{type:"quote",text:`"We are at the 'introduction of photography' period of programming. Painting by hand just doesn't have the same appeal anymore" - Orta Therox`},{type:"quote",text:'"Programming in the normal way feels like walking. You type out each expression, stepping incrementally toward your goal. When programming with AI, each move is bigger than a step. You lift off the ground." - Mary Rose Cook'},{type:"quote",text:'"Tomorrow all this may change, but right now after daily experience writing code with LLMs I strongly believe the maximum quality of work is reached using the human+LLM equation." - antirez'},{type:"quote",text:`"The magic that's coming now is the most powerful yet. And that means that we're beginning a profound period of exploration and creativity, trying to understand how to make that magic work and to derive new advantages from its power." - Tim O'Reilly`},{type:"quote",text:`"They're applying years of hard-won engineering wisdom to shape and constrain the AI's output. The AI is accelerating their implementation, but their expertise is what keeps the code maintainable." - Addy Osmani`},{type:"quote",text:'"I love computers just for the—sheer machine of it. This is the most exciting new thing that computers have been doing, probably in my lifetime." - DHH'},{type:"quote",text:`"We wouldn't even need to bother looking at the AI-generated code any more, just like we don't bother looking at the machine code generated by a compiler." - Martin Kleppmann`},{type:"quote",text:'"Real progress is messy, iterative, and deeply intertwined with the tools we build. Large language models are the latest, most dramatic example of that truth." - Daniel Lemire'},{type:"quote",text:`"'Human in the loop' is evolving from 'human who fixes AI mistakes' to 'human who directs AI work.'" - Ethan Mollick`},{type:"quote",text:`"I'm trying to code like a surgeon. A surgeon isn't a manager, they do the actual work! But their skills and time are highly leveraged." - Geoffrey Litt`},{type:"quote",text:`"It's important to do things fast. You learn more per unit time because you make contact with reality more frequently." - Nat Friedman`},{type:"quote",text:'"Once coding speed jumps, everything around it becomes the constraint. Your throughput gets capped by whatever is slowest." - Paul Dix'},{type:"quote",text:'"Bubble or no bubble, no one knows anything." - Benedict Evans'},{type:"quote",text:`"I actually don't think documentation is too important: LLMs can read the code a lot faster than you to figure out how to use it." - Simon Willison`},{type:"quote",text:`"The vast majority of AI tokens in the future will be used on things we don't even do today as workers." - Aaron Levie`},{type:"quote",text:`"Once you're airborne, you're suddenly immune to the length of the runway. You have days, not months. Time to break some things." - Kent Beck`},{type:"quote",text:'"Absolutely every fundamental assumption about how I work has to be questioned. There are days when it feels like I would be better off if I did not know anything about programming and started from scratch." - David Crawshaw'},{type:"quote",text:'"Code was the easiest part." - Andrej Karpathy'},{type:"quote",text:`"It's amazing for learning a codebase you're not familiar with, so it's great for discovery. Getting us out of writing boilerplate, getting us out of memorizing APIs, getting us out of looking up that thing from Stack Overflow." - Jeremy Howard`},{type:"quote",text:`"Don't anthropomorphize them!" - Steven Sinofsky`}],m_1=40,u_1=40;class Uj extends p1{agentMode;mysteriousMessage;mysterySequenceProgress;onShowMysteryModal;constructor(J={}){super(J.key?{key:J.key}:{});this.agentMode=J.agentMode,this.mysteriousMessage=J.mysteriousMessage,this.mysterySequenceProgress=J.mysterySequenceProgress,this.onShowMysteryModal=J.onShowMysteryModal}createState(){return new v26}}class v26 extends u1{_glow;_t=0;_timer=null;_fps=0;_shockwaves=[];_suggestion;_morphStartTime=null;_previousHasMystery=!1;initState(){super.initState(),this._glow=new hF,this._suggestion=x26[Math.floor(Math.random()*x26.length)],this._previousHasMystery=!!this.widget.mysteriousMessage}getMorphProgress(J){if(this._morphStartTime===null)return null;let Q=J-this._morphStartTime;if(Q>=y26)return null;return Q/y26}dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;super.dispose()}startAnimation(J){if(this._timer)clearInterval(this._timer),this._timer=null;if(this._fps=J,J>0)this._timer=setInterval(()=>{this._t+=1/J,this._shockwaves=this._shockwaves.filter((Q)=>this._t-Q.startTime<gF),this.setState(()=>{})},1000/J)}build(J){let Y=x0.of(J).colorScheme,X=W0.of(J).app,V=t0.of(J).capabilities.animationSupport,K=V==="fast"?60:V==="slow"?15:0;if(K!==this._fps)this.startAnimation(K);let q=!!this.widget.mysteriousMessage,W=this._suggestion,H=V==="disabled"?3:this._t;if(q&&!this._previousHasMystery&&V!=="disabled")this._morphStartTime=H;this._previousHasMystery=q;let z=this.getMorphProgress(H),F=z!==null,U=W.type==="quote"||W.type==="news"?new f({color:Y.foreground,dim:!0}):W.type==="hint"?new f({color:Y.secondary}):new f({color:W.type==="prompt"||W.type==="note"?Y.primary:Y.warning}),D=new f({color:X.keybind}),B=new f({color:X.command}),N=new f({color:Y.foreground,dim:!0}),w=[];if(W.type==="hint"){let k=W.text.split(/(`[^`]+`)/g);for(let b of k)if(b.startsWith("`")&&b.endsWith("`")){let c=b.slice(1,-1);w.push(new S(c,B))}else w.push(new S(b,U))}else w.push(new S(W.text,U));let M=V==="fast",L=(k)=>{this._shockwaves.push(k),this.setState(()=>{})},O=M?new o61({text:"Welcome to Amp",baseColor:Y.foreground,glow:this._glow,time:H,agentMode:this.widget.agentMode,orbWidth:m_1,orbHeight:u_1,glowIntensity:1,shockwaves:this._shockwaves}):new e({text:new S("Welcome to Amp",new f({color:Y.foreground}))}),A=null;if(q){let b=0.3+(Math.sin(H*0.5)*0.5+0.5)*0.4,c=new f({color:Y.primary,italic:!0,dim:b<0.5}),v=this.widget.mysterySequenceProgress?.matched.length??0,x=v>0?"Keep going...":"A message awaits...",g=[];for(let d=0;d<k26.length;d++){let h=k26[d],i=h==="ctrl+x"?"Ctrl-X":h.toUpperCase(),V1=d<v?new f({color:Y.primary,bold:!0}):D;if(d>0)g.push(new S(", ",N));g.push(new S(i,V1))}A=new k1({crossAxisAlignment:"start",mainAxisSize:"min",children:[M?new o61({text:x,baseColor:Y.primary,glow:this._glow,time:H,agentMode:this.widget.agentMode,orbWidth:m_1,orbHeight:u_1,glowIntensity:0.6,shockwaves:this._shockwaves}):new e({text:new S(x,c)}),new e({text:new S("",void 0,[...g,new S(" to unlock",N)])})]})}let I,j=`A message awaits...
|
|
4341
4341
|
Ctrl-X, Y, Z to unlock`;if(F){let b=W.text.replace(/`([^`]+)`/g,"$1")+`
|
|
4342
4342
|
`,c=cV8(b,j,z),m=new f({color:Y.primary,dim:!0}),v=c.split(`
|
|
4343
4343
|
`);I=new k1({crossAxisAlignment:"start",mainAxisSize:"min",children:[new e({text:new S(v[0]??"",m)}),new e({text:new S(v[1]??" ",m)})]})}else if(q)I=new I1({width:0,height:0});else I=new k1({crossAxisAlignment:"start",mainAxisSize:"min",children:[new e({text:new S("",void 0,w)}),new e({text:new S(" ")})]});let C=[O,new e({text:new S("",void 0,[new S(`
|
|
@@ -5075,7 +5075,7 @@ exit code: ${G}`,new f({color:Z.foreground,dim:!0,italic:!0})));if(V)K.push(new
|
|
|
5075
5075
|
`));let q=K.startsWith("file://")?Q0.parse(K):Q0.file(K),W=q7(q,X??void 0);G.push(new S(` • ${W}`,new f({color:Z.foreground,dim:!0})))}return new e({text:new S("",void 0,G)})}class G$6 extends S0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Y=Q.length>0,X=[new e({text:new S(Y?"This will delete this message and any subsequent messages in the thread, and will restore the following files:":"This will delete this message and any subsequent messages in the thread.",new f({color:o.yellow,bold:!0}))}),new I1({height:1})],G=$$6(J,Q);if(G)X.push(G),X.push(new I1({height:1}));let V=[{value:"confirm",label:Y?"Delete and restore":"Delete"},{value:"cancel",label:"Cancel"}];return X.push(new O5({options:V,onSelect:(K)=>{if(K==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:j1.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new k1({mainAxisSize:"min",crossAxisAlignment:"start",children:X})}}class V$6 extends S0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Y=[],Z=$$6(J,Q);if(Z)Y.push(new e({text:new S("This will restore the following files:",new f({color:o.yellow,bold:!0}))})),Y.push(new I1({height:1})),Y.push(Z),Y.push(new I1({height:1}));let X=[{value:"confirm",label:"Confirm edit"},{value:"cancel",label:"Cancel"}];return Y.push(new O5({options:X,onSelect:(G)=>{if(G==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:j1.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new k1({mainAxisSize:"min",crossAxisAlignment:"start",children:Y})}}class h81 extends p1{initialText;onSubmitted;message;completionBuilder;autocompleteHandle;onShowImagePreview;constructor(J){super();this.initialText=J.initialText,this.onSubmitted=J.onSubmitted,this.message=J.message,this.completionBuilder=J.completionBuilder,this.autocompleteHandle=J.autocompleteHandle,this.onShowImagePreview=J.onShowImagePreview}createState(){return new K$6}}class K$6 extends u1{controller=new Q7;currentShellModeStatus;imageAttachments=[];initState(){this.controller.text=this.widget.initialText,this.controller.addListener(this.textChangeListener);let J=rF(this.widget.initialText);if(this.currentShellModeStatus=J?.visibility,this.widget.message){let Q=this.widget.message.content.filter((Y)=>Y.type==="image");this.imageAttachments=Q}}dispose(){this.controller.removeListener(this.textChangeListener),this.controller.dispose(),super.dispose()}textChangeListener=()=>{let J=this.controller.text,Y=rF(J)?.visibility;if(Y!==this.currentShellModeStatus)this.currentShellModeStatus=Y,this.setState(()=>{})};handleSubmit=(J)=>{this.widget.onSubmitted(J,this.imageAttachments)};handleInsertImage=(J)=>{let Q=vj(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Q=this.imageAttachments[J];if(Q)this.widget.onShowImagePreview(Q,J,()=>{this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Y,Z)=>Z!==J)})})};build(J){let Q=W0.of(J),Y=Q.colors,Z=Q.app,X=this.currentShellModeStatus?vZ6(Q,this.currentShellModeStatus):Y$6,G=null,V=this.widget.message&&Cl(this.widget.message);if(V)G=fy1(J,V);let K=new Dg({controller:this.controller,triggers:[new YU],completionBuilder:this.widget.completionBuilder,ampURL:"",onSubmitted:this.handleSubmit,theme:Y,placeholder:"",enabled:!0,autofocus:!0,shellPromptRules:B81(Q),imageAttachments:this.imageAttachments,onInsertImage:this.handleInsertImage,popImage:this.handlePopImage,onImageClick:this.handleImageClick,minLines:1,textColor:X,autocompleteHandle:this.widget.autocompleteHandle,autoOverlayPosition:!0}),q=[];if(q.push(K),G)q.push(new I1({height:1})),q.push(G);let W;if(q.length===1)W=q[0];else W=new k1({mainAxisSize:"min",crossAxisAlignment:"start",children:q});let H=[];if(this.currentShellModeStatus===oF)H.push(new S("shell mode (incognito)",new f({color:Q.app.shellModeHidden})));else if(this.currentShellModeStatus===U81)H.push(new S("shell mode",new f({color:Q.app.shellMode})));else H.push(new S("esc",new f({color:Z.keybind})),new S(" to cancel",new f({color:Y.foreground,dim:!0})));return new Jh({child:new VY({decoration:{border:y0.all(new j0(X,2,"solid"))},padding:j1.only({left:1,right:1}),overlays:[{child:new e({text:new S("",void 0,H)}),position:"bottom",alignment:"left"}],child:W})})}}class g81 extends x8{}class m81 extends x8{}class hy1 extends x8{}class gy1 extends x8{}class my1 extends x8{}class uy1 extends x8{}class py1 extends x8{}class dy1 extends x8{}function aB8(J,Q,Y){let X=W0.maybeOf(J)?.colors??x0.of(J).colorScheme,V=Q.trimStart().startsWith("You're absolutely right"),K=new y8(`${Y}-text`),q=[];if(V)q.push(new Wy1({key:K,markdown:Q,defaultColor:X.foreground}));else q.push(new f8({key:K,markdown:Q}));if(q.length===1)return q[0];return new k1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q})}function oB8(J,Q){let Z=x0.of(J).colorScheme;if(Q.summary.type!=="message")return new d1;return new k1({crossAxisAlignment:"start",children:[new e({text:new S("Summary:",new f({color:Z.foreground,dim:!0,bold:!0,italic:!0})),selectable:!0}),new I1({height:1}),new f8({markdown:Q.summary.summary,styleScheme:{text:new f({color:Z.foreground,dim:!0,italic:!0}),inlineCode:new f({color:Z.foreground,dim:!0,italic:!0}),codeBlock:new f({color:Z.foreground,dim:!0,italic:!0}),tableBorder:Z.foreground,link:new f({color:Z.foreground,dim:!0,italic:!0}),syntaxHighlight:{keyword:Z.foreground,string:Z.foreground,number:Z.foreground,comment:Z.foreground,function:Z.foreground,variable:Z.foreground,type:Z.foreground,operator:Z.foreground}}})]})}class u81 extends p1{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onShellCommandSubmit;onMessageRestoreSubmit;onMessageForkSubmit;getAffectedFiles;thread;focusNode;onDismissFocus;isInSelectionMode=!1;isInHandoffMode=!1;completionBuilder;onShowImagePreview;onSelectionChanged;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Y=this.items[Q];if(Y?.type==="message"){if(Y.message.role==="user"||gO(Y.message))J.push(Q)}}return J}constructor({key:J,items:Q,subagentToolsByParentID:Y={},controller:Z,autofocus:X=!1,onNewMessage:G,showScrollbar:V=!0,onCopy:K,onMessageEditSubmit:q,onMessageRestoreSubmit:W,onMessageForkSubmit:H,getAffectedFiles:z,thread:F,focusNode:U,onDismissFocus:D,isInSelectionMode:B=!1,isInHandoffMode:N=!1,completionBuilder:w,onShowImagePreview:M,onSelectionChanged:L}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Y,this.controller=Z,this.autofocus=X,this.onNewMessage=G,this.showScrollbar=V,this.onCopy=K,this.onMessageEditSubmit=q,this.onMessageRestoreSubmit=W,this.onMessageForkSubmit=H,this.getAffectedFiles=z,this.thread=F,this.focusNode=U,this.onDismissFocus=D,this.isInSelectionMode=B,this.isInHandoffMode=N,this.completionBuilder=w,this.onShowImagePreview=M,this.onSelectionChanged=L}createState(){return new q$6}}class q$6 extends u1{_controller=null;_isDisposed=!1;_thinkingBlockStates=new Map;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;_isShowingEditConfirmation=!1;_pendingEditText=null;_pendingEditImageAttachments=[];_affectedFiles=[];_autocompleteHandle={dismiss:()=>{}};_scrollListener=null;get controller(){return this._controller}dismiss(){Y4.instance.addPostFrameCallback(()=>{this.widget.focusNode?.unfocus()}),this.widget.onDismissFocus?.()}_navigateUp(J,Q){if(Q<=0)return null;if(J===null)return Q-1;if(J<=0)return 0;return J-1}_navigateDown(J,Q){if(Q<=0)return null;if(J===null)return null;if(J>=Q-1)return null;return J+1}_ordinalToIndex(J,Q){if(Q===null)return null;if(Q<0||Q>=J.length)return null;return J[Q]??null}_getUserCount(){return this.widget.userMessageIndices.length}_clearSelectedUserMessage(){let J=this._selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._selectedUserMessageOrdinal=null})}_selectUserMessageByOrdinal(J){let Q=this._selectedUserMessageOrdinal,Y=J,Z=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,X=this.getUserMessageIndexFromOrdinal(Y);if(Z!==null)this._widgetCache.delete(Z);if(X!==null)this._widgetCache.delete(X);if(this.setState(()=>{this._selectedUserMessageOrdinal=Y}),X!==null)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(X,{animated:!0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._editingMessageOrdinal,Y=J,Z=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,X=Y!==null?this.getUserMessageIndexFromOrdinal(Y):null;if(Z!==null)this._widgetCache.delete(Z);if(X!==null)this._widgetCache.delete(X);this.setState(()=>{this._editingMessageOrdinal=Y})}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Y=this.widget.userMessageIndices.indexOf(J);return Y>=0?Y:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Y=J==="up"?this._navigateUp(this._selectedUserMessageOrdinal,Q):this._navigateDown(this._selectedUserMessageOrdinal,Q);if(Y===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Y!==null)this._selectUserMessageByOrdinal(Y)}handleNavigateUserMessageUp=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._editingMessageOrdinal!==null)return this.setState(()=>{let J=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);this._editingMessageOrdinal=null}),"handled";else if(this._selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._editingMessageOrdinal=null}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{if(this._selectedUserMessageOrdinal!==null)return this._selectEditingUserMessageByOrdinal(this._selectedUserMessageOrdinal),"handled";return"ignored"};handleRestoreMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||gO(Q.message)))this.showRestoreConfirmation(Q.message,J)}return"handled"}return"ignored"};async showRestoreConfirmation(J,Q){let Y=[];if(this.widget.getAffectedFiles)try{Y=await this.widget.getAffectedFiles(J)}catch{Y=[]}if(this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!0,this._affectedFiles=Y}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}handleRestoreConfirm=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageRestoreSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!1,this._affectedFiles=[]}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!1,this._affectedFiles=[]}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}}return"handled"};handleForkMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||gO(Q.message))){if(J===0)return"ignored";this.widget.onMessageForkSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss()}}return"handled"}return"ignored"};handleEditConfirmationRequest=async(J,Q)=>{if(J.trim()===""&&Q.length===0)return;if(this._editingMessageOrdinal!==null){let Y=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(Y!=null){let Z=this.widget.items[Y],X=[];if(this.widget.getAffectedFiles&&Z?.type==="message")try{X=await this.widget.getAffectedFiles(Z.message)}catch{X=[]}if(X.length===0&&Z?.type==="message"&&(Z.message.role==="user"||Z.message.role==="info")){this.widget.onMessageEditSubmit?.(Z.message,J,Q),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._editingMessageOrdinal=null}),this.dismiss(),this.controller.animateToBottom(100);return}if(this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!0,this._pendingEditText=J,this._pendingEditImageAttachments=Q,this._affectedFiles=X,this._editingMessageOrdinal=null}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Y)})}}};handleEditConfirm=()=>{if(this._selectedUserMessageOrdinal!==null&&this._pendingEditText!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageEditSubmit?.(Q.message,this._pendingEditText,this._pendingEditImageAttachments),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._pendingEditImageAttachments=[],this._affectedFiles=[]}),this.dismiss(),this.controller.animateToBottom(100)}}};handleEditCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._pendingEditImageAttachments=[],this._affectedFiles=[]}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}}};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Y=V7(Q.content),Z=Q.content.filter((X)=>X.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${Z}|${Y}`}else if(Q.role==="assistant"){let Y=V7(Q.content),Z=Q.state?.type??"none",X=Q.content.filter((q)=>q.type==="thinking"),G=Q.content.filter((q)=>q.type==="tool_use"),V=Q.usage,K=V?`${V.credits??""}|${V.inputTokens}|${V.outputTokens}|${V.cacheCreationInputTokens??""}|${V.cacheReadInputTokens??""}|${V.model??""}`:"no-usage";return`${J.id}|assistant|${Z}|${X.length}|${G.length}|${Y}|${K}`}else{let Z=Q.content.map((X)=>X.type).join(",");return`${J.id}|info|${Z}`}}else{let Y=J.toolResult.run.status;return`${J.id}|tool|${Y}|${J.toolUse.id}`}}getThinkingBlockExpanded(J,Q){let Y=`${J}-${Q}`;return this._thinkingBlockStates.get(Y)??Y7.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Y)=>{let Z=`${J}-${Q}`;this.setState(()=>{this._thinkingBlockStates.set(Z,Y),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Y,Z,X){let G=Y===X,V=Z.state?.type==="streaming"&&G,K=Z.state?.type==="cancelled"&&G;return new AM({key:new y8(`thinking-${Q}-${Y}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Y),onToggle:this.toggleThinkingBlock(Q,Y),isStreaming:V,isCancelled:K})}buildAssistantMessageWidget(J,Q,Y,Z){let X=Q.content.map((U,D)=>({block:U,index:D})).filter((U)=>U.block.type==="thinking"&&Gg(U.block.thinking).length>0),G=X.length>0,V=X.length>0?X.at(-1).index:-1,K=Q.content.filter((U)=>U.type==="text"),q=[];if(q.push(...X.map(({block:U,index:D})=>this.buildThinkingBlock(U,Y,D,Q,V))),G&&K.length>0)q.push(new I1({height:1}));let W=V7(K);if(W.trim())q.push(aB8(J,W,Z));let H=qy1(J),z=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(H&&z){let D=W0.maybeOf(J)?.colors??x0.of(J).colorScheme,B=$X6(Q.usage);q.push(new J0({padding:j1.only({top:1}),child:new e({text:new S(B,new f({color:D.foreground,dim:!0}))})}))}let F;if(q.length===0)F=new d1;else if(q.length===1)F=q[0];else F=new k1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q});return F}buildThreadItemWidget(J,Q,Y){let Z=new y8(`thread-item-${Q.id}`);if(Q.type==="message"){let X=Q.message;if(X.role==="user"){let G,V=(K,q)=>{this.widget.onShowImagePreview(K,q,()=>{})};if(!this.widget.isInSelectionMode)G=new lj({message:X,isFirstMessage:Y>0,onShowImagePreview:V});else{let K=this.getOrdinalFromUserMessageIndex(Y);if(K===null)G=new lj({message:X,isFirstMessage:Y>0,onShowImagePreview:V});else if(this._editingMessageOrdinal===K)G=new h81({initialText:V7(X.content),message:X,onSubmitted:(q,W)=>{this.handleEditConfirmationRequest(q,W)},completionBuilder:this.widget.completionBuilder,autocompleteHandle:this._autocompleteHandle,onShowImagePreview:this.widget.onShowImagePreview});else if(this._selectedUserMessageOrdinal===K)G=new f81({message:X,isFirstMessage:Y>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,isShowingEditConfirmation:this._isShowingEditConfirmation,affectedFiles:this._affectedFiles,pendingEditText:this._pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onShowImagePreview:V});else G=new lj({message:X,isFirstMessage:Y>0,onShowImagePreview:V})}return G}else if(X.role==="assistant"){let G=this.buildAssistantMessageWidget(J,X,Y,Q.id);return new d1({key:Z,child:G})}else{let G=X,V=[],K=this.getOrdinalFromUserMessageIndex(Y),q=this.widget.isInSelectionMode&&K!==null&&this._selectedUserMessageOrdinal===K,W=(H,z)=>{this.widget.onShowImagePreview(H,z,()=>{})};for(let H of G.content)if(H.type==="manual_bash_invocation")if(this._editingMessageOrdinal===K){let F=`${D81(H.hidden??!1)}${H.args.cmd}`;V.push(new h81({initialText:F,message:G,onSubmitted:(U,D)=>{this.handleEditConfirmationRequest(U,D)},completionBuilder:this.widget.completionBuilder,autocompleteHandle:this._autocompleteHandle,onShowImagePreview:this.widget.onShowImagePreview}))}else if(!this.widget.isInSelectionMode||!q)V.push(new lj({message:G,isFirstMessage:Y>0,onShowImagePreview:W}));else V.push(new f81({message:G,isFirstMessage:Y>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,isShowingEditConfirmation:this._isShowingEditConfirmation,affectedFiles:this._affectedFiles,pendingEditText:this._pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onShowImagePreview:W}));else if(H.type==="summary"&&H.summary.type==="message")V.push(oB8(J,H));if(V.length===0)return new d1;if(V.length===1)return V[0];return new k1({crossAxisAlignment:"stretch",children:V})}}else{let X=new HW({toolUse:Q.toolUse,toolRun:Q.toolResult.run,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new d1({key:Z,child:X})}}initState(){if(super.initState(),this._controller=this.widget.controller||new a4,this._scrollListener=()=>{this._autocompleteHandle.dismiss()},this._controller.addListener(this._scrollListener),this._globalToggleListener=()=>{this.setState(()=>{this._thinkingBlockStates.clear(),this._widgetCache.clear()})},Y7.instance.addListener(this._globalToggleListener),this.widget.items.length>0)Y4.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let Y=this.getLatestUserMessageOrdinal();if(Y!==null)this._selectUserMessageByOrdinal(Y)}if(J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Y=0;Y<Q;Y++){let Z=J.items[Y],X=this.widget.items[Y];if(Z&&X){if(Z.type!==X.type){this._widgetCache.delete(Y);continue}if(Z.type==="toolResult"&&X.type==="toolResult"){let G=Z.toolResult.run,V=X.toolResult.run;if(G.status!==V.status||"result"in G!=="result"in V||"error"in G!=="error"in V)this._widgetCache.delete(Y)}if(Z.type==="message"&&X.type==="message"){let G=Z.message,V=X.message;if(G.content!==V.content)this._widgetCache.delete(Y)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Y of this._streamingIndexes)if(Y>=this.widget.items.length)this._streamingIndexes.delete(Y)}_cleanupOrphanedCacheEntries(){for(let J of this._widgetCache.keys())if(J>=this.widget.items.length)this._widgetCache.delete(J)}_isMessageStreaming(J){if(J.type!=="message")return!1;let Q=J.message;if(Q.role!=="assistant")return!1;if(Q.state.type==="streaming")return!0;return Q.content.at(-1)?.type==="thinking"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this.widget.items.length)this._streamingIndexes.delete(J);for(let J=0;J<this.widget.items.length;J++){let Q=this.widget.items[J];if(!Q)continue;let Y=this._isMessageStreaming(Q);if(Y&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Y&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Q=J.size;if(typeof Q.height==="number"&&Q.height>0)return this._viewportHeight=Q.height,Q.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._scrollListener&&this._controller)this._controller.removeListener(this._scrollListener),this._scrollListener=null;if(this._globalToggleListener)Y7.instance.removeListener(this._globalToggleListener);if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=W0.of(J),Y=qy1(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Y)this._widgetCache.clear();this._lastCostDisplayState=Y;let Z=this._getTotalItemCount(J),X=[];for(let F=0;F<Z;F++)if(X.push(this._buildItemAtIndex(J,F)),F<Z-1)X.push(new I1({height:1}));let G=new q4({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new k1({key:new y8("message-list-column"),crossAxisAlignment:"start",children:X})}),K=[new J0({padding:j1.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:G})];if(this.widget.showScrollbar&&this._controller){let F=new C9({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});K.push(new f4({right:1,top:0,bottom:0,child:new I1({width:1,child:F})}))}let q=new x4({children:K}),W=new tq({child:q,onCopy:this.widget.onCopy,onSelectionChanged:this.widget.onSelectionChanged}),H=new Map([[g81,new h6(this.handleNavigateUserMessageUp)],[m81,new h6(this.handleNavigateUserMessageDown)],[hy1,new h6(this.handleEscape)],[gy1,new h6(this.handleScrollDown)],[my1,new h6(this.handleScrollUp)],[uy1,new h6(this.handleEditMessage)],[py1,new h6(this.handleRestoreMessage)],[dy1,new h6(this.handleForkMessage)]]),z=new Map([[p0.key("Tab"),new g81],[p0.shift("Tab"),new m81],[p0.key("Escape"),new hy1],[p0.key("j"),new gy1],[p0.key("k"),new my1],[p0.key("e"),new uy1],[p0.key("r"),new py1],[p0.key("f"),new dy1]]);if(!J7())z.set(p0.key("ArrowUp"),new g81),z.set(p0.key("ArrowDown"),new m81);if(this.widget.focusNode)return new A6({focusNode:this.widget.focusNode,child:new b5({actions:H,child:new C3({shortcuts:z,focusNode:this.widget.focusNode,child:W})})});return W}_getTotalItemCount(J){return this.widget.items.length}_shouldDimItem(J){if(this.widget.isInHandoffMode)return!0;if(this._isShowingRestoreConfirmation||this._isShowingEditConfirmation){let Q=this._selectedUserMessageOrdinal;if(Q===null)return!1;let Y=this.getUserMessageIndexFromOrdinal(Q);if(Y===null)return!1;return J>Y}if(this._editingMessageOrdinal!==null){let Q=this.getUserMessageIndexFromOrdinal(this._editingMessageOrdinal);if(Q===null)return!1;return J>Q}return!1}_buildItemAtIndex(J,Q){let Y=this.widget.items[Q];if(!Y)return new d1;let Z=Y.type==="message"&&this._isMessageStreaming(Y),X=Y.type==="toolResult"&&(Y.toolResult.run.status==="queued"||Y.toolResult.run.status==="in-progress")&&!("result"in Y.toolResult.run)&&!("error"in Y.toolResult.run),G=this._shouldDimItem(Q);if(!Z&&!X){let q=`${this._signatureFor(Y)}|dim:${G?1:0}`,W=this._widgetCache.get(Q);if(W&&W.sig===q)return W.widget;let H=this.buildThreadItemWidget(J,Y,Q),z=G?new GY({forceDim:!0,child:H}):H;return this._widgetCache.set(Q,{sig:q,widget:z}),z}let K=this.buildThreadItemWidget(J,Y,Q);return G?new GY({forceDim:!0,child:K}):K}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offsetPercent:Y=0.25,edge:Z="top",duration:X}={}){if(this._isDisposed||!this._controller)return!1;let G=this._getMessageRelativeOffset(J,Z);if(G===null)return!1;let V=this._getViewportHeight(),K=Math.floor(V*Y),q=G-K;if(Q)this._controller.animateTo(q,X);else this._controller.jumpTo(q);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new y8("message-list-column"),Y=(Z)=>{if(Z.widget.key?.equals(Q))return Z;for(let X of Z.children){let G=Y(X);if(G)return G}return null};return Y(J)}_getMessageRelativeOffset(J,Q){let Y=this._getColumnElement();if(!Y)return null;let Z=J*2,X=Y.children[Z];if(!X?.renderObject)return null;let G=X.renderObject,V=Y.renderObject;if(!V)return null;let K=G.localToGlobal({x:0,y:0}),q=V.localToGlobal({x:0,y:0}),W=0;if(Q==="bottom")W=G.size.height;return K.y+W-q.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Y=this._controller?.offset??0,Z=J+Q;return{totalContentHeight:Math.max(Z,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Y,0)}}}n6();j6();n6();K0();class cy1{threadService;workers=new Map;threadsMap=new Map;mainThreadSubs=new Map;workerStatusSubs=new Map;mainThreadObservable;workerStatusObservable;emitMainThread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new T1((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.workerStatusObservable=new T1((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.workers.set(Q,{state:"initial"});let Y=this.threadService.observePatches(Q).pipe(Sl()).subscribe((X)=>{this.threadsMap.set(Q,X);let G=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:X,workerStatus:G})});this.mainThreadSubs.set(Q,Y);let Z=J.status.subscribe((X)=>{if(this.workers.set(Q,X),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:X})});this.workerStatusSubs.set(Q,Z)}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);this.workers.delete(J),this.threadsMap.delete(J)}observeThread(J){return{mainThread:new T1((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new T1((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]=Zw(Y,Z)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.workerStatusSubs.clear(),this.workers.clear(),this.threadsMap.clear()}}function rB8(J,Q){switch(Q.type){case"main-thread-patch":{let{thread:Y,workerStatus:Z}=Q,{items:X}=p81(Y),G=Zw(Y,Z),V=qH({messages:Y.messages}),K=Array.isArray(V)?V:[];return{...J,items:X,viewState:G,todosList:K,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=Zw(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function p81(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 z=X+1;z<J.messages.length;z++){let F=J.messages[z];if(F){for(let U of F.content)if(U.type==="tool_result"&&U.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":{if(G.content.some((q)=>q.type==="manual_bash_invocation"||q.type==="summary"&&q.summary.type==="message"))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)??R2(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}}class ly1 extends p1{props;constructor(J){super();this.props=J}createState(){return new W$6}}class W$6 extends u1{state={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 cy1(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((X)=>{this.dispatch({type:"main-thread-patch",thread:X.mainThread,workerStatus:X.workerStatus})});this.subscriptions.push(Y);let Z=Q.workerStatus.subscribe((X)=>{this.dispatch({type:"worker-status-change",workerStatus:X.status})});this.subscriptions.push(Z)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={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=rB8(this.state,J)})}getThreadData(){let J=(X)=>X===x9||X===T8||X===WG||X===M2,Q=new Map;for(let X of this.state.items)if(X.type==="toolResult"&&J(X.toolUse.name))Q.set(X.toolUse.id,{toolUseId:X.toolUse.id,toolName:X.toolUse.name,toolRun:X.toolResult.run});let Y=Array.from(Q.values()),Z={};for(let{toolUseId:X,toolRun:G}of Y){let V=[],K;if(G.status==="in-progress"||G.status==="done"||G.status==="error"||G.status==="cancelled")K=G.progress;if(K){let q=0;for(let W of K)if(W.tool_uses)for(let H of W.tool_uses){let z=`${X}:progress:${q++}`,F=H.status==="done"&&H.result!==void 0?{status:"done",result:H.result}:{status:H.status};V.push({toolUse:hO(H.tool_name,H.input,z),toolRun:F})}}Z[X]=V}return{...this.state,subagentToolsByParentID:Z}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker,this.recentThreadIDs)}}class iy1 extends p1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new H$6}}class H$6 extends u1{build(J){let Y=W0.of(J).colors,{todos:Z,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Z)||Z.length===0)return new I1({width:0,height:0});let G=Z.map((V)=>this.buildTodoItem(V,Y));return new d1({child:new J0({padding:j1.symmetric(1,0),child:new k1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new e({text:new S(X,new f({bold:!0,color:Y.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),Z=J.status==="completed",X=new f({bold:J.status==="in-progress",color:Q.foreground,dim:Z}),G=new f({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Z});return new X0({crossAxisAlignment:"start",children:[new e({text:new S(Y,X)}),new I1({width:1}),new A0({child:new e({text:new S(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class ny1 extends p1{ad;onDismiss;onButtonClick;onImpression;onAdInfoClick;constructor({key:J,ad:Q,onDismiss:Y,onButtonClick:Z,onImpression:X,onAdInfoClick:G}){super({key:J});this.ad=Q,this.onDismiss=Y,this.onButtonClick=Z,this.onImpression=X,this.onAdInfoClick=G}createState(){return new z$6}}class z$6 extends u1{lastTrackedAdId=null;initState(){super.initState(),this.fireImpressionIfNeeded()}didUpdateWidget(J){super.didUpdateWidget(J),this.fireImpressionIfNeeded()}fireImpressionIfNeeded(){let J=this.widget.ad;if(J.id!==this.lastTrackedAdId)this.lastTrackedAdId=J.id,this.widget.onImpression?.(J)}build(J){let Q=W0.of(J),Y=Q.colors.primary,Z=Q.colors.foreground,X=this.widget.ad;return new d1({decoration:new N6(void 0,new y0(new j0(Y,1,"rounded"),new j0(Y,1,"rounded"),void 0,new j0(Y,1,"rounded"))),child:new J0({padding:j1.horizontal(1),child:new k1({children:[new X0({crossAxisAlignment:"start",children:[new A0({child:new e({text:new S(X.content,new f({color:Z}))})}),new I1({width:4}),new H6({onClick:()=>this.widget.onAdInfoClick?.(),cursor:"pointer",child:new e({text:new S("Ad",new f({color:Z,dim:!0}))})})]}),new X0({crossAxisAlignment:"start",children:[new _C1({text:X.buttonLabel,onPressed:()=>this.widget.onButtonClick?.(),padding:j1.horizontal(1),color:Y,reverse:!0}),new I1({width:2}),new e({text:new S(X.destinationUrlHostname,new f({color:Z,dim:!0}))})]})]})})})}}class ay1 extends p1{props;constructor(J){super();this.props=J}createState(){return new F$6(this.props.autofocus??!0)}}class F$6 extends u1{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=t0.sizeOf(J),Z=Math.min(60,Y.width-4),X=Y.height-4,G=[];if(this.widget.props.title)G.push(new e({text:new S(this.widget.props.title,new f({bold:!0,color:o.blue}))}),new I1({height:1}));if(this.widget.props.message)G.push(new e({text:new S(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)G.push(new I1({height:1}));let V=[];if(this.widget.props.showCopyOption)V.push(new e({text:new S("Enter to copy",new f({dim:!0}))}));return V.push(new e({text:new S("Escape to close",new f({dim:!0}))})),G.push(new X0({children:V.flatMap((K,q)=>q<V.length-1?[K,new I1({width:1}),new e({text:new S("•",new f({dim:!0}))}),new I1({width:1})]:[K]),mainAxisSize:"min"})),new b0({child:new d1({constraints:new O0(Z,Z,0,X),decoration:new N6(o.default(),new y0(new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"))),padding:new j1(2,2,2,2),child:new A6({autofocus:this.autofocus,onKey:Q,child:new k1({children:G,mainAxisSize:"min"})})})})}}class oy1 extends p1{props;constructor(J){super();this.props=J}createState(){return new U$6(this.props.autofocus??!0)}}class U$6 extends u1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(V)=>{if(V.key==="Enter"||V.key==="Escape"||V.ctrlKey&&V.key==="c")return this.widget.props.onClose(),"handled";return"ignored"},Y=t0.sizeOf(J),Z=Math.min(60,Y.width-4),X=Y.height-4,G=[];if(G.push(new e({text:new S("Ads make Amp Free possible",new f({bold:!0}))})),this.widget.props.provider)G.push(new I1({height:1}),new e({text:new S(`Ad source: ${this.widget.props.provider}`,new f({dim:!0}))}));return G.push(new I1({height:1}),new e({text:new S("Escape to close",new f({dim:!0}))})),new b0({child:new d1({constraints:new O0(Z,Z,0,X),decoration:new N6(o.default(),new y0(new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"))),padding:new j1(2,2,2,2),child:new A6({autofocus:this.autofocus,onKey:Q,child:new k1({children:G,mainAxisSize:"min"})})})})}}function ry1(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})}fX();v1();import{spawn as sB8}from"node:child_process";import{promises as tB8}from"node:fs";function D$6(J){return J.kind==="executable"}function B$6(J){return J.kind==="markdown"}var zW=50000,N$6=300000;async function sy1(J,Q,Y,Z={}){let{timeoutMs:X=N$6,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(P.debug("Executing command",{commandName:J,filePath:K.filePath,args:Q}),B$6(K))return await eB8(K,Q);else if(D$6(K))return await JN8(K,Q,X,G);else return{success:!1,output:"",error:"Unsupported command type"}}catch(K){return P.error("Failed to execute command",{commandName:J,error:K}),{success:!1,output:"",error:K instanceof Error?K.message:"Unknown error occurred"}}}async function eB8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await tB8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>zW?Y.slice(0,zW)+`
|
|
5076
5076
|
... (output truncated at ${zW} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function JN8(J,Q,Y=N$6,Z){return new Promise((X)=>{let[G,V]=QN8(J,Q);P.debug("Spawning command",{spawnCommand:G,spawnArgs:V.slice(0,10),filePath:J.filePath,timeoutMs:Y});let K=dS(Z),q=!1,W=setTimeout(()=>{q=!0,K.abort(),P.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=sB8(G,V,{stdio:["pipe","pipe","pipe"],signal:K.signal,detached:!0}),z=[],F=[],U=0;H.stdout?.on("data",(D)=>{let B=D.toString();if(U+=B.length,U<=zW)z.push(B);else{let N=zW-(U-B.length);if(N>0)z.push(B.slice(0,N))}}),H.stderr?.on("data",(D)=>{let B=D.toString();if(U+=B.length,U<=zW)F.push(B);else{let N=zW-(U-B.length);if(N>0)F.push(B.slice(0,N))}}),H.on("close",(D)=>{if(clearTimeout(W),q){X({success:!1,output:z.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(K.signal.aborted){X({success:!1,output:z.join(""),error:"The command was aborted",exitCode:D??void 0});return}let B=D===0||D===1,N=z.join(""),w=F.join(""),M=N;if(!B&&!N.trim()&&w.trim())M=w;else if(w.trim())M+=N?`
|
|
5077
5077
|
${w}`:w;if(U>zW)M+=`
|
|
5078
|
-
... (output truncated at ${zW} characters)`;X({success:B,output:M.trim(),error:!B?w.trim()||"Command failed":void 0,exitCode:D??void 0})}),H.on("error",(D)=>{clearTimeout(W);let B=D.message;if(q)B=`Command timed out after ${Y}ms`;else if(D.message.includes("operation was aborted")||D.name==="AbortError")B="The command was aborted";X({success:!1,output:z.join(""),error:B})})})}function QN8(J,Q){let{filePath:Y,interpreter:Z,extension:X}=J;if(process.platform==="win32")return ZN8(Y,Z?[...Z]:null,X,Q);else return YN8(Y,Z?[...Z]:null,X,Q)}function YN8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];else return[J,Z]}function ZN8(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]}}v1();aO();RX();b9();K3();MO();MG();N3();RQ();CH();UZ();n6();Fb();t9();MC();K0();var s$6=H0(iH(),1);import{writeFile as i$6}from"fs/promises";import n$6 from"path";v1();N3();class ty1{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.1768204893-g301329"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Za(Q,this.configService)}catch(Q){P.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 ZU extends p1{props;constructor(J){super();this.props=J}createState(){return new w$6}}class w$6 extends u1{_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 M$6 extends u1{controller=new Q7;focusNode=new r6({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=W0.of(J),{colors:Y,app:Z}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=y0.all(new j0(Y.foreground,1,"solid")),q=new T3({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]}),H=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,[new S("Command: ",new f({color:Y.foreground})),new S(this.widget.props.commandName,new f({color:o.yellow,bold:!0}))])})}),z=[];if(V)z.push(new S("Enter",new f({color:Z.keybind}))),z.push(new S(" to submit, ",new f({color:Y.foreground,dim:!0})));z.push(new S("Esc",new f({color:Z.keybind}))),z.push(new S(" to cancel",new f({color:Y.foreground,dim:!0})));let F=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,z)})});return new d1({decoration:{border:K,color:o.default()},padding:j1.all(1),child:new k1({children:[H,new I1({height:1}),W,new O8,F]})})}}class Bg extends p1{props;constructor(J){super();this.props=J}createState(){return new M$6}}import{isDeepStrictEqual as VN8}from"node:util";var XN8=/[\\/_ +.#"@[({&]/,$N8=/[\\/_ +.#"@[({&]/g,GN8=/[\s-]/,L$6=/[\s-]/g;function c81(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,z,F,U,D;while(W>=0){if(z=c81(J,Q,Y,Z,W+1,G+1,V),z>H){if(W===X)z*=1;else if(GN8.test(J.charAt(W-1))){if(z*=0.9,D=J.slice(X,W-1).match(L$6),D&&X>0)z*=0.999**D.length}else if(XN8.test(J.charAt(W-1))){if(z*=0.8,U=J.slice(X,W-1).match($N8),U&&X>0)z*=0.999**U.length}else if(z*=0.3,X>0)z*=0.999**(W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<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(F=c81(J,Q,Y,Z,W+1,G+2,V),F*0.1>z)z=F*0.1}if(z>H)H=z;W=Y.indexOf(q,W+1)}return V[K]=H,H}function d81(J){return J.toLowerCase().replace(L$6," ")}function O$6(J,Q){let Y=c81(J,Q,d81(J),d81(Q),0,0,{}),Z=Q.trim().split(/\s+/);if(Z.length>1){let X=0,G=0;for(let K of Z){let q=c81(J,K,d81(J),d81(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 ij{}class nj{}class l81{}class i81{}class A$6 extends p1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new I$6}}class I$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}function KN8(J,Q){if(J==="")return{matches:!0,score:1};let Y=O$6(Q,J);return{matches:Y>0.15,score:Y}}class P7 extends p1{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new E$6}}class E$6 extends u1{controller=new Q7;focusNode;scrollController=new a4;selectedIndex=0;itemContexts=[];cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new r6({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),Y4.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(!VN8(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 ij){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof nj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof l81){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 i81)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,...KN8(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;nR(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(),Y4.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=W0.of(J),{colors:Y}=Q,Z=this.getFilteredItems(),X=y0.all(new j0(Y.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new T3({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Y.foreground,border:null},maxLines:1}),K=new C3({shortcuts:new Map([[new p0("ArrowDown"),new ij],[new p0("ArrowUp"),new nj],[new p0("Tab"),new ij],[new p0("Tab",{shift:!0}),new nj],[new p0("n",{ctrl:!0}),new ij],[new p0("p",{ctrl:!0}),new nj],[new p0("Enter"),new l81],[new p0("Escape"),new i81]]),focusNode:this.focusNode,child:V}),q=new b5({actions:new Map([[ij,new h6(this.invoke)],[nj,new h6(this.invoke)],[l81,new h6(this.invoke)],[i81,new h6(this.invoke)]]),child:K}),W=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";H=new I1({height:10,child:new b0({child:new e({text:new S(B,new f({color:Y.foreground}))})})})}else if(Z.length===0&&this.widget.props.emptyStateText)H=new A0({child:new b0({child:new e({text:new S(this.widget.props.emptyStateText,new f({color:Y.foreground,dim:!0}))})})});else{let B=Z.map((N,w)=>{let M=w===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,O;if(this.widget.props.renderItem)O=this.widget.props.renderItem(N,M,L,J);else{let A=M?o.yellow:void 0,I=M?o.black:Y.foreground;O=new d1({decoration:A?{color:A}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S(this.widget.props.getLabel(N),new f({color:I,dim:L}))})})}return new A$6(new H6({onClick:(A)=>this.handleItemClick(w,A.clickCount),child:O}),(A)=>{this.itemContexts[w]=A})});H=new k1({children:B,crossAxisAlignment:"start"})}let z=new A0({child:new H6({onScroll:this.handleScroll,opaque:!1,child:new q4({controller:this.scrollController,autofocus:!1,child:H})})}),F=[];if(this.widget.props.title){let B=new d1({padding:j1.symmetric(1,0),child:new e({text:new S(this.widget.props.title,new f({color:o.yellow,bold:!0}))})});F.push(B)}if(F.push(W,new I1({height:1}),z),this.controller.text!==""){let B=Z.length>0?Z[this.selectedIndex]:void 0,N=B&&this.widget.props.buildDisabledReasonWidget?.(B);if(N)F.push(new d1({padding:j1.vertical(1),child:new b0({child:N})}));else F.push(new I1({height:3}))}if(this.widget.props.footer)F.push(this.widget.props.footer);return new d1({decoration:{border:X,color:o.default()},padding:j1.symmetric(1,0),child:new k1({children:F})})}}function R$6(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 ey1 extends S0{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)=>R$6(X.pubDate).length));return new P7({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=W0.of(K),{colors:W}=q,H=G?o.yellow:void 0,z=G?o.black:W.foreground,F=o.index(8),U=(D,B)=>new I1({width:B,child:X0.end([new e({text:new S(D,new f({color:F}))})])});return new d1({decoration:H?{color:H}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[new A0({child:new e({text:new S(X.title,new f({color:z})),overflow:"ellipsis",maxLines:1})}),new I1({width:2}),U(R$6(X.pubDate),Y)]})})}})}}class Jx1 extends p1{createState(){return new j$6}}class j$6 extends u1{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 e({text:new S("●",new f({color:this.isGreen?o.green:o.index(8),bold:!0})),maxLines:1})}}function qN8(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 BY.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 Qx1(J,Q,Y){return new e({text:new S(`${J}${Q}`,new f({color:Y})),maxLines:1})}function WN8(J,Q,Y,Z){return[Qx1("+",J,Z.success),O8.horizontal(1),Qx1("~",Q,Z.warning),O8.horizontal(1),Qx1("-",Y,Z.destructive)]}class n81 extends S0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((z)=>z.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((z)=>z.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],Z=new Set(Y),X=this.props.currentThreadID,G=[...Q].sort((z,F)=>{if(X){if(z.id===X)return-1;if(F.id===X)return 1}let U=Y.indexOf(z.id),D=Y.indexOf(F.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),V=qN8(G),K=Math.max(0,...V.map((z)=>z.description.timeAgo.length)),q=W0.of(J),W=new J0({padding:j1.symmetric(0,1),child:new b0({child:new e({text:new S("",new f({color:q.colors.foreground,dim:!0}),[new S("Ctrl+T",new f({color:o.blue,dim:!0})),new S(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new f({color:q.colors.foreground,dim:!0}))])})})});return new P7({items:V,getLabel:(z)=>z.title,onAccept:(z)=>this.props.onSelect?.(z.id),onDismiss:this.props.onDismiss,onSelectionChange:(z)=>{if(this.props.previewController){if(z)this.props.previewController.select(z.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:(z,F,U,D)=>{let B=W0.of(D),{colors:N}=B,w=F?o.yellow:void 0,M=F?o.black:N.foreground,L=o.index(8),O=(m,v)=>new I1({width:v,child:X0.end([new e({text:new S(m,new f({color:L}))})])}),A=this.props.threadViewStates[z.id],I=[],j=z.relationshipType==="handoff",C=new N81;if(z.depth>0){let m=[],v=z.ancestorsAreLast.slice(1);for(let d of v)m.push(new S(C.getAncestorPrefix(d),new f({color:C.connectorColor,dim:C.connectorDim})));let x=z.isLast?C.elbow:C.tee,g=C.getConnectorText(x);m.push(new S(g,new f({color:C.connectorColor,dim:C.connectorDim}))),I.push(new e({text:new S("",void 0,m)}))}let y=[],k=X===z.id?new S("(current) ",new f({color:o.green})):Z.has(z.id)?new S("(visited) ",new f({color:N.foreground,dim:!0})):null;if(k)y.push(new e({text:k}));if(A){if(A.state==="active"&&(A.interactionState==="tool-running"||A.interactionState==="handoff"||A.inferenceState==="running"))y.push(new Jx1),y.push(new I1({width:1}))}let b=z.title;if(z.relationshipType==="fork"){let m=b.match(/^Forked\((\d+)\): /);if(m)b=b.slice(m[0].length);else while(b.startsWith("Forked: "))b=b.slice(8);y.push(new e({text:new S("[fork] ",new f({color:o.blue}))}))}else if(j)y.push(new e({text:new S("[handoff] ",new f({color:o.index(208)}))}));if(y.push(new A0({child:new e({text:new S(b,new f({color:M})),overflow:"ellipsis",maxLines:1})})),y.push(new I1({width:2})),z.diffStats&&(z.diffStats.added>0||z.diffStats.changed>0||z.diffStats.deleted>0)){let m=F?{success:L,warning:L,destructive:L}:N;y.push(...WN8(z.diffStats.added,z.diffStats.changed,z.diffStats.deleted,m)),y.push(new I1({width:2}))}return y.push(O(z.description.timeAgo,K)),new d1({decoration:w?{color:w}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[...I,...y]})})}})}}class T$6 extends p1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new C$6}}class C$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}var P$6=30,HN8=30;class aj{}class oj{}class a81{}class o81{}class Yx1 extends p1{props;constructor(J){super();this.props=J}createState(){return new _$6}}class _$6 extends u1{highlightedIndex=0;controller=new Q7;focusNode;scrollController=new a4;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;nR(J,{top:Y,bottom:Z},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Q}=this.widget.props;if(!J)this.filteredClusters=[...Q];else this.filteredClusters=Q.filter((Y)=>Y.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof aj){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof oj){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof a81){let Q=this.filteredClusters[this.highlightedIndex];if(Q)this.widget.props.onAccept(Q);return"handled"}if(J instanceof o81)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Q)=>{if(J>=0&&J<this.filteredClusters.length){if(Q===1)this.highlightedIndex=J,this.setState();else if(Q===2){let Y=this.filteredClusters[J];if(Y)this.widget.props.onAccept(Y)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return;else if(this.highlightedIndex>0)this.highlightedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})};build(J){let{currentThreadID:Q}=this.widget.props,Y=W0.of(J),{colors:Z}=Y,V=t0.of(J).size.width>=HN8+P$6,K=y0.all(new j0(Z.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,W=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("Select a cluster",new f({color:o.yellow,bold:!0}))})}),H=new T3({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),z=new C3({shortcuts:new Map([[new p0("ArrowDown"),new aj],[new p0("ArrowUp"),new oj],[new p0("Tab"),new aj],[new p0("Tab",{shift:!0}),new oj],[new p0("n",{ctrl:!0}),new aj],[new p0("p",{ctrl:!0}),new oj],[new p0("Enter"),new a81],[new p0("Escape"),new o81]]),focusNode:this.focusNode,child:H}),F=new b5({actions:new Map([[aj,new h6(this.invoke)],[oj,new h6(this.invoke)],[a81,new h6(this.invoke)],[o81,new h6(this.invoke)]]),child:z}),U=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Z.foreground}))})}),new A0({child:F})]});this.itemContexts=[];let D=this.filteredClusters.map((O,A)=>{let I=A===this.highlightedIndex,j=Q?O.threads.some((b)=>b.id===Q):!1,C=I?o.yellow:void 0,y=I?o.black:o.default(),k=[new S(O.label,new f({color:y})),new S(` (${O.threads.length})`,new f({color:y,dim:!0}))];if(j)k.push(new S(" (current)",new f({color:I?o.black:o.green})));return new T$6(new H6({onClick:(b)=>this.handleItemClick(A,b.clickCount),child:new d1({decoration:C?{color:C}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S("",void 0,k)})})}),(b)=>{this.itemContexts[A]=b})}),B=new k1({children:D,crossAxisAlignment:"start"}),N=new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})}),w=q?q.threads.map((O)=>({id:O.id,title:O.title,parentID:O.parentID,updatedAt:O.updatedAt})):[],M=q?new d1({padding:j1.all(1),child:new IM({threads:w,autofocus:!1,offsetY:2})}):null,L;if(V){let O=M?new A0({child:M}):new I1({width:P$6});L=new X0({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,O]})}else{let O=[new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})})];if(M)O.push(new A0({child:M}));L=new k1({crossAxisAlignment:"stretch",children:O})}return new d1({decoration:{border:K,color:o.default()},padding:j1.symmetric(1,0),child:new k1({children:[W,U,new I1({height:1}),new A0({child:L})]})})}}class Zx1 extends S0{props;constructor(J){super();this.props=J}build(){return new b0({child:new e({text:new S("",void 0,[new S(`Forked to new thread:
|
|
5078
|
+
... (output truncated at ${zW} characters)`;X({success:B,output:M.trim(),error:!B?w.trim()||"Command failed":void 0,exitCode:D??void 0})}),H.on("error",(D)=>{clearTimeout(W);let B=D.message;if(q)B=`Command timed out after ${Y}ms`;else if(D.message.includes("operation was aborted")||D.name==="AbortError")B="The command was aborted";X({success:!1,output:z.join(""),error:B})})})}function QN8(J,Q){let{filePath:Y,interpreter:Z,extension:X}=J;if(process.platform==="win32")return ZN8(Y,Z?[...Z]:null,X,Q);else return YN8(Y,Z?[...Z]:null,X,Q)}function YN8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];else return[J,Z]}function ZN8(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]}}v1();aO();RX();b9();K3();MO();MG();N3();RQ();CH();UZ();n6();Fb();t9();MC();K0();var s$6=H0(iH(),1);import{writeFile as i$6}from"fs/promises";import n$6 from"path";v1();N3();class ty1{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.1768218876-g7c0d4d"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Za(Q,this.configService)}catch(Q){P.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 ZU extends p1{props;constructor(J){super();this.props=J}createState(){return new w$6}}class w$6 extends u1{_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 M$6 extends u1{controller=new Q7;focusNode=new r6({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=W0.of(J),{colors:Y,app:Z}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=y0.all(new j0(Y.foreground,1,"solid")),q=new T3({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]}),H=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,[new S("Command: ",new f({color:Y.foreground})),new S(this.widget.props.commandName,new f({color:o.yellow,bold:!0}))])})}),z=[];if(V)z.push(new S("Enter",new f({color:Z.keybind}))),z.push(new S(" to submit, ",new f({color:Y.foreground,dim:!0})));z.push(new S("Esc",new f({color:Z.keybind}))),z.push(new S(" to cancel",new f({color:Y.foreground,dim:!0})));let F=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,z)})});return new d1({decoration:{border:K,color:o.default()},padding:j1.all(1),child:new k1({children:[H,new I1({height:1}),W,new O8,F]})})}}class Bg extends p1{props;constructor(J){super();this.props=J}createState(){return new M$6}}import{isDeepStrictEqual as VN8}from"node:util";var XN8=/[\\/_ +.#"@[({&]/,$N8=/[\\/_ +.#"@[({&]/g,GN8=/[\s-]/,L$6=/[\s-]/g;function c81(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,z,F,U,D;while(W>=0){if(z=c81(J,Q,Y,Z,W+1,G+1,V),z>H){if(W===X)z*=1;else if(GN8.test(J.charAt(W-1))){if(z*=0.9,D=J.slice(X,W-1).match(L$6),D&&X>0)z*=0.999**D.length}else if(XN8.test(J.charAt(W-1))){if(z*=0.8,U=J.slice(X,W-1).match($N8),U&&X>0)z*=0.999**U.length}else if(z*=0.3,X>0)z*=0.999**(W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<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(F=c81(J,Q,Y,Z,W+1,G+2,V),F*0.1>z)z=F*0.1}if(z>H)H=z;W=Y.indexOf(q,W+1)}return V[K]=H,H}function d81(J){return J.toLowerCase().replace(L$6," ")}function O$6(J,Q){let Y=c81(J,Q,d81(J),d81(Q),0,0,{}),Z=Q.trim().split(/\s+/);if(Z.length>1){let X=0,G=0;for(let K of Z){let q=c81(J,K,d81(J),d81(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 ij{}class nj{}class l81{}class i81{}class A$6 extends p1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new I$6}}class I$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}function KN8(J,Q){if(J==="")return{matches:!0,score:1};let Y=O$6(Q,J);return{matches:Y>0.15,score:Y}}class P7 extends p1{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new E$6}}class E$6 extends u1{controller=new Q7;focusNode;scrollController=new a4;selectedIndex=0;itemContexts=[];cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new r6({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),Y4.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(!VN8(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 ij){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof nj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof l81){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 i81)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,...KN8(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;nR(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(),Y4.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=W0.of(J),{colors:Y}=Q,Z=this.getFilteredItems(),X=y0.all(new j0(Y.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new T3({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Y.foreground,border:null},maxLines:1}),K=new C3({shortcuts:new Map([[new p0("ArrowDown"),new ij],[new p0("ArrowUp"),new nj],[new p0("Tab"),new ij],[new p0("Tab",{shift:!0}),new nj],[new p0("n",{ctrl:!0}),new ij],[new p0("p",{ctrl:!0}),new nj],[new p0("Enter"),new l81],[new p0("Escape"),new i81]]),focusNode:this.focusNode,child:V}),q=new b5({actions:new Map([[ij,new h6(this.invoke)],[nj,new h6(this.invoke)],[l81,new h6(this.invoke)],[i81,new h6(this.invoke)]]),child:K}),W=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";H=new I1({height:10,child:new b0({child:new e({text:new S(B,new f({color:Y.foreground}))})})})}else if(Z.length===0&&this.widget.props.emptyStateText)H=new A0({child:new b0({child:new e({text:new S(this.widget.props.emptyStateText,new f({color:Y.foreground,dim:!0}))})})});else{let B=Z.map((N,w)=>{let M=w===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,O;if(this.widget.props.renderItem)O=this.widget.props.renderItem(N,M,L,J);else{let A=M?o.yellow:void 0,I=M?o.black:Y.foreground;O=new d1({decoration:A?{color:A}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S(this.widget.props.getLabel(N),new f({color:I,dim:L}))})})}return new A$6(new H6({onClick:(A)=>this.handleItemClick(w,A.clickCount),child:O}),(A)=>{this.itemContexts[w]=A})});H=new k1({children:B,crossAxisAlignment:"start"})}let z=new A0({child:new H6({onScroll:this.handleScroll,opaque:!1,child:new q4({controller:this.scrollController,autofocus:!1,child:H})})}),F=[];if(this.widget.props.title){let B=new d1({padding:j1.symmetric(1,0),child:new e({text:new S(this.widget.props.title,new f({color:o.yellow,bold:!0}))})});F.push(B)}if(F.push(W,new I1({height:1}),z),this.controller.text!==""){let B=Z.length>0?Z[this.selectedIndex]:void 0,N=B&&this.widget.props.buildDisabledReasonWidget?.(B);if(N)F.push(new d1({padding:j1.vertical(1),child:new b0({child:N})}));else F.push(new I1({height:3}))}if(this.widget.props.footer)F.push(this.widget.props.footer);return new d1({decoration:{border:X,color:o.default()},padding:j1.symmetric(1,0),child:new k1({children:F})})}}function R$6(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 ey1 extends S0{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)=>R$6(X.pubDate).length));return new P7({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=W0.of(K),{colors:W}=q,H=G?o.yellow:void 0,z=G?o.black:W.foreground,F=o.index(8),U=(D,B)=>new I1({width:B,child:X0.end([new e({text:new S(D,new f({color:F}))})])});return new d1({decoration:H?{color:H}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[new A0({child:new e({text:new S(X.title,new f({color:z})),overflow:"ellipsis",maxLines:1})}),new I1({width:2}),U(R$6(X.pubDate),Y)]})})}})}}class Jx1 extends p1{createState(){return new j$6}}class j$6 extends u1{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 e({text:new S("●",new f({color:this.isGreen?o.green:o.index(8),bold:!0})),maxLines:1})}}function qN8(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 BY.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 Qx1(J,Q,Y){return new e({text:new S(`${J}${Q}`,new f({color:Y})),maxLines:1})}function WN8(J,Q,Y,Z){return[Qx1("+",J,Z.success),O8.horizontal(1),Qx1("~",Q,Z.warning),O8.horizontal(1),Qx1("-",Y,Z.destructive)]}class n81 extends S0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((z)=>z.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((z)=>z.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],Z=new Set(Y),X=this.props.currentThreadID,G=[...Q].sort((z,F)=>{if(X){if(z.id===X)return-1;if(F.id===X)return 1}let U=Y.indexOf(z.id),D=Y.indexOf(F.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),V=qN8(G),K=Math.max(0,...V.map((z)=>z.description.timeAgo.length)),q=W0.of(J),W=new J0({padding:j1.symmetric(0,1),child:new b0({child:new e({text:new S("",new f({color:q.colors.foreground,dim:!0}),[new S("Ctrl+T",new f({color:o.blue,dim:!0})),new S(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new f({color:q.colors.foreground,dim:!0}))])})})});return new P7({items:V,getLabel:(z)=>z.title,onAccept:(z)=>this.props.onSelect?.(z.id),onDismiss:this.props.onDismiss,onSelectionChange:(z)=>{if(this.props.previewController){if(z)this.props.previewController.select(z.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:(z,F,U,D)=>{let B=W0.of(D),{colors:N}=B,w=F?o.yellow:void 0,M=F?o.black:N.foreground,L=o.index(8),O=(m,v)=>new I1({width:v,child:X0.end([new e({text:new S(m,new f({color:L}))})])}),A=this.props.threadViewStates[z.id],I=[],j=z.relationshipType==="handoff",C=new N81;if(z.depth>0){let m=[],v=z.ancestorsAreLast.slice(1);for(let d of v)m.push(new S(C.getAncestorPrefix(d),new f({color:C.connectorColor,dim:C.connectorDim})));let x=z.isLast?C.elbow:C.tee,g=C.getConnectorText(x);m.push(new S(g,new f({color:C.connectorColor,dim:C.connectorDim}))),I.push(new e({text:new S("",void 0,m)}))}let y=[],k=X===z.id?new S("(current) ",new f({color:o.green})):Z.has(z.id)?new S("(visited) ",new f({color:N.foreground,dim:!0})):null;if(k)y.push(new e({text:k}));if(A){if(A.state==="active"&&(A.interactionState==="tool-running"||A.interactionState==="handoff"||A.inferenceState==="running"))y.push(new Jx1),y.push(new I1({width:1}))}let b=z.title;if(z.relationshipType==="fork"){let m=b.match(/^Forked\((\d+)\): /);if(m)b=b.slice(m[0].length);else while(b.startsWith("Forked: "))b=b.slice(8);y.push(new e({text:new S("[fork] ",new f({color:o.blue}))}))}else if(j)y.push(new e({text:new S("[handoff] ",new f({color:o.index(208)}))}));if(y.push(new A0({child:new e({text:new S(b,new f({color:M})),overflow:"ellipsis",maxLines:1})})),y.push(new I1({width:2})),z.diffStats&&(z.diffStats.added>0||z.diffStats.changed>0||z.diffStats.deleted>0)){let m=F?{success:L,warning:L,destructive:L}:N;y.push(...WN8(z.diffStats.added,z.diffStats.changed,z.diffStats.deleted,m)),y.push(new I1({width:2}))}return y.push(O(z.description.timeAgo,K)),new d1({decoration:w?{color:w}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[...I,...y]})})}})}}class T$6 extends p1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new C$6}}class C$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}var P$6=30,HN8=30;class aj{}class oj{}class a81{}class o81{}class Yx1 extends p1{props;constructor(J){super();this.props=J}createState(){return new _$6}}class _$6 extends u1{highlightedIndex=0;controller=new Q7;focusNode;scrollController=new a4;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;nR(J,{top:Y,bottom:Z},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Q}=this.widget.props;if(!J)this.filteredClusters=[...Q];else this.filteredClusters=Q.filter((Y)=>Y.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof aj){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof oj){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof a81){let Q=this.filteredClusters[this.highlightedIndex];if(Q)this.widget.props.onAccept(Q);return"handled"}if(J instanceof o81)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Q)=>{if(J>=0&&J<this.filteredClusters.length){if(Q===1)this.highlightedIndex=J,this.setState();else if(Q===2){let Y=this.filteredClusters[J];if(Y)this.widget.props.onAccept(Y)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return;else if(this.highlightedIndex>0)this.highlightedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})};build(J){let{currentThreadID:Q}=this.widget.props,Y=W0.of(J),{colors:Z}=Y,V=t0.of(J).size.width>=HN8+P$6,K=y0.all(new j0(Z.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,W=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("Select a cluster",new f({color:o.yellow,bold:!0}))})}),H=new T3({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),z=new C3({shortcuts:new Map([[new p0("ArrowDown"),new aj],[new p0("ArrowUp"),new oj],[new p0("Tab"),new aj],[new p0("Tab",{shift:!0}),new oj],[new p0("n",{ctrl:!0}),new aj],[new p0("p",{ctrl:!0}),new oj],[new p0("Enter"),new a81],[new p0("Escape"),new o81]]),focusNode:this.focusNode,child:H}),F=new b5({actions:new Map([[aj,new h6(this.invoke)],[oj,new h6(this.invoke)],[a81,new h6(this.invoke)],[o81,new h6(this.invoke)]]),child:z}),U=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Z.foreground}))})}),new A0({child:F})]});this.itemContexts=[];let D=this.filteredClusters.map((O,A)=>{let I=A===this.highlightedIndex,j=Q?O.threads.some((b)=>b.id===Q):!1,C=I?o.yellow:void 0,y=I?o.black:o.default(),k=[new S(O.label,new f({color:y})),new S(` (${O.threads.length})`,new f({color:y,dim:!0}))];if(j)k.push(new S(" (current)",new f({color:I?o.black:o.green})));return new T$6(new H6({onClick:(b)=>this.handleItemClick(A,b.clickCount),child:new d1({decoration:C?{color:C}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S("",void 0,k)})})}),(b)=>{this.itemContexts[A]=b})}),B=new k1({children:D,crossAxisAlignment:"start"}),N=new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})}),w=q?q.threads.map((O)=>({id:O.id,title:O.title,parentID:O.parentID,updatedAt:O.updatedAt})):[],M=q?new d1({padding:j1.all(1),child:new IM({threads:w,autofocus:!1,offsetY:2})}):null,L;if(V){let O=M?new A0({child:M}):new I1({width:P$6});L=new X0({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,O]})}else{let O=[new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})})];if(M)O.push(new A0({child:M}));L=new k1({crossAxisAlignment:"stretch",children:O})}return new d1({decoration:{border:K,color:o.default()},padding:j1.symmetric(1,0),child:new k1({children:[W,U,new I1({height:1}),new A0({child:L})]})})}}class Zx1 extends S0{props;constructor(J){super();this.props=J}build(){return new b0({child:new e({text:new S("",void 0,[new S(`Forked to new thread:
|
|
5079
5079
|
|
|
5080
5080
|
`,new f({color:o.white,dim:!0})),new S(`"${this.props.newThreadTitle||"Untitled"}"`,new f({color:o.white}))]),textAlign:"center"})})}}v1();class S$6 extends u1{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){P.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){P.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=W0.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 P7({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,z)=>{let F=W?o.yellow:void 0,U=W?o.black:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let B=this.currentQuery.trim().toLowerCase();return new d1({decoration:F?{color:F}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S("",void 0,[new S("Create new label: ",new f({color:U})),new S(B,new f({color:U,bold:!0}))])})})}return new d1({decoration:F?{color:F}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S(q.name,new f({color:U}))})})},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 z=W.trim().toLowerCase();return z.length===0||q.name.includes(z)},sortItems:(q,W,H)=>{let z="__isCreateMarker"in q.item&&q.item.__isCreateMarker,F="__isCreateMarker"in W.item&&W.item.__isCreateMarker;if(z&&!F)return-1;if(!z&&F)return 1;return W.score-q.score}})}}class Xx1 extends p1{props;constructor(J){super();this.props=J}createState(){return new S$6}}class XU extends p1{props;constructor(J){super();this.props=J}createState(){return new k$6}}class k$6 extends u1{_spinner=new YJ;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=W0.of(J),{colors:Y}=Q,Z=y0.all(new j0(Y.foreground,1,"solid")),X=this._spinner.toBraille(),G=new e({textAlign:"center",text:new S("",void 0,[new S(X,new f({color:o.yellow})),new S(" ",void 0),new S(this.widget.props.message,new f({color:Y.foreground}))])}),K=[new A0({child:new k1({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[G]})})];if(this.widget.props.onAbort)K.push(new I1({height:2,child:new d1({padding:j1.symmetric(2,0),child:new e({text:new S("",new f({dim:!0}),[new S("Press ",new f({color:Y.foreground})),new S("Esc",new f({color:Y.info})),new S(" to cancel",new f({color:Y.foreground}))])})})}));let q=new d1({decoration:new N6(o.default(),Z),child:new I1({width:60,height:7,child:new k1({mainAxisAlignment:"start",children:K})})});if(this.widget.props.onAbort)return new A6({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}class RM extends p1{props;constructor(J){super();this.props=J}createState(){return new y$6}}class y$6 extends u1{scrollController=new a4;scrollAreaKey=new r7("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 DY}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=W0.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=F81(Y);return{title:H.title,type:H.type,description:H.description}})(),X=Z.type==="error"?o.red:o.yellow,G=y0.all(new j0(o.default(),1,"solid")),V=new d1({padding:j1.symmetric(1,0),child:new e({text:new S(Z.title,new f({color:X,bold:!0}))})}),K=this.isWidgetMessage(Y)?Y.widget:new e({text:new S(Z.description,new f({color:o.default()})),selectable:!0}),q=new A0({child:new tq({child:new d1({padding:j1.symmetric(1,0),child:new X0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new A0({child:new q4({controller:this.scrollController,autofocus:!0,child:K})}),new C9({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let H=this.scrollController.maxScrollExtent,z=this.scrollController.offset,F=this.getViewportHeight(),U=H+F;return{totalContentHeight:Math.max(U,0),viewportHeight:Math.max(F,1),scrollOffset:Math.max(z,0)}}})]})})})}),W=new d1({padding:j1.symmetric(1,0),child:new e({text:this.widget.props.onRetry?new S("",void 0,[new S("Press ",new f({color:o.default(),dim:!0})),new S("R",new f({color:o.yellow})),new S(" to retry, ",new f({color:o.default(),dim:!0})),new S("Esc",new f({color:o.yellow})),new S(" to cancel",new f({color:o.default(),dim:!0}))]):new S("Press any key to close",new f({color:o.default(),dim:!0,italic:!0}))})});return new A6({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 d1({decoration:{border:G,color:o.default()},padding:j1.all(1),child:new k1({mainAxisAlignment:"center",children:[V,new I1({height:1}),q,W]})})})}}class $x1 extends S0{build(){return new b0({child:new e({text:new S("",void 0,[new S(`✓ Thread Shared
|
|
5081
5081
|
|
|
@@ -5185,7 +5185,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
5185
5185
|
|
|
5186
5186
|
To use Sonnet 4.5, use large mode instead: amp --mode large
|
|
5187
5187
|
Learn more: https://ampcode.com/news/large-mode
|
|
5188
|
-
`),process.exit(1);if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")wG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")wG("experimental.agentMode",Q.mode)}async function vb1(J){try{await QI8(q51.dirname(kb1),{recursive:!0}),await YI8(kb1,J,"utf-8")}catch(Q){P.debug("Failed to save last thread ID",Q)}}async function $I8(){try{return(await xW6(kb1,"utf-8")).trim()}catch(J){return null}}function GI8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}var SW6=[{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??gZ,description:`Custom settings file path (overrides the default location ${gZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Cw})`},{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:J7(),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)",hidden:!0},{name:"mode",long:"mode",short:"m",type:"option",default:DO.SMART.key,description:`Set the agent mode (${dY().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:dY().map((J)=>J.mode).concat("large")},{name:"jmap",long:"jmap",type:"switch",default:!1,description:"Use experimental JMAP TUI (connects to server instead of running locally)",hidden:!0}],kW6=(J)=>("deprecated"in J)&&J.deprecated===!0,VI8=(J)=>("hidden"in J)&&J.hidden===!0,KI8=(J)=>("default"in J),qI8=(J)=>("default"in J)?J.default:void 0;function WI8(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 t6(vZ.unknownCommand(Y),1,V)}}var vW6=null;function Mb5(){return vW6}async function lg(J){let Q=await J.configService.getLatest(),Y=gT0(Q.settings["experimental.autoHandoff"]);return{...J,getThreadEnvironment:MR,vfs:UE0({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new DI(J.fileSystem),generateThreadTitle:Ri0,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>jQ(J.configService),internalHooks:mT0(Y)}}var W51=Q0.file(ZI8.homedir()),yb1=process.env.XDG_CONFIG_HOME?Q0.file(process.env.XDG_CONFIG_HOME):s1.joinPath(W51,".config");async function qJ(J,Q){sU0("0.0.
|
|
5188
|
+
`),process.exit(1);if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")wG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")wG("experimental.agentMode",Q.mode)}async function vb1(J){try{await QI8(q51.dirname(kb1),{recursive:!0}),await YI8(kb1,J,"utf-8")}catch(Q){P.debug("Failed to save last thread ID",Q)}}async function $I8(){try{return(await xW6(kb1,"utf-8")).trim()}catch(J){return null}}function GI8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}var SW6=[{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??gZ,description:`Custom settings file path (overrides the default location ${gZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Cw})`},{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:J7(),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)",hidden:!0},{name:"mode",long:"mode",short:"m",type:"option",default:DO.SMART.key,description:`Set the agent mode (${dY().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:dY().map((J)=>J.mode).concat("large")},{name:"jmap",long:"jmap",type:"switch",default:!1,description:"Use experimental JMAP TUI (connects to server instead of running locally)",hidden:!0}],kW6=(J)=>("deprecated"in J)&&J.deprecated===!0,VI8=(J)=>("hidden"in J)&&J.hidden===!0,KI8=(J)=>("default"in J),qI8=(J)=>("default"in J)?J.default:void 0;function WI8(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 t6(vZ.unknownCommand(Y),1,V)}}var vW6=null;function Mb5(){return vW6}async function lg(J){let Q=await J.configService.getLatest(),Y=gT0(Q.settings["experimental.autoHandoff"]);return{...J,getThreadEnvironment:MR,vfs:UE0({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new DI(J.fileSystem),generateThreadTitle:Ri0,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>jQ(J.configService),internalHooks:mT0(Y)}}var W51=Q0.file(ZI8.homedir()),yb1=process.env.XDG_CONFIG_HOME?Q0.file(process.env.XDG_CONFIG_HOME):s1.joinPath(W51,".config");async function qJ(J,Q){sU0("0.0.1768218876-g7c0d4d");let Y=gl({storage:J.settings,secretStorage:J.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:W51,userConfigDir:yb1}),Z=I0(jQ(Y).pipe(u4((g)=>g!=="pending"))),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (w91(),N91));X(Y);let G=await Y.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let{toolService:V,dispose:K}=ur0({configService:Y}),q=new Map,W=()=>q.clear(),H=new oF1(Y,J.settings.getWorkspaceRootPath()),z=_T0({configService:Y,filesystem:Q8}),F=iI0({configService:Y,trustStore:H,skillMCPServers:z.skillMCPServers,createOAuthProvider:async(g,d,h)=>{let i=`${g}:${d}`,u=q.get(i);if(u)return P.debug("Reusing existing OAuth provider for server",{serverName:g,serverUrl:d}),u;P.debug("Creating OAuth provider for server",{serverName:g,serverUrl:d});let V1=(async()=>{let O1=new OB(J.secrets),n=await O1.getClientInfo(g,d),w1=h?.scopes??n?.scopes,M1=x96();P.info("OAuth headless mode check",{useHeadless:M1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:v8.isTTY});let S1;if(M1)S1=J.executeMode?y96():k96(g);let B1=new lF1({storage:O1,serverName:g,serverUrl:d,clientId:h?.clientId??n?.clientId,clientSecret:h?.clientSecret??n?.clientSecret,authUrl:h?.authUrl??n?.authUrl,tokenUrl:h?.tokenUrl??n?.tokenUrl,scopes:w1,headlessAuthHandler:S1});return P.debug("OAuth provider created",{serverName:g,serverUrl:d,hasManualClientId:!!(h?.clientId??n?.clientId),willUseDCR:!(h?.clientId??n?.clientId),scopes:w1,headlessMode:M1,executeMode:J.executeMode}),B1})();return q.set(i,V1),V1}}),U=Rb({configService:Y,filesystem:Q8,spawn:XF}),{initializeToolProviders:D,startToolProviders:B}=await Promise.resolve().then(() => (_W6(),CW6)),N;if(J.executeMode){let g=await D({toolService:V,providers:[F,U],initialTimeout:15000});N=g.registrations;for(let[d,h]of g.initErrors)P.warn(`${d} provider initialization slow or failed:`,h)}else N=B({toolService:V,providers:[F,U]});if(Q.jetbrains)lO("JetBrains");else if(Q.ide&&F86())lO("VS Code");else if(Q.ide&&U86())lO("Neovim");if(J.executeMode)tU0(!0);let w,M=f9.status.pipe(q0((g)=>Boolean(g.connected&&g.authenticated)),q6()).subscribe((g)=>{if(g){if(!w)w=V.registerTool(ya0)}else w?.dispose(),w=void 0}),L;if(!J.executeMode){let g=await J.settings.get("fuzzy.alwaysIncludePaths")??[];L=new F01(process.cwd(),{alwaysIncludePaths:g},!0)}else L=new class extends F01{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(v8.write(`No API key found. Starting login flow...
|
|
5189
5189
|
`),!await HI8(J))await _w(),process.exit(1)}let O=await bT0({isDevelopment:!1}),A=await Z,I=R9(A)&&A.features.some((g)=>g.name===PX.LIVE_SYNC&&g.enabled),j=new AE1(O,Y,I),C=new WE1(O,{lazy:!0}),y=Q.notifications!==void 0?Q.notifications:!J.executeMode,k=nr0({playNotificationSound:async(g)=>{if(y){ir0(g);let d=o01(),h=bT1();if((!d||h)&&G.settings["notifications.system.enabled"]!==!1){if(g==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(g==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(o01()),threadService:j,configService:Y});P.info("Starting Amp background services");let b=Si0({threadService:j,threadHistoryService:C,configService:Y,isExtensionDevelopment:!1,liveSyncEnabled:I,fileChangeTrackerStorage:new DI(Q8),fileSystem:Q8,getServerStatus:()=>jQ(Y)}),c;f9.status.subscribe((g)=>{c=g});let m=new uq1({workspaceRoots:[Q0.file(process.cwd())],getCurrentFile:()=>{if(!c?.openFile)return;try{return Q0.parse(c.openFile)}catch(g){P.warn("Failed to parse current file URI",{uri:c.openFile,error:g});return}},getOpenFiles:()=>{if(!c?.visibleFiles?.length)return[];let g=c.openFile;return c.visibleFiles.filter((d)=>d!==g).map((d)=>{try{return Q0.parse(d)}catch(h){return P.warn("Failed to parse visible file URI",{uri:d,error:h}),null}}).filter((d)=>d!==null)}}),v=new Uk1,x={codebaseContextService:m,configService:Y,toolService:V,mcpService:F,skillService:z,toolboxService:U,trustStore:H,threadService:j,threadHistoryService:C,threadSyncService:b,threadStorage:O,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:L,notificationService:k,fileSystem:Q.jetbrains||Q.ide?HE0:Q8,terminal:v,serverStatus:A};return{...x,async asyncDispose(){if(x.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await x.mcpService.waitForAuthentication();for(let g of N.values())g.dispose();await x.mcpService.dispose(),W(),await x.threadService.asyncDispose(),await x.threadSyncService.flushFileChanges(),x.configService.unsubscribe(),K(),x.fuzzyServer.dispose(),x.threadSyncService.dispose(),x.settingsStorage[Symbol.dispose](),M.unsubscribe(),w?.dispose()}}}async function HI8(J){if(!J.executeMode){if(!await Wk1("Would you like to log in to Amp? [(y)es, (n)o]: "))return v8.write(`Login cancelled. Run the command again to retry.
|
|
5190
5190
|
`),!1}return await bW6(J)}async function bW6(J){let Q=JI8(32).toString("hex"),Y=await qk1(J.ampURL,Q),Z=new AbortController;try{await WH(Y,Z.signal)}catch(G){P.error("Error opening browser",{error:G})}let X=await qk1(J.ampURL,Q,!1);v8.write(`If your browser does not open automatically, visit:
|
|
5191
5191
|
|
|
@@ -5193,7 +5193,7 @@ ${Z0.blue.bold(X)}
|
|
|
5193
5193
|
|
|
5194
5194
|
`);try{return await PQ6(J.ampURL,Q,J.secrets,Z),v8.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(G){return P.error("Login failed",{error:G}),H2.write(`
|
|
5195
5195
|
Login failed: ${G instanceof Error?G.message:String(G)}
|
|
5196
|
-
`),!1}}function zI8(){let J=new U$().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)_R(),process.exit(0);let z=H.originalError??H;c06(z)}),J.option("-V, --version","Print the version number and exit",()=>{let z;try{z=`, ${dA(new Date("2026-01-
|
|
5196
|
+
`),!1}}function zI8(){let J=new U$().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)_R(),process.exit(0);let z=H.originalError??H;c06(z)}),J.option("-V, --version","Print the version number and exit",()=>{let z;try{z=`, ${dA(new Date("2026-01-12T11:59:31.016Z"))} ago`}catch{}v8.write(`0.0.1768218876-g7c0d4d (released 2026-01-12T11:59:31.016Z${z??""})
|
|
5197
5197
|
`),process.exit(0)}),J.addHelpText("after",q56()),J.configureHelp({formatHelp:W56}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let F=z.optsWithGlobals(),U=await X7(F);await BI8(U)}),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,z)=>{let F=z.optsWithGlobals(),U=await X7(F);await DI8(U,await GC1(F,U.settings))});let Q=async(H,z,F)=>{gl({storage:z.settings,secretStorage:z.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:W51,userConfigDir:yb1});let U={...z,executeMode:!1};await xb1(U,{...H,openThreadSwitcher:!0},F)},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,z)=>{let F=z.optsWithGlobals(),U=await X7(F);await yW6(F,U,z)});if(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,z)=>{let F=z.optsWithGlobals(),U=await X7(F);await EI8(F,U,z)}),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,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);if(z.pick)H2.write(`${Z0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
5198
5198
|
`);if(z.last||H||D.executeMode)await II8(U,D,H,F);else await Q(U,D,F)}),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,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await AI8(U,D,H,F)}),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,z)=>{let F=z.optsWithGlobals(),U=await X7(F);await yW6(F,U,z)}),Y.command("search <query>").alias("find").summary("Search threads").description(`Search for threads using a query DSL.
|
|
5199
5199
|
|
|
@@ -5205,11 +5205,11 @@ Query syntax:
|
|
|
5205
5205
|
|
|
5206
5206
|
All matching is case-insensitive. File paths use partial matching.`).option("-n, --limit <number>","Maximum number of threads to return","20").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await jI8(U,D,H,z.limit?parseInt(z.limit,10):20)}),Y.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support [message]","Share thread with Amp support for debugging").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await OI8(U,D,H,F,z.support)}),Y.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(H,z,F,U)=>{let D=U.optsWithGlobals(),B=await X7(D);await NI8(D,B,H,z,U)}),Y.command("archive <threadId>").summary("Archive a thread").description("Archive a thread to hide it from the thread switcher and navigation. Use --unarchive to restore.").option("--unarchive","Unarchive the thread instead of archiving").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await wI8(U,D,H,!z.unarchive)}),Y.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await MI8(U,D,H,F)}),Y.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await LI8(U,D,H,z,F)}),Ts0(Y,X7,QQ,qJ,H51,hM,W2),zY6(J,async(H,z)=>{let F=await X7(z);QQ(H,z);let U=await qJ(F,z);return{context:F,mcpService:U.mcpService,toolService:U.toolService,toolServices:U.toolService,configService:U.configService,cleanupTerminal:_R,asyncDispose:U.asyncDispose.bind(U)}}),tQ6(J,async(H)=>{let z=H.optsWithGlobals(),F=await X7(z);QQ(H,z);let U=await qJ(F,z);return{settings:F.settings,configService:U.configService,skillService:U.skillService,asyncDispose:U.asyncDispose.bind(U)}}),uQ6(J,async(H)=>{let z=H.optsWithGlobals();return await X7(z)}),yQ6(J,async(H)=>{let z=await X7(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(F)=>{QQ(F,H);let U=await qJ(z,H);return{mcpService:U.mcpService,settings:z.settings,asyncDispose:U.asyncDispose.bind(U)}}}}),process.env.AMP_EXPERIMENTAL_REMOTE==="1")cQ6(J,async(H,z)=>{let F=await X7(z);QQ(H,z);let U=gl({storage:F.settings,secretStorage:F.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:F.ampURL,homeDir:W51,userConfigDir:yb1}),D=await I0(jQ(U).pipe(u4((N)=>N!=="pending"))),B=R9(D)?D.features:[];return{ampURL:F.ampURL,secretStorage:F.secrets,features:B,asyncDispose:async()=>{}}});function X(H,z,F){let D=typeof H.description==="string"?H.description:F===void 0?H.description(!0):H.description(F),B=new hq(z,D),N=qI8(H);if(N)B.default(N);if(B.hidden=VI8(H)||kW6(H),"choices"in H)B.choices([...H.choices]);return B}for(let H of SW6)switch(H.type){case"flag":{J.addOption(X(H,`--${H.long}`)),J.addOption(X(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(X(H,`--${H.long}`,!0));break}default:{J.addOption(X(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let G=new hq("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(G);let V=new hq("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(V);let K=new hq("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(K);let q=new hq("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let W=new hq("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_EXPERIMENTAL_REMOTE==="1"){let H=new hq("--headless","Run in headless mode: listen for remote commands without showing TUI").default(!1);J.addOption(H)}if(process.env.AMP_CONNECT==="1"){let H=new hq("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return J.action(async(H,z)=>{let F=H,U=await X7(F);if(Object.keys(F).forEach((D)=>{let B=SW6.find((N)=>N.name===D);if(B&&kW6(B)&&!KI8(B))H2.write(Z0.yellow(`Warning: '--${D}' flag is deprecated
|
|
5207
5207
|
`))}),z.args.length>0)WI8(U,z);await xb1(U,F,z)}),C56(J),J}async function K51(J,Q){let{thread:Y,visibility:Z}=Q,X=Y?.id??nY(),G=await lg(J);if(Y)await J.threadStorage.set(X,Y);let V=await b8.getOrCreateForThread(G,X),K=await J.threadStorage.get(X);if(Q.agentMode&&!K?.agentMode&&(!K||K7(K)===0))await V.handle({type:"agent-mode",mode:Q.agentMode});if(Z)await J.threadSyncService.updateThreadMeta(X,R41(Z));let q=J.threadService.observe(X).subscribe(async(W)=>{if(H5(W,"assistant"))await vb1(X),q.unsubscribe()});return await V.resume(),V}async function xb1(J,Q,Y){let Z=E41(Q);if(Z instanceof Error)W2(Z.message);let X,G=null;if(Q.streamJsonInput)X="";else if(typeof Q.execute==="string"){X=Q.execute;let m=(await Fk1()).trimEnd();if(m)G=m}else X=(await Fk1()).trimEnd();if(Q.remote&&!J.executeMode)throw new t6("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new t6("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new t6("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new t6("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new t6("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new t6("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&X===""&&!Q.streamJsonInput&&!Q.jmap)throw new t6("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
5208
|
-
Or pipe via stdin: echo "your message" | amp --execute`);QQ(Y,Q);let V=await qJ(J,Q);vW6=V;let K=await lg(V),{serverStatus:q}=V,W=R9(q)?q.user.email:void 0,H=R9(q)?q.features:[],z=R9(q)?q.workspace:null,F=GI8(W);if((J.executeMode||Q.streamJson)&&A9(Q.mode)&&!F)throw new t6(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.headless){if(!H.some((x)=>x.name===PX.AMP_CONNECT&&x.enabled))throw new t6("Remote control features require the amp-connect feature flag. Contact support to enable.",1);let v=await V.secretStorage.get("apiKey",J.ampURL);if(!v)throw new t6("API key required for headless mode. Please run `amp login` first.",1);await S96({ampURL:J.ampURL,apiKey:v,version:"0.0.
|
|
5208
|
+
Or pipe via stdin: echo "your message" | amp --execute`);QQ(Y,Q);let V=await qJ(J,Q);vW6=V;let K=await lg(V),{serverStatus:q}=V,W=R9(q)?q.user.email:void 0,H=R9(q)?q.features:[],z=R9(q)?q.workspace:null,F=GI8(W);if((J.executeMode||Q.streamJson)&&A9(Q.mode)&&!F)throw new t6(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.headless){if(!H.some((x)=>x.name===PX.AMP_CONNECT&&x.enabled))throw new t6("Remote control features require the amp-connect feature flag. Contact support to enable.",1);let v=await V.secretStorage.get("apiKey",J.ampURL);if(!v)throw new t6("API key required for headless mode. Please run `amp login` first.",1);await S96({ampURL:J.ampURL,apiKey:v,version:"0.0.1768218876-g7c0d4d",dependencies:V,workerDeps:K}),await V.asyncDispose(),process.exit(0)}if(Q.jmap)throw new t6("JMAP mode is only available in development builds",1);let U=async(m)=>{let v=await xW6(m,"utf-8"),x=JSON.parse(v);if(!W3(x.id))throw new t6(vZ.invalidThreadId);return K51(V,{visibility:Z,agentMode:Q.mode,thread:x})},D=async(m)=>{if(!W3(m))throw new t6(vZ.invalidThreadId);try{let[x,g]=await Promise.all([S4.getThreadLinkInfo({thread:m},{config:V.configService}),S4.getUserInfo({},{config:V.configService})]);if(x.ok&&g.ok){let d=x.result.creatorUserID,h=g.result.id;if(d&&d!==h&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new t6(`Cannot resume thread created by another user.
|
|
5209
5209
|
|
|
5210
5210
|
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(x){if(x instanceof t6)throw x;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:x})}let v=await V.threadService.get(m)??void 0;return P.info(`[fetchAndStartThread] Loaded thread ${m}, agentMode: ${v?.agentMode??"undefined"}`),K51(V,{visibility:Z,agentMode:v?void 0:Q.mode,thread:v})},B=async()=>{try{if(Q.threadId)return D(Q.threadId);else return K51(V,{visibility:Z,agentMode:Q.mode})}catch(m){if(m instanceof t6)throw m;throw await Vf(m,Q.threadId),Error("handleError should have called process.exit()")}},N=async()=>{return K51(V,{visibility:Z,agentMode:Q.mode})};if(Q.format==="jsonl")H2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
5211
|
-
`),await _w(),process.exit(1);if(J.executeMode&&Q.remote)await pQ6(X,G,V.configService),await V.asyncDispose(),process.exit(0);let w=await B();if(J.executeMode)fQ6(V.mcpService,J.settings),await J66(w,w.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,F,Q.mode),await V.asyncDispose(),process.exit(0);let M=!1,L=!1,O=!1;if(Q.jetbrains||Q.ide){await qD0();let m=rO({jetbrainsOnly:Q.jetbrains});if(m.length===0){if(Q.jetbrains)L=!await V.configService.get("jetbrains.skipInstall")}else if(m.length===1){let v=m[0];if(v)f9.selectConfig(v)}else O=!0}let A=K61("0.0.
|
|
5212
|
-
`);let Y=!J.headless&&(!!J.execute||!process.stdout.isTTY&&!J.streamJson),Z=process.stdout.isTTY&&process.stderr.isTTY,X=await n96({...J,workspaceTrust:{current:!0,changes:OC},getHook:process.env.AMP_URL?(K,q)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let K=await vQ6(J.mcpConfig);X=bQ6(X,K)}let G=q51.dirname(X.getSettingsFilePath());lr0($h,G);let V=await X.get("url","global");if(!V)V=c3;if(!HH(V))P.info("Targeting custom Amp server",{ampURL:V});return X=cU0(X),{executeMode:Y,isTTY:Z,ampURL:V,settings:X,secrets:nQ6(await GC1(J,X))}}function FI8(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 UI8(){let J=FI8(process.argv);if(m06({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),XI8(P),P.info("Starting Amp CLI.",{version:"0.0.
|
|
5211
|
+
`),await _w(),process.exit(1);if(J.executeMode&&Q.remote)await pQ6(X,G,V.configService),await V.asyncDispose(),process.exit(0);let w=await B();if(J.executeMode)fQ6(V.mcpService,J.settings),await J66(w,w.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,F,Q.mode),await V.asyncDispose(),process.exit(0);let M=!1,L=!1,O=!1;if(Q.jetbrains||Q.ide){await qD0();let m=rO({jetbrainsOnly:Q.jetbrains});if(m.length===0){if(Q.jetbrains)L=!await V.configService.get("jetbrains.skipInstall")}else if(m.length===1){let v=m[0];if(v)f9.selectConfig(v)}else O=!0}let A=K61("0.0.1768218876-g7c0d4d",V.settingsStorage),I=new Se(V.threadStorage),j=T1.of([Q0.file(process.cwd())]),C=pq1(void 0,j),y=new I41(V.mcpService,J.settings.getWorkspaceRootPath());if(X)w.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let b=await(async()=>{try{let m=await S4.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(m.ok)return P.info("User free tier status:",m),m.result}catch(m){throw P.error("Failed to fetch free tier status:",m),m}})(),c=await rQ6();P.info("Loaded session state:",c),await Xv1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new G01,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,threadID:w.threadID,threadFuzzyIndexer:I,worker:w,workerDeps:K,skillService:K.skillService,configService:V.configService,internalAPIClient:S4,ampURL:J.ampURL,startNewThread:N,switchToThread:D,ideClient:f9,commandRegistry:C,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:y,showJetBrainsInstaller:L,showIdePicker:M,showIdePickerHint:O,openThreadSwitcher:Q.openThreadSwitcher,updateService:A,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:c,freeTierStatus:b,workspace:z??null,features:H,isDogfooding:F,threadDependencies:V,initialAgentMode:Y.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function X7(J){if(J.interactive)H2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
5212
|
+
`);let Y=!J.headless&&(!!J.execute||!process.stdout.isTTY&&!J.streamJson),Z=process.stdout.isTTY&&process.stderr.isTTY,X=await n96({...J,workspaceTrust:{current:!0,changes:OC},getHook:process.env.AMP_URL?(K,q)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let K=await vQ6(J.mcpConfig);X=bQ6(X,K)}let G=q51.dirname(X.getSettingsFilePath());lr0($h,G);let V=await X.get("url","global");if(!V)V=c3;if(!HH(V))P.info("Targeting custom Amp server",{ampURL:V});return X=cU0(X),{executeMode:Y,isTTY:Z,ampURL:V,settings:X,secrets:nQ6(await GC1(J,X))}}function FI8(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 UI8(){let J=FI8(process.argv);if(m06({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),XI8(P),P.info("Starting Amp CLI.",{version:"0.0.1768218876-g7c0d4d",buildTimestamp:"2026-01-12T11:59:31.016Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new t6(vZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await zI8().parseAsync(process.argv)}dr0().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await UI8().catch(Vf)});async function DI8(J,Q){let Y=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Y)await J.settings.set("url",process.env.AMP_URL,"global"),v8.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
5213
5213
|
`);else if(!HH(J.ampURL))v8.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
5214
5214
|
`);let Z=process.env.AMP_API_KEY;if(Z)v8.write(`API key found in environment variable, storing...
|
|
5215
5215
|
`),await Q.set("apiKey",Z,J.ampURL),v8.write(`API key successfully stored.
|
|
@@ -5223,7 +5223,7 @@ This thread belongs to a different user and cannot be continued for security rea
|
|
|
5223
5223
|
`);process.exit(0)}async function NI8(J,Q,Y,Z,X){QQ(X,J);let G=await qJ(Q,J);try{let V=ig(Y);if(!V)ng(Y);let K=V,q=Z.trim();if(q.length===0)W2("Thread name cannot be empty");if(q.length>256)W2("Thread name cannot exceed 256 characters");if(!(await hM(K,G)).messages.length)W2("Cannot rename an empty thread.");let H=await lg(G);await(await b8.getOrCreateForThread(H,K)).handle({type:"title",value:q}),P.info("GOT HERE"),await G.threadSyncService.sync(),P.info("GOT THERE"),v8.write(Z0.green(`✓ Thread ${K} renamed to "${q}"
|
|
5224
5224
|
`)),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose();let K=`Failed to rename thread: ${V instanceof Error?V.message:String(V)}`;W2(K)}}async function wI8(J,Q,Y,Z){let X=await qJ(Q,J);try{let G=ig(Y);if(!G)ng(Y);let V=await S4.archiveThread({thread:G,archived:Z},{config:X.configService});if(!V.ok)W2(`Failed to ${Z?"archive":"unarchive"} thread: ${V.error.message??V.error.code}`);v8.write(Z0.green(`✓ Thread ${Z?"archived":"unarchived"} successfully
|
|
5225
5225
|
`)),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose(),W2(`Failed to ${Z?"archive":"unarchive"} thread: ${G instanceof Error?G.message:String(G)}`)}}async function MI8(J,Q,Y,Z){QQ(Z,J);let X=await qJ(Q,J);try{let G=ig(Y);if(!G)ng(Y);let K=await hM(G,X),q=GR(K);v8.write(q+`
|
|
5226
|
-
`),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)}`;W2(V)}}async function LI8(J,Q,Y,Z,X){QQ(X,J);let G=await qJ(Q,J);try{let V=await H51(Y),K=await hM(V,G),q=Z.typing!==!1,W=parseInt(Z.wpm||"120",10),H=parseInt(Z.messageDelay||"1000",10),z=parseInt(Z.toolProgressDelay||"800",10),F=parseInt(Z.exitDelay||"3",10)*1000,U=Z.indicator!==!1,D=await lg(G),B=K.id;await G.threadStorage.set(B,K);let N=await b8.getOrCreateForThread(D,B);await N.resume();let w=_e.fromWorker(N),M=new Se(G.threadStorage),L=T1.of([Q0.file(process.cwd())]),O=pq1(void 0,L),A=new I41(G.mcpService,Q.settings.getWorkspaceRootPath()),I=K61("0.0.
|
|
5226
|
+
`),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)}`;W2(V)}}async function LI8(J,Q,Y,Z,X){QQ(X,J);let G=await qJ(Q,J);try{let V=await H51(Y),K=await hM(V,G),q=Z.typing!==!1,W=parseInt(Z.wpm||"120",10),H=parseInt(Z.messageDelay||"1000",10),z=parseInt(Z.toolProgressDelay||"800",10),F=parseInt(Z.exitDelay||"3",10)*1000,U=Z.indicator!==!1,D=await lg(G),B=K.id;await G.threadStorage.set(B,K);let N=await b8.getOrCreateForThread(D,B);await N.resume();let w=_e.fromWorker(N),M=new Se(G.threadStorage),L=T1.of([Q0.file(process.cwd())]),O=pq1(void 0,L),A=new I41(G.mcpService,Q.settings.getWorkspaceRootPath()),I=K61("0.0.1768218876-g7c0d4d",G.settingsStorage),j=Rb({configService:G.configService,filesystem:Q8,spawn:XF});await Xv1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new G01,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,threadID:B,threadFuzzyIndexer:M,worker:w,workerDeps:D,skillService:D.skillService,configService:G.configService,internalAPIClient:S4,ampURL:Q.ampURL,startNewThread:async()=>w,switchToThread:async()=>w,ideClient:f9,commandRegistry:O,mcpService:G.mcpService,toolboxService:j,mcpTrustHandler:A,showJetBrainsInstaller:!1,updateService:I,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:F,showIndicator:U},freeTierStatus:{canUseAmpFree:!0,isDailyGrantEnabled:!1},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await Vf(V,Y)}}async function OI8(J,Q,Y,Z,X){QQ(Z,J);let G=await qJ(Q,J);try{let V=ig(Y);if(!V)ng(Y);let K=V,q=await S4.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=E41(J,W);if(!H&&!X)W2("Must specify either --visibility or --support");if(H&&X)W2("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)W2(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,R41(H)),v8.write(Z0.green("✓ ")+`Thread ${K} visibility changed to ${H}.
|
|
5227
5227
|
`);if(X){await hM(K,G);let z=typeof X==="string"?X:void 0;await uR0(G.threadService,K,G.configService,z),v8.write(Z0.green("✓ ")+`Thread ${K} has been shared with Amp support. These thread reports will be aggregated and analysed.
|
|
5228
5228
|
`)}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),W2(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function AI8(J,Q,Y,Z){QQ(Z,J);let X=await qJ(Q,J),G=await lg(X);try{let V=await H51(Y),q=(await hM(V,X)).messages.length-1,W=await b8.getOrCreateForThread(G,V),H=await qR(W,X.threadSyncService,q);await Promise.all([X.threadSyncService.uploadThread(V),X.threadSyncService.uploadThread(H)]),await vb1(H),v8.write(`${H}
|
|
5229
5229
|
`),await X.asyncDispose(),process.exit(0)}catch(V){H2.write(`Error forking thread: ${V instanceof Error?V.message:String(V)}
|