@sourcegraph/amp 0.0.1764583899-g57f324 → 0.0.1764590491-gb0d62c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +16 -16
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -401,8 +401,8 @@ ${Q.comment}`:Q.comment}this.doc.range[2]=Q.offset;break}default:this.errors.pus
401
401
  `)+1;while(Q!==0)this.onNewLine(this.offset+Q),Q=this.source.indexOf(`
402
402
  `,Q)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(J){let Q=J.items[J.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,Q.value){let Y="end"in Q.value?Q.value.end:void 0;if((Array.isArray(Y)?Y[Y.length-1]:void 0)?.type==="comment")Y?.push(this.sourceToken);else J.items.push({start:[this.sourceToken]})}else if(Q.sep)Q.sep.push(this.sourceToken);else Q.start.push(this.sourceToken);return;case"space":case"comment":if(Q.value)J.items.push({start:[this.sourceToken]});else if(Q.sep)Q.sep.push(this.sourceToken);else{if(this.atIndentedComment(Q.start,J.indent)){let X=J.items[J.items.length-2]?.value?.end;if(Array.isArray(X)){Array.prototype.push.apply(X,Q.start),X.push(this.sourceToken),J.items.pop();return}}Q.start.push(this.sourceToken)}return}if(this.indent>=J.indent){let Y=!this.onKeyLine&&this.indent===J.indent,X=Y&&(Q.sep||Q.explicitKey)&&this.type!=="seq-item-ind",G=[];if(X&&Q.sep&&!Q.value){let Z=[];for(let q=0;q<Q.sep.length;++q){let V=Q.sep[q];switch(V.type){case"newline":Z.push(q);break;case"space":break;case"comment":if(V.indent>J.indent)Z.length=0;break;default:Z.length=0}}if(Z.length>=2)G=Q.sep.splice(Z[1])}switch(this.type){case"anchor":case"tag":if(X||Q.value)G.push(this.sourceToken),J.items.push({start:G}),this.onKeyLine=!0;else if(Q.sep)Q.sep.push(this.sourceToken);else Q.start.push(this.sourceToken);return;case"explicit-key-ind":if(!Q.sep&&!Q.explicitKey)Q.start.push(this.sourceToken),Q.explicitKey=!0;else if(X||Q.value)G.push(this.sourceToken),J.items.push({start:G,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(Q.explicitKey)if(!Q.sep)if(lU(Q.start,"newline"))Object.assign(Q,{key:null,sep:[this.sourceToken]});else{let Z=pP(Q.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Z,key:null,sep:[this.sourceToken]}]})}else if(Q.value)J.items.push({start:[],key:null,sep:[this.sourceToken]});else if(lU(Q.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:G,key:null,sep:[this.sourceToken]}]});else if(gj0(Q.key)&&!lU(Q.sep,"newline")){let Z=pP(Q.start),q=Q.key,V=Q.sep;V.push(this.sourceToken),delete Q.key,delete Q.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Z,key:q,sep:V}]})}else if(G.length>0)Q.sep=Q.sep.concat(G,this.sourceToken);else Q.sep.push(this.sourceToken);else if(!Q.sep)Object.assign(Q,{key:null,sep:[this.sourceToken]});else if(Q.value||X)J.items.push({start:G,key:null,sep:[this.sourceToken]});else if(lU(Q.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else Q.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let Z=this.flowScalar(this.type);if(X||Q.value)J.items.push({start:G,key:Z,sep:[]}),this.onKeyLine=!0;else if(Q.sep)this.stack.push(Z);else Object.assign(Q,{key:Z,sep:[]}),this.onKeyLine=!0;return}default:{let Z=this.startBlockValue(J);if(Z){if(Z.type==="block-seq"){if(!Q.explicitKey&&Q.sep&&!lU(Q.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(Y)J.items.push({start:G});this.stack.push(Z);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(J){let Q=J.items[J.items.length-1];switch(this.type){case"newline":if(Q.value){let Y="end"in Q.value?Q.value.end:void 0;if((Array.isArray(Y)?Y[Y.length-1]:void 0)?.type==="comment")Y?.push(this.sourceToken);else J.items.push({start:[this.sourceToken]})}else Q.start.push(this.sourceToken);return;case"space":case"comment":if(Q.value)J.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(Q.start,J.indent)){let X=J.items[J.items.length-2]?.value?.end;if(Array.isArray(X)){Array.prototype.push.apply(X,Q.start),X.push(this.sourceToken),J.items.pop();return}}Q.start.push(this.sourceToken)}return;case"anchor":case"tag":if(Q.value||this.indent<=J.indent)break;Q.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==J.indent)break;if(Q.value||lU(Q.start,"seq-item-ind"))J.items.push({start:[this.sourceToken]});else Q.start.push(this.sourceToken);return}if(this.indent>J.indent){let Y=this.startBlockValue(J);if(Y){this.stack.push(Y);return}}yield*this.pop(),yield*this.step()}*flowCollection(J){let Q=J.items[J.items.length-1];if(this.type==="flow-error-end"){let Y;do yield*this.pop(),Y=this.peek(1);while(Y&&Y.type==="flow-collection")}else if(J.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!Q||Q.sep)J.items.push({start:[this.sourceToken]});else Q.start.push(this.sourceToken);return;case"map-value-ind":if(!Q||Q.value)J.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Q.sep)Q.sep.push(this.sourceToken);else Object.assign(Q,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!Q||Q.value)J.items.push({start:[this.sourceToken]});else if(Q.sep)Q.sep.push(this.sourceToken);else Q.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let X=this.flowScalar(this.type);if(!Q||Q.value)J.items.push({start:[],key:X,sep:[]});else if(Q.sep)this.stack.push(X);else Object.assign(Q,{key:X,sep:[]});return}case"flow-map-end":case"flow-seq-end":J.end.push(this.sourceToken);return}let Y=this.startBlockValue(J);if(Y)this.stack.push(Y);else yield*this.pop(),yield*this.step()}else{let Y=this.peek(2);if(Y.type==="block-map"&&(this.type==="map-value-ind"&&Y.indent===J.indent||this.type==="newline"&&!Y.items[Y.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&Y.type!=="flow-collection"){let X=tr(Y),G=pP(X);bj0(J);let Z=J.end.splice(1,J.end.length);Z.push(this.sourceToken);let q={type:"block-map",offset:J.offset,indent:J.indent,items:[{start:G,key:J,sep:Z}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=q}else yield*this.lineEnd(J)}}flowScalar(J){if(this.onNewLine){let Q=this.source.indexOf(`
403
403
  `)+1;while(Q!==0)this.onNewLine(this.offset+Q),Q=this.source.indexOf(`
404
- `,Q)+1}return{type:J,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(J){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let Q=tr(J),Y=pP(Q);return Y.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let Q=tr(J),Y=pP(Q);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(J,Q){if(this.type!=="comment")return!1;if(this.indent<=Q)return!1;return J.every((Y)=>Y.type==="newline"||Y.type==="space")}*documentEnd(J){if(this.type!=="doc-mode"){if(J.end)J.end.push(this.sourceToken);else J.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(J){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(J.end)J.end.push(this.sourceToken);else J.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}hC4.Parser=mj0});var lj0=f((iC4)=>{var uj0=XD1(),gC4=nv(),ev=av(),mC4=FN1(),uC4=c9(),pC4=FD1(),pj0=UD1();function dj0(J){let Q=J.prettyErrors!==!1;return{lineCounter:J.lineCounter||Q&&new pC4.LineCounter||null,prettyErrors:Q}}function dC4(J,Q={}){let{lineCounter:Y,prettyErrors:X}=dj0(Q),G=new pj0.Parser(Y?.addNewLine),Z=new uj0.Composer(Q),q=Array.from(Z.compose(G.parse(J)));if(X&&Y)for(let V of q)V.errors.forEach(ev.prettifyError(J,Y)),V.warnings.forEach(ev.prettifyError(J,Y));if(q.length>0)return q;return Object.assign([],{empty:!0},Z.streamInfo())}function cj0(J,Q={}){let{lineCounter:Y,prettyErrors:X}=dj0(Q),G=new pj0.Parser(Y?.addNewLine),Z=new uj0.Composer(Q),q=null;for(let V of Z.compose(G.parse(J),!0,J.length))if(!q)q=V;else if(q.options.logLevel!=="silent"){q.errors.push(new ev.YAMLParseError(V.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&Y)q.errors.forEach(ev.prettifyError(J,Y)),q.warnings.forEach(ev.prettifyError(J,Y));return q}function cC4(J,Q,Y){let X=void 0;if(typeof Q==="function")X=Q;else if(Y===void 0&&Q&&typeof Q==="object")Y=Q;let G=cj0(J,Y);if(!G)return null;if(G.warnings.forEach((Z)=>mC4.warn(G.options.logLevel,Z)),G.errors.length>0)if(G.options.logLevel!=="silent")throw G.errors[0];else G.errors=[];return G.toJS(Object.assign({reviver:X},Y))}function lC4(J,Q,Y){let X=null;if(typeof Q==="function"||Array.isArray(Q))X=Q;else if(Y===void 0&&Q)Y=Q;if(typeof Y==="string")Y=Y.length;if(typeof Y==="number"){let G=Math.round(Y);Y=G<1?void 0:G>8?{indent:8}:{indent:G}}if(J===void 0){let{keepUndefined:G}=Y??Q??{};if(!G)return}if(uC4.isDocument(J)&&!X)return J.toString(Y);return new gC4.Document(J,X,Y).toString(Y)}iC4.parse=cC4;iC4.parseAllDocuments=dC4;iC4.parseDocument=cj0;iC4.stringify=lC4});var dP=f((Kj4)=>{var sC4=XD1(),tC4=nv(),eC4=uN1(),BD1=av(),Jj4=kv(),iU=c9(),Qj4=uU(),Yj4=a2(),Xj4=dU(),Gj4=cU(),Zj4=rr(),$j4=zD1(),qj4=FD1(),Vj4=UD1(),er=lj0(),ij0=Sv();Kj4.Composer=sC4.Composer;Kj4.Document=tC4.Document;Kj4.Schema=eC4.Schema;Kj4.YAMLError=BD1.YAMLError;Kj4.YAMLParseError=BD1.YAMLParseError;Kj4.YAMLWarning=BD1.YAMLWarning;Kj4.Alias=Jj4.Alias;Kj4.isAlias=iU.isAlias;Kj4.isCollection=iU.isCollection;Kj4.isDocument=iU.isDocument;Kj4.isMap=iU.isMap;Kj4.isNode=iU.isNode;Kj4.isPair=iU.isPair;Kj4.isScalar=iU.isScalar;Kj4.isSeq=iU.isSeq;Kj4.Pair=Qj4.Pair;Kj4.Scalar=Yj4.Scalar;Kj4.YAMLMap=Xj4.YAMLMap;Kj4.YAMLSeq=Gj4.YAMLSeq;Kj4.CST=Zj4;Kj4.Lexer=$j4.Lexer;Kj4.LineCounter=qj4.LineCounter;Kj4.Parser=Vj4.Parser;Kj4.parse=er.parse;Kj4.parseAllDocuments=er.parseAllDocuments;Kj4.parseDocument=er.parseDocument;Kj4.stringify=er.stringify;Kj4.visit=ij0.visit;Kj4.visitAsync=ij0.visitAsync});function nj0(J,Q){if(Q.length===0)return X0.of([]);return new X0((Y)=>{let X=new _Y,G=()=>{Y.next(Array.from(X.keys()).toSorted((V,K)=>V.toString().localeCompare(K.toString())))},Z=new AbortController;Promise.all(Q.map(async(V)=>{if(pI0(V))return J.findFiles(V,{signal:Z.signal});try{return await J.stat(V),[V]}catch(K){if(K instanceof WJ)return[];if(typeof K==="object"&&K!==null&&"code"in K&&K.code==="ELOOP")return h.warn("Infinite symlink loop detected in guidance file",{file:V.toString()}),[];throw K}})).then((V)=>{for(let K of V.flat())X.add(K);G()}).catch((V)=>{if(!Z.signal.aborted)Z.abort();if(!xQ(V))Y.error(V)});let q=Q.map((V)=>J.watch(V,{ignoreChanges:!0}).subscribe({next:(K)=>{if(K.type==="create"||K.type==="change")X.add(K.uri);else if(K.type==="delete")X.delete(K.uri);G()}}));return()=>{Z.abort();for(let V of q)V.unsubscribe()}})}var aj0=N1(()=>{r0();FH();L0();a$();fQ()});function Js(J){let Q=/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/,Y=J.match(Q);if(!Y)return{frontMatter:null,content:J.trim()};let[,X,G]=Y,Z=null;try{let q=rj0.default.parse(X?.trim()??"");if(q&&typeof q==="object")Z={...q,globs:Array.isArray(q.globs)?q.globs:q.globs&&typeof q.globs==="string"?[q.globs]:void 0}}catch(q){return h.error("Invalid YAML front matter in guidance file",{error:q}),{frontMatter:null,content:J.trim()}}return{frontMatter:Z,content:(G??"").trim()}}function sj0(J,Q,Y){if(!J||!J.globs||J.globs.length===0)return!0;Y=l4(Y);let X=Q.map((G)=>l4(G));for(let G of J.globs){let Z=G;if(G.startsWith("./")||G.startsWith("../"))Z=_E(o0.dirname(Y).path,G);else if(!G.startsWith("/")&&!G.startsWith("**/"))Z=`**/${G}`;let q=oj0.default(Z,{dot:!0});for(let V of X)if(q(ZJ(V)))return!0}return!1}var oj0,rj0;var ND1=N1(()=>{G4();kE();L0();oj0=N6(RM(),1),rj0=N6(dP(),1)});async function tj0(J,Q,Y,X,G){let Z=[];Y=mj4(Y);let q=/@([a-zA-Z0-9._~/*?[\]{}\\,-]+)/g,V;while((V=q.exec(Y))!==null){let K=V[1];if(!K)continue;K=K.replace(/[.,;!?)]+$/,""),K=K.replace(/\\(\*)/g,"$1");let W=gj4(K,Q);if(W){h.warn("Ignoring glob pattern:",W);continue}try{let H=await uj4(J,Q,K,X,G);Z.push(...H)}catch(H){continue}}return Z}function gj4(J,Q){let Y=Q.fsPath;if(J.startsWith("**/")||["*","**","/*","/**","","/"].includes(J)||J.includes("__dangerous_glob_canary__"))return`Ignoring glob pattern "${J}" in ${Y}, because it may cause performance issues.`;return null}function mj4(J){let Q=J.replace(/```[\s\S]*?```/g,"");return Q=Q.replace(/`[^`]*`/g,""),Q=Q.replace(/<code[^>]*>[\s\S]*?<\/code>/gi,""),Q}async function uj4(J,Q,Y,X,G){let Z,q;if(Y.startsWith("~/")){if(X.homeDir===null)return[];let K=Y.slice(2),{basePart:W,patternPart:H}=DD1(K);Z=W?o0.joinPath(X.homeDir,W):l4(X.homeDir),q=H}else if(Y.startsWith("/")){let K=Y.slice(1),{basePart:W,patternPart:H}=DD1(K);Z=W?o0.joinPath(d0.file("/"),W):d0.file("/"),q=H}else{let K=o0.dirname(Q),{basePart:W,patternPart:H}=DD1(Y);Z=W?o0.joinPath(K,W):K,q=H}if(ej0(q))try{let W=await J.findFiles({base:Z,pattern:q},{signal:G,maxResults:1000});if(W.length>=1000)h.warn("Truncating very large glob expansion result",`Limit (1000) exceeded for '${Y}' in ${Q.fsPath}.`);return W}catch(K){return[]}if(!q)return[];return[o0.joinPath(Z,q)]}function ej0(J){return J.includes("*")||J.includes("?")||J.includes("[")||J.includes("{")}function DD1(J){let Q=J.split("/"),Y=[],X=[],G=!1;for(let Z of Q)if(G||ej0(Z))G=!0,X.push(Z);else Y.push(Z);if(!G){if(Y.length===0)return{basePart:null,patternPart:""};let Z=Y.pop();return{basePart:Y.length===0?null:Y.join("/"),patternPart:Z}}return{basePart:Y.length===0?null:Y.join("/"),patternPart:X.join("/")}}var JS0=N1(()=>{G4();L0()});async function QS0({filesystem:J},Q,Y,X=[],G){let Z=[],q=new _Y,V=new _Y,K=new L2,W=[];async function H(L,A=!1){let E=l4(L.uri);if(q.has(E))return null;if(V.has(E))return null;V.add(E);try{let P=await J.readFile(E,{signal:G}),{frontMatter:I,content:T}=Js(P),S=sj0(I,X,E),y={...L,type:A?L.type:"mentioned",content:T,frontMatter:I,exclude:!S,"~debug":{mentionedBy:K.has(E)?[K.get(E)]:void 0}};q.add(E),Z.push(y);let x=await tj0(J,E,P,Y,G);for(let g of x){if(!K.has(g))K.set(g,L.uri);let p={uri:j6(g),type:"mentioned"},b=await H(p,!1);if(b)W.push({file:b,afterFile:L.uri})}return y}catch(P){if(P instanceof Error&&P.message.includes("EISDIR"))return h.debug("Guidance file is a directory, skipping",{uri:L.uri}),null;if(ZQ(P))h.debug("Guidance file not found (expected)",{uri:L.uri});else h.error("Error resolving guidance file",{uri:L.uri,error:P});return null}finally{V.delete(E)}}for(let L of MD1(Q))await H(L,!0);let z=[],U=new Set;function N(L){if(U.has(L.uri))return;z.push(L),U.add(L.uri);let A=W.filter((E)=>E.afterFile===L.uri);for(let E of A)N(E.file)}let M=Z.filter((L)=>L.type!=="mentioned");for(let L of M)N(L);return z}var YS0=N1(()=>{G4();L0();a$();fQ();ND1();D3();JS0()});function pj4(J){return{homeDir:J.userConfigDir?j6(J.userConfigDir):null}}function LD1(J){if(J.path==="/"||J.path==="")return!0;let Q=J.fsPath;if(Q==="/"||Q==="/Users"||Q==="/home"||/^[A-Z]:[\\/?]?$/.test(Q))return!0;if(["/proc","/sys","/dev"].includes(Q))return!0;return!1}function dj4({filesystem:J,configService:Q},Y){let X=Q.config.pipe(q6((G)=>!!G.settings["guidanceFiles.specs"]),_4());return d8(oZ1(J),Y?Y:X0.of(null),Q.workspaceRoots,X).pipe(k4(([G,Z,q,V])=>{let K=q??Z?.env?.initial?.trees?.map((z)=>z.uri).filter((z)=>z!==void 0).map((z)=>l4(z));if(!K)K=[];let W=[];W.push(...K);for(let z of K){let U=o0.dirname(z);while(U){if(LD1(U))break;W.push(U);let N=o0.dirname(U);if(o0.equalURIs(N,U))break;U=N}}if(Q.userConfigDir)W.push(o0.joinPath(Q.userConfigDir,"amp")),W.push(Q.userConfigDir);let H=W.flatMap((z)=>Jf.map((U)=>o0.joinPath(z,U)));if(V)H.push(...K.map((z)=>({base:z,pattern:GS0})));return nj0(G,H).pipe(q6((z)=>{let U=[],N=new Set;for(let M of z){let L=o0.dirname(M).toString(),A=o0.basename(M);if(A.toLowerCase().endsWith(".spec.md")){if(K.some((T)=>o0.hasPrefix(M,T)))U.push({uri:j6(M),type:"project"});continue}if(N.has(L))continue;let E=Jf.findIndex((T)=>T===A);if(E===-1)continue;let P=!1,I=o0.dirname(M);for(let T=0;T<E;T++){let S=Jf[T];if(z.some((y)=>{let x=o0.equalURIs(o0.dirname(y),I),g=o0.basename(y)===S;return x&&g})){P=!0;break}}if(P)continue;if(N.add(L),K.some((T)=>o0.hasPrefix(M,T))){U.push({uri:j6(M),type:"project"});continue}if(Q.userConfigDir&&o0.hasPrefix(M,Q.userConfigDir)){U.push({uri:j6(M),type:"user"});continue}U.push({uri:j6(M),type:"parent"})}return U}))}))}function cj4({filesystem:J,configService:Q},Y){let X=Q.config.pipe(q6((Z)=>!!Z.settings["guidanceFiles.specs"]),_4());function G(Z){let q=new Set,V=[];for(let K of Z){let W=o0.dirname(K).toString();if(!q.has(W))q.add(W),V.push(W)}return V.join(",")}return d8(Y.pipe(q6((Z)=>({thread:Z,readFiles:ZS0(Z)})),_4((Z,q)=>G(Z.readFiles)===G(q.readFiles))),oZ1(J),Q.workspaceRoots,X).pipe(cF(async([{readFiles:Z},q,V,K],W)=>{if(!V)V=[];let H=new _Y;for(let U of Z){let N=o0.dirname(U);while(!H.has(N)&&V.some((M)=>o0.hasPrefix(N,M)&&!o0.equalURIs(M,N)))H.add(N),N=o0.dirname(N)}let z=(await Promise.all(Array.from(H.keys()).map(async(U)=>{for(let N of Jf)try{let M=o0.joinPath(U,N);return await q.stat(M,{signal:W}),{uri:j6(M),type:"subtree"}}catch(M){if(typeof M==="object"&&M!==null&&"code"in M&&M.code==="ELOOP")h.warn("Infinite symlink loop detected in guidance file",{file:o0.joinPath(U,N).toString()});continue}return null}))).filter((U)=>U!==null);if(K){let U=await Promise.all(Array.from(H.keys()).map(async(N)=>{return await q.findFiles({base:N,pattern:GS0})}));z.push(...U.flat().map((N)=>({uri:j6(N),type:"subtree"})))}return z}))}function ZS0(J){let Q=[];for(let Y of J.messages)if(Y.role==="assistant"){for(let X of Y.content)if(X.type==="tool_use"&&(X.name===d6||X.name===f$1)){let G=eW(J,X.id);if(G&&G.run.status==="done"){let Z=G.run.result;if(typeof Z==="object"&&Z.absolutePath)Q.push(d0.file(Z.absolutePath))}}}for(let Y of J.messages)if(Y.role==="user"&&Y.fileMentions)for(let X of Y.fileMentions.files)Q.push(X.uri);return Q}function lj4(J){let Q=new Set;for(let Y of J.messages)if(Y.role==="assistant"){for(let X of Y.content)if(X.type==="tool_use"){let G=X.name===d6||X.name===f$1,Z=X.name===N5;if(G||Z){let q=eW(J,X.id);if(q&&q.run.status==="done"){let V=q.run.result;if(typeof V==="object"&&V!==null&&"discoveredGuidanceFiles"in V&&Array.isArray(V.discoveredGuidanceFiles)&&V.discoveredGuidanceFiles.length>0)for(let K of V.discoveredGuidanceFiles)Q.add(K.uri)}}}}else if(Y.role==="user"&&Y.discoveredGuidanceFiles)for(let X of Y.discoveredGuidanceFiles)Q.add(X.uri);return Q}async function Ys(J,Q,Y){let[X,G]=await Promise.all([M6(dj4(J,X0.of({env:Q.env})),Y),M6(cj4(J,X0.of(Q)),Y)]);return Y?.throwIfAborted(),(await QS0({filesystem:aZ1(J.filesystem)?await M6(J.filesystem):J.filesystem},MD1([...X,...G]),pj4(J.configService),ZS0(Q),Y)).filter((q)=>!q.exclude)}function MD1(J){return J.toSorted((Q,Y)=>{let X=XS0[Q.type]-XS0[Y.type];if(X!==0)return X;return Q.uri.localeCompare(Y.uri)})}function Qf(J){let Q=d0.parse(J),Y=o0.basename(Q)||"AGENTS.md",X=o0.basename(o0.dirname(Q));return X?`${X}/${Y}`:Y}async function cP(J,Q,Y,X,G,Z){let q=X?lj4(X):new Set;if(G)for(let W of G)q.add(W);let V=[],K=o0.dirname(Q);while(Y.some((W)=>o0.hasPrefix(K,W)&&!o0.equalURIs(W,K))){Z?.throwIfAborted();for(let H of Jf){let z=o0.joinPath(K,H),U=j6(z);if(q.has(U))break;try{await J.stat(z,{signal:Z});let M=(await J.readFile(z,{signal:Z})).split(`
405
- `).length;V.push({uri:U,lineCount:M});break}catch{continue}}let W=o0.dirname(K);if(o0.equalURIs(W,K))break;K=W}return V}var Qs="AGENT.md",L9="AGENTS.md",Jf,GS0="*.spec.md",XS0;var D3=N1(()=>{G4();r0();L0();a$();aj0();t8();N4();YS0();Jf=[L9,"Agents.md","agents.md",Qs,"Agent.md","agent.md","CLAUDE.md"];XS0={user:0,project:1,parent:2,subtree:3}});function nj4(J){let Q=J.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!Q||!Q[1]||!Q[2])throw Error("SKILL.md must have YAML frontmatter");let Y=$S0.default.parse(Q[1]);if(!Y.name||!Y.description)throw Error("SKILL.md frontmatter must include name and description");return{frontmatter:Y,content:Q[2]}}async function aj4(J,Q,Y){let X=[],G=5;async function Z(q,V){if(V>5)return;try{let K=await J.readdir(q,{signal:Y});for(let W of K){let H=o0.basename(W.uri);if(W.isDirectory&&(H==="node_modules"||H===".git"))continue;if(W.isDirectory)await Z(W.uri,V+1);else if(ij4.test(H))X.push(W.uri)}}catch(K){h.debug("Failed to scan skill directory",{path:q.toString(),error:K})}}return await Z(Q,0),X}async function Yf(J,Q,Y,X,G,Z="skill"){try{await J.stat(Q,{signal:G});let q=await aj4(J,Q,G);for(let V of q){let K=o0.dirname(V),W=j6(K);if(!Y.has(W)){Y.add(W);try{let H=await J.readFile(V,{signal:G}),{frontmatter:z,content:U}=nj4(H);if(z.isolatedContext)continue;X.push({name:z.name,description:z.description,frontmatter:z,content:U,baseDir:j6(K)})}catch(H){h.warn(`Failed to load ${Z}`,{path:j6(V),error:H})}}}}catch(q){h.debug(`Failed to process ${Z} directory`,{path:Q.toString(),error:q})}}async function Xf(J,Q,Y){let X=[],G=new Set,Z=typeof process<"u"&&process.env.HOME?process.env.HOME:null;if(Z){let H=o0.joinPath(d0.file(Z),".claude","skills");await Yf(J,H,G,X,Y,"skill");let z=o0.joinPath(d0.file(Z),".claude","plugins","cache");await Yf(J,z,G,X,Y,"plugin skill");let U=o0.joinPath(d0.file(Z),".claude","plugins","marketplaces");await Yf(J,U,G,X,Y,"marketplace plugin skill")}let q=new Set;for(let H of Q){let z=sJ(H);q.add(j6(z));while(z){if(LD1(z))break;q.add(j6(z));let U=o0.dirname(z);if(o0.equalURIs(U,z))break;z=U}}let V=typeof process<"u"&&process.env.AMP_TOOLBOX?process.env.AMP_TOOLBOX:void 0,K=typeof process<"u"&&process.env.HOME?`${process.env.HOME}/.config/amp/tools`:null,W=V?V.split(":").filter(Boolean):K?[K]:[];for(let H of W){let z=d0.file(H);await Yf(J,z,G,X,Y,"skill from toolbox")}h.info("Scanning workspace roots for skills",{searchRoots:[...q],workspaceRoots:Q});for(let H of q){let z=sJ(H),U=o0.joinPath(z,".claude","skills");await Yf(J,U,G,X,Y,"skill")}return h.info("Finished loading skills",{totalSkills:X.length,skillNames:X.map((H)=>H.name),skillBaseDirs:X.map((H)=>H.baseDir)}),X}function qS0(J){if(J.length===0)return null;let Q=J.filter((Y)=>!Y.frontmatter["disable-model-invocation"]).map((Y)=>`- **${Y.name}**: ${Y.description}`).join(`
404
+ `,Q)+1}return{type:J,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(J){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let Q=tr(J),Y=pP(Q);return Y.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let Q=tr(J),Y=pP(Q);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(J,Q){if(this.type!=="comment")return!1;if(this.indent<=Q)return!1;return J.every((Y)=>Y.type==="newline"||Y.type==="space")}*documentEnd(J){if(this.type!=="doc-mode"){if(J.end)J.end.push(this.sourceToken);else J.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(J){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(J.end)J.end.push(this.sourceToken);else J.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}hC4.Parser=mj0});var lj0=f((iC4)=>{var uj0=XD1(),gC4=nv(),ev=av(),mC4=FN1(),uC4=c9(),pC4=FD1(),pj0=UD1();function dj0(J){let Q=J.prettyErrors!==!1;return{lineCounter:J.lineCounter||Q&&new pC4.LineCounter||null,prettyErrors:Q}}function dC4(J,Q={}){let{lineCounter:Y,prettyErrors:X}=dj0(Q),G=new pj0.Parser(Y?.addNewLine),Z=new uj0.Composer(Q),q=Array.from(Z.compose(G.parse(J)));if(X&&Y)for(let V of q)V.errors.forEach(ev.prettifyError(J,Y)),V.warnings.forEach(ev.prettifyError(J,Y));if(q.length>0)return q;return Object.assign([],{empty:!0},Z.streamInfo())}function cj0(J,Q={}){let{lineCounter:Y,prettyErrors:X}=dj0(Q),G=new pj0.Parser(Y?.addNewLine),Z=new uj0.Composer(Q),q=null;for(let V of Z.compose(G.parse(J),!0,J.length))if(!q)q=V;else if(q.options.logLevel!=="silent"){q.errors.push(new ev.YAMLParseError(V.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&Y)q.errors.forEach(ev.prettifyError(J,Y)),q.warnings.forEach(ev.prettifyError(J,Y));return q}function cC4(J,Q,Y){let X=void 0;if(typeof Q==="function")X=Q;else if(Y===void 0&&Q&&typeof Q==="object")Y=Q;let G=cj0(J,Y);if(!G)return null;if(G.warnings.forEach((Z)=>mC4.warn(G.options.logLevel,Z)),G.errors.length>0)if(G.options.logLevel!=="silent")throw G.errors[0];else G.errors=[];return G.toJS(Object.assign({reviver:X},Y))}function lC4(J,Q,Y){let X=null;if(typeof Q==="function"||Array.isArray(Q))X=Q;else if(Y===void 0&&Q)Y=Q;if(typeof Y==="string")Y=Y.length;if(typeof Y==="number"){let G=Math.round(Y);Y=G<1?void 0:G>8?{indent:8}:{indent:G}}if(J===void 0){let{keepUndefined:G}=Y??Q??{};if(!G)return}if(uC4.isDocument(J)&&!X)return J.toString(Y);return new gC4.Document(J,X,Y).toString(Y)}iC4.parse=cC4;iC4.parseAllDocuments=dC4;iC4.parseDocument=cj0;iC4.stringify=lC4});var dP=f((Kj4)=>{var sC4=XD1(),tC4=nv(),eC4=uN1(),BD1=av(),Jj4=kv(),iU=c9(),Qj4=uU(),Yj4=a2(),Xj4=dU(),Gj4=cU(),Zj4=rr(),$j4=zD1(),qj4=FD1(),Vj4=UD1(),er=lj0(),ij0=Sv();Kj4.Composer=sC4.Composer;Kj4.Document=tC4.Document;Kj4.Schema=eC4.Schema;Kj4.YAMLError=BD1.YAMLError;Kj4.YAMLParseError=BD1.YAMLParseError;Kj4.YAMLWarning=BD1.YAMLWarning;Kj4.Alias=Jj4.Alias;Kj4.isAlias=iU.isAlias;Kj4.isCollection=iU.isCollection;Kj4.isDocument=iU.isDocument;Kj4.isMap=iU.isMap;Kj4.isNode=iU.isNode;Kj4.isPair=iU.isPair;Kj4.isScalar=iU.isScalar;Kj4.isSeq=iU.isSeq;Kj4.Pair=Qj4.Pair;Kj4.Scalar=Yj4.Scalar;Kj4.YAMLMap=Xj4.YAMLMap;Kj4.YAMLSeq=Gj4.YAMLSeq;Kj4.CST=Zj4;Kj4.Lexer=$j4.Lexer;Kj4.LineCounter=qj4.LineCounter;Kj4.Parser=Vj4.Parser;Kj4.parse=er.parse;Kj4.parseAllDocuments=er.parseAllDocuments;Kj4.parseDocument=er.parseDocument;Kj4.stringify=er.stringify;Kj4.visit=ij0.visit;Kj4.visitAsync=ij0.visitAsync});function nj0(J,Q){if(Q.length===0)return X0.of([]);return new X0((Y)=>{let X=new _Y,G=()=>{Y.next(Array.from(X.keys()).toSorted((V,K)=>V.toString().localeCompare(K.toString())))},Z=new AbortController;Promise.all(Q.map(async(V)=>{if(pI0(V))return J.findFiles(V,{signal:Z.signal});try{return await J.stat(V),[V]}catch(K){if(K instanceof WJ)return[];if(typeof K==="object"&&K!==null&&"code"in K&&K.code==="ELOOP")return h.warn("Infinite symlink loop detected in guidance file",{file:V.toString()}),[];throw K}})).then((V)=>{for(let K of V.flat())X.add(K);G()}).catch((V)=>{if(!Z.signal.aborted)Z.abort();if(!xQ(V))Y.error(V)});let q=Q.map((V)=>J.watch(V,{ignoreChanges:!0}).subscribe({next:(K)=>{if(K.type==="create"||K.type==="change")X.add(K.uri);else if(K.type==="delete")X.delete(K.uri);G()}}));return()=>{Z.abort();for(let V of q)V.unsubscribe()}})}var aj0=N1(()=>{r0();FH();L0();a$();fQ()});function Js(J){let Q=/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/,Y=J.match(Q);if(!Y)return{frontMatter:null,content:J.trim()};let[,X,G]=Y,Z=null;try{let q=rj0.default.parse(X?.trim()??"");if(q&&typeof q==="object")Z={...q,globs:Array.isArray(q.globs)?q.globs:q.globs&&typeof q.globs==="string"?[q.globs]:void 0}}catch(q){return h.error("Invalid YAML front matter in guidance file",{error:q}),{frontMatter:null,content:J.trim()}}return{frontMatter:Z,content:(G??"").trim()}}function sj0(J,Q,Y){if(!J||!J.globs||J.globs.length===0)return!0;Y=l4(Y);let X=Q.map((G)=>l4(G));for(let G of J.globs){let Z=G;if(G.startsWith("./")||G.startsWith("../"))Z=_E(o0.dirname(Y).path,G);else if(!G.startsWith("/")&&!G.startsWith("**/"))Z=`**/${G}`;let q=oj0.default(Z,{dot:!0});for(let V of X)if(q(ZJ(V)))return!0}return!1}var oj0,rj0;var ND1=N1(()=>{G4();kE();L0();oj0=N6(RM(),1),rj0=N6(dP(),1)});async function tj0(J,Q,Y,X,G){let Z=[];Y=mj4(Y);let q=/@([a-zA-Z0-9._~/*?[\]{}\\,-]+)/g,V;while((V=q.exec(Y))!==null){let K=V[1];if(!K)continue;K=K.replace(/[.,;!?)]+$/,""),K=K.replace(/\\(\*)/g,"$1");let W=gj4(K,Q);if(W){h.warn("Ignoring glob pattern:",W);continue}try{let H=await uj4(J,Q,K,X,G);Z.push(...H)}catch(H){continue}}return Z}function gj4(J,Q){let Y=Q.fsPath;if(J.startsWith("**/")||["*","**","/*","/**","","/"].includes(J)||J.includes("__dangerous_glob_canary__"))return`Ignoring glob pattern "${J}" in ${Y}, because it may cause performance issues.`;return null}function mj4(J){let Q=J.replace(/```[\s\S]*?```/g,"");return Q=Q.replace(/`[^`]*`/g,""),Q=Q.replace(/<code[^>]*>[\s\S]*?<\/code>/gi,""),Q}async function uj4(J,Q,Y,X,G){let Z,q;if(Y.startsWith("~/")){if(X.homeDir===null)return[];let K=Y.slice(2),{basePart:W,patternPart:H}=DD1(K);Z=W?o0.joinPath(X.homeDir,W):l4(X.homeDir),q=H}else if(Y.startsWith("/")){let K=Y.slice(1),{basePart:W,patternPart:H}=DD1(K);Z=W?o0.joinPath(d0.file("/"),W):d0.file("/"),q=H}else{let K=o0.dirname(Q),{basePart:W,patternPart:H}=DD1(Y);Z=W?o0.joinPath(K,W):K,q=H}if(ej0(q))try{let W=await J.findFiles({base:Z,pattern:q},{signal:G,maxResults:1000});if(W.length>=1000)h.warn("Truncating very large glob expansion result",`Limit (1000) exceeded for '${Y}' in ${Q.fsPath}.`);return W}catch(K){return[]}if(!q)return[];return[o0.joinPath(Z,q)]}function ej0(J){return J.includes("*")||J.includes("?")||J.includes("[")||J.includes("{")}function DD1(J){let Q=J.split("/"),Y=[],X=[],G=!1;for(let Z of Q)if(G||ej0(Z))G=!0,X.push(Z);else Y.push(Z);if(!G){if(Y.length===0)return{basePart:null,patternPart:""};let Z=Y.pop();return{basePart:Y.length===0?null:Y.join("/"),patternPart:Z}}return{basePart:Y.length===0?null:Y.join("/"),patternPart:X.join("/")}}var JS0=N1(()=>{G4();L0()});async function QS0({filesystem:J},Q,Y,X=[],G){let Z=[],q=new _Y,V=new _Y,K=new L2,W=[];async function H(L,A=!1){let E=l4(L.uri);if(q.has(E))return null;if(V.has(E))return null;V.add(E);try{let P=await J.readFile(E,{signal:G}),{frontMatter:I,content:T}=Js(P),S=sj0(I,X,E),y={...L,type:A?L.type:"mentioned",content:T,frontMatter:I,exclude:!S,"~debug":{mentionedBy:K.has(E)?[K.get(E)]:void 0}};q.add(E),Z.push(y);let x=await tj0(J,E,P,Y,G);for(let g of x){if(!K.has(g))K.set(g,L.uri);let p={uri:j6(g),type:"mentioned"},b=await H(p,!1);if(b)W.push({file:b,afterFile:L.uri})}return y}catch(P){if(P instanceof Error&&P.message.includes("EISDIR"))return h.debug("Guidance file is a directory, skipping",{uri:L.uri}),null;if(ZQ(P))h.debug("Guidance file not found (expected)",{uri:L.uri});else h.error("Error resolving guidance file",{uri:L.uri,error:P});return null}finally{V.delete(E)}}for(let L of MD1(Q))await H(L,!0);let z=[],U=new Set;function N(L){if(U.has(L.uri))return;z.push(L),U.add(L.uri);let A=W.filter((E)=>E.afterFile===L.uri);for(let E of A)N(E.file)}let M=Z.filter((L)=>L.type!=="mentioned");for(let L of M)N(L);return z}var YS0=N1(()=>{G4();L0();a$();fQ();ND1();D3();JS0()});function pj4(J){return{homeDir:J.userConfigDir?j6(J.userConfigDir):null}}function LD1(J){if(J.path==="/"||J.path==="")return!0;let Q=J.fsPath;if(Q==="/"||Q==="/Users"||Q==="/home"||/^[A-Z]:[\\/?]?$/.test(Q))return!0;if(["/proc","/sys","/dev"].includes(Q))return!0;return!1}function dj4({filesystem:J,configService:Q},Y){let X=Q.config.pipe(q6((G)=>!!G.settings["guidanceFiles.specs"]),_4());return d8(oZ1(J),Y?Y:X0.of(null),Q.workspaceRoots,X).pipe(k4(([G,Z,q,V])=>{let K=q??Z?.env?.initial?.trees?.map((z)=>z.uri).filter((z)=>z!==void 0).map((z)=>l4(z));if(!K)K=[];let W=[];W.push(...K);for(let z of K){let U=o0.dirname(z);while(U){if(LD1(U))break;W.push(U);let N=o0.dirname(U);if(o0.equalURIs(N,U))break;U=N}}if(Q.userConfigDir)W.push(o0.joinPath(Q.userConfigDir,"amp")),W.push(Q.userConfigDir);let H=W.flatMap((z)=>Jf.map((U)=>o0.joinPath(z,U)));if(V)H.push(...K.map((z)=>({base:z,pattern:GS0})));return nj0(G,H).pipe(q6((z)=>{let U=[],N=new Set;for(let M of z){let L=o0.dirname(M).toString(),A=o0.basename(M);if(A.toLowerCase().endsWith(".spec.md")){if(K.some((T)=>o0.hasPrefix(M,T)))U.push({uri:j6(M),type:"project"});continue}if(N.has(L))continue;let E=Jf.findIndex((T)=>T===A);if(E===-1)continue;let P=!1,I=o0.dirname(M);for(let T=0;T<E;T++){let S=Jf[T];if(z.some((y)=>{let x=o0.equalURIs(o0.dirname(y),I),g=o0.basename(y)===S;return x&&g})){P=!0;break}}if(P)continue;if(N.add(L),K.some((T)=>o0.hasPrefix(M,T))){U.push({uri:j6(M),type:"project"});continue}if(Q.userConfigDir&&o0.hasPrefix(M,Q.userConfigDir)){U.push({uri:j6(M),type:"user"});continue}U.push({uri:j6(M),type:"parent"})}return U}))}))}function cj4({filesystem:J,configService:Q},Y){let X=Q.config.pipe(q6((Z)=>!!Z.settings["guidanceFiles.specs"]),_4());function G(Z){let q=new Set,V=[];for(let K of Z){let W=o0.dirname(K).toString();if(!q.has(W))q.add(W),V.push(W)}return V.join(",")}return d8(Y.pipe(q6((Z)=>({thread:Z,readFiles:ZS0(Z)})),_4((Z,q)=>G(Z.readFiles)===G(q.readFiles))),oZ1(J),Q.workspaceRoots,X).pipe(cF(async([{readFiles:Z},q,V,K],W)=>{if(!V)V=[];let H=new _Y;for(let U of Z){let N=o0.dirname(U);while(!H.has(N)&&V.some((M)=>o0.hasPrefix(N,M)&&!o0.equalURIs(M,N)))H.add(N),N=o0.dirname(N)}let z=(await Promise.all(Array.from(H.keys()).map(async(U)=>{for(let N of Jf)try{let M=o0.joinPath(U,N);return await q.stat(M,{signal:W}),{uri:j6(M),type:"subtree"}}catch(M){if(typeof M==="object"&&M!==null&&"code"in M&&M.code==="ELOOP")h.warn("Infinite symlink loop detected in guidance file",{file:o0.joinPath(U,N).toString()});continue}return null}))).filter((U)=>U!==null);if(K){let U=await Promise.all(Array.from(H.keys()).map(async(N)=>{return await q.findFiles({base:N,pattern:GS0})}));z.push(...U.flat().map((N)=>({uri:j6(N),type:"subtree"})))}return z}))}function ZS0(J){let Q=[];for(let Y of J.messages)if(Y.role==="assistant"){for(let X of Y.content)if(X.type==="tool_use"&&(X.name===d6||X.name===f$1)){let G=eW(J,X.id);if(G&&G.run.status==="done"){let Z=G.run.result;if(typeof Z==="object"&&Z.absolutePath)Q.push(d0.file(Z.absolutePath))}}}for(let Y of J.messages)if(Y.role==="user"&&Y.fileMentions)for(let X of Y.fileMentions.files)Q.push(X.uri);return Q}function lj4(J){let Q=new Set;for(let Y of J.messages)if(Y.role==="assistant"){for(let X of Y.content)if(X.type==="tool_use"){let G=X.name===d6||X.name===f$1,Z=X.name===N5;if(G||Z){let q=eW(J,X.id);if(q&&q.run.status==="done"){let V=q.run.result;if(typeof V==="object"&&V!==null&&"discoveredGuidanceFiles"in V&&Array.isArray(V.discoveredGuidanceFiles)&&V.discoveredGuidanceFiles.length>0)for(let K of V.discoveredGuidanceFiles)Q.add(K.uri)}}}}else if(Y.role==="user"&&Y.discoveredGuidanceFiles)for(let X of Y.discoveredGuidanceFiles)Q.add(X.uri);return Q}async function Ys(J,Q,Y){let[X,G]=await Promise.all([M6(dj4(J,X0.of({env:Q.env})),Y),M6(cj4(J,X0.of(Q)),Y)]);return Y?.throwIfAborted(),(await QS0({filesystem:aZ1(J.filesystem)?await M6(J.filesystem):J.filesystem},MD1([...X,...G]),pj4(J.configService),ZS0(Q),Y)).filter((q)=>!q.exclude)}function MD1(J){return J.toSorted((Q,Y)=>{let X=XS0[Q.type]-XS0[Y.type];if(X!==0)return X;return Q.uri.localeCompare(Y.uri)})}function Qf(J){let Q=d0.parse(J),Y=o0.basename(Q)||"AGENTS.md",X=o0.basename(o0.dirname(Q));return X?`${X}/${Y}`:Y}async function cP(J,Q,Y,X,G,Z){let q=X?lj4(X):new Set;if(G)for(let W of G)q.add(W);let V=[],K=o0.dirname(Q);while(Y.some((W)=>o0.hasPrefix(K,W)&&!o0.equalURIs(W,K))){Z?.throwIfAborted();for(let H of Jf){let z=o0.joinPath(K,H),U=j6(z);if(q.has(U)||G?.has(U))break;try{await J.stat(z,{signal:Z});let M=(await J.readFile(z,{signal:Z})).split(`
405
+ `).length;if(!G?.has(U))G?.add(U),q.add(U),V.push({uri:U,lineCount:M});break}catch{continue}}let W=o0.dirname(K);if(o0.equalURIs(W,K))break;K=W}return V}var Qs="AGENT.md",L9="AGENTS.md",Jf,GS0="*.spec.md",XS0;var D3=N1(()=>{G4();r0();L0();a$();aj0();t8();N4();YS0();Jf=[L9,"Agents.md","agents.md",Qs,"Agent.md","agent.md","CLAUDE.md"];XS0={user:0,project:1,parent:2,subtree:3}});function nj4(J){let Q=J.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!Q||!Q[1]||!Q[2])throw Error("SKILL.md must have YAML frontmatter");let Y=$S0.default.parse(Q[1]);if(!Y.name||!Y.description)throw Error("SKILL.md frontmatter must include name and description");return{frontmatter:Y,content:Q[2]}}async function aj4(J,Q,Y){let X=[],G=5;async function Z(q,V){if(V>5)return;try{let K=await J.readdir(q,{signal:Y});for(let W of K){let H=o0.basename(W.uri);if(W.isDirectory&&(H==="node_modules"||H===".git"))continue;if(W.isDirectory)await Z(W.uri,V+1);else if(ij4.test(H))X.push(W.uri)}}catch(K){h.debug("Failed to scan skill directory",{path:q.toString(),error:K})}}return await Z(Q,0),X}async function Yf(J,Q,Y,X,G,Z="skill"){try{await J.stat(Q,{signal:G});let q=await aj4(J,Q,G);for(let V of q){let K=o0.dirname(V),W=j6(K);if(!Y.has(W)){Y.add(W);try{let H=await J.readFile(V,{signal:G}),{frontmatter:z,content:U}=nj4(H);if(z.isolatedContext)continue;X.push({name:z.name,description:z.description,frontmatter:z,content:U,baseDir:j6(K)})}catch(H){h.warn(`Failed to load ${Z}`,{path:j6(V),error:H})}}}}catch(q){h.debug(`Failed to process ${Z} directory`,{path:Q.toString(),error:q})}}async function Xf(J,Q,Y){let X=[],G=new Set,Z=typeof process<"u"&&process.env.HOME?process.env.HOME:null;if(Z){let H=o0.joinPath(d0.file(Z),".claude","skills");await Yf(J,H,G,X,Y,"skill");let z=o0.joinPath(d0.file(Z),".claude","plugins","cache");await Yf(J,z,G,X,Y,"plugin skill");let U=o0.joinPath(d0.file(Z),".claude","plugins","marketplaces");await Yf(J,U,G,X,Y,"marketplace plugin skill")}let q=new Set;for(let H of Q){let z=sJ(H);q.add(j6(z));while(z){if(LD1(z))break;q.add(j6(z));let U=o0.dirname(z);if(o0.equalURIs(U,z))break;z=U}}let V=typeof process<"u"&&process.env.AMP_TOOLBOX?process.env.AMP_TOOLBOX:void 0,K=typeof process<"u"&&process.env.HOME?`${process.env.HOME}/.config/amp/tools`:null,W=V?V.split(":").filter(Boolean):K?[K]:[];for(let H of W){let z=d0.file(H);await Yf(J,z,G,X,Y,"skill from toolbox")}h.info("Scanning workspace roots for skills",{searchRoots:[...q],workspaceRoots:Q});for(let H of q){let z=sJ(H),U=o0.joinPath(z,".claude","skills");await Yf(J,U,G,X,Y,"skill")}return h.info("Finished loading skills",{totalSkills:X.length,skillNames:X.map((H)=>H.name),skillBaseDirs:X.map((H)=>H.baseDir)}),X}function qS0(J){if(J.length===0)return null;let Q=J.filter((Y)=>!Y.frontmatter["disable-model-invocation"]).map((Y)=>`- **${Y.name}**: ${Y.description}`).join(`
406
406
  `);if(!Q)return null;return Q}var $S0,ij4;var AD1=N1(()=>{G4();L0();D3();$S0=N6(dP(),1),ij4=/^skill\.md$/i});function oj4(J,Q){return{...J,description:J.description?.replace(VS0,Q)}}async function WS0(J,Q,Y,X){if(J.name!==fk)return J;let G=await Xf(Q,Y,X);h.info("Loaded skills for system prompt",{skillCount:G.length,skillNames:G.map((V)=>V.name),skillBaseDirs:G.map((V)=>V.baseDir),workspaceRoots:Y});let q=qS0(G)??"No skills available. Skills can be added to `.amp/skills/` in your workspace.";return oj4(J,q)}var VS0="{{AVAILABLE_SKILLS}}",KS0;var OD1=N1(()=>{G4();r0();L0();AD1();N4();KS0={spec:{name:fk,description:["Load a specialized skill that provides domain-specific instructions and workflows.","","When you recognize that a task matches one of the available skills listed below, use this tool to load the full skill instructions.","","The skill will inject detailed instructions, workflows, and access to bundled resources (scripts, references, templates) into the conversation context.","","Parameters:","- name: The name of the skill to load (must match one of the skills listed below)","",'Example: To use the web-browser skill for interacting with web pages, call this tool with name: "web-browser"',"","# Available Skills","",VS0].join(`
407
407
  `),inputSchema:{type:"object",properties:{name:{type:"string",description:"The name of the skill to load"}},required:["name"]},source:"builtin",executionProfile:{resourceKeys:()=>[]}},fn:({args:J},Q)=>s6(async()=>{let X=(await M6(Q.configService.workspaceRoots)??[]).map((K)=>j6(K)),G=await Xf(Q.filesystem,X),Z=G.find((K)=>K.name===J.name);if(!Z){let K=G.map((W)=>W.name).join(", ");return{status:"done",result:{content:[{type:"text",text:`Skill "${J.name}" not found. Available skills: ${K||"none"}`}]}}}let V=[`# ${Z.frontmatter.name} Skill`,"",Z.content,"","---","",`**Skill Base Directory**: \`{baseDir}\` resolves to \`${Z.baseDir}\``,"","You can access bundled resources using the Read tool:","- Scripts: `{baseDir}/scripts/script_name.py`","- References: `{baseDir}/references/doc_name.md`","- Assets: `{baseDir}/assets/template.html`"].join(`
408
408
  `).replace(/\{baseDir\}/g,Z.baseDir);return await Q.handleThreadDelta({type:"info:skill-injection",skillName:J.name,content:V}),{status:"done",result:{content:[{type:"text",text:V}]}}})}});function HS0(J){let{interval:Q,fn:Y,cacheKey:X}=J,G=new Map,Z=new Map;return(...q)=>{let V=X?X(...q):"default",K=Date.now(),W=Z.get(V)||0;if(G.has(V)&&K-W<Q)return G.get(V);Z.set(V,K);let H=Y(...q);return G.set(V,H),H}}async function rj4(J,Q,Y,X){let G=X?.testing?"":J.fsPath,Z=[],q=await Y.readdir(J),V=await Promise.all(q.filter((z)=>!Gx(o0.basename(z.uri))).map(async(z)=>{try{let U=await Y.stat(z.uri);return{name:o0.basename(z.uri),isDirectory:U.isDirectory}}catch{return{name:o0.basename(z.uri),isDirectory:!1}}}));V.sort((z,U)=>{if(z.isDirectory===U.isDirectory)return z.name.localeCompare(U.name);return z.isDirectory?-1:1});let K=500,W=V.length>K,H=V.slice(0,K);for(let{name:z,isDirectory:U}of H){let N=G&&!G.endsWith("/")?"/":"",M=`${G}${N}${z}${U?"/":""}`;Z.push(M)}if(W){let z=V.length-K;Z.push(`... and ${z} more ${r9(z,"entry","entries")}`)}return Z.join(`
@@ -2054,7 +2054,7 @@ IMPORTANT: Always use the ${V7} tool to plan and track tasks throughout the conv
2054
2054
  ${Q.join(`
2055
2055
  `)}
2056
2056
 
2057
- `}var fS0;var OL=N1(()=>{G4();_X();fS0={currentlyVisibleFiles:[]}});function hS0(J){return Boolean(J&&typeof J==="object"&&"isImage"in J&&J.isImage&&"imageInfo"in J&&J.imageInfo&&typeof J.imageInfo==="object"&&"mimeType"in J.imageInfo&&typeof J.imageInfo.mimeType==="string"&&YP(J.imageInfo.mimeType)&&"size"in J.imageInfo&&typeof J.imageInfo.size==="number")}function bS0(J,Q,Y){return(X,G)=>{let Z=sw0({readFileFn:async(q,V)=>G.filesystem.readFile(q,{signal:V}),readBinaryFileFn:(q,V)=>G.filesystem.readBinaryFile(q,{signal:V}),maxFileSizeBytes:J,maxLines:Q,maxLineBytes:Y});return s6(async(q)=>{let V=await Z(X,G,q);if(V.status==="done"&&typeof V.result==="object"){let K=d0.file(V.result.absolutePath),W=await cP(G.filesystem,K,G.dirs,G.thread,void 0,q);if(W.length>0)return{...V,result:{...V.result,discoveredGuidanceFiles:W}}}return V})}}var ZS4,$S4,wL,lP;var iP=N1(()=>{G4();r0();SH();D3();oM();UH();N4();_X();ZS4=bS0(sa,hF1,bF1),$S4=bS0(rw0,200,1024);wL={spec:{name:d6,description:n2`
2057
+ `}var fS0;var OL=N1(()=>{G4();_X();fS0={currentlyVisibleFiles:[]}});function hS0(J){return Boolean(J&&typeof J==="object"&&"isImage"in J&&J.isImage&&"imageInfo"in J&&J.imageInfo&&typeof J.imageInfo==="object"&&"mimeType"in J.imageInfo&&typeof J.imageInfo.mimeType==="string"&&YP(J.imageInfo.mimeType)&&"size"in J.imageInfo&&typeof J.imageInfo.size==="number")}function bS0(J,Q,Y){return(X,G)=>{let Z=sw0({readFileFn:async(q,V)=>G.filesystem.readFile(q,{signal:V}),readBinaryFileFn:(q,V)=>G.filesystem.readBinaryFile(q,{signal:V}),maxFileSizeBytes:J,maxLines:Q,maxLineBytes:Y});return s6(async(q)=>{let V=await Z(X,G,q);if(V.status==="done"&&typeof V.result==="object"){let K=d0.file(V.result.absolutePath),W=await cP(G.filesystem,K,G.dirs,G.thread,G.discoveredGuidanceFileURIs,q);if(W.length>0)return{...V,result:{...V.result,discoveredGuidanceFiles:W}}}return V})}}var ZS4,$S4,wL,lP;var iP=N1(()=>{G4();r0();SH();D3();oM();UH();N4();_X();ZS4=bS0(sa,hF1,bF1),$S4=bS0(rw0,200,1024);wL={spec:{name:d6,description:n2`
2058
2058
  Read a file or list a directory from the file system. If the path is a directory, it returns a line-numbered list of entries. If the file or directory doesn't exist, an error is returned.
2059
2059
 
2060
2060
  - The path parameter MUST be an absolute path.
@@ -2495,7 +2495,7 @@ ${l3(g58)}
2495
2495
  - Use ${"finder"} first to locate relevant code concepts
2496
2496
  - Then use ${"Grep"} to find specific implementations or all occurrences
2497
2497
  - For complex tasks, iterate between both tools to refine your understanding
2498
- `,u58=m58,xK={spec:{name:v8,description:u58,inputSchema:{type:"object",properties:{pattern:{type:"string",description:"The pattern to search for (regex)"},path:{type:"string",description:"The file or directory path to search in. Cannot be used with glob."},glob:{type:"string",description:"The glob pattern to search for. Cannot be used with path."},caseSensitive:{type:"boolean",description:"Whether to search case-sensitively"},literal:{type:"boolean",description:"Whether to treat the pattern as a literal string instead of a regex"}},required:["pattern"]},source:"builtin",executionProfile:{resourceKeys:(J)=>{if(J&&typeof J==="object"&&"path"in J&&typeof J.path==="string")return[{key:J.path,mode:"read"}];return[]}}},fn:IU({os:()=>Promise.resolve().then(() => (Gt0(),Xt0)).then(({nodeGrepTool:J})=>J),github:null,gitlab:null})}});var Vt0={};y8(Vt0,{nodeCreateFileTool:()=>l58});var l58=({args:J,userInput:Q},Y)=>{let{filesystem:X,config:G}=Y;return s6(async(Z)=>{if(typeof J.content!=="string")throw Error("create_file: content must be specified");Z.throwIfAborted();let q=vQ(J.path);await NH(q).acquire();try{let V=await LU(q,X,G.settings);if(V.requiresConsent){if(Q&&!Q.accepted)return{status:"rejected-by-user",reason:V.reason,toAllow:V.toAllow?[V.toAllow]:void 0};else if(!Q?.accepted)return{status:"blocked-on-user",reason:V.reason,toAllow:V.toAllow?[V.toAllow]:void 0}}await X.mkdirp(o0.dirname(q),{signal:Z}),await X.writeFile(q,J.content,{signal:Z});let K=await cP(X,q,Y.dirs,Y.thread,void 0,Z);if(K.length>0)return{status:"done",result:{message:`Successfully created file ${J.path}`,discoveredGuidanceFiles:K},trackFiles:[j6(q)]};return{status:"done",result:`Successfully created file ${J.path}`,trackFiles:[j6(q)]}}finally{NH(q).release()}})};var Kt0=N1(()=>{G4();r0();D3();sM();zo();_X()});var i58=`Create or overwrite a file in the workspace.
2498
+ `,u58=m58,xK={spec:{name:v8,description:u58,inputSchema:{type:"object",properties:{pattern:{type:"string",description:"The pattern to search for (regex)"},path:{type:"string",description:"The file or directory path to search in. Cannot be used with glob."},glob:{type:"string",description:"The glob pattern to search for. Cannot be used with path."},caseSensitive:{type:"boolean",description:"Whether to search case-sensitively"},literal:{type:"boolean",description:"Whether to treat the pattern as a literal string instead of a regex"}},required:["pattern"]},source:"builtin",executionProfile:{resourceKeys:(J)=>{if(J&&typeof J==="object"&&"path"in J&&typeof J.path==="string")return[{key:J.path,mode:"read"}];return[]}}},fn:IU({os:()=>Promise.resolve().then(() => (Gt0(),Xt0)).then(({nodeGrepTool:J})=>J),github:null,gitlab:null})}});var Vt0={};y8(Vt0,{nodeCreateFileTool:()=>l58});var l58=({args:J,userInput:Q},Y)=>{let{filesystem:X,config:G}=Y;return s6(async(Z)=>{if(typeof J.content!=="string")throw Error("create_file: content must be specified");Z.throwIfAborted();let q=vQ(J.path);await NH(q).acquire();try{let V=await LU(q,X,G.settings);if(V.requiresConsent){if(Q&&!Q.accepted)return{status:"rejected-by-user",reason:V.reason,toAllow:V.toAllow?[V.toAllow]:void 0};else if(!Q?.accepted)return{status:"blocked-on-user",reason:V.reason,toAllow:V.toAllow?[V.toAllow]:void 0}}await X.mkdirp(o0.dirname(q),{signal:Z}),await X.writeFile(q,J.content,{signal:Z});let K=await cP(X,q,Y.dirs,Y.thread,Y.discoveredGuidanceFileURIs,Z);if(K.length>0)return{status:"done",result:{message:`Successfully created file ${J.path}`,discoveredGuidanceFiles:K},trackFiles:[j6(q)]};return{status:"done",result:`Successfully created file ${J.path}`,trackFiles:[j6(q)]}}finally{NH(q).release()}})};var Kt0=N1(()=>{G4();r0();D3();sM();zo();_X()});var i58=`Create or overwrite a file in the workspace.
2499
2499
 
2500
2500
  Use this tool when you want to create a new file with the given content, or when you want to replace the contents of an existing file.
2501
2501
 
@@ -3202,7 +3202,7 @@ ${J.trim()}
3202
3202
  `){let H=Y.trim();if(H)Q.push({content:H,lineNumber:q});Y="",Z++,q=Z}else if(W===`
3203
3203
  `)Y+=W,Z++;else Y+=W}let V=Y.trim();if(V)Q.push({content:V,lineNumber:q});return Q}function _11(J){let Q=Ho4(J),Y=[];for(let X=0;X<Q.length;X++){let G=Q[X];if(G.content.startsWith("#"))continue;let Z=Wo4(G.content);if(!Z.success)return Z.error.line=G.lineNumber,Z;Y.push(Z.data)}return{success:!0,data:Y}}function zo4(J){if(typeof J!=="string")return!1;if(/[\s*"'\\]/.test(J)||J.includes("/")||J===""||!/^[a-zA-Z0-9_*.-]+$/.test(J))return!0;if(Fo4(J))return!0;return!1}function Fo4(J){return/^-?\d+(\.\d+)?([eE][-+]?\d+)?$/.test(J)}function EA(J){if(typeof J!=="string")return String(J);if(!zo4(J))return J;return`'${J.replace(/'/g,"\\'")}'`}function S11(J,Q=""){let Y=[];for(let[X,G]of Object.entries(J)){let Z=Q?`${Q}.${X}`:X;if(Array.isArray(G))for(let q=0;q<G.length;q++){let V=`${Z}.${q}`;if(typeof G[q]==="object"&&G[q]!==null)Y.push(...S11(G[q],V));else Y.push({path:V,value:G[q]})}else if(typeof G==="object"&&G!==null)Y.push(...S11(G,Z));else Y.push({path:Z,value:G})}return Y}function Uo4(J,Q){let Y=[];if(typeof Q==="string"||typeof Q==="boolean"||typeof Q==="number"||Q===null)Y.push(`--${J} ${EA(Q)}`);else if(Array.isArray(Q)){let X=Q.every((Z)=>typeof Z==="string"||typeof Z==="boolean"||typeof Z==="number"||Z===null);if(!J.includes(".")&&X)for(let Z of Q)Y.push(`--${J} ${EA(Z)}`);else for(let Z=0;Z<Q.length;Z++)if(typeof Q[Z]==="object"&&Q[Z]!==null){let q=S11({[`${J}.${Z}`]:Q[Z]});for(let{path:V,value:K}of q)Y.push(`--${V} ${EA(K)}`)}else Y.push(`--${J}.${Z} ${EA(Q[Z])}`)}else if(typeof Q==="object"&&Q!==null){let X=S11({[J]:Q});for(let{path:G,value:Z}of X)Y.push(`--${G} ${EA(Z)}`)}return Y}function k11(J){let Q=[];if(Q.push(J.action),J.action==="delegate"&&J.to)Q.push(`--to ${EA(J.to)}`);if(J.context)Q.push(`--context ${J.context}`);if(Q.push(EA(J.tool)),J.matches)for(let[Y,X]of Object.entries(J.matches)){let G=Uo4(Y,X);Q.push(...G)}return Q.join(" ")}function Rb(J){return J.map(k11).join(`
3204
3204
  `)}function Bo4(J){return J.configService.config.pipe(q6((Q)=>{if(Q.settings?.dangerouslyAllowAll===!0)return[{tool:"*",action:"allow"}];return JI(Q.settings?.permissions)}),_4())}async function y11(J,Q,Y,X="thread",G,Z){let q=await M6(Bo4(Y));try{let V=await GP(J,Q,q,X,$x,G,"user",Z);if(!V.matchedEntry)V=await GP(J,Q,AT,X,void 0,G,"built-in",Z);if(!V.matchedEntry)return{permitted:!1,action:null,reason:"No matching entry found, denying by default"};let W=V.matchedEntry?.action==="delegate"&&V.action!=="reject"?"delegate":V.action;switch(V.action){case"allow":return{permitted:!0,action:W,matchedEntry:V.matchedEntry,error:V.error,source:V.source};case"reject":return{permitted:!1,action:W,matchedEntry:V.matchedEntry,reason:`Rejected by ${V.source==="built-in"?"built-in":V.source||"unknown"} permissions rule ${V.matchIndex}: ${k11(V.matchedEntry)}`,error:V.error,source:V.source};case"ask":return{permitted:!1,action:W,matchedEntry:V.matchedEntry,reason:`Matches ${V.source==="built-in"?"built-in":V.source||"unknown"} permissions rule ${V.matchIndex}: ${k11(V.matchedEntry)}`,error:V.error,source:V.source};case null:if(V.error)return{permitted:!1,action:null,reason:V.error,error:V.error};return{permitted:!0,action:null};default:return{permitted:!1,action:null,reason:"Unknown permission result"}}}catch(V){return{permitted:!1,action:null,reason:V instanceof Error?V.message:"Permission evaluation failed",error:V instanceof Error?V.message:"Permission evaluation failed"}}}fQ();G4();L0();a$();OU();QP();f11();function Hl0(J){if(J.before===void 0&&J.after===void 0)throw Error("unreachable");if(J.before===null&&J.after===null)throw Error("unreachable")}var No4=4;function h11(J,Q,Y){let X=new Map,G=(q)=>{let V=void 0;for(let[K,W]of X.entries())for(let[H,z]of W.entries()){if(!o0.equalURIs(H,q))continue;if(!V||z.timestamp<V.timestamp)V=z}return V},Z=async({filesFilter:q,toolUsesToRevert:V,pruneRevertedToolUses:K})=>{let W=new L2,H=new Map;for(let[N,M]of X.entries()){let L=V?V.has(N):!0;for(let[A,E]of M.entries()){if(q&&!q(A))continue;if(E.reverted)continue;let P=W.get(A)||{changesAfterKeep:[]};if(!L){if(!P.latestKeepChange||E.timestamp>P.latestKeepChange.timestamp)P.latestKeepChange=E}else P.changesAfterKeep.push(E),H.set(E,N);W.set(A,P)}}let z=Array.from(W.entries()).filter(([,{changesAfterKeep:N}])=>N.length>0);if(await v11(z,No4,async([N,{latestKeepChange:M,changesAfterKeep:L}])=>{try{let A=L.reduce((P,I)=>I.timestamp<P.timestamp?I:P),E=M?M.after:A.isNewFile?null:A.before;await Y(N,E),Xx(N,Q,Date.now());for(let P of L){P.reverted=!0;let I=H.get(P);if(I)try{let T={toolUseID:I,fileChangeID:P.id};await J.store(Q,T,P)}catch(T){h.error(`Error updating backup for file ${N}:`,T)}}}catch(A){h.error(`Error reverting file ${N}:`,A)}}),K&&V)for(let N of V)X.delete(N)};return{async getAllRecords(){return X},async record(q){if(!q.toolUse)return;let V=X.get(q.toolUse);if(!V)V=new L2,X.set(q.toolUse,V);if(V.has(q.uri))throw Error(`change to file ${q.uri} is already tracked for tool use ${q.toolUse}, multiple changes are not yet implemented`);let K=G(q.uri),W=q.before===null,H=K?DH(K.before??"",q.after??"",q.uri):DH(q.before??"",q.after??"",q.uri),z=crypto.randomUUID(),U={id:z,uri:j6(q.uri),before:q.before??"",after:q.after??"",diff:H,isNewFile:W,reverted:!1,timestamp:Date.now()};Xx(q.uri,Q,U.timestamp),V.set(q.uri,U),await J.store(Q,{toolUseID:q.toolUse,fileChangeID:z},U),h.debug("Recorded file change",{isNewFile:W,filePath:q.uri.toString(),toolUseID:q.toolUse})},async restoreFromBackups(){let q=await J.list(Q)??[];X.clear();for(let V of q){let{toolUseID:K}=V,W=await J.load(Q,V);if(!W)continue;if(!X.has(K))X.set(K,new L2);X.get(K).set(W.uri,W)}return{totalBackups:q.length}},async revertAll(q){let V=new Set;for(let[K]of X.entries())V.add(K);await Z({filesFilter:q?(K)=>o0.equalURIs(K,q):void 0,toolUsesToRevert:V,pruneRevertedToolUses:!1})},async revertChanges(q){await Z({toolUsesToRevert:q,pruneRevertedToolUses:!0})},getFilesForToolUses(q){let V=new L2;for(let[K,W]of X.entries()){if(!q.has(K))continue;for(let[H,z]of W.entries()){if(z.reverted)continue;V.set(H,!0)}}return Array.from(V.keys()).map(j6)},async cleanupBackups(){await J.cleanup(Q)},async getLastEdit(q){let V,K=0;for(let[W,H]of X.entries()){let z=H.get(q);if(z&&!z.reverted&&z.timestamp>=K)V=z,K=z.timestamp}if(!V)return;return{oldContent:V.before,newContent:V.after,revert:()=>{V.reverted=!0}}},dispose(){X.clear()}}}fQ();r0();eI();fQ();function tE1(J,Q){let Y={readFile:async(X,G)=>{let Z=await Q.getLastEdit(X);if(Z){if(Z.newContent===null)throw Error(`File has been deleted: ${X}`);return Z.newContent}return J.readFile(X,G)},readBinaryFile:async(X,G)=>{let Z=await Y.readFile(X,G);return new TextEncoder().encode(Z)},getMtime:async(X,G)=>{if(await Q.getLastEdit(X))return Date.now();return J.getMtime(X,G)},stat:async(X,G)=>{let Z=await Q.getLastEdit(X);if(Z){if(Z.newContent===null)throw Error(`File has been deleted: ${X}`);return{size:V5.bufferByteLengthCompat(Z.newContent),isDirectory:!1}}return J.stat(X,G)},realpath:async(X,G)=>{return J.realpath(X,G)},findFiles:async(X,G)=>{return J.findFiles(X,G)},readdir:async(X,G)=>{return J.readdir(X,G)},access:async(X,G)=>{let Z=await Q.getLastEdit(X);if(Z){if(Z.newContent===null)throw Error(`File has been deleted: ${X}`);return}return J.access(X,G)},watch:()=>nG};return Y}function zl0(J,Q,Y){let X={...tE1(J,Q),writeFile:async(G,Z,q)=>{await Q.record({toolUse:Y,uri:G,before:await KP(X,G,q),after:Z})},mkdirp:async()=>{},rename:async(G,Z)=>{throw Error("Rename operations are not supported in this implementation")},delete:async(G,Z)=>{let q=await KP(X,G,Z);if(q===null)throw Error(`Cannot delete file that does not exist: ${G}`);await Q.record({toolUse:Y,uri:G,before:q,after:null})},isExclusiveWriterFor:async()=>!0,watch(){return nG},__isImmutableBaseFileSystem:!1,__trackedFileSystem:!0};return X}fQ();function b11(J,Q,Y){async function X(G,Z,q){let V={};V.before=await KP(J,Z),await q(),V.after=await KP(J,Z),Hl0(V),await Q.record({toolUse:G,uri:Z,...V})}return{...J,async writeFile(G,Z,q){await X(Y,G,()=>J.writeFile(G,Z,q))},__isImmutableBaseFileSystem:!1,__trackedFileSystem:!0}}Jq();function Fl0(J,Q,Y,X){async function G(q,V,K){let W=Q.fileSystemForURI(X(),q);if(W.mountedTree.fs==="os"&&!e$(W))if(V!==null)await W.writeFile(q,V,{signal:K});else await W.delete(q,{signal:K})}let Z=h11(J.fileChangeTrackerStorage,Y,G);return{fileSystemReader:()=>{let q=Q.fileSystemWithMountedTrees(X());return CU1(q)?q.mapReader((V)=>{if(e$(V))return tE1(V,Z);return V}):q},trackedFileSystem:(q)=>{function V(K,W){if(CU1(K))return{...K.map((H)=>V(H,W)),__trackedFileSystem:!0};if(e$(K))return zl0(K,Z,W);return b11(K,Z,W)}return V(Q.fileSystemWithMountedTrees(X()),q)},tracker:Z}}Jq();N4();function Do4(J,Q,Y){let X=Y.getExecutionProfile(J.name),G=Y.getExecutionProfile(Q.name);if(!X||!G)return!0;if(X.serial||G.serial)return!0;let Z=X.resourceKeys(J.input??{}),q=G.resourceKeys(Q.input??{});for(let V of Z)for(let K of q)if(V.key===K.key){if(V.mode==="write"||K.mode==="write")return!0}return!1}function Mo4(J,Q,Y){for(let X of Q)if(Do4(J,X,Y))return!0;return!1}function Ul0(J,Q){if(J.length===0)return[];let Y=[],X=[];for(let G of J){if(Mo4(G,X,Q)){if(X.length>0)Y.push(X),X=[]}X.push(G)}if(X.length>0)Y.push(X);return Y}x7();var Bl0=N6(b6(),1),Lo4="amp";function eE1(){return Bl0.trace.getTracer(Lo4)}function Nl0(J){if(J instanceof Error)return J;if(typeof J==="string")return Error(J);return Error(String(J))}function Ao4(J){return[(Q)=>{return J.end(),Q},(Q)=>{throw J.recordException(Nl0(Q)),J.end(),Q}]}function JI1(J,Q,Y){let X=Y.value;Y.value=function(...G){return eE1().startActiveSpan(Q,(Z)=>{try{let q=X.apply(this,G);if(q instanceof Promise)return q.then(...Ao4(Z));return Z.end(),q}catch(q){throw Z.recordException(Nl0(q)),Z.end(),q}})}}Ml0();L0();L0();function wo4(J){if(J.action.type==="redact-tool-input"&&J.on.event!=="tool:post-execute")return"redact-tool-input action can only be used with tool:post-execute event";if(J.action.type==="send-user-message"&&J.on.event!=="tool:pre-execute")return"send-user-message action can only be used with tool:pre-execute event";return null}function QI1(J){if(!J||!Array.isArray(J))return[];return J.filter((Q)=>{if(Q.compatibilityDate!=="2025-05-13")return!1;let Y=wo4(Q);if(Y)return h.warn(`Hook "${Q.id}" is invalid: ${Y}`),!1;return!0})}function Ll0(J,Q){if(!J)return{action:null};J=QI1(J);for(let Y of J){if(Y.if===!1)continue;if(Y.on.event==="tool:pre-execute"){if(!(Array.isArray(Y.on.tool)?Y.on.tool:[Y.on.tool]).includes(Q.toolUse.name))continue;let G=JSON.stringify(Q.toolUse.input),Z=Array.isArray(Y.on["input.contains"])?Y.on["input.contains"]:[Y.on["input.contains"]];for(let q of Z)if(G.includes(q)){if(h.debug(`Hook triggered: ${Y.id}`,{hookID:Y.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,matchString:q,action:Y.action}),Y.action.type==="send-user-message")return{hookID:Y.id,action:Y.action}}}}return{action:null}}function Al0(J,Q){if(!J)return{action:null};J=QI1(J);for(let Y of J){if(Y.if===!1)continue;if(Y.on.event==="tool:post-execute"){if(!(Array.isArray(Y.on.tool)?Y.on.tool:[Y.on.tool]).includes(Q.toolUse.name))continue;if(h.debug(`Post-execution hook triggered: ${Y.id}`,{hookID:Y.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,action:Y.action}),Y.action.type==="redact-tool-input")return{hookID:Y.id,action:Y.action}}}return{action:null}}function Ol0(J,Q){if(!J)return{action:null};try{return J(Q.thread)}catch(Y){return h.error("Error processing assistant end-turn hook",Y),{action:null}}}async function g11(J,Q,Y){if(!Q.action)return{abortOp:!1};switch(Q.action.type){case"send-user-message":{let X={type:"user:message",message:{content:[{type:"text",text:Q.action.message}],source:{type:"hook",hook:Q.hookID}}};return J.updateThread(X),J.onThreadDelta(X),{abortOp:!0}}case"redact-tool-input":{if(!Y?.toolUseID)return h.warn("redact-tool-input action requires toolUseID in context"),{abortOp:!1};let X={type:"tool:processed",toolUse:Y.toolUseID,newArgs:Q.action.redactedInput};return J.updateThread(X),J.onThreadDelta(X),h.debug("Tool input redacted",{hookID:Q.hookID,toolUseID:Y.toolUseID}),{abortOp:!1}}}}function qz(J){return Eo4(J?.["experimental.agentMode"])}function Eo4(J){return J??"smart"}sG();W3();t8();function wl0(J,Q,Y,X){let G=Q;if(Q&&$5(Q)){if(!(X?.canUseAmpFree??!1))G=void 0}let Z=c$(J);if(Z===0&&G)return G;if(J.agentMode)return J.agentMode;if(Z>0){let q=Xq1(J);if(q)return q}if(G)return G;return qz(Y)}function Tb(J,Q){let Y=Q.agentMode??Xq1(Q),X=WN0(J);if(X)return{agentMode:Y??"smart",model:X};if(J["model.sonnet"])return{agentMode:Y??"smart",model:"anthropic/claude-sonnet-4-5-20250929"};let G=Y??qz(J);return{model:TM(G),agentMode:G}}t8();xt();function IA(J,Q){let Y=J&&Q?.state==="active"&&Q.inferenceState!=="running"?Io4(J):{running:0,blocked:0};return{...Q,interactionState:J&&Q?.state==="active"?YI1(J,Q.inferenceState):!1,toolState:Y}}function Io4(J){let Q=J.messages.at(-1);if(!Q||Q.role==="assistant")return{running:0,blocked:0};let Y=0,X=0;for(let G of Q.content){if(G.type!=="tool_result")continue;let Z=G.run.status;if(Z==="in-progress")Y++;else if(Z==="blocked-on-user")X++}return{running:Y,blocked:X}}function YI1(J,Q){if(Q==="running")return!1;let Y=J.messages.at(-1);if(!Y)return"user-message-initial";if(Y.role==="assistant")return Y.state.type==="complete"&&Y.state.stopReason==="end_turn"?"user-message-reply":!1;if(Y.content.some((X)=>X.type==="tool_result"&&X.run.status==="blocked-on-user"))return"user-tool-approval";if(Y.content.some((X)=>X.type==="tool_result"&&X.run.status==="in-progress"))return"tool-running";return!1}r0();L0();Jq();var Pl0=N6(b6(),1);var El0=N6(dP(),1);function Il0(J){if(J.status==="done"){if(J.result!==null&&typeof J.result==="object"&&"output"in J.result&&typeof J.result.output==="string"){if("truncation"in J.result&&typeof J.result.truncation==="object"&&J.result.truncation!==null&&"prefixLinesOmitted"in J.result.truncation&&typeof J.result.truncation.prefixLinesOmitted==="number"){let Q=J.result.truncation.prefixLinesOmitted;return`--- Truncated ${Q} ${r9(Q,"line")} above this ---
3205
- `+J.result.output}return J.result.output}}return El0.default.stringify(J)}var Po4=Pl0.metrics.getMeter("thread-worker-service"),XI1=Po4.createGauge("thread_worker_count",{description:"Number of active thread workers"});class Rl0{threadWorkers=new zk;async getOrCreateForThread(J,Q){if(await J.threadService.getPrimitiveProperty(Q,"mainThreadID"))return this.getOrCreateForSubThread(J,Q);return this.getOrCreateForThreadInternal(J,Q)}async getOrCreateForSubThread(J,Q){return this.getOrCreateForThreadInternal(J,Q)}async getOrCreateForThreadInternal(J,Q){let Y=this.threadWorkers.get(Q);if(!Y){if(Y=new Cb(J,Q),this.threadWorkers.set(Q,Y),this.threadWorkers.size>25)h.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Q,totalWorkerCount:this.threadWorkers.size})}return XI1.record(this.threadWorkers.size),Y}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(k4((J)=>J.size===0?X0.of({}):d8(...Array.from(J.values()).map((Q)=>Q.status.pipe(q6((Y)=>[Q.threadID,Q.threadReadWriter?IA(Q.thread,Y):void 0])))).pipe(q6((Q)=>Object.fromEntries(Q)))),y$(25),x8())}get(J){return this.threadWorkers.get(J)}prettyPrintToolRun(J,Q){let Y=this.threadWorkers.get(J);if(!Y)throw Error(`No worker found for thread ${J}`);for(let X of Y.thread.messages)for(let G of X.content)if(G.type==="tool_result"&&G.toolUseID===Q)return Il0(G.run);throw Error(`Tool run not found for thread ${J} and tool use ${Q}`)}async cancelToolOnly(J,Q){await this.threadWorkers.get(J)?.cancelToolOnly(Q)}async cancel(J){await this.threadWorkers.get(J)?.cancel()}async dispose(J){let Q=this.threadWorkers.get(J);if(Q)await Q.asyncDispose(),this.threadWorkers.delete(J),XI1.record(this.threadWorkers.size);this.threadWorkers.dispose()}async retry(J){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No active worker for thread ${J}`);await Q.retry()}async revertFileChanges(J,Q){let Y=this.threadWorkers.get(J);if(!Y)throw Error(`No active worker for thread ${J}`);await Y.revertFileChanges(Q)}async getFilesAffectedByTruncation(J,Q){let Y=this.threadWorkers.get(J);if(!Y)throw Error(`No active worker for thread ${J}`);return Y.getFilesAffectedByTruncation(Q)}async cleanupThreadBackups(J,Q){let Y=this.threadWorkers.get(Q);if(Y)await Y.fs.tracker.cleanupBackups();else{let X=await J.threadService.get(Q);if(!X)return;let G=J.vfs.fileSystemWithMountedTrees(Ax(X));try{await new ux(G).cleanup(Q),h.debug(`Cleaned up backup files for thread ${Q}`,{threadID:Q})}catch(Z){h.error("Error cleaning up thread backups",Z,{threadID:Q})}}}async disposeAll(){await Promise.all(Array.from(this.threadWorkers.values()).map(async(J)=>await J.asyncDispose())),this.threadWorkers.clear(),XI1.record(0)}}var E3=new Rl0;G4();r0();D3();W3();hU();function Tl0(J){let Q=[],Y=/@((?:[^\s@\\,;]|\\.)+)/g,X;while((X=Y.exec(J))!==null){let G=X[1],Z=Ro4(G).replace(/[.,;:!?)}\]]+$/,"");Q.push(Z)}return Q}function Ro4(J){if(J.match(/^[A-Za-z]:[\\]/))return J.replace(/\\(.)/g,(Q,Y)=>{if(Y===" "||Y==="("||Y===")"||Y==="["||Y==="]"||Y==="?"||Y==="*")return Y;return Q});return J.replace(/\\(.)/g,"$1")}t8();OL();async function Sl0(J,{configService:Q,filesystem:Y}){let X={sentAt:Date.now()},G=await M6(Q.workspaceRoots)??[],Z=d2(J.content);if(G.length===0)return{role:"user",content:J.content,source:J.source,fileMentions:void 0,userState:void 0,agentMode:J.agentMode,meta:X};let q=await zr({fileSystem:Y},Tl0(Z),{searchPaths:G,shouldIncludeImages:!J.agentMode||uk(J.agentMode)}),V;if(q?.files&&q.files.length>0){let H=new Set,z=[];for(let U of q.files){let N=l4(U.uri),M=await cP(Y,N,G,null,H);for(let L of M){if(!z.some((A)=>A.uri===L.uri))z.push(L);H.add(L.uri)}}if(z.length>0)V=z}let K=await(await Promise.resolve().then(() => (jl0(),Cl0))).getUserState();return{role:"user",content:q?.imageBlocks?.length?[...J.content,...q.imageBlocks]:J.content,source:J.source,fileMentions:q,userState:{...K??fS0},agentMode:J.agentMode,discoveredGuidanceFiles:V,meta:X}}class Cb{deps;threadID;async resumeInProgressTools(){for(let J of this.thread.messages){if(J.role!=="user")continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;if(!(!N2(Q.run)&&Q.run.status!=="blocked-on-user"&&!this.ops.tools[Q.toolUseID]))continue;let X=this.findToolUseById(Q.toolUseID);if(!X)continue;if(X.name===d9||X.name===QB0){this.findAndCancelToolRun(Q.toolUseID);continue}h.debug(`re-invoking tool ${X.name} with ID ${Q.toolUseID}`,{name:"resumeInProgressTools",threadID:this.threadID}),this.invokeTool(X,Q.userInput)}}await this.updateFileChanges()}findToolUseById(J){for(let Q of this.thread.messages){if(Q.role!=="assistant")continue;for(let Y of Q.content)if(Y.type==="tool_use"&&Y.id===J)return Y}return}trackFilesFromHistory(){h.debug("Tracking files from thread history",{name:"trackFilesFromHistory",threadID:this.threadID});for(let J of this.thread.messages){if(J.role==="user"&&J.fileMentions?.files)this.trackFiles(J.fileMentions.files.map((Q)=>Q.uri).filter((Q)=>Q!==void 0));if(J.role==="user"){for(let Q of J.content)if(Q.type==="tool_result"&&Q.run.status==="done")this.trackFiles(Q.run.trackFiles??[])}}}async getConfig(J){return M6(this.deps.configService.config,J)}async getCodeHostService(J){if(!this.codeHostService){let Q=this.thread.env?.initial.trees||[],Y=await this.getConfig(J);this.codeHostService=gR0(Q,this.deps.threadService,this.deps.mcpService,Y,this.threadID)}return this.codeHostService}setupSettingsChangeHandlers(){this.setupPermissionsChangeHandler()}setupPermissionsChangeHandler(){this.deps.configService.config.pipe(q6((J)=>JI(J.settings?.permissions)),_4(),YU0(1),uF(this.disposed$)).subscribe(()=>{this.reevaluateBlockedTools()})}reevaluateBlockedTools(){for(let J=this.thread.messages.length-1;J>=0;J--){let Q=this.thread.messages[J];if(!Q||Q.role!=="user")continue;let Y=!1;for(let X of Q.content)if(X.type==="tool_result"&&X.run?.status==="blocked-on-user"&&X.toolUseID)Y=!0,this.checkAndApproveBlockedTool(X.toolUseID);if(!Y)break}}async checkAndApproveBlockedTool(J){try{let Q=this.findToolUseById(J);if(!Q){h.warn("Tool use block not found for blocked tool",{toolUseID:J});return}let Y=await y11(Q.name,Q.input??{},{configService:this.deps.configService},this.thread.mainThreadID?"subagent":"thread",this.threadID,J);if(Y.permitted)h.info("Auto-approving previously blocked tool due to permission change",{toolName:Q.name,toolUseID:J,threadID:this.threadID}),this.handle({type:"user:tool-input",toolUse:J,value:{accepted:!0}});else h.debug("Tool remains blocked after permission change",{toolName:Q.name,toolUseID:J,reason:Y.reason})}catch(Q){h.warn("Failed to re-evaluate blocked tool",{error:Q,toolUseID:J})}}async cleanupTaskToolSubThreads(J=this.thread.messages.length){let Q=this.thread.messages.slice(0,J),Y=Qq1(Q),X=new Set(Y.map((Z)=>Z.toolUseID)),G=new Set;for(let[Z]of this.registeredSubthreads.entries())if(!X.has(Z))G.add(Z);for(let Z of G){let q=this.registeredSubthreads.get(Z);if(q.fileChanges?.unsubscribe(),await q.worker?.revertFileChanges(),q.latestFiles=[],this.mergeAndEmit(),await this.cleanupThreadBackups(q.threadID),await q.worker?.asyncDispose(),this.deps.deleteThread)try{await this.deps.deleteThread(q.threadID)}catch(V){h.error(`Failed to delete Task tool sub-thread: ${q.threadID}`,V,{threadID:this.threadID,subThreadID:q.threadID})}else h.warn(`Cannot delete Task tool sub-thread: ${q.threadID} - threadHistoryService not available`,{threadID:this.threadID,subThreadID:q.threadID});this.registeredSubthreads.delete(Z)}if(G.size>0)this.emitSubthreads()}ops={tools:{},toolMessages:{},inference:null};_state=new R5("initial");state=this._state.pipe(_4(),x8({shouldCountRefs:!0}));handleMutex=new s$;ephemeralError=new R5(void 0);inferenceState=new R5("idle");fileChanges=new R5({files:[]});toolCallUpdates=new i4;trackedFiles=new _Y;fs;cachedFileChanges=[];registeredSubthreads=new Map;subthreadSequenceNumber=0;_subthreadsSubject=new R5([]);subthreads=this._subthreadsSubject.pipe(_4(),x8({shouldCountRefs:!0}));disposed$=new i4;isDisposed=!1;cancelledToolUses=new Set;codeHostService=null;shouldContinueAfterRejection=!1;lastInferenceRequestId;constructor(J,Q){this.deps=J;this.threadID=Q;this.fs=Fl0({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.vfs,Q,()=>Ax(this.thread))}status=this.state.pipe(k4((J)=>J==="active"?d8(this.inferenceState.pipe(_4()),this.fileChanges.pipe(_4()),this.ephemeralError,this.toolCallUpdates.pipe(c8(void 0))).pipe(q6(([Q,Y,X])=>({state:J,inferenceState:Q,fileChanges:Y,ephemeralError:X?{message:X.message,stack:"stack"in X?X.stack:void 0,error:"error"in X&&X.error&&typeof X.error==="object"&&"error"in X.error?X.error.error:void 0}:void 0})),uF(this.disposed$)):X0.of({state:J})),x8({shouldCountRefs:!0}));threadReadWriter=null;get thread(){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);return this.threadReadWriter.read()}set thread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.write(J),this.__testing__setThread(J)}updateThread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.update(Av0(J)),this.__testing__setThread(this.threadReadWriter.read())}async acquireThread(){if(!this.threadReadWriter)this.threadReadWriter=await this.deps.threadService.exclusiveSyncReadWriter(this.threadID),this._state.next("active")}__testing__setThread(J){}__testing__getDeps(){return this.deps}async resume(){if(this.resumed)return;if(this.resumed=!0,this.handleCalled)throw Error("cannot call ThreadWorker.resume after ThreadWorker.handle");await this.acquireThread(),await this.restoreFileChangesFromBackups();let J=this.thread.messages.at(-1);if(J?.role==="assistant"&&J.state.type==="streaming")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});if(this.trackFilesFromHistory(),await this.initializeCompletedSubthreads(),this.thread.mainThreadID)return;if(sB0(J)||tB0(J)&&!this.shouldContinueAfterRejection||Yq1(J)){this.inferenceState.next("cancelled");return}await this.resumeInProgressTools(),this.setupSettingsChangeHandlers();let Q=this.thread.messages.findLastIndex((X)=>X.role==="user"?eB0(X):X.role==="assistant"&&X.state.type==="complete");if(Q===-1){if(this.thread.messages.length!==0)throw Error(`(bug) invalid thread: ${this.threadID}`);return}let Y=this.thread.messages[Q];switch(Y.role){case"user":if(!Y.interrupted)this.onThreadDelta({type:"user:message",message:Y});break;case"assistant":this.onThreadDelta({type:"assistant:message",message:Y});break}}resumed=!1;async initializeCompletedSubthreads(){let J=Qq1(this.thread.messages);for(let{toolUseID:Q,threadID:Y,toolUse:X,toolResult:G}of J){let Z=N2(G.run),q=G.run.status==="blocked-on-user";if(Z&&!q)await this.registerSubthread(Q,Y,X)}}async forkThread(J){await this.acquireThread();let{threadService:Q}=this.deps,Y=await Q.forkThread(this.threadID,J);await this.handle({type:"fork:created",forkThreadID:Y.threadID,fromMessageIndex:J});let X=await Q.getPrimitiveProperty(this.threadID,"v");if(X!==null)await Q.flushVersion(this.threadID,X);return Y.threadID}async handle(J,Q){await this.handleMutex.acquire();try{await this.innerHandle(J,Q)}finally{this.handleMutex.release()}}async innerHandle(J,Q){if(this.isDisposed){h.debug(`Skipping ${J.type} - worker disposed.`,{name:"handle queue",threadID:this.threadID});return}if(Q?.aborted){h.debug(`Skipping ${J.type} - signal aborted.`,{name:"handle queue",threadID:this.threadID});return}if(await this.resume(),this.handleCalled=!0,await this.acquireThread(),J.type==="thread:truncate")await this.cleanupFileChanges(J.fromIndex),await this.cleanupTaskToolSubThreads(J.fromIndex);let Y=J;if(J.type==="user:message"){let X=await Sl0(J.message,{configService:this.deps.configService,filesystem:this.fs.fileSystemReader()});Y=JU(J,(G)=>{G.message=l8(X),Q?.throwIfAborted()})}try{if(this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);let X=J.type==="user:message"&&J.index!==void 0;if(this.updateThread(Y),this.onThreadDelta(Y),X)await this.cleanupFileChanges(),await this.cleanupTaskToolSubThreads(),await this.cleanupForkThreads()}catch(X){if(!xQ(X))h.error("Ephemeral error during handle processing",X,{name:"ThreadWorker",threadID:this.threadID}),this.ephemeralError.next(X instanceof Error?X:Error(String(X)));else h.debug(`AbortError caught during handle processing for ${Y.type}.`,{name:"handle queue",threadID:this.threadID})}}handleCalled=!1;onThreadDelta(J){switch(J.type){case"user:message":{if(J.index!==void 0)this.trackedFiles.clear(),this.thread.messages.forEach((Q)=>{if(Q.role==="user"){for(let Y of Q.content)if(Y.type==="tool_result"&&Y.run.status==="done"&&Y.run.trackFiles)this.trackFiles(Y.run.trackFiles);if(Q.fileMentions?.files)this.trackFiles(Q.fileMentions.files.map((Y)=>Y.uri).filter((Y)=>Y!==void 0))}});else this.trackFiles(J.message.fileMentions?.files?.map((Q)=>Q.uri).filter((Q)=>Q!==void 0)??[]);this.runInferenceAndUpdateThread();break}case"user:message-queue:dequeue":{let Q=this.thread.messages.at(-1);if(!Q)break;if(Q.role!=="user")break;this.trackFiles(Q.fileMentions?.files?.map((Y)=>Y.uri).filter((Y)=>Y!==void 0)??[]),this.runInferenceAndUpdateThread();break}case"user:tool-input":{let Q=IX(this.thread,J.toolUse);if(Q)this.invokeTool(Q,J.value);break}case"tool:data":{if(this.cancelledToolUses.has(J.toolUse)){this.updateThread({type:"tool:data",toolUse:J.toolUse,data:{status:"cancelled",reason:"cancelled by user message"}});return}let Q=IX(this.thread,J.toolUse);if(J.data.status==="in-progress"&&Q?.name===qJ){let Y=Q,X=Jq1(J.data.progress);if(X)this.registerSubthread(J.toolUse,X,Y)}if(N2(J.data)){this.cancelledToolUses.delete(J.toolUse);let Y=this.ops.toolCompletionResolvers?.[J.toolUse];if(Y){if(J.data.status==="done")Y.resolve();else Y.reject(Error(`Tool ${J.data.status}: ${J.toolUse}`));delete this.ops.toolCompletionResolvers?.[J.toolUse]}}if(Q){let Y=Co4(this.thread,J.toolUse,this.shouldContinueAfterRejection);h.debug(`updated tool_result${Y?" and running inference because all tools completed":""}`,{name:`handleThreadDelta(${J.type}, ${J.toolUse}, ${J.data.status})`,threadID:this.threadID});let X=this.shouldContinueAfterRejection||this.inferenceState.getValue()!=="cancelled";if(Y&&X)this.runInferenceAndUpdateThread()}this.toolCallUpdates.next();break}case"assistant:message":{let Q=this.findToolUsesNeedingInvocation(J.message);h.debug(`saw ${Q.length} tool uses (${Q.map((Y)=>Y.name).join(", ")})`,{name:`handleThreadDelta(${J.type})`,threadID:this.threadID}),this.executeToolsWithPlan(Q);break}case"user:message-queue:enqueue":{let Q=this.inferenceState.getValue();if(YI1(this.thread,Q)!=="tool-running"){if(Q==="cancelled"){this.handle({type:"user:message-queue:dequeue"});break}else if(Q==="idle"){let X=this.thread.messages.at(-1);if(X?.role==="assistant"){if(X.state.type==="cancelled"||X.state.type==="error"){this.handle({type:"user:message-queue:dequeue"});break}if(X.state.type==="complete"&&X.state.stopReason!=="tool_use"){this.handle({type:"user:message-queue:dequeue"});break}}else if(X?.role==="info"){this.handle({type:"user:message-queue:dequeue"});break}}}break}case"info:manual-bash-invocation":{this.handle({type:"user:message-queue:dequeue"});break}case"info:skill-injection":break;case"cancelled":break;case"inference:completed":{let Q=KJ(this.thread,"assistant");if(Q&&Q.state.type==="complete"&&Q.state.stopReason==="refusal"){this.ephemeralError.next(Error("The model refused to respond to this request. Please retry with a different prompt."));break}if(Q){let X=this.findToolUsesNeedingInvocation(Q);this.executeToolsWithPlan(X)}if(Q&&Q.state.type==="complete"&&Q.state.stopReason==="end_turn")if(this.thread.queuedMessages&&this.thread.queuedMessages.length>0)this.handle({type:"user:message-queue:dequeue"});else g11(this,Ol0(this.deps.internalHooks?.onAssistantTurnEnd,{thread:this.thread}));break}}}findToolUsesNeedingInvocation(J){if(J.content.some((G)=>G.type==="tool_use"&&!p2(G)))return[];if(!(J.state?.type==="complete"||J.state?.type==="cancelled"))return[];let X=QQ(this.thread);return J.content.filter((G)=>G.type==="tool_use").filter((G)=>!X.has(G.id)&&!this.cancelledToolUses.has(G.id))}async getWorkspaceRoots(J){return await M6(this.deps.configService.workspaceRoots,J)??this.thread.env?.initial?.trees?.map((Q)=>Q.uri).filter((Q)=>Q!==void 0).map(sJ)??[]}async executeToolsWithPlan(J){if(J.length===0)return;let Q=Ul0(J,this.deps.toolService);h.debug(`executing ${J.length} tools in ${Q.length} batch(es)`,{name:"executeToolsWithPlan",threadID:this.threadID,batches:Q.map((Y)=>Y.map((X)=>X.name))}),await this.executeToolBatchesSequentially(Q)}async executeToolBatchesSequentially(J){for(let Q of J){let X=(await Promise.allSettled(Q.map((G)=>this.invokeToolAndWait(G,void 0)))).filter((G)=>G.status==="rejected");if(X.length>0)h.warn(`${X.length} tool(s) failed in batch`,{name:"executeToolBatchesSequentially",threadID:this.threadID,errors:X.map((G)=>G.reason)})}}async invokeToolAndWait(J,Q){let Y=new Promise((X,G)=>{if(!this.ops.toolCompletionResolvers)this.ops.toolCompletionResolvers={};this.ops.toolCompletionResolvers[J.id]={resolve:X,reject:G}});this.invokeTool(J,Q).catch((X)=>{let G=this.ops.toolCompletionResolvers?.[J.id];if(G)h.debug(`Tool invocation setup failed for ${J.id}`,{name:"invokeToolAndWait",threadID:this.threadID,error:String(X)}),G.reject(X),delete this.ops.toolCompletionResolvers?.[J.id]}),await Y}async invokeTool(J,Q){if(this.ops.tools[J.id])throw Error(`(bug) tool invocation already in progress: ${J.id}`);if(!p2(J))throw Error(`(bug) tool use is incomplete: ${J.id}`);let Y=await this.getConfig(),X=Ll0(Y.settings?.hooks,{threadID:this.threadID,toolUse:J}),{abortOp:G}=await g11(this,X);if(G){let q=this.ops.toolCompletionResolvers?.[J.id];if(q)q.resolve(),delete this.ops.toolCompletionResolvers?.[J.id];return}let Z=new AbortController;this.ops.tools[J.id]=Z,this.updateThread({type:"tool:data",toolUse:J.id,data:{status:"in-progress"}});try{let q=await this.getWorkspaceRoots(Z.signal),V=BI(this.thread),K=new X0((M)=>{this.ops.toolMessages[J.id]=M}),W=await this.getCodeHostService(Z.signal),H={...this.deps,dir:q.at(0)??null,dirs:q,tool:J.name,thread:this.thread,config:await this.getConfig(),trackedFiles:new _Y(this.trackedFiles),filesystem:this.fs.trackedFileSystem(J.id),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:J.id,todos:V,toolMessages:K,threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),pullRequestChanges:W.pullRequestChanges,agentMode:await this.getSelectedAgentMode()},z=this.deps.toolService.preprocessArgs?.(J.name,J.input,H);if(z)this.handle({type:"tool:processed",toolUse:J.id,newArgs:z});let U=z??J.input,N=this.deps.toolService.invokeTool(J.name,{args:U,userInput:Q},H).pipe(uF(this.disposed$),k$(()=>{delete this.ops.tools[J.id],this.ops.toolMessages[J.id]?.complete(),delete this.ops.toolMessages[J.id]})).subscribe({next:async(M)=>{if(h.debug(`${J.id}, ${M.status}`,{name:"invokeTool",threadID:this.threadID}),N2(M)){delete this.ops.tools[J.id],N.unsubscribe();let L=this.ops.toolCompletionResolvers?.[J.id];if(L){if(M.status==="done")L.resolve();else L.reject(Error(`Tool ${M.status}: ${J.id}`));delete this.ops.toolCompletionResolvers?.[J.id]}if(M.status==="done"&&M.trackFiles?.length)this.trackFiles(M.trackFiles);if(Y.settings?.hooks){let A=Al0(Y.settings.hooks,{threadID:this.threadID,toolUse:J});await g11(this,A,{toolUseID:J.id})}}await this.updateFileChanges(),await this.handle({type:"tool:data",toolUse:J.id,data:M},Z.signal)},error:async(M)=>{let L=this.ops.toolCompletionResolvers?.[J.id];if(L)L.reject(M),delete this.ops.toolCompletionResolvers?.[J.id];await this.handle({type:"tool:data",toolUse:J.id,data:{status:"error",error:{message:"message"in M?M.message:String(M),displayMessage:"displayMessage"in M?M.displayMessage:void 0}}},Z.signal)},complete:()=>{let M=this.ops.toolCompletionResolvers?.[J.id];if(!M)return;let L=QQ(this.thread).get(J.id)?.run;if(L&&N2(L))return;let A;if(this.isDisposed)A="Worker disposed";else if(Z.signal.aborted)A="Tool aborted";else if(this.cancelledToolUses.has(J.id))A="Tool cancelled";else A="Tool observable completed without terminal state";M.reject(Error(A)),delete this.ops.toolCompletionResolvers?.[J.id]}});aM(Z.signal,()=>N.unsubscribe())}catch(q){delete this.ops.tools[J.id];let V=this.ops.toolCompletionResolvers?.[J.id];if(V)V.reject(q),delete this.ops.toolCompletionResolvers?.[J.id];throw q}}async cancelInProgressTools(){for(let J of Object.keys(this.ops.tools))await this.cancelTool(J)}cancelAllActiveTools(){let J=QQ(this.thread);for(let Q of this.thread.messages){if(Q.role!=="assistant")continue;for(let Y of Q.content)if(Y.type==="tool_use"&&p2(Y)){let X=J.get(Y.id);if(!(X&&N2(X.run)))this.cancelledToolUses.add(Y.id)}}for(let Q of this.thread.messages)if(Q.role==="user"){for(let Y of Q.content)if(Y.type==="tool_result"){if(!N2(Y.run))this.cancelledToolUses.add(Y.toolUseID)}}}cancelUnstartedTools(){let J=QQ(this.thread),Q=this.thread.messages.findLastIndex((X)=>Yq1(X)),Y=Q===-1?this.thread.messages:this.thread.messages.slice(Q+1);for(let X of Y){if(X.role!=="assistant")continue;for(let G of X.content)if(G.type==="tool_use"&&p2(G)){let Z=J.get(G.id);if(!Z||Z.run.status==="blocked-on-user")this.updateThread({type:"tool:data",toolUse:G.id,data:{status:"cancelled"}})}}}rollbackPartialAssistantMessage(){let J=-1;for(let Q=this.thread.messages.length-1;Q>=0;Q--)if(this.thread.messages[Q]?.role==="user"){J=Q;break}if(J>=0&&J<this.thread.messages.length-1)return this.updateThread({type:"thread:truncate",fromIndex:J+1}),!0;return!1}async runInferenceAndUpdateThread(J=0){this.ops.inference?.abort(),this.ops.inference=null,this.inferenceState.next(J>0?"retrying":"running");let Q=new AbortController;this.ops.inference=Q,this.cancelAllActiveTools(),this.cancelUnstartedTools(),await this.cancelInProgressTools();for(let V of this.thread.messages)if(V.role==="user"){for(let K of V.content)if(K.type==="tool_result"&&K.run.status==="blocked-on-user")this.updateThread({type:"tool:data",toolUse:K.toolUseID,data:{status:"cancelled"}})}let Y=this.thread.messages.at(-1);if(this.thread.mainThreadID===void 0&&Y?.role==="user"&&this.thread.messages.filter((V)=>V.role==="user").length===1){if(this.deps.getThreadEnvironment)this.deps.getThreadEnvironment().then(async(V)=>{this.updateThread({type:"environment",env:{initial:{...this.thread.env?.initial,...V}}})}).catch((V)=>{h.error("Failed to initialize thread environment",V,{threadID:this.threadID})})}if(this.thread.mainThreadID===void 0&&!this.thread.title)this.getConfig(Q.signal).then((V)=>{if(Q.signal.aborted)return;let K=V.settings?.["agent.skipTitleGenerationIfMessageContains"]||[],W=this.thread.messages.find((H)=>{if(H.role!=="user")return!1;if(K.length===0)return!0;let z=d2(H.content);return!K.some((U)=>z.includes(U))});if(W)this.deps.generateThreadTitle(W,this.thread,this.deps.configService,Q.signal).then(({title:H,usage:z})=>{if(Q.signal.aborted||this.isDisposed)return;if(H!==void 0&&this.thread.title!==H)this.updateThread({type:"title",value:H,usage:z})}).catch((H)=>{if(!xQ(H))h.error("generateThreadTitle error",H,{name:"ThreadWorker",threadID:this.threadID})})}).catch((V)=>{if(!xQ(V))h.error("ThreadWorker title generation config error",V)});let G=await this.getConfig(),{model:Z,agentMode:q}=Tb(G.settings,this.thread);try{let[V,K,W]=Z.match(/(.*?)\/(.*)/)??[],H=ql0(K??"",W??""),z=crypto.randomUUID();this.lastInferenceRequestId=z;let U=H.stream({model:W??"",thread:this.thread,buildSystemPromptDeps:{toolService:this.deps.toolService,configService:this.deps.configService,getThreadEnvironment:this.deps.getThreadEnvironment,filesystem:this.fs.fileSystemReader(),threadService:this.deps.threadService},signal:Q.signal,agentMode:q,retryCount:J,clientRequestId:z}),N;for await(let M of U){if(this.inferenceState.getValue()==="retrying")this.inferenceState.next("running");N=M,await this.handle({type:"assistant:message-update",message:M})}if(N?.usage&&this.lastInferenceRequestId){let{fetchCreditsByRequestId:M}=await Promise.resolve().then(() => (bB(),yl0)),L=await M(this.lastInferenceRequestId,this.deps.configService,{signal:Q.signal});if(L!==null)N={...N,usage:{...N.usage,credits:L}};this.lastInferenceRequestId=void 0}await this.handle({type:"inference:completed",model:N?.usage?.model,usage:N?.usage})}catch(V){if(!(xQ(V)||nw0(V))){let K=V instanceof Error?V:Error(String(V));if((this.threadReadWriter?this.rollbackPartialAssistantMessage():!1)&&J<qK.maxRetries)return h.info("Retrying after midstream error",{threadID:this.threadID,attempt:J+1,maxRetries:qK.maxRetries}),this.runInferenceAndUpdateThread(J+1);this.ephemeralError.next(K)}return}finally{if(this.ops.inference===Q)this.ops.inference=null,this.inferenceState.next("idle")}}async findAndCancelToolRun(J,Q){if(this.cancelInference(),!IX(this.thread,J))return;await this.cancelTool(J,Q)}async cancelToolOnly(J,Q){if(!IX(this.thread,J))return;let X=this.cancelDataForToolRun(J);await this.cancelSubthread(J);let G=this.ops.toolMessages[J];if(G){try{G.next({type:"stop-command"})}catch(Z){h.warn("Failed to send stop-command",{id:J,error:Z})}G.complete(),delete this.ops.toolMessages[J]}h.debug(`cancelToolOnly(${J})`),await this.handle({type:"tool:data",toolUse:J,data:X},Q)}invokeBashTool(J,Q,Y){return new X0((X)=>{let G,Z,q,K=((H)=>{return aM(H,()=>{if(h.warn("Manual bash abort -> unsubscribe",{threadID:this.threadID}),q?.unsubscribe(),Z?.unsubscribe(),X?.complete(),G)this.handleManualBashInvocation(J,{status:"cancelled",progress:t$1(G)},Y)})})(Q);return(async()=>{try{if(Q.aborted){X.error(Error("Operation was aborted"));return}let H=await this.getWorkspaceRoots(Q),z=await this.getConfig(Q),U=await this.getCodeHostService(Q),N={...this.deps,dir:H.at(0)??null,dirs:H,tool:d9,thread:this.thread,config:z,trackedFiles:new _Y(this.trackedFiles),filesystem:cI0(this.fs.fileSystemReader()),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:CM(),todos:[],threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),pullRequestChanges:U.pullRequestChanges};Z=this.deps.toolService.invokeTool(d9,{args:J,userInput:{accepted:!0}},N).subscribe({next:(M)=>{G=M,X.next(M)},error:(M)=>{X.error(M)},complete:()=>{if(G)this.handleManualBashInvocation(J,G,Y);X.complete()}}),q=this.disposed$.subscribe(()=>{K(),Z?.unsubscribe(),X?.complete()})}catch(H){X.error(H)}})(),()=>{K(),Z?.unsubscribe(),q?.unsubscribe()}})}async handleManualBashInvocation(J,Q,Y){await this.handle({type:"info:manual-bash-invocation",args:J,toolRun:Q,hidden:Y})}async cleanupThreadBackups(J){try{await this.fs.tracker.cleanupBackups(),h.debug(`Cleaned up backup files for thread ${J}`,{threadID:J})}catch(Q){h.error("Error cleaning up thread backups",Q,{threadID:J})}}cancelDataForToolRun(J){let Y=QQ(this.thread).get(J)?.run;return{status:"cancelled",progress:Y?t$1(Y):void 0}}async cancelTool(J,Q){let Y=this.cancelDataForToolRun(J);await this.cancelSubthread(J);let X=this.ops.toolMessages[J];if(X){try{X.next({type:"stop-command"})}catch(G){h.warn("Failed to send stop-command",{id:J,error:G})}X.complete(),delete this.ops.toolMessages[J]}h.debug(`cancelToolRun(${J})`),await this.handle({type:"tool:data",toolUse:J,data:Y},Q)}async cancel(){h.debug("cancel: aborting inference operation and tools"),this.cancelInference(),this.cancelAllActiveTools(),this.cancelUnstartedTools(),await this.cancelInProgressTools(),await this.handle({type:"cancelled"},void 0)}cancelInference(){if(this.ops.inference)this.ops.inference.abort(Error(yF1.USER_CANCELLED)),this.ops.inference=null;this.inferenceState.next("cancelled")}async retry(){if(h.debug("retry: retrying inference operation"),this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);if(this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;let J=this.thread.messages.at(-1);if(J?.role==="assistant"&&J.state.type==="complete"&&J.state.stopReason==="refusal")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});this.inferenceState.next("idle"),await this.runInferenceAndUpdateThread()}setTestEphemeralError(J){this.ephemeralError.next(J)}async cancelSubthread(J){let Q=this.registeredSubthreads.get(J);if(Q&&Q.worker)await Q.worker.cancel()}abortToolOp(J){this.ops.tools[J]?.abort(),delete this.ops.tools[J]}abortAllTools(){for(let J of Object.keys(this.ops.tools)){let Q=J,Y=this.ops.toolMessages[Q];if(Y)try{Y.next({type:"stop-command"}),Y.complete(),delete this.ops.toolMessages[Q]}catch(X){h.warn("Failed to send stop-command during disposal",{id:Q,error:X})}this.abortToolOp(Q)}}trackFiles(J){for(let Q of J)this.trackedFiles.add(Q)}async restoreFileChangesFromBackups(){try{let J=await this.fs.tracker.restoreFromBackups();h.debug(`Restored ${J.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(J){h.error("Error restoring file changes",J,{threadID:this.threadID})}}async revertFileChanges(J){for(let Q of this.registeredSubthreads.values()){let Y=Q?.worker;if(Y)await Y.revertFileChanges(J)}await this.fs.tracker.revertAll(J),await this.updateFileChanges()}async getAllTrackedChanges(){let J=new Map;for(let Y of this.registeredSubthreads.values()){let X=Y?.worker;if(X){let G=await X.getAllTrackedChanges();for(let[Z,q]of G.entries())J.set(Z,q)}}let Q=await this.fs.tracker.getAllRecords();for(let[Y,X]of Q.entries())J.set(Y,X);return J}async cleanupForkThreads(J=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:J})}async getToolUsesToRevert(J=this.thread.messages.length){let Q=new Set;this.thread.messages.slice(0,J).forEach((G)=>{if(G.role==="user"){for(let Z of G.content)if(Z.type==="tool_result")Q.add(Z.toolUseID)}else for(let Z of G.content)if(Z.type==="tool_use")Q.add(Z.id)});let Y=new Set,X=await this.fs.tracker.getAllRecords();for(let[G]of X.entries())if(!Q.has(G))Y.add(G);return Y}async getFilesAffectedByTruncation(J){let Q=await this.getToolUsesToRevert(J);if(Q.size===0)return[];return this.fs.tracker.getFilesForToolUses(Q)}async cleanupFileChanges(J=this.thread.messages.length){let Q=await this.getToolUsesToRevert(J);if(Q.size===0)return;await this.fs.tracker.revertChanges(Q),await this.updateFileChanges()}async updateFileChanges(){this.cachedFileChanges=await Dl0(this.fs.tracker),this.mergeAndEmit()}mergeAndEmit(){let J=new L2;for(let Y of this.cachedFileChanges)J.set(Y.uri,Y);for(let Y of this.registeredSubthreads.values())for(let X of Y.latestFiles??[])J.set(X.uri,X);let Q=J.size;if(Q>50)h.warn("Excessive file changes detected - potential memory issue",{name:"mergeAndEmit",threadID:this.threadID,fileChangeCount:Q,ownFileChanges:this.cachedFileChanges.length,subthreadCount:this.registeredSubthreads.size});this.fileChanges.next({files:[...J.values()]})}emitSubthreads(){let J=Array.from(this.registeredSubthreads.values()).sort((Q,Y)=>Q.sequenceNumber-Y.sequenceNumber).map((Q)=>({threadID:Q.threadID,toolUse:Q.toolUse,sequenceNumber:Q.sequenceNumber}));this._subthreadsSubject.next(J)}async registerSubthread(J,Q,Y){if(this.registeredSubthreads.has(J))return;let X=await E3.getOrCreateForSubThread(this.deps,Q);await X.resume();let G=X.status.pipe(D7((Z)=>Z.state==="active"),q6((Z)=>Z.fileChanges.files),uF(this.disposed$)).subscribe((Z)=>{let q=this.registeredSubthreads.get(J);if(!q)return;q.latestFiles=Z,this.mergeAndEmit()});this.registeredSubthreads.set(J,{threadID:Q,worker:X,fileChanges:G,toolUse:Y,sequenceNumber:++this.subthreadSequenceNumber}),this.emitSubthreads()}continueInferenceAfterRejection(J=!0){this.shouldContinueAfterRejection=J}async asyncDispose(){if(this.isDisposed)return;if(h.debug("ThreadWorker disposal starting",{name:"ThreadWorker.dispose",threadID:this.threadID,subthreadCount:this.registeredSubthreads.size,activeToolCount:Object.keys(this.ops.tools).length}),this.isDisposed=!0,this.disposed$.next(),this.disposed$.complete(),await Promise.all(Array.from(this.registeredSubthreads.values()).map(async(J)=>{J.fileChanges?.unsubscribe(),await J.worker?.asyncDispose()})),this.registeredSubthreads.clear(),this.cancelledToolUses.clear(),this.ops.toolCompletionResolvers)for(let J of Object.keys(this.ops.toolCompletionResolvers)){let Q=this.ops.toolCompletionResolvers[J];if(Q)try{Q.reject(Error("Worker disposed"))}finally{delete this.ops.toolCompletionResolvers[J]}}if(this._state.complete(),this.ephemeralError.complete(),this.inferenceState.complete(),this.fileChanges.complete(),this.toolCallUpdates.complete(),this._subthreadsSubject.complete(),this.abortAllTools(),this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;if(this.fs.tracker.dispose(),this.codeHostService)this.codeHostService.dispose(),this.codeHostService=null;if(this.threadReadWriter)await this.threadReadWriter.asyncDispose(),this.threadReadWriter=null}async getSelectedAgentMode(){let J=await this.getConfig(),{agentMode:Q}=Tb(J.settings,this.thread);return Q}}s71([JI1],Cb.prototype,"invokeTool",null),s71([JI1],Cb.prototype,"runInferenceAndUpdateThread",null);function Co4(J,Q,Y=!1){let X=KJ(J,"assistant");if(!X||X.state.type!=="complete"||X.state.stopReason!=="tool_use")return!1;let G=X.content.filter((V)=>V.type==="tool_use").map((V)=>V.id);if(Q&&!G.includes(Q))return h.debug(`tool:data for orphaned tool_use ${Q} - ignoring for inference`,{name:"shouldRunInferenceWithToolData",threadID:J.id}),!1;if(G.length===0)return!1;let Z=QQ(J);return G.every((V)=>{let K=Z.get(V);if(!K||!N2(K.run))return!1;let W=K.run.status;if(W==="cancelled")return!1;if(W==="rejected-by-user")return Y;return!0})}class p11 extends Cb{constructor(J,Q){super(J,Q)}static fromWorker(J){let Q=J.__testing__getDeps(),Y=new p11(Q,J.threadID);return Y.threadReadWriter=J.threadReadWriter,Y}async resume(){throw Error("ReplayThreadWorker: resume() is not allowed in replay mode")}async handle(J,Q){throw Error("ReplayThreadWorker: handle() is not allowed in replay mode")}async forkThread(J){throw Error("ReplayThreadWorker: forkThread() is not allowed in replay mode")}invokeBashTool(J,Q,Y){throw Error("ReplayThreadWorker: invokeBashTool() is not allowed in replay mode")}async retry(){throw Error("ReplayThreadWorker: retry() is not allowed in replay mode")}async cancel(){throw Error("ReplayThreadWorker: cancel() is not allowed in replay mode")}async findAndCancelToolRun(J,Q){throw Error("ReplayThreadWorker: findAndCancelToolRun() is not allowed in replay mode")}async cancelToolOnly(J,Q){throw Error("ReplayThreadWorker: cancelToolOnly() is not allowed in replay mode")}async revertFileChanges(){throw Error("ReplayThreadWorker: revertFileChanges() is not allowed in replay mode")}continueInferenceAfterRejection(J){}}t8();G4();L0();class d11{storage;index=new Map;initialized=!1;initPromise=null;constructor(J){this.storage=J;this.ensureInitialized(),this.setupChangeListener()}async search(J,Q=20){if(!this.initialized)return[];if(this.index.size===0)return[];let Y=Array.from(this.index.entries()).map(([Z,q])=>{return new yY({id:Z,kind:"file",path:q,uri:d0.parse(`thread://${Z}`),metadata:{size:0,mtime:0,isSymlink:!1}})});return new fo(J,{maxResults:Q,minScore:J?400:0}).match(Y).map((Z)=>({id:Z.entry.id,title:Z.entry.path,score:Z.score}))}async ensureInitialized(){if(this.initialized)return;if(this.initPromise)return this.initPromise;return this.initPromise=this.loadIndex(),this.initPromise}async loadIndex(){try{let J=await this.storage.keys(),Q=50;for(let Y=0;Y<J.length;Y+=50){let X=J.slice(Y,Y+50),G=await Promise.all(X.map(async(Z)=>{return(await this.storage.get(Z))?.title||null}));for(let Z=0;Z<X.length;Z++){let q=X[Z],V=G[Z];if(q&&V&&V.trim().length>0)this.index.set(q,V)}if(Y+50<J.length)await new Promise((Z)=>setImmediate(Z))}this.initialized=!0,h.debug("Thread fuzzy indexer initialized",{indexedCount:this.index.size})}catch(J){h.warn("Failed to load thread index",J),this.initialized=!0}}setupChangeListener(){this.storage.changes.subscribe(async(J)=>{if(!this.initialized)return;if(J===void 0){await this.loadIndex();return}try{let Q=await this.storage.get(J);if(Q?.title)this.index.set(J,Q.title);else this.index.delete(J)}catch(Q){h.warn("Failed to update thread index for change",{key:J,error:Q})}})}dispose(){this.index.clear(),this.initialized=!1,this.initPromise=null}}r0();r0();function xl0(J){return new X0((Q)=>{let Y=!1,X=!1;(async()=>{try{let q=await J.keys();if(X)return;for(let V of q){if(X)return;let K=await J.get(V);if(X)return;Q.next({key:V,value:K,type:"initial"})}if(Y=!0,!X)Q.next({type:"initial-complete"})}catch(q){if(!X)Q.error(q)}})();let Z=J.changes.subscribe({next:async(q)=>{if(!Y||q===void 0)return;try{let V=await J.get(q);if(!X)Q.next({key:q,value:V,type:"change"})}catch(V){if(!X)Q.error(V)}},error:(q)=>Q.error(q),complete:()=>Q.complete()});return()=>{X=!0,Z.unsubscribe()}})}function vl0(J){let Q=J??{},Y=new Map,X=new i4;if(J){let G=Date.now();for(let Z of Object.keys(J))Y.set(Z,G)}return{async get(G){return Promise.resolve(Q[G])},async set(G,Z){Q[G]=Z,Y.set(G,Date.now()),X.next(G)},async delete(G){delete Q[G],Y.delete(G),X.next(G)},async keys(){return Object.keys(Q).toSorted((Z,q)=>(Y.get(q)??0)-(Y.get(Z)??0))},async path(G){return Promise.resolve(void 0)},changes:X.pipe(c8(void 0))}}t8();class GI1{storage;entriesMap=new Map;historySubject=new i4;storageSubscription;_observeHistory;constructor(J,Q={}){this.storage=J;if(!Q.lazy)this.initializeObservable()}initializeObservable(){if(this._observeHistory)return;this._observeHistory=X0.from(this.historySubject).pipe(Uk(200,{leading:!0,trailing:!0}),x8()),this.storageSubscription=xl0(this.storage).subscribe({next:(J)=>{if(J.type==="initial-complete"){this.emitCurrentList();return}let{key:Q,value:Y}=J;if(Y&&"messages"in Y)if(!(Y.messages.length===0&&!Y.draft))this.entriesMap.set(Q,jo4(Y));else this.entriesMap.delete(Q);else this.entriesMap.delete(Q);this.emitCurrentList()},error:(J)=>this.historySubject.error(J),complete:()=>{this.emitCurrentList(),this.historySubject.complete()}})}emitCurrentList(){let J=Array.from(this.entriesMap.values()).toSorted((Q,Y)=>Y.userLastInteractedAt-Q.userLastInteractedAt);this.historySubject.next(J)}observeHistory(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory}observeThreadList(){return this.observeHistory().pipe(_4((J,Q)=>{if(J.length!==Q.length)return!1;return J.every((Y,X)=>{let G=Q[X];if(!G)return!1;return Y.id===G.id&&Y.title===G.title&&Y.userLastInteractedAt===G.userLastInteractedAt&&Y.mainThreadID===G.mainThreadID&&JSON.stringify(Y.parentRelationships)===JSON.stringify(G.parentRelationships)&&JSON.stringify(Y.env?.initial?.trees?.map((Z)=>Z.displayName))===JSON.stringify(G.env?.initial?.trees?.map((Z)=>Z.displayName))})}))}dispose(){this.storageSubscription?.unsubscribe()}}function c11(J){return Math.max(J.created,...J.messages.map((Q)=>Q.role==="user"?Q.meta?.sentAt:void 0).filter((Q)=>Q!==void 0))}function jo4(J){return{id:J.id,v:J.v,created:J.created,title:J.title??null,userLastInteractedAt:c11(J),env:J.env,originThreadID:J.originThreadID,mainThreadID:J.mainThreadID,parentRelationships:ik(J),summaryStats:{diffStats:NI(J)}}}t8();function OT(J,Q){let Y=[];if(Y.push(So4(J,Q)),J.title)Y.push(`# ${J.title}`);let X=tG(J),G=X?X.index:0;for(let Z=G;Z<J.messages.length;Z++){let q=J.messages[Z];if(q)Y.push(_o4(q))}return Y.join(`
3205
+ `+J.result.output}return J.result.output}}return El0.default.stringify(J)}var Po4=Pl0.metrics.getMeter("thread-worker-service"),XI1=Po4.createGauge("thread_worker_count",{description:"Number of active thread workers"});class Rl0{threadWorkers=new zk;async getOrCreateForThread(J,Q){if(await J.threadService.getPrimitiveProperty(Q,"mainThreadID"))return this.getOrCreateForSubThread(J,Q);return this.getOrCreateForThreadInternal(J,Q)}async getOrCreateForSubThread(J,Q){return this.getOrCreateForThreadInternal(J,Q)}async getOrCreateForThreadInternal(J,Q){let Y=this.threadWorkers.get(Q);if(!Y){if(Y=new Cb(J,Q),this.threadWorkers.set(Q,Y),this.threadWorkers.size>25)h.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Q,totalWorkerCount:this.threadWorkers.size})}return XI1.record(this.threadWorkers.size),Y}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(k4((J)=>J.size===0?X0.of({}):d8(...Array.from(J.values()).map((Q)=>Q.status.pipe(q6((Y)=>[Q.threadID,Q.threadReadWriter?IA(Q.thread,Y):void 0])))).pipe(q6((Q)=>Object.fromEntries(Q)))),y$(25),x8())}get(J){return this.threadWorkers.get(J)}prettyPrintToolRun(J,Q){let Y=this.threadWorkers.get(J);if(!Y)throw Error(`No worker found for thread ${J}`);for(let X of Y.thread.messages)for(let G of X.content)if(G.type==="tool_result"&&G.toolUseID===Q)return Il0(G.run);throw Error(`Tool run not found for thread ${J} and tool use ${Q}`)}async cancelToolOnly(J,Q){await this.threadWorkers.get(J)?.cancelToolOnly(Q)}async cancel(J){await this.threadWorkers.get(J)?.cancel()}async dispose(J){let Q=this.threadWorkers.get(J);if(Q)await Q.asyncDispose(),this.threadWorkers.delete(J),XI1.record(this.threadWorkers.size);this.threadWorkers.dispose()}async retry(J){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No active worker for thread ${J}`);await Q.retry()}async revertFileChanges(J,Q){let Y=this.threadWorkers.get(J);if(!Y)throw Error(`No active worker for thread ${J}`);await Y.revertFileChanges(Q)}async getFilesAffectedByTruncation(J,Q){let Y=this.threadWorkers.get(J);if(!Y)throw Error(`No active worker for thread ${J}`);return Y.getFilesAffectedByTruncation(Q)}async cleanupThreadBackups(J,Q){let Y=this.threadWorkers.get(Q);if(Y)await Y.fs.tracker.cleanupBackups();else{let X=await J.threadService.get(Q);if(!X)return;let G=J.vfs.fileSystemWithMountedTrees(Ax(X));try{await new ux(G).cleanup(Q),h.debug(`Cleaned up backup files for thread ${Q}`,{threadID:Q})}catch(Z){h.error("Error cleaning up thread backups",Z,{threadID:Q})}}}async disposeAll(){await Promise.all(Array.from(this.threadWorkers.values()).map(async(J)=>await J.asyncDispose())),this.threadWorkers.clear(),XI1.record(0)}}var E3=new Rl0;G4();r0();D3();W3();hU();function Tl0(J){let Q=[],Y=/@((?:[^\s@\\,;]|\\.)+)/g,X;while((X=Y.exec(J))!==null){let G=X[1],Z=Ro4(G).replace(/[.,;:!?)}\]]+$/,"");Q.push(Z)}return Q}function Ro4(J){if(J.match(/^[A-Za-z]:[\\]/))return J.replace(/\\(.)/g,(Q,Y)=>{if(Y===" "||Y==="("||Y===")"||Y==="["||Y==="]"||Y==="?"||Y==="*")return Y;return Q});return J.replace(/\\(.)/g,"$1")}t8();OL();async function Sl0(J,{configService:Q,filesystem:Y}){let X={sentAt:Date.now()},G=await M6(Q.workspaceRoots)??[],Z=d2(J.content);if(G.length===0)return{role:"user",content:J.content,source:J.source,fileMentions:void 0,userState:void 0,agentMode:J.agentMode,meta:X};let q=await zr({fileSystem:Y},Tl0(Z),{searchPaths:G,shouldIncludeImages:!J.agentMode||uk(J.agentMode)}),V;if(q?.files&&q.files.length>0){let H=new Set,z=[];for(let U of q.files){let N=l4(U.uri),M=await cP(Y,N,G,null,H);for(let L of M){if(!z.some((A)=>A.uri===L.uri))z.push(L);H.add(L.uri)}}if(z.length>0)V=z}let K=await(await Promise.resolve().then(() => (jl0(),Cl0))).getUserState();return{role:"user",content:q?.imageBlocks?.length?[...J.content,...q.imageBlocks]:J.content,source:J.source,fileMentions:q,userState:{...K??fS0},agentMode:J.agentMode,discoveredGuidanceFiles:V,meta:X}}class Cb{deps;threadID;async resumeInProgressTools(){for(let J of this.thread.messages){if(J.role!=="user")continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;if(!(!N2(Q.run)&&Q.run.status!=="blocked-on-user"&&!this.ops.tools[Q.toolUseID]))continue;let X=this.findToolUseById(Q.toolUseID);if(!X)continue;if(X.name===d9||X.name===QB0){this.findAndCancelToolRun(Q.toolUseID);continue}h.debug(`re-invoking tool ${X.name} with ID ${Q.toolUseID}`,{name:"resumeInProgressTools",threadID:this.threadID}),this.invokeTool(X,Q.userInput)}}await this.updateFileChanges()}findToolUseById(J){for(let Q of this.thread.messages){if(Q.role!=="assistant")continue;for(let Y of Q.content)if(Y.type==="tool_use"&&Y.id===J)return Y}return}trackFilesFromHistory(){h.debug("Tracking files from thread history",{name:"trackFilesFromHistory",threadID:this.threadID});for(let J of this.thread.messages){if(J.role==="user"&&J.fileMentions?.files)this.trackFiles(J.fileMentions.files.map((Q)=>Q.uri).filter((Q)=>Q!==void 0));if(J.role==="user"){for(let Q of J.content)if(Q.type==="tool_result"&&Q.run.status==="done")this.trackFiles(Q.run.trackFiles??[])}}}async getConfig(J){return M6(this.deps.configService.config,J)}async getCodeHostService(J){if(!this.codeHostService){let Q=this.thread.env?.initial.trees||[],Y=await this.getConfig(J);this.codeHostService=gR0(Q,this.deps.threadService,this.deps.mcpService,Y,this.threadID)}return this.codeHostService}setupSettingsChangeHandlers(){this.setupPermissionsChangeHandler()}setupPermissionsChangeHandler(){this.deps.configService.config.pipe(q6((J)=>JI(J.settings?.permissions)),_4(),YU0(1),uF(this.disposed$)).subscribe(()=>{this.reevaluateBlockedTools()})}reevaluateBlockedTools(){for(let J=this.thread.messages.length-1;J>=0;J--){let Q=this.thread.messages[J];if(!Q||Q.role!=="user")continue;let Y=!1;for(let X of Q.content)if(X.type==="tool_result"&&X.run?.status==="blocked-on-user"&&X.toolUseID)Y=!0,this.checkAndApproveBlockedTool(X.toolUseID);if(!Y)break}}async checkAndApproveBlockedTool(J){try{let Q=this.findToolUseById(J);if(!Q){h.warn("Tool use block not found for blocked tool",{toolUseID:J});return}let Y=await y11(Q.name,Q.input??{},{configService:this.deps.configService},this.thread.mainThreadID?"subagent":"thread",this.threadID,J);if(Y.permitted)h.info("Auto-approving previously blocked tool due to permission change",{toolName:Q.name,toolUseID:J,threadID:this.threadID}),this.handle({type:"user:tool-input",toolUse:J,value:{accepted:!0}});else h.debug("Tool remains blocked after permission change",{toolName:Q.name,toolUseID:J,reason:Y.reason})}catch(Q){h.warn("Failed to re-evaluate blocked tool",{error:Q,toolUseID:J})}}async cleanupTaskToolSubThreads(J=this.thread.messages.length){let Q=this.thread.messages.slice(0,J),Y=Qq1(Q),X=new Set(Y.map((Z)=>Z.toolUseID)),G=new Set;for(let[Z]of this.registeredSubthreads.entries())if(!X.has(Z))G.add(Z);for(let Z of G){let q=this.registeredSubthreads.get(Z);if(q.fileChanges?.unsubscribe(),await q.worker?.revertFileChanges(),q.latestFiles=[],this.mergeAndEmit(),await this.cleanupThreadBackups(q.threadID),await q.worker?.asyncDispose(),this.deps.deleteThread)try{await this.deps.deleteThread(q.threadID)}catch(V){h.error(`Failed to delete Task tool sub-thread: ${q.threadID}`,V,{threadID:this.threadID,subThreadID:q.threadID})}else h.warn(`Cannot delete Task tool sub-thread: ${q.threadID} - threadHistoryService not available`,{threadID:this.threadID,subThreadID:q.threadID});this.registeredSubthreads.delete(Z)}if(G.size>0)this.emitSubthreads()}ops={tools:{},toolMessages:{},inference:null};_state=new R5("initial");state=this._state.pipe(_4(),x8({shouldCountRefs:!0}));handleMutex=new s$;ephemeralError=new R5(void 0);inferenceState=new R5("idle");fileChanges=new R5({files:[]});toolCallUpdates=new i4;trackedFiles=new _Y;discoveredGuidanceFileURIs=new Set;fs;cachedFileChanges=[];registeredSubthreads=new Map;subthreadSequenceNumber=0;_subthreadsSubject=new R5([]);subthreads=this._subthreadsSubject.pipe(_4(),x8({shouldCountRefs:!0}));disposed$=new i4;isDisposed=!1;cancelledToolUses=new Set;codeHostService=null;shouldContinueAfterRejection=!1;lastInferenceRequestId;constructor(J,Q){this.deps=J;this.threadID=Q;this.fs=Fl0({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.vfs,Q,()=>Ax(this.thread))}status=this.state.pipe(k4((J)=>J==="active"?d8(this.inferenceState.pipe(_4()),this.fileChanges.pipe(_4()),this.ephemeralError,this.toolCallUpdates.pipe(c8(void 0))).pipe(q6(([Q,Y,X])=>({state:J,inferenceState:Q,fileChanges:Y,ephemeralError:X?{message:X.message,stack:"stack"in X?X.stack:void 0,error:"error"in X&&X.error&&typeof X.error==="object"&&"error"in X.error?X.error.error:void 0}:void 0})),uF(this.disposed$)):X0.of({state:J})),x8({shouldCountRefs:!0}));threadReadWriter=null;get thread(){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);return this.threadReadWriter.read()}set thread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.write(J),this.__testing__setThread(J)}updateThread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.update(Av0(J)),this.__testing__setThread(this.threadReadWriter.read())}async acquireThread(){if(!this.threadReadWriter)this.threadReadWriter=await this.deps.threadService.exclusiveSyncReadWriter(this.threadID),this._state.next("active")}__testing__setThread(J){}__testing__getDeps(){return this.deps}async resume(){if(this.resumed)return;if(this.resumed=!0,this.handleCalled)throw Error("cannot call ThreadWorker.resume after ThreadWorker.handle");await this.acquireThread(),await this.restoreFileChangesFromBackups();let J=this.thread.messages.at(-1);if(J?.role==="assistant"&&J.state.type==="streaming")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});if(this.trackFilesFromHistory(),await this.initializeCompletedSubthreads(),this.thread.mainThreadID)return;if(sB0(J)||tB0(J)&&!this.shouldContinueAfterRejection||Yq1(J)){this.inferenceState.next("cancelled");return}await this.resumeInProgressTools(),this.setupSettingsChangeHandlers();let Q=this.thread.messages.findLastIndex((X)=>X.role==="user"?eB0(X):X.role==="assistant"&&X.state.type==="complete");if(Q===-1){if(this.thread.messages.length!==0)throw Error(`(bug) invalid thread: ${this.threadID}`);return}let Y=this.thread.messages[Q];switch(Y.role){case"user":if(!Y.interrupted)this.onThreadDelta({type:"user:message",message:Y});break;case"assistant":this.onThreadDelta({type:"assistant:message",message:Y});break}}resumed=!1;async initializeCompletedSubthreads(){let J=Qq1(this.thread.messages);for(let{toolUseID:Q,threadID:Y,toolUse:X,toolResult:G}of J){let Z=N2(G.run),q=G.run.status==="blocked-on-user";if(Z&&!q)await this.registerSubthread(Q,Y,X)}}async forkThread(J){await this.acquireThread();let{threadService:Q}=this.deps,Y=await Q.forkThread(this.threadID,J);await this.handle({type:"fork:created",forkThreadID:Y.threadID,fromMessageIndex:J});let X=await Q.getPrimitiveProperty(this.threadID,"v");if(X!==null)await Q.flushVersion(this.threadID,X);return Y.threadID}async handle(J,Q){await this.handleMutex.acquire();try{await this.innerHandle(J,Q)}finally{this.handleMutex.release()}}async innerHandle(J,Q){if(this.isDisposed){h.debug(`Skipping ${J.type} - worker disposed.`,{name:"handle queue",threadID:this.threadID});return}if(Q?.aborted){h.debug(`Skipping ${J.type} - signal aborted.`,{name:"handle queue",threadID:this.threadID});return}if(await this.resume(),this.handleCalled=!0,await this.acquireThread(),J.type==="thread:truncate")await this.cleanupFileChanges(J.fromIndex),await this.cleanupTaskToolSubThreads(J.fromIndex);let Y=J;if(J.type==="user:message"){let X=await Sl0(J.message,{configService:this.deps.configService,filesystem:this.fs.fileSystemReader()});Y=JU(J,(G)=>{G.message=l8(X),Q?.throwIfAborted()})}try{if(this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);let X=J.type==="user:message"&&J.index!==void 0;if(this.updateThread(Y),this.onThreadDelta(Y),X)await this.cleanupFileChanges(),await this.cleanupTaskToolSubThreads(),await this.cleanupForkThreads()}catch(X){if(!xQ(X))h.error("Ephemeral error during handle processing",X,{name:"ThreadWorker",threadID:this.threadID}),this.ephemeralError.next(X instanceof Error?X:Error(String(X)));else h.debug(`AbortError caught during handle processing for ${Y.type}.`,{name:"handle queue",threadID:this.threadID})}}handleCalled=!1;onThreadDelta(J){switch(J.type){case"user:message":{if(J.index!==void 0)this.trackedFiles.clear(),this.thread.messages.forEach((Q)=>{if(Q.role==="user"){for(let Y of Q.content)if(Y.type==="tool_result"&&Y.run.status==="done"&&Y.run.trackFiles)this.trackFiles(Y.run.trackFiles);if(Q.fileMentions?.files)this.trackFiles(Q.fileMentions.files.map((Y)=>Y.uri).filter((Y)=>Y!==void 0))}});else this.trackFiles(J.message.fileMentions?.files?.map((Q)=>Q.uri).filter((Q)=>Q!==void 0)??[]);this.runInferenceAndUpdateThread();break}case"user:message-queue:dequeue":{let Q=this.thread.messages.at(-1);if(!Q)break;if(Q.role!=="user")break;this.trackFiles(Q.fileMentions?.files?.map((Y)=>Y.uri).filter((Y)=>Y!==void 0)??[]),this.runInferenceAndUpdateThread();break}case"user:tool-input":{let Q=IX(this.thread,J.toolUse);if(Q)this.invokeTool(Q,J.value);break}case"tool:data":{if(this.cancelledToolUses.has(J.toolUse)){this.updateThread({type:"tool:data",toolUse:J.toolUse,data:{status:"cancelled",reason:"cancelled by user message"}});return}let Q=IX(this.thread,J.toolUse);if(J.data.status==="in-progress"&&Q?.name===qJ){let Y=Q,X=Jq1(J.data.progress);if(X)this.registerSubthread(J.toolUse,X,Y)}if(N2(J.data)){this.cancelledToolUses.delete(J.toolUse);let Y=this.ops.toolCompletionResolvers?.[J.toolUse];if(Y){if(J.data.status==="done")Y.resolve();else Y.reject(Error(`Tool ${J.data.status}: ${J.toolUse}`));delete this.ops.toolCompletionResolvers?.[J.toolUse]}}if(Q){let Y=Co4(this.thread,J.toolUse,this.shouldContinueAfterRejection);h.debug(`updated tool_result${Y?" and running inference because all tools completed":""}`,{name:`handleThreadDelta(${J.type}, ${J.toolUse}, ${J.data.status})`,threadID:this.threadID});let X=this.shouldContinueAfterRejection||this.inferenceState.getValue()!=="cancelled";if(Y&&X)this.runInferenceAndUpdateThread()}this.toolCallUpdates.next();break}case"assistant:message":{let Q=this.findToolUsesNeedingInvocation(J.message);h.debug(`saw ${Q.length} tool uses (${Q.map((Y)=>Y.name).join(", ")})`,{name:`handleThreadDelta(${J.type})`,threadID:this.threadID}),this.executeToolsWithPlan(Q);break}case"user:message-queue:enqueue":{let Q=this.inferenceState.getValue();if(YI1(this.thread,Q)!=="tool-running"){if(Q==="cancelled"){this.handle({type:"user:message-queue:dequeue"});break}else if(Q==="idle"){let X=this.thread.messages.at(-1);if(X?.role==="assistant"){if(X.state.type==="cancelled"||X.state.type==="error"){this.handle({type:"user:message-queue:dequeue"});break}if(X.state.type==="complete"&&X.state.stopReason!=="tool_use"){this.handle({type:"user:message-queue:dequeue"});break}}else if(X?.role==="info"){this.handle({type:"user:message-queue:dequeue"});break}}}break}case"info:manual-bash-invocation":{this.handle({type:"user:message-queue:dequeue"});break}case"info:skill-injection":break;case"cancelled":break;case"inference:completed":{let Q=KJ(this.thread,"assistant");if(Q&&Q.state.type==="complete"&&Q.state.stopReason==="refusal"){this.ephemeralError.next(Error("The model refused to respond to this request. Please retry with a different prompt."));break}if(Q){let X=this.findToolUsesNeedingInvocation(Q);this.executeToolsWithPlan(X)}if(Q&&Q.state.type==="complete"&&Q.state.stopReason==="end_turn")if(this.thread.queuedMessages&&this.thread.queuedMessages.length>0)this.handle({type:"user:message-queue:dequeue"});else g11(this,Ol0(this.deps.internalHooks?.onAssistantTurnEnd,{thread:this.thread}));break}}}findToolUsesNeedingInvocation(J){if(J.content.some((G)=>G.type==="tool_use"&&!p2(G)))return[];if(!(J.state?.type==="complete"||J.state?.type==="cancelled"))return[];let X=QQ(this.thread);return J.content.filter((G)=>G.type==="tool_use").filter((G)=>!X.has(G.id)&&!this.cancelledToolUses.has(G.id))}async getWorkspaceRoots(J){return await M6(this.deps.configService.workspaceRoots,J)??this.thread.env?.initial?.trees?.map((Q)=>Q.uri).filter((Q)=>Q!==void 0).map(sJ)??[]}async executeToolsWithPlan(J){if(J.length===0)return;let Q=Ul0(J,this.deps.toolService);h.debug(`executing ${J.length} tools in ${Q.length} batch(es)`,{name:"executeToolsWithPlan",threadID:this.threadID,batches:Q.map((Y)=>Y.map((X)=>X.name))}),await this.executeToolBatchesSequentially(Q)}async executeToolBatchesSequentially(J){for(let Q of J){let X=(await Promise.allSettled(Q.map((G)=>this.invokeToolAndWait(G,void 0)))).filter((G)=>G.status==="rejected");if(X.length>0)h.warn(`${X.length} tool(s) failed in batch`,{name:"executeToolBatchesSequentially",threadID:this.threadID,errors:X.map((G)=>G.reason)})}}async invokeToolAndWait(J,Q){let Y=new Promise((X,G)=>{if(!this.ops.toolCompletionResolvers)this.ops.toolCompletionResolvers={};this.ops.toolCompletionResolvers[J.id]={resolve:X,reject:G}});this.invokeTool(J,Q).catch((X)=>{let G=this.ops.toolCompletionResolvers?.[J.id];if(G)h.debug(`Tool invocation setup failed for ${J.id}`,{name:"invokeToolAndWait",threadID:this.threadID,error:String(X)}),G.reject(X),delete this.ops.toolCompletionResolvers?.[J.id]}),await Y}async invokeTool(J,Q){if(this.ops.tools[J.id])throw Error(`(bug) tool invocation already in progress: ${J.id}`);if(!p2(J))throw Error(`(bug) tool use is incomplete: ${J.id}`);let Y=await this.getConfig(),X=Ll0(Y.settings?.hooks,{threadID:this.threadID,toolUse:J}),{abortOp:G}=await g11(this,X);if(G){let q=this.ops.toolCompletionResolvers?.[J.id];if(q)q.resolve(),delete this.ops.toolCompletionResolvers?.[J.id];return}let Z=new AbortController;this.ops.tools[J.id]=Z,this.updateThread({type:"tool:data",toolUse:J.id,data:{status:"in-progress"}});try{let q=await this.getWorkspaceRoots(Z.signal),V=BI(this.thread),K=new X0((M)=>{this.ops.toolMessages[J.id]=M}),W=await this.getCodeHostService(Z.signal),H={...this.deps,dir:q.at(0)??null,dirs:q,tool:J.name,thread:this.thread,config:await this.getConfig(),trackedFiles:new _Y(this.trackedFiles),filesystem:this.fs.trackedFileSystem(J.id),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:J.id,todos:V,toolMessages:K,threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),pullRequestChanges:W.pullRequestChanges,agentMode:await this.getSelectedAgentMode(),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs},z=this.deps.toolService.preprocessArgs?.(J.name,J.input,H);if(z)this.handle({type:"tool:processed",toolUse:J.id,newArgs:z});let U=z??J.input,N=this.deps.toolService.invokeTool(J.name,{args:U,userInput:Q},H).pipe(uF(this.disposed$),k$(()=>{delete this.ops.tools[J.id],this.ops.toolMessages[J.id]?.complete(),delete this.ops.toolMessages[J.id]})).subscribe({next:async(M)=>{if(h.debug(`${J.id}, ${M.status}`,{name:"invokeTool",threadID:this.threadID}),N2(M)){delete this.ops.tools[J.id],N.unsubscribe();let L=this.ops.toolCompletionResolvers?.[J.id];if(L){if(M.status==="done")L.resolve();else L.reject(Error(`Tool ${M.status}: ${J.id}`));delete this.ops.toolCompletionResolvers?.[J.id]}if(M.status==="done"&&M.trackFiles?.length)this.trackFiles(M.trackFiles);if(Y.settings?.hooks){let A=Al0(Y.settings.hooks,{threadID:this.threadID,toolUse:J});await g11(this,A,{toolUseID:J.id})}}await this.updateFileChanges(),await this.handle({type:"tool:data",toolUse:J.id,data:M},Z.signal)},error:async(M)=>{let L=this.ops.toolCompletionResolvers?.[J.id];if(L)L.reject(M),delete this.ops.toolCompletionResolvers?.[J.id];await this.handle({type:"tool:data",toolUse:J.id,data:{status:"error",error:{message:"message"in M?M.message:String(M),displayMessage:"displayMessage"in M?M.displayMessage:void 0}}},Z.signal)},complete:()=>{let M=this.ops.toolCompletionResolvers?.[J.id];if(!M)return;let L=QQ(this.thread).get(J.id)?.run;if(L&&N2(L))return;let A;if(this.isDisposed)A="Worker disposed";else if(Z.signal.aborted)A="Tool aborted";else if(this.cancelledToolUses.has(J.id))A="Tool cancelled";else A="Tool observable completed without terminal state";M.reject(Error(A)),delete this.ops.toolCompletionResolvers?.[J.id]}});aM(Z.signal,()=>N.unsubscribe())}catch(q){delete this.ops.tools[J.id];let V=this.ops.toolCompletionResolvers?.[J.id];if(V)V.reject(q),delete this.ops.toolCompletionResolvers?.[J.id];throw q}}async cancelInProgressTools(){for(let J of Object.keys(this.ops.tools))await this.cancelTool(J)}cancelAllActiveTools(){let J=QQ(this.thread);for(let Q of this.thread.messages){if(Q.role!=="assistant")continue;for(let Y of Q.content)if(Y.type==="tool_use"&&p2(Y)){let X=J.get(Y.id);if(!(X&&N2(X.run)))this.cancelledToolUses.add(Y.id)}}for(let Q of this.thread.messages)if(Q.role==="user"){for(let Y of Q.content)if(Y.type==="tool_result"){if(!N2(Y.run))this.cancelledToolUses.add(Y.toolUseID)}}}cancelUnstartedTools(){let J=QQ(this.thread),Q=this.thread.messages.findLastIndex((X)=>Yq1(X)),Y=Q===-1?this.thread.messages:this.thread.messages.slice(Q+1);for(let X of Y){if(X.role!=="assistant")continue;for(let G of X.content)if(G.type==="tool_use"&&p2(G)){let Z=J.get(G.id);if(!Z||Z.run.status==="blocked-on-user")this.updateThread({type:"tool:data",toolUse:G.id,data:{status:"cancelled"}})}}}rollbackPartialAssistantMessage(){let J=-1;for(let Q=this.thread.messages.length-1;Q>=0;Q--)if(this.thread.messages[Q]?.role==="user"){J=Q;break}if(J>=0&&J<this.thread.messages.length-1)return this.updateThread({type:"thread:truncate",fromIndex:J+1}),!0;return!1}async runInferenceAndUpdateThread(J=0){this.ops.inference?.abort(),this.ops.inference=null,this.inferenceState.next(J>0?"retrying":"running");let Q=new AbortController;this.ops.inference=Q,this.cancelAllActiveTools(),this.cancelUnstartedTools(),await this.cancelInProgressTools();for(let V of this.thread.messages)if(V.role==="user"){for(let K of V.content)if(K.type==="tool_result"&&K.run.status==="blocked-on-user")this.updateThread({type:"tool:data",toolUse:K.toolUseID,data:{status:"cancelled"}})}let Y=this.thread.messages.at(-1);if(this.thread.mainThreadID===void 0&&Y?.role==="user"&&this.thread.messages.filter((V)=>V.role==="user").length===1){if(this.deps.getThreadEnvironment)this.deps.getThreadEnvironment().then(async(V)=>{this.updateThread({type:"environment",env:{initial:{...this.thread.env?.initial,...V}}})}).catch((V)=>{h.error("Failed to initialize thread environment",V,{threadID:this.threadID})})}if(this.thread.mainThreadID===void 0&&!this.thread.title)this.getConfig(Q.signal).then((V)=>{if(Q.signal.aborted)return;let K=V.settings?.["agent.skipTitleGenerationIfMessageContains"]||[],W=this.thread.messages.find((H)=>{if(H.role!=="user")return!1;if(K.length===0)return!0;let z=d2(H.content);return!K.some((U)=>z.includes(U))});if(W)this.deps.generateThreadTitle(W,this.thread,this.deps.configService,Q.signal).then(({title:H,usage:z})=>{if(Q.signal.aborted||this.isDisposed)return;if(H!==void 0&&this.thread.title!==H)this.updateThread({type:"title",value:H,usage:z})}).catch((H)=>{if(!xQ(H))h.error("generateThreadTitle error",H,{name:"ThreadWorker",threadID:this.threadID})})}).catch((V)=>{if(!xQ(V))h.error("ThreadWorker title generation config error",V)});let G=await this.getConfig(),{model:Z,agentMode:q}=Tb(G.settings,this.thread);try{let[V,K,W]=Z.match(/(.*?)\/(.*)/)??[],H=ql0(K??"",W??""),z=crypto.randomUUID();this.lastInferenceRequestId=z;let U=H.stream({model:W??"",thread:this.thread,buildSystemPromptDeps:{toolService:this.deps.toolService,configService:this.deps.configService,getThreadEnvironment:this.deps.getThreadEnvironment,filesystem:this.fs.fileSystemReader(),threadService:this.deps.threadService},signal:Q.signal,agentMode:q,retryCount:J,clientRequestId:z}),N;for await(let M of U){if(this.inferenceState.getValue()==="retrying")this.inferenceState.next("running");N=M,await this.handle({type:"assistant:message-update",message:M})}if(N?.usage&&this.lastInferenceRequestId){let{fetchCreditsByRequestId:M}=await Promise.resolve().then(() => (bB(),yl0)),L=await M(this.lastInferenceRequestId,this.deps.configService,{signal:Q.signal});if(L!==null)N={...N,usage:{...N.usage,credits:L}};this.lastInferenceRequestId=void 0}await this.handle({type:"inference:completed",model:N?.usage?.model,usage:N?.usage})}catch(V){if(!(xQ(V)||nw0(V))){let K=V instanceof Error?V:Error(String(V));if((this.threadReadWriter?this.rollbackPartialAssistantMessage():!1)&&J<qK.maxRetries)return h.info("Retrying after midstream error",{threadID:this.threadID,attempt:J+1,maxRetries:qK.maxRetries}),this.runInferenceAndUpdateThread(J+1);this.ephemeralError.next(K)}return}finally{if(this.ops.inference===Q)this.ops.inference=null,this.inferenceState.next("idle")}}async findAndCancelToolRun(J,Q){if(this.cancelInference(),!IX(this.thread,J))return;await this.cancelTool(J,Q)}async cancelToolOnly(J,Q){if(!IX(this.thread,J))return;let X=this.cancelDataForToolRun(J);await this.cancelSubthread(J);let G=this.ops.toolMessages[J];if(G){try{G.next({type:"stop-command"})}catch(Z){h.warn("Failed to send stop-command",{id:J,error:Z})}G.complete(),delete this.ops.toolMessages[J]}h.debug(`cancelToolOnly(${J})`),await this.handle({type:"tool:data",toolUse:J,data:X},Q)}invokeBashTool(J,Q,Y){return new X0((X)=>{let G,Z,q,K=((H)=>{return aM(H,()=>{if(h.warn("Manual bash abort -> unsubscribe",{threadID:this.threadID}),q?.unsubscribe(),Z?.unsubscribe(),X?.complete(),G)this.handleManualBashInvocation(J,{status:"cancelled",progress:t$1(G)},Y)})})(Q);return(async()=>{try{if(Q.aborted){X.error(Error("Operation was aborted"));return}let H=await this.getWorkspaceRoots(Q),z=await this.getConfig(Q),U=await this.getCodeHostService(Q),N={...this.deps,dir:H.at(0)??null,dirs:H,tool:d9,thread:this.thread,config:z,trackedFiles:new _Y(this.trackedFiles),filesystem:cI0(this.fs.fileSystemReader()),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:CM(),todos:[],threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),pullRequestChanges:U.pullRequestChanges,discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs};Z=this.deps.toolService.invokeTool(d9,{args:J,userInput:{accepted:!0}},N).subscribe({next:(M)=>{G=M,X.next(M)},error:(M)=>{X.error(M)},complete:()=>{if(G)this.handleManualBashInvocation(J,G,Y);X.complete()}}),q=this.disposed$.subscribe(()=>{K(),Z?.unsubscribe(),X?.complete()})}catch(H){X.error(H)}})(),()=>{K(),Z?.unsubscribe(),q?.unsubscribe()}})}async handleManualBashInvocation(J,Q,Y){await this.handle({type:"info:manual-bash-invocation",args:J,toolRun:Q,hidden:Y})}async cleanupThreadBackups(J){try{await this.fs.tracker.cleanupBackups(),h.debug(`Cleaned up backup files for thread ${J}`,{threadID:J})}catch(Q){h.error("Error cleaning up thread backups",Q,{threadID:J})}}cancelDataForToolRun(J){let Y=QQ(this.thread).get(J)?.run;return{status:"cancelled",progress:Y?t$1(Y):void 0}}async cancelTool(J,Q){let Y=this.cancelDataForToolRun(J);await this.cancelSubthread(J);let X=this.ops.toolMessages[J];if(X){try{X.next({type:"stop-command"})}catch(G){h.warn("Failed to send stop-command",{id:J,error:G})}X.complete(),delete this.ops.toolMessages[J]}h.debug(`cancelToolRun(${J})`),await this.handle({type:"tool:data",toolUse:J,data:Y},Q)}async cancel(){h.debug("cancel: aborting inference operation and tools"),this.cancelInference(),this.cancelAllActiveTools(),this.cancelUnstartedTools(),await this.cancelInProgressTools(),await this.handle({type:"cancelled"},void 0)}cancelInference(){if(this.ops.inference)this.ops.inference.abort(Error(yF1.USER_CANCELLED)),this.ops.inference=null;this.inferenceState.next("cancelled")}async retry(){if(h.debug("retry: retrying inference operation"),this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);if(this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;let J=this.thread.messages.at(-1);if(J?.role==="assistant"&&J.state.type==="complete"&&J.state.stopReason==="refusal")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});this.inferenceState.next("idle"),await this.runInferenceAndUpdateThread()}setTestEphemeralError(J){this.ephemeralError.next(J)}async cancelSubthread(J){let Q=this.registeredSubthreads.get(J);if(Q&&Q.worker)await Q.worker.cancel()}abortToolOp(J){this.ops.tools[J]?.abort(),delete this.ops.tools[J]}abortAllTools(){for(let J of Object.keys(this.ops.tools)){let Q=J,Y=this.ops.toolMessages[Q];if(Y)try{Y.next({type:"stop-command"}),Y.complete(),delete this.ops.toolMessages[Q]}catch(X){h.warn("Failed to send stop-command during disposal",{id:Q,error:X})}this.abortToolOp(Q)}}trackFiles(J){for(let Q of J)this.trackedFiles.add(Q)}async restoreFileChangesFromBackups(){try{let J=await this.fs.tracker.restoreFromBackups();h.debug(`Restored ${J.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(J){h.error("Error restoring file changes",J,{threadID:this.threadID})}}async revertFileChanges(J){for(let Q of this.registeredSubthreads.values()){let Y=Q?.worker;if(Y)await Y.revertFileChanges(J)}await this.fs.tracker.revertAll(J),await this.updateFileChanges()}async getAllTrackedChanges(){let J=new Map;for(let Y of this.registeredSubthreads.values()){let X=Y?.worker;if(X){let G=await X.getAllTrackedChanges();for(let[Z,q]of G.entries())J.set(Z,q)}}let Q=await this.fs.tracker.getAllRecords();for(let[Y,X]of Q.entries())J.set(Y,X);return J}async cleanupForkThreads(J=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:J})}async getToolUsesToRevert(J=this.thread.messages.length){let Q=new Set;this.thread.messages.slice(0,J).forEach((G)=>{if(G.role==="user"){for(let Z of G.content)if(Z.type==="tool_result")Q.add(Z.toolUseID)}else for(let Z of G.content)if(Z.type==="tool_use")Q.add(Z.id)});let Y=new Set,X=await this.fs.tracker.getAllRecords();for(let[G]of X.entries())if(!Q.has(G))Y.add(G);return Y}async getFilesAffectedByTruncation(J){let Q=await this.getToolUsesToRevert(J);if(Q.size===0)return[];return this.fs.tracker.getFilesForToolUses(Q)}async cleanupFileChanges(J=this.thread.messages.length){let Q=await this.getToolUsesToRevert(J);if(Q.size===0)return;await this.fs.tracker.revertChanges(Q),await this.updateFileChanges()}async updateFileChanges(){this.cachedFileChanges=await Dl0(this.fs.tracker),this.mergeAndEmit()}mergeAndEmit(){let J=new L2;for(let Y of this.cachedFileChanges)J.set(Y.uri,Y);for(let Y of this.registeredSubthreads.values())for(let X of Y.latestFiles??[])J.set(X.uri,X);let Q=J.size;if(Q>50)h.warn("Excessive file changes detected - potential memory issue",{name:"mergeAndEmit",threadID:this.threadID,fileChangeCount:Q,ownFileChanges:this.cachedFileChanges.length,subthreadCount:this.registeredSubthreads.size});this.fileChanges.next({files:[...J.values()]})}emitSubthreads(){let J=Array.from(this.registeredSubthreads.values()).sort((Q,Y)=>Q.sequenceNumber-Y.sequenceNumber).map((Q)=>({threadID:Q.threadID,toolUse:Q.toolUse,sequenceNumber:Q.sequenceNumber}));this._subthreadsSubject.next(J)}async registerSubthread(J,Q,Y){if(this.registeredSubthreads.has(J))return;let X=await E3.getOrCreateForSubThread(this.deps,Q);await X.resume();let G=X.status.pipe(D7((Z)=>Z.state==="active"),q6((Z)=>Z.fileChanges.files),uF(this.disposed$)).subscribe((Z)=>{let q=this.registeredSubthreads.get(J);if(!q)return;q.latestFiles=Z,this.mergeAndEmit()});this.registeredSubthreads.set(J,{threadID:Q,worker:X,fileChanges:G,toolUse:Y,sequenceNumber:++this.subthreadSequenceNumber}),this.emitSubthreads()}continueInferenceAfterRejection(J=!0){this.shouldContinueAfterRejection=J}async asyncDispose(){if(this.isDisposed)return;if(h.debug("ThreadWorker disposal starting",{name:"ThreadWorker.dispose",threadID:this.threadID,subthreadCount:this.registeredSubthreads.size,activeToolCount:Object.keys(this.ops.tools).length}),this.isDisposed=!0,this.disposed$.next(),this.disposed$.complete(),await Promise.all(Array.from(this.registeredSubthreads.values()).map(async(J)=>{J.fileChanges?.unsubscribe(),await J.worker?.asyncDispose()})),this.registeredSubthreads.clear(),this.cancelledToolUses.clear(),this.ops.toolCompletionResolvers)for(let J of Object.keys(this.ops.toolCompletionResolvers)){let Q=this.ops.toolCompletionResolvers[J];if(Q)try{Q.reject(Error("Worker disposed"))}finally{delete this.ops.toolCompletionResolvers[J]}}if(this._state.complete(),this.ephemeralError.complete(),this.inferenceState.complete(),this.fileChanges.complete(),this.toolCallUpdates.complete(),this._subthreadsSubject.complete(),this.abortAllTools(),this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;if(this.fs.tracker.dispose(),this.codeHostService)this.codeHostService.dispose(),this.codeHostService=null;if(this.threadReadWriter)await this.threadReadWriter.asyncDispose(),this.threadReadWriter=null}async getSelectedAgentMode(){let J=await this.getConfig(),{agentMode:Q}=Tb(J.settings,this.thread);return Q}}s71([JI1],Cb.prototype,"invokeTool",null),s71([JI1],Cb.prototype,"runInferenceAndUpdateThread",null);function Co4(J,Q,Y=!1){let X=KJ(J,"assistant");if(!X||X.state.type!=="complete"||X.state.stopReason!=="tool_use")return!1;let G=X.content.filter((V)=>V.type==="tool_use").map((V)=>V.id);if(Q&&!G.includes(Q))return h.debug(`tool:data for orphaned tool_use ${Q} - ignoring for inference`,{name:"shouldRunInferenceWithToolData",threadID:J.id}),!1;if(G.length===0)return!1;let Z=QQ(J);return G.every((V)=>{let K=Z.get(V);if(!K||!N2(K.run))return!1;let W=K.run.status;if(W==="cancelled")return!1;if(W==="rejected-by-user")return Y;return!0})}class p11 extends Cb{constructor(J,Q){super(J,Q)}static fromWorker(J){let Q=J.__testing__getDeps(),Y=new p11(Q,J.threadID);return Y.threadReadWriter=J.threadReadWriter,Y}async resume(){throw Error("ReplayThreadWorker: resume() is not allowed in replay mode")}async handle(J,Q){throw Error("ReplayThreadWorker: handle() is not allowed in replay mode")}async forkThread(J){throw Error("ReplayThreadWorker: forkThread() is not allowed in replay mode")}invokeBashTool(J,Q,Y){throw Error("ReplayThreadWorker: invokeBashTool() is not allowed in replay mode")}async retry(){throw Error("ReplayThreadWorker: retry() is not allowed in replay mode")}async cancel(){throw Error("ReplayThreadWorker: cancel() is not allowed in replay mode")}async findAndCancelToolRun(J,Q){throw Error("ReplayThreadWorker: findAndCancelToolRun() is not allowed in replay mode")}async cancelToolOnly(J,Q){throw Error("ReplayThreadWorker: cancelToolOnly() is not allowed in replay mode")}async revertFileChanges(){throw Error("ReplayThreadWorker: revertFileChanges() is not allowed in replay mode")}continueInferenceAfterRejection(J){}}t8();G4();L0();class d11{storage;index=new Map;initialized=!1;initPromise=null;constructor(J){this.storage=J;this.ensureInitialized(),this.setupChangeListener()}async search(J,Q=20){if(!this.initialized)return[];if(this.index.size===0)return[];let Y=Array.from(this.index.entries()).map(([Z,q])=>{return new yY({id:Z,kind:"file",path:q,uri:d0.parse(`thread://${Z}`),metadata:{size:0,mtime:0,isSymlink:!1}})});return new fo(J,{maxResults:Q,minScore:J?400:0}).match(Y).map((Z)=>({id:Z.entry.id,title:Z.entry.path,score:Z.score}))}async ensureInitialized(){if(this.initialized)return;if(this.initPromise)return this.initPromise;return this.initPromise=this.loadIndex(),this.initPromise}async loadIndex(){try{let J=await this.storage.keys(),Q=50;for(let Y=0;Y<J.length;Y+=50){let X=J.slice(Y,Y+50),G=await Promise.all(X.map(async(Z)=>{return(await this.storage.get(Z))?.title||null}));for(let Z=0;Z<X.length;Z++){let q=X[Z],V=G[Z];if(q&&V&&V.trim().length>0)this.index.set(q,V)}if(Y+50<J.length)await new Promise((Z)=>setImmediate(Z))}this.initialized=!0,h.debug("Thread fuzzy indexer initialized",{indexedCount:this.index.size})}catch(J){h.warn("Failed to load thread index",J),this.initialized=!0}}setupChangeListener(){this.storage.changes.subscribe(async(J)=>{if(!this.initialized)return;if(J===void 0){await this.loadIndex();return}try{let Q=await this.storage.get(J);if(Q?.title)this.index.set(J,Q.title);else this.index.delete(J)}catch(Q){h.warn("Failed to update thread index for change",{key:J,error:Q})}})}dispose(){this.index.clear(),this.initialized=!1,this.initPromise=null}}r0();r0();function xl0(J){return new X0((Q)=>{let Y=!1,X=!1;(async()=>{try{let q=await J.keys();if(X)return;for(let V of q){if(X)return;let K=await J.get(V);if(X)return;Q.next({key:V,value:K,type:"initial"})}if(Y=!0,!X)Q.next({type:"initial-complete"})}catch(q){if(!X)Q.error(q)}})();let Z=J.changes.subscribe({next:async(q)=>{if(!Y||q===void 0)return;try{let V=await J.get(q);if(!X)Q.next({key:q,value:V,type:"change"})}catch(V){if(!X)Q.error(V)}},error:(q)=>Q.error(q),complete:()=>Q.complete()});return()=>{X=!0,Z.unsubscribe()}})}function vl0(J){let Q=J??{},Y=new Map,X=new i4;if(J){let G=Date.now();for(let Z of Object.keys(J))Y.set(Z,G)}return{async get(G){return Promise.resolve(Q[G])},async set(G,Z){Q[G]=Z,Y.set(G,Date.now()),X.next(G)},async delete(G){delete Q[G],Y.delete(G),X.next(G)},async keys(){return Object.keys(Q).toSorted((Z,q)=>(Y.get(q)??0)-(Y.get(Z)??0))},async path(G){return Promise.resolve(void 0)},changes:X.pipe(c8(void 0))}}t8();class GI1{storage;entriesMap=new Map;historySubject=new i4;storageSubscription;_observeHistory;constructor(J,Q={}){this.storage=J;if(!Q.lazy)this.initializeObservable()}initializeObservable(){if(this._observeHistory)return;this._observeHistory=X0.from(this.historySubject).pipe(Uk(200,{leading:!0,trailing:!0}),x8()),this.storageSubscription=xl0(this.storage).subscribe({next:(J)=>{if(J.type==="initial-complete"){this.emitCurrentList();return}let{key:Q,value:Y}=J;if(Y&&"messages"in Y)if(!(Y.messages.length===0&&!Y.draft))this.entriesMap.set(Q,jo4(Y));else this.entriesMap.delete(Q);else this.entriesMap.delete(Q);this.emitCurrentList()},error:(J)=>this.historySubject.error(J),complete:()=>{this.emitCurrentList(),this.historySubject.complete()}})}emitCurrentList(){let J=Array.from(this.entriesMap.values()).toSorted((Q,Y)=>Y.userLastInteractedAt-Q.userLastInteractedAt);this.historySubject.next(J)}observeHistory(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory}observeThreadList(){return this.observeHistory().pipe(_4((J,Q)=>{if(J.length!==Q.length)return!1;return J.every((Y,X)=>{let G=Q[X];if(!G)return!1;return Y.id===G.id&&Y.title===G.title&&Y.userLastInteractedAt===G.userLastInteractedAt&&Y.mainThreadID===G.mainThreadID&&JSON.stringify(Y.parentRelationships)===JSON.stringify(G.parentRelationships)&&JSON.stringify(Y.env?.initial?.trees?.map((Z)=>Z.displayName))===JSON.stringify(G.env?.initial?.trees?.map((Z)=>Z.displayName))})}))}dispose(){this.storageSubscription?.unsubscribe()}}function c11(J){return Math.max(J.created,...J.messages.map((Q)=>Q.role==="user"?Q.meta?.sentAt:void 0).filter((Q)=>Q!==void 0))}function jo4(J){return{id:J.id,v:J.v,created:J.created,title:J.title??null,userLastInteractedAt:c11(J),env:J.env,originThreadID:J.originThreadID,mainThreadID:J.mainThreadID,parentRelationships:ik(J),summaryStats:{diffStats:NI(J)}}}t8();function OT(J,Q){let Y=[];if(Y.push(So4(J,Q)),J.title)Y.push(`# ${J.title}`);let X=tG(J),G=X?X.index:0;for(let Z=G;Z<J.messages.length;Z++){let q=J.messages[Z];if(q)Y.push(_o4(q))}return Y.join(`
3206
3206
 
3207
3207
  `)}function So4(J,Q){let Y=["---"];if(J.title)Y.push(`title: ${J.title}`);if(Q)Y.push(`author: ${Q}`);if(Y.push(`threadId: ${J.id}`),Y.push(`created: ${new Date(J.created).toISOString()}`),J.agentMode)Y.push(`agentMode: ${J.agentMode}`);return Y.push("---"),Y.join(`
3208
3208
  `)}function _o4(J){switch(J.role){case"user":return ko4(J);case"assistant":return yo4(J);case"info":return xo4(J)}}function ko4(J){let Q=["## User"];if(J.interrupted)Q.push("*(interrupted)*");for(let Y of J.content)switch(Y.type){case"text":Q.push(ZI1(Y,!0));break;case"image":Q.push(vo4(Y));break;case"tool_result":Q.push(ho4(Y));break}return Q.join(`
@@ -4173,15 +4173,15 @@ Actual: ${G}`)}async function tV8(J,Q,Y){let{execSync:X}=await import("node:ch
4173
4173
  ${N}`;if(G==="pnpm"&&N.includes("Unable to find the global bin directory"))M+=`
4174
4174
 
4175
4175
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4176
- npm install -g @sourcegraph/amp`;V(Error(M))}},error:(U)=>{if(!H)H=!0,V(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,q()}})})}L0();L0();async function B41(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),q=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!q.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let V=await q.json(),K=V["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=XK8(J,K),H=W<0,z,U;if(V.time){let N=V.time[J],M=V.time[K],L=Date.now();if(N)z=Math.floor((L-new Date(N).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return h.info("NPM version comparison",{currentVersion:J,latestVersion:K,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:K,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(G){return h.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function XK8(J,Q){let Y=(q)=>{let[V,K]=q.split("-");return{parts:V?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let q=0;q<Z;q++){let V=X.parts[q]||0,K=G.parts[q]||0;if(V<K)return-1;if(V>K)return 1}if(X.label===G.label)return 0;if(!X.label&&G.label)return 1;if(X.label&&!G.label)return-1;if(X.label&&G.label)return X.label<G.label?-1:1;return 0}r0();function N41(J,Q){let Y=new i4,X=Y.pipe(x8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new kV().scoped("update"),Z=X.subscribe({next:(q)=>{G.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){G.debug("using fake update status for testing",{status:q}),await nU(500),Y.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let V=await Q.get("updates.mode");if(V==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:V});let K=qO(),W=await B41(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,N=0.5;if(Math.abs(U)<0.5)return G.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await U41();if(!V)V=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:V});if(V==="warn"){if(!H())Y.next("update-available");return}if(!z){if(G.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}try{await Xm(W.latestVersion,z);let U=await ZN(W.latestVersion),N={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",N),Y.next("updated");else G.warn("success with warning",N),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(q){G.debug("check failed",{error:q})}finally{await nU(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as cK}from"node:process";function C56(J){let Q=new nA().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(X)=>{await PC1(X.force||!1,X.verbose||!1,"0.0.1764583899-g57f324"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new nA("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(X)=>{await GK8(X.targetVersion)});J.addCommand(Y)}async function GK8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")cK.write(b4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4176
+ npm install -g @sourcegraph/amp`;V(Error(M))}},error:(U)=>{if(!H)H=!0,V(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,q()}})})}L0();L0();async function B41(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),q=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!q.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let V=await q.json(),K=V["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=XK8(J,K),H=W<0,z,U;if(V.time){let N=V.time[J],M=V.time[K],L=Date.now();if(N)z=Math.floor((L-new Date(N).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return h.info("NPM version comparison",{currentVersion:J,latestVersion:K,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:K,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(G){return h.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function XK8(J,Q){let Y=(q)=>{let[V,K]=q.split("-");return{parts:V?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let q=0;q<Z;q++){let V=X.parts[q]||0,K=G.parts[q]||0;if(V<K)return-1;if(V>K)return 1}if(X.label===G.label)return 0;if(!X.label&&G.label)return 1;if(X.label&&!G.label)return-1;if(X.label&&G.label)return X.label<G.label?-1:1;return 0}r0();function N41(J,Q){let Y=new i4,X=Y.pipe(x8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new kV().scoped("update"),Z=X.subscribe({next:(q)=>{G.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){G.debug("using fake update status for testing",{status:q}),await nU(500),Y.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let V=await Q.get("updates.mode");if(V==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:V});let K=qO(),W=await B41(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,N=0.5;if(Math.abs(U)<0.5)return G.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await U41();if(!V)V=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:V});if(V==="warn"){if(!H())Y.next("update-available");return}if(!z){if(G.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}try{await Xm(W.latestVersion,z);let U=await ZN(W.latestVersion),N={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",N),Y.next("updated");else G.warn("success with warning",N),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(q){G.debug("check failed",{error:q})}finally{await nU(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as cK}from"node:process";function C56(J){let Q=new nA().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(X)=>{await PC1(X.force||!1,X.verbose||!1,"0.0.1764590491-gb0d62c"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new nA("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(X)=>{await GK8(X.targetVersion)});J.addCommand(Y)}async function GK8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")cK.write(b4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4177
4177
 
4178
4178
  `));try{if(!J){cK.write(b4.blue(`Checking for updates...
4179
- `));let X=qO(),{hasUpdate:G,latestVersion:Z}=await B41("0.0.1764583899-g57f324",X);if(!G){cK.write(b4.green(`✓ Amp CLI is already up to date: ${"0.0.1764583899-g57f324"} (${"released"} ${"2025-12-01T10:17:29.363Z"})
4180
- `));let V=await ZN("0.0.1764583899-g57f324");if(V.warning)cK.write(`
4179
+ `));let X=qO(),{hasUpdate:G,latestVersion:Z}=await B41("0.0.1764590491-gb0d62c",X);if(!G){cK.write(b4.green(`✓ Amp CLI is already up to date: ${"0.0.1764590491-gb0d62c"} (${"released"} ${"2025-12-01T12:07:01.770Z"})
4180
+ `));let V=await ZN("0.0.1764590491-gb0d62c");if(V.warning)cK.write(`
4181
4181
  `+b4.yellow(V.warning)+`
4182
4182
  `);process.exit(0)}if(!Z)cK.write(b4.yellow("[WARN] could not find latest version")),process.exit(0);J=Z}cK.write(b4.blue(`Updating to version ${J}...
4183
4183
  `)),await Xm(J,void 0,(X)=>{cK.write(b4.dim(`Running: ${X}
4184
- `))});let Q="released";cK.write(b4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-12-01T10:17:29.363Z"})
4184
+ `))});let Q="released";cK.write(b4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-12-01T12:07:01.770Z"})
4185
4185
  `));let Y=await ZN(J);if(Y.warning)cK.write(`
4186
4186
  `+b4.yellow(Y.warning)+`
4187
4187
  `);process.exit(0)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);cK.write(b4.red.bold("Error: ")+Y+`
@@ -4628,7 +4628,7 @@ function execute() {
4628
4628
  }
4629
4629
  }
4630
4630
  `.replaceAll("__TOOL_NAME__",JSON.stringify(J))}r0();import{Console as HH8}from"node:console";var zH8=(J)=>{if(J==="builtin")return"built-in";if(typeof J==="object"&&"toolbox"in J)return`toolbox: ${J.toolbox}`;if(typeof J==="object"&&"mcp"in J)return`mcp: ${J.mcp}`;if(typeof J==="object"&&"remote"in J)return`remote: ${J.remote}`;return"unknown"},FH8=(J)=>J.json?UH8(J):BH8(J),UH8=(J)=>(Q)=>{let Y={name:Q.name,description:Q.description??null,inputSchema:Q.inputSchema,source:Q.source},X=J.isTTY?JSON.stringify(Y,null,2):JSON.stringify(Y);J.stdout.write(X)},BH8=(J)=>(Q)=>{function Y(V){return V&&"type"in V&&typeof V.type==="string"}function X(V,K){if(Z.log(`${" ".repeat(K)}- ${V.key} (${V.type}): ${V.description??""}`),V.children.length>0)for(let W of V.children)X(W,K+1)}function G(V,K){if(!Y(K))return null;let W={key:V,type:K.type,description:K.description,children:[]};if(W.type==="object")W.children=Object.entries(K.properties??{}).map(([H,z])=>G(V?`${V}.${H}`:H,z)).filter((H)=>!!H);else if(W.type==="array"&&K.items){if(W.type=`array of ${K.items.type}`,K.items.type==="object")W.children=G(null,K.items)?.children||[]}return W}let Z=new HH8(J.stdout);if(Z.log(`# ${Q.name} (${zH8(Q.source)})`),Z.log(""),Q.description)Z.log(Q.description);if(Z.log(""),!Q.inputSchema.properties||Object.keys(Q.inputSchema.properties).length===0)return;Z.log("# Schema"),Z.log("");let q=Object.keys(Q.inputSchema.properties).map((V)=>{let K=Q.inputSchema.properties?Q.inputSchema.properties[V]:void 0;return G(V,K)}).filter((V)=>!!V);for(let V of q)X(V,0)};async function c76(J){let Y=(await M6(J.toolService.tools)).find((Z)=>Z.spec.name===J.toolName);if(Y===void 0){J.stdout.write(`No such tool: ${J.toolName}
4631
- `),J.exit(1);return}let X=Y.spec;FH8(J)(X),J.exit(0)}r0();var e76=N6(r76(),1);a$();t8();G4();r0();async function s76(J){let{toolName:Q,configService:Y,toolService:X,mcpService:G}=J,Z={id:p$(),created:Date.now(),v:0,messages:[]},q=d0.file(process.cwd()),V=CM(),K=h11(qB1,Z.id,async()=>{}),W=await Y.getLatest();return{dir:q,dirs:[q],tool:Q,thread:Z,trackedFiles:new _Y,toolUseID:V,todos:void 0,configService:Y,toolService:X,mcpService:G,config:W,filesystem:b11(D5,K,V),fileChangeTracker:K,getAllTrackedChanges:async()=>K.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>X0.of(Z),get:()=>Promise.resolve(Z)},getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},vfs:{writeFile:D5.writeFile.bind(D5),readFile:D5.readFile.bind(D5),stat:D5.stat.bind(D5)},deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:qB1}}function kH8(J){let Q=new i4,Y=()=>Q.next();return process.once("SIGINT",Y),J.pipe(uF(Q),NX((X)=>{if(X.status==="error")throw Error(`Tool execution error: ${JSON.stringify(X.error)}`);else if(X.status==="rejected-by-user")throw Error("Tool execution was rejected by user");else if(X.status==="cancelled")throw Error("Tool execution was cancelled")}),k$(()=>{process.off("SIGINT",Y)}))}async function J26(J){let{toolName:Q,rawArgs:Y,stdinInput:X,only:G,stream:Z,threadDeps:q,stdout:V,stderr:K,exit:W}=J,H=q.toolService;try{let U=(await M6(H.tools)).find((I)=>I.spec.name===Q);if(!U){K.write(`Error: Tool '${Q}' not found
4631
+ `),J.exit(1);return}let X=Y.spec;FH8(J)(X),J.exit(0)}r0();var e76=N6(r76(),1);a$();t8();G4();r0();async function s76(J){let{toolName:Q,configService:Y,toolService:X,mcpService:G}=J,Z={id:p$(),created:Date.now(),v:0,messages:[]},q=d0.file(process.cwd()),V=CM(),K=h11(qB1,Z.id,async()=>{}),W=await Y.getLatest();return{dir:q,dirs:[q],tool:Q,thread:Z,trackedFiles:new _Y,toolUseID:V,todos:void 0,configService:Y,toolService:X,mcpService:G,config:W,filesystem:b11(D5,K,V),fileChangeTracker:K,getAllTrackedChanges:async()=>K.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>X0.of(Z),get:()=>Promise.resolve(Z)},getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},vfs:{writeFile:D5.writeFile.bind(D5),readFile:D5.readFile.bind(D5),stat:D5.stat.bind(D5)},deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:qB1,discoveredGuidanceFileURIs:new Set}}function kH8(J){let Q=new i4,Y=()=>Q.next();return process.once("SIGINT",Y),J.pipe(uF(Q),NX((X)=>{if(X.status==="error")throw Error(`Tool execution error: ${JSON.stringify(X.error)}`);else if(X.status==="rejected-by-user")throw Error("Tool execution was rejected by user");else if(X.status==="cancelled")throw Error("Tool execution was cancelled")}),k$(()=>{process.off("SIGINT",Y)}))}async function J26(J){let{toolName:Q,rawArgs:Y,stdinInput:X,only:G,stream:Z,threadDeps:q,stdout:V,stderr:K,exit:W}=J,H=q.toolService;try{let U=(await M6(H.tools)).find((I)=>I.spec.name===Q);if(!U){K.write(`Error: Tool '${Q}' not found
4632
4632
  `),W(1);return}let N=hH8(Y),M=U.spec,L;if(X)try{L=JSON.parse(X)}catch(I){K.write(`Error: Invalid JSON input from stdin: ${I instanceof Error?I.message:"Unknown error"}
4633
4633
  `),W(1);return}else try{L=yH8(N,M.inputSchema,Q)}catch(I){K.write(`Error: ${I instanceof Error?I.message:"Unknown error"}
4634
4634
  `),W(1);return}let A=fH8(L,M.inputSchema,Q);if(A){K.write(`Error: ${A}
@@ -4801,7 +4801,7 @@ exit code: ${Z}`,new q1({color:X.foreground,dim:!0,italic:!0})));if(q)V.push(new
4801
4801
  `,N),...M])})];if(W.url){let S=W.url.replace(/^https?:\/\//,"");I.push(new Y7({uri:W.url,text:S,style:new q1({color:Y.secondary,underline:!0})}))}let T=new z0({width:40,child:new n0({crossAxisAlignment:"start",mainAxisSize:"min",children:I})});return F8.child(new i6({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new cj1({width:ZX6,height:$X6,agentMode:this.widget.agentMode,glow:this._glow,t:L,fps:0,shockwaves:this._shockwaves,onShockwave:E,...q==="disabled"&&{seed:42}}),new z0({width:2}),T]}))}}L0();t8();N4();x7();t8();r0();function OL8(J,Q){return`${J}:${Q}`}class wk1{threadService;workers=new Map;threadsMap=new Map;subthreadsMap=new Map;mainThreadSubs=new Map;subthreadsSubs=new Map;workerStatusSubs=new Map;subthreadPatchSubs=new Map;mainThreadObservable;subthreadObservable;workerStatusObservable;emitMainThread=null;emitSubthread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new X0((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.subthreadObservable=new X0((Q)=>{return this.emitSubthread=(Y)=>Q.next(Y),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new X0((Q)=>{return this.emitWorkerStatus=(Y)=>Q.next(Y),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.subthreadsMap.set(Q,[]),this.workers.set(Q,{state:"initial"});let Y=this.threadService.observePatches(Q).pipe(jM()).subscribe((Z)=>{this.threadsMap.set(Q,Z);let q=this.subthreadsMap.get(Q)||[],V=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:Z,subthreads:q,workerStatus:V})});this.mainThreadSubs.set(Q,Y);let X=J.status.subscribe((Z)=>{if(this.workers.set(Q,Z),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:Z})});this.workerStatusSubs.set(Q,X);let G=J.subthreads.subscribe((Z)=>{this.subthreadsMap.set(Q,Z);for(let q of Z){let V=OL8(Q,q.toolUse.id);if(this.subthreadPatchSubs.has(V))continue;let K=this.threadService.observePatches(q.threadID).pipe(jM()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:q})});this.subthreadPatchSubs.set(V,K)}});this.subthreadsSubs.set(Q,G)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Y=this.workerStatusSubs.get(J);if(Y)Y.unsubscribe(),this.workerStatusSubs.delete(J);let X=this.subthreadsSubs.get(J);if(X)X.unsubscribe(),this.subthreadsSubs.delete(J);for(let[G,Z]of this.subthreadPatchSubs.entries())if(G.startsWith(`${J}:`))Z.unsubscribe(),this.subthreadPatchSubs.delete(G);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new X0((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),subthreads:new X0((Q)=>{return this.subthreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new X0((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 X=this.workers.get(Q);if(X)J[Q]=IA(Y,X)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.subthreadsSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();for(let J of this.subthreadPatchSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.subthreadsSubs.clear(),this.workerStatusSubs.clear(),this.subthreadPatchSubs.clear(),this.workers.clear(),this.threadsMap.clear(),this.subthreadsMap.clear()}}function wL8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Y,subthread:X}=Q,G=J.subagents[X.threadID];if(!G){if(G={subThreadID:Y.id,parentToolID:X.toolUse.id,taskDescription:X.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=QQ(J.mainThread);G.isCompleted=VX6(W,X.toolUse.id)}}let Z=EL8(Y,G.agentState),q=G.agentState===Z?G:{...G,agentState:Z},V={...J.tools},K=lC(Y).items.filter((W)=>W.type==="toolResult");for(let W of K)V[W.id]={id:W.id,subthreadID:Y.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[X.threadID]:q},tools:V,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Y,subthreads:X,workerStatus:G}=Q,Z=QQ(Y),q={...J.subagents};for(let z of X){let U=q[z.threadID];if(!U)continue;let N=VX6(Z,z.toolUse.id);q[z.threadID]={...U,isCompleted:N}}let{items:V}=lC(Y),K=IA(Y,G),W=BI({messages:Y.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:q,items:V,viewState:K,todosList:H,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=IA(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function lC(J){let Q=[],Y=new Map,X=new Set;for(let[G,Z]of J.messages.entries()){let q=`${Z.role}-${G}`;switch(Z.role){case"assistant":{let V=Z.state.type==="streaming";for(let W of Z.content)if(W.type==="tool_use"){if(Y.set(W.id,W),V)X.add(W.id)}if(Z.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:q,message:Z});for(let W of Z.content)if(W.type==="tool_use"){let H=!1;for(let z=G+1;z<J.messages.length;z++){let U=J.messages[z];if(U){for(let N of U.content)if(N.type==="tool_result"&&N.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:V?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:q,message:Z});break;case"user":{let V=Z.content.some((K)=>K.type==="text"&&K.text.trim()||K.type==="image");for(let K of Z.content)if(K.type==="tool_result"){let W=Y.get(K.toolUseID)??IX(J,K.toolUseID);if(!W)throw Error(`(bug) tool use ${K.toolUseID} not found`);Q.push({type:"toolResult",id:K.toolUseID,toolUse:W,toolResult:K})}if(V)Q.push({type:"message",id:q,message:Z});break}}}return{items:Q}}function VX6(J,Q){let Y=J.get(Q);return(Y&&N2(Y.run))??!1}function EL8(J,Q){let Y=J.messages.at(-1);if(Y?.content.some((G)=>G.type==="tool_result"&&G.run.status==="blocked-on-user"))return h.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(lC(J).items.some((G)=>G.type==="toolResult"&&G.toolResult.run.status==="in-progress")){let G=Q?.type==="running-tools"?Q.startTime:Date.now();return h.info("Subagent status: running-tools",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}if(Y&&Y.role==="assistant"&&Y.state.type==="streaming")switch(Y.content.at(-1)?.type){case"text":return h.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return h.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let Z=Q?.type==="running-tools"?Q.startTime:Date.now();return h.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:Z,hasStartTime:!!Z}),{type:"running-tools",startTime:Z}}default:return h.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return h.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class Ek1 extends Q6{props;constructor(J){super();this.props=J}createState(){return new KX6}}class KX6 extends e0{state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new wk1(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((Z)=>{this.dispatch({type:"main-thread-patch",thread:Z.mainThread,subthreads:Z.subthreads,workerStatus:Z.workerStatus})});this.subscriptions.push(Y);let X=Q.subthreads.subscribe((Z)=>{this.dispatch({type:"subthread-patch",thread:Z.thread,subthread:Z.subthread})});this.subscriptions.push(X);let G=Q.workerStatus.subscribe((Z)=>{this.dispatch({type:"worker-status-change",workerStatus:Z.status})});this.subscriptions.push(G)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=wL8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((Z)=>({toolUse:Z.toolUse,toolRun:Z.toolRun,subthreadID:Z.subthreadID})),Q={};for(let Z of Object.values(this.state.subagents)){let q=J.filter((V)=>V.subthreadID===Z.subThreadID);Q[Z.parentToolID]=q}let Y=(Z)=>Z===s5||Z===V9||Z===EX,X=new Map;for(let Z of this.state.items)if(Z.type==="toolResult"&&Y(Z.toolUse.name))X.set(Z.toolUse.id,{toolUseId:Z.toolUse.id,toolName:Z.toolUse.name,toolRun:Z.toolResult.run});let G=Array.from(X.values());for(let{toolUseId:Z,toolRun:q}of G){let V=[],K;if(q.status==="in-progress"||q.status==="done"||q.status==="error"||q.status==="cancelled")K=q.progress;if(K){let W=0;for(let H of K)if(H.tool_uses)for(let z of H.tool_uses){let U=`${Z}:progress:${W++}`;V.push({toolUse:zI(z.tool_name,z.input,U),toolRun:{status:z.status}})}}Q[Z]=V}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker,this.recentThreadIDs)}}class Ik1 extends Q6{props;constructor(J){super({key:J.key});this.props=J}createState(){return new WX6}}class WX6 extends e0{build(J){let Y=B6.of(J).colors,{todos:X,title:G="TODOs"}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new z0({width:0,height:0});let Z=X.map((q)=>this.buildTodoItem(q,Y));return new J6({child:new h6({padding:j0.symmetric(1,0),child:new n0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new g1({text:new e(G,new q1({bold:!0,color:Y.foreground}))}),...Z]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),X=J.status==="completed",G=new q1({bold:J.status==="in-progress",color:Q.foreground,dim:X}),Z=new q1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:X});return new i6({crossAxisAlignment:"start",children:[new g1({text:new e(Y,G)}),new z0({width:1}),new F4({child:new g1({text:new e(J.content,Z)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Pk1 extends O6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Y,onButtonClick:X}){super({key:J});this.ad=Q,this.onDismiss=Y,this.onButtonClick=X}build(J){let Q=B6.of(J),Y=Q.colors.primary,X=Q.colors.foreground;return new J6({decoration:new z8(void 0,new g4(new w4(Y,1,"rounded"),new w4(Y,1,"rounded"),void 0,new w4(Y,1,"rounded"))),child:new h6({padding:j0.horizontal(1),child:new n0({children:[new i6({crossAxisAlignment:"start",children:[new F4({child:new g1({text:new e(this.ad.content,new q1({color:X}))})}),new z0({width:4}),new Y7({uri:"https://ampcode.com/free",text:"Ad",style:new q1({color:X,dim:!0})})]}),new i6({crossAxisAlignment:"start",children:[new YS1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:j0.horizontal(1),color:Y,reverse:!0}),new z0({width:2}),new g1({text:new e(this.ad.destinationUrlHostname,new q1({color:X,dim:!0}))})]})]})})})}}class Rk1 extends Q6{props;constructor(J){super();this.props=J}createState(){return new HX6(this.props.autofocus??!0)}}class HX6 extends e0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(V)=>{if(V.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(V.ctrlKey&&V.key==="c"||V.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=H8.sizeOf(J),X=Math.min(60,Y.width-4),G=Y.height-4,Z=[];if(this.widget.props.title)Z.push(new g1({text:new e(this.widget.props.title,new q1({bold:!0,color:A1.blue}))}),new z0({height:1}));if(this.widget.props.message)Z.push(new g1({text:new e(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)Z.push(new z0({height:1}));let q=[];if(this.widget.props.showCopyOption)q.push(new g1({text:new e("Enter to copy",new q1({dim:!0}))}));return q.push(new g1({text:new e("Escape to close",new q1({dim:!0}))})),Z.push(new i6({children:q.flatMap((V,K)=>K<q.length-1?[V,new z0({width:1}),new g1({text:new e("•",new q1({dim:!0}))}),new z0({width:1})]:[V]),mainAxisSize:"min"})),new F8({child:new J6({constraints:new c6(X,X,0,G),decoration:new z8(A1.default(),new g4(new w4(A1.blue,1,"rounded"),new w4(A1.blue,1,"rounded"),new w4(A1.blue,1,"rounded"),new w4(A1.blue,1,"rounded"))),padding:new j0(2,2,2,2),child:new G9({autofocus:this.autofocus,onKey:Q,child:new n0({children:Z,mainAxisSize:"min"})})})})}}class _91 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,_91.prototype)}}class k91 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,k91.prototype)}}function Tk1(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})}FH();L0();import{spawn as IL8}from"node:child_process";import{promises as PL8}from"node:fs";function zX6(J){return J.kind==="executable"}function FX6(J){return J.kind==="markdown"}var yz=50000,UX6=300000;async function Ck1(J,Q,Y,X={}){let{timeoutMs:G=UX6,signal:Z,source:q}=X;try{let V=await Y.getCommand(J,q);if(!V)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Y.isCommandAvailable(J,q))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(h.debug("Executing command",{commandName:J,filePath:V.filePath,args:Q}),FX6(V))return await RL8(V,Q);else if(zX6(V))return await TL8(V,Q,G,Z);else return{success:!1,output:"",error:"Unsupported command type"}}catch(V){return h.error("Failed to execute command",{commandName:J,error:V}),{success:!1,output:"",error:V instanceof Error?V.message:"Unknown error occurred"}}}async function RL8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await PL8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>yz?Y.slice(0,yz)+`
4802
4802
  ... (output truncated at ${yz} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function TL8(J,Q,Y=UX6,X){return new Promise((G)=>{let[Z,q]=CL8(J,Q);h.debug("Spawning command",{spawnCommand:Z,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Y});let V=iw0(X),K=!1,W=setTimeout(()=>{K=!0,V.abort(),h.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=IL8(Z,q,{stdio:["pipe","pipe","pipe"],signal:V.signal,detached:!0}),z=[],U=[],N=0;H.stdout?.on("data",(M)=>{let L=M.toString();if(N+=L.length,N<=yz)z.push(L);else{let A=yz-(N-L.length);if(A>0)z.push(L.slice(0,A))}}),H.stderr?.on("data",(M)=>{let L=M.toString();if(N+=L.length,N<=yz)U.push(L);else{let A=yz-(N-L.length);if(A>0)U.push(L.slice(0,A))}}),H.on("close",(M)=>{if(clearTimeout(W),K){G({success:!1,output:z.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(V.signal.aborted){G({success:!1,output:z.join(""),error:"The command was aborted",exitCode:M??void 0});return}let L=M===0||M===1,A=z.join(""),E=U.join(""),P=A;if(!L&&!A.trim()&&E.trim())P=E;else if(E.trim())P+=A?`
4803
4803
  ${E}`:E;if(N>yz)P+=`
4804
- ... (output truncated at ${yz} characters)`;G({success:L,output:P.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(K)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";G({success:!1,output:z.join(""),error:L})})})}function CL8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return SL8(Y,X?[...X]:null,G,Q);else return jL8(Y,X?[...X]:null,G,Q)}function jL8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function SL8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}L0();sG();W3();sW();vX();Qq();UH();ZK();t8();x7();Hk();r0();var SX6=N6(dP(),1);import{writeFile as TX6}from"fs/promises";import CX6 from"path";L0();vX();class jk1{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.1764583899-g57f324"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await ko(Q,this.configService)}catch(Q){h.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 Sk1 extends Q6{props;constructor(J){super();this.props=J}createState(){return new BX6}}class BX6 extends e0{_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 NX6 extends e0{controller=new iZ;focusNode=new n8({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=B6.of(J),{colors:Y,app:X}=Q,G=this.widget.props.isRequiredArg??!0,Z=this.controller.text.trim().length>0,q=!G||Z,V=g4.all(new w4(Y.foreground,1,"solid")),K=new AO({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(N)=>{let M=N.trim();if(G&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new i6({children:[new J6({decoration:{color:A1.default()},child:new g1({text:new e(">",new q1({color:Y.foreground}))})}),new F4({child:K})]}),H=new J6({padding:j0.symmetric(1,0),child:new g1({text:new e("",void 0,[new e("Command: ",new q1({color:Y.foreground})),new e(this.widget.props.commandName,new q1({color:A1.yellow,bold:!0}))])})}),z=[];if(q)z.push(new e("Enter",new q1({color:X.keybind}))),z.push(new e(" to submit, ",new q1({color:Y.foreground,dim:!0})));z.push(new e("Esc",new q1({color:X.keybind}))),z.push(new e(" to cancel",new q1({color:Y.foreground,dim:!0})));let U=new J6({padding:j0.symmetric(1,0),child:new g1({text:new e("",void 0,z)})});return new J6({decoration:{border:V,color:A1.default()},padding:j0.all(1),child:new n0({children:[H,new z0({height:1}),W,new n5,U]})})}}class y91 extends Q6{props;constructor(J){super();this.props=J}createState(){return new NX6}}UH();class DX6 extends e0{controller=new iZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new n8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=MU)return!1;let Q=jC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=B6.of(J),{colors:Y,app:X}=Q,Z=H8.of(J).size.height,q=Math.max(Math.floor(Z*0.5),10),V=new yO({controller:this.controller,triggers:[new EN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(N)=>{this.widget.props.onSubmit(N.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:I9.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),K=new G9({focusNode:this.focusNode,child:V}),W=new J6({constraints:new c6({maxHeight:q}),padding:j0.symmetric(1,0),child:K}),H=new J6({padding:j0.symmetric(1,0),child:new g1({text:new e("",void 0,[new e("Command: ",new q1({color:Y.foreground})),new e(this.widget.props.commandName,new q1({color:A1.yellow,bold:!0}))])})}),z=new J6({padding:j0.symmetric(1,0),child:new g1({text:this.isConfirmingClearInput?new e("",void 0,[new e("Esc",new q1({color:X.keybind})),new e(" again to clear input",new q1({color:Y.foreground,dim:!0}))]):new e("",void 0,[new e("Press ",new q1({color:Y.foreground,dim:!0})),new e("Enter",new q1({color:X.keybind})),new e(" to submit, ",new q1({color:Y.foreground,dim:!0})),new e("Esc",new q1({color:X.keybind})),new e(" to clear",new q1({color:Y.foreground,dim:!0}))])})}),U=[H,new z0({height:1}),new F4({child:W}),new z0({height:1}),z];return new J6({decoration:{border:g4.all(new w4(Y.foreground,1,"solid")),color:A1.default()},padding:j0.all(1),child:new n0({children:U})})}}class iC extends Q6{props;constructor(J){super();this.props=J}createState(){return new DX6}}import{isDeepStrictEqual as xL8}from"node:util";var _L8=/[\\/_ +.#"@[({&]/,kL8=/[\\/_ +.#"@[({&]/g,yL8=/[\s-]/,MX6=/[\s-]/g;function v91(J,Q,Y,X,G,Z,q){if(Z===Q.length){if(G===J.length)return 1;return 0.99}let V=`${G},${Z}`;if(q[V]!==void 0)return q[V];let K=X.charAt(Z),W=Y.indexOf(K,G),H=0,z,U,N,M;while(W>=0){if(z=v91(J,Q,Y,X,W+1,Z+1,q),z>H){if(W===G)z*=1;else if(yL8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(G,W-1).match(MX6),M&&G>0)z*=Math.pow(0.999,M.length)}else if(_L8.test(J.charAt(W-1))){if(z*=0.8,N=J.slice(G,W-1).match(kL8),N&&G>0)z*=Math.pow(0.999,N.length)}else if(z*=0.3,G>0)z*=Math.pow(0.999,W-G);if(J.charAt(W)!==Q.charAt(Z))z*=0.9999}if(z<0.1&&(Y.charAt(W-1)===X.charAt(Z+1)||X.charAt(Z+1)===X.charAt(Z)&&Y.charAt(W-1)!==X.charAt(Z))){if(U=v91(J,Q,Y,X,W+1,Z+2,q),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Y.indexOf(K,W+1)}return q[V]=H,H}function x91(J){return J.toLowerCase().replace(MX6," ")}function LX6(J,Q){let Y=v91(J,Q,x91(J),x91(Q),0,0,{}),X=Q.trim().split(/\s+/);if(X.length>1){let G=0,Z=0;for(let V of X){let K=v91(J,V,x91(J),x91(V),0,0,{});if(K===0)return Y;G+=K,Z+=V.length}let q=G/X.length*0.95;return Math.max(Y,q)}return Y}class nC{}class aC{}class f91{}class h91{}class AX6 extends Q6{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new OX6}}class OX6 extends e0{build(J){return this.widget.onContext(J),this.widget.child}}function vL8(J,Q){if(J==="")return{matches:!0,score:1};let Y=LX6(Q,J);return{matches:Y>0.15,score:Y}}class mq extends Q6{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new wX6}}class wX6 extends e0{controller=new iZ;focusNode;scrollController=new e2;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new n8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),Y9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!xL8(J.props.items,this.widget.props.items)){this.ensureSelectedItemVisible();let Q=this.getFilteredItems();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 nC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof aC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof f91){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 h91)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Y)=>!this.widget.props.filterItem||this.widget.props.filterItem(Y,J)).map((Y)=>({item:Y,...vL8(J,this.widget.props.getLabel(Y))})).filter((Y)=>Y.matches).sort(this.widget.props.sortItems?(Y,X)=>this.widget.props.sortItems(Y,X,J):(Y,X)=>X.score-Y.score).map((Y)=>Y.item);if(this.widget.props.maxRenderItems)return Q.slice(0,this.widget.props.maxRenderItems);return Q}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,X=Q.size.height;v81(J,{top:Y,bottom:X},{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(),Y9.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 X=Y[J],G=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!G){if(X)this.widget.props.onAccept(X)}}};build(J){let Q=B6.of(J),{colors:Y}=Q,X=this.getFilteredItems(),G=g4.all(new w4(Y.foreground,1,"solid")),Z=this.widget.props.enabled??!0,q=new AO({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:Z,style:{textColor:Y.foreground,border:null},maxLines:1}),V=new fq({shortcuts:new Map([[new B4("ArrowDown"),new nC],[new B4("ArrowUp"),new aC],[new B4("Tab"),new nC],[new B4("Tab",{shift:!0}),new aC],[new B4("n",{ctrl:!0}),new nC],[new B4("p",{ctrl:!0}),new aC],[new B4("Enter"),new f91],[new B4("Escape"),new h91]]),focusNode:this.focusNode,child:q}),K=new eQ({actions:new Map([[nC,new X9(this.invoke)],[aC,new X9(this.invoke)],[f91,new X9(this.invoke)],[h91,new X9(this.invoke)]]),child:V}),W=new i6({children:[new J6({decoration:{color:A1.default()},child:new g1({text:new e(">",new q1({color:Y.foreground}))})}),new F4({child:K})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new z0({height:10,child:new F8({child:new g1({text:new e(L,new q1({color:Y.foreground}))})})})}else if(X.length===0&&this.widget.props.emptyStateText)H=new F4({child:new F8({child:new g1({text:new e(this.widget.props.emptyStateText,new q1({color:Y.foreground,dim:!0}))})})});else{let L=X.map((A,E)=>{let P=E===this.selectedIndex,I=this.widget.props.isItemDisabled?.(A)??!1,T;if(this.widget.props.renderItem)T=this.widget.props.renderItem(A,P,I,J);else{let S=P?A1.yellow:void 0,y=P?A1.black:Y.foreground;T=new J6({decoration:S?{color:S}:void 0,padding:j0.symmetric(2,0),child:new g1({text:new e(this.widget.props.getLabel(A),new q1({color:y,dim:I}))})})}return new AX6(new M8({onClick:(S)=>this.handleItemClick(E,S.clickCount),child:T}),(S)=>{this.itemContexts[E]=S})});H=new n0({children:L,crossAxisAlignment:"start"})}let z=new F4({child:new M8({onScroll:this.handleScroll,opaque:!1,child:new u7({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new J6({padding:j0.symmetric(1,0),child:new g1({text:new e(this.widget.props.title,new q1({color:A1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new z0({height:1}),z),this.controller.text!==""){let L=X.length>0?X[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new J6({padding:j0.vertical(1),child:new F8({child:A})}));else U.push(new z0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new J6({decoration:{border:G,color:A1.default()},padding:j0.symmetric(1,0),child:new n0({children:U})})}}class _k1 extends Q6{createState(){return new EX6}}class EX6 extends e0{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 g1({text:new e("●",new q1({color:this.isGreen?A1.green:A1.index(8),bold:!0})),maxLines:1})}}function fL8(J){let Q=new Map,Y=new Map,X=new Map,G=[];for(let q of J)Q.set(q.id,q);for(let q of J){let V=q.parentRelationships.find((K)=>K.role==="child"&&Q.has(K.threadID));if(V){X.set(q.id,V.type);let K=V.threadID,W=Y.get(K)||[];W.push(q),Y.set(K,W)}else G.push(q)}return FG.flatten(G,(q)=>Y.get(q.id)).map((q)=>({...q.item,depth:q.depth,isLast:q.isLast,ancestorsAreLast:q.ancestorsAreLast,relationshipType:X.get(q.item.id)}))}function kk1(J,Q,Y){return new g1({text:new e(`${J}${Q}`,new q1({color:Y})),maxLines:1})}function hL8(J,Q,Y,X){return[kk1("+",J,X.success),n5.horizontal(1),kk1("~",Q,X.warning),n5.horizontal(1),kk1("-",Y,X.destructive)]}class b91 extends O6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((H)=>H.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((H)=>H.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],X=this.props.currentThreadID,G=[...Q].sort((H,z)=>{if(X){if(H.id===X)return-1;if(z.id===X)return 1}let U=Y.indexOf(H.id),N=Y.indexOf(z.id);if(U!==-1&&N!==-1)return U-N;if(U!==-1)return-1;if(N!==-1)return 1;return 0}),Z=fL8(G),q=Math.max(0,...Z.map((H)=>H.description.timeAgo.length)),V=B6.of(J),K=new h6({padding:j0.symmetric(0,1),child:new F8({child:new g1({text:new e("",new q1({color:V.colors.foreground,dim:!0}),[new e("Ctrl+T",new q1({color:A1.blue,dim:!0})),new e(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new q1({color:V.colors.foreground,dim:!0}))])})})});return new mq({items:Z,getLabel:(H)=>H.title,onAccept:(H)=>this.props.onSelect?.(H.id),onDismiss:this.props.onDismiss,onSelectionChange:(H)=>{if(this.props.previewController){if(H)this.props.previewController.select(H.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:1000,footer:this.props.isLoading?void 0:K,renderItem:(H,z,U,N)=>{let M=B6.of(N),{colors:L}=M,A=z?A1.yellow:void 0,E=z?A1.black:L.foreground,P=A1.index(8),I=(J1,n)=>new z0({width:n,child:i6.end([new g1({text:new e(J1,new q1({color:P}))})])}),T=this.props.threadViewStates[H.id],S=[],y=H.relationshipType==="handoff",x=new p81;if(H.depth>0){let J1=[],n=H.ancestorsAreLast.slice(1);for(let H1 of n)J1.push(new e(x.getAncestorPrefix(H1),new q1({color:x.connectorColor,dim:x.connectorDim})));let u=H.isLast?x.elbow:x.tee,s=x.getConnectorText(u);J1.push(new e(s,new q1({color:x.connectorColor,dim:x.connectorDim}))),S.push(new g1({text:new e("",void 0,J1)}))}let g=[],p=this.props.currentThreadID===H.id?new e("(current) ",new q1({color:A1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new e("(visited) ",new q1({color:L.foreground,dim:!0})):null;if(p)g.push(new g1({text:p}));if(T){if(T.state==="active"&&(T.interactionState==="tool-running"||T.interactionState===!1))g.push(new _k1),g.push(new z0({width:1}))}let b=H.title;if(H.relationshipType==="fork"){let J1=b.match(/^Forked\((\d+)\): /);if(J1)b=b.slice(J1[0].length);else while(b.startsWith("Forked: "))b=b.slice(8);g.push(new g1({text:new e("[fork] ",new q1({color:A1.blue}))}))}else if(y)g.push(new g1({text:new e("[handoff] ",new q1({color:A1.index(208)}))}));if(g.push(new F4({child:new g1({text:new e(b,new q1({color:E})),overflow:"ellipsis",maxLines:1})})),g.push(new z0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let J1=z?{success:P,warning:P,destructive:P}:L;g.push(...hL8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,J1)),g.push(new z0({width:2}))}return g.push(I(H.description.timeAgo,q)),new J6({decoration:A?{color:A}:void 0,padding:j0.symmetric(2,0),child:new i6({children:[...S,...g]})})}})}}function IX6(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/60000),G=Math.floor(Y/3600000),Z=Math.floor(Y/86400000);if(X<1)return"just now";if(X<60)return`${X}m ago`;if(G<24)return`${G}h ago`;if(Z<7)return`${Z}d ago`;return J.toLocaleDateString()}class yk1 extends O6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((G,Z)=>Z.pubDate.getTime()-G.pubDate.getTime()),Y=Math.max(0,...Q.map((G)=>IX6(G.pubDate).length));return new mq({items:Q,getLabel:(G)=>G.title,onAccept:(G)=>this.props.onSelect?.(G),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(G,Z,q,V)=>{let K=B6.of(V),{colors:W}=K,H=Z?A1.yellow:void 0,z=Z?A1.black:W.foreground,U=A1.index(8),N=G.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new z0({width:A,child:i6.end([new g1({text:new e(L,new q1({color:U}))})])});return new J6({decoration:H?{color:H}:void 0,padding:j0.symmetric(2,0),child:new i6({children:[new F4({child:new g1({text:new e(G.title,new q1({color:z})),overflow:"ellipsis",maxLines:1})}),new z0({width:2}),new g1({text:new e(N,new q1({color:U})),maxLines:1}),new z0({width:2}),M(IX6(G.pubDate),Y)]})})}})}}class xk1 extends O6{props;constructor(J){super();this.props=J}build(){return new F8({child:new g1({text:new e("",void 0,[new e(`Forked to new thread:
4804
+ ... (output truncated at ${yz} characters)`;G({success:L,output:P.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(K)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";G({success:!1,output:z.join(""),error:L})})})}function CL8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return SL8(Y,X?[...X]:null,G,Q);else return jL8(Y,X?[...X]:null,G,Q)}function jL8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function SL8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}L0();sG();W3();sW();vX();Qq();UH();ZK();t8();x7();Hk();r0();var SX6=N6(dP(),1);import{writeFile as TX6}from"fs/promises";import CX6 from"path";L0();vX();class jk1{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.1764590491-gb0d62c"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await ko(Q,this.configService)}catch(Q){h.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 Sk1 extends Q6{props;constructor(J){super();this.props=J}createState(){return new BX6}}class BX6 extends e0{_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 NX6 extends e0{controller=new iZ;focusNode=new n8({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=B6.of(J),{colors:Y,app:X}=Q,G=this.widget.props.isRequiredArg??!0,Z=this.controller.text.trim().length>0,q=!G||Z,V=g4.all(new w4(Y.foreground,1,"solid")),K=new AO({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(N)=>{let M=N.trim();if(G&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new i6({children:[new J6({decoration:{color:A1.default()},child:new g1({text:new e(">",new q1({color:Y.foreground}))})}),new F4({child:K})]}),H=new J6({padding:j0.symmetric(1,0),child:new g1({text:new e("",void 0,[new e("Command: ",new q1({color:Y.foreground})),new e(this.widget.props.commandName,new q1({color:A1.yellow,bold:!0}))])})}),z=[];if(q)z.push(new e("Enter",new q1({color:X.keybind}))),z.push(new e(" to submit, ",new q1({color:Y.foreground,dim:!0})));z.push(new e("Esc",new q1({color:X.keybind}))),z.push(new e(" to cancel",new q1({color:Y.foreground,dim:!0})));let U=new J6({padding:j0.symmetric(1,0),child:new g1({text:new e("",void 0,z)})});return new J6({decoration:{border:V,color:A1.default()},padding:j0.all(1),child:new n0({children:[H,new z0({height:1}),W,new n5,U]})})}}class y91 extends Q6{props;constructor(J){super();this.props=J}createState(){return new NX6}}UH();class DX6 extends e0{controller=new iZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new n8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=MU)return!1;let Q=jC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=B6.of(J),{colors:Y,app:X}=Q,Z=H8.of(J).size.height,q=Math.max(Math.floor(Z*0.5),10),V=new yO({controller:this.controller,triggers:[new EN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(N)=>{this.widget.props.onSubmit(N.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:I9.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),K=new G9({focusNode:this.focusNode,child:V}),W=new J6({constraints:new c6({maxHeight:q}),padding:j0.symmetric(1,0),child:K}),H=new J6({padding:j0.symmetric(1,0),child:new g1({text:new e("",void 0,[new e("Command: ",new q1({color:Y.foreground})),new e(this.widget.props.commandName,new q1({color:A1.yellow,bold:!0}))])})}),z=new J6({padding:j0.symmetric(1,0),child:new g1({text:this.isConfirmingClearInput?new e("",void 0,[new e("Esc",new q1({color:X.keybind})),new e(" again to clear input",new q1({color:Y.foreground,dim:!0}))]):new e("",void 0,[new e("Press ",new q1({color:Y.foreground,dim:!0})),new e("Enter",new q1({color:X.keybind})),new e(" to submit, ",new q1({color:Y.foreground,dim:!0})),new e("Esc",new q1({color:X.keybind})),new e(" to clear",new q1({color:Y.foreground,dim:!0}))])})}),U=[H,new z0({height:1}),new F4({child:W}),new z0({height:1}),z];return new J6({decoration:{border:g4.all(new w4(Y.foreground,1,"solid")),color:A1.default()},padding:j0.all(1),child:new n0({children:U})})}}class iC extends Q6{props;constructor(J){super();this.props=J}createState(){return new DX6}}import{isDeepStrictEqual as xL8}from"node:util";var _L8=/[\\/_ +.#"@[({&]/,kL8=/[\\/_ +.#"@[({&]/g,yL8=/[\s-]/,MX6=/[\s-]/g;function v91(J,Q,Y,X,G,Z,q){if(Z===Q.length){if(G===J.length)return 1;return 0.99}let V=`${G},${Z}`;if(q[V]!==void 0)return q[V];let K=X.charAt(Z),W=Y.indexOf(K,G),H=0,z,U,N,M;while(W>=0){if(z=v91(J,Q,Y,X,W+1,Z+1,q),z>H){if(W===G)z*=1;else if(yL8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(G,W-1).match(MX6),M&&G>0)z*=Math.pow(0.999,M.length)}else if(_L8.test(J.charAt(W-1))){if(z*=0.8,N=J.slice(G,W-1).match(kL8),N&&G>0)z*=Math.pow(0.999,N.length)}else if(z*=0.3,G>0)z*=Math.pow(0.999,W-G);if(J.charAt(W)!==Q.charAt(Z))z*=0.9999}if(z<0.1&&(Y.charAt(W-1)===X.charAt(Z+1)||X.charAt(Z+1)===X.charAt(Z)&&Y.charAt(W-1)!==X.charAt(Z))){if(U=v91(J,Q,Y,X,W+1,Z+2,q),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Y.indexOf(K,W+1)}return q[V]=H,H}function x91(J){return J.toLowerCase().replace(MX6," ")}function LX6(J,Q){let Y=v91(J,Q,x91(J),x91(Q),0,0,{}),X=Q.trim().split(/\s+/);if(X.length>1){let G=0,Z=0;for(let V of X){let K=v91(J,V,x91(J),x91(V),0,0,{});if(K===0)return Y;G+=K,Z+=V.length}let q=G/X.length*0.95;return Math.max(Y,q)}return Y}class nC{}class aC{}class f91{}class h91{}class AX6 extends Q6{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new OX6}}class OX6 extends e0{build(J){return this.widget.onContext(J),this.widget.child}}function vL8(J,Q){if(J==="")return{matches:!0,score:1};let Y=LX6(Q,J);return{matches:Y>0.15,score:Y}}class mq extends Q6{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new wX6}}class wX6 extends e0{controller=new iZ;focusNode;scrollController=new e2;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new n8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),Y9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!xL8(J.props.items,this.widget.props.items)){this.ensureSelectedItemVisible();let Q=this.getFilteredItems();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 nC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof aC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof f91){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 h91)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Y)=>!this.widget.props.filterItem||this.widget.props.filterItem(Y,J)).map((Y)=>({item:Y,...vL8(J,this.widget.props.getLabel(Y))})).filter((Y)=>Y.matches).sort(this.widget.props.sortItems?(Y,X)=>this.widget.props.sortItems(Y,X,J):(Y,X)=>X.score-Y.score).map((Y)=>Y.item);if(this.widget.props.maxRenderItems)return Q.slice(0,this.widget.props.maxRenderItems);return Q}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,X=Q.size.height;v81(J,{top:Y,bottom:X},{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(),Y9.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 X=Y[J],G=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!G){if(X)this.widget.props.onAccept(X)}}};build(J){let Q=B6.of(J),{colors:Y}=Q,X=this.getFilteredItems(),G=g4.all(new w4(Y.foreground,1,"solid")),Z=this.widget.props.enabled??!0,q=new AO({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:Z,style:{textColor:Y.foreground,border:null},maxLines:1}),V=new fq({shortcuts:new Map([[new B4("ArrowDown"),new nC],[new B4("ArrowUp"),new aC],[new B4("Tab"),new nC],[new B4("Tab",{shift:!0}),new aC],[new B4("n",{ctrl:!0}),new nC],[new B4("p",{ctrl:!0}),new aC],[new B4("Enter"),new f91],[new B4("Escape"),new h91]]),focusNode:this.focusNode,child:q}),K=new eQ({actions:new Map([[nC,new X9(this.invoke)],[aC,new X9(this.invoke)],[f91,new X9(this.invoke)],[h91,new X9(this.invoke)]]),child:V}),W=new i6({children:[new J6({decoration:{color:A1.default()},child:new g1({text:new e(">",new q1({color:Y.foreground}))})}),new F4({child:K})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new z0({height:10,child:new F8({child:new g1({text:new e(L,new q1({color:Y.foreground}))})})})}else if(X.length===0&&this.widget.props.emptyStateText)H=new F4({child:new F8({child:new g1({text:new e(this.widget.props.emptyStateText,new q1({color:Y.foreground,dim:!0}))})})});else{let L=X.map((A,E)=>{let P=E===this.selectedIndex,I=this.widget.props.isItemDisabled?.(A)??!1,T;if(this.widget.props.renderItem)T=this.widget.props.renderItem(A,P,I,J);else{let S=P?A1.yellow:void 0,y=P?A1.black:Y.foreground;T=new J6({decoration:S?{color:S}:void 0,padding:j0.symmetric(2,0),child:new g1({text:new e(this.widget.props.getLabel(A),new q1({color:y,dim:I}))})})}return new AX6(new M8({onClick:(S)=>this.handleItemClick(E,S.clickCount),child:T}),(S)=>{this.itemContexts[E]=S})});H=new n0({children:L,crossAxisAlignment:"start"})}let z=new F4({child:new M8({onScroll:this.handleScroll,opaque:!1,child:new u7({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new J6({padding:j0.symmetric(1,0),child:new g1({text:new e(this.widget.props.title,new q1({color:A1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new z0({height:1}),z),this.controller.text!==""){let L=X.length>0?X[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new J6({padding:j0.vertical(1),child:new F8({child:A})}));else U.push(new z0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new J6({decoration:{border:G,color:A1.default()},padding:j0.symmetric(1,0),child:new n0({children:U})})}}class _k1 extends Q6{createState(){return new EX6}}class EX6 extends e0{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 g1({text:new e("●",new q1({color:this.isGreen?A1.green:A1.index(8),bold:!0})),maxLines:1})}}function fL8(J){let Q=new Map,Y=new Map,X=new Map,G=[];for(let q of J)Q.set(q.id,q);for(let q of J){let V=q.parentRelationships.find((K)=>K.role==="child"&&Q.has(K.threadID));if(V){X.set(q.id,V.type);let K=V.threadID,W=Y.get(K)||[];W.push(q),Y.set(K,W)}else G.push(q)}return FG.flatten(G,(q)=>Y.get(q.id)).map((q)=>({...q.item,depth:q.depth,isLast:q.isLast,ancestorsAreLast:q.ancestorsAreLast,relationshipType:X.get(q.item.id)}))}function kk1(J,Q,Y){return new g1({text:new e(`${J}${Q}`,new q1({color:Y})),maxLines:1})}function hL8(J,Q,Y,X){return[kk1("+",J,X.success),n5.horizontal(1),kk1("~",Q,X.warning),n5.horizontal(1),kk1("-",Y,X.destructive)]}class b91 extends O6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((H)=>H.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((H)=>H.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],X=this.props.currentThreadID,G=[...Q].sort((H,z)=>{if(X){if(H.id===X)return-1;if(z.id===X)return 1}let U=Y.indexOf(H.id),N=Y.indexOf(z.id);if(U!==-1&&N!==-1)return U-N;if(U!==-1)return-1;if(N!==-1)return 1;return 0}),Z=fL8(G),q=Math.max(0,...Z.map((H)=>H.description.timeAgo.length)),V=B6.of(J),K=new h6({padding:j0.symmetric(0,1),child:new F8({child:new g1({text:new e("",new q1({color:V.colors.foreground,dim:!0}),[new e("Ctrl+T",new q1({color:A1.blue,dim:!0})),new e(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new q1({color:V.colors.foreground,dim:!0}))])})})});return new mq({items:Z,getLabel:(H)=>H.title,onAccept:(H)=>this.props.onSelect?.(H.id),onDismiss:this.props.onDismiss,onSelectionChange:(H)=>{if(this.props.previewController){if(H)this.props.previewController.select(H.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:1000,footer:this.props.isLoading?void 0:K,renderItem:(H,z,U,N)=>{let M=B6.of(N),{colors:L}=M,A=z?A1.yellow:void 0,E=z?A1.black:L.foreground,P=A1.index(8),I=(J1,n)=>new z0({width:n,child:i6.end([new g1({text:new e(J1,new q1({color:P}))})])}),T=this.props.threadViewStates[H.id],S=[],y=H.relationshipType==="handoff",x=new p81;if(H.depth>0){let J1=[],n=H.ancestorsAreLast.slice(1);for(let H1 of n)J1.push(new e(x.getAncestorPrefix(H1),new q1({color:x.connectorColor,dim:x.connectorDim})));let u=H.isLast?x.elbow:x.tee,s=x.getConnectorText(u);J1.push(new e(s,new q1({color:x.connectorColor,dim:x.connectorDim}))),S.push(new g1({text:new e("",void 0,J1)}))}let g=[],p=this.props.currentThreadID===H.id?new e("(current) ",new q1({color:A1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new e("(visited) ",new q1({color:L.foreground,dim:!0})):null;if(p)g.push(new g1({text:p}));if(T){if(T.state==="active"&&(T.interactionState==="tool-running"||T.interactionState===!1))g.push(new _k1),g.push(new z0({width:1}))}let b=H.title;if(H.relationshipType==="fork"){let J1=b.match(/^Forked\((\d+)\): /);if(J1)b=b.slice(J1[0].length);else while(b.startsWith("Forked: "))b=b.slice(8);g.push(new g1({text:new e("[fork] ",new q1({color:A1.blue}))}))}else if(y)g.push(new g1({text:new e("[handoff] ",new q1({color:A1.index(208)}))}));if(g.push(new F4({child:new g1({text:new e(b,new q1({color:E})),overflow:"ellipsis",maxLines:1})})),g.push(new z0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let J1=z?{success:P,warning:P,destructive:P}:L;g.push(...hL8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,J1)),g.push(new z0({width:2}))}return g.push(I(H.description.timeAgo,q)),new J6({decoration:A?{color:A}:void 0,padding:j0.symmetric(2,0),child:new i6({children:[...S,...g]})})}})}}function IX6(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/60000),G=Math.floor(Y/3600000),Z=Math.floor(Y/86400000);if(X<1)return"just now";if(X<60)return`${X}m ago`;if(G<24)return`${G}h ago`;if(Z<7)return`${Z}d ago`;return J.toLocaleDateString()}class yk1 extends O6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((G,Z)=>Z.pubDate.getTime()-G.pubDate.getTime()),Y=Math.max(0,...Q.map((G)=>IX6(G.pubDate).length));return new mq({items:Q,getLabel:(G)=>G.title,onAccept:(G)=>this.props.onSelect?.(G),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(G,Z,q,V)=>{let K=B6.of(V),{colors:W}=K,H=Z?A1.yellow:void 0,z=Z?A1.black:W.foreground,U=A1.index(8),N=G.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new z0({width:A,child:i6.end([new g1({text:new e(L,new q1({color:U}))})])});return new J6({decoration:H?{color:H}:void 0,padding:j0.symmetric(2,0),child:new i6({children:[new F4({child:new g1({text:new e(G.title,new q1({color:z})),overflow:"ellipsis",maxLines:1})}),new z0({width:2}),new g1({text:new e(N,new q1({color:U})),maxLines:1}),new z0({width:2}),M(IX6(G.pubDate),Y)]})})}})}}class xk1 extends O6{props;constructor(J){super();this.props=J}build(){return new F8({child:new g1({text:new e("",void 0,[new e(`Forked to new thread:
4805
4805
 
4806
4806
  `,new q1({color:A1.white,dim:!0})),new e(`"${this.props.newThreadTitle||"Untitled"}"`,new q1({color:A1.white}))]),textAlign:"center"})})}}class IN extends Q6{props;constructor(J){super();this.props=J}createState(){return new PX6}}class PX6 extends e0{_spinner=new nZ;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=B6.of(J),{colors:Y}=Q,X=g4.all(new w4(Y.foreground,1,"solid")),G=this._spinner.toBraille(),Z=new g1({textAlign:"center",text:new e("",void 0,[new e(G,new q1({color:A1.yellow})),new e(" ",void 0),new e(this.widget.props.message,new q1({color:Y.foreground}))])}),V=[new F4({child:new n0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)V.push(new z0({height:2,child:new J6({padding:j0.symmetric(2,0),child:new g1({text:new e("",new q1({dim:!0}),[new e("Press ",new q1({color:Y.foreground})),new e("Esc",new q1({color:Y.info})),new e(" to cancel",new q1({color:Y.foreground}))])})})}));let K=new J6({decoration:new z8(A1.default(),X),child:new z0({width:60,height:7,child:new n0({mainAxisAlignment:"start",children:V})})});if(this.widget.props.onAbort)return new G9({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:K});return K}}class xz extends Q6{props;constructor(J){super();this.props=J}createState(){return new RX6}}class RX6 extends e0{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof oK}build(J){let Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let W=b81(Q);return{title:W.title,type:W.type,description:W.description}})(),X=Y.type==="error"?A1.red:A1.yellow,G=g4.all(new w4(A1.default(),1,"solid")),Z=new J6({padding:j0.symmetric(1,0),child:new g1({text:new e(Y.title,new q1({color:X,bold:!0}))})}),q=this.isWidgetMessage(Q)?Q.widget:new g1({text:new e(Y.description,new q1({color:A1.default()})),selectable:!0}),V=new F4({child:new DO({child:new J6({padding:j0.symmetric(1,0),child:q})})}),K=new J6({padding:j0.symmetric(1,0),child:new g1({text:this.widget.props.onRetry?new e("",void 0,[new e("Press ",new q1({color:A1.default(),dim:!0})),new e("R",new q1({color:A1.yellow})),new e(" to retry, ",new q1({color:A1.default(),dim:!0})),new e("Esc",new q1({color:A1.yellow})),new e(" to cancel",new q1({color:A1.default(),dim:!0}))]):new e("Press any key to close",new q1({color:A1.default(),dim:!0,italic:!0}))})});return new G9({onKey:(W)=>{if(this.widget.props.onRetry&&W.key==="r")return this.widget.props.onRetry(),"handled";if(W.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!0,child:new J6({decoration:{border:G,color:A1.default()},padding:j0.all(1),child:new n0({mainAxisAlignment:"center",children:[Z,new z0({height:1}),V,K]})})})}}class vk1 extends O6{build(){return new F8({child:new g1({text:new e("",void 0,[new e(`✓ Thread Shared
4807
4807
 
@@ -4885,7 +4885,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
4885
4885
  `)?`${V}...`:G,W=new q1({color:A1.index(8)}),H=[new e(K,W)];if(q>0){let z=new q1({color:Y.success});for(let U=1;U<=q;U++)H.push(new e(" ")),H.push(new e(`[${U}]`,z))}return new h6({padding:j0.only({bottom:0}),child:new i6({crossAxisAlignment:"start",children:[new h6({padding:j0.only({right:1}),child:new g1({text:new e("•",new q1({color:A1.index(8)}))})}),new F4({child:new g1({text:new e("",void 0,H)})})]})})}}class Hy1 extends Q6{createState(){return new wG6}}class wG6 extends e0{_animationTimer;_visible=!0;initState(){super.initState(),this._startAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._visible=!this._visible})},500)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=new q1({color:A1.red}),Y=new q1({color:this._visible?A1.red:A1.transparent()});return new i6({children:[new g1({text:new e("⏺",Y)}),new z0({width:1}),new g1({text:new e("Replay",Q)})]})}}class zy1 extends O6{entry;constructor({key:J,entry:Q}){super({key:J});this.entry=Q}build(J){let Q=B6.of(J),Y=Q.colors.secondary,X=Q.colors.foreground,G=this.entry.authors.map((Z)=>Z.name).join(", ");return new J6({decoration:new z8(void 0,new g4(new w4(Y,1,"rounded"),new w4(Y,1,"rounded"),void 0,new w4(Y,1,"rounded"))),child:new h6({padding:j0.horizontal(1),child:new n0({children:[new i6({crossAxisAlignment:"start",children:[new F4({child:new g1({text:new e(this.entry.title,new q1({color:X,bold:!0}))})}),new z0({width:4}),new g1({text:new e(G||"Community",new q1({color:X,dim:!0}))})]}),new i6({crossAxisAlignment:"start",children:[new F4({child:new g1({text:new e(this.truncateDescription(this.entry.description),new q1({color:X,dim:!0}))})}),new z0({width:2}),new Y7({uri:this.entry.link,text:"View Thread",style:new q1({color:Y,underline:!0})})]})]})})})}truncateDescription(J){let Y=J.replace(/\s+/g," ").trim();if(Y.length<=80)return Y;return Y.slice(0,79)+"…"}}r0();function nA8(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/3600000),G=Math.floor(X/24),Z=Math.floor(G/7),q=Math.floor(G/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;if(Z<=4)return`${Z}w ago`;return`${q}mo ago`}class Fy1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList().subscribe((G)=>{X.unsubscribe(),Y(G)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(q6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((X)=>{if(!Q.trim())return!0;let G=X.title?.toLowerCase()||"untitled",Z=X.id.toLowerCase(),q=Q.toLowerCase();return G.includes(q)||Z.includes(q)}).map((X)=>{let G=new Date(X.userLastInteractedAt),Z=nA8(G),q=X.id.slice(-8),V=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:Z,title:X.title||"Untitled",shortThreadID:q},diffStats:X.summaryStats?.diffStats,workspaceURI:V,parentRelationships:X.parentRelationships}})}}L0();t8();class Uy1{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new e2;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){h.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){h.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(jM()).subscribe((Q)=>{if(this.currentId===J)this.current=Q,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}function EG6(J,Q){switch(J){case"update-available":return[new e("A newer Amp is available. Run ",new q1({color:Q.foreground,dim:!0})),new e("amp update",new q1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new e("Update complete, run ",new q1({color:Q.foreground,dim:!0})),new e("amp update",new q1({color:Q.warning})),new e(" to see warnings",new q1({color:Q.foreground,dim:!0}))];case"update-error":return[new e("Update failed, run ",new q1({color:Q.foreground,dim:!0})),new e("amp update",new q1({color:Q.warning})),new e(" to see warnings",new q1({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function tA8(J){return new Promise((Q)=>{oA8("git",["branch","--show-current"],{cwd:J},(Y,X)=>{if(Y){Q(null);return}let G=X.trim();Q(G||null)})})}class _G6 extends Q6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new kG6}}class kG6 extends e0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;paletteShowOptions=null;threadsForPicker=[];isLoadingThreads=!1;threadPreviewController=new Uy1;previewThread=null;planScrollController=(()=>{let J=new e2;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new e2;return J.followMode=!1,J})();filterThreadPickerByWorkspace=!0;agentModePulseSeq=0;currentGitBranch=null;messageViewFocusNode=new n8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new n8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;threadFeedReader=null;currentThreadFeedEntry=null;threadFeedEntries=[];threadFeedSubscription=null;threadFeedRotationTimer=null;threadFeedHidden=!1;threadFeedTickerQueue=[];hasSubmittedFirstMessage=!1;currentUserInfo=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;previousThreadIdForHint=null;pendingMCPServers=[];mcpTrustSubscription=null;agentModeSubscription=null;currentAgentMode="smart";inMemoryAgentModeOverride=null;cachedVisibleModes=rG();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;toastController=new WS1;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;async initThreadFeed(){let J=await M6(this.widget.dependencies.configService.config);if(J.settings["feed.enabled"]===!1)this.threadFeedHidden=!0;let Q=J.settings.url,Y=Q.includes("localhost")||Q.includes("127.0.0.1");try{let q=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService});if(q.ok){let V=q.result,K="user"in V?V.user:V;this.currentUserInfo={username:K.username??void 0,displayName:K.displayName??void 0};let W="ffe10a0c-6c42-41ce-a3a6-38990fd6caf8";if(!Y&&V.team?.id!==W)return}else return}catch(q){h.debug("Failed to fetch user info for thread feed filtering",q);return}let X="/threads.rss",G=async(q,V)=>{let K=q instanceof Request?q.url:q.toString();return zJ(K,V,this.widget.dependencies.configService)},Z=vl0();Z.get("entries").then((q)=>{if(q){let V=this.filterEntries(q);if(this.threadFeedEntries=V,V.length>0&&!this.currentThreadFeedEntry){let K=[...V].sort((H,z)=>z.pubDate.getTime()-H.pubDate.getTime());this.threadFeedTickerQueue=[...K,...this.threadFeedTickerQueue];let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}),this.threadFeedReader=new Rj1(Z,G,{url:X}),this.threadFeedSubscription=this.threadFeedReader.stream().subscribe({next:(q)=>{try{let V=this.filterEntries(q);if(V.length>0){this.threadFeedEntries=[...V,...this.threadFeedEntries];let K=[...V].sort((W,H)=>H.pubDate.getTime()-W.pubDate.getTime());if(this.threadFeedTickerQueue=[...K,...this.threadFeedTickerQueue],!this.currentThreadFeedEntry){let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}catch(V){h.error("Thread feed: error in next handler",V)}},error:(q)=>{h.error("Thread feed error:",q)}}),this.resetThreadFeedRotation()}filterEntries(J){if(!this.currentUserInfo)return J;let{username:Q,displayName:Y}=this.currentUserInfo;return J.filter((X)=>{return!X.authors.some((G)=>{let Z=G.name;if(!Z)return!1;return Q&&Z===Q||Y&&Z===Y||Q&&Z.includes(Q)})})}rotateThreadFeed(){if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);this.threadFeedRotationTimer=setInterval(()=>{let J=this.getNextFeedEntry();if(J)this.setState(()=>{this.currentThreadFeedEntry=J})},30000)}resetThreadFeedRotation(){this.rotateThreadFeed()}getNextFeedEntry(){if(this.threadFeedTickerQueue.length>0)return this.threadFeedTickerQueue.shift();return null}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.worker.thread.id;this.recordNavigation(J);let Q=await this.widget.dependencies.startNewThread();return this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,this.widget.dependencies.switchWorker(Q),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.previousThreadIdForHint=J}),Q};async startReplay(){let J=this.widget.dependencies.replayMode;if(!J)return;let{thread:Q,typingEnabled:Y,baseWpm:X}=J,G=Q.messages;for(let Z=0;Z<G.length;Z++){if(this.replayAbortController.signal.aborted)break;let q=G[Z];if(!q)continue;if(Z>0)await this.replaySleep(J.messageDelayMs);if(q.role==="user"&&Y){let W=q.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
4886
4886
  `);if(W)await this.replayTypeMessage(W,X)}if(q.role==="assistant"){let W=q.content.some((U)=>U.type==="tool_use"),H=G[Z+1],z=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&z){let U={...q,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let N=J.thread.id;this.getMessageScrollController(N).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),q]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,q],this.textController.clear()});let V=J.thread.id;this.getMessageScrollController(V).scrollToBottom()}await this.replaySleep(J.exitDelayMs),I9.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Y=J.split(/(?<=\s)/),X=60000/Q;for(let G of Y){if(this.replayAbortController.signal.aborted)break;if(this.looksLikePastedContent(G.trim())){await this.replaySleep(150),this.textController.text=this.textController.text+G,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{}),await this.replaySleep(300);continue}let Z=X/G.length;for(let q of G){this.textController.text=this.textController.text+q,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let V=0.8+Math.random()*0.4,K=Z*V;await this.replaySleep(K)}}}looksLikePastedContent(J){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(J))return!0;if(J.startsWith("/")&&J.length>10)return!0;if(/^[a-z]:\\/i.test(J))return!0;if(/^[a-f0-9]{7,40}$/i.test(J))return!0;if(/^T-[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(J))return!0;return!1}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return U81(this.widget.dependencies.worker.thread,this.inMemoryAgentModeOverride?{agentMode:this.inMemoryAgentModeOverride}:null,this.freeTierStatus,{"experimental.agentMode":this.currentAgentMode})}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Y=J.items.filter((Z)=>Z.type==="toolResult").filter((Z)=>Z.toolResult.run.status==="in-progress"||Z.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((Z)=>Z.toolRun.status==="in-progress"||Z.toolRun.status==="queued");return[...Y,...X].length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new e(this.submitDisabledHint,new q1({color:J.foreground,dim:!0}));if(this.isExiting)return new e("Exiting...",new q1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new e("",void 0,[new e("Ctrl+C",new q1({color:Q.keybind})),new e(" again to exit",new q1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new e("",void 0,[new e("Esc",new q1({color:Q.keybind})),new e(" again to clear input",new q1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new e("",void 0,[new e("Escape",new q1({color:Q.keybind})),new e(" to close help",new q1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let G=this.getEffectiveAgentMode(),Z=Ay1(G);return new e("",void 0,[new e("Images aren't supported in ",new q1({color:J.warning,dim:!1})),new e(G,new q1({color:Z})),new e(" mode.",new q1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new e("",void 0,[new e("Esc",new q1({color:Q.keybind})),new e(" again to cancel",new q1({color:J.foreground,dim:!0}))]);return new e("",void 0,[new e("Esc",new q1({color:Q.keybind})),new e(" to cancel",new q1({color:J.foreground,dim:!0}))])}if(this.showingCannotToggleMessage)return new e(this.showingCannotToggleMessage,new q1({color:J.warning,dim:!1}));let Y=EG6(this.updateState,J);if(Y)return new e("",void 0,Y);let X=this.widget.dependencies.worker.thread;if(X.agentMode==="plan"&&WO(X))return new e("",void 0,[new e("Ctrl+O",new q1({color:Q.keybind})),new e(" → Execute Plan",new q1({color:J.foreground,dim:!0}))]);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Y}=this.widget.dependencies;if(!Q.mainThread?.id)return;let G=Q.mainThread?.messages.findIndex((Z)=>Z===J);if(G===void 0||G===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),await Y.handle({type:"thread:truncate",fromIndex:G}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(Z){h.error("Failed to edit message:",Z)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Y,threadSyncService:X}=this.widget.dependencies,G=Q.mainThread?.id;if(!G)return;let Z=Q.mainThread?.messages.findIndex((q)=>q===J);if(Z===void 0||Z<=0)return;try{let q=await E3.getOrCreateForThread(Y,G),V=await wT(q,X,Z-1);await this.switchToExistingThread(V)}catch(q){h.error("Failed to fork thread:",q),this.showErrorMessage(`Failed to fork thread: ${q}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Y,worker:X}=this.widget.dependencies,G=Y.mainThread;if(!G)return;let Z=G.messages.findIndex((q)=>q.messageId!==void 0&&q.messageId===J.messageId);if(Z===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let q=NN(Q);if(q)await X.handle({type:"thread:truncate",fromIndex:Z}),this.invokeBashCommand(q.cmd,{visibility:q.visibility});else{let V=[{type:"text",text:Q}];if(this.imageAttachments.length>0)V.push(...this.imageAttachments);let K={content:V,agentMode:G.agentMode},W=Z===0;if(G.agentMode&&!W&&K.agentMode!==G.agentMode){h.error(`Cannot edit message: This thread uses ${G.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:K,index:Z})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(q){h.error("Failed to edit message:",q)}};getAffectedFiles=async(J)=>{let{worker:Q}=this.widget.dependencies;try{return(await Q.getFilesAffectedByTruncation(J)).map(ZJ)}catch(Y){return h.error("Failed to get affected files:",Y),[]}};textController=new iZ;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new e2);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let G=this.searchElementTreeByKey(X,Q);if(G)return G}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{this.toastController.show("Selection copied to clipboard","success",2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Y=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Y}`:"";process.stdout.write(mC1(X))}}_handleTextCopy(J){if(J&&J.length>0)this.toastController.show("Selection copied to clipboard","success",2000)}textFieldKey=new t7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Y=NN(J)?.visibility;if(Y!==this.currentShellModeStatus)this.currentShellModeStatus=Y,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),Y9.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Q)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.showCommandPalette({type:"standalone",commandId:"continue",onSubmit:()=>{this.threadPreviewController.clear(),this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null}),Y9.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};showCommandPalette(J){if(this.setState(()=>{this.isShowingPalette=!this.isShowingPalette,this.paletteShowOptions=J??null}),this.isShowingPalette)this.loadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new hk1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.widget.dependencies.isDogfooding,this.paletteConfig)}return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new mk1(this.widget.dependencies.fuzzyServer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})};getCommandPaletteContext=(J)=>{let{threadState:Q,recentThreadIDs:Y}=this.widget.dependencies;if(!Q.mainThread)return null;let X=d0.file(process.cwd()),G=j6(X);return{recentThreadIDs:Y,currentThreadID:Q.mainThread.id,context:J,worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let Z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),Z},setImageAttachments:(Z)=>{this.setState(()=>{this.imageAttachments=Z})},editorDispatch:(Z)=>{switch(Z.type){case"set-input":this.textController.clear(),this.textController.insertText(Z.input);break;case"insert-text":this.textController.insertText(Z.text);break;case"clear":this.textController.clear();break}},submitMessage:(Z)=>{return this.proceedWithUserMessage(Z)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,mcpService:this.widget.dependencies.mcpService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus?.canUseAmpFree??!1,switchToThread:async(Z)=>{return await this.switchToExistingThread(Z),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(Z,q,V)=>{let K=this.widget.dependencies.threadState.mainThread?.id;if(!K)throw Error("No active thread");let W=setTimeout(()=>{V.throwIfAborted()},60000);try{let H=await this.widget.dependencies.threadService.generateHandoffPrompt(K,Z,q,this.widget.dependencies.configService,V);return clearTimeout(W),H}catch(H){throw clearTimeout(W),H}},handleHandoff:async(Z,q)=>{let{goal:V,generatedPrompt:K,images:W}=q;if(!V&&!K)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let H=this.widget.dependencies.threadState.mainThread?.id;if(!H)return{ok:!1,error:Error("No active thread")};let z=setTimeout(()=>Z.abort(new _91("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let U=await this.widget.dependencies.threadService.createHandoffThread(H,{goal:V,generatedPrompt:K,images:W},this.widget.dependencies.configService,Z.signal);return clearTimeout(z),await this.switchToExistingThread(U),{ok:!0}}catch(U){if(clearTimeout(z),U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")))throw Z.signal.reason;throw U}}catch(H){return h.error("Failed to create handoff thread",H),{ok:!1,error:H instanceof Error?H:Error(String(H))}}},getGuidanceFiles:async(Z)=>{if(!Q.mainThread)return[];return(await Ys({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,Z)).map((V)=>({uri:V.uri,type:V.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(Z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=Z})},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,handleExecutePlan:async()=>{try{let Z=Q.mainThread?.id;if(!Z){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let q=await this.widget.dependencies.threadService.createPlanExecutionThread(Z,"smart");await this.switchToExistingThread(q)}catch(Z){h.error("Failed to execute plan",Z),this.setState(()=>{this.displayMessage=Error(`Failed to execute plan: ${Z instanceof Error?Z.message:String(Z)}`)})}},planFileManager:this.widget.dependencies.planFileManager,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:G,threadViewStates:this.widget.dependencies.workerController.threadViewStates,currentThreadFeedEntry:this.currentThreadFeedEntry,threadFeedEntries:this.threadFeedEntries,threadFeedHidden:this.threadFeedHidden,setThreadFeedHidden:(Z)=>{this.setState(()=>{this.threadFeedHidden=Z})}}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new Fy1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await tA8(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{visibility:Q})=>{let Y=Date.now(),X=`bash-${Y}-${Math.random().toString(36).substring(7)}`,G={cmd:J},Z=new AbortController;this.widget.dependencies.worker.invokeBashTool(G,Z.signal,Q===BN).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((K)=>K.id===X))this.bashInvocations=this.bashInvocations.map((K)=>K.id===X?{...K,toolRun:q}:K);else{let K={id:X,args:G,toolRun:q,startTime:Y,abortController:Z,hidden:Q===BN};this.bashInvocations=[...this.bashInvocations,K]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};toggleAgentMode=()=>{let J=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(c$(J.thread)>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.getEffectiveAgentMode(),G=ji(X,this.cachedVisibleModes);if(G!==X)this.setState(()=>{this.inMemoryAgentModeOverride=G,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.getEffectiveAgentMode(),Y=ji(Q,this.cachedVisibleModes);if(Y===Q)return;if(this.setState(()=>{this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),$5(Y))this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus){if(!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(!this.freeTierStatus.workspaceAllowsAmpFree){this.setState(()=>{this.showingCannotToggleMessage="Your workspace does not allow Amp Free. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!uk(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=MU)return!1;let Y=jC(J);if(typeof Y==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Y}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Y,unlink:X,rmdir:G,writeFile:Z}=await import("node:fs/promises"),{tmpdir:q}=await import("node:os"),V=await import("node:path");try{let K=await Q(V.join(q(),"amp-edit-")),W=V.join(K,"message.amp.md");await Z(W,J,"utf-8"),await Pz(W);try{let H=await Y(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")h.error("Failed to read temporary file",H)}try{await X(W),await G(K)}catch(H){h.warn("Failed to clean up temporary file",H)}}catch(K){h.error("Error opening editor:",K)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=NN(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};initState(){if($G.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();I9.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),I9.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),I9.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Y)=>{Y9.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus,M6(this.widget.dependencies.configService.config).then((Y)=>{this.paletteConfig=Y;let X=U81(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,Y.settings);if(h.info(`[initState] Resolved agentMode: ${X}`),this.widget.dependencies.sessionState?.agentMode)this.setState(()=>{this.inMemoryAgentModeOverride=X})}),this.updateGitBranch(),this.adSubscription=$j1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride&&$5(this.inMemoryAgentModeOverride)||this.randomAd===null)&&Zj1(this.lastUserInteractionTime)}).subscribe({next:(Y)=>{if(Y){let X=rA8(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (X51(),Y51)).then(({recordAdEvent:G})=>{let Z=this.widget.dependencies.worker.thread,q=Z.messages[Z.messages.length-1];G("viewed",{adId:Y.id,advertiserId:Y.advertiserId,threadId:Z.id,messageId:q?.messageId,impressionId:X,placement:"tui",matchType:Y.metadata?.matchType,matchedPatterns:Y.metadata?.matchedPatterns,candidateAdPoolCount:Y.metadata?.candidateAdPoolCount,clientRegion:Y.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=Y}),Y9.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}});let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Y)=>{this.setState(()=>{this.pendingMCPServers=Y})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Y)=>{this.setState(()=>{this.ideStatus=Y})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Y)=>{let X=this.widget.dependencies.getCurrentWorker();if(!X){h.warn("No active thread worker found to handle IDE message");return}await new Promise((G)=>setTimeout(G,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}}),h.debug("Message sent from IDE to agent",{message:Y.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Y)=>{this.textController.insertText(Y),h.debug("Appended text to CLI prompt from IDE",{text:Y.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Y)=>{this.setState(()=>{this.connectedClientsStatus=Y})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Y)=>{this.setState(()=>{this.updateState=Y})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Y)=>{let X=rG(Y.settings,this.freeTierStatus?.canUseAmpFree);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Y)=>{let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initThreadFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.threadFeedSubscription)this.threadFeedSubscription.unsubscribe();if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);if(this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(mC1("")),this.shouldUseProgressBar())process.stdout.write(D76())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((V)=>V.type==="toolResult").map((V)=>({toolUse:V.toolUse,toolRun:V.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((V)=>V.toolRun.status==="blocked-on-user");if(X.length===0)return null;let G=X[0],Z=G.toolRun.status==="blocked-on-user"?G.toolRun.toAllow??[]:[],q=G.toolRun.status==="blocked-on-user"?G.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:G.toolUse,toAllow:Z}],subthreadID:G.subthreadID,reason:q}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){h.error("No current tool confirmation found");return}let Y=Q.tools[0]?.useBlock;if(!Y){h.error("No tool use block found in confirmation");return}if(J==="allow-all-session")x$("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(G){if(G&&G instanceof Error)this.setState(()=>{this.displayMessage=G});else h.error("Failed to write dangerouslyAllowAll setting:",G);return}if(J==="always-guarded"){let G=Q.tools[0]?.toAllow??[],Z=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...G,...Z];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q,"global")}if(J==="connect-github"){let G=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await sY(this.context,G);return}if(J==="disable-librarian"){let G=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!G.includes(EX))await this.widget.dependencies.settingsStorage.set("tools.disable",[...G,EX],"global")}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let G={type:"user:tool-input",toolUse:Y.id,value:{accepted:X}};if(Q.subthreadID)await(await E3.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(G);else await this.widget.dependencies.worker.handle(G)}catch(G){h.error("Failed to send tool confirmation:",G)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Y=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Y)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Y=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Y.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null}),await this.startAndSwitchToNewThread();break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),O41({agentMode:"smart"}),await this.startAndSwitchToNewThread();break}case"handoff":{if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);this.showCommandPalette({type:"normal",commandId:"handoff"});break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Q}=this.widget.dependencies;await J.deny();try{await Pz(Q.getSettingsFilePath())}catch(Y){let X=Y instanceof Error?Y.message:String(Y);await this.showErrorMessage(`Failed to open settings: ${X}`)}};cancelStreamingMessage=async()=>{await E3.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Y=J.messages[Q];if(Y?.role==="user"&&!Y.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J,Q={})=>{let{recordInNavigationHistory:Y=!0}=Q;if(Y){let X=this.widget.dependencies.worker.thread.id;if(X!==J)this.recordNavigation(X)}try{h.info(`[switchToExistingThread] Switching to thread: ${J}`);let X=await this.widget.dependencies.switchToThread(J);h.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${X.thread.agentMode}`);let G=await this.widget.dependencies.configService.getLatest(),Z=U81(X.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,G.settings);if(h.info(`[switchToExistingThread] Thread ${J} resolved agentMode: ${Z}`),this.widget.dependencies.worker=X,this.widget.dependencies.threadID=X.thread.id,this.widget.dependencies.switchWorker(X),this.setState(()=>{h.info("[switchToExistingThread] Clearing inMemoryAgentModeOverride"),this.inMemoryAgentModeOverride=null}),X.thread.draft)if(h.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof X.thread.draft==="string")this.textController.insertText(X.thread.draft);else{let q=X.thread.draft.filter((W)=>W.type==="text"),V=X.thread.draft.filter((W)=>W.type==="image"),K=q.map((W)=>W.text).join(`
4887
4887
  `);if(K)this.textController.insertText(K);if(V.length>0)this.setState(()=>{this.imageAttachments=V})}}catch(X){throw h.error("Failed to switch to thread:",J,X),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,Y=c$(Q.thread)===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Y&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let G=[{type:"text",text:J}];if(this.imageAttachments.length>0)G.push(...this.imageAttachments);if(await Q.handle({type:"user:message",message:{content:G,agentMode:X}}),Y)O41({agentMode:X});this.scrollMessageViewToBottom(),this.setState(()=>{if(this.imageAttachments=[],!this.hasSubmittedFirstMessage)this.hasSubmittedFirstMessage=!0}),Y9.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((X)=>X.type==="handoff"&&X.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();O41({agentMode:Q}).catch((Y)=>{h.warn("Failed to save session state on exit:",Y)}).finally(()=>{I9.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=sA8();if(J===Q)return"~";if(J.startsWith(Q+Qu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Qu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Qu.sep),"…",Q.slice(-2).join(Qu.sep)].join(Qu.sep)}build(J){let Q=H8.of(J),Y=B6.of(J),X=Y.base;this.themeColors=X;let{colors:G,app:Z}=Y;this.themeApp=Z;let q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,V=q.thread.agentMode&&$5(q.thread.agentMode),K=V&&this.randomAd!==null,W=!V&&this.currentThreadFeedEntry!==null&&!this.threadFeedHidden&&this.hasSubmittedFirstMessage,H=K||W,{threadState:z}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),N=this.widget.dependencies.replayMode,M=Boolean(N),L=z.items,A=z.mainThread||void 0,E=z.subagentToolsByParentID,P=z.todosList;if(M){let J4={...N.thread,messages:this.replayDisplayedMessages};L=lC(J4).items,A=J4,E={};let o4=BI({messages:this.replayDisplayedMessages});P=Array.isArray(o4)?o4:[]}let I=A?.id,T=A,S=M?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),y=(J4)=>new C91({key:new t7(`preview-message-view-${J4.id}`),items:lC(J4).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:J4,focusNode:new n8({debugLabel:"PreviewFocus"})}),x=this.previewThread,g=x?x.messages.length>2000?new n0({mainAxisSize:"max",children:[new F4({child:new z0}),new h6({padding:j0.all(2),child:new F8({child:new g1({text:new e("Thread too long for preview",new q1({color:G.mutedForeground,dim:!0}))})})})]}):y(x):S?new S91({agentMode:this.getEffectiveAgentMode()}):new C91({key:I?new t7(`message-view-${I}`):void 0,items:L,subagentToolsByParentID:E,controller:I?this.getMessageScrollController(I):new e2,autofocus:!1,onCopy:M?void 0:this._handleTextCopy.bind(this),thread:T,onMessageEditSubmit:M?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:M?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:M?void 0:this.forkMessage,getAffectedFiles:M?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),p=Math.max(Math.floor(Q.size.height*0.4),12),b=this.getCurrentEphemeralError(),l=this.buildBottomWidget(b,U,G,Y,z,P,p,H,M),J1=Q.size.width<40,n=z.mainThread?oB0(z.mainThread):void 0,u=new c81({threadViewState:z.viewState,threadTokenUsage:n,threadID:I??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:J1,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),s=new d81({bashInvocations:this.bashInvocations}),H1=[],W1=this.getEffectiveAgentMode(),o=this.currentShellModeStatus,r=Ay1(W1),i=!o?W1.length+1:0,F1=Q.capabilities.animationSupport,y1=F1==="disabled"?0:F1==="slow"?30:60,t=mV(W1)?.uiHints?.fasterAnimation?3:1,f1=y1>0&&this.agentModePulseSeq>0?new H5({children:[l,new C7({top:0,left:1,right:1,height:1,child:new Vy1({color:r,trigger:this.agentModePulseSeq,fps:y1,speed:t,leftOffset:i})})]}):l;H1.push(new F4({child:g}),s);let C1=new H5({children:[new n0({mainAxisSize:"min",children:[K?new Pk1({ad:this.randomAd,onButtonClick:async()=>{let J4=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (X51(),Y51)).then(({recordAdEvent:Z8})=>{let f4=this.widget.dependencies.worker.thread,M4=f4.messages[f4.messages.length-1];Z8("clicked",{adId:J4.id,advertiserId:J4.advertiserId,threadId:f4.id,messageId:M4?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:J4.metadata?.matchType,matchedPatterns:J4.metadata?.matchedPatterns,candidateAdPoolCount:J4.metadata?.candidateAdPoolCount,clientRegion:J4.metadata?.clientRegion})});if(!await sY(this.context,J4.shortDestinationUrl)){let f4=I9.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:f4,url:J4.shortDestinationUrl}})}}}):W?new zy1({entry:this.currentThreadFeedEntry}):new z0({height:0}),new J6({constraints:new c6(0,Q.size.width,0,p),child:f1})]}),H?new C7({top:0,left:0,right:0,child:new vG6({userHeight:this.bottomGridUserHeight,maxHeight:p,onInitializeHeight:(J4)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(J4,p)})},onDrag:(J4)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(J4.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let o4=Math.floor(J4.localPosition.y)-this.bottomGridDragStartY,Z8=Math.max(4,this.bottomGridDragStartHeight-o4),f4=Math.min(Z8,p),M4=Math.floor(f4);if(this.bottomGridUserHeight!==M4)this.setState(()=>{this.bottomGridUserHeight=M4})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new z0({height:0})]});H1.push(C1,new z0({height:1,child:new h6({padding:j0.horizontal(1),child:u})}));let w0=new n0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:H1}),s1=M&&N?.showIndicator!==!1?new H5({children:[w0,new C7({top:0,left:0,child:new Hy1})]}):w0,U1=new X9(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((o4)=>{h.error("Failed to mark message as interrupted:",o4)}),this.cancelStreamingMessage().catch((o4)=>{h.error("Failed to cancel streaming message:",o4)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return h.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),Y1=new X9(()=>{return this.onExitPressed(),"handled"}),O1=new X9(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),w1=new X9(()=>{return TJ.instance.toggleAll(),"handled"}),I1=new X9(()=>{return this.widget.dependencies.configService.getLatest().then((J4)=>{x$("internal.showCost",!(J4.settings["internal.showCost"]??!0))}),"handled"}),E1=new X9(()=>{return I9.instance.toggleFrameStatsOverlay(),"handled"}),d1=new X9(()=>{return I9.instance.tuiInstance.getScreen().markForRefresh(),Y9.instance.requestFrame(),"handled"}),h1=new X9(()=>{return this.toggleAgentMode(),"handled"}),r1=new X9(()=>{let o4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:Z8}=this.widget.dependencies,f4=Z8.mainThread?.id;return f4?this.getMessageScrollController(f4):null})();if(o4){let Z8=Math.max(Math.floor(Q.size.height*0.4),10),f4=Q.size.height-Z8;o4.animatePageUp(f4,100)}return"handled"}),$0=new X9(()=>{let o4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:Z8}=this.widget.dependencies,f4=Z8.mainThread?.id;return f4?this.getMessageScrollController(f4):null})();if(o4){let Z8=Math.max(Math.floor(Q.size.height*0.4),10),f4=Q.size.height-Z8;o4.animatePageDown(f4,100)}return"handled"}),G0=new X9(()=>{let o4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:Z8}=this.widget.dependencies,f4=Z8.mainThread?.id;return f4?this.getMessageScrollController(f4):null})();if(o4)o4.animateTo(0,100);return"handled"}),T0=new X9(()=>{let o4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:Z8}=this.widget.dependencies,f4=Z8.mainThread?.id;return f4?this.getMessageScrollController(f4):null})();if(o4)o4.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),F6=new X9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:J4}=this.widget.dependencies;if(!J4.mainThread?.messages.some((Z8)=>Z8.role==="user"||UI(Z8)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),L6=new X9((J4)=>{if(J4.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),E4=new X9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return h81().then(async(J4)=>{if(J4)try{this.handleInsertImage(J4)}finally{try{let{unlink:o4}=await import("node:fs/promises");await o4(J4)}catch{}}}),"handled"}),m4=new Map([[B4.ctrl("c"),new jm],[B4.ctrl("l"),new xm],[B4.ctrl("o"),new y81],[B4.ctrl("v"),new Tm],[B4.alt("s"),new kC],[B4.ctrl("s"),new kC],[B4.alt("p"),new ym],[B4.ctrl("r"),new _m],[B4.alt("d"),new km],[B4.ctrl("t"),new vm],[B4.key("PageUp"),new j81],[B4.key("PageDown"),new S81],[B4.key("Home"),new _81],[B4.key("End"),new k81],[B4.key("Escape"),new Cm],[B4.ctrl("p"),new yC("previous")],[B4.ctrl("n"),new yC("next")],[B4.key("Tab"),new fm]]);if(!t2())m4.set(B4.key("ArrowUp"),new fm);if(!1)m4.set(B4.alt("c"),new Sm);let I0=new X9(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),u0=new X9(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),r6=new Map([[Cm,U1],[xm,d1],[kC,h1],[y81,I0],[Tm,E4],[Sm,O1],[_m,w1],[km,I1],[ym,E1],[vm,u0],[jm,Y1],[j81,r1],[S81,$0],[_81,G0],[k81,T0],[fm,F6],[yC,L6]]),R4=[s1];if(this.isShowingConsoleOverlay)R4.push(new dk1);if(this.isShowingHelp&&this.paletteConfig)R4.push(new ik1({commands:this.getPaletteCommands().getAllCommands()}));if(this.adActionModal)R4.push(new Rk1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(J4)=>{let o4=this.adActionModal.url;if(J4==="copy")try{await I9.instance.tuiInstance.clipboard.writeText(o4),this.setState(()=>{this.displayMessage=new zG("Link copied to clipboard")})}catch(Z8){h.error("Failed to copy to clipboard",{error:Z8}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:J4}=this.widget.dependencies;R4.push(new Ky1({servers:this.pendingMCPServers,onAlwaysTrust:J4.trustAlways.bind(J4),onTrustOnce:J4.trustOnce.bind(J4),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:J4.deny.bind(J4)}))}if(this.isShowingFileChangesOverlay)R4.push(new PS1({threadData:z}));if(this.isShowingCostBreakdownOverlay&&z.mainThread)R4.push(new ck1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)R4.push(new uk1({details:this.confirmationOverlayContent}));let j8=this.getCommandPaletteContext(J);if(j8&&this.isShowingPalette&&this.paletteConfig)R4.push(new F8({child:new J6({constraints:c6.loose(80,20),child:new gk1({commandContext:j8,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})})}));if(this.isShowingIdePicker)R4.push(new ak1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let L5=new H5({children:R4});if(this.isShowingJetBrainsInstaller)return new LO({child:new eQ({actions:r6,child:new fq({shortcuts:m4,debugLabel:"jetbrains-installer-shortcuts",child:new qy1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new Cz({controller:this.toastController,child:new LO({child:new HS1({controller:this.toastController,child:new eQ({actions:r6,child:new fq({shortcuts:m4,debugLabel:"main-app-shortcuts",child:L5})})})})})}buildScrollableTodoList(J,Q,Y){return new yG6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Y})}buildBottomWidget(J,Q,Y,X,G,Z,q,V,K){if(J)return new lk1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new pk1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new Wy1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let W=u81(X),H=this.isInRestrictedFreeMode(),z=new yO({key:this.textFieldKey,controller:this.textController,triggers:K?[]:[new EN],completionBuilder:K?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:K?void 0:this.onTextSubmitted,theme:Y,placeholder:K?"Press Ctrl+C to exit":H?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!H&&!this.isShowingStandalonePalette(),shellPromptRules:W,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker,clipboard:I9.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,previousThreadId:this.previousThreadIdForHint&&(G.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let p=this.previousThreadIdForHint;if(p)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${p} `},onDoubleAtTrigger:K?void 0:()=>{let p=this.textController.text,b=this.textController.cursorPosition,J1=p.slice(0,b).lastIndexOf("@@");this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:()=>{if(J1!==-1){let n=this.textController.text,u=n.slice(0,J1)+n.slice(J1+2);this.textController.text=u,this.textController.cursorPosition=J1}},onSubmit:()=>{this.dismissPalette()},onCancel:()=>{this.dismissPalette()}})}}),U=G.mainThread?.queuedMessages??[],N=Array.isArray(Z)&&Z.length>0,M=Array.isArray(U)&&U.length>0,L=G.mainThread?.agentMode==="plan"&&WO(G.mainThread),A,E;if(L){if(A=new rj1(new j91({thread:G.mainThread,onExecute:async()=>{let p=this.getCommandPaletteContext();if(p)await this.getPaletteCommands().execute("execute-plan",p,void 0,new AbortController)},onEdit:async()=>{try{let p=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:b}=await this.widget.dependencies.planFileManager.ensureSync(G.mainThread.id);I9.instance.tuiInstance.suspend();let{execSync:l}=await import("child_process");l(`${p} "${b}"`,{stdio:"inherit"}),I9.instance.tuiInstance.resume()}catch(p){h.error("Failed to edit plan",p),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:X}),{clipBehavior:"antiAlias"}),M)E=new Q51({queuedMessages:U});else if(N)E=this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!H,X)}else A=M?new Q51({queuedMessages:U}):void 0,E=N?this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!H,X):void 0;let P=[],I=this.currentShellModeStatus;if(I)P.push({child:new g1({text:new e(I==="hidden"?"shell mode (incognito)":"shell mode",new q1({color:I==="hidden"?X.app.shellModeHidden:X.app.shellMode}))}),position:"top-left"});if(!I&&this.cachedVisibleModes.length>1){let p=this.previewThread,b=p?p.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),l=Ay1(b);if(p)P.push({child:new g1({text:new e(b,new q1({color:l}))}),position:"top-left"});else{let J1=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,n=c$(J1.thread)===0,u=new g1({text:new e(b,new q1({color:l}))});P.push({child:n?new M8({child:u,onClick:this.toggleAgentMode,cursor:"pointer"}):u,position:"top-left"})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let p=this.connectedClientsStatus,b=p.mode||"disconnected",l=!!p.errorMessage,J1=p.clientID||"unknown",n,u;if(l)n="●",u=A1.red;else if(b==="presence")n="○",u=A1.yellow;else if(b==="connected"&&p.connected)n="●",u=A1.green;else n="○",u=A1.yellow;let s=this.connectedClientsStatusExpanded?`${J1} ${n}`:n;P.push({child:new M8({child:new g1({text:new e(s,new q1({color:u}))}),onClick:this.toggleConnectedClientsStatus,cursor:"pointer"}),position:"top-right",offsetX:-2})}let T=K?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:G.mainThread?.env?.initial.trees?.[0]?.uri,S;if(T)S=d0.parse(T).fsPath;else S=process.cwd();let y=this.toHomeRelative(S),x=this.shorten(y),g=!K&&this.currentGitBranch?`${x} (${this.currentGitBranch})`:x;return P.push({child:new g1({text:new e(g,new q1({color:Y.foreground,dim:!0}))}),position:"bottom-right"}),new NS1({leftChild:new F4({child:z}),rightChild1:A,rightChild2:E,maxHeight:q,overlayTexts:P,borderColor:H||!this.isTextfieldAndAutocompleteFocused?A1.index(8):void 0,hasBanner:V,userHeight:this.bottomGridUserHeight,onInitializeHeight:(p)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(p,q)})},onDrag:(p)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(p.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let b=Math.floor(p.localPosition.y)-this.bottomGridDragStartY,l=Math.max(4,this.bottomGridDragStartHeight-b),J1=Math.min(l,q),n=Math.floor(J1);if(this.bottomGridUserHeight!==n)this.setState(()=>{this.bottomGridUserHeight=n})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!V})}}async function Oy1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)I9.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let X=()=>null,Z=!1,q=new Lz(Z,1000,J.inspectorPort),V=J.features?.find((A)=>A.name==="amp-connect")?.enabled??!1,K=new Ek1({threadService:J.threadService,worker:J.worker,builder:(A,E,P,I,T,S)=>{if(X=T,J.threadDependencies&&V)Sj1(J.threadDependencies,J.configService,T,I,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((g)=>{h.error("Failed to start automatic presence:",g)});let y=T(),x={...J,worker:y,threadID:y.thread.id};return new _G6({...x,threadState:E,workerController:P,switchWorker:I,getCurrentWorker:T,recentThreadIDs:S})}}),W=new OS1({configService:J.configService,child:K}),H=new MS1({configService:J.configService,child:W}),z=new XS1(H),U=new B6({data:xC.fromBaseTheme(lZ.default()),child:z});try{await Qj1(U,{onRootElementMounted:(A)=>{if(h.info("TUI input ready for user interaction"),Z)q.start(A)}})}finally{if(Z)q.stop();if(J.threadDependencies&&V){let{stopGlobalSession:A}=await Promise.resolve().then(() => (_j1(),N36));A()}}let M=X()?.thread.id||J.threadID,L=await J.threadService.get(M);if(L&&L.messages.length>0){let A=`${J.ampURL.replace(/\/$/,"")}/threads/${M}`;h36(L,A,J.stdout)}}function Ay1(J){let Y=mV(J)?.uiHints?.secondaryColor;if(Y)return A1.rgb(Y.r,Y.g,Y.b);return eA8(J)}class yG6 extends Q6{props;constructor(J){super();this.props=J}createState(){return new xG6}}class xG6 extends e0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,controller:Y,appTheme:X}=this.widget.props;return new i6({crossAxisAlignment:"stretch",children:[new F4({child:new u7({controller:Y,autofocus:!1,child:new Ik1({todos:Q})})}),new QY({controller:Y,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:G,offset:Z}=Y,q=this.viewportHeight,V=G+q;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(q,1),scrollOffset:Math.max(Z,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(X,G=0)=>{if(X&&"size"in X&&"children"in X){let Z=X.children||[];for(let q of Z){if(q&&"size"in q){let K=q.size;if(typeof K?.height==="number"&&K.height>0)return K.height}let V=Q(q,G+1);if(V>0)return V}}return 0},Y=Q(J);if(Y>0)return Y;if("size"in J){let X=J.size;if(typeof X?.height==="number"&&X.height>0)return X.height}return this.viewportHeight}}class vG6 extends O6{props;constructor(J){super();this.props=J}build(J){return new M8({child:new z0({height:1}),cursor:i9.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let X=J.findRenderObject()?.size.height??0;if(X>0){this.props.onInitializeHeight(X);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function eA8(J){let Q=0;for(let G=0;G<J.length;G++){let Z=J.charCodeAt(G);Q=(Q<<5)-Q+Z,Q=Q&Q}let Y=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Y.length;return A1.index(Y[X])}Jj1();try{if(process.platform==="win32")await Promise.resolve().then(() => N6(Fj(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){Y$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
4888
- `)}var rx1=ox1.join(RF0||ox1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function AP8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),q=Y||"Warning",V=!1;J.warn(Z,{name:q,code:X})}}function cq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")x$("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")x$("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")x$("model.sonnet",Q.useSonnet)}async function tx1(J){try{await DP8(ox1.dirname(rx1),{recursive:!0}),await MP8(rx1,J,"utf-8")}catch(Q){h.debug("Failed to save last thread ID",Q)}}async function OP8(){try{return(await qV6(rx1,"utf-8")).trim()}catch(J){return null}}var GV6=[{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(h).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${ZC1})`},{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:t2(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:VI.SMART.key,description:`Set the agent mode (${rG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:rG().map((J)=>J.mode)}],ZV6=(J)=>("deprecated"in J)&&J.deprecated===!0,wP8=(J)=>("hidden"in J)&&J.hidden===!0,EP8=(J)=>("default"in J),IP8=(J)=>("default"in J)?J.default:void 0;function PP8(J,Q){let Y=Q.args[0],X=Q.commands.map((Z)=>Z.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let Z=X.filter((V)=>Y.includes(V)||V.includes(Y)),q="Run amp --help for a list of available commands.";if(Z.length>0)q=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new _8(bZ.unknownCommand(Y),1,q)}}var VV6=null;function TA5(){return VV6}function Iu(J){return{...J,getThreadEnvironment:r61,vfs:rI0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new ux(J.fileSystem),generateThreadTitle:pl0,deleteThread:(Q)=>J.threadService.delete(Q)}}var ex1=d0.file(LP8.homedir()),KV6=process.env.XDG_CONFIG_HOME?d0.file(process.env.XDG_CONFIG_HOME):o0.joinPath(ex1,".config");async function lq(J,Q){$N0("0.0.1764583899-g57f324");let Y=qq1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:X0.of([d0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:ex1,userConfigDir:KV6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (X51(),Y51));X(Y);let G=await Y.getLatest();h.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let{toolService:Z,dispose:q}=q16({configService:Y}),V=new Map,K=()=>V.clear(),W=new KU1(Y,J.settings.getWorkspaceRootPath()),H=XI0({configService:Y,trustStore:W,createOAuthProvider:async(n)=>{let u=V.get(n);if(u)return h.debug("Reusing existing OAuth provider for server",{serverName:n}),u;h.debug("Creating OAuth provider for server",{serverName:n});let s=(async()=>{let H1=new nM(J.secrets),W1=await H1.getClientInfo(n),o=new _F1({storage:H1,serverName:n,clientId:W1?.clientId,clientSecret:W1?.clientSecret,scopes:W1?.scopes});return h.debug("OAuth provider created",{serverName:n,hasManualClientId:!!W1?.clientId,willUseDCR:!W1?.clientId}),o})();return V.set(n,s),s}}),z=o01({configService:Y,filesystem:D5,spawn:bA}),{initializeToolProviders:U}=await Promise.resolve().then(() => (XV6(),YV6)),{registrations:N,initErrors:M}=await U({toolService:Z,providers:[H,z],initialTimeout:J.executeMode?15000:5000});for(let[n,u]of M)h.warn(`${n} provider initialization slow or failed:`,u);if(Q.jetbrains)DI("JetBrains");else if(Q.ide&&H56())DI("VS Code");else if(Q.ide&&z56())DI("Neovim");if(J.executeMode)qN0(!0);let L,A=M2.status.pipe(q6((n)=>Boolean(n.connected&&n.authenticated)),_4()).subscribe((n)=>{if(n){if(!L)L=Z.registerTool(is0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode)E=new q41(process.cwd(),{},!0);else E=new class extends q41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(h5.write(`No API key found. Starting login flow...
4888
+ `)}var rx1=ox1.join(RF0||ox1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function AP8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),q=Y||"Warning",V=!1;J.warn(Z,{name:q,code:X})}}function cq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")x$("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")x$("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")x$("model.sonnet",Q.useSonnet)}async function tx1(J){try{await DP8(ox1.dirname(rx1),{recursive:!0}),await MP8(rx1,J,"utf-8")}catch(Q){h.debug("Failed to save last thread ID",Q)}}async function OP8(){try{return(await qV6(rx1,"utf-8")).trim()}catch(J){return null}}var GV6=[{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(h).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${ZC1})`},{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:t2(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:VI.SMART.key,description:`Set the agent mode (${rG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:rG().map((J)=>J.mode)}],ZV6=(J)=>("deprecated"in J)&&J.deprecated===!0,wP8=(J)=>("hidden"in J)&&J.hidden===!0,EP8=(J)=>("default"in J),IP8=(J)=>("default"in J)?J.default:void 0;function PP8(J,Q){let Y=Q.args[0],X=Q.commands.map((Z)=>Z.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let Z=X.filter((V)=>Y.includes(V)||V.includes(Y)),q="Run amp --help for a list of available commands.";if(Z.length>0)q=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new _8(bZ.unknownCommand(Y),1,q)}}var VV6=null;function TA5(){return VV6}function Iu(J){return{...J,getThreadEnvironment:r61,vfs:rI0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new ux(J.fileSystem),generateThreadTitle:pl0,deleteThread:(Q)=>J.threadService.delete(Q)}}var ex1=d0.file(LP8.homedir()),KV6=process.env.XDG_CONFIG_HOME?d0.file(process.env.XDG_CONFIG_HOME):o0.joinPath(ex1,".config");async function lq(J,Q){$N0("0.0.1764590491-gb0d62c");let Y=qq1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:X0.of([d0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:ex1,userConfigDir:KV6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (X51(),Y51));X(Y);let G=await Y.getLatest();h.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let{toolService:Z,dispose:q}=q16({configService:Y}),V=new Map,K=()=>V.clear(),W=new KU1(Y,J.settings.getWorkspaceRootPath()),H=XI0({configService:Y,trustStore:W,createOAuthProvider:async(n)=>{let u=V.get(n);if(u)return h.debug("Reusing existing OAuth provider for server",{serverName:n}),u;h.debug("Creating OAuth provider for server",{serverName:n});let s=(async()=>{let H1=new nM(J.secrets),W1=await H1.getClientInfo(n),o=new _F1({storage:H1,serverName:n,clientId:W1?.clientId,clientSecret:W1?.clientSecret,scopes:W1?.scopes});return h.debug("OAuth provider created",{serverName:n,hasManualClientId:!!W1?.clientId,willUseDCR:!W1?.clientId}),o})();return V.set(n,s),s}}),z=o01({configService:Y,filesystem:D5,spawn:bA}),{initializeToolProviders:U}=await Promise.resolve().then(() => (XV6(),YV6)),{registrations:N,initErrors:M}=await U({toolService:Z,providers:[H,z],initialTimeout:J.executeMode?15000:5000});for(let[n,u]of M)h.warn(`${n} provider initialization slow or failed:`,u);if(Q.jetbrains)DI("JetBrains");else if(Q.ide&&H56())DI("VS Code");else if(Q.ide&&z56())DI("Neovim");if(J.executeMode)qN0(!0);let L,A=M2.status.pipe(q6((n)=>Boolean(n.connected&&n.authenticated)),_4()).subscribe((n)=>{if(n){if(!L)L=Z.registerTool(is0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode)E=new q41(process.cwd(),{},!0);else E=new class extends q41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(h5.write(`No API key found. Starting login flow...
4889
4889
  `),!await RP8(J))await ZO(),process.exit(1)}let P=await TR0({isDevelopment:!1}),I=new KI1(P,Y),T=new GI1(P,{lazy:!0}),S=new LU1(I,(n,u)=>{let s=E3.get(n);if(s)s.handle(u).catch((H1)=>{h.error("Failed to apply artifact delta",H1)})}),y=Q.notifications!==void 0?Q.notifications:!J.executeMode,x=K16({playNotificationSound:async(n)=>{if(y){V16(n);let u=tC1(),s=eC1();if((!u||s)&&G.settings["notifications.system.enabled"]!==!1){if(n==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(n==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:I,configService:Y});h.info("Starting Amp background services");let g=cl0({threadService:I,threadHistoryService:T,configService:Y,isExtensionDevelopment:!1}),p;M2.status.subscribe((n)=>{p=n});let b=new lZ1({workspaceRoots:[d0.file(process.cwd())],getCurrentFile:()=>{if(!p?.openFile)return;try{return d0.parse(p.openFile)}catch(n){h.warn("Failed to parse current file URI",{uri:p.openFile,error:n});return}},getOpenFiles:()=>{if(!p?.visibleFiles?.length)return[];let n=p.openFile;return p.visibleFiles.filter((u)=>u!==n).map((u)=>{try{return d0.parse(u)}catch(s){return h.warn("Failed to parse visible file URI",{uri:u,error:s}),null}}).filter((u)=>u!==null)}}),l=new Yj1,J1={codebaseContextService:b,configService:Y,toolService:Z,mcpService:H,trustStore:W,threadService:I,threadHistoryService:T,threadSyncService:g,planFileManager:S,threadStorage:P,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,notificationService:x,fileSystem:Q.jetbrains||Q.ide?nI0:D5,terminal:l};return{...J1,async asyncDispose(){if(J1.mcpService.hasAuthenticatingClients())h.info("Waiting for OAuth authentication to complete before exit..."),await J1.mcpService.waitForAuthentication();for(let n of N.values())n.dispose();await J1.mcpService.dispose(),K(),await J1.threadService.asyncDispose(),J1.configService.unsubscribe(),q(),J1.fuzzyServer.dispose(),J1.threadSyncService.dispose(),J1.settingsStorage[Symbol.dispose](),A.unsubscribe(),L?.dispose()}}}async function RP8(J){if(!J.executeMode){if(!await SC1("Would you like to log in to Amp? [(y)es, (n)o]: "))return h5.write(`Login cancelled. Run the command again to retry.
4890
4890
  `),!1}return await WV6(J)}async function WV6(J){let Q=NP8(32).toString("hex"),Y=await jC1(J.ampURL,Q),X=new AbortController;try{await vE(Y,X.signal)}catch(Z){h.error("Error opening browser",{error:Z})}let G=await jC1(J.ampURL,Q,!1);h5.write(`If your browser does not open automatically, visit:
4891
4891
 
@@ -4895,7 +4895,7 @@ ${b4.blue.bold(G)}
4895
4895
  Login successful! You can now use the Amp CLI.
4896
4896
  `),!0}catch(Z){return h.error("Login failed",{error:Z}),Y$.write(`
4897
4897
  Login failed: ${Z instanceof Error?Z.message:String(Z)}
4898
- `),!1}}function TP8(){let J=new nA().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)JC(),process.exit(0);let z=H.originalError??H;Z96(z)}),J.option("-V, --version","Print the version number and exit",()=>{h5.write(`0.0.1764583899-g57f324 (released 2025-12-01T10:17:29.363Z)
4898
+ `),!1}}function TP8(){let J=new nA().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)JC(),process.exit(0);let z=H.originalError??H;Z96(z)}),J.option("-V, --version","Print the version number and exit",()=>{h5.write(`0.0.1764590491-gb0d62c (released 2025-12-01T12:07:01.770Z)
4899
4899
  `),process.exit(0)}),J.addHelpText("after",V56()),J.configureHelp({formatHelp:K56}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await qY(U);await _P8(N)}),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 U=z.optsWithGlobals(),N=await qY(U);await SP8(N,await MC1(U,N.settings))});let Q=async(H,z,U)=>{qq1({storage:z.settings,secretStorage:z.secrets,workspaceRoots:X0.of([d0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:ex1,userConfigDir:KV6});let N={...z,executeMode:!1};await sx1(N,{...H,openThreadSwitcher:!0},U)},Y=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await qY(U);await $V6(U,N,z)});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 U=z.optsWithGlobals(),N=await qY(U);await bP8(U,N,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,U)=>{let N=U.optsWithGlobals(),M=await qY(N);if(z.pick)Y$.write(`${b4.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
4900
4900
  `);if(z.last||H||M.executeMode)await hP8(N,M,H,U);else await Q(N,M,U)}),Y.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await qY(N);await fP8(N,M,H,U)}),Y.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await qY(U);await $V6(U,N,z)}),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,U)=>{let N=U.optsWithGlobals(),M=await qY(N);await vP8(N,M,H,U,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,U,N)=>{let M=N.optsWithGlobals(),L=await qY(M);await kP8(M,L,H,z,N)}),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,U)=>{let N=U.optsWithGlobals(),M=await qY(N);await yP8(N,M,H,U)}),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,U)=>{let N=U.optsWithGlobals(),M=await qY(N);await xP8(N,M,H,z,U)}),G26(J,async(H,z)=>{let U=await qY(z);cq(H,z);let N=await lq(U,z);return{context:U,mcpService:N.mcpService,toolService:N.toolService,toolServices:N.toolService,configService:N.configService,cleanupTerminal:JC,asyncDispose:N.asyncDispose.bind(N)}}),i56(J,async(H)=>{let z=H.optsWithGlobals();return await qY(z)}),f56(J,async(H)=>{let z=await qY(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(U)=>{cq(U,H);let N=await lq(z,H);return{mcpService:N.mcpService,settings:z.settings,asyncDispose:N.asyncDispose.bind(N)}}}});function G(H,z,U){let M=typeof H.description==="string"?H.description:U===void 0?H.description(!0):H.description(U),L=new rB(z,M),A=IP8(H);if(A)L.default(A);if(L.hidden=wP8(H)||ZV6(H),"choices"in H)L.choices([...H.choices]);return L}for(let H of GV6)switch(H.type){case"flag":{J.addOption(G(H,`--${H.long}`)),J.addOption(G(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(G(H,`--${H.long}`,!0));break}default:{J.addOption(G(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let Z=new rB("-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(Z);let q=new rB("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(q);let V=new rB("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(V);let K=new rB("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(K);let W=new rB("--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_CONNECT==="1"){let H=new rB("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return J.action(async(H,z)=>{let U=H,N=await qY(U);if(z.getOptionValueSourceWithGlobals("tryOpus")==="cli")h5.write(b4.yellow(`Opus 4.5 is now the default in Amp's smart mode. Rerun without --try-opus.
4901
4901
  `)),process.exit(0);if(Object.keys(U).forEach((M)=>{let L=GV6.find((A)=>A.name===M);if(L&&ZV6(L)&&!EP8(L))Y$.write(b4.yellow(`Warning: '--${M}' flag is deprecated
@@ -4903,8 +4903,8 @@ Login failed: ${Z instanceof Error?Z.message:String(Z)}
4903
4903
  Or pipe via stdin: echo "your message" | amp --execute`);cq(Y,Q);let q=await lq(J,Q);VV6=q;let V=Iu(q),K=async(l)=>{let J1=await qV6(l,"utf-8"),n=JSON.parse(J1);if(!d$(n.id))throw new _8(bZ.invalidThreadId);return l51(q,{visibility:X,agentMode:Q.mode,thread:n})},W=async(l)=>{if(!d$(l))throw new _8(bZ.invalidThreadId);try{let[n,u]=await Promise.all([T5.getThreadLinkInfo({thread:l},{config:q.configService}),T5.getUserInfo({},{config:q.configService})]);if(n.ok&&u.ok){let s=n.result.creatorUserID,H1=u.result.id;if(s&&s!==H1&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new _8(`Cannot resume thread created by another user.
4904
4904
 
4905
4905
  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(n){if(n instanceof _8)throw n;h.warn("Failed to validate thread ownership in CLI, allowing to open",{error:n})}let J1=await q.threadService.get(l)??void 0;return h.info(`[fetchAndStartThread] Loaded thread ${l}, agentMode: ${J1?.agentMode??"undefined"}`),l51(q,{visibility:X,agentMode:J1?void 0:Q.mode,thread:J1})},H=async()=>{try{if(Q.threadId)return W(Q.threadId);else return l51(q,{visibility:X})}catch(l){if(l instanceof _8)throw l;throw await lg(l,Q.threadId),Error("handleError should have called process.exit()")}},z=async()=>{return l51(q,{visibility:X})};if(Q.format==="jsonl")Y$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
4906
- `),await ZO(),process.exit(1);if(J.executeMode&&Q.remote)await n56(G,Z,q.configService),await q.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)g56(q.mcpService,J.settings),await A96(U,U.threadID,G,Z,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let N=!1,M=!1;if(Q.jetbrains||Q.ide){await IM0();let l=yI({jetbrainsOnly:Q.jetbrains});if(l.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(l.length===1){let J1=l[0];if(J1)M2.selectConfig(J1)}else N=!0}let L=N41("0.0.1764583899-g57f324",q.settingsStorage),A=new d11(q.threadStorage),E=X0.of([d0.file(process.cwd())]),P=Y$1(void 0,E),I=new D41(q.mcpService,J.settings.getWorkspaceRootPath());if(G)U.handle({type:"user:message",message:{content:[{type:"text",text:G}]}});let T=(async()=>{try{let l=await T5.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)});if(l.ok)return h.info("User free tier status:",l),l.result}catch(l){h.error("Failed to fetch free tier status:",l)}})(),S=(async()=>{try{let l=await T5.getUserInfo({},{config:q.configService});if(l.ok)return l.result}catch(l){h.debug("Failed to fetch user workspace info:",l)}})(),[y,x]=await Promise.all([T,S]),g=x?.email,p=g&&(g.endsWith("@sourcegraph.com")||g.endsWith("@ampcode.com")||g==="auth-bypass-user@example.com");if(p)q.toolService.registerTool(os0);let b=await s56();h.info("Loaded session state:",b),await Oy1({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new J41,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadSyncService:q.threadSyncService,planFileManager:q.planFileManager,threadID:U.threadID,threadFuzzyIndexer:A,worker:U,workerDeps:V,configService:q.configService,internalAPIClient:T5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:M2,connectedClientsService:new bi,commandRegistry:P,mcpService:q.mcpService,mcpTrustHandler:I,showJetBrainsInstaller:M,showIdePicker:N,openThreadSwitcher:Q.openThreadSwitcher,updateService:L,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:b,freeTierStatus:y,workspace:x?.team??null,features:x?.features??[],isDogfooding:p||!1,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function qY(J){if(J.interactive)Y$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4907
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await i96({...J,workspaceTrust:{current:!0,changes:Fk},getHook:process.env.AMP_URL?(Z,q)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let Z=await h56(J.mcpConfig);X=b56(X,Z)}let G=await X.get("url","global");if(!G)G=OY;if(!lF(G))h.info("Targeting custom Amp server",{ampURL:G});return X=PU0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:a56(await MC1(J,X))}}function CP8(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let Z=X.slice(2).replace(/-([a-z])/g,(V,K)=>K.toUpperCase()),q=J[Y+1];if(q&&!q.startsWith("--"))Q[Z]=q,Y++}}return Q}async function jP8(){let J=CP8(process.argv);if(r86({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),AP8(h),h.info("Starting Amp CLI.",{version:"0.0.1764583899-g57f324",buildTimestamp:"2025-12-01T10:17:29.363Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new _8(bZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await TP8().parseAsync(process.argv)}eE1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await jP8().catch(lg)});async function SP8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),h5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4906
+ `),await ZO(),process.exit(1);if(J.executeMode&&Q.remote)await n56(G,Z,q.configService),await q.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)g56(q.mcpService,J.settings),await A96(U,U.threadID,G,Z,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let N=!1,M=!1;if(Q.jetbrains||Q.ide){await IM0();let l=yI({jetbrainsOnly:Q.jetbrains});if(l.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(l.length===1){let J1=l[0];if(J1)M2.selectConfig(J1)}else N=!0}let L=N41("0.0.1764590491-gb0d62c",q.settingsStorage),A=new d11(q.threadStorage),E=X0.of([d0.file(process.cwd())]),P=Y$1(void 0,E),I=new D41(q.mcpService,J.settings.getWorkspaceRootPath());if(G)U.handle({type:"user:message",message:{content:[{type:"text",text:G}]}});let T=(async()=>{try{let l=await T5.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)});if(l.ok)return h.info("User free tier status:",l),l.result}catch(l){h.error("Failed to fetch free tier status:",l)}})(),S=(async()=>{try{let l=await T5.getUserInfo({},{config:q.configService});if(l.ok)return l.result}catch(l){h.debug("Failed to fetch user workspace info:",l)}})(),[y,x]=await Promise.all([T,S]),g=x?.email,p=g&&(g.endsWith("@sourcegraph.com")||g.endsWith("@ampcode.com")||g==="auth-bypass-user@example.com");if(p)q.toolService.registerTool(os0);let b=await s56();h.info("Loaded session state:",b),await Oy1({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new J41,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadSyncService:q.threadSyncService,planFileManager:q.planFileManager,threadID:U.threadID,threadFuzzyIndexer:A,worker:U,workerDeps:V,configService:q.configService,internalAPIClient:T5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:M2,connectedClientsService:new bi,commandRegistry:P,mcpService:q.mcpService,mcpTrustHandler:I,showJetBrainsInstaller:M,showIdePicker:N,openThreadSwitcher:Q.openThreadSwitcher,updateService:L,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:b,freeTierStatus:y,workspace:x?.team??null,features:x?.features??[],isDogfooding:p||!1,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function qY(J){if(J.interactive)Y$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4907
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await i96({...J,workspaceTrust:{current:!0,changes:Fk},getHook:process.env.AMP_URL?(Z,q)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let Z=await h56(J.mcpConfig);X=b56(X,Z)}let G=await X.get("url","global");if(!G)G=OY;if(!lF(G))h.info("Targeting custom Amp server",{ampURL:G});return X=PU0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:a56(await MC1(J,X))}}function CP8(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let Z=X.slice(2).replace(/-([a-z])/g,(V,K)=>K.toUpperCase()),q=J[Y+1];if(q&&!q.startsWith("--"))Q[Z]=q,Y++}}return Q}async function jP8(){let J=CP8(process.argv);if(r86({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),AP8(h),h.info("Starting Amp CLI.",{version:"0.0.1764590491-gb0d62c",buildTimestamp:"2025-12-01T12:07:01.770Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new _8(bZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await TP8().parseAsync(process.argv)}eE1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await jP8().catch(lg)});async function SP8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),h5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4908
4908
  `);else if(!lF(J.ampURL))h5.write(`Logging in to ${new URL(J.ampURL).hostname}
4909
4909
  `);let Y=process.env.AMP_API_KEY;if(Y)h5.write(`API key found in environment variable, storing...
4910
4910
  `),await Q.set("apiKey",Y,J.ampURL),h5.write(`API key successfully stored.
@@ -4917,7 +4917,7 @@ This thread belongs to a different user and cannot be continued for security rea
4917
4917
  `);else h5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
4918
4918
  `);process.exit(0)}async function kP8(J,Q,Y,X,G){cq(G,J);let Z=await lq(Q,J);try{let q=i51(Y);if(!q)n51(Y);let V=q,K=X.trim();if(K.length===0)Q$("Thread name cannot be empty");if(K.length>256)Q$("Thread name cannot exceed 256 characters");if(!(await Uj(V,Z)).messages.length)Q$("Cannot rename an empty thread.");let H=Iu(Z);await(await E3.getOrCreateForThread(H,V)).handle({type:"title",value:K}),h.info("GOT HERE"),await Z.threadSyncService.sync(),h.info("GOT THERE"),h5.write(b4.green(`✓ Thread ${V} renamed to "${K}"
4919
4919
  `)),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose();let V=`Failed to rename thread: ${q instanceof Error?q.message:String(q)}`;Q$(V)}}async function yP8(J,Q,Y,X){cq(X,J);let G=await lq(Q,J);try{let Z=i51(Y);if(!Z)n51(Y);let V=await Uj(Z,G),K=OT(V);h5.write(K+`
4920
- `),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let q=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;Q$(q)}}async function xP8(J,Q,Y,X,G){cq(G,J);let Z=await lq(Q,J);try{let q=await Jv1(Y),V=await Uj(q,Z),K=X.typing!==!1,W=parseInt(X.wpm||"120",10),H=parseInt(X.messageDelay||"1000",10),z=parseInt(X.toolProgressDelay||"800",10),U=parseInt(X.exitDelay||"3",10)*1000,N=X.indicator!==!1,M=Iu(Z),L=V.id;await Z.threadStorage.set(L,V);let A=await E3.getOrCreateForThread(M,L);await A.resume();let E=p11.fromWorker(A),P=new d11(Z.threadStorage),I=X0.of([d0.file(process.cwd())]),T=Y$1(void 0,I),S=new D41(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=N41("0.0.1764583899-g57f324",Z.settingsStorage);await Oy1({codebaseContextService:Z.codebaseContextService,stdout:process.stdout,history:new J41,fuzzyServer:Z.fuzzyServer,settingsStorage:Z.settingsStorage,threadService:Z.threadService,threadHistoryService:Z.threadHistoryService,threadSyncService:Z.threadSyncService,planFileManager:Z.planFileManager,threadID:L,threadFuzzyIndexer:P,worker:E,workerDeps:M,configService:Z.configService,internalAPIClient:T5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:M2,connectedClientsService:new bi,commandRegistry:T,mcpService:Z.mcpService,mcpTrustHandler:S,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:V,typingEnabled:K,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:N}}),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),await lg(q,Y)}}async function vP8(J,Q,Y,X,G){cq(X,J);let Z=await lq(Q,J);try{let q=i51(Y);if(!q)n51(Y);let V=q,K=await T5.getUserInfo({},{config:Z.configService}),W=K.ok?K.result:null,H=M41(J,W);if(!H&&!G)Q$("Must specify either --visibility or --support");if(H&&G)Q$("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)Q$(H.message);if(H)await Z.threadSyncService.updateThreadMeta(V,L41(H)),h5.write(b4.green("✓ ")+`Thread ${V} visibility changed to ${H}.
4920
+ `),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let q=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;Q$(q)}}async function xP8(J,Q,Y,X,G){cq(G,J);let Z=await lq(Q,J);try{let q=await Jv1(Y),V=await Uj(q,Z),K=X.typing!==!1,W=parseInt(X.wpm||"120",10),H=parseInt(X.messageDelay||"1000",10),z=parseInt(X.toolProgressDelay||"800",10),U=parseInt(X.exitDelay||"3",10)*1000,N=X.indicator!==!1,M=Iu(Z),L=V.id;await Z.threadStorage.set(L,V);let A=await E3.getOrCreateForThread(M,L);await A.resume();let E=p11.fromWorker(A),P=new d11(Z.threadStorage),I=X0.of([d0.file(process.cwd())]),T=Y$1(void 0,I),S=new D41(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=N41("0.0.1764590491-gb0d62c",Z.settingsStorage);await Oy1({codebaseContextService:Z.codebaseContextService,stdout:process.stdout,history:new J41,fuzzyServer:Z.fuzzyServer,settingsStorage:Z.settingsStorage,threadService:Z.threadService,threadHistoryService:Z.threadHistoryService,threadSyncService:Z.threadSyncService,planFileManager:Z.planFileManager,threadID:L,threadFuzzyIndexer:P,worker:E,workerDeps:M,configService:Z.configService,internalAPIClient:T5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:M2,connectedClientsService:new bi,commandRegistry:T,mcpService:Z.mcpService,mcpTrustHandler:S,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:V,typingEnabled:K,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:N}}),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),await lg(q,Y)}}async function vP8(J,Q,Y,X,G){cq(X,J);let Z=await lq(Q,J);try{let q=i51(Y);if(!q)n51(Y);let V=q,K=await T5.getUserInfo({},{config:Z.configService}),W=K.ok?K.result:null,H=M41(J,W);if(!H&&!G)Q$("Must specify either --visibility or --support");if(H&&G)Q$("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)Q$(H.message);if(H)await Z.threadSyncService.updateThreadMeta(V,L41(H)),h5.write(b4.green("✓ ")+`Thread ${V} visibility changed to ${H}.
4921
4921
  `);if(G){await Uj(V,Z);let z=typeof G==="string"?G:void 0;await OR0(Z.threadService,V,Z.configService,z),h5.write(b4.green("✓ ")+`Thread ${V} has been shared with Amp support. These thread reports will be aggregated and analysed.
4922
4922
  `)}await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),Q$(`Failed to update thread: ${q instanceof Error?q.message:String(q)}`)}}async function fP8(J,Q,Y,X){cq(X,J);let G=await lq(Q,J),Z=Iu(G);try{let q=await Jv1(Y),K=(await Uj(q,G)).messages.length-1,W=await E3.getOrCreateForThread(Z,q),H=await wT(W,G.threadSyncService,K);await Promise.all([G.threadSyncService.uploadThread(q),G.threadSyncService.uploadThread(H)]),await tx1(H),h5.write(`${H}
4923
4923
  `),await G.asyncDispose(),process.exit(0)}catch(q){Y$.write(`Error forking thread: ${q instanceof Error?q.message:String(q)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1764583899-g57f324",
3
+ "version": "0.0.1764590491-gb0d62c",
4
4
  "description": "CLI for Amp, the frontier coding agent from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {