@sourcegraph/amp 0.0.1765237900-gbaf2e6 → 0.0.1765238489-gbaf2e6

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 +9 -9
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4058,11 +4058,11 @@ Actual: ${X}`)}async function Vq8(J,Q,Z){let{execSync:Y}=await import("node:ch
4058
4058
  ${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))M+=`
4059
4059
 
4060
4060
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4061
- npm install -g @sourcegraph/amp`;K(Error(M))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}U0();U0();async function j41(J,Q){let Y=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=zq8(J,q),H=W<0,z,U;if(K.time){let D=K.time[J],M=K.time[q],L=Date.now();if(D)z=Math.floor((L-new Date(D).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return v.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(X){return v.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function zq8(J,Q){let Z=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Y=Z(J),X=Z(Q),G=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Y.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}i0();function S41(J,Q){let Z=new d4,Y=Z.pipe(C8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new EK().scoped("update"),G=Y.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await TR(500),Z.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=iA(),W=await j41(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,D=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await C41();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Z.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Z.next("update-available");return}if(z==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Z.next("update-available");return}try{await Bm(W.latestVersion,z);let U=await gB(W.latestVersion),D={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",D),Z.next("updated");else X.warn("success with warning",D),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await TR(5000),Z.next("hidden"),G.unsubscribe(),Z.complete()}}),{state:Y}}import{stderr as bq}from"node:process";function b56(J){let Q=new _A().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(Y)=>{await Rj1(Y.force||!1,Y.verbose||!1,"0.0.1765237900-gbaf2e6"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new _A("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(Y)=>{await Fq8(Y.targetVersion)});J.addCommand(Z)}async function Fq8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")bq.write(y4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4061
+ npm install -g @sourcegraph/amp`;K(Error(M))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}U0();U0();async function j41(J,Q){let Y=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=zq8(J,q),H=W<0,z,U;if(K.time){let D=K.time[J],M=K.time[q],L=Date.now();if(D)z=Math.floor((L-new Date(D).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return v.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(X){return v.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function zq8(J,Q){let Z=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Y=Z(J),X=Z(Q),G=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Y.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}i0();function S41(J,Q){let Z=new d4,Y=Z.pipe(C8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new EK().scoped("update"),G=Y.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await TR(500),Z.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=iA(),W=await j41(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,D=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await C41();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Z.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Z.next("update-available");return}if(z==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Z.next("update-available");return}try{await Bm(W.latestVersion,z);let U=await gB(W.latestVersion),D={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",D),Z.next("updated");else X.warn("success with warning",D),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await TR(5000),Z.next("hidden"),G.unsubscribe(),Z.complete()}}),{state:Y}}import{stderr as bq}from"node:process";function b56(J){let Q=new _A().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(Y)=>{await Rj1(Y.force||!1,Y.verbose||!1,"0.0.1765238489-gbaf2e6"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new _A("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(Y)=>{await Fq8(Y.targetVersion)});J.addCommand(Z)}async function Fq8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")bq.write(y4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4062
4062
 
4063
4063
  `));try{if(!J){bq.write(y4.blue(`Checking for updates...
4064
- `));let Z=iA(),{hasUpdate:Y,latestVersion:X}=await j41("0.0.1765237900-gbaf2e6",Z);if(!Y){bq.write(y4.green(`✓ Amp CLI is already up to date: ${"0.0.1765237900-gbaf2e6"} (${"released"} ${"2025-12-08T23:56:54.642Z"})
4065
- `));let V=await gB("0.0.1765237900-gbaf2e6");if(V.warning)bq.write(`
4064
+ `));let Z=iA(),{hasUpdate:Y,latestVersion:X}=await j41("0.0.1765238489-gbaf2e6",Z);if(!Y){bq.write(y4.green(`✓ Amp CLI is already up to date: ${"0.0.1765238489-gbaf2e6"} (${"released"} ${"2025-12-09T00:06:53.598Z"})
4065
+ `));let V=await gB("0.0.1765238489-gbaf2e6");if(V.warning)bq.write(`
4066
4066
  `+y4.yellow(V.warning)+`
4067
4067
  `);process.exit(0)}if(!X)bq.write(y4.yellow("[WARN] could not find latest version")),process.exit(0);J=X}bq.write(y4.blue(`Updating to version ${J}...
4068
4068
  `)),await Bm(J,void 0,(Z)=>{bq.write(y4.dim(`Running: ${Z}
@@ -4708,7 +4708,7 @@ Ctrl-X Y Z to unlock`;if(U){let a=W.text.replace(/`([^`]+)`/g,"$1")+`
4708
4708
  `,A)])}),y];if(!q&&!U&&W.url){let m=W.url.replace(/^https?:\/\//,"");b.push(new n5({uri:W.url,text:m,style:new J1({color:Z.secondary,underline:!0})}))}if(k&&!U)b.push(k);let d=new X0({width:40,child:new v0({crossAxisAlignment:"start",mainAxisSize:"min",children:b})});return x4.child(new N6({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new Y_1({width:_y1,height:ky1,agentMode:this.widget.agentMode,glow:this._glow,t:H,fps:0,shockwaves:this._shockwaves,onShockwave:P,...V==="disabled"&&{seed:42}}),new X0({width:2}),d]}))}}U0();S8();z4();U7();S8();i0();function ZO8(J,Q){return`${J}:${Q}`}class yy1{threadService;workers=new Map;threadsMap=new Map;subthreadsMap=new Map;mainThreadSubs=new Map;subthreadsSubs=new Map;workerStatusSubs=new Map;subthreadPatchSubs=new Map;mainThreadObservable;subthreadObservable;workerStatusObservable;emitMainThread=null;emitSubthread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new Q0((Q)=>{return this.emitMainThread=(Z)=>Q.next(Z),()=>{this.emitMainThread=null}}),this.subthreadObservable=new Q0((Q)=>{return this.emitSubthread=(Z)=>Q.next(Z),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new Q0((Q)=>{return this.emitWorkerStatus=(Z)=>Q.next(Z),()=>{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 Z=this.threadService.observePatches(Q).pipe(NM()).subscribe((G)=>{this.threadsMap.set(Q,G);let V=this.subthreadsMap.get(Q)||[],K=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:G,subthreads:V,workerStatus:K})});this.mainThreadSubs.set(Q,Z);let Y=J.status.subscribe((G)=>{if(this.workers.set(Q,G),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:G})});this.workerStatusSubs.set(Q,Y);let X=J.subthreads.subscribe((G)=>{this.subthreadsMap.set(Q,G);for(let V of G){let K=ZO8(Q,V.toolUse.id);if(this.subthreadPatchSubs.has(K))continue;let q=this.threadService.observePatches(V.threadID).pipe(NM()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:V})});this.subthreadPatchSubs.set(K,q)}});this.subthreadsSubs.set(Q,X)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Z=this.workerStatusSubs.get(J);if(Z)Z.unsubscribe(),this.workerStatusSubs.delete(J);let Y=this.subthreadsSubs.get(J);if(Y)Y.unsubscribe(),this.subthreadsSubs.delete(J);for(let[X,G]of this.subthreadPatchSubs.entries())if(X.startsWith(`${J}:`))G.unsubscribe(),this.subthreadPatchSubs.delete(X);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new Q0((Q)=>{return this.mainThreadObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})}),subthreads:new Q0((Q)=>{return this.subthreadObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})}),workerStatus:new Q0((Q)=>{return this.workerStatusObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})})}}get threadViewStates(){let J={};for(let[Q,Z]of this.threadsMap){let Y=this.workers.get(Q);if(Y)J[Q]=UA(Z,Y)}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 YO8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Z,subthread:Y}=Q,X=J.subagents[Y.threadID];if(!X){if(X={subThreadID:Z.id,parentToolID:Y.toolUse.id,taskDescription:Y.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=lJ(J.mainThread);X.isCompleted=pY6(W,Y.toolUse.id)}}let G=XO8(Z,X.agentState),V=X.agentState===G?X:{...X,agentState:G},K={...J.tools},q=cC(Z).items.filter((W)=>W.type==="toolResult");for(let W of q)K[W.id]={id:W.id,subthreadID:Z.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[Y.threadID]:V},tools:K,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Z,subthreads:Y,workerStatus:X}=Q,G=lJ(Z),V={...J.subagents};for(let z of Y){let U=V[z.threadID];if(!U)continue;let D=pY6(G,z.toolUse.id);V[z.threadID]={...U,isCompleted:D}}let{items:K}=cC(Z),q=UA(Z,X),W=qI({messages:Z.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:V,items:K,viewState:q,todosList:H,mainThread:Z}}case"worker-status-change":{if(!J.mainThread)return J;let Z=UA(J.mainThread,Q.workerStatus);if(Z===J.viewState)return J;return{...J,viewState:Z}}default:return J}}function cC(J){let Q=[],Z=new Map,Y=new Set;for(let[X,G]of J.messages.entries()){let V=`${G.role}-${X}`;switch(G.role){case"assistant":{let K=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(Z.set(W.id,W),K)Y.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,message:G});for(let W of G.content)if(W.type==="tool_use"){let H=!1;for(let z=X+1;z<J.messages.length;z++){let U=J.messages[z];if(U){for(let D of U.content)if(D.type==="tool_result"&&D.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:K?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:V,message:G});break;case"user":{let K=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=Z.get(q.toolUseID)??LY(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(K)Q.push({type:"message",id:V,message:G});break}}}return{items:Q}}function pY6(J,Q){let Z=J.get(Q);return(Z&&W2(Z.run))??!1}function XO8(J,Q){let Z=J.messages.at(-1);if(Z?.content.some((X)=>X.type==="tool_result"&&X.run.status==="blocked-on-user"))return v.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(cC(J).items.some((X)=>X.type==="toolResult"&&X.toolResult.run.status==="in-progress")){let X=Q?.type==="running-tools"?Q.startTime:Date.now();return v.info("Subagent status: running-tools",{threadID:J.id,startTime:X,hasStartTime:!!X}),{type:"running-tools",startTime:X}}if(Z&&Z.role==="assistant"&&Z.state.type==="streaming")switch(Z.content.at(-1)?.type){case"text":return v.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return v.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let G=Q?.type==="running-tools"?Q.startTime:Date.now();return v.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}default:return v.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return v.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class xy1 extends d0{props;constructor(J){super();this.props=J}createState(){return new dY6}}class dY6 extends u0{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 yy1(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),Z=Q.mainThread.subscribe((G)=>{this.dispatch({type:"main-thread-patch",thread:G.mainThread,subthreads:G.subthreads,workerStatus:G.workerStatus})});this.subscriptions.push(Z);let Y=Q.subthreads.subscribe((G)=>{this.dispatch({type:"subthread-patch",thread:G.thread,subthread:G.subthread})});this.subscriptions.push(Y);let X=Q.workerStatus.subscribe((G)=>{this.dispatch({type:"worker-status-change",workerStatus:G.status})});this.subscriptions.push(X)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=YO8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((G)=>({toolUse:G.toolUse,toolRun:G.toolRun,subthreadID:G.subthreadID})),Q={};for(let G of Object.values(this.state.subagents)){let V=J.filter((K)=>K.subthreadID===G.subThreadID);Q[G.parentToolID]=V}let Z=(G)=>G===A5||G===o8||G===MY,Y=new Map;for(let G of this.state.items)if(G.type==="toolResult"&&Z(G.toolUse.name))Y.set(G.toolUse.id,{toolUseId:G.toolUse.id,toolName:G.toolUse.name,toolRun:G.toolResult.run});let X=Array.from(Y.values());for(let{toolUseId:G,toolRun:V}of X){let K=[],q;if(V.status==="in-progress"||V.status==="done"||V.status==="error"||V.status==="cancelled")q=V.progress;if(q){let W=0;for(let H of q)if(H.tool_uses)for(let z of H.tool_uses){let U=`${G}:progress:${W++}`;K.push({toolUse:GI(z.tool_name,z.input,U),toolRun:{status:z.status}})}}Q[G]=K}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Z)=>this.switchWorker(Z),()=>this.currentWorker,this.recentThreadIDs)}}class vy1 extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new cY6}}class cY6 extends u0{build(J){let Z=X6.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new X0({width:0,height:0});let G=Y.map((V)=>this.buildTodoItem(V,Z));return new g0({child:new z6({padding:z0.symmetric(1,0),child:new v0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new _1({text:new i(X,new J1({bold:!0,color:Z.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Z=this.getStatusIcon(J.status),Y=J.status==="completed",X=new J1({bold:J.status==="in-progress",color:Q.foreground,dim:Y}),G=new J1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Y});return new N6({crossAxisAlignment:"start",children:[new _1({text:new i(Z,X)}),new X0({width:1}),new c6({child:new _1({text:new i(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class fy1 extends E6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:Y}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=Y}build(J){let Q=X6.of(J),Z=Q.colors.primary,Y=Q.colors.foreground;return new g0({decoration:new M8(void 0,new O4(new W4(Z,1,"rounded"),new W4(Z,1,"rounded"),void 0,new W4(Z,1,"rounded"))),child:new z6({padding:z0.horizontal(1),child:new v0({children:[new N6({crossAxisAlignment:"start",children:[new c6({child:new _1({text:new i(this.ad.content,new J1({color:Y}))})}),new X0({width:4}),new n5({uri:"https://ampcode.com/free",text:"Ad",style:new J1({color:Y,dim:!0})})]}),new N6({crossAxisAlignment:"start",children:[new U_1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:z0.horizontal(1),color:Z,reverse:!0}),new X0({width:2}),new _1({text:new i(this.ad.destinationUrlHostname,new J1({color:Y,dim:!0}))})]})]})})})}}class hy1 extends d0{props;constructor(J){super();this.props=J}createState(){return new lY6(this.props.autofocus??!0)}}class lY6 extends u0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(K)=>{if(K.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(K.ctrlKey&&K.key==="c"||K.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Z=b4.sizeOf(J),Y=Math.min(60,Z.width-4),X=Z.height-4,G=[];if(this.widget.props.title)G.push(new _1({text:new i(this.widget.props.title,new J1({bold:!0,color:z1.blue}))}),new X0({height:1}));if(this.widget.props.message)G.push(new _1({text:new i(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)G.push(new X0({height:1}));let V=[];if(this.widget.props.showCopyOption)V.push(new _1({text:new i("Enter to copy",new J1({dim:!0}))}));return V.push(new _1({text:new i("Escape to close",new J1({dim:!0}))})),G.push(new N6({children:V.flatMap((K,q)=>q<V.length-1?[K,new X0({width:1}),new _1({text:new i("•",new J1({dim:!0}))}),new X0({width:1})]:[K]),mainAxisSize:"min"})),new x4({child:new g0({constraints:new w6(Y,Y,0,X),decoration:new M8(z1.default(),new O4(new W4(z1.blue,1,"rounded"),new W4(z1.blue,1,"rounded"),new W4(z1.blue,1,"rounded"),new W4(z1.blue,1,"rounded"))),padding:new z0(2,2,2,2),child:new F8({autofocus:this.autofocus,onKey:Q,child:new v0({children:G,mainAxisSize:"min"})})})})}}class V51 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,V51.prototype)}}class K51 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,K51.prototype)}}function by1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Z)=>{if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z})}HH();U0();import{spawn as $O8}from"node:child_process";import{promises as GO8}from"node:fs";function iY6(J){return J.kind==="executable"}function nY6(J){return J.kind==="markdown"}var Az=50000,aY6=300000;async function gy1(J,Q,Z,Y={}){let{timeoutMs:X=aY6,signal:G,source:V}=Y;try{let K=await Z.getCommand(J,V);if(!K)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J,V))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(v.debug("Executing command",{commandName:J,filePath:K.filePath,args:Q}),nY6(K))return await VO8(K,Q);else if(iY6(K))return await KO8(K,Q,X,G);else return{success:!1,output:"",error:"Unsupported command type"}}catch(K){return v.error("Failed to execute command",{commandName:J,error:K}),{success:!1,output:"",error:K instanceof Error?K.message:"Unknown error occurred"}}}async function VO8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await GO8.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>Az?Z.slice(0,Az)+`
4709
4709
  ... (output truncated at ${Az} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function KO8(J,Q,Z=aY6,Y){return new Promise((X)=>{let[G,V]=qO8(J,Q);v.debug("Spawning command",{spawnCommand:G,spawnArgs:V.slice(0,10),filePath:J.filePath,timeoutMs:Z});let K=qR0(Y),q=!1,W=setTimeout(()=>{q=!0,K.abort(),v.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),H=$O8(G,V,{stdio:["pipe","pipe","pipe"],signal:K.signal,detached:!0}),z=[],U=[],D=0;H.stdout?.on("data",(M)=>{let L=M.toString();if(D+=L.length,D<=Az)z.push(L);else{let A=Az-(D-L.length);if(A>0)z.push(L.slice(0,A))}}),H.stderr?.on("data",(M)=>{let L=M.toString();if(D+=L.length,D<=Az)U.push(L);else{let A=Az-(D-L.length);if(A>0)U.push(L.slice(0,A))}}),H.on("close",(M)=>{if(clearTimeout(W),q){X({success:!1,output:z.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(K.signal.aborted){X({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(""),I=A;if(!L&&!A.trim()&&E.trim())I=E;else if(E.trim())I+=A?`
4710
4710
  ${E}`:E;if(D>Az)I+=`
4711
- ... (output truncated at ${Az} characters)`;X({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(q)L=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";X({success:!1,output:z.join(""),error:L})})})}function qO8(J,Q){let{filePath:Z,interpreter:Y,extension:X}=J;if(process.platform==="win32")return HO8(Z,Y?[...Y]:null,X,Q);else return WO8(Z,Y?[...Y]:null,X,Q)}function WO8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];else return[J,Y]}function HO8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Y]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Y]];case".exe":return[J,Y];default:return[J,Y]}}U0();_G();R7();CK();TY();tG();zH();Jq();S8();U7();Fk();i0();var EX6=W6(lP(),1);import{writeFile as AX6}from"fs/promises";import OX6 from"path";U0();TY();class my1{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,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1765237900-gbaf2e6"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await kr(Q,this.configService)}catch(Q){v.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class lC extends d0{props;constructor(J){super();this.props=J}createState(){return new oY6}}class oY6 extends u0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class rY6 extends u0{controller=new h$;focusNode=new D8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=X6.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=O4.all(new W4(Z.foreground,1,"solid")),q=new VO({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let M=D.trim();if(X&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new N6({children:[new g0({decoration:{color:z1.default()},child:new _1({text:new i(">",new J1({color:Z.foreground}))})}),new c6({child:q})]}),H=new g0({padding:z0.symmetric(1,0),child:new _1({text:new i("",void 0,[new i("Command: ",new J1({color:Z.foreground})),new i(this.widget.props.commandName,new J1({color:z1.yellow,bold:!0}))])})}),z=[];if(V)z.push(new i("Enter",new J1({color:Y.keybind}))),z.push(new i(" to submit, ",new J1({color:Z.foreground,dim:!0})));z.push(new i("Esc",new J1({color:Y.keybind}))),z.push(new i(" to cancel",new J1({color:Z.foreground,dim:!0})));let U=new g0({padding:z0.symmetric(1,0),child:new _1({text:new i("",void 0,z)})});return new g0({decoration:{border:K,color:z1.default()},padding:z0.all(1),child:new v0({children:[H,new X0({height:1}),W,new Z5,U]})})}}class q51 extends d0{props;constructor(J){super();this.props=J}createState(){return new rY6}}zH();class sY6 extends u0{controller=new h$;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new D8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=VU)return!1;let Q=CC(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=X6.of(J),{colors:Z,app:Y}=Q,G=b4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new AO({controller:this.controller,triggers:[new WN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:t8.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new F8({focusNode:this.focusNode,child:K}),W=new g0({constraints:new w6({maxHeight:V}),padding:z0.symmetric(1,0),child:q}),H=new g0({padding:z0.symmetric(1,0),child:new _1({text:new i("",void 0,[new i("Command: ",new J1({color:Z.foreground})),new i(this.widget.props.commandName,new J1({color:z1.yellow,bold:!0}))])})}),z=new g0({padding:z0.symmetric(1,0),child:new _1({text:this.isConfirmingClearInput?new i("",void 0,[new i("Esc",new J1({color:Y.keybind})),new i(" again to clear input",new J1({color:Z.foreground,dim:!0}))]):new i("",void 0,[new i("Press ",new J1({color:Z.foreground,dim:!0})),new i("Enter",new J1({color:Y.keybind})),new i(" to submit, ",new J1({color:Z.foreground,dim:!0})),new i("Esc",new J1({color:Y.keybind})),new i(" to clear",new J1({color:Z.foreground,dim:!0}))])})}),U=[H,new X0({height:1}),new c6({child:W}),new X0({height:1}),z];return new g0({decoration:{border:O4.all(new W4(Z.foreground,1,"solid")),color:z1.default()},padding:z0.all(1),child:new v0({children:U})})}}class iC extends d0{props;constructor(J){super();this.props=J}createState(){return new sY6}}import{isDeepStrictEqual as BO8}from"node:util";var zO8=/[\\/_ +.#"@[({&]/,FO8=/[\\/_ +.#"@[({&]/g,UO8=/[\s-]/,tY6=/[\s-]/g;function H51(J,Q,Z,Y,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Y.charAt(G),W=Z.indexOf(q,X),H=0,z,U,D,M;while(W>=0){if(z=H51(J,Q,Z,Y,W+1,G+1,V),z>H){if(W===X)z*=1;else if(UO8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(X,W-1).match(tY6),M&&X>0)z*=Math.pow(0.999,M.length)}else if(zO8.test(J.charAt(W-1))){if(z*=0.8,D=J.slice(X,W-1).match(FO8),D&&X>0)z*=Math.pow(0.999,D.length)}else if(z*=0.3,X>0)z*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Z.charAt(W-1)===Y.charAt(G+1)||Y.charAt(G+1)===Y.charAt(G)&&Z.charAt(W-1)!==Y.charAt(G))){if(U=H51(J,Q,Z,Y,W+1,G+2,V),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Z.indexOf(q,W+1)}return V[K]=H,H}function W51(J){return J.toLowerCase().replace(tY6," ")}function eY6(J,Q){let Z=H51(J,Q,W51(J),W51(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,G=0;for(let K of Y){let q=H51(J,K,W51(J),W51(K),0,0,{});if(q===0)return Z;X+=q,G+=K.length}let V=X/Y.length*0.95;return Math.max(Z,V)}return Z}class nC{}class aC{}class z51{}class F51{}class JX6 extends d0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new QX6}}class QX6 extends u0{build(J){return this.widget.onContext(J),this.widget.child}}function NO8(J,Q){if(J==="")return{matches:!0,score:1};let Z=eY6(Q,J);return{matches:Z>0.15,score:Z}}class AJ extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new ZX6}}class ZX6 extends u0{controller=new h$;focusNode;scrollController=new i5;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new D8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),c8.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(!BO8(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 z51){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof F51)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...NO8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,Y)=>this.widget.props.sortItems(Z,Y,J):(Z,Y)=>Y.score-Z.score).map((Z)=>Z.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 Z=0,Y=Q.size.height;G91(J,{top:Z,bottom:Y},{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(),c8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!X){if(Y)this.widget.props.onAccept(Y)}}};build(J){let Q=X6.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=O4.all(new W4(Z.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new VO({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new QX({shortcuts:new Map([[new V4("ArrowDown"),new nC],[new V4("ArrowUp"),new aC],[new V4("Tab"),new nC],[new V4("Tab",{shift:!0}),new aC],[new V4("n",{ctrl:!0}),new nC],[new V4("p",{ctrl:!0}),new aC],[new V4("Enter"),new z51],[new V4("Escape"),new F51]]),focusNode:this.focusNode,child:V}),q=new BJ({actions:new Map([[nC,new P8(this.invoke)],[aC,new P8(this.invoke)],[z51,new P8(this.invoke)],[F51,new P8(this.invoke)]]),child:K}),W=new N6({children:[new g0({decoration:{color:z1.default()},child:new _1({text:new i(">",new J1({color:Z.foreground}))})}),new c6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new X0({height:10,child:new x4({child:new _1({text:new i(L,new J1({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new c6({child:new x4({child:new _1({text:new i(this.widget.props.emptyStateText,new J1({color:Z.foreground,dim:!0}))})})});else{let L=Y.map((A,E)=>{let I=E===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,R;if(this.widget.props.renderItem)R=this.widget.props.renderItem(A,I,P,J);else{let k=I?z1.yellow:void 0,y=I?z1.black:Z.foreground;R=new g0({decoration:k?{color:k}:void 0,padding:z0.symmetric(2,0),child:new _1({text:new i(this.widget.props.getLabel(A),new J1({color:y,dim:P}))})})}return new JX6(new K8({onClick:(k)=>this.handleItemClick(E,k.clickCount),child:R}),(k)=>{this.itemContexts[E]=k})});H=new v0({children:L,crossAxisAlignment:"start"})}let z=new c6({child:new K8({onScroll:this.handleScroll,opaque:!1,child:new W5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new g0({padding:z0.symmetric(1,0),child:new _1({text:new i(this.widget.props.title,new J1({color:z1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new X0({height:1}),z),this.controller.text!==""){let L=Y.length>0?Y[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new g0({padding:z0.vertical(1),child:new x4({child:A})}));else U.push(new X0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new g0({decoration:{border:X,color:z1.default()},padding:z0.symmetric(1,0),child:new v0({children:U})})}}function YX6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class uy1 extends E6{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>YX6(X.pubDate).length));return new AJ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=X6.of(K),{colors:W}=q,H=G?z1.yellow:void 0,z=G?z1.black:W.foreground,U=z1.index(8),D=(M,L)=>new X0({width:L,child:N6.end([new _1({text:new i(M,new J1({color:U}))})])});return new g0({decoration:H?{color:H}:void 0,padding:z0.symmetric(2,0),child:new N6({children:[new c6({child:new _1({text:new i(X.title,new J1({color:z})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),D(YX6(X.pubDate),Z)]})})}})}}class py1 extends d0{createState(){return new XX6}}class XX6 extends u0{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 _1({text:new i("●",new J1({color:this.isGreen?z1.green:z1.index(8),bold:!0})),maxLines:1})}}function DO8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Y.set(V.id,K.type);let q=K.threadID,W=Z.get(q)||[];W.push(V),Z.set(q,W)}else X.push(V)}return YX.flatten(X,(V)=>Z.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function dy1(J,Q,Z){return new _1({text:new i(`${J}${Q}`,new J1({color:Z})),maxLines:1})}function MO8(J,Q,Z,Y){return[dy1("+",J,Y.success),Z5.horizontal(1),dy1("~",Q,Y.warning),Z5.horizontal(1),dy1("-",Z,Y.destructive)]}class U51 extends E6{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 Z=this.props.recentThreadIDs||[],Y=this.props.currentThreadID,X=[...Q].sort((H,z)=>{if(Y){if(H.id===Y)return-1;if(z.id===Y)return 1}let U=Z.indexOf(H.id),D=Z.indexOf(z.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),G=DO8(X),V=Math.max(0,...G.map((H)=>H.description.timeAgo.length)),K=X6.of(J),q=new z6({padding:z0.symmetric(0,1),child:new x4({child:new _1({text:new i("",new J1({color:K.colors.foreground,dim:!0}),[new i("Ctrl+T",new J1({color:z1.blue,dim:!0})),new i(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new J1({color:K.colors.foreground,dim:!0}))])})})});return new AJ({items:G,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:q,renderItem:(H,z,U,D)=>{let M=X6.of(D),{colors:L}=M,A=z?z1.yellow:void 0,E=z?z1.black:L.foreground,I=z1.index(8),P=(Z1,t)=>new X0({width:t,child:N6.end([new _1({text:new i(Z1,new J1({color:I}))})])}),R=this.props.threadViewStates[H.id],k=[],y=H.relationshipType==="handoff",x=new F91;if(H.depth>0){let Z1=[],t=H.ancestorsAreLast.slice(1);for(let V1 of t)Z1.push(new i(x.getAncestorPrefix(V1),new J1({color:x.connectorColor,dim:x.connectorDim})));let p=H.isLast?x.elbow:x.tee,e=x.getConnectorText(p);Z1.push(new i(e,new J1({color:x.connectorColor,dim:x.connectorDim}))),k.push(new _1({text:new i("",void 0,Z1)}))}let b=[],d=this.props.currentThreadID===H.id?new i("(current) ",new J1({color:z1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new i("(visited) ",new J1({color:L.foreground,dim:!0})):null;if(d)b.push(new _1({text:d}));if(R){if(R.state==="active"&&(R.interactionState==="tool-running"||R.interactionState===!1))b.push(new py1),b.push(new X0({width:1}))}let m=H.title;if(H.relationshipType==="fork"){let Z1=m.match(/^Forked\((\d+)\): /);if(Z1)m=m.slice(Z1[0].length);else while(m.startsWith("Forked: "))m=m.slice(8);b.push(new _1({text:new i("[fork] ",new J1({color:z1.blue}))}))}else if(y)b.push(new _1({text:new i("[handoff] ",new J1({color:z1.index(208)}))}));if(b.push(new c6({child:new _1({text:new i(m,new J1({color:E})),overflow:"ellipsis",maxLines:1})})),b.push(new X0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let Z1=z?{success:I,warning:I,destructive:I}:L;b.push(...MO8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,Z1)),b.push(new X0({width:2}))}return b.push(P(H.description.timeAgo,V)),new g0({decoration:A?{color:A}:void 0,padding:z0.symmetric(2,0),child:new N6({children:[...k,...b]})})}})}}function $X6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class cy1 extends E6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>$X6(X.pubDate).length));return new AJ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=X6.of(K),{colors:W}=q,H=G?z1.yellow:void 0,z=G?z1.black:W.foreground,U=z1.index(8),D=X.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new X0({width:A,child:N6.end([new _1({text:new i(L,new J1({color:U}))})])});return new g0({decoration:H?{color:H}:void 0,padding:z0.symmetric(2,0),child:new N6({children:[new c6({child:new _1({text:new i(X.title,new J1({color:z})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new _1({text:new i(D,new J1({color:U})),maxLines:1}),new X0({width:2}),M($X6(X.pubDate),Z)]})})}})}}class ly1 extends E6{props;constructor(J){super();this.props=J}build(){return new x4({child:new _1({text:new i("",void 0,[new i(`Forked to new thread:
4711
+ ... (output truncated at ${Az} characters)`;X({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(q)L=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";X({success:!1,output:z.join(""),error:L})})})}function qO8(J,Q){let{filePath:Z,interpreter:Y,extension:X}=J;if(process.platform==="win32")return HO8(Z,Y?[...Y]:null,X,Q);else return WO8(Z,Y?[...Y]:null,X,Q)}function WO8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];else return[J,Y]}function HO8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Y]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Y]];case".exe":return[J,Y];default:return[J,Y]}}U0();_G();R7();CK();TY();tG();zH();Jq();S8();U7();Fk();i0();var EX6=W6(lP(),1);import{writeFile as AX6}from"fs/promises";import OX6 from"path";U0();TY();class my1{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,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1765238489-gbaf2e6"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await kr(Q,this.configService)}catch(Q){v.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class lC extends d0{props;constructor(J){super();this.props=J}createState(){return new oY6}}class oY6 extends u0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class rY6 extends u0{controller=new h$;focusNode=new D8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=X6.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=O4.all(new W4(Z.foreground,1,"solid")),q=new VO({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let M=D.trim();if(X&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new N6({children:[new g0({decoration:{color:z1.default()},child:new _1({text:new i(">",new J1({color:Z.foreground}))})}),new c6({child:q})]}),H=new g0({padding:z0.symmetric(1,0),child:new _1({text:new i("",void 0,[new i("Command: ",new J1({color:Z.foreground})),new i(this.widget.props.commandName,new J1({color:z1.yellow,bold:!0}))])})}),z=[];if(V)z.push(new i("Enter",new J1({color:Y.keybind}))),z.push(new i(" to submit, ",new J1({color:Z.foreground,dim:!0})));z.push(new i("Esc",new J1({color:Y.keybind}))),z.push(new i(" to cancel",new J1({color:Z.foreground,dim:!0})));let U=new g0({padding:z0.symmetric(1,0),child:new _1({text:new i("",void 0,z)})});return new g0({decoration:{border:K,color:z1.default()},padding:z0.all(1),child:new v0({children:[H,new X0({height:1}),W,new Z5,U]})})}}class q51 extends d0{props;constructor(J){super();this.props=J}createState(){return new rY6}}zH();class sY6 extends u0{controller=new h$;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new D8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=VU)return!1;let Q=CC(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=X6.of(J),{colors:Z,app:Y}=Q,G=b4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new AO({controller:this.controller,triggers:[new WN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:t8.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new F8({focusNode:this.focusNode,child:K}),W=new g0({constraints:new w6({maxHeight:V}),padding:z0.symmetric(1,0),child:q}),H=new g0({padding:z0.symmetric(1,0),child:new _1({text:new i("",void 0,[new i("Command: ",new J1({color:Z.foreground})),new i(this.widget.props.commandName,new J1({color:z1.yellow,bold:!0}))])})}),z=new g0({padding:z0.symmetric(1,0),child:new _1({text:this.isConfirmingClearInput?new i("",void 0,[new i("Esc",new J1({color:Y.keybind})),new i(" again to clear input",new J1({color:Z.foreground,dim:!0}))]):new i("",void 0,[new i("Press ",new J1({color:Z.foreground,dim:!0})),new i("Enter",new J1({color:Y.keybind})),new i(" to submit, ",new J1({color:Z.foreground,dim:!0})),new i("Esc",new J1({color:Y.keybind})),new i(" to clear",new J1({color:Z.foreground,dim:!0}))])})}),U=[H,new X0({height:1}),new c6({child:W}),new X0({height:1}),z];return new g0({decoration:{border:O4.all(new W4(Z.foreground,1,"solid")),color:z1.default()},padding:z0.all(1),child:new v0({children:U})})}}class iC extends d0{props;constructor(J){super();this.props=J}createState(){return new sY6}}import{isDeepStrictEqual as BO8}from"node:util";var zO8=/[\\/_ +.#"@[({&]/,FO8=/[\\/_ +.#"@[({&]/g,UO8=/[\s-]/,tY6=/[\s-]/g;function H51(J,Q,Z,Y,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Y.charAt(G),W=Z.indexOf(q,X),H=0,z,U,D,M;while(W>=0){if(z=H51(J,Q,Z,Y,W+1,G+1,V),z>H){if(W===X)z*=1;else if(UO8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(X,W-1).match(tY6),M&&X>0)z*=Math.pow(0.999,M.length)}else if(zO8.test(J.charAt(W-1))){if(z*=0.8,D=J.slice(X,W-1).match(FO8),D&&X>0)z*=Math.pow(0.999,D.length)}else if(z*=0.3,X>0)z*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Z.charAt(W-1)===Y.charAt(G+1)||Y.charAt(G+1)===Y.charAt(G)&&Z.charAt(W-1)!==Y.charAt(G))){if(U=H51(J,Q,Z,Y,W+1,G+2,V),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Z.indexOf(q,W+1)}return V[K]=H,H}function W51(J){return J.toLowerCase().replace(tY6," ")}function eY6(J,Q){let Z=H51(J,Q,W51(J),W51(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,G=0;for(let K of Y){let q=H51(J,K,W51(J),W51(K),0,0,{});if(q===0)return Z;X+=q,G+=K.length}let V=X/Y.length*0.95;return Math.max(Z,V)}return Z}class nC{}class aC{}class z51{}class F51{}class JX6 extends d0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new QX6}}class QX6 extends u0{build(J){return this.widget.onContext(J),this.widget.child}}function NO8(J,Q){if(J==="")return{matches:!0,score:1};let Z=eY6(Q,J);return{matches:Z>0.15,score:Z}}class AJ extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new ZX6}}class ZX6 extends u0{controller=new h$;focusNode;scrollController=new i5;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new D8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),c8.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(!BO8(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 z51){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof F51)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...NO8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,Y)=>this.widget.props.sortItems(Z,Y,J):(Z,Y)=>Y.score-Z.score).map((Z)=>Z.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 Z=0,Y=Q.size.height;G91(J,{top:Z,bottom:Y},{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(),c8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!X){if(Y)this.widget.props.onAccept(Y)}}};build(J){let Q=X6.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=O4.all(new W4(Z.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new VO({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new QX({shortcuts:new Map([[new V4("ArrowDown"),new nC],[new V4("ArrowUp"),new aC],[new V4("Tab"),new nC],[new V4("Tab",{shift:!0}),new aC],[new V4("n",{ctrl:!0}),new nC],[new V4("p",{ctrl:!0}),new aC],[new V4("Enter"),new z51],[new V4("Escape"),new F51]]),focusNode:this.focusNode,child:V}),q=new BJ({actions:new Map([[nC,new P8(this.invoke)],[aC,new P8(this.invoke)],[z51,new P8(this.invoke)],[F51,new P8(this.invoke)]]),child:K}),W=new N6({children:[new g0({decoration:{color:z1.default()},child:new _1({text:new i(">",new J1({color:Z.foreground}))})}),new c6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new X0({height:10,child:new x4({child:new _1({text:new i(L,new J1({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new c6({child:new x4({child:new _1({text:new i(this.widget.props.emptyStateText,new J1({color:Z.foreground,dim:!0}))})})});else{let L=Y.map((A,E)=>{let I=E===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,R;if(this.widget.props.renderItem)R=this.widget.props.renderItem(A,I,P,J);else{let k=I?z1.yellow:void 0,y=I?z1.black:Z.foreground;R=new g0({decoration:k?{color:k}:void 0,padding:z0.symmetric(2,0),child:new _1({text:new i(this.widget.props.getLabel(A),new J1({color:y,dim:P}))})})}return new JX6(new K8({onClick:(k)=>this.handleItemClick(E,k.clickCount),child:R}),(k)=>{this.itemContexts[E]=k})});H=new v0({children:L,crossAxisAlignment:"start"})}let z=new c6({child:new K8({onScroll:this.handleScroll,opaque:!1,child:new W5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new g0({padding:z0.symmetric(1,0),child:new _1({text:new i(this.widget.props.title,new J1({color:z1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new X0({height:1}),z),this.controller.text!==""){let L=Y.length>0?Y[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new g0({padding:z0.vertical(1),child:new x4({child:A})}));else U.push(new X0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new g0({decoration:{border:X,color:z1.default()},padding:z0.symmetric(1,0),child:new v0({children:U})})}}function YX6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class uy1 extends E6{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>YX6(X.pubDate).length));return new AJ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=X6.of(K),{colors:W}=q,H=G?z1.yellow:void 0,z=G?z1.black:W.foreground,U=z1.index(8),D=(M,L)=>new X0({width:L,child:N6.end([new _1({text:new i(M,new J1({color:U}))})])});return new g0({decoration:H?{color:H}:void 0,padding:z0.symmetric(2,0),child:new N6({children:[new c6({child:new _1({text:new i(X.title,new J1({color:z})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),D(YX6(X.pubDate),Z)]})})}})}}class py1 extends d0{createState(){return new XX6}}class XX6 extends u0{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 _1({text:new i("●",new J1({color:this.isGreen?z1.green:z1.index(8),bold:!0})),maxLines:1})}}function DO8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Y.set(V.id,K.type);let q=K.threadID,W=Z.get(q)||[];W.push(V),Z.set(q,W)}else X.push(V)}return YX.flatten(X,(V)=>Z.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function dy1(J,Q,Z){return new _1({text:new i(`${J}${Q}`,new J1({color:Z})),maxLines:1})}function MO8(J,Q,Z,Y){return[dy1("+",J,Y.success),Z5.horizontal(1),dy1("~",Q,Y.warning),Z5.horizontal(1),dy1("-",Z,Y.destructive)]}class U51 extends E6{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 Z=this.props.recentThreadIDs||[],Y=this.props.currentThreadID,X=[...Q].sort((H,z)=>{if(Y){if(H.id===Y)return-1;if(z.id===Y)return 1}let U=Z.indexOf(H.id),D=Z.indexOf(z.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),G=DO8(X),V=Math.max(0,...G.map((H)=>H.description.timeAgo.length)),K=X6.of(J),q=new z6({padding:z0.symmetric(0,1),child:new x4({child:new _1({text:new i("",new J1({color:K.colors.foreground,dim:!0}),[new i("Ctrl+T",new J1({color:z1.blue,dim:!0})),new i(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new J1({color:K.colors.foreground,dim:!0}))])})})});return new AJ({items:G,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:q,renderItem:(H,z,U,D)=>{let M=X6.of(D),{colors:L}=M,A=z?z1.yellow:void 0,E=z?z1.black:L.foreground,I=z1.index(8),P=(Z1,t)=>new X0({width:t,child:N6.end([new _1({text:new i(Z1,new J1({color:I}))})])}),R=this.props.threadViewStates[H.id],k=[],y=H.relationshipType==="handoff",x=new F91;if(H.depth>0){let Z1=[],t=H.ancestorsAreLast.slice(1);for(let V1 of t)Z1.push(new i(x.getAncestorPrefix(V1),new J1({color:x.connectorColor,dim:x.connectorDim})));let p=H.isLast?x.elbow:x.tee,e=x.getConnectorText(p);Z1.push(new i(e,new J1({color:x.connectorColor,dim:x.connectorDim}))),k.push(new _1({text:new i("",void 0,Z1)}))}let b=[],d=this.props.currentThreadID===H.id?new i("(current) ",new J1({color:z1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new i("(visited) ",new J1({color:L.foreground,dim:!0})):null;if(d)b.push(new _1({text:d}));if(R){if(R.state==="active"&&(R.interactionState==="tool-running"||R.interactionState===!1))b.push(new py1),b.push(new X0({width:1}))}let m=H.title;if(H.relationshipType==="fork"){let Z1=m.match(/^Forked\((\d+)\): /);if(Z1)m=m.slice(Z1[0].length);else while(m.startsWith("Forked: "))m=m.slice(8);b.push(new _1({text:new i("[fork] ",new J1({color:z1.blue}))}))}else if(y)b.push(new _1({text:new i("[handoff] ",new J1({color:z1.index(208)}))}));if(b.push(new c6({child:new _1({text:new i(m,new J1({color:E})),overflow:"ellipsis",maxLines:1})})),b.push(new X0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let Z1=z?{success:I,warning:I,destructive:I}:L;b.push(...MO8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,Z1)),b.push(new X0({width:2}))}return b.push(P(H.description.timeAgo,V)),new g0({decoration:A?{color:A}:void 0,padding:z0.symmetric(2,0),child:new N6({children:[...k,...b]})})}})}}function $X6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class cy1 extends E6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>$X6(X.pubDate).length));return new AJ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=X6.of(K),{colors:W}=q,H=G?z1.yellow:void 0,z=G?z1.black:W.foreground,U=z1.index(8),D=X.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new X0({width:A,child:N6.end([new _1({text:new i(L,new J1({color:U}))})])});return new g0({decoration:H?{color:H}:void 0,padding:z0.symmetric(2,0),child:new N6({children:[new c6({child:new _1({text:new i(X.title,new J1({color:z})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new _1({text:new i(D,new J1({color:U})),maxLines:1}),new X0({width:2}),M($X6(X.pubDate),Z)]})})}})}}class ly1 extends E6{props;constructor(J){super();this.props=J}build(){return new x4({child:new _1({text:new i("",void 0,[new i(`Forked to new thread:
4712
4712
 
4713
4713
  `,new J1({color:z1.white,dim:!0})),new i(`"${this.props.newThreadTitle||"Untitled"}"`,new J1({color:z1.white}))]),textAlign:"center"})})}}U0();class GX6 extends u0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){v.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){v.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){if(J.length===0)return null;if(J.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(J))return"Label must be lowercase alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null}buildItemsWithCreateOption(){let J=this.widget.props.currentLabels||[],Z=[...this.labels.filter((Y)=>!J.includes(Y.name))];if(this.currentQuery.trim().length>0&&!this.isLoading){let Y=this.currentQuery.trim().toLowerCase(),X=this.labels.some((V)=>V.name===Y),G=J.includes(Y);if(!X&&!G&&this.isValidLabelName(Y))Z.unshift({id:"__create__",name:Y,createdAt:"",__isCreateMarker:!0})}return Z}build(J){let Q=X6.of(J),{colors:Z}=Q,Y=this.currentQuery.trim().toLowerCase(),X=Y.length>0?this.getValidationError(Y):null;return new AJ({title:"Add Label",items:this.buildItemsWithCreateOption(),getLabel:(G)=>G.name,onAccept:(G)=>{this.widget.props.onSelect(G.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:X||"Type to create a new label",renderItem:(G,V,K,q)=>{let W=V?z1.yellow:void 0,H=V?z1.black:Z.foreground;if("__isCreateMarker"in G&&G.__isCreateMarker)return new g0({decoration:W?{color:W}:void 0,padding:z0.symmetric(2,0),child:new _1({text:new i("",void 0,[new i("Create: ",new J1({color:H})),new i(G.name,new J1({color:H,bold:!0}))])})});return new g0({decoration:W?{color:W}:void 0,padding:z0.symmetric(2,0),child:new _1({text:new i(G.name,new J1({color:H}))})})},filterItem:(G,V)=>{let K=this.currentQuery;if(this.currentQuery=V,K!==V)this.setState();if("__isCreateMarker"in G&&G.__isCreateMarker)return!0;let W=V.trim().toLowerCase();return W.length===0||G.name.includes(W)}})}}class iy1 extends d0{props;constructor(J){super();this.props=J}createState(){return new GX6}}class tq extends d0{props;constructor(J){super();this.props=J}createState(){return new VX6}}class VX6 extends u0{_spinner=new b$;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=X6.of(J),{colors:Z}=Q,Y=O4.all(new W4(Z.foreground,1,"solid")),X=this._spinner.toBraille(),G=new _1({textAlign:"center",text:new i("",void 0,[new i(X,new J1({color:z1.yellow})),new i(" ",void 0),new i(this.widget.props.message,new J1({color:Z.foreground}))])}),K=[new c6({child:new v0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[G]})})];if(this.widget.props.onAbort)K.push(new X0({height:2,child:new g0({padding:z0.symmetric(2,0),child:new _1({text:new i("",new J1({dim:!0}),[new i("Press ",new J1({color:Z.foreground})),new i("Esc",new J1({color:Z.info})),new i(" to cancel",new J1({color:Z.foreground}))])})})}));let q=new g0({decoration:new M8(z1.default(),Y),child:new X0({width:60,height:7,child:new v0({mainAxisAlignment:"start",children:K})})});if(this.widget.props.onAbort)return new F8({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}class xV extends d0{props;constructor(J){super();this.props=J}createState(){return new KX6}}class KX6 extends u0{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof kV}build(J){let Q=this.widget.props.message,Z=(()=>{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=q91(Q);return{title:W.title,type:W.type,description:W.description}})(),Y=Z.type==="error"?z1.red:z1.yellow,X=O4.all(new W4(z1.default(),1,"solid")),G=new g0({padding:z0.symmetric(1,0),child:new _1({text:new i(Z.title,new J1({color:Y,bold:!0}))})}),V=this.isWidgetMessage(Q)?Q.widget:new _1({text:new i(Z.description,new J1({color:z1.default()})),selectable:!0}),K=new c6({child:new XO({child:new g0({padding:z0.symmetric(1,0),child:V})})}),q=new g0({padding:z0.symmetric(1,0),child:new _1({text:this.widget.props.onRetry?new i("",void 0,[new i("Press ",new J1({color:z1.default(),dim:!0})),new i("R",new J1({color:z1.yellow})),new i(" to retry, ",new J1({color:z1.default(),dim:!0})),new i("Esc",new J1({color:z1.yellow})),new i(" to cancel",new J1({color:z1.default(),dim:!0}))]):new i("Press any key to close",new J1({color:z1.default(),dim:!0,italic:!0}))})});return new F8({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 g0({decoration:{border:X,color:z1.default()},padding:z0.all(1),child:new v0({mainAxisAlignment:"center",children:[G,new X0({height:1}),K,q]})})})}}class ny1 extends E6{build(){return new x4({child:new _1({text:new i("",void 0,[new i(`✓ Thread Shared
4714
4714
 
@@ -4799,7 +4799,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
4799
4799
  `)?`${K}...`:X,W=new J1({color:z1.index(8)}),H=[new i(q,W)];if(V>0){let z=new J1({color:Z.success});for(let U=1;U<=V;U++)H.push(new i(" ")),H.push(new i(`[${U}]`,z))}return new z6({padding:z0.only({bottom:0}),child:new N6({crossAxisAlignment:"start",children:[new z6({padding:z0.only({right:1}),child:new _1({text:new i("•",new J1({color:z1.index(8)}))})}),new c6({child:new _1({text:new i("",void 0,H)})})]})})}}class kx1 extends d0{createState(){return new N$6}}class N$6 extends u0{_animationTimer;_visible=!0;initState(){super.initState(),this._startAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._visible=!this._visible})},500)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=new J1({color:z1.red}),Z=new J1({color:this._visible?z1.red:z1.transparent()});return new N6({children:[new _1({text:new i("⏺",Z)}),new X0({width:1}),new _1({text:new i("Replay",Q)})]})}}class yx1 extends E6{entry;width;constructor({key:J,entry:Q,width:Z}){super({key:J});this.entry=Q,this.width=Z}build(J){let Z=X6.of(J).colors.mutedForeground,Y=this.entry,X=Y.authors[0]?.name||"Community";if(X.includes("@"))X=X.split("@")[0]??X;let G=" · ",V=50,K=this.truncateToWidth(Y.title,V),q=`${G}${K}`,W=Math.max(1,this.width-q.length-2),H=Y.description.replace(/\s+/g," ").trim(),z=`@${X}: ${H}`,U=this.truncateToWidth(z,W),D=new _1({text:new i(U,new J1({color:Z,dim:!0}))}),M=new _1({text:new i(q,new J1({color:Z,dim:!0}))});return new K8({onClick:()=>h3(J,Y.link),cursor:"pointer",child:new X0({width:this.width,height:1,child:new z6({padding:z0.horizontal(1),child:new N6({children:[new c6({child:new JN(new X0({width:W,height:1,child:D}))}),M]})})})})}truncateToWidth(J,Q){if(J.length<=Q)return J;return J.slice(0,Q-1)+"…"}}i0();function fw8(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/3600000),X=Math.floor(Y/24),G=Math.floor(X/7),V=Math.floor(X/30);if(Y<1)return"Just now";if(Y<24)return`${Y}h ago`;if(X<7)return`${X}d ago`;if(G<=4)return`${G}w ago`;return`${V}mo ago`}class xx1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Z)=>{let Y=this.threadHistoryService.observeThreadList().subscribe((X)=>{Y.unsubscribe(),Z(X)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(Q6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((Y)=>{if(!Q.trim())return!0;let X=Y.title?.toLowerCase()||"untitled",G=Y.id.toLowerCase(),V=Q.toLowerCase();return X.includes(V)||G.includes(V)}).map((Y)=>{let X=new Date(Y.userLastInteractedAt),G=fw8(X),V=Y.id.slice(-8),K=Y.env?.initial.trees?.[0]?.uri;return{id:Y.id,title:Y.title||"Untitled",updatedAt:new Date(Y.userLastInteractedAt).toISOString(),description:{timeAgo:G,title:Y.title||"Untitled",shortThreadID:V},diffStats:Y.summaryStats?.diffStats,workspaceURI:K,parentRelationships:Y.parentRelationships}})}}U0();S8();class vx1{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new i5;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){v.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){v.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(NM()).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 D$6(J,Q){switch(J){case"update-available":return[new i("A newer Amp is available. Run ",new J1({color:Q.foreground,dim:!0})),new i("amp update",new J1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new i("Update complete, run ",new J1({color:Q.foreground,dim:!0})),new i("amp update",new J1({color:Q.warning})),new i(" to see warnings",new J1({color:Q.foreground,dim:!0}))];case"update-error":return[new i("Update failed, run ",new J1({color:Q.foreground,dim:!0})),new i("amp update",new J1({color:Q.warning})),new i(" to see warnings",new J1({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function uw8(J){return new Promise((Q)=>{bw8("git",["branch","--show-current"],{cwd:J},(Z,Y)=>{if(Z){Q(null);return}let X=Y.trim();Q(X||null)})})}class P$6 extends d0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new px1}}class px1 extends u0{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;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;threadCostInfoLastUsageLedgerLength=0;lastInferenceState=void 0;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;paletteShowOptions=null;threadsForPicker=[];clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new vx1;previewThread=null;planScrollController=(()=>{let J=new i5;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new i5;return J.followMode=!1,J})();filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new D8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new D8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;threadFeedReader=null;currentThreadFeedEntry=null;threadFeedEntries=[];threadFeedSubscription=null;threadFeedRotationTimer=null;threadFeedHidden=!1;threadFeedTickerQueue=[];hasSubmittedFirstMessage=!1;currentUserInfo=null;newsFeedReader=null;newsFeedEntries=[];newsFeedSubscription=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;previousThreadIdForHint=null;pendingMCPServers=[];mcpTrustSubscription=null;mcpServers=[];mcpServersSubscription=null;cacheTimerState=null;cacheTimerSubscription=null;agentModeController=null;freeTierStatus={canUseAmpFree:!1};agentModePulseSeq=0;agentModeSlideProgress=null;agentModeSlideTimer=null;updateState="hidden";updateServiceSubscription=null;toastController=new w_1;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];async initThreadFeed(){let J=await K6(this.widget.dependencies.configService.config);if(J.settings["feed.enabled"]===!1)this.threadFeedHidden=!0;let Q=J.settings.url,Z=Q.includes("localhost")||Q.includes("127.0.0.1");try{let V=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService});if(V.ok){let K=V.result,q="user"in K?K.user:K;this.currentUserInfo={username:q.username??void 0,displayName:q.displayName??void 0};let W="ffe10a0c-6c42-41ce-a3a6-38990fd6caf8";if(!Z&&K.team?.id!==W)return}else return}catch(V){v.debug("Failed to fetch user info for thread feed filtering",V);return}let Y="/threads.rss",X=async(V,K)=>{let q=V instanceof Request?V.url:V.toString();return T3(q,K,this.widget.dependencies.configService)},G=GT1();G.get("entries").then((V)=>{if(V){let K=this.filterEntries(V);if(this.threadFeedEntries=K,K.length>0&&!this.currentThreadFeedEntry){let q=[...K].sort((H,z)=>z.pubDate.getTime()-H.pubDate.getTime());this.threadFeedTickerQueue=[...q,...this.threadFeedTickerQueue];let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}),this.threadFeedReader=new bS1(G,X,{url:Y}),this.threadFeedSubscription=this.threadFeedReader.stream().subscribe({next:(V)=>{try{let K=this.filterEntries(V);if(K.length>0){this.threadFeedEntries=[...K,...this.threadFeedEntries];let q=[...K].sort((W,H)=>H.pubDate.getTime()-W.pubDate.getTime());if(this.threadFeedTickerQueue=[...q,...this.threadFeedTickerQueue],!this.currentThreadFeedEntry){let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}catch(K){v.error("Thread feed: error in next handler",K)}},error:(V)=>{v.error("Thread feed error:",V)}}),this.resetThreadFeedRotation()}filterEntries(J){if(!this.currentUserInfo)return J;let{username:Q,displayName:Z}=this.currentUserInfo;return J.filter((Y)=>{return!Y.authors.some((X)=>{let G=X.name;if(!G)return!1;return Q&&G===Q||Z&&G===Z||Q&&G.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}async initNewsFeed(){let J=async(Z)=>{return T3(Z,void 0,this.widget.dependencies.configService)},Q=GT1();this.newsFeedReader=new hS1(Q,J,"/news.rss"),this.newsFeedSubscription=this.newsFeedReader.stream().subscribe({next:(Z)=>{if(Z.length>0)this.setState(()=>{this.newsFeedEntries=[...Z,...this.newsFeedEntries]})},error:(Z)=>{v.error("News feed error:",Z)}})}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:Z,baseWpm:Y}=J,X=Q.messages;for(let G=0;G<X.length;G++){if(this.replayAbortController.signal.aborted)break;let V=X[G];if(!V)continue;if(G>0)await this.replaySleep(J.messageDelayMs);if(V.role==="user"&&Z){let W=V.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
4800
4800
  `);if(W)await this.replayTypeMessage(W,Y)}if(V.role==="assistant"){let W=V.content.some((U)=>U.type==="tool_use"),H=X[G+1],z=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&z){let U={...V,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let D=J.thread.id;this.getMessageScrollController(D).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),V]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,V],this.textController.clear()});let K=J.thread.id;this.getMessageScrollController(K).scrollToBottom()}await this.replaySleep(J.exitDelayMs),t8.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Z=J.split(/(?<=\s)/),Y=60000/Q;for(let X of Z){if(this.replayAbortController.signal.aborted)break;if(this.looksLikePastedContent(X.trim())){await this.replaySleep(150),this.textController.text=this.textController.text+X,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{}),await this.replaySleep(300);continue}let G=Y/X.length;for(let V of X){this.textController.text=this.textController.text+V,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let K=0.8+Math.random()*0.4,q=G*K;await this.replaySleep(q)}}}looksLikePastedContent(J){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(J))return!0;if(J.startsWith("/")&&J.length>10)return!0;if(/^[a-z]:\\/i.test(J))return!0;if(/^[a-f0-9]{7,40}$/i.test(J))return!0;if(/^T-[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(J))return!0;return!1}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return this.agentModeController?.getEffectiveMode()??"smart"}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Z=J.items.filter((G)=>G.type==="toolResult").filter((G)=>G.toolResult.run.status==="in-progress"||G.toolResult.run.status==="queued"),Y=J.subagentActiveTools.filter((G)=>G.toolRun.status==="in-progress"||G.toolRun.status==="queued");return[...Z,...Y].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 i(this.submitDisabledHint,new J1({color:J.foreground,dim:!0}));if(this.isExiting)return new i("Exiting...",new J1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new i("",void 0,[new i("Ctrl+C",new J1({color:Q.keybind})),new i(" again to exit",new J1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new i("",void 0,[new i("Esc",new J1({color:Q.keybind})),new i(" again to clear input",new J1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new i("",void 0,[new i("Escape",new J1({color:Q.keybind})),new i(" to close help",new J1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),G=ux1(X);return new i("",void 0,[new i("Images aren't supported in ",new J1({color:J.warning,dim:!1})),new i(X,new J1({color:G})),new i(" mode.",new J1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new i("",void 0,[new i("Esc",new J1({color:Q.keybind})),new i(" again to cancel",new J1({color:J.foreground,dim:!0}))]);return new i("",void 0,[new i("Esc",new J1({color:Q.keybind})),new i(" to cancel",new J1({color:J.foreground,dim:!0}))])}if(this.statusMessage)return new i(this.statusMessage,new J1({color:J.foreground,dim:!0}));let Z=D$6(this.updateState,J);if(Z)return new i("",void 0,Z);let Y=this.widget.dependencies.worker.thread;if(Y.agentMode==="plan"&&eA(Y))return new i("",void 0,[new i("Ctrl+O",new J1({color:Q.keybind})),new i(" → Execute Plan",new J1({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:Z}=this.widget.dependencies;if(!Q.mainThread?.id)return;let X=Q.mainThread?.messages.findIndex((G)=>G===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:X}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(G){v.error("Failed to edit message:",G)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:Y}=this.widget.dependencies,X=Q.mainThread?.id;if(!X)return;let G=Q.mainThread?.messages.findIndex((V)=>V===J);if(G===void 0||G<=0)return;try{let V=await G3.getOrCreateForThread(Z,X),K=await jR(V,Y,G-1);await this.switchToExistingThread(K)}catch(V){v.error("Failed to fork thread:",V),this.showErrorMessage(`Failed to fork thread: ${V}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:Y}=this.widget.dependencies,X=Z.mainThread;if(!X)return;let G=X.messages.findIndex((V)=>V.messageId!==void 0&&V.messageId===J.messageId);if(G===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),this.widget.dependencies.history.add(Q);let V=ZN(Q);if(V)await Y.handle({type:"thread:truncate",fromIndex:G}),this.invokeBashCommand(V.cmd,{visibility:V.visibility});else{let K=[{type:"text",text:Q}];if(this.imageAttachments.length>0)K.push(...this.imageAttachments);let q={content:K,agentMode:X.agentMode},W=G===0;if(X.agentMode&&!W&&q.agentMode!==X.agentMode){v.error(`Cannot edit message: This thread uses ${X.agentMode} mode. To change mode, create a new thread.`);return}await Y.handle({type:"user:message",message:q,index:G})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){v.error("Failed to edit message:",V)}};getAffectedFiles=async(J)=>{let{worker:Q}=this.widget.dependencies;try{return(await Q.getFilesAffectedByTruncation(J)).map(n3)}catch(Z){return v.error("Failed to get affected files:",Z),[]}};textController=new h$;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new i5);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 Y=this.searchElementTreeByKey(J.child,Q);if(Y)return Y}if(J?.children)for(let Y of J.children){let X=this.searchElementTreeByKey(Y,Q);if(X)return X}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{this.toastController.show("Selection copied to clipboard","success",2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),Y=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(pj1(Y))}}_handleTextCopy(J){if(J&&J.length>0)this.toastController.show("Selection copied to clipboard","success",2000)}textFieldKey=new n7("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 Q=ZN(J);this.currentShellModeStatus=Q?.visibility,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),c8.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(Z){let Y=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})}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}),c8.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 Yx1(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 Gx1(this.widget.dependencies.fuzzyServer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})};getCommandPaletteContext=(J)=>{let{threadState:Q,recentThreadIDs:Z}=this.widget.dependencies;if(!Q.mainThread)return null;let Y=f0.file(process.cwd()),X=T6(Y);return{recentThreadIDs:Z,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 G=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),G},setImageAttachments:(G)=>{this.setState(()=>{this.imageAttachments=G})},editorDispatch:(G)=>{switch(G.type){case"set-input":this.textController.clear(),this.textController.insertText(G.input);break;case"insert-text":this.textController.insertText(G.text);break;case"clear":this.textController.clear();break}},submitMessage:(G)=>{return this.proceedWithUserMessage(G)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,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,switchToThread:async(G)=>{return await this.switchToExistingThread(G),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(G,V,K)=>{let q=this.widget.dependencies.threadState.mainThread?.id;if(!q)throw Error("No active thread");let W=setTimeout(()=>{K.throwIfAborted()},60000);try{let H=await this.widget.dependencies.threadService.generateHandoffPrompt(q,G,V,this.widget.dependencies.configService,K);return clearTimeout(W),H}catch(H){throw clearTimeout(W),H}},handleHandoff:async(G,V)=>{let{goal:K,generatedPrompt:q,images:W}=V;if(!K&&!q)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let H=this.widget.dependencies.threadState.mainThread?.id;if(!H)return{ok:!1,error:Error("No active thread")};let z=setTimeout(()=>G.abort(new V51("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let U=await this.widget.dependencies.threadService.createHandoffThread(H,{goal:K,generatedPrompt:q,images:W},this.widget.dependencies.configService,G.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 G.signal.reason;throw U}}catch(H){return v.error("Failed to create handoff thread",H),{ok:!1,error:H instanceof Error?H:Error(String(H))}}},getGuidanceFiles:async(G)=>{if(!Q.mainThread)return[];return(await Jt({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,G)).map((K)=>({uri:K.uri,type:K.type}))},openIdePicker:()=>{this.openIdePicker()},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(G)=>{this.agentModeController?.setMode(G)},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,handleExecutePlan:async()=>{try{let G=Q.mainThread?.id;if(!G){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let V=await this.widget.dependencies.threadService.createPlanExecutionThread(G,"smart");await this.switchToExistingThread(V)}catch(G){v.error("Failed to execute plan",G),this.setState(()=>{this.displayMessage=Error(`Failed to execute plan: ${G instanceof Error?G.message:String(G)}`)})}},planFileManager:this.widget.dependencies.planFileManager,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.clustersForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:X,threadViewStates:this.widget.dependencies.workerController.threadViewStates,currentThreadFeedEntry:this.currentThreadFeedEntry,threadFeedEntries:this.threadFeedEntries,threadFeedHidden:this.threadFeedHidden,newsFeedEntries:this.newsFeedEntries,setThreadFeedHidden:(G)=>{this.setState(()=>{this.threadFeedHidden=G})},showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:this.widget.dependencies.features,showStatusMessage:(G,V=2000)=>{if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=G}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},V)}}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new xx1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.clustersForPicker=LX6(Q),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await uw8(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 Z=Date.now(),Y=`bash-${Z}-${Math.random().toString(36).substring(7)}`,X={cmd:J},G=new AbortController;this.widget.dependencies.worker.invokeBashTool(X,G.signal,Q===QN).subscribe({next:(V)=>{this.setState(()=>{if(this.bashInvocations.find((q)=>q.id===Y))this.bashInvocations=this.bashInvocations.map((q)=>q.id===Y?{...q,toolRun:V}:q);else{let q={id:Y,args:X,toolRun:V,startTime:Z,abortController:G,hidden:Q===QN};this.bashInvocations=[...this.bashInvocations,q]}})},error:()=>this.removeBashInvocation(Y),complete:()=>this.removeBashInvocation(Y)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=f26(()=>{let J=this.widget.dependencies.threadID;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(Q.ok)this.setState(()=>{this.threadCostInfo=Q.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J,Q)=>{let Z=J!==this.threadCostInfoLastUsageLedgerLength,Y=Q==="idle"&&this.lastInferenceState==="running";if(this.threadCostInfoLastUsageLedgerLength=J,this.lastInferenceState=Q,Z||Y)this.fetchThreadCostInfo()};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.agentModeController.toggle())this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};startAgentModeSlide=()=>{if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer);this.setState(()=>{this.agentModeSlideProgress=0});let J=800,Q=16,Z=Q/J;this.agentModeSlideTimer=setInterval(()=>{this.setState(()=>{if(this.agentModeSlideProgress!==null){if(this.agentModeSlideProgress=Math.min(1,this.agentModeSlideProgress+Z),this.agentModeSlideProgress>=1){if(this.agentModeSlideProgress=null,this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null}}})},Q)};handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!ky(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>=VU)return!1;let Z=CC(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Z}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(!Q.ok)v.error("Failed to destruct mysterious message",Q.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Q)=>{v.error("Failed to destruct mysterious message",Q)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Z,unlink:Y,rmdir:X,writeFile:G}=await import("node:fs/promises"),{tmpdir:V}=await import("node:os"),K=await import("node:path");try{let q=await Q(K.join(V(),"amp-edit-")),W=K.join(q,"message.amp.md");await G(W,J,"utf-8"),await SV(W);try{let H=await Z(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")v.error("Failed to read temporary file",H)}try{await Y(W),await X(q)}catch(H){v.warn("Failed to clean up temporary file",H)}}catch(q){v.error("Error opening editor:",q)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=ZN(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{this.setState(()=>{})};initState(){if(rY.getInstance().interceptConsole(),this.freeTierStatus=this.widget.dependencies.freeTierStatus,this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();t8.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),t8.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),t8.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{c8.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),K6(this.widget.dependencies.configService.config).then((Z)=>{this.paletteConfig=Z,this.agentModeController=new cS1({initialCliMode:this.widget.dependencies.initialAgentMode,sessionState:this.widget.dependencies.sessionState??null,freeTierStatus:this.freeTierStatus,initialSettings:Z.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.getCurrentWorker()?.thread??this.widget.dependencies.worker.thread}),this.agentModeController.addListener(this.agentModeListener)}),this.updateGitBranch(),this.adSubscription=HS1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{let Z=this.agentModeController?.getMode();return(Z&&j9(Z)||this.randomAd===null)&&WS1(this.lastUserInteractionTime)}).subscribe({next:(Z)=>{if(Z){let Y=gw8(16).toString("hex");this.lastAdImpressionId=Y,Promise.resolve().then(() => (g51(),b51)).then(({recordAdEvent:X})=>{let G=this.widget.dependencies.worker.thread,V=G.messages[G.messages.length-1];X("viewed",{adId:Z.id,advertiserId:Z.advertiserId,threadId:G.id,messageId:V?.messageId,impressionId:Y,placement:"tui",matchType:Z.metadata?.matchType,matchedPatterns:Z.metadata?.matchedPatterns,candidateAdPoolCount:Z.metadata?.candidateAdPoolCount,clientRegion:Z.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=Z}),c8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}});let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Z)=>{this.setState(()=>{this.pendingMCPServers=Z})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((Z)=>{this.setState(()=>{this.mcpServers=Z})}),this.cacheTimerSubscription=this.widget.dependencies.worker.cacheTimer.subscribe((Z)=>{this.setState(()=>{this.cacheTimerState=Z})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Z)=>{this.setState(()=>{this.ideStatus=Z})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Z)=>{let Y=this.widget.dependencies.getCurrentWorker();if(!Y){v.warn("No active thread worker found to handle IDE message");return}await new Promise((X)=>setTimeout(X,50)),await Y.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),v.debug("Message sent from IDE to agent",{message:Z.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Z)=>{this.textController.insertText(Z),v.debug("Appended text to CLI prompt from IDE",{text:Z.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Z)=>{this.setState(()=>{this.connectedClientsStatus=Z})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Z)=>{this.setState(()=>{this.updateState=Z})}),this.mysteriousMessageSubscription=v81(this.widget.dependencies.configService).pipe(u5((Z)=>Z!=="pending"),Q6((Z)=>f81(Z)?Z.mysteriousMessage??null:null),F4((Z,Y)=>Z?.id===Y?.id)).subscribe((Z)=>{this.setState(()=>{if(Z?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=Z,Z&&!this.mysterySequenceManager)this.mysterySequenceManager=new t81(new Map([[new s81(px1.MYSTERY_SEQUENCE),new rm]])),this.mysteryKeyInterceptorUnsubscribe=t8.instance.addKeyInterceptor((Y)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let X=this.mysterySequenceManager.handleKeyEvent(Y);if(X.consumed){if(X.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=X.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!Z)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let Y=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initThreadFeed(),this.initNewsFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener();let Q=this.widget.dependencies.threadID;if(this.threadCostInfoThreadID!==void 0&&this.threadCostInfoThreadID!==Q)this.threadCostInfo=void 0,this.threadCostInfoThreadID=void 0,this.threadCostInfoLastUsageLedgerLength=0,this.fetchThreadCostInfo();let{threadState:Z}=this.widget.dependencies;this.maybeRefetchThreadCostInfo(Z.mainThread?.usageLedger?.events.length??0,Z.viewState.state==="active"?Z.viewState.inferenceState:void 0)}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.cacheTimerSubscription)this.cacheTimerSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.threadFeedSubscription)this.threadFeedSubscription.unsubscribe();if(this.newsFeedSubscription)this.newsFeedSubscription.unsubscribe();if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null;if(this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(pj1("")),this.shouldUseProgressBar())process.stdout.write(C76())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,Y=[...J.items.filter((K)=>K.type==="toolResult").map((K)=>({toolUse:K.toolUse,toolRun:K.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((K)=>K.toolRun.status==="blocked-on-user");if(Y.length===0)return null;let X=Y[0],G=X.toolRun.status==="blocked-on-user"?X.toolRun.toAllow??[]:[],V=X.toolRun.status==="blocked-on-user"?X.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:X.toolUse,toAllow:G}],subthreadID:X.subthreadID,reason:V}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){v.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){v.error("No tool use block found in confirmation");return}if(J==="allow-all-session")jG("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(X){if(X&&X instanceof Error)this.setState(()=>{this.displayMessage=X});else v.error("Failed to write dangerouslyAllowAll setting:",X);return}if(J==="always-guarded"){let X=Q.tools[0]?.toAllow??[],G=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],V=[...X,...G];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",V,"global")}if(J==="connect-github"){let X=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await h3(this.context,X);return}if(J==="disable-librarian"){let X=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!X.includes(MY))await this.widget.dependencies.settingsStorage.set("tools.disable",[...X,MY],"global")}let Y=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let X={type:"user:tool-input",toolUse:Z.id,value:{accepted:Y}};if(Q.subthreadID)await(await G3.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(X);else await this.widget.dependencies.worker.handle(X)}catch(X){v.error("Failed to send tool confirmation:",X)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"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.agentModeController?.setMode("smart"),this.setState(()=>{this.dismissedEphemeralErrorKey=null}),v41({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 SV(Q.getSettingsFilePath())}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);await this.showErrorMessage(`Failed to open settings: ${Y}`)}};cancelStreamingMessage=async()=>{await G3.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 Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J,Q={})=>{let{recordInNavigationHistory:Z=!0}=Q;if(Z){let Y=this.widget.dependencies.worker.thread.id;if(Y!==J)this.recordNavigation(Y)}try{v.info(`[switchToExistingThread] Switching to thread: ${J}`);let Y=await this.widget.dependencies.switchToThread(J);if(v.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${Y.thread.agentMode}`),this.widget.dependencies.worker=Y,this.widget.dependencies.threadID=Y.thread.id,this.widget.dependencies.switchWorker(Y),v.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null),Y.thread.draft)if(v.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof Y.thread.draft==="string")this.textController.insertText(Y.thread.draft);else{let X=Y.thread.draft.filter((K)=>K.type==="text"),G=Y.thread.draft.filter((K)=>K.type==="image"),V=X.map((K)=>K.text).join(`
4801
4801
  `);if(V)this.textController.insertText(V);if(G.length>0)this.setState(()=>{this.imageAttachments=G})}}catch(Y){throw v.error("Failed to switch to thread:",J,Y),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,Z=s3(Q.thread)===0,Y=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&Y!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let X=[{type:"text",text:J}];if(this.imageAttachments.length>0)X.push(...this.imageAttachments);if(Z)this.startAgentModeSlide();if(await Q.handle({type:"user:message",message:{content:X,agentMode:Y}}),Z)v41({agentMode:Y});this.scrollMessageViewToBottom(),this.setState(()=>{if(this.imageAttachments=[],!this.hasSubmittedFirstMessage)this.hasSubmittedFirstMessage=!0}),c8.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((Y)=>Y.type==="handoff"&&Y.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();v41({agentMode:Q}).catch((Z)=>{v.warn("Failed to save session state on exit:",Z)}).finally(()=>{t8.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=mw8();if(J===Q)return"~";if(J.startsWith(Q+Du.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Du.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Du.sep),"…",Q.slice(-2).join(Du.sep)].join(Du.sep)}build(J){let Q=b4.of(J),Z=X6.of(J),Y=Z.base;this.themeColors=Y;let{colors:X,app:G}=Z;this.themeApp=G;let V=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,K=V.thread.agentMode&&j9(V.thread.agentMode),q=K&&this.randomAd!==null,W=!K&&this.currentThreadFeedEntry!==null&&!this.threadFeedHidden,H=Boolean(q),{threadState:z}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),D=this.widget.dependencies.replayMode,M=Boolean(D),L=z.items,A=z.mainThread||void 0,E=z.subagentToolsByParentID,I=z.todosList;if(M){let m6={...D.thread,messages:this.replayDisplayedMessages};L=cC(m6).items,A=m6,E={};let a6=qI({messages:this.replayDisplayedMessages});I=Array.isArray(a6)?a6:[]}let P=A?.id,R=A,k=M?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),y=(m6)=>new Z51({key:new n7(`preview-message-view-${m6.id}`),items:cC(m6).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:m6,focusNode:new D8({debugLabel:"PreviewFocus"})}),x=this.previewThread,b=x?x.messages.length>2000?new v0({mainAxisSize:"max",children:[new c6({child:new X0}),new z6({padding:z0.all(2),child:new x4({child:new _1({text:new i("Thread too long for preview",new J1({color:X.mutedForeground,dim:!0}))})})})]}):y(x):k?new G51({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal}):new Z51({key:P?new n7(`message-view-${P}`):void 0,items:L,subagentToolsByParentID:E,controller:P?this.getMessageScrollController(P):new i5,autofocus:!1,onCopy:M?void 0:this._handleTextCopy.bind(this),thread:R,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}),d=Math.max(Math.floor(Q.size.height*0.4),12),m=this.getCurrentEphemeralError(),a=Q.size.width<40,Z1=z.mainThread?fL0(z.mainThread):void 0,t=c91(J),p=this.buildBottomWidget(m,U,X,Z,z,I,d,H,M,Z1,this.cacheTimerState??void 0,Q,t),e=new N91({threadViewState:z.viewState,threadTokenUsage:Z1,threadID:P??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,mcpServers:this.mcpServers,isNarrow:a,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}),V1=new U91({bashInvocations:this.bashInvocations}),U1=[];if(W&&this.currentThreadFeedEntry)U1.push(new yx1({entry:this.currentThreadFeedEntry,width:Q.size.width}));let r=this.getEffectiveAgentMode(),o=this.currentShellModeStatus,l=ux1(r),H1=!o?r.length+1:0,k1=Q.capabilities.animationSupport,s=k1==="disabled"?0:k1==="slow"?30:60,g1=kK(r)?.uiHints?.fasterAnimation?3:1,R1=s>0&&this.agentModePulseSeq>0?new b9({children:[p,new f5({top:0,left:1,right:1,height:1,child:new Cx1({color:l,trigger:this.agentModePulseSeq,fps:s,speed:g1,leftOffset:H1})})]}):p;U1.push(new c6({child:b}),V1);let I0=new b9({children:[new v0({mainAxisSize:"min",children:[q?new fy1({ad:this.randomAd,onButtonClick:async()=>{let m6=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (g51(),b51)).then(({recordAdEvent:L9})=>{let w4=this.widget.dependencies.worker.thread,IJ=w4.messages[w4.messages.length-1];L9("clicked",{adId:m6.id,advertiserId:m6.advertiserId,threadId:w4.id,messageId:IJ?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:m6.metadata?.matchType,matchedPatterns:m6.metadata?.matchedPatterns,candidateAdPoolCount:m6.metadata?.candidateAdPoolCount,clientRegion:m6.metadata?.clientRegion})});if(!await h3(this.context,m6.shortDestinationUrl)){let w4=t8.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:w4,url:m6.shortDestinationUrl}})}}}):new X0({height:0}),new g0({constraints:new w6(0,Q.size.width,0,d),child:R1})]}),H?new f5({top:0,left:0,right:0,child:new C$6({userHeight:this.bottomGridUserHeight,maxHeight:d,onInitializeHeight:(m6)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(m6,d)})},onDrag:(m6)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(m6.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let a6=Math.floor(m6.localPosition.y)-this.bottomGridDragStartY,L9=Math.max(4,this.bottomGridDragStartHeight-a6),w4=Math.min(L9,d),IJ=Math.floor(w4);if(this.bottomGridUserHeight!==IJ)this.setState(()=>{this.bottomGridUserHeight=IJ})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new X0({height:0})]});U1.push(I0,new X0({height:1,child:new z6({padding:z0.horizontal(1),child:e})}));let P1=new v0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:U1}),F1=M&&D?.showIndicator!==!1?new b9({children:[P1,new f5({top:0,left:0,child:new kx1})]}):P1,Y1=new P8(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.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((a6)=>{v.error("Failed to mark message as interrupted:",a6)}),this.cancelStreamingMessage().catch((a6)=>{v.error("Failed to cancel streaming message:",a6)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return v.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.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"}),O1=new P8(()=>{return this.onExitPressed(),"handled"}),A1=new P8(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),C1=new P8(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),S1=new P8(()=>{return LJ.instance.toggleAll(),"handled"}),c1=new P8(()=>{return this.widget.dependencies.configService.getLatest().then((m6)=>{jG("internal.showDetailedCosts",!(m6.settings["internal.showDetailedCosts"]??!1))}),"handled"}),m1=new P8(()=>{return t8.instance.toggleFrameStatsOverlay(),"handled"}),s1=new P8(()=>{return t8.instance.tuiInstance.getScreen().markForRefresh(),c8.instance.requestFrame(),"handled"}),K0=new P8(()=>{return this.toggleAgentMode(),"handled"}),q0=new P8(()=>{let a6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:L9}=this.widget.dependencies,w4=L9.mainThread?.id;return w4?this.getMessageScrollController(w4):null})();if(a6){let L9=Math.max(Math.floor(Q.size.height*0.4),10),w4=Q.size.height-L9;a6.animatePageUp(w4,100)}return"handled"}),k0=new P8(()=>{let a6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:L9}=this.widget.dependencies,w4=L9.mainThread?.id;return w4?this.getMessageScrollController(w4):null})();if(a6){let L9=Math.max(Math.floor(Q.size.height*0.4),10),w4=Q.size.height-L9;a6.animatePageDown(w4,100)}return"handled"}),f6=new P8(()=>{let a6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:L9}=this.widget.dependencies,w4=L9.mainThread?.id;return w4?this.getMessageScrollController(w4):null})();if(a6)a6.animateTo(0,100);return"handled"}),d6=new P8(()=>{let a6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:L9}=this.widget.dependencies,w4=L9.mainThread?.id;return w4?this.getMessageScrollController(w4):null})();if(a6)a6.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),Z8=new P8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:m6}=this.widget.dependencies;if(!m6.mainThread?.messages.some((L9)=>L9.role==="user"||KI(L9)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),J9=new P8((m6)=>{if(m6.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),t9=new P8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return K91().then(async(m6)=>{if(m6)try{this.handleInsertImage(m6)}finally{try{let{unlink:a6}=await import("node:fs/promises");await a6(m6)}catch{}}}),"handled"}),E0=new Map([[V4.ctrl("c"),new dm],[V4.ctrl("l"),new am],[V4.ctrl("o"),new X91],[V4.ctrl("v"),new um],[V4.alt("s"),new kC],[V4.ctrl("s"),new kC],[V4.alt("p"),new nm],[V4.ctrl("r"),new lm],[V4.alt("d"),new im],[V4.ctrl("t"),new om],[V4.key("PageUp"),new J91],[V4.key("PageDown"),new Q91],[V4.key("Home"),new Z91],[V4.key("End"),new Y91],[V4.key("Escape"),new pm],[V4.ctrl("p"),new yC("previous")],[V4.ctrl("n"),new yC("next")],[V4.key("Tab"),new sm]]);if(!u2())E0.set(V4.key("ArrowUp"),new sm);if(!1)E0.set(V4.alt("c"),new cm);let X4=new P8(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),$8=new P8(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),l8=new P8(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),K7=new Map([[pm,Y1],[am,s1],[kC,K0],[X91,X4],[um,t9],[cm,A1],[a81,C1],[lm,S1],[im,c1],[nm,m1],[om,$8],[dm,O1],[J91,q0],[Q91,k0],[Z91,f6],[Y91,d6],[sm,Z8],[yC,J9],[rm,l8]]),Q9=[F1];if(this.isShowingConsoleOverlay)Q9.push(new qx1);if(this.isShowingHelp&&this.paletteConfig)Q9.push(new zx1({commands:this.getPaletteCommands().getAllCommands()}));if(this.isShowingMCPStatusModal)Q9.push(new Zy1({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)Q9.push(new _x1({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.adActionModal)Q9.push(new hy1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(m6)=>{let a6=this.adActionModal.url;if(m6==="copy")try{await t8.instance.tuiInstance.clipboard.writeText(a6),this.setState(()=>{this.displayMessage=new ZX("Link copied to clipboard")})}catch(L9){v.error("Failed to copy to clipboard",{error:L9}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:m6}=this.widget.dependencies;Q9.push(new jx1({servers:this.pendingMCPServers,onAlwaysTrust:m6.trustAlways.bind(m6),onTrustOnce:m6.trustOnce.bind(m6),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:m6.deny.bind(m6)}))}if(this.isShowingFileChangesOverlay)Q9.push(new y_1({threadData:z}));if(this.isShowingContextDetailOverlay){let m6=this.threadCostInfo?.costBreakdownURL;Q9.push(new Wx1({thread:z.mainThread??void 0,tokenUsage:Z1??void 0,cacheTimerState:this.cacheTimerState??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:m6?()=>{h3(J,m6)}:void 0}))}if(this.isShowingConfirmationOverlay)Q9.push(new Vx1({details:this.confirmationOverlayContent}));let q7=this.getCommandPaletteContext(J);if(q7&&this.isShowingPalette&&this.paletteConfig)Q9.push(new x4({child:new $x1({commandContext:q7,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)Q9.push(new Ux1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let b5=new b9({children:Q9});if(this.isShowingJetBrainsInstaller)return new GO({child:new BJ({actions:K7,child:new QX({shortcuts:E0,debugLabel:"jetbrains-installer-shortcuts",child:new Rx1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new Nz({controller:this.toastController,child:new GO({child:new E_1({controller:this.toastController,child:new BJ({actions:K7,child:new QX({shortcuts:E0,debugLabel:"main-app-shortcuts",child:b5})})})})})}buildScrollableTodoList(J,Q,Z){return new T$6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Z})}buildBottomWidget(J,Q,Z,Y,X,G,V,K,q,W,H,z,U){if(J)return new Hx1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Kx1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new Sx1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let D=z91(Y),M=this.agentModeController?.isInRestrictedFreeMode()??!1,L=new AO({key:this.textFieldKey,controller:this.textController,triggers:q?[]:[new WN],completionBuilder:q?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:q?void 0:this.onTextSubmitted,theme:Z,placeholder:q?"Press Ctrl+C to exit":M?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!M&&!this.isShowingStandalonePalette(),shellPromptRules:D,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker,clipboard:t8.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let l=this.previousThreadIdForHint;if(l)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${l} `},onDoubleAtTrigger:q?void 0:()=>{let l=this.textController.text,H1=this.textController.cursorPosition,s=l.slice(0,H1).lastIndexOf("@@");this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:()=>{if(s!==-1){let g1=this.textController.text,R1=g1.slice(0,s)+g1.slice(s+2);this.textController.text=R1,this.textController.cursorPosition=s}},onSubmit:()=>{this.dismissPalette()},onCancel:()=>{this.dismissPalette()}})}}),A=X.mainThread?.queuedMessages??[],E=Array.isArray(G)&&G.length>0,I=Array.isArray(A)&&A.length>0,P=X.mainThread?.agentMode==="plan"&&eA(X.mainThread),R,k;if(P){if(R=new JN(new Y51({thread:X.mainThread,onExecute:async()=>{let l=this.getCommandPaletteContext();if(l)await this.getPaletteCommands().execute("execute-plan",l,void 0,new AbortController)},onEdit:async()=>{try{let l=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:H1}=await this.widget.dependencies.planFileManager.ensureSync(X.mainThread.id);t8.instance.tuiInstance.suspend();let{execSync:k1}=await import("child_process");k1(`${l} "${H1}"`,{stdio:"inherit"}),t8.instance.tuiInstance.resume()}catch(l){v.error("Failed to edit plan",l),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:Y}),{clipBehavior:"antiAlias"}),I)k=new h51({queuedMessages:A});else if(E)k=this.buildScrollableTodoList(G,this.isTextfieldAndAutocompleteFocused&&!M,Y)}else R=I?new h51({queuedMessages:A}):void 0,k=E?this.buildScrollableTodoList(G,this.isTextfieldAndAutocompleteFocused&&!M,Y):void 0;let y=[],x=this.currentShellModeStatus;if(x)y.push({child:new _1({text:new i(x==="hidden"?"shell mode (incognito)":"shell mode",new J1({color:x==="hidden"?Y.app.shellModeHidden:Y.app.shellMode}))}),position:"top-left"});let d=this.connectedClientsStatus&&this.connectedClientsStatus.enabled?this.connectedClientsStatusExpanded?(this.connectedClientsStatus?.clientID?.length??7)+3:3:0,m=this.agentModeController?.getVisibleModes()??[];if(!x&&m.length>1){let l=this.previewThread,H1=l?l.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),k1=ux1(H1),s=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,g1=l??s.thread,R1=s3(g1)>0,I0=this.agentModeSlideProgress!==null,P1,o1;if(I0){P1="top-left";let Y1=z.size.width-H1.length-4-d;o1=Math.floor(this.agentModeSlideProgress*Y1)}else if(R1)P1="top-right",o1=d;else P1="top-left",o1=void 0;if(l)y.push({child:new _1({text:new i(H1,new J1({color:k1}))}),position:P1,offsetX:o1});else{let F1=!R1&&!I0,Y1=new _1({text:new i(H1,new J1({color:k1}))});y.push({child:F1?new K8({child:Y1,onClick:this.toggleAgentMode,cursor:"pointer"}):Y1,position:P1,offsetX:o1})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let l=this.connectedClientsStatus,H1=l.mode||"disconnected",k1=!!l.errorMessage,s=l.clientID||"unknown",g1,R1;if(k1)g1="●",R1=z1.red;else if(H1==="presence")g1="○",R1=z1.yellow;else if(H1==="connected"&&l.connected)g1="●",R1=z1.green;else g1="○",R1=z1.yellow;let I0=this.connectedClientsStatusExpanded?`${s} ${g1}`:g1;y.push({child:new K8({child:new _1({text:new i(I0,new J1({color:R1}))}),onClick:this.toggleConnectedClientsStatus,cursor:"pointer"}),position:"top-right",offsetX:-2})}let a=q?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:X.mainThread?.env?.initial.trees?.[0]?.uri,Z1;if(a)Z1=f0.parse(a).fsPath;else Z1=process.cwd();let t=this.toHomeRelative(Z1),p=this.shorten(t),e=!q&&this.currentGitBranch?`${p} (${this.currentGitBranch})`:p;if(y.push({child:new _1({text:new i(e,new J1({color:Z.foreground,dim:!0}))}),position:"bottom-right"}),this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0&&this.textController.text.trim()==="")y.push({child:new _1({text:new i("",void 0,[new i("press ",new J1({color:Z.foreground,dim:!0})),new i("enter",new J1({color:Y.app.keybind})),new i(" to reference the previous thread",new J1({color:Z.foreground,dim:!0}))])}),position:"bottom-left"});let U1=this.previewThread,r=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(s3(r.thread)>0&&!x&&!U1){let l=[],H1=new J1({color:Z.foreground,dim:!0}),k1=new i(" · ",H1);if(W){let s=W.totalInputTokens/W.maxInputTokens,g1=Math.round(s*100),R1=Math.max(0,Math.min(g1,100)),I0=B91(s,W.maxInputTokens),P1=H1;if(I0==="danger")P1=new J1({color:Z.destructive});else if(I0==="warning")P1=new J1({color:Z.warning});else if(I0==="recommendation")P1=new J1({color:Y.app.recommendation});let o1=Math.round(W.maxInputTokens/1000);l.push(new i(`${R1}% of ${o1}k`,P1))}if(U&&this.threadCostInfo){let s=A51(this.threadCostInfo,{colors:{foreground:Z.foreground},dim:!0});if(s.length>0){if(l.length>0)l.push(k1);l.push(...s)}}if(U&&H){let s=X.viewState.state==="active"&&X.viewState.inferenceState==="idle",g1=v26(H,s);if(g1){if(l.length>0)l.push(k1);let R1=H1;if(g1.urgency==="warning")R1=new J1({color:Z.warning});l.push(new i(g1.text,R1))}}if(l.length>0){let s=new _1({text:new i("",void 0,l)});y.push({child:U?new K8({child:s,onClick:this.showContextDetailOverlay,cursor:"pointer"}):s,position:"top-left"})}}return new C_1({leftChild:new c6({child:L}),rightChild1:R,rightChild2:k,maxHeight:V,overlayTexts:y,borderColor:M||!this.isTextfieldAndAutocompleteFocused?z1.index(8):void 0,hasBanner:K,userHeight:this.bottomGridUserHeight,onInitializeHeight:(l)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(l,V)})},onDrag:(l)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(l.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let H1=Math.floor(l.localPosition.y)-this.bottomGridDragStartY,k1=Math.max(4,this.bottomGridDragStartHeight-H1),s=Math.min(k1,V),g1=Math.floor(s);if(this.bottomGridUserHeight!==g1)this.setState(()=>{this.bottomGridUserHeight=g1})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!K})}}async function dx1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)t8.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let Y=()=>null,G=!1,V=new qz(G,1000,J.inspectorPort),K=J.features.find((A)=>A.name===FI.AMP_CONNECT)?.enabled??!1,q=new xy1({threadService:J.threadService,worker:J.worker,builder:(A,E,I,P,R,k)=>{if(Y=R,J.threadDependencies&&K)pS1(J.threadDependencies,J.configService,R,P,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((b)=>{v.error("Failed to start automatic presence:",b)});let y=R(),x={...J,worker:y,threadID:y.thread.id};return new P$6({...x,threadState:E,workerController:I,switchWorker:P,getCurrentWorker:R,recentThreadIDs:k})}}),W=new j_1({configService:J.configService,child:q}),H=new Yy1({configService:J.configService,child:W}),z=new B_1(H),U=new X6({data:xC.fromBaseTheme(v$.default()),child:z});try{await YS1(U,{onRootElementMounted:(A)=>{if(v.info("TUI input ready for user interaction"),G)V.start(A)}})}finally{if(G)V.stop();if(J.threadDependencies&&K){let{stopGlobalSession:A}=await Promise.resolve().then(() => (dS1(),i36));A()}}let M=Y()?.thread.id||J.threadID,L=await J.threadService.get(M);if(L&&L.messages.length>0){let A=`${J.ampURL.replace(/\/$/,"")}/threads/${M}`;FJ6(L,A,J.stdout)}}function ux1(J){let Z=kK(J)?.uiHints?.secondaryColor;if(Z)return z1.rgb(Z.r,Z.g,Z.b);return pw8(J)}class T$6 extends d0{props;constructor(J){super();this.props=J}createState(){return new R$6}}class R$6 extends u0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,controller:Z,appTheme:Y}=this.widget.props;return new N6({crossAxisAlignment:"stretch",children:[new c6({child:new W5({controller:Z,autofocus:!1,child:new vy1({todos:Q})})}),new MJ({controller:Z,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:G}=Z,V=this.viewportHeight,K=X+V;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(V,1),scrollOffset:Math.max(G,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let G=Y.children||[];for(let V of G){if(V&&"size"in V){let q=V.size;if(typeof q?.height==="number"&&q.height>0)return q.height}let K=Q(V,X+1);if(K>0)return K}}return 0},Z=Q(J);if(Z>0)return Z;if("size"in J){let Y=J.size;if(typeof Y?.height==="number"&&Y.height>0)return Y.height}return this.viewportHeight}}class C$6 extends E6{props;constructor(J){super();this.props=J}build(J){return new K8({child:new X0({height:1}),cursor:k9.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let Y=J.findRenderObject()?.size.height??0;if(Y>0){this.props.onInitializeHeight(Y);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function pw8(J){let Q=0;for(let X=0;X<J.length;X++){let G=J.charCodeAt(X);Q=(Q<<5)-Q+G,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],Y=Math.abs(Q)%Z.length;return z1.index(Z[Y])}ZS1();try{if(process.platform==="win32")await Promise.resolve().then(() => W6(Fj(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){o$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
4802
- `)}var Mf1=Df1.join(aU0||Df1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function qR8(J){process.emitWarning=function(Q,Z,Y,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Z||"Warning",K=!1;J.warn(G,{name:V,code:Y})}}function n$(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")jG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")jG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")jG("model.sonnet",Q.useSonnet)}async function Af1(J){try{await GR8(Df1.dirname(Mf1),{recursive:!0}),await VR8(Mf1,J,"utf-8")}catch(Q){v.debug("Failed to save last thread ID",Q)}}async function WR8(){try{return(await Qq6(Mf1,"utf-8")).trim()}catch(J){return null}}var tK6=[{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??j$,description:`Custom settings file path (overrides the default location ${j$})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(v).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${qj1})`},{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:u2(),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:ZI.SMART.key,description:`Set the agent mode (${dX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:dX().map((J)=>J.mode)}],eK6=(J)=>("deprecated"in J)&&J.deprecated===!0,HR8=(J)=>("hidden"in J)&&J.hidden===!0,zR8=(J)=>("default"in J),FR8=(J)=>("default"in J)?J.default:void 0;function UR8(J,Q){let Z=Q.args[0],Y=Q.commands.map((G)=>G.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let G=Y.filter((K)=>Z.includes(K)||K.includes(Z)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new j8(C$.unknownCommand(Z),1,V)}}var Zq6=null;function Vj5(){return Zq6}function mu(J){return{...J,getThreadEnvironment:W41,vfs:zj0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Ev(J.fileSystem),generateThreadTitle:Gr0,deleteThread:(Q)=>J.threadService.delete(Q)}}var Of1=f0.file(KR8.homedir()),Yq6=process.env.XDG_CONFIG_HOME?f0.file(process.env.XDG_CONFIG_HOME):n0.joinPath(Of1,".config");async function a$(J,Q){iL0("0.0.1765237900-gbaf2e6");let Z=rz1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([f0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Of1,userConfigDir:Yq6}),{initializeCLITelemetry:Y}=await Promise.resolve().then(() => (g51(),b51));Y(Z);let X=await Z.getLatest();v.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=z16({configService:Z}),K=new Map,q=()=>K.clear(),W=new HN1(Z,J.settings.getWorkspaceRootPath()),H=LC0({configService:Z,trustStore:W,createOAuthProvider:async(t,p,e)=>{let V1=`${t}:${p}`,U1=K.get(V1);if(U1)return v.debug("Reusing existing OAuth provider for server",{serverName:t,serverUrl:p}),U1;v.debug("Creating OAuth provider for server",{serverName:t,serverUrl:p});let r=(async()=>{let o=new xM(J.secrets),l=await o.getClientInfo(t,p),H1=e?.scopes??l?.scopes,k1=new xB1({storage:o,serverName:t,serverUrl:p,clientId:e?.clientId??l?.clientId,clientSecret:e?.clientSecret??l?.clientSecret,authUrl:e?.authUrl??l?.authUrl,tokenUrl:e?.tokenUrl??l?.tokenUrl,scopes:H1});return v.debug("OAuth provider created",{serverName:t,serverUrl:p,hasManualClientId:!!(e?.clientId??l?.clientId),willUseDCR:!(e?.clientId??l?.clientId),scopes:H1}),k1})();return K.set(V1,r),r}}),z=H61({configService:Z,filesystem:r8,spawn:wA}),{initializeToolProviders:U,startToolProviders:D}=await Promise.resolve().then(() => (sK6(),rK6)),M;if(J.executeMode){let t=await U({toolService:G,providers:[H,z],initialTimeout:15000});M=t.registrations;for(let[p,e]of t.initErrors)v.warn(`${p} provider initialization slow or failed:`,e)}else M=D({toolService:G,providers:[H,z]});if(Q.jetbrains)HI("JetBrains");else if(Q.ide&&D56())HI("VS Code");else if(Q.ide&&M56())HI("Neovim");if(J.executeMode)nL0(!0);let L,A=F2.status.pipe(Q6((t)=>Boolean(t.connected&&t.authenticated)),F4()).subscribe((t)=>{if(t){if(!L)L=G.registerTool($t0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let t=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new O41(process.cwd(),{alwaysIncludePaths:t},!0)}else E=new class extends O41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(w5.write(`No API key found. Starting login flow...
4802
+ `)}var Mf1=Df1.join(aU0||Df1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function qR8(J){process.emitWarning=function(Q,Z,Y,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Z||"Warning",K=!1;J.warn(G,{name:V,code:Y})}}function n$(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")jG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")jG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")jG("model.sonnet",Q.useSonnet)}async function Af1(J){try{await GR8(Df1.dirname(Mf1),{recursive:!0}),await VR8(Mf1,J,"utf-8")}catch(Q){v.debug("Failed to save last thread ID",Q)}}async function WR8(){try{return(await Qq6(Mf1,"utf-8")).trim()}catch(J){return null}}var tK6=[{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??j$,description:`Custom settings file path (overrides the default location ${j$})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(v).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${qj1})`},{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:u2(),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:ZI.SMART.key,description:`Set the agent mode (${dX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:dX().map((J)=>J.mode)}],eK6=(J)=>("deprecated"in J)&&J.deprecated===!0,HR8=(J)=>("hidden"in J)&&J.hidden===!0,zR8=(J)=>("default"in J),FR8=(J)=>("default"in J)?J.default:void 0;function UR8(J,Q){let Z=Q.args[0],Y=Q.commands.map((G)=>G.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let G=Y.filter((K)=>Z.includes(K)||K.includes(Z)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new j8(C$.unknownCommand(Z),1,V)}}var Zq6=null;function Vj5(){return Zq6}function mu(J){return{...J,getThreadEnvironment:W41,vfs:zj0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Ev(J.fileSystem),generateThreadTitle:Gr0,deleteThread:(Q)=>J.threadService.delete(Q)}}var Of1=f0.file(KR8.homedir()),Yq6=process.env.XDG_CONFIG_HOME?f0.file(process.env.XDG_CONFIG_HOME):n0.joinPath(Of1,".config");async function a$(J,Q){iL0("0.0.1765238489-gbaf2e6");let Z=rz1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([f0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Of1,userConfigDir:Yq6}),{initializeCLITelemetry:Y}=await Promise.resolve().then(() => (g51(),b51));Y(Z);let X=await Z.getLatest();v.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=z16({configService:Z}),K=new Map,q=()=>K.clear(),W=new HN1(Z,J.settings.getWorkspaceRootPath()),H=LC0({configService:Z,trustStore:W,createOAuthProvider:async(t,p,e)=>{let V1=`${t}:${p}`,U1=K.get(V1);if(U1)return v.debug("Reusing existing OAuth provider for server",{serverName:t,serverUrl:p}),U1;v.debug("Creating OAuth provider for server",{serverName:t,serverUrl:p});let r=(async()=>{let o=new xM(J.secrets),l=await o.getClientInfo(t,p),H1=e?.scopes??l?.scopes,k1=new xB1({storage:o,serverName:t,serverUrl:p,clientId:e?.clientId??l?.clientId,clientSecret:e?.clientSecret??l?.clientSecret,authUrl:e?.authUrl??l?.authUrl,tokenUrl:e?.tokenUrl??l?.tokenUrl,scopes:H1});return v.debug("OAuth provider created",{serverName:t,serverUrl:p,hasManualClientId:!!(e?.clientId??l?.clientId),willUseDCR:!(e?.clientId??l?.clientId),scopes:H1}),k1})();return K.set(V1,r),r}}),z=H61({configService:Z,filesystem:r8,spawn:wA}),{initializeToolProviders:U,startToolProviders:D}=await Promise.resolve().then(() => (sK6(),rK6)),M;if(J.executeMode){let t=await U({toolService:G,providers:[H,z],initialTimeout:15000});M=t.registrations;for(let[p,e]of t.initErrors)v.warn(`${p} provider initialization slow or failed:`,e)}else M=D({toolService:G,providers:[H,z]});if(Q.jetbrains)HI("JetBrains");else if(Q.ide&&D56())HI("VS Code");else if(Q.ide&&M56())HI("Neovim");if(J.executeMode)nL0(!0);let L,A=F2.status.pipe(Q6((t)=>Boolean(t.connected&&t.authenticated)),F4()).subscribe((t)=>{if(t){if(!L)L=G.registerTool($t0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let t=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new O41(process.cwd(),{alwaysIncludePaths:t},!0)}else E=new class extends O41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(w5.write(`No API key found. Starting login flow...
4803
4803
  `),!await BR8(J))await dA(),process.exit(1)}let I=await dS0({isDevelopment:!1}),P=new HT1(I,Z),R=new VT1(I,{lazy:!0}),k=new ON1(P,(t,p)=>{let e=G3.get(t);if(e)e.handle(p).catch((V1)=>{v.error("Failed to apply artifact delta",V1)})}),y=Q.notifications!==void 0?Q.notifications:!J.executeMode,x=U16({playNotificationSound:async(t)=>{if(y){F16(t);let p=JS1(),e=QS1();if((!p||e)&&X.settings["notifications.system.enabled"]!==!1){if(t==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(t==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:P,configService:Z});v.info("Starting Amp background services");let b=Kr0({threadService:P,threadHistoryService:R,configService:Z,isExtensionDevelopment:!1}),d;F2.status.subscribe((t)=>{d=t});let m=new hG1({workspaceRoots:[f0.file(process.cwd())],getCurrentFile:()=>{if(!d?.openFile)return;try{return f0.parse(d.openFile)}catch(t){v.warn("Failed to parse current file URI",{uri:d.openFile,error:t});return}},getOpenFiles:()=>{if(!d?.visibleFiles?.length)return[];let t=d.openFile;return d.visibleFiles.filter((p)=>p!==t).map((p)=>{try{return f0.parse(p)}catch(e){return v.warn("Failed to parse visible file URI",{uri:p,error:e}),null}}).filter((p)=>p!==null)}}),a=new XS1,Z1={codebaseContextService:m,configService:Z,toolService:G,mcpService:H,trustStore:W,threadService:P,threadHistoryService:R,threadSyncService:b,planFileManager:k,threadStorage:I,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,notificationService:x,fileSystem:Q.jetbrains||Q.ide?qj0:r8,terminal:a};return{...Z1,async asyncDispose(){if(Z1.mcpService.hasAuthenticatingClients())v.info("Waiting for OAuth authentication to complete before exit..."),await Z1.mcpService.waitForAuthentication();for(let t of M.values())t.dispose();await Z1.mcpService.dispose(),q(),await Z1.threadService.asyncDispose(),Z1.configService.unsubscribe(),V(),Z1.fuzzyServer.dispose(),Z1.threadSyncService.dispose(),Z1.settingsStorage[Symbol.dispose](),A.unsubscribe(),L?.dispose()}}}async function BR8(J){if(!J.executeMode){if(!await kj1("Would you like to log in to Amp? [(y)es, (n)o]: "))return w5.write(`Login cancelled. Run the command again to retry.
4804
4804
  `),!1}return await Xq6(J)}async function Xq6(J){let Q=$R8(32).toString("hex"),Z=await _j1(J.ampURL,Q),Y=new AbortController;try{await lW(Z,Y.signal)}catch(G){v.error("Error opening browser",{error:G})}let X=await _j1(J.ampURL,Q,!1);w5.write(`If your browser does not open automatically, visit:
4805
4805
 
@@ -4809,7 +4809,7 @@ ${y4.blue.bold(X)}
4809
4809
  Login successful! You can now use the Amp CLI.
4810
4810
  `),!0}catch(G){return v.error("Login failed",{error:G}),o$.write(`
4811
4811
  Login failed: ${G instanceof Error?G.message:String(G)}
4812
- `),!1}}function NR8(){let J=new _A().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)rR(),process.exit(0);let z=H.originalError??H;W96(z)}),J.option("-V, --version","Print the version number and exit",()=>{w5.write(`0.0.1765237900-gbaf2e6 (released 2025-12-08T23:56:54.642Z)
4812
+ `),!1}}function NR8(){let J=new _A().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)rR(),process.exit(0);let z=H.originalError??H;W96(z)}),J.option("-V, --version","Print the version number and exit",()=>{w5.write(`0.0.1765238489-gbaf2e6 (released 2025-12-09T00:06:53.598Z)
4813
4813
  `),process.exit(0)}),J.addHelpText("after",U56()),J.configureHelp({formatHelp:B56}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await XZ(U);await AR8(D)}),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(),D=await XZ(U);await LR8(D,await Aj1(U,D.settings))});let Q=async(H,z,U)=>{rz1({storage:z.settings,secretStorage:z.secrets,workspaceRoots:Q0.of([f0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:Of1,userConfigDir:Yq6});let D={...z,executeMode:!1};await Lf1(D,{...H,openThreadSwitcher:!0},U)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await XZ(U);await Jq6(U,D,z)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await XZ(U);await RR8(U,D,z)}),Z.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 D=U.optsWithGlobals(),M=await XZ(D);if(z.pick)o$.write(`${y4.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
4814
4814
  `);if(z.last||H||M.executeMode)await TR8(D,M,H,U);else await Q(D,M,U)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await XZ(D);await PR8(D,M,H,U)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await XZ(U);await Jq6(U,D,z)}),Z.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 D=U.optsWithGlobals(),M=await XZ(D);await IR8(D,M,H,U,z.support)}),Z.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,D)=>{let M=D.optsWithGlobals(),L=await XZ(M);await OR8(M,L,H,z,D)}),Z.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 D=U.optsWithGlobals(),M=await XZ(D);await wR8(D,M,H,U)}),Z.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 D=U.optsWithGlobals(),M=await XZ(D);await ER8(D,M,H,z,U)}),K26(J,async(H,z)=>{let U=await XZ(z);n$(H,z);let D=await a$(U,z);return{context:U,mcpService:D.mcpService,toolService:D.toolService,toolServices:D.toolService,configService:D.configService,cleanupTerminal:rR,asyncDispose:D.asyncDispose.bind(D)}}),Y76(J,async(H)=>{let z=H.optsWithGlobals();return await XZ(z)}),i56(J,async(H)=>{let z=await XZ(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(U)=>{n$(U,H);let D=await a$(z,H);return{mcpService:D.mcpService,settings:z.settings,asyncDispose:D.asyncDispose.bind(D)}}}});function X(H,z,U){let M=typeof H.description==="string"?H.description:U===void 0?H.description(!0):H.description(U),L=new _q(z,M),A=FR8(H);if(A)L.default(A);if(L.hidden=HR8(H)||eK6(H),"choices"in H)L.choices([...H.choices]);return L}for(let H of tK6)switch(H.type){case"flag":{J.addOption(X(H,`--${H.long}`)),J.addOption(X(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(X(H,`--${H.long}`,!0));break}default:{J.addOption(X(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let G=new _q("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(G);let V=new _q("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(V);let K=new _q("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(K);let q=new _q("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let W=new _q("--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 _q("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return B26(J),J.action(async(H,z)=>{let U=H,D=await XZ(U);if(z.getOptionValueSourceWithGlobals("tryOpus")==="cli")w5.write(y4.yellow(`Opus 4.5 is now the default in Amp's smart mode. Rerun without --try-opus.
4815
4815
  `)),process.exit(0);if(Object.keys(U).forEach((L)=>{let A=tK6.find((E)=>E.name===L);if(A&&eK6(A)&&!zR8(A))o$.write(y4.yellow(`Warning: '--${L}' flag is deprecated
@@ -4817,8 +4817,8 @@ Login failed: ${G instanceof Error?G.message:String(G)}
4817
4817
  Or pipe via stdin: echo "your message" | amp --execute`);n$(Z,Q);let V=await a$(J,Q);Zq6=V;let K=mu(V),q=async(Z1)=>{let t=await Qq6(Z1,"utf-8"),p=JSON.parse(t);if(!cX(p.id))throw new j8(C$.invalidThreadId);return R71(V,{visibility:Y,agentMode:Q.mode,thread:p})},W=async(Z1)=>{if(!cX(Z1))throw new j8(C$.invalidThreadId);try{let[p,e]=await Promise.all([K5.getThreadLinkInfo({thread:Z1},{config:V.configService}),K5.getUserInfo({},{config:V.configService})]);if(p.ok&&e.ok){let V1=p.result.creatorUserID,U1=e.result.id;if(V1&&V1!==U1&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new j8(`Cannot resume thread created by another user.
4818
4818
 
4819
4819
  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(p){if(p instanceof j8)throw p;v.warn("Failed to validate thread ownership in CLI, allowing to open",{error:p})}let t=await V.threadService.get(Z1)??void 0;return v.info(`[fetchAndStartThread] Loaded thread ${Z1}, agentMode: ${t?.agentMode??"undefined"}`),R71(V,{visibility:Y,agentMode:t?void 0:Q.mode,thread:t})},H=async()=>{try{if(Q.threadId)return W(Q.threadId);else return R71(V,{visibility:Y,agentMode:Q.mode})}catch(Z1){if(Z1 instanceof j8)throw Z1;throw await Jm(Z1,Q.threadId),Error("handleError should have called process.exit()")}},z=async()=>{return R71(V,{visibility:Y,agentMode:Q.mode})};if(Q.format==="jsonl")o$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
4820
- `),await dA(),process.exit(1);if(J.executeMode&&Q.remote)await X76(X,G,V.configService),await V.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)r56(V.mcpService,J.settings),await P96(U,U.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await V.asyncDispose(),process.exit(0);let D=!1,M=!1,L=!1;if(Q.jetbrains||Q.ide){await VA0();let Z1=BI({jetbrainsOnly:Q.jetbrains});if(Z1.length===0){if(Q.jetbrains)M=!await V.configService.get("jetbrains.skipInstall")}else if(Z1.length===1){let t=Z1[0];if(t)F2.selectConfig(t)}else L=!0}let A=S41("0.0.1765237900-gbaf2e6",V.settingsStorage),E=new g01(V.threadStorage),I=Q0.of([f0.file(process.cwd())]),P=iG1(void 0,I),R=new _41(V.mcpService,J.settings.getWorkspaceRootPath());if(X)U.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let k=(async()=>{try{let Z1=await K5.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(Z1.ok)return v.info("User free tier status:",Z1),Z1.result}catch(Z1){throw v.error("Failed to fetch free tier status:",Z1),Z1}})(),y=(async()=>{try{let Z1=await K5.getUserInfo({},{config:V.configService});if(Z1.ok)return Z1.result}catch(Z1){v.debug("Failed to fetch user workspace info:",Z1)}})(),[x,b]=await Promise.all([k,y]),d=b?.email,m=d&&(d.endsWith("@sourcegraph.com")||d.endsWith("@ampcode.com")||d==="auth-bypass-user@example.com"),a=await K76();v.info("Loaded session state:",a),await dx1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new U41,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,planFileManager:V.planFileManager,threadID:U.threadID,threadFuzzyIndexer:E,worker:U,workerDeps:K,configService:V.configService,internalAPIClient:K5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:F2,connectedClientsService:new Ba,commandRegistry:P,mcpService:V.mcpService,mcpTrustHandler:R,showJetBrainsInstaller:M,showIdePicker:D,showIdePickerHint:L,openThreadSwitcher:Q.openThreadSwitcher,updateService:A,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:a,freeTierStatus:{canUseAmpFree:x.canUseAmpFree&&!b?.features.some((Z1)=>Z1.name===FI.UBI&&Z1.enabled)},workspace:b?.team??null,features:b?.features??[],isDogfooding:m||!1,threadDependencies:V,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function XZ(J){if(J.interactive)o$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4821
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,Y=await t96({...J,workspaceTrust:{current:!0,changes:Bk},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await a56(J.mcpConfig);Y=o56(Y,G)}let X=await Y.get("url","global");if(!X)X=DZ;if(!_F(X))v.info("Targeting custom Amp server",{ampURL:X});return Y=nB0(Y),{executeMode:Q,isTTY:Z,ampURL:X,settings:Y,secrets:$76(await Aj1(J,Y))}}function DR8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let G=Y.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Z+1];if(V&&!V.startsWith("--"))Q[G]=V,Z++}}return Q}async function MR8(){let J=DR8(process.argv);if(Q96({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),qR8(v),v.info("Starting Amp CLI.",{version:"0.0.1765237900-gbaf2e6",buildTimestamp:"2025-12-08T23:56:54.642Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new j8(C$.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await NR8().parseAsync(process.argv)}eP1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await MR8().catch(Jm)});async function LR8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),w5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4820
+ `),await dA(),process.exit(1);if(J.executeMode&&Q.remote)await X76(X,G,V.configService),await V.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)r56(V.mcpService,J.settings),await P96(U,U.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await V.asyncDispose(),process.exit(0);let D=!1,M=!1,L=!1;if(Q.jetbrains||Q.ide){await VA0();let Z1=BI({jetbrainsOnly:Q.jetbrains});if(Z1.length===0){if(Q.jetbrains)M=!await V.configService.get("jetbrains.skipInstall")}else if(Z1.length===1){let t=Z1[0];if(t)F2.selectConfig(t)}else L=!0}let A=S41("0.0.1765238489-gbaf2e6",V.settingsStorage),E=new g01(V.threadStorage),I=Q0.of([f0.file(process.cwd())]),P=iG1(void 0,I),R=new _41(V.mcpService,J.settings.getWorkspaceRootPath());if(X)U.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let k=(async()=>{try{let Z1=await K5.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(Z1.ok)return v.info("User free tier status:",Z1),Z1.result}catch(Z1){throw v.error("Failed to fetch free tier status:",Z1),Z1}})(),y=(async()=>{try{let Z1=await K5.getUserInfo({},{config:V.configService});if(Z1.ok)return Z1.result}catch(Z1){v.debug("Failed to fetch user workspace info:",Z1)}})(),[x,b]=await Promise.all([k,y]),d=b?.email,m=d&&(d.endsWith("@sourcegraph.com")||d.endsWith("@ampcode.com")||d==="auth-bypass-user@example.com"),a=await K76();v.info("Loaded session state:",a),await dx1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new U41,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,planFileManager:V.planFileManager,threadID:U.threadID,threadFuzzyIndexer:E,worker:U,workerDeps:K,configService:V.configService,internalAPIClient:K5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:F2,connectedClientsService:new Ba,commandRegistry:P,mcpService:V.mcpService,mcpTrustHandler:R,showJetBrainsInstaller:M,showIdePicker:D,showIdePickerHint:L,openThreadSwitcher:Q.openThreadSwitcher,updateService:A,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:a,freeTierStatus:{canUseAmpFree:x.canUseAmpFree&&!b?.features.some((Z1)=>Z1.name===FI.UBI&&Z1.enabled)},workspace:b?.team??null,features:b?.features??[],isDogfooding:m||!1,threadDependencies:V,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function XZ(J){if(J.interactive)o$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4821
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,Y=await t96({...J,workspaceTrust:{current:!0,changes:Bk},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await a56(J.mcpConfig);Y=o56(Y,G)}let X=await Y.get("url","global");if(!X)X=DZ;if(!_F(X))v.info("Targeting custom Amp server",{ampURL:X});return Y=nB0(Y),{executeMode:Q,isTTY:Z,ampURL:X,settings:Y,secrets:$76(await Aj1(J,Y))}}function DR8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let G=Y.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Z+1];if(V&&!V.startsWith("--"))Q[G]=V,Z++}}return Q}async function MR8(){let J=DR8(process.argv);if(Q96({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),qR8(v),v.info("Starting Amp CLI.",{version:"0.0.1765238489-gbaf2e6",buildTimestamp:"2025-12-09T00:06:53.598Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new j8(C$.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await NR8().parseAsync(process.argv)}eP1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await MR8().catch(Jm)});async function LR8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),w5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4822
4822
  `);else if(!_F(J.ampURL))w5.write(`Logging in to ${new URL(J.ampURL).hostname}
4823
4823
  `);let Z=process.env.AMP_API_KEY;if(Z)w5.write(`API key found in environment variable, storing...
4824
4824
  `),await Q.set("apiKey",Z,J.ampURL),w5.write(`API key successfully stored.
@@ -4831,7 +4831,7 @@ This thread belongs to a different user and cannot be continued for security rea
4831
4831
  `);else w5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
4832
4832
  `);process.exit(0)}async function OR8(J,Q,Z,Y,X){n$(X,J);let G=await a$(Q,J);try{let V=C71(Z);if(!V)j71(Z);let K=V,q=Y.trim();if(q.length===0)i$("Thread name cannot be empty");if(q.length>256)i$("Thread name cannot exceed 256 characters");if(!(await Uj(K,G)).messages.length)i$("Cannot rename an empty thread.");let H=mu(G);await(await G3.getOrCreateForThread(H,K)).handle({type:"title",value:q}),v.info("GOT HERE"),await G.threadSyncService.sync(),v.info("GOT THERE"),w5.write(y4.green(`✓ Thread ${K} renamed to "${q}"
4833
4833
  `)),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose();let K=`Failed to rename thread: ${V instanceof Error?V.message:String(V)}`;i$(K)}}async function wR8(J,Q,Z,Y){n$(Y,J);let X=await a$(Q,J);try{let G=C71(Z);if(!G)j71(Z);let K=await Uj(G,X),q=RR(K);w5.write(q+`
4834
- `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;i$(V)}}async function ER8(J,Q,Z,Y,X){n$(X,J);let G=await a$(Q,J);try{let V=await wf1(Z),K=await Uj(V,G),q=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),z=parseInt(Y.toolProgressDelay||"800",10),U=parseInt(Y.exitDelay||"3",10)*1000,D=Y.indicator!==!1,M=mu(G),L=K.id;await G.threadStorage.set(L,K);let A=await G3.getOrCreateForThread(M,L);await A.resume();let E=b01.fromWorker(A),I=new g01(G.threadStorage),P=Q0.of([f0.file(process.cwd())]),R=iG1(void 0,P),k=new _41(G.mcpService,Q.settings.getWorkspaceRootPath()),y=S41("0.0.1765237900-gbaf2e6",G.settingsStorage);await dx1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new U41,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:L,threadFuzzyIndexer:I,worker:E,workerDeps:M,configService:G.configService,internalAPIClient:K5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:F2,connectedClientsService:new Ba,commandRegistry:R,mcpService:G.mcpService,mcpTrustHandler:k,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:D},freeTierStatus:{canUseAmpFree:!0},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await Jm(V,Z)}}async function IR8(J,Q,Z,Y,X){n$(Y,J);let G=await a$(Q,J);try{let V=C71(Z);if(!V)j71(Z);let K=V,q=await K5.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=k41(J,W);if(!H&&!X)i$("Must specify either --visibility or --support");if(H&&X)i$("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)i$(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,y41(H)),w5.write(y4.green("✓ ")+`Thread ${K} visibility changed to ${H}.
4834
+ `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;i$(V)}}async function ER8(J,Q,Z,Y,X){n$(X,J);let G=await a$(Q,J);try{let V=await wf1(Z),K=await Uj(V,G),q=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),z=parseInt(Y.toolProgressDelay||"800",10),U=parseInt(Y.exitDelay||"3",10)*1000,D=Y.indicator!==!1,M=mu(G),L=K.id;await G.threadStorage.set(L,K);let A=await G3.getOrCreateForThread(M,L);await A.resume();let E=b01.fromWorker(A),I=new g01(G.threadStorage),P=Q0.of([f0.file(process.cwd())]),R=iG1(void 0,P),k=new _41(G.mcpService,Q.settings.getWorkspaceRootPath()),y=S41("0.0.1765238489-gbaf2e6",G.settingsStorage);await dx1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new U41,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:L,threadFuzzyIndexer:I,worker:E,workerDeps:M,configService:G.configService,internalAPIClient:K5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:F2,connectedClientsService:new Ba,commandRegistry:R,mcpService:G.mcpService,mcpTrustHandler:k,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:D},freeTierStatus:{canUseAmpFree:!0},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await Jm(V,Z)}}async function IR8(J,Q,Z,Y,X){n$(Y,J);let G=await a$(Q,J);try{let V=C71(Z);if(!V)j71(Z);let K=V,q=await K5.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=k41(J,W);if(!H&&!X)i$("Must specify either --visibility or --support");if(H&&X)i$("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)i$(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,y41(H)),w5.write(y4.green("✓ ")+`Thread ${K} visibility changed to ${H}.
4835
4835
  `);if(X){await Uj(K,G);let z=typeof X==="string"?X:void 0;await hS0(G.threadService,K,G.configService,z),w5.write(y4.green("✓ ")+`Thread ${K} has been shared with Amp support. These thread reports will be aggregated and analysed.
4836
4836
  `)}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),i$(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function PR8(J,Q,Z,Y){n$(Y,J);let X=await a$(Q,J),G=mu(X);try{let V=await wf1(Z),q=(await Uj(V,X)).messages.length-1,W=await G3.getOrCreateForThread(G,V),H=await jR(W,X.threadSyncService,q);await Promise.all([X.threadSyncService.uploadThread(V),X.threadSyncService.uploadThread(H)]),await Af1(H),w5.write(`${H}
4837
4837
  `),await X.asyncDispose(),process.exit(0)}catch(V){o$.write(`Error forking thread: ${V instanceof Error?V.message:String(V)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1765237900-gbaf2e6",
3
+ "version": "0.0.1765238489-gbaf2e6",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {