@sourcegraph/amp 0.0.1763856110-g40edea → 0.0.1763857589-g40edea

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
@@ -4878,11 +4878,11 @@ Actual: ${Z}`)}async function MX5(J,Q,Y){let{execSync:X}=await import("node:ch
4878
4878
  ${R}`;if(Z==="pnpm"&&R.includes("Unable to find the global bin directory"))_+=`
4879
4879
 
4880
4880
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4881
- npm install -g @sourcegraph/amp`;W(Error(_))}},error:(E)=>{if(!O)O=!0,W(Error(`Failed to spawn ${Z}: ${E.message}`))},complete:()=>{if(!O)O=!0,K()}})})}U9();U9();async function Mt1(J,Q){let X=Q||"https://registry.npmjs.org";try{let Z=new AbortController,V=setTimeout(()=>Z.abort(),5000),K=await fetch(`${X}/@sourcegraph/amp`,{signal:Z.signal});if(clearTimeout(V),!K.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=await K.json(),U=W["dist-tags"]?.latest;if(!U)return{hasUpdate:!1,currentVersion:J,source:"npm"};let N=EX5(J,U),O=N<0,A,E;if(W.time){let R=W.time[J],_=W.time[U],y=Date.now();if(R)A=Math.floor((y-new Date(R).getTime())/3600000);if(_)E=Math.floor((y-new Date(_).getTime())/3600000)}return I1.info("NPM version comparison",{currentVersion:J,latestVersion:U,compareResult:N,hasUpdate:O,currentVersionAge:A,latestVersionAge:E}),{hasUpdate:O,latestVersion:U,currentVersion:J,currentVersionAge:A,latestVersionAge:E,source:"npm"}}catch(Z){return I1.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function EX5(J,Q){let Y=(K)=>{let[W,U]=K.split("-");return{parts:W?.split(".").map(Number)||[],label:U}},X=Y(J),Z=Y(Q),V=Math.max(X.parts.length,Z.parts.length);for(let K=0;K<V;K++){let W=X.parts[K]||0,U=Z.parts[K]||0;if(W<U)return-1;if(W>U)return 1}if(X.label===Z.label)return 0;if(!X.label&&Z.label)return 1;if(X.label&&!Z.label)return-1;if(X.label&&Z.label)return X.label<Z.label?-1:1;return 0}d5();function Ot1(J,Q){let Y=new FY,X=Y.pipe(JG({shouldCountRefs:!1}));return setImmediate(async()=>{let Z=new px().scoped("update"),V=X.subscribe({next:(K)=>{Z.debug("emit new state",K)}});try{let K=process.env.AMP_TEST_UPDATE_STATUS;if(K){Z.debug("using fake update status for testing",{status:K}),await Xa(500),Y.next(K);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Z.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let W=await Q.get("updates.mode");if(W==="disabled"){Z.debug("checking disabled");return}Z.debug("checking",{currentVersion:J,mode:W});let U=e41(),N=await Mt1(J,U);if(!(N.latestVersion&&N.hasUpdate)){Z.debug("no update available");return}let O=()=>{if(N.currentVersionAge!==void 0&&N.latestVersionAge!==void 0){let E=N.currentVersionAge-N.latestVersionAge,R=0.5;if(Math.abs(E)<0.5)return Z.debug("versions too close together, suppressing update warning",{currentVersionAge:N.currentVersionAge,latestVersionAge:N.latestVersionAge,ageDifferenceHours:E}),!0}return!1},A=await Dt1();if(!W)W=A==="pnpm"?"warn":"auto",Z.debug("no configured update mode; selected default based on package manager",{packageManager:A,mode:W});if(W==="warn"){if(!O())Y.next("update-available");return}if(!A){if(Z.debug("auto-update not supported, falling back to warn mode"),!O())Y.next("update-available");return}try{await sI1(N.latestVersion,A);let E=await Nr(N.latestVersion),R={from:N.currentVersion,to:N.latestVersion,...E};if(E.status==="same")Z.info("success",R),Y.next("updated");else Z.warn("success with warning",R),Y.next("updated-with-warning")}catch(E){Y.next("update-error")}}catch(K){Z.debug("check failed",{error:K})}finally{await Xa(5000),Y.next("hidden"),V.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as $h}from"node:process";function tS4(J){let Q=new u41().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(X)=>{await wu0(X.force||!1,X.verbose||!1,"0.0.1763856110-g40edea"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new u41("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("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await IX5(X.version)});J.addCommand(Y)}async function IX5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")$h.write(oQ.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4881
+ npm install -g @sourcegraph/amp`;W(Error(_))}},error:(E)=>{if(!O)O=!0,W(Error(`Failed to spawn ${Z}: ${E.message}`))},complete:()=>{if(!O)O=!0,K()}})})}U9();U9();async function Mt1(J,Q){let X=Q||"https://registry.npmjs.org";try{let Z=new AbortController,V=setTimeout(()=>Z.abort(),5000),K=await fetch(`${X}/@sourcegraph/amp`,{signal:Z.signal});if(clearTimeout(V),!K.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=await K.json(),U=W["dist-tags"]?.latest;if(!U)return{hasUpdate:!1,currentVersion:J,source:"npm"};let N=EX5(J,U),O=N<0,A,E;if(W.time){let R=W.time[J],_=W.time[U],y=Date.now();if(R)A=Math.floor((y-new Date(R).getTime())/3600000);if(_)E=Math.floor((y-new Date(_).getTime())/3600000)}return I1.info("NPM version comparison",{currentVersion:J,latestVersion:U,compareResult:N,hasUpdate:O,currentVersionAge:A,latestVersionAge:E}),{hasUpdate:O,latestVersion:U,currentVersion:J,currentVersionAge:A,latestVersionAge:E,source:"npm"}}catch(Z){return I1.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function EX5(J,Q){let Y=(K)=>{let[W,U]=K.split("-");return{parts:W?.split(".").map(Number)||[],label:U}},X=Y(J),Z=Y(Q),V=Math.max(X.parts.length,Z.parts.length);for(let K=0;K<V;K++){let W=X.parts[K]||0,U=Z.parts[K]||0;if(W<U)return-1;if(W>U)return 1}if(X.label===Z.label)return 0;if(!X.label&&Z.label)return 1;if(X.label&&!Z.label)return-1;if(X.label&&Z.label)return X.label<Z.label?-1:1;return 0}d5();function Ot1(J,Q){let Y=new FY,X=Y.pipe(JG({shouldCountRefs:!1}));return setImmediate(async()=>{let Z=new px().scoped("update"),V=X.subscribe({next:(K)=>{Z.debug("emit new state",K)}});try{let K=process.env.AMP_TEST_UPDATE_STATUS;if(K){Z.debug("using fake update status for testing",{status:K}),await Xa(500),Y.next(K);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Z.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let W=await Q.get("updates.mode");if(W==="disabled"){Z.debug("checking disabled");return}Z.debug("checking",{currentVersion:J,mode:W});let U=e41(),N=await Mt1(J,U);if(!(N.latestVersion&&N.hasUpdate)){Z.debug("no update available");return}let O=()=>{if(N.currentVersionAge!==void 0&&N.latestVersionAge!==void 0){let E=N.currentVersionAge-N.latestVersionAge,R=0.5;if(Math.abs(E)<0.5)return Z.debug("versions too close together, suppressing update warning",{currentVersionAge:N.currentVersionAge,latestVersionAge:N.latestVersionAge,ageDifferenceHours:E}),!0}return!1},A=await Dt1();if(!W)W=A==="pnpm"?"warn":"auto",Z.debug("no configured update mode; selected default based on package manager",{packageManager:A,mode:W});if(W==="warn"){if(!O())Y.next("update-available");return}if(!A){if(Z.debug("auto-update not supported, falling back to warn mode"),!O())Y.next("update-available");return}try{await sI1(N.latestVersion,A);let E=await Nr(N.latestVersion),R={from:N.currentVersion,to:N.latestVersion,...E};if(E.status==="same")Z.info("success",R),Y.next("updated");else Z.warn("success with warning",R),Y.next("updated-with-warning")}catch(E){Y.next("update-error")}}catch(K){Z.debug("check failed",{error:K})}finally{await Xa(5000),Y.next("hidden"),V.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as $h}from"node:process";function tS4(J){let Q=new u41().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(X)=>{await wu0(X.force||!1,X.verbose||!1,"0.0.1763857589-g40edea"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new u41("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("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await IX5(X.version)});J.addCommand(Y)}async function IX5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")$h.write(oQ.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4882
4882
 
4883
4883
  `));try{if(!J){$h.write(oQ.blue(`Checking for updates...
4884
- `));let Y=e41(),{hasUpdate:X,latestVersion:Z}=await Mt1("0.0.1763856110-g40edea",Y);if(!X){$h.write(oQ.green(`✓ Amp CLI is already up to date.
4885
- `));let V=await Nr("0.0.1763856110-g40edea");if(V.warning)$h.write(`
4884
+ `));let Y=e41(),{hasUpdate:X,latestVersion:Z}=await Mt1("0.0.1763857589-g40edea",Y);if(!X){$h.write(oQ.green(`✓ Amp CLI is already up to date.
4885
+ `));let V=await Nr("0.0.1763857589-g40edea");if(V.warning)$h.write(`
4886
4886
  `+oQ.yellow(V.warning)+`
4887
4887
  `);process.exit(0)}if(!Z)$h.write(oQ.yellow("[WARN] could not find latest version")),process.exit(0);J=Z}$h.write(oQ.blue(`Updating to version ${J}...
4888
4888
  `)),await sI1(J,void 0,(Y)=>{$h.write(oQ.dim(`Running: ${Y}
@@ -5504,7 +5504,7 @@ exit code: ${V}`,new U6({color:X.foreground,dim:!0,italic:!0})));if(K)W.push(new
5504
5504
  `,E),...R],y=new V2({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new a4({text:new h0("",void 0,_)})]});return YX.child(new C2({constraints:new i3(40,120,0,1/0),child:new hJ({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[new HQ({flex:1,child:new Ag0({width:40,height:40,agentMode:this.agentMode,fps:K==="fast"?60:K==="slow"?15:0,...K==="disabled"&&{seed:42,t:3}})}),new S9({width:1}),new HQ({flex:2,child:y})]})}))}}U9();fG();dJ();YV();fG();d5();function sW5(J,Q){return`${J}:${Q}`}class ap0{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 L8((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.subthreadObservable=new L8((Q)=>{return this.emitSubthread=(Y)=>Q.next(Y),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new L8((Q)=>{return this.emitWorkerStatus=(Y)=>Q.next(Y),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.subthreadsMap.set(Q,[]),this.workers.set(Q,{state:"initial"});let Y=this.threadService.observePatches(Q).pipe(N01()).subscribe((V)=>{this.threadsMap.set(Q,V);let K=this.subthreadsMap.get(Q)||[],W=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:V,subthreads:K,workerStatus:W})});this.mainThreadSubs.set(Q,Y);let X=J.status.subscribe((V)=>{if(this.workers.set(Q,V),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:V})});this.workerStatusSubs.set(Q,X);let Z=J.subthreads.subscribe((V)=>{this.subthreadsMap.set(Q,V);for(let K of V){let W=sW5(Q,K.toolUse.id);if(this.subthreadPatchSubs.has(W))continue;let U=this.threadService.observePatches(K.threadID).pipe(N01()).subscribe((N)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:N,subthread:K})});this.subthreadPatchSubs.set(W,U)}});this.subthreadsSubs.set(Q,Z)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Y=this.workerStatusSubs.get(J);if(Y)Y.unsubscribe(),this.workerStatusSubs.delete(J);let X=this.subthreadsSubs.get(J);if(X)X.unsubscribe(),this.subthreadsSubs.delete(J);for(let[Z,V]of this.subthreadPatchSubs.entries())if(Z.startsWith(`${J}:`))V.unsubscribe(),this.subthreadPatchSubs.delete(Z);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new L8((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),subthreads:new L8((Q)=>{return this.subthreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new L8((Q)=>{return this.workerStatusObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})})}}get threadViewStates(){let J={};for(let[Q,Y]of this.threadsMap){let X=this.workers.get(Q);if(X)J[Q]=L41(Y,X)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.subthreadsSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();for(let J of this.subthreadPatchSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.subthreadsSubs.clear(),this.workerStatusSubs.clear(),this.subthreadPatchSubs.clear(),this.workers.clear(),this.threadsMap.clear(),this.subthreadsMap.clear()}}function tW5(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Y,subthread:X}=Q,Z=J.subagents[X.threadID];if(!Z){if(Z={subThreadID:Y.id,parentToolID:X.toolUse.id,taskDescription:X.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let N=RO(J.mainThread);Z.isCompleted=Af4(N,X.toolUse.id)}}let V=eW5(Y,Z.agentState),K=Z.agentState===V?Z:{...Z,agentState:V},W={...J.tools},U=lZ1(Y).items.filter((N)=>N.type==="toolResult");for(let N of U)W[N.id]={id:N.id,subthreadID:Y.id,toolRun:N.toolResult.run,toolUse:N.toolUse};return{subagents:{...J.subagents,[X.threadID]:K},tools:W,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Y,subthreads:X,workerStatus:Z}=Q,V=RO(Y),K={...J.subagents};for(let A of X){let E=K[A.threadID];if(!E)continue;let R=Af4(V,A.toolUse.id);K[A.threadID]={...E,isCompleted:R}}let{items:W}=lZ1(Y),U=L41(Y,Z),N=UY1({messages:Y.messages}),O=Array.isArray(N)?N:[];return{...J,subagents:K,items:W,viewState:U,todosList:O,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=L41(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function lZ1(J){let Q=[],Y=new Map,X=new Set;for(let[Z,V]of J.messages.entries()){let K=`${V.role}-${Z}`;switch(V.role){case"assistant":{let W=V.state.type==="streaming";for(let N of V.content)if(N.type==="tool_use"){if(Y.set(N.id,N),W)X.add(N.id)}if(V.content.some((N)=>N.type==="text"&&N.text.trim()||N.type==="thinking"))Q.push({type:"message",id:K,message:V});for(let N of V.content)if(N.type==="tool_use"){let O=!1;for(let A=Z+1;A<J.messages.length;A++){let E=J.messages[A];if(E){for(let R of E.content)if(R.type==="tool_result"&&R.toolUseID===N.id){O=!0;break}}if(O)break}if(!O)Q.push({type:"toolResult",id:N.id,toolUse:N,toolResult:{type:"tool_result",toolUseID:N.id,run:{status:W?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:K,message:V});break;case"user":{if(V.content.some((U)=>U.type==="text"&&U.text.trim()||U.type==="image"))Q.push({type:"message",id:K,message:V});for(let U of V.content)if(U.type==="tool_result"){let N=Y.get(U.toolUseID)??PP(J,U.toolUseID);if(!N)throw Error(`(bug) tool use ${U.toolUseID} not found`);Q.push({type:"toolResult",id:U.toolUseID,toolUse:N,toolResult:U})}break}}}return{items:Q}}function Af4(J,Q){let Y=J.get(Q);return(Y&&TF(Y.run))??!1}function eW5(J,Q){let Y=J.messages.at(-1);if(Y?.content.some((Z)=>Z.type==="tool_result"&&Z.run.status==="blocked-on-user"))return I1.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(lZ1(J).items.some((Z)=>Z.type==="toolResult"&&Z.toolResult.run.status==="in-progress")){let Z=Q?.type==="running-tools"?Q.startTime:Date.now();return I1.info("Subagent status: running-tools",{threadID:J.id,startTime:Z,hasStartTime:!!Z}),{type:"running-tools",startTime:Z}}if(Y&&Y.role==="assistant"&&Y.state.type==="streaming")switch(Y.content.at(-1)?.type){case"text":return I1.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return I1.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let V=Q?.type==="running-tools"?Q.startTime:Date.now();return I1.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:V,hasStartTime:!!V}),{type:"running-tools",startTime:V}}default:return I1.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return I1.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class rp0 extends v2{props;constructor(J){super();this.props=J}createState(){return new Lf4}}class Lf4 extends y2{state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new ap0(J),this.currentWorker=Q,this.setupSubscriptions(Q)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Y=Q.mainThread.subscribe((V)=>{this.dispatch({type:"main-thread-patch",thread:V.mainThread,subthreads:V.subthreads,workerStatus:V.workerStatus})});this.subscriptions.push(Y);let X=Q.subthreads.subscribe((V)=>{this.dispatch({type:"subthread-patch",thread:V.thread,subthread:V.subthread})});this.subscriptions.push(X);let Z=Q.workerStatus.subscribe((V)=>{this.dispatch({type:"worker-status-change",workerStatus:V.status})});this.subscriptions.push(Z)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J)}dispatch(J){this.setState(()=>{this.state=tW5(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((V)=>({toolUse:V.toolUse,toolRun:V.toolRun,subthreadID:V.subthreadID})),Q={};for(let V of Object.values(this.state.subagents)){let K=J.filter((W)=>W.subthreadID===V.subThreadID);Q[V.parentToolID]=K}let Y=(V)=>V===rK||V===MG||V===XY1||V===qn||V===Vn||V===$Y1||V===GY1||V===IP,X=new Map;for(let V of this.state.items)if(V.type==="toolResult"&&Y(V.toolUse.name))X.set(V.toolUse.id,{toolUseId:V.toolUse.id,toolName:V.toolUse.name,toolRun:V.toolResult.run});let Z=Array.from(X.values());for(let{toolUseId:V,toolRun:K}of Z){let W=[],U;if(K.status==="in-progress"||K.status==="done"||K.status==="error"||K.status==="cancelled")U=K.progress;if(U){let N=0;for(let O of U)if(O.tool_uses)for(let A of O.tool_uses){let E=`${V}:progress:${N++}`;W.push({toolUse:HY1(A.tool_name,A.input,E),toolRun:{status:A.status}})}}Q[V]=W}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker)}}class op0 extends v2{props;constructor(J){super({key:J.key});this.props=J}createState(){return new wf4}}class wf4 extends y2{build(J){let Y=L3.of(J).colors,{todos:X,title:Z="TODOs"}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new S9({width:0,height:0});let V=X.map((K)=>this.buildTodoItem(K,Y));return new C2({child:new f3({padding:U5.symmetric(1,0),child:new V2({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new a4({text:new h0(Z,new U6({bold:!0,color:Y.foreground}))}),...V]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),X=J.status==="completed",Z=new U6({bold:J.status==="in-progress",color:Q.foreground,dim:X}),V=new U6({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:X});return new hJ({crossAxisAlignment:"start",children:[new a4({text:new h0(Y,Z)}),new S9({width:1}),new HQ({child:new a4({text:new h0(J.content,V)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class sp0 extends $3{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Y,onButtonClick:X}){super({key:J});this.ad=Q,this.onDismiss=Y,this.onButtonClick=X}build(J){let Q=L3.of(J),Y=Q.colors.primary,X=Q.colors.foreground;return new C2({decoration:new z$(void 0,new RY(new sQ(Y,1,"rounded"),new sQ(Y,1,"rounded"),void 0,new sQ(Y,1,"rounded"))),child:new f3({padding:U5.horizontal(1),child:new V2({children:[new hJ({crossAxisAlignment:"start",children:[new HQ({child:new a4({text:new h0(this.ad.content,new U6({color:X}))})}),new S9({width:4}),new uO({uri:"https://ampcode.com/free",text:"Ad",style:new U6({color:X,dim:!0}),onError:(Z)=>{}})]}),new hJ({crossAxisAlignment:"start",children:[new kg0({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:U5.horizontal(1),color:Y,reverse:!0}),new S9({width:2}),new a4({text:new h0(this.ad.destinationUrlHostname,new U6({color:X,dim:!0}))})]})]})})})}}class tp0 extends v2{props;constructor(J){super();this.props=J}createState(){return new Ef4(this.props.autofocus??!0)}}class Ef4 extends y2{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(W)=>{if(W.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(W.ctrlKey&&W.key==="c"||W.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=DX.sizeOf(J),X=Math.min(60,Y.width-4),Z=Y.height-4,V=[];if(this.widget.props.title)V.push(new a4({text:new h0(this.widget.props.title,new U6({bold:!0,color:k6.blue}))}),new S9({height:1}));if(this.widget.props.message)V.push(new a4({text:new h0(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)V.push(new S9({height:1}));let K=[];if(this.widget.props.showCopyOption)K.push(new a4({text:new h0("Enter to copy",new U6({dim:!0}))}));return K.push(new a4({text:new h0("Escape to close",new U6({dim:!0}))})),V.push(new hJ({children:K.flatMap((W,U)=>U<K.length-1?[W,new S9({width:1}),new a4({text:new h0("•",new U6({dim:!0}))}),new S9({width:1})]:[W]),mainAxisSize:"min"})),new YX({child:new C2({constraints:new i3(X,X,0,Z),decoration:new z$(k6.default(),new RY(new sQ(k6.blue,1,"rounded"),new sQ(k6.blue,1,"rounded"),new sQ(k6.blue,1,"rounded"),new sQ(k6.blue,1,"rounded"))),padding:new U5(2,2,2,2),child:new ZG({autofocus:this.autofocus,onKey:Q,child:new V2({children:V,mainAxisSize:"min"})})})})}}class q10 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,q10.prototype)}}class V10 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,V10.prototype)}}function ep0(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Y)=>{if(Y.startsWith('"')&&Y.endsWith('"')||Y.startsWith("'")&&Y.endsWith("'"))return Y.slice(1,-1);return Y})}Un();U9();import{spawn as JH5}from"node:child_process";import{promises as QH5}from"node:fs";function If4(J){return J.kind==="executable"}function Pf4(J){return J.kind==="markdown"}var fp=50000,Tf4=300000;async function Jd0(J,Q,Y,X={}){let{timeoutMs:Z=Tf4,signal:V,source:K}=X;try{let W=await Y.getCommand(J,K);if(!W)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Y.isCommandAvailable(J,K))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(I1.debug("Executing command",{commandName:J,filePath:W.filePath,args:Q}),Pf4(W))return await YH5(W,Q);else if(If4(W))return await XH5(W,Q,Z,V);else return{success:!1,output:"",error:"Unsupported command type"}}catch(W){return I1.error("Failed to execute command",{commandName:J,error:W}),{success:!1,output:"",error:W instanceof Error?W.message:"Unknown error occurred"}}}async function YH5(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await QH5.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>fp?Y.slice(0,fp)+`
5505
5505
  ... (output truncated at ${fp} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function XH5(J,Q,Y=Tf4,X){return new Promise((Z)=>{let[V,K]=$H5(J,Q);I1.debug("Spawning command",{spawnCommand:V,spawnArgs:K.slice(0,10),filePath:J.filePath,timeoutMs:Y});let W=Ho6(X),U=!1,N=setTimeout(()=>{U=!0,W.abort(),I1.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),O=JH5(V,K,{stdio:["pipe","pipe","pipe"],signal:W.signal,detached:!0}),A=[],E=[],R=0;O.stdout?.on("data",(_)=>{let y=_.toString();if(R+=y.length,R<=fp)A.push(y);else{let h=fp-(R-y.length);if(h>0)A.push(y.slice(0,h))}}),O.stderr?.on("data",(_)=>{let y=_.toString();if(R+=y.length,R<=fp)E.push(y);else{let h=fp-(R-y.length);if(h>0)E.push(y.slice(0,h))}}),O.on("close",(_)=>{if(clearTimeout(N),U){Z({success:!1,output:A.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(W.signal.aborted){Z({success:!1,output:A.join(""),error:"The command was aborted",exitCode:_??void 0});return}let y=_===0||_===1,h=A.join(""),p=E.join(""),l=h;if(!y&&!h.trim()&&p.trim())l=p;else if(p.trim())l+=h?`
5506
5506
  ${p}`:p;if(R>fp)l+=`
5507
- ... (output truncated at ${fp} characters)`;Z({success:y,output:l.trim(),error:!y?p.trim()||"Command failed":void 0,exitCode:_??void 0})}),O.on("error",(_)=>{clearTimeout(N);let y=_.message;if(U)y=`Command timed out after ${Y}ms`;else if(_.message.includes("operation was aborted")||_.name==="AbortError")y="The command was aborted";Z({success:!1,output:A.join(""),error:y})})})}function $H5(J,Q){let{filePath:Y,interpreter:X,extension:Z}=J;if(process.platform==="win32")return ZH5(Y,X?[...X]:null,Z,Q);else return GH5(Y,X?[...X]:null,Z,Q)}function GH5(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function ZH5(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}U9();yk();iV();$m();kk();_k();Jf();dm();ea1();YV();ZD1();d5();EX1();import{writeFile as kf4}from"fs/promises";import yf4 from"path";U9();kk();class Qd0{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1763856110-g40edea"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await tl1(Q,this.configService)}catch(Q){I1.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 Yd0 extends v2{props;constructor(J){super();this.props=J}createState(){return new Rf4}}class Rf4 extends y2{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class Cf4 extends y2{controller=new Lj;focusNode=new m$({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=L3.of(J),{colors:Y,app:X}=Q,Z=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!Z||V,W=RY.all(new sQ(Y.foreground,1,"solid")),U=new K81({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(R)=>{let _=R.trim();if(Z&&_.length===0)return;this.widget.props.onSubmit(_)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),N=new hJ({children:[new C2({decoration:{color:k6.default()},child:new a4({text:new h0(">",new U6({color:Y.foreground}))})}),new HQ({child:U})]}),O=new C2({padding:U5.symmetric(1,0),child:new a4({text:new h0("",void 0,[new h0("Command: ",new U6({color:Y.foreground})),new h0(this.widget.props.commandName,new U6({color:k6.yellow,bold:!0}))])})}),A=[];if(K)A.push(new h0("Enter",new U6({color:X.keybind}))),A.push(new h0(" to submit, ",new U6({color:Y.foreground,dim:!0})));A.push(new h0("Esc",new U6({color:X.keybind}))),A.push(new h0(" to cancel",new U6({color:Y.foreground,dim:!0})));let E=new C2({padding:U5.symmetric(1,0),child:new a4({text:new h0("",void 0,A)})});return new C2({decoration:{border:W,color:k6.default()},padding:U5.all(1),child:new V2({children:[O,new S9({height:1}),N,new IK,E]})})}}class K10 extends v2{props;constructor(J){super();this.props=J}createState(){return new Cf4}}Jf();class jf4 extends y2{controller=new Lj;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new m$({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>=Nn)return!1;let Q=CZ1(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=L3.of(J),{colors:Y,app:X}=Q,V=DX.of(J).size.height,K=Math.max(Math.floor(V*0.5),10),W=new I81({controller:this.controller,triggers:[new kr],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(R)=>{this.widget.props.onSubmit(R.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:cG.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),U=new ZG({focusNode:this.focusNode,child:W}),N=new C2({constraints:new i3({maxHeight:K}),padding:U5.symmetric(1,0),child:U}),O=new C2({padding:U5.symmetric(1,0),child:new a4({text:new h0("",void 0,[new h0("Command: ",new U6({color:Y.foreground})),new h0(this.widget.props.commandName,new U6({color:k6.yellow,bold:!0}))])})}),A=new C2({padding:U5.symmetric(1,0),child:new a4({text:this.isConfirmingClearInput?new h0("",void 0,[new h0("Esc",new U6({color:X.keybind})),new h0(" again to clear input",new U6({color:Y.foreground,dim:!0}))]):new h0("",void 0,[new h0("Press ",new U6({color:Y.foreground,dim:!0})),new h0("Enter",new U6({color:X.keybind})),new h0(" to submit, ",new U6({color:Y.foreground,dim:!0})),new h0("Esc",new U6({color:X.keybind})),new h0(" to clear",new U6({color:Y.foreground,dim:!0}))])})}),E=[O,new S9({height:1}),new HQ({child:N}),new S9({height:1}),A];return new C2({decoration:{border:RY.all(new sQ(Y.foreground,1,"solid")),color:k6.default()},padding:U5.all(1),child:new V2({children:E})})}}class P81 extends v2{props;constructor(J){super();this.props=J}createState(){return new jf4}}class Xd0 extends $3{props;constructor(J){super();this.props=J}build(){return new YX({child:new a4({text:new h0("",void 0,[new h0(`Forked to new thread:
5507
+ ... (output truncated at ${fp} characters)`;Z({success:y,output:l.trim(),error:!y?p.trim()||"Command failed":void 0,exitCode:_??void 0})}),O.on("error",(_)=>{clearTimeout(N);let y=_.message;if(U)y=`Command timed out after ${Y}ms`;else if(_.message.includes("operation was aborted")||_.name==="AbortError")y="The command was aborted";Z({success:!1,output:A.join(""),error:y})})})}function $H5(J,Q){let{filePath:Y,interpreter:X,extension:Z}=J;if(process.platform==="win32")return ZH5(Y,X?[...X]:null,Z,Q);else return GH5(Y,X?[...X]:null,Z,Q)}function GH5(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function ZH5(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}U9();yk();iV();$m();kk();_k();Jf();dm();ea1();YV();ZD1();d5();EX1();import{writeFile as kf4}from"fs/promises";import yf4 from"path";U9();kk();class Qd0{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1763857589-g40edea"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await tl1(Q,this.configService)}catch(Q){I1.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 Yd0 extends v2{props;constructor(J){super();this.props=J}createState(){return new Rf4}}class Rf4 extends y2{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class Cf4 extends y2{controller=new Lj;focusNode=new m$({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=L3.of(J),{colors:Y,app:X}=Q,Z=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!Z||V,W=RY.all(new sQ(Y.foreground,1,"solid")),U=new K81({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(R)=>{let _=R.trim();if(Z&&_.length===0)return;this.widget.props.onSubmit(_)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),N=new hJ({children:[new C2({decoration:{color:k6.default()},child:new a4({text:new h0(">",new U6({color:Y.foreground}))})}),new HQ({child:U})]}),O=new C2({padding:U5.symmetric(1,0),child:new a4({text:new h0("",void 0,[new h0("Command: ",new U6({color:Y.foreground})),new h0(this.widget.props.commandName,new U6({color:k6.yellow,bold:!0}))])})}),A=[];if(K)A.push(new h0("Enter",new U6({color:X.keybind}))),A.push(new h0(" to submit, ",new U6({color:Y.foreground,dim:!0})));A.push(new h0("Esc",new U6({color:X.keybind}))),A.push(new h0(" to cancel",new U6({color:Y.foreground,dim:!0})));let E=new C2({padding:U5.symmetric(1,0),child:new a4({text:new h0("",void 0,A)})});return new C2({decoration:{border:W,color:k6.default()},padding:U5.all(1),child:new V2({children:[O,new S9({height:1}),N,new IK,E]})})}}class K10 extends v2{props;constructor(J){super();this.props=J}createState(){return new Cf4}}Jf();class jf4 extends y2{controller=new Lj;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new m$({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>=Nn)return!1;let Q=CZ1(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=L3.of(J),{colors:Y,app:X}=Q,V=DX.of(J).size.height,K=Math.max(Math.floor(V*0.5),10),W=new I81({controller:this.controller,triggers:[new kr],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(R)=>{this.widget.props.onSubmit(R.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:cG.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),U=new ZG({focusNode:this.focusNode,child:W}),N=new C2({constraints:new i3({maxHeight:K}),padding:U5.symmetric(1,0),child:U}),O=new C2({padding:U5.symmetric(1,0),child:new a4({text:new h0("",void 0,[new h0("Command: ",new U6({color:Y.foreground})),new h0(this.widget.props.commandName,new U6({color:k6.yellow,bold:!0}))])})}),A=new C2({padding:U5.symmetric(1,0),child:new a4({text:this.isConfirmingClearInput?new h0("",void 0,[new h0("Esc",new U6({color:X.keybind})),new h0(" again to clear input",new U6({color:Y.foreground,dim:!0}))]):new h0("",void 0,[new h0("Press ",new U6({color:Y.foreground,dim:!0})),new h0("Enter",new U6({color:X.keybind})),new h0(" to submit, ",new U6({color:Y.foreground,dim:!0})),new h0("Esc",new U6({color:X.keybind})),new h0(" to clear",new U6({color:Y.foreground,dim:!0}))])})}),E=[O,new S9({height:1}),new HQ({child:N}),new S9({height:1}),A];return new C2({decoration:{border:RY.all(new sQ(Y.foreground,1,"solid")),color:k6.default()},padding:U5.all(1),child:new V2({children:E})})}}class P81 extends v2{props;constructor(J){super();this.props=J}createState(){return new jf4}}class Xd0 extends $3{props;constructor(J){super();this.props=J}build(){return new YX({child:new a4({text:new h0("",void 0,[new h0(`Forked to new thread:
5508
5508
 
5509
5509
  `,new U6({color:k6.white,dim:!0})),new h0(`"${this.props.newThreadTitle||"Untitled"}"`,new U6({color:k6.white}))]),textAlign:"center"})})}}class hp extends v2{props;constructor(J){super();this.props=J}createState(){return new Sf4}}class Sf4 extends y2{_spinner=new Fh;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=L3.of(J),{colors:Y}=Q,X=RY.all(new sQ(Y.foreground,1,"solid")),Z=this._spinner.toBraille(),V=new a4({textAlign:"center",text:new h0("",void 0,[new h0(Z,new U6({color:k6.yellow})),new h0(" ",void 0),new h0(this.widget.props.message,new U6({color:Y.foreground}))])}),W=[new HQ({child:new V2({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)W.push(new S9({height:2,child:new C2({padding:U5.symmetric(2,0),child:new a4({text:new h0("",new U6({dim:!0}),[new h0("Press ",new U6({color:Y.foreground})),new h0("Esc",new U6({color:Y.info})),new h0(" to cancel",new U6({color:Y.foreground}))])})})}));let U=new C2({decoration:new z$(k6.default(),X),child:new S9({width:60,height:7,child:new V2({mainAxisAlignment:"start",children:W})})});if(this.widget.props.onAbort)return new ZG({debugLabel:"LoadingDialog",autofocus:!0,onKey:(N)=>{if(N.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:U});return U}}class bp extends v2{props;constructor(J){super();this.props=J}createState(){return new _f4}}class _f4 extends y2{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof Kh}build(J){let Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let N=Be1(Q);return{title:N.title,type:N.type,description:N.description}})(),X=Y.type==="error"?k6.red:k6.yellow,Z=RY.all(new sQ(k6.default(),1,"solid")),V=new C2({padding:U5.symmetric(1,0),child:new a4({text:new h0(Y.title,new U6({color:X,bold:!0}))})}),K=this.isWidgetMessage(Q)?Q.widget:new a4({text:new h0(Y.description,new U6({color:k6.default()})),selectable:!0}),W=new HQ({child:new Z81({child:new C2({padding:U5.symmetric(1,0),child:K})})}),U=new C2({padding:U5.symmetric(1,0),child:new a4({text:this.widget.props.onRetry?new h0("",void 0,[new h0("Press ",new U6({color:k6.default(),dim:!0})),new h0("R",new U6({color:k6.yellow})),new h0(" to retry, ",new U6({color:k6.default(),dim:!0})),new h0("Esc",new U6({color:k6.yellow})),new h0(" to cancel",new U6({color:k6.default(),dim:!0}))]):new h0("Press any key to close",new U6({color:k6.default(),dim:!0,italic:!0}))})});return new ZG({onKey:(N)=>{if(this.widget.props.onRetry&&N.key==="r")return this.widget.props.onRetry(),"handled";if(N.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 C2({decoration:{border:Z,color:k6.default()},padding:U5.all(1),child:new V2({mainAxisAlignment:"center",children:[V,new S9({height:1}),W,U]})})})}}class $d0 extends $3{build(){return new YX({child:new a4({text:new h0("",void 0,[new h0(`✓ Thread Shared
5510
5510
 
@@ -5590,7 +5590,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
5590
5590
  `)?`${W}...`:Z,N=new U6({color:k6.index(8)}),O=[new h0(U,N)];if(K>0){let A=new U6({color:Y.success});for(let E=1;E<=K;E++)O.push(new h0(" ")),O.push(new h0(`[${E}]`,A))}return new f3({padding:U5.only({bottom:0}),child:new hJ({crossAxisAlignment:"start",children:[new f3({padding:U5.only({right:1}),child:new a4({text:new h0("•",new U6({color:k6.index(8)}))})}),new HQ({child:new a4({text:new h0("",void 0,O)})})]})})}}class vd0 extends v2{createState(){return new Th4}}class Th4 extends y2{_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 U6({color:k6.red}),Y=new U6({color:this._visible?k6.red:k6.transparent()});return new hJ({children:[new a4({text:new h0("⏺",Y)}),new S9({width:1}),new a4({text:new h0("Replay",Q)})]})}}function Nz5(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/3600000),Z=Math.floor(X/24),V=Math.floor(Z/7),K=Math.floor(Z/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(Z<7)return`${Z}d ago`;if(V<=4)return`${V}w ago`;return`${K}mo ago`}class xd0{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{return{ok:!0,threads:(await new Promise((Z)=>{let V=this.threadHistoryService.observeThreadList().subscribe((K)=>{V.unsubscribe(),Z(K)})})).filter((Z)=>{if(!J.trim())return!0;let V=Z.title?.toLowerCase()||"untitled",K=Z.id.toLowerCase(),W=J.toLowerCase();return V.includes(W)||K.includes(W)}).map((Z)=>{let V=new Date(Z.userLastInteractedAt),K=Nz5(V),W=Z.id.slice(-8),U=Z.env?.initial.trees?.[0]?.uri;return{id:Z.id,title:Z.title||"Untitled",updatedAt:new Date(Z.userLastInteractedAt).toISOString(),description:{timeAgo:K,title:Z.title||"Untitled",shortThreadID:W},diffStats:Z.summaryStats?.diffStats,workspaceURI:U,parentRelationships:Z.parentRelationships}})}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}}U9();fG();class fd0{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new eN;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){I1.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){I1.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(N01()).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 Rh4(J,Q){switch(J){case"update-available":return[new h0("A newer Amp is available. Run ",new U6({color:Q.foreground,dim:!0})),new h0("amp update",new U6({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new h0("Update complete, run ",new U6({color:Q.foreground,dim:!0})),new h0("amp update",new U6({color:Q.warning})),new h0(" to see warnings",new U6({color:Q.foreground,dim:!0}))];case"update-error":return[new h0("Update failed, run ",new U6({color:Q.foreground,dim:!0})),new h0("amp update",new U6({color:Q.warning})),new h0(" to see warnings",new U6({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function Lz5(J){return new Promise((Q)=>{Mz5("git",["branch","--show-current"],{cwd:J},(Y,X)=>{if(Y){Q(null);return}let Z=X.trim();Q(Z||null)})})}class _h4 extends v2{dependencies;constructor(J){super();this.dependencies=J}createState(){return new kh4}}class kh4 extends y2{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;threadsForPicker=[];isLoadingThreads=!1;threadPreviewController=new fd0;previewThread=null;planScrollController=(()=>{let J=new eN;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new eN;return J.followMode=!1,J})();showingSelectionCopiedHint=!1;isShowingStandaloneThreadPicker=!1;filterThreadPickerByWorkspace=!0;agentModePulseSeq=0;currentGitBranch=null;messageViewFocusNode=new m$({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new m$({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;pendingMCPServers=[];mcpTrustSubscription=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=Gj();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.worker.thread.id;this.recordNavigation(J);let Q=await this.widget.dependencies.startNewThread();return this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,this.widget.dependencies.switchWorker(Q),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),Q};async startReplay(){let J=this.widget.dependencies.replayMode;if(!J)return;let{thread:Q,typingEnabled:Y,baseWpm:X}=J,Z=Q.messages;for(let V=0;V<Z.length;V++){if(this.replayAbortController.signal.aborted)break;let K=Z[V];if(!K)continue;if(V>0)await this.replaySleep(J.messageDelayMs);if(K.role==="user"&&Y){let N=K.content.filter((O)=>O.type==="text").map((O)=>O.text).join(`
5591
5591
  `);if(N)await this.replayTypeMessage(N,X)}if(K.role==="assistant"){let N=K.content.some((E)=>E.type==="tool_use"),O=Z[V+1],A=O?.role==="user"&&O.content.some((E)=>E.type==="tool_result");if(N&&A){let E={...K,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,E],this.textController.clear()});let R=J.thread.id;this.getMessageScrollController(R).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),K]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,K],this.textController.clear()});let W=J.thread.id;this.getMessageScrollController(W).scrollToBottom()}await this.replaySleep(J.exitDelayMs),cG.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Y=J.split(/(?<=\s)/),X=60000/Q;for(let Z of Y){if(this.replayAbortController.signal.aborted)break;let V=X/Z.length;for(let K of Z){this.textController.text=this.textController.text+K,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let W=0.8+Math.random()*0.4,U=V*W;await this.replaySleep(U)}}}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return mt1(this.widget.dependencies.worker.thread,this.inMemoryAgentModeOverride?{agentMode:this.inMemoryAgentModeOverride}:null,this.freeTierStatus,{"experimental.agentMode":this.currentAgentMode})}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Y=J.items.filter((V)=>V.type==="toolResult").filter((V)=>V.toolResult.run.status==="in-progress"||V.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((V)=>V.toolRun.status==="in-progress"||V.toolRun.status==="queued");return[...Y,...X].length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new h0(this.submitDisabledHint,new U6({color:J.foreground,dim:!0}));if(this.isExiting)return new h0("Exiting...",new U6({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new h0("",void 0,[new h0("Ctrl+C",new U6({color:Q.keybind})),new h0(" again to exit",new U6({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new h0("",void 0,[new h0("Esc",new U6({color:Q.keybind})),new h0(" again to clear input",new U6({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new h0("",void 0,[new h0("Escape",new U6({color:Q.keybind})),new h0(" to close help",new U6({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let Z=this.getEffectiveAgentMode(),V=gd0(Z);return new h0("",void 0,[new h0("Images aren't supported in ",new U6({color:J.warning,dim:!1})),new h0(Z,new U6({color:V})),new h0(" mode.",new U6({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new h0("",void 0,[new h0("Esc",new U6({color:Q.keybind})),new h0(" again to cancel",new U6({color:J.foreground,dim:!0}))]);return new h0("",void 0,[new h0("Esc",new U6({color:Q.keybind})),new h0(" to cancel",new U6({color:J.foreground,dim:!0}))])}if(this.showingSelectionCopiedHint)return new h0("Selection copied to clipboard",new U6({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new h0(this.showingCannotToggleMessage,new U6({color:J.warning,dim:!1}));let Y=Rh4(this.updateState,J);if(Y)return new h0("",void 0,Y);let X=this.widget.dependencies.worker.thread;if(X.agentMode==="plan"&&Y81(X))return new h0("",void 0,[new h0("Ctrl+O",new U6({color:Q.keybind})),new h0(" → Execute Plan",new U6({color:J.foreground,dim:!0}))]);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Y}=this.widget.dependencies;if(!Q.mainThread?.id)return;let Z=Q.mainThread?.messages.findIndex((V)=>V===J);if(Z===void 0||Z===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),await Y.handle({type:"thread:truncate",fromIndex:Z}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){I1.error("Failed to edit message:",V)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Y,threadSyncService:X}=this.widget.dependencies,Z=Q.mainThread?.id;if(!Z)return;let V=Q.mainThread?.messages.findIndex((K)=>K===J);if(V===void 0||V<=0)return;try{let K=await wB.getOrCreateForThread(Y,Z),W=await tG1(K,X,V-1);await this.switchToExistingThread(W)}catch(K){I1.error("Failed to fork thread:",K),this.showErrorMessage(`Failed to fork thread: ${K}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Y,worker:X}=this.widget.dependencies,Z=Y.mainThread;if(!Z)return;let V=Z.messages.findIndex((K)=>K.messageId!==void 0&&K.messageId===J.messageId);if(V===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let K=Ir(Q);if(K)await X.handle({type:"thread:truncate",fromIndex:V}),this.invokeBashCommand(K.cmd,{visibility:K.visibility});else{let W=[{type:"text",text:Q}];if(this.imageAttachments.length>0)W.push(...this.imageAttachments);let U={content:W,agentMode:Z.agentMode},N=V===0;if(Z.agentMode&&!N&&U.agentMode!==Z.agentMode){I1.error(`Cannot edit message: This thread uses ${Z.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:U,index:V})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(K){I1.error("Failed to edit message:",K)}};getAffectedFiles=async(J)=>{let{worker:Q}=this.widget.dependencies;try{return(await Q.getFilesAffectedByTruncation(J)).map((X)=>{try{return new URL(X).pathname}catch{return X}})}catch(Y){return I1.error("Failed to get affected files:",Y),[]}};textController=new Lj;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new eN);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Z=this.searchElementTreeByKey(X,Q);if(Z)return Z}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=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Y=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Y}`:"";process.stdout.write(hu0(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new uz("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Y=Ir(J)?.visibility;if(Y!==this.currentShellModeStatus)this.currentShellModeStatus=Y,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),dG.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Q)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.loadThreadsForPicker(),this.setState(()=>{this.isShowingStandaloneThreadPicker=!0})};dismissStandaloneThreadPicker=()=>{this.exitApplication()};handleStandaloneThreadSelect=async(J)=>{try{await this.switchToExistingThread(J,{recordInNavigationHistory:!1}),this.threadPreviewController.clear(),this.setState(()=>{this.isShowingStandaloneThreadPicker=!1}),dG.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker)this.autocompleteFocusNode.requestFocus()})}catch(Q){I1.error("Failed to switch thread:",Q),this.showErrorMessage(`Failed to switch thread: ${Q}`)}};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};showCommandPalette(){if(this.setState(()=>{this.isShowingPalette=!this.isShowingPalette}),this.isShowingPalette)this.loadThreadsForPicker()}getPaletteCommands(){if(!this.paletteCommands)this.paletteCommands=new Zd0(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.widget.dependencies.isDogfooding);return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Kd0(this.widget.dependencies.fuzzyServer,this.widget.dependencies.threadFuzzyIndexer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1})};getCommandPaletteContext=()=>{let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return null;let Q=a5.file(process.cwd()),Y=C7(Q);return{worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:J.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let X=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),X},setImageAttachments:(X)=>{this.setState(()=>{this.imageAttachments=X})},editorDispatch:(X)=>{switch(X.type){case"set-input":this.textController.clear(),this.textController.insertText(X.input);break;case"insert-text":this.textController.insertText(X.text);break;case"clear":this.textController.clear();break}},submitMessage:(X)=>{return this.proceedWithUserMessage(X)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,mcpService:this.widget.dependencies.mcpService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus?.canUseAmpFree??!1,switchToThread:async(X)=>{return await this.switchToExistingThread(X),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(X,Z,V)=>{let K=this.widget.dependencies.threadState.mainThread?.id;if(!K)throw Error("No active thread");let W=setTimeout(()=>{V.throwIfAborted()},60000);try{let U=await this.widget.dependencies.threadService.generateHandoffPrompt(K,X,Z,this.widget.dependencies.configService,V);return clearTimeout(W),U}catch(U){throw clearTimeout(W),U}},handleHandoff:async(X,Z)=>{let{goal:V,generatedPrompt:K,images:W}=Z;if(!V&&!K)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let U=this.widget.dependencies.threadState.mainThread?.id;if(!U)return{ok:!1,error:Error("No active thread")};let N=setTimeout(()=>X.abort(new q10("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let O=await this.widget.dependencies.threadService.createHandoffThread(U,{goal:V,generatedPrompt:K,images:W},this.widget.dependencies.configService,X.signal);return clearTimeout(N),await this.switchToExistingThread(O),{ok:!0}}catch(O){if(clearTimeout(N),O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")))throw X.signal.reason;throw O}}catch(U){return I1.error("Failed to create handoff thread",U),{ok:!1,error:U instanceof Error?U:Error(String(U))}}},getGuidanceFiles:async(X)=>{if(!J.mainThread)return[];return(await Vl1({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},J.mainThread,X)).map((V)=>({uri:V.uri,type:V.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(X)=>{this.setState(()=>{this.inMemoryAgentModeOverride=X,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,handleExecutePlan:async()=>{try{let X=J.mainThread?.id;if(!X){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let Z=await this.widget.dependencies.threadService.createPlanExecutionThread(X,"smart");await this.switchToExistingThread(Z)}catch(X){I1.error("Failed to execute plan",X),this.setState(()=>{this.displayMessage=Error(`Failed to execute plan: ${X instanceof Error?X.message:String(X)}`)})}},planFileManager:this.widget.dependencies.planFileManager,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:Y,threadViewStates:this.widget.dependencies.workerController.threadViewStates}};async loadThreadsForPicker(){if(this.isLoadingThreads)return;this.setState(()=>{this.isLoadingThreads=!0});try{let Q=await new xd0(this.widget.dependencies.threadHistoryService).fetchThreadSummaries();if(Q.ok)this.setState(()=>{this.threadsForPicker=Q.threads})}finally{this.setState(()=>{this.isLoadingThreads=!1})}}updateGitBranch=async()=>{let J=await Lz5(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{visibility:Q})=>{let Y=Date.now(),X=`bash-${Y}-${Math.random().toString(36).substring(7)}`,Z={cmd:J},V=new AbortController;this.widget.dependencies.worker.invokeBashTool(Z,V.signal,Q===Er).subscribe({next:(K)=>{this.setState(()=>{if(this.bashInvocations.find((U)=>U.id===X))this.bashInvocations=this.bashInvocations.map((U)=>U.id===X?{...U,toolRun:K}:U);else{let U={id:X,args:Z,toolRun:K,startTime:Y,abortController:V,hidden:Q===Er};this.bashInvocations=[...this.bashInvocations,U]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};toggleAgentMode=()=>{let J=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(Kk(J.thread)>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.getEffectiveAgentMode(),Z=aE1(X,this.cachedVisibleModes);if(Z!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Z,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.getEffectiveAgentMode(),Y=aE1(Q,this.cachedVisibleModes);if(Y===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),XV(Y))this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus){if(!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(!this.freeTierStatus.workspaceAllowsAmpFree){this.setState(()=>{this.showingCannotToggleMessage="Your workspace does not allow Amp Free. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!AE1(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>=Nn)return!1;let Y=CZ1(J);if(typeof Y==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Y}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Y,unlink:X,rmdir:Z,writeFile:V}=await import("node:fs/promises"),{tmpdir:K}=await import("node:os"),W=await import("node:path");try{let U=await Q(W.join(K(),"amp-edit-")),N=W.join(U,"message.amp.md");await V(N,J,"utf-8"),await jp(N);try{let O=await Y(N,"utf-8");this.textController.text=O}catch(O){if(O?.code!=="ENOENT")I1.error("Failed to read temporary file",O)}try{await X(N),await Z(U)}catch(O){I1.warn("Failed to clean up temporary file",O)}}catch(U){I1.error("Error opening editor:",U)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=Ir(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};initState(){if(ZT.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();cG.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),cG.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),cG.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Y)=>{dG.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus,A7(this.widget.dependencies.configService.config).then((Y)=>{let X=mt1(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,Y.settings);if(I1.info(`[initState] Resolved agentMode: ${X}`),this.widget.dependencies.sessionState?.agentMode)this.setState(()=>{this.inMemoryAgentModeOverride=X})}),this.updateGitBranch(),this.adSubscription=Xg0(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride&&XV(this.inMemoryAgentModeOverride)||this.randomAd===null)&&Yg0(this.lastUserInteractionTime)}).subscribe({next:(Y)=>{if(Y){let X=Oz5(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (C10(),R10)).then(({recordAdEvent:Z})=>{let V=this.widget.dependencies.worker.thread,K=V.messages[V.messages.length-1];Z("viewed",{adId:Y.id,advertiserId:Y.advertiserId,threadId:V.id,messageId:K?.messageId,impressionId:X,placement:"tui",matchType:Y.metadata?.matchType,matchedPatterns:Y.metadata?.matchedPatterns,candidateAdPoolCount:Y.metadata?.candidateAdPoolCount,clientRegion:Y.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=Y}),dG.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}});let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Y)=>{this.setState(()=>{this.pendingMCPServers=Y})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Y)=>{this.setState(()=>{this.ideStatus=Y})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Y)=>{let X=this.widget.dependencies.getCurrentWorker();if(!X){I1.warn("No active thread worker found to handle IDE message");return}await new Promise((Z)=>setTimeout(Z,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}}),I1.debug("Message sent from IDE to agent",{message:Y.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Y)=>{this.textController.insertText(Y),I1.debug("Appended text to CLI prompt from IDE",{text:Y.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Y)=>{this.setState(()=>{this.connectedClientsStatus=Y})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Y)=>{this.setState(()=>{this.updateState=Y})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Y)=>{let X=Gj(Y.settings,this.freeTierStatus?.canUseAmpFree);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Y)=>{let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100)}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.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(hu0("")),this.shouldUseProgressBar())process.stdout.write(m_4())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((W)=>W.type==="toolResult").map((W)=>({toolUse:W.toolUse,toolRun:W.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((W)=>W.toolRun.status==="blocked-on-user");if(X.length===0)return null;let Z=X[0],V=Z.toolRun.status==="blocked-on-user"?Z.toolRun.toAllow??[]:[],K=Z.toolRun.status==="blocked-on-user"?Z.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:Z.toolUse,toAllow:V}],subthreadID:Z.subthreadID,reason:K}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){I1.error("No current tool confirmation found");return}let Y=Q.tools[0]?.useBlock;if(!Y){I1.error("No tool use block found in confirmation");return}if(J==="allow-all-session")Qk("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(Z){if(Z&&Z instanceof Error)this.setState(()=>{this.displayMessage=Z});else I1.error("Failed to write dangerouslyAllowAll setting:",Z);return}if(J==="always-guarded"){let Z=Q.tools[0]?.toAllow??[],V=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],K=[...Z,...V];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",K,"global")}if(J==="connect-github"){let Z=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await EO(Z)}catch(V){I1.error("Failed to open settings page:",V),await this.showErrorMessage(`Cannot open browser. Please go to ${Z} to connect to GitHub`)}return}if(J==="disable-librarian"){let Z=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!Z.includes(IP))await this.widget.dependencies.settingsStorage.set("tools.disable",[...Z,IP],"global")}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Z={type:"user:tool-input",toolUse:Y.id,value:{accepted:X}};if(Q.subthreadID)await(await wB.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Z);else await this.widget.dependencies.worker.handle(Z)}catch(Z){I1.error("Failed to send tool confirmation:",Z)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Y=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Y)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Y=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Y.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null}),await this.startAndSwitchToNewThread();break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),It1({agentMode:"smart"}),await this.startAndSwitchToNewThread();break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Q}=this.widget.dependencies;await J.deny();try{await jp(Q.getSettingsFilePath())}catch(Y){let X=Y instanceof Error?Y.message:String(Y);await this.showErrorMessage(`Failed to open settings: ${X}`)}};cancelStreamingMessage=async()=>{await wB.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Y=J.messages[Q];if(Y?.role==="user"&&!Y.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J,Q={})=>{let{recordInNavigationHistory:Y=!0}=Q;if(Y){let X=this.widget.dependencies.worker.thread.id;if(X!==J)this.recordNavigation(X)}try{I1.info(`[switchToExistingThread] Switching to thread: ${J}`);let X=await this.widget.dependencies.switchToThread(J);I1.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${X.thread.agentMode}`);let Z=await this.widget.dependencies.configService.getLatest(),V=mt1(X.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,Z.settings);if(I1.info(`[switchToExistingThread] Thread ${J} resolved agentMode: ${V}`),this.widget.dependencies.worker=X,this.widget.dependencies.threadID=X.thread.id,this.widget.dependencies.switchWorker(X),this.setState(()=>{I1.info("[switchToExistingThread] Clearing inMemoryAgentModeOverride"),this.inMemoryAgentModeOverride=null}),X.thread.draft)if(I1.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof X.thread.draft==="string")this.textController.insertText(X.thread.draft);else{let K=X.thread.draft.filter((N)=>N.type==="text"),W=X.thread.draft.filter((N)=>N.type==="image"),U=K.map((N)=>N.text).join(`
5592
5592
  `);if(U)this.textController.insertText(U);if(W.length>0)this.setState(()=>{this.imageAttachments=W})}}catch(X){throw I1.error("Failed to switch to thread:",J,X),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,Y=Kk(Q.thread)===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Y&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let Z=[{type:"text",text:J}];if(this.imageAttachments.length>0)Z.push(...this.imageAttachments);if(await Q.handle({type:"user:message",message:{content:Z,agentMode:X}}),Y)It1({agentMode:X});this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]}),dG.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((X)=>X.type==="handoff"&&X.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();It1({agentMode:Q}).catch((Y)=>{I1.warn("Failed to save session state on exit:",Y)}).finally(()=>{cG.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=Az5();if(J===Q)return"~";if(J.startsWith(Q+cP1.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(cP1.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(cP1.sep),"…",Q.slice(-2).join(cP1.sep)].join(cP1.sep)}build(J){let Q=DX.of(J),Y=L3.of(J),X=Y.base;this.themeColors=X;let{colors:Z,app:V}=Y;this.themeApp=V;let K=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,W=K.thread.agentMode&&XV(K.thread.agentMode)&&this.randomAd!==null,{threadState:U}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let N=this.getCurrentConfirmation(),O=this.widget.dependencies.replayMode,A=Boolean(O),E=U.items,R=U.mainThread||void 0,_=U.subagentToolsByParentID,y=U.todosList;if(A){let U2={...O.thread,messages:this.replayDisplayedMessages};E=lZ1(U2).items,R=U2,_={};let E5=UY1({messages:this.replayDisplayedMessages});y=Array.isArray(E5)?E5:[]}let h=R?.id,p=R,l=A?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),o=(U2)=>new $10({key:new uz(`preview-message-view-${U2.id}`),items:lZ1(U2).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:U2,focusNode:new m$({debugLabel:"PreviewFocus"})}),r=this.previewThread,q1=r?r.messages.length>2000?new V2({mainAxisSize:"max",children:[new HQ({child:new S9}),new f3({padding:U5.all(2),child:new YX({child:new a4({text:new h0("Thread too long for preview",new U6({color:Z.mutedForeground,dim:!0}))})})})]}):o(r):l?new Z10({agentMode:this.getEffectiveAgentMode()}):new $10({key:h?new uz(`message-view-${h}`):void 0,items:E,subagentToolsByParentID:_,controller:h?this.getMessageScrollController(h):new eN,autofocus:!1,onCopy:A?void 0:this._handleTextCopy.bind(this),thread:p,onMessageEditSubmit:A?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:A?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:A?void 0:this.forkMessage,getAffectedFiles:A?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),K1=Math.max(Math.floor(Q.size.height*0.4),12),H1=this.getCurrentEphemeralError(),b1=this.buildBottomWidget(H1,N,Z,Y,U,y,K1,W?this.randomAd:null,A),x1=Q.size.width<40,h1=U.mainThread?bn6(U.mainThread):void 0,e1=new Ae1({threadViewState:U.viewState,threadTokenUsage:h1,threadID:h??null,thread:U.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:x1,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!N,showingEphemeralError:Boolean(U.viewState.state==="active"&&U.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),T0=new Oe1({bashInvocations:this.bashInvocations}),A0=[],S1=this.getEffectiveAgentMode(),P0=this.currentShellModeStatus,e0=gd0(S1),H0=!P0?S1.length+1:0,D0=Q.capabilities.animationSupport,B0=D0==="disabled"?0:D0==="slow"?30:60,Z0=nf(S1)?.uiHints?.fasterAnimation?3:1,m0=B0>0&&this.agentModePulseSeq>0?new JW({children:[b1,new tN({top:0,left:1,right:1,height:1,child:new _d0({color:e0,trigger:this.agentModePulseSeq,fps:B0,speed:Z0,leftOffset:H0})})]}):b1;A0.push(new HQ({child:q1}),T0);let s6=new JW({children:[new V2({mainAxisSize:"min",children:[W?new sp0({ad:this.randomAd,onButtonClick:async()=>{let U2=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (C10(),R10)).then(({recordAdEvent:E5})=>{let b8=this.widget.dependencies.worker.thread,n3=b8.messages[b8.messages.length-1];E5("clicked",{adId:U2.id,advertiserId:U2.advertiserId,threadId:b8.id,messageId:n3?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:U2.metadata?.matchType,matchedPatterns:U2.metadata?.matchedPatterns,candidateAdPoolCount:U2.metadata?.candidateAdPoolCount,clientRegion:U2.metadata?.clientRegion})});try{await EO(U2.shortDestinationUrl)}catch(E5){let n3=cG.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:n3,url:U2.shortDestinationUrl}})}}}):new S9({height:0}),new C2({constraints:new i3(0,Q.size.width,0,K1),child:m0})]}),W?new tN({top:0,left:0,right:0,child:new xh4({userHeight:this.bottomGridUserHeight,maxHeight:K1,onInitializeHeight:(U2)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(U2,K1)})},onDrag:(U2)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(U2.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let E5=Math.floor(U2.localPosition.y)-this.bottomGridDragStartY,b8=Math.max(4,this.bottomGridDragStartHeight-E5),n3=Math.min(b8,K1),PX=Math.floor(n3);if(this.bottomGridUserHeight!==PX)this.setState(()=>{this.bottomGridUserHeight=PX})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new S9({height:0})]});A0.push(s6,new S9({height:1,child:new f3({padding:U5.horizontal(1),child:e1})}));let C0=new V2({crossAxisAlignment:"stretch",mainAxisSize:"max",children:A0}),F4=A?new JW({children:[C0,new tN({top:0,left:0,child:new vd0})]}):C0,R6=new GG(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((E5)=>{I1.error("Failed to mark message as interrupted:",E5)}),this.cancelStreamingMessage().catch((E5)=>{I1.error("Failed to cancel streaming message:",E5)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return I1.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"}),f4=new GG(()=>{return this.onExitPressed(),"handled"}),S6=new GG(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),e4=new GG(()=>{return BM.instance.toggleAll(),"handled"}),y0=new GG(()=>{return this.widget.dependencies.configService.getLatest().then((U2)=>{Qk("internal.showCost",!(U2.settings["internal.showCost"]??!0))}),"handled"}),F0=new GG(()=>{return cG.instance.toggleFrameStatsOverlay(),"handled"}),l0=new GG(()=>{return cG.instance.tuiInstance.getScreen().markForRefresh(),dG.instance.requestFrame(),"handled"}),X6=new GG(()=>{return this.toggleAgentMode(),"handled"}),r1=new GG(()=>{let E5=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:b8}=this.widget.dependencies,n3=b8.mainThread?.id;return n3?this.getMessageScrollController(n3):null})();if(E5){let b8=Math.max(Math.floor(Q.size.height*0.4),10),n3=Q.size.height-b8;E5.animatePageUp(n3,100)}return"handled"}),z6=new GG(()=>{let E5=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:b8}=this.widget.dependencies,n3=b8.mainThread?.id;return n3?this.getMessageScrollController(n3):null})();if(E5){let b8=Math.max(Math.floor(Q.size.height*0.4),10),n3=Q.size.height-b8;E5.animatePageDown(n3,100)}return"handled"}),O6=new GG(()=>{let E5=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:b8}=this.widget.dependencies,n3=b8.mainThread?.id;return n3?this.getMessageScrollController(n3):null})();if(E5)E5.animateTo(0,100);return"handled"}),H4=new GG(()=>{let E5=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:b8}=this.widget.dependencies,n3=b8.mainThread?.id;return n3?this.getMessageScrollController(n3):null})();if(E5)E5.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),s4=new GG(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:U2}=this.widget.dependencies;if(!U2.mainThread?.messages.some((b8)=>b8.role==="user"||FY1(b8)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),f8=new GG((U2)=>{if(U2.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),P8=new GG(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return Ue1().then(async(U2)=>{if(U2)try{this.handleInsertImage(U2)}finally{try{let{unlink:E5}=await import("node:fs/promises");await E5(U2)}catch{}}}),"handled"}),V9=new Map([[sJ.ctrl("c"),new MP1],[sJ.ctrl("l"),new EP1],[sJ.ctrl("o"),new $e1],[sJ.ctrl("v"),new NP1],[sJ.alt("s"),new SZ1],[sJ.ctrl("s"),new SZ1],[sJ.alt("p"),new wP1],[sJ.ctrl("r"),new AP1],[sJ.alt("d"),new LP1],[sJ.ctrl("t"),new IP1],[sJ.key("PageUp"),new Je1],[sJ.key("PageDown"),new Qe1],[sJ.key("Home"),new Ye1],[sJ.key("End"),new Xe1],[sJ.key("Escape"),new DP1],[sJ.ctrl("p"),new _Z1("previous")],[sJ.ctrl("n"),new _Z1("next")],[sJ.key("Tab"),new PP1]]);if(!EU())V9.set(sJ.key("ArrowUp"),new PP1);if(!1)V9.set(sJ.alt("c"),new OP1);let $7=new GG(()=>{if(this.isShowingStandaloneThreadPicker)return"handled";return this.showCommandPalette(),"handled"}),b3=new GG(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),tJ=new Map([[DP1,R6],[EP1,l0],[SZ1,X6],[$e1,$7],[NP1,P8],[OP1,S6],[AP1,e4],[LP1,y0],[wP1,F0],[IP1,b3],[MP1,f4],[Je1,r1],[Qe1,z6],[Ye1,O6],[Xe1,H4],[PP1,s4],[_Z1,f8]]),j7=[F4];if(this.isShowingConsoleOverlay)j7.push(new zd0);if(this.isShowingHelp){let U2=this.getPaletteCommands().getAllCommands();j7.push(new Bd0({commands:U2}))}if(this.adActionModal)j7.push(new tp0({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(U2)=>{let E5=this.adActionModal.url;if(U2==="copy")try{await cG.instance.tuiInstance.clipboard.writeText(E5),this.setState(()=>{this.displayMessage=new HT("Link copied to clipboard")})}catch(b8){I1.error("Failed to copy to clipboard",{error:b8}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:U2}=this.widget.dependencies;j7.push(new kd0({servers:this.pendingMCPServers,onAlwaysTrust:U2.trustAlways.bind(U2),onTrustOnce:U2.trustOnce.bind(U2),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:U2.deny.bind(U2)}))}if(this.isShowingFileChangesOverlay)j7.push(new eg0({threadData:U}));if(this.isShowingCostBreakdownOverlay&&U.mainThread)j7.push(new Fd0({thread:U.mainThread}));if(this.isShowingConfirmationOverlay)j7.push(new Wd0({details:this.confirmationOverlayContent}));let G9=this.getCommandPaletteContext();if(G9&&this.isShowingPalette)j7.push(new YX({child:new C2({constraints:i3.loose(80,20),child:new Vd0({commandContext:G9,mainThread:U.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette})})}));if(this.isShowingIdePicker)j7.push(new Dd0({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));if(this.isShowingStandaloneThreadPicker){let U2=a5.file(process.cwd()),E5=C7(U2);j7.push(new YX({child:new C2({constraints:i3.loose(80,20),child:new fZ1({threads:this.threadsForPicker,title:"Continue Thread",onSelect:this.handleStandaloneThreadSelect,onDismiss:this.dismissStandaloneThreadPicker,previewController:this.threadPreviewController,isLoading:this.isLoadingThreads,currentWorkspaceURI:E5,filterByWorkspace:this.filterThreadPickerByWorkspace,threadViewStates:this.widget.dependencies.workerController.threadViewStates})})}))}let a9=new JW({children:j7});if(this.isShowingJetBrainsInstaller)return new V81({child:new IL({actions:tJ,child:new $y({shortcuts:V9,debugLabel:"jetbrains-installer-shortcuts",child:new Sd0({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let k4=new Pr({onError:(U2)=>{this.showErrorMessage(U2.message)},child:a9});return new V81({child:new IL({actions:tJ,child:new $y({shortcuts:V9,debugLabel:"main-app-shortcuts",child:k4})})})}buildScrollableTodoList(J,Q,Y){return new yh4({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Y})}buildBottomWidget(J,Q,Y,X,Z,V,K,W,U){if(J)return new Ud0({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Hd0({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new yd0({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let N=X.app,O=Me1(X),A=this.isInRestrictedFreeMode(),E=new I81({key:this.textFieldKey,controller:this.textController,triggers:U?[]:[new kr],completionBuilder:U?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:U?void 0:this.onTextSubmitted,theme:Y,placeholder:U?"Press Ctrl+C to exit":A?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!A&&!this.isShowingStandaloneThreadPicker,shellPromptRules:O,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker,clipboard:cG.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage}),R=Z.mainThread?.queuedMessages??[],_=Array.isArray(V)&&V.length>0,y=Array.isArray(R)&&R.length>0,h=Z.mainThread?.agentMode==="plan"&&Y81(Z.mainThread),p,l;if(h){if(p=new wg0(new G10({thread:Z.mainThread,onExecute:async()=>{let h1=this.getCommandPaletteContext();if(h1)await this.getPaletteCommands().execute("execute-plan",h1,void 0,new AbortController)},onEdit:async()=>{try{let h1=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:e1}=await this.widget.dependencies.planFileManager.ensureSync(Z.mainThread.id);cG.instance.tuiInstance.suspend();let{execSync:T0}=await import("child_process");T0(`${h1} "${e1}"`,{stdio:"inherit"}),cG.instance.tuiInstance.resume()}catch(h1){I1.error("Failed to edit plan",h1),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:X}),{clipBehavior:"antiAlias"}),y)l=new T10({queuedMessages:R});else if(_)l=this.buildScrollableTodoList(V,this.isTextfieldAndAutocompleteFocused&&!A,X)}else p=y?new T10({queuedMessages:R}):void 0,l=_?this.buildScrollableTodoList(V,this.isTextfieldAndAutocompleteFocused&&!A,X):void 0;let o=[],r=this.currentShellModeStatus;if(r)o.push({text:new h0(r==="hidden"?"shell mode (incognito)":"shell mode",new U6({color:r==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left"});if(!r&&this.cachedVisibleModes.length>1){let h1=this.previewThread,e1=h1?h1.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),T0=gd0(e1);if(h1)o.push({text:new h0(e1,new U6({color:T0})),position:"top-left",offsetY:0});else{let S1=aE1(e1,this.cachedVisibleModes)!==e1,P0=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,e0=Kk(P0.thread)===0,D0=A||!this.hasToggledAgentMode&&S1&&e0?new h0("",void 0,[new h0(e1,new U6({color:T0})),new h0(" (click or ",new U6({color:Y.foreground,dim:!0})),new h0("Ctrl+S",new U6({color:N.keybind})),new h0(" to switch)",new U6({color:Y.foreground,dim:!0}))]):new h0(e1,new U6({color:T0}));o.push({text:D0,position:"top-left",offsetY:0,onClick:e0?this.toggleAgentMode:void 0})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let h1=this.connectedClientsStatus,e1=h1.mode||"disconnected",T0=!!h1.errorMessage,A0=h1.clientID||"unknown",S1,P0;if(T0)S1="●",P0=k6.red;else if(e1==="presence")S1="○",P0=k6.yellow;else if(e1==="connected"&&h1.connected)S1="●",P0=k6.green;else S1="○",P0=k6.yellow;let e0=this.connectedClientsStatusExpanded?`${A0} ${S1}`:S1;o.push({text:new h0(e0,new U6({color:P0})),position:"top-right",offsetX:-2,offsetY:0,onClick:this.toggleConnectedClientsStatus})}let q1=U?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:Z.mainThread?.env?.initial.trees?.[0]?.uri,K1;if(q1)K1=a5.parse(q1).fsPath;else K1=process.cwd();let H1=this.toHomeRelative(K1),b1=this.shorten(H1),x1=!U&&this.currentGitBranch?`${b1} (${this.currentGitBranch})`:b1;return o.push({text:new h0(x1,new U6({color:Y.foreground,dim:!0})),position:"bottom-right"}),new cg0({leftChild:new HQ({child:E}),rightChild1:p,rightChild2:l,maxHeight:K,overlayTexts:o,borderColor:A||!this.isTextfieldAndAutocompleteFocused?k6.index(8):void 0,hasBanner:W!==null,userHeight:this.bottomGridUserHeight,onInitializeHeight:(h1)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(h1,K)})},onDrag:(h1)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(h1.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let e1=Math.floor(h1.localPosition.y)-this.bottomGridDragStartY,T0=Math.max(4,this.bottomGridDragStartHeight-e1),A0=Math.min(T0,K),S1=Math.floor(A0);if(this.bottomGridUserHeight!==S1)this.setState(()=>{this.bottomGridUserHeight=S1})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:W===null})}}async function md0(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)cG.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let X=()=>null,V=!1,K=new Rp(V,1000,J.inspectorPort),W=J.features?.find((h)=>h.name==="amp-connect")?.enabled??!1,U=new rp0({threadService:J.threadService,worker:J.worker,builder:(h,p,l,o,r)=>{if(X=r,J.threadDependencies&&W)qg0(J.threadDependencies,J.configService,r,o,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((b1)=>{I1.error("Failed to start automatic presence:",b1)});let q1=r(),K1=q1.thread.id,H1={...J,worker:q1,threadID:K1};return new _h4({...H1,threadState:p,workerController:l,switchWorker:o,getCurrentWorker:r})}}),N=new rg0({configService:J.configService,child:U}),O=new ig0({configService:J.configService,child:N}),A=new yg0(O),E=new L3({data:yZ1.fromBaseTheme(Aj.default()),child:A});try{await tu0(E,{onRootElementMounted:(h)=>{if(I1.info("TUI input ready for user interaction"),V)K.start(h)}})}finally{if(V)K.stop();if(J.threadDependencies&&W){let{stopGlobalSession:h}=await Promise.resolve().then(() => (Vg0(),yk4));h()}}let _=X()?.thread.id||J.threadID,y=await J.threadService.get(_);if(y&&y.messages.length>0){let h=`${J.ampURL.replace(/\/$/,"")}/threads/${_}`;Qy4(y,h,J.stdout)}}function gd0(J){return J==="smart"?k6.rgb(145,119,199):J==="rush"?k6.rgb(228,180,2):XV(J)?k6.rgb(0,184,255):J==="plan"?k6.rgb(153,102,255):wz5(J)}class yh4 extends v2{props;constructor(J){super();this.props=J}createState(){return new vh4}}class vh4 extends y2{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,controller:Y,appTheme:X}=this.widget.props;return new hJ({crossAxisAlignment:"stretch",children:[new HQ({child:new hF({controller:Y,autofocus:!1,child:new op0({todos:Q})})}),new FT({controller:Y,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:Z,offset:V}=Y,K=this.viewportHeight,W=Z+K;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(K,1),scrollOffset:Math.max(V,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(X,Z=0)=>{if(X&&"size"in X&&"children"in X){let V=X.children||[];for(let K of V){if(K&&"size"in K){let U=K.size;if(typeof U?.height==="number"&&U.height>0)return U.height}let W=Q(K,Z+1);if(W>0)return W}}return 0},Y=Q(J);if(Y>0)return Y;if("size"in J){let X=J.size;if(typeof X?.height==="number"&&X.height>0)return X.height}return this.viewportHeight}}class xh4 extends $3{props;constructor(J){super();this.props=J}build(J){return new H$({child:new S9({height:1}),cursor:hZ.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let X=J.findRenderObject()?.size.height??0;if(X>0){this.props.onInitializeHeight(X);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function wz5(J){let Q=0;for(let Z=0;Z<J.length;Z++){let V=J.charCodeAt(Z);Q=(Q<<5)-Q+V,Q=Q&Q}let Y=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Y.length;return k6.index(Y[X])}su0();try{if(process.platform==="win32")await Promise.resolve().then(() => _7(Wq1(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){Sj.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
5593
- `)}var Nl0=Bl0.join(Nl6||Bl0.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function lN5(J){process.emitWarning=function(Q,Y,X,Z){let V=typeof Q==="string"?Q:Q.message||String(Q),K=Y||"Warning",W=!1;J.warn(V,{name:K,code:X})}}function Wy(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")Qk("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")Qk("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")Qk("model.sonnet",Q.useSonnet)}async function Ml0(J){try{await pN5(Bl0.dirname(Nl0),{recursive:!0}),await dN5(Nl0,J,"utf-8")}catch(Q){I1.debug("Failed to save last thread ID",Q)}}async function iN5(){try{return(await qm4(Nl0,"utf-8")).trim()}catch(J){return null}}var $m4=[{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??Bj,description:`Custom settings file path (overrides the default location ${Bj})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(I1).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Yu0})`},{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:EU(),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 Gemini 3":"Use default model (Gemini 3)"},{name:"mode",long:"mode",short:"m",type:"option",default:vG1.SMART.key,description:`Set the agent mode (${Gj().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Gj().map((J)=>J.mode)}],Gm4=(J)=>("deprecated"in J)&&J.deprecated===!0,nN5=(J)=>("hidden"in J)&&J.hidden===!0,aN5=(J)=>("default"in J),rN5=(J)=>("default"in J)?J.default:void 0;function oN5(J,Q){let Y=Q.args[0],X=Q.commands.map((V)=>V.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let V=X.filter((W)=>Y.includes(W)||W.includes(Y)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new V$(Uj.unknownCommand(Y),1,K)}}var Vm4=null;function Wq7(){return Vm4}function FT1(J){return{...J,getThreadEnvironment:es1,vfs:yo6({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new BE1(J.fileSystem),generateThreadTitle:TI4,deleteThread:(Q)=>J.threadService.delete(Q)}}var Ol0=a5.file(cN5.homedir()),Km4=process.env.XDG_CONFIG_HOME?a5.file(process.env.XDG_CONFIG_HOME):P2.joinPath(Ol0,".config");async function Hy(J,Q){on6("0.0.1763856110-g40edea");let Y=Ex0({storage:J.settings,secretStorage:J.secrets,workspaceRoots:L8.of([a5.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Ol0,userConfigDir:Km4}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (C10(),R10));X(Y);let Z=await Y.getLatest();I1.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let V=new A41({configService:Y}),K=new Map,W=()=>K.clear(),U=new sf0(Y,J.settings.getWorkspaceRootPath()),N=XI4({configService:Y,trustStore:U,createOAuthProvider:async(T0)=>{let A0=K.get(T0);if(A0)return I1.debug("Reusing existing OAuth provider for server",{serverName:T0}),A0;I1.debug("Creating OAuth provider for server",{serverName:T0});let S1=(async()=>{let P0=new h41(J.secrets),e0=await P0.getClientInfo(T0),H0=new xf0({storage:P0,serverName:T0,clientId:e0?.clientId,clientSecret:e0?.clientSecret,scopes:e0?.scopes});return I1.debug("OAuth provider created",{serverName:T0,hasManualClientId:!!e0?.clientId,willUseDCR:!e0?.clientId}),H0})();return K.set(T0,S1),S1}}),O=Fo1({configService:Y,filesystem:$V,spawn:k41}),{initializeToolProviders:A}=await Promise.resolve().then(() => (Xm4(),Ym4)),{registrations:E,initErrors:R}=await A({toolServices:V,providers:[N,O],initialTimeout:J.executeMode?15000:5000});for(let[T0,A0]of R)I1.warn(`${T0} provider initialization slow or failed:`,A0);if(Q.jetbrains)NY1("JetBrains");else if(Q.ide&&xS4())NY1("VS Code");else if(Q.ide&&fS4())NY1("Neovim");if(J.executeMode)sn6(!0);let _,y=_F.status.pipe(A2((T0)=>Boolean(T0.connected&&T0.authenticated)),lQ()).subscribe((T0)=>{if(T0){if(!_)_=V.registerTool(x$1)}else _?.dispose(),_=void 0}),h;if(!J.executeMode)h=new Wt1(process.cwd(),{},!0);else h=new class extends Wt1{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(TK.write(`No API key found. Starting login flow...
5593
+ `)}var Nl0=Bl0.join(Nl6||Bl0.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function lN5(J){process.emitWarning=function(Q,Y,X,Z){let V=typeof Q==="string"?Q:Q.message||String(Q),K=Y||"Warning",W=!1;J.warn(V,{name:K,code:X})}}function Wy(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")Qk("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")Qk("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")Qk("model.sonnet",Q.useSonnet)}async function Ml0(J){try{await pN5(Bl0.dirname(Nl0),{recursive:!0}),await dN5(Nl0,J,"utf-8")}catch(Q){I1.debug("Failed to save last thread ID",Q)}}async function iN5(){try{return(await qm4(Nl0,"utf-8")).trim()}catch(J){return null}}var $m4=[{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??Bj,description:`Custom settings file path (overrides the default location ${Bj})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(I1).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Yu0})`},{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:EU(),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 Gemini 3":"Use default model (Gemini 3)"},{name:"mode",long:"mode",short:"m",type:"option",default:vG1.SMART.key,description:`Set the agent mode (${Gj().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Gj().map((J)=>J.mode)}],Gm4=(J)=>("deprecated"in J)&&J.deprecated===!0,nN5=(J)=>("hidden"in J)&&J.hidden===!0,aN5=(J)=>("default"in J),rN5=(J)=>("default"in J)?J.default:void 0;function oN5(J,Q){let Y=Q.args[0],X=Q.commands.map((V)=>V.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let V=X.filter((W)=>Y.includes(W)||W.includes(Y)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new V$(Uj.unknownCommand(Y),1,K)}}var Vm4=null;function Wq7(){return Vm4}function FT1(J){return{...J,getThreadEnvironment:es1,vfs:yo6({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new BE1(J.fileSystem),generateThreadTitle:TI4,deleteThread:(Q)=>J.threadService.delete(Q)}}var Ol0=a5.file(cN5.homedir()),Km4=process.env.XDG_CONFIG_HOME?a5.file(process.env.XDG_CONFIG_HOME):P2.joinPath(Ol0,".config");async function Hy(J,Q){on6("0.0.1763857589-g40edea");let Y=Ex0({storage:J.settings,secretStorage:J.secrets,workspaceRoots:L8.of([a5.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Ol0,userConfigDir:Km4}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (C10(),R10));X(Y);let Z=await Y.getLatest();I1.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let V=new A41({configService:Y}),K=new Map,W=()=>K.clear(),U=new sf0(Y,J.settings.getWorkspaceRootPath()),N=XI4({configService:Y,trustStore:U,createOAuthProvider:async(T0)=>{let A0=K.get(T0);if(A0)return I1.debug("Reusing existing OAuth provider for server",{serverName:T0}),A0;I1.debug("Creating OAuth provider for server",{serverName:T0});let S1=(async()=>{let P0=new h41(J.secrets),e0=await P0.getClientInfo(T0),H0=new xf0({storage:P0,serverName:T0,clientId:e0?.clientId,clientSecret:e0?.clientSecret,scopes:e0?.scopes});return I1.debug("OAuth provider created",{serverName:T0,hasManualClientId:!!e0?.clientId,willUseDCR:!e0?.clientId}),H0})();return K.set(T0,S1),S1}}),O=Fo1({configService:Y,filesystem:$V,spawn:k41}),{initializeToolProviders:A}=await Promise.resolve().then(() => (Xm4(),Ym4)),{registrations:E,initErrors:R}=await A({toolServices:V,providers:[N,O],initialTimeout:J.executeMode?15000:5000});for(let[T0,A0]of R)I1.warn(`${T0} provider initialization slow or failed:`,A0);if(Q.jetbrains)NY1("JetBrains");else if(Q.ide&&xS4())NY1("VS Code");else if(Q.ide&&fS4())NY1("Neovim");if(J.executeMode)sn6(!0);let _,y=_F.status.pipe(A2((T0)=>Boolean(T0.connected&&T0.authenticated)),lQ()).subscribe((T0)=>{if(T0){if(!_)_=V.registerTool(x$1)}else _?.dispose(),_=void 0}),h;if(!J.executeMode)h=new Wt1(process.cwd(),{},!0);else h=new class extends Wt1{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(TK.write(`No API key found. Starting login flow...
5594
5594
  `),!await sN5(J))await s41(),process.exit(1)}let p=await MI4({isDevelopment:!1}),l=new Xh0(p,Y),o=new Jh0(p,{lazy:!0}),r=new tf0(l,(T0,A0)=>{let S1=wB.get(T0);if(S1)S1.handle(A0).catch((P0)=>{I1.error("Failed to apply artifact delta",P0)})}),q1=Q.notifications!==void 0?Q.notifications:!J.executeMode,K1=yI4({playNotificationSound:async(T0)=>{if(q1){kI4(T0);let A0=ru0(),S1=ou0();if((!A0||S1)&&Z.settings["notifications.system.enabled"]!==!1){if(T0==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(T0==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:l,configService:Y});I1.info("Starting Amp background services");let H1=CI4({threadService:l,threadHistoryService:o,configService:Y,isExtensionDevelopment:!1}),b1;_F.status.subscribe((T0)=>{b1=T0});let x1=new aB0({workspaceRoots:[a5.file(process.cwd())],getCurrentFile:()=>{if(!b1?.openFile)return;try{return a5.parse(b1.openFile)}catch(T0){I1.warn("Failed to parse current file URI",{uri:b1.openFile,error:T0});return}},getOpenFiles:()=>{if(!b1?.visibleFiles?.length)return[];let T0=b1.openFile;return b1.visibleFiles.filter((A0)=>A0!==T0).map((A0)=>{try{return a5.parse(A0)}catch(S1){return I1.warn("Failed to parse visible file URI",{uri:A0,error:S1}),null}}).filter((A0)=>A0!==null)}}),h1=new eu0,e1={codebaseContextService:x1,configService:Y,toolServices:V,mcpService:N,trustStore:U,threadService:l,threadHistoryService:o,threadSyncService:H1,planFileManager:r,threadStorage:p,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:h,notificationService:K1,fileSystem:Q.jetbrains||Q.ide?zI4:$V,terminal:h1};return{...e1,async asyncDispose(){for(let T0 of E.values())T0.dispose();await e1.mcpService.dispose(),W(),await e1.threadService.asyncDispose(),e1.configService.unsubscribe(),e1.toolServices.dispose(),e1.fuzzyServer.dispose(),e1.threadSyncService.dispose(),e1.settingsStorage[Symbol.dispose](),y.unsubscribe(),_?.dispose()}}}async function sN5(J){if(!J.executeMode){if(!await Ru0("Would you like to log in to Amp? [(y)es, (n)o]: "))return TK.write(`Login cancelled. Run the command again to retry.
5595
5595
  `),!1}return await Wm4(J)}async function Wm4(J){let Q=mN5(32).toString("hex"),Y=await Tu0(J.ampURL,Q),X=new AbortController;try{await EO(Y,X.signal)}catch(V){I1.error("Error opening browser",{error:V})}let Z=await Tu0(J.ampURL,Q,!1);TK.write(`If your browser does not open automatically, visit:
5596
5596
 
@@ -5600,15 +5600,15 @@ ${oQ.blue.bold(Z)}
5600
5600
  Login successful! You can now use the Amp CLI.
5601
5601
  `),!0}catch(V){return I1.error("Login failed",{error:V}),Sj.write(`
5602
5602
  Login failed: ${V instanceof Error?V.message:String(V)}
5603
- `),!1}}function tN5(){let J=new u41().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((O)=>{if(O.code==="commander.help"||O.code==="commander.version"||O.exitCode===0)zZ1(),process.exit(0);let A=O.originalError??O;jj4(A)}),J.option("-V, --version","Print the version number and exit",()=>{TK.write(`0.0.1763856110-g40edea (released 2025-11-23T00:07:05.987Z)
5603
+ `),!1}}function tN5(){let J=new u41().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((O)=>{if(O.code==="commander.help"||O.code==="commander.version"||O.exitCode===0)zZ1(),process.exit(0);let A=O.originalError??O;jj4(A)}),J.option("-V, --version","Print the version number and exit",()=>{TK.write(`0.0.1763857589-g40edea (released 2025-11-23T00:31:35.785Z)
5604
5604
  `),process.exit(0)}),J.addHelpText("after",kS4()),J.configureHelp({formatHelp:yS4}),J.command("logout").description("Log out by removing stored API key").action(async(O,A)=>{let E=A.optsWithGlobals(),R=await kL(E);await YD5(R)}),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(O,A)=>{let E=A.optsWithGlobals(),R=await kL(E);await QD5(R,await Bu0(E,R.settings))});let Q=async(O,A,E)=>{Ex0({storage:A.settings,secretStorage:A.secrets,workspaceRoots:L8.of([a5.file(process.cwd())]),defaultAmpURL:A.ampURL,homeDir:Ol0,userConfigDir:Km4});let R={...A,executeMode:!1};await Dl0(R,{...O,openThreadSwitcher:!0},E)},Y=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(O,A)=>{let E=A.optsWithGlobals(),R=await kL(E);await Zm4(E,R,A)});Y.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(O,A)=>{let E=A.optsWithGlobals(),R=await kL(E);await KD5(E,R,A)}),Y.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(O,A,E)=>{let R=E.optsWithGlobals(),_=await kL(R);if(A.pick)Sj.write(`${oQ.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
5605
5605
  `);if(A.last||O||_.executeMode)await VD5(R,_,O,E);else await Q(R,_,E)}),Y.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(O,A,E)=>{let R=E.optsWithGlobals(),_=await kL(R);await qD5(R,_,O,E)}),Y.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(O,A)=>{let E=A.optsWithGlobals(),R=await kL(E);await Zm4(E,R,A)}),Y.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support [message]","Share thread with Amp support for debugging").action(async(O,A,E)=>{let R=E.optsWithGlobals(),_=await kL(R);await ZD5(R,_,O,E,A.support)}),Y.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(O,A,E,R)=>{let _=R.optsWithGlobals(),y=await kL(_);await XD5(_,y,O,A,R)}),Y.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(O,A,E)=>{let R=E.optsWithGlobals(),_=await kL(R);await $D5(R,_,O,E)}),Y.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(O,A,E)=>{let R=E.optsWithGlobals(),_=await kL(R);await GD5(R,_,O,A,E)}),Ck4(J,async(O,A)=>{let E=await kL(A);Wy(O,A);let R=await Hy(E,A);return{context:E,mcpService:R.mcpService,toolService:R.toolServices,toolServices:R.toolServices,configService:R.configService,cleanupTerminal:zZ1,asyncDispose:R.asyncDispose.bind(R)}}),N_4(J,async(O)=>{let A=O.optsWithGlobals();return await kL(A)}),Z_4(J,async(O)=>{let A=await kL(O);return{settings:A.settings,secretStorage:A.secrets,getThreadDeps:async(E)=>{Wy(E,O);let R=await Hy(A,O);return{mcpService:R.mcpService,settings:A.settings,asyncDispose:R.asyncDispose.bind(R)}}}});function Z(O,A,E){let _=typeof O.description==="string"?O.description:E===void 0?O.description(!0):O.description(E),y=new qr(A,_),h=rN5(O);if(h)y.default(h);if(y.hidden=nN5(O)||Gm4(O),"choices"in O)y.choices([...O.choices]);return y}for(let O of $m4)switch(O.type){case"flag":{J.addOption(Z(O,`--${O.long}`)),J.addOption(Z(O,`--no-${O.long}`,!1));break}case"switch":{J.addOption(Z(O,`--${O.long}`,!0));break}default:{J.addOption(Z(O,`${"short"in O?`-${O.short}, `:""}--${O.long} <value>`));break}}let V=new qr("-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(V);let K=new qr("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(K);let W=new qr("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(W);let U=new qr("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(U);let N=new qr("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(N),process.env.AMP_CONNECT==="1"){let O=new qr("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(O)}return J.action(async(O,A)=>{let E=O,R=await kL(E);if(Object.keys(E).forEach((_)=>{let y=$m4.find((h)=>h.name===_);if(y&&Gm4(y)&&!aN5(y))Sj.write(oQ.yellow(`Warning: '--${_}' flag is deprecated
5606
5606
  `))}),A.args.length>0)oN5(R,A);await Dl0(R,E,A)}),tS4(J),J}async function N00(J,Q){let{thread:Y,visibility:X}=Q,Z=Y?.id??qk(),V=FT1(J);if(Y)await J.threadStorage.set(Z,Y);let K=await wB.getOrCreateForThread(V,Z),W=await J.threadStorage.get(Z);if(Q.agentMode&&!W?.agentMode&&Kk(K.thread)===0)await K.handle({type:"agent-mode",mode:Q.agentMode});if(X)await J.threadSyncService.updateThreadMeta(Z,wt1(X));let U=J.threadService.observe(Z).subscribe(async(N)=>{if(oD(N,"assistant"))await Ml0(Z),U.unsubscribe()});return await K.resume(),K}async function Dl0(J,Q,Y){let X=Lt1(Q);if(X instanceof Error)jj(X.message);let Z,V=null;if(Q.streamJsonInput)Z="";else if(typeof Q.execute==="string"){Z=Q.execute;let e1=(await Cu0()).trimEnd();if(e1)V=e1}else Z=(await Cu0()).trimEnd();if(Q.remote&&!J.executeMode)throw new V$("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new V$("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new V$("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new V$("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if((J.executeMode||Q.streamJson)&&XV(Q.mode))throw new V$(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.stats&&!J.executeMode)throw new V$("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new V$("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&Z===""&&!Q.streamJsonInput)throw new V$("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
5607
5607
  Or pipe via stdin: echo "your message" | amp --execute`);Wy(Y,Q);let K=await Hy(J,Q);Vm4=K;let W=FT1(K),U=async(e1)=>{let T0=await qm4(e1,"utf-8"),A0=JSON.parse(T0);if(!Vk(A0.id))throw new V$(Uj.invalidThreadId);return N00(K,{visibility:X,agentMode:Q.mode,thread:A0})},N=async(e1)=>{if(!Vk(e1))throw new V$(Uj.invalidThreadId);try{let[A0,S1]=await Promise.all([EV.getThreadLinkInfo({thread:e1},{config:K.configService}),EV.getUserInfo({},{config:K.configService})]);if(A0.ok&&S1.ok){let P0=A0.result.creatorUserID,e0=S1.result.id;if(P0&&P0!==e0&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new V$(`Cannot resume thread created by another user.
5608
5608
 
5609
5609
  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(A0){if(A0 instanceof V$)throw A0;I1.warn("Failed to validate thread ownership in CLI, allowing to open",{error:A0})}let T0=await K.threadService.get(e1)??void 0;return I1.info(`[fetchAndStartThread] Loaded thread ${e1}, agentMode: ${T0?.agentMode??"undefined"}`),N00(K,{visibility:X,agentMode:T0?void 0:Q.mode,thread:T0})},O=async()=>{try{if(Q.threadId)return N(Q.threadId);else return N00(K,{visibility:X})}catch(e1){if(e1 instanceof V$)throw e1;throw await uI1(e1,Q.threadId),Error("handleError should have called process.exit()")}},A=async()=>{return N00(K,{visibility:X})};if(Q.format==="jsonl")Sj.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
5610
- `),await s41(),process.exit(1);if(J.executeMode&&Q.remote)await D_4(Z,V,K.configService),await K.asyncDispose(),process.exit(0);let E=await O();if(J.executeMode)K_4(K.mcpService,J.settings),await cj4(E,E.threadID,Z,V,K,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await K.asyncDispose(),process.exit(0);let R=!1,_=!1;if(Q.jetbrains||Q.ide){await YZ4();let e1=v$1({jetbrainsOnly:Q.jetbrains});if(e1.length===0){if(Q.jetbrains)_=!await K.configService.get("jetbrains.skipInstall")}else if(e1.length===1){let T0=e1[0];if(T0)_F.selectConfig(T0)}else R=!0}let y=Ot1("0.0.1763856110-g40edea",K.settingsStorage),h=new As1(K.threadStorage),p=L8.of([a5.file(process.cwd())]),l=ZN0(void 0,p),o=new At1(K.mcpService,J.settings.getWorkspaceRootPath());if(Z)E.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}});let r=(async()=>{try{let e1=await EV.getUserFreeTierStatus({},{config:K.configService,signal:AbortSignal.timeout(5000)});if(e1.ok)return I1.info("User free tier status:",e1),e1.result}catch(e1){I1.error("Failed to fetch free tier status:",e1)}})(),q1=(async()=>{try{let e1=await EV.getUserInfo({},{config:K.configService});if(e1.ok)return e1.result}catch(e1){I1.debug("Failed to fetch user workspace info:",e1)}})(),[K1,H1]=await Promise.all([r,q1]),b1=H1?.email,x1=b1&&(b1.endsWith("@sourcegraph.com")||b1.endsWith("@ampcode.com")||b1==="auth-bypass-user@example.com");if(x1)K.toolServices.registerTool(_I4);let h1=await L_4();I1.info("Loaded session state:",h1),await md0({codebaseContextService:K.codebaseContextService,stdout:process.stdout,history:new Xt1,fuzzyServer:K.fuzzyServer,settingsStorage:K.settingsStorage,threadService:K.threadService,threadHistoryService:K.threadHistoryService,threadSyncService:K.threadSyncService,planFileManager:K.planFileManager,threadID:E.threadID,threadFuzzyIndexer:h,worker:E,workerDeps:W,configService:K.configService,internalAPIClient:EV,ampURL:J.ampURL,startNewThread:A,switchToThread:N,ideClient:_F,connectedClientsService:new Oo1,commandRegistry:l,mcpService:K.mcpService,mcpTrustHandler:o,showJetBrainsInstaller:_,showIdePicker:R,openThreadSwitcher:Q.openThreadSwitcher,updateService:y,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:h1,freeTierStatus:K1,workspace:H1?.team??null,features:H1?.features??[],isDogfooding:x1||!1,threadDependencies:K}),await K.asyncDispose(),process.exit(0)}async function kL(J){if(J.interactive)Sj.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5611
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await NS4({...J,workspaceTrust:{current:!0,changes:VD1},getHook:process.env.AMP_URL?(V,K)=>{if(V==="url")return Promise.resolve(process.env.AMP_URL);return K()}:void 0});if(J.mcpConfig){let V=await q_4(J.mcpConfig);X=V_4(X,V)}let Z=await X.get("url","global");if(!Z)Z=HE;if(!oi(Z))I1.info("Targeting custom Amp server",{ampURL:Z});return X=Ni6(X),{executeMode:Q,isTTY:Y,ampURL:Z,settings:X,secrets:M_4(await Bu0(J,X))}}function eN5(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let V=X.slice(2).replace(/-([a-z])/g,(W,U)=>U.toUpperCase()),K=J[Y+1];if(K&&!K.startsWith("--"))Q[V]=K,Y++}}return Q}async function JD5(){let J=eN5(process.argv);if(Aj4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),lN5(I1),I1.info("Starting Amp CLI.",{version:"0.0.1763856110-g40edea",buildTimestamp:"2025-11-23T00:07:05.987Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new V$(Uj.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await tN5().parseAsync(process.argv)}sy0().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await JD5().catch(uI1)});async function QD5(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),TK.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5610
+ `),await s41(),process.exit(1);if(J.executeMode&&Q.remote)await D_4(Z,V,K.configService),await K.asyncDispose(),process.exit(0);let E=await O();if(J.executeMode)K_4(K.mcpService,J.settings),await cj4(E,E.threadID,Z,V,K,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await K.asyncDispose(),process.exit(0);let R=!1,_=!1;if(Q.jetbrains||Q.ide){await YZ4();let e1=v$1({jetbrainsOnly:Q.jetbrains});if(e1.length===0){if(Q.jetbrains)_=!await K.configService.get("jetbrains.skipInstall")}else if(e1.length===1){let T0=e1[0];if(T0)_F.selectConfig(T0)}else R=!0}let y=Ot1("0.0.1763857589-g40edea",K.settingsStorage),h=new As1(K.threadStorage),p=L8.of([a5.file(process.cwd())]),l=ZN0(void 0,p),o=new At1(K.mcpService,J.settings.getWorkspaceRootPath());if(Z)E.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}});let r=(async()=>{try{let e1=await EV.getUserFreeTierStatus({},{config:K.configService,signal:AbortSignal.timeout(5000)});if(e1.ok)return I1.info("User free tier status:",e1),e1.result}catch(e1){I1.error("Failed to fetch free tier status:",e1)}})(),q1=(async()=>{try{let e1=await EV.getUserInfo({},{config:K.configService});if(e1.ok)return e1.result}catch(e1){I1.debug("Failed to fetch user workspace info:",e1)}})(),[K1,H1]=await Promise.all([r,q1]),b1=H1?.email,x1=b1&&(b1.endsWith("@sourcegraph.com")||b1.endsWith("@ampcode.com")||b1==="auth-bypass-user@example.com");if(x1)K.toolServices.registerTool(_I4);let h1=await L_4();I1.info("Loaded session state:",h1),await md0({codebaseContextService:K.codebaseContextService,stdout:process.stdout,history:new Xt1,fuzzyServer:K.fuzzyServer,settingsStorage:K.settingsStorage,threadService:K.threadService,threadHistoryService:K.threadHistoryService,threadSyncService:K.threadSyncService,planFileManager:K.planFileManager,threadID:E.threadID,threadFuzzyIndexer:h,worker:E,workerDeps:W,configService:K.configService,internalAPIClient:EV,ampURL:J.ampURL,startNewThread:A,switchToThread:N,ideClient:_F,connectedClientsService:new Oo1,commandRegistry:l,mcpService:K.mcpService,mcpTrustHandler:o,showJetBrainsInstaller:_,showIdePicker:R,openThreadSwitcher:Q.openThreadSwitcher,updateService:y,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:h1,freeTierStatus:K1,workspace:H1?.team??null,features:H1?.features??[],isDogfooding:x1||!1,threadDependencies:K}),await K.asyncDispose(),process.exit(0)}async function kL(J){if(J.interactive)Sj.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5611
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await NS4({...J,workspaceTrust:{current:!0,changes:VD1},getHook:process.env.AMP_URL?(V,K)=>{if(V==="url")return Promise.resolve(process.env.AMP_URL);return K()}:void 0});if(J.mcpConfig){let V=await q_4(J.mcpConfig);X=V_4(X,V)}let Z=await X.get("url","global");if(!Z)Z=HE;if(!oi(Z))I1.info("Targeting custom Amp server",{ampURL:Z});return X=Ni6(X),{executeMode:Q,isTTY:Y,ampURL:Z,settings:X,secrets:M_4(await Bu0(J,X))}}function eN5(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let V=X.slice(2).replace(/-([a-z])/g,(W,U)=>U.toUpperCase()),K=J[Y+1];if(K&&!K.startsWith("--"))Q[V]=K,Y++}}return Q}async function JD5(){let J=eN5(process.argv);if(Aj4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),lN5(I1),I1.info("Starting Amp CLI.",{version:"0.0.1763857589-g40edea",buildTimestamp:"2025-11-23T00:31:35.785Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new V$(Uj.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await tN5().parseAsync(process.argv)}sy0().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await JD5().catch(uI1)});async function QD5(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),TK.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5612
5612
  `);else if(!oi(J.ampURL))TK.write(`Logging in to ${new URL(J.ampURL).hostname}
5613
5613
  `);let Y=process.env.AMP_API_KEY;if(Y)TK.write(`API key found in environment variable, storing...
5614
5614
  `),await Q.set("apiKey",Y,J.ampURL),TK.write(`API key successfully stored.
@@ -5621,7 +5621,7 @@ This thread belongs to a different user and cannot be continued for security rea
5621
5621
  `);else TK.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
5622
5622
  `);process.exit(0)}async function XD5(J,Q,Y,X,Z){Wy(Z,J);let V=await Hy(Q,J);try{let K=D00(Y);if(!K)M00(Y);let W=K,U=X.trim();if(U.length===0)jj("Thread name cannot be empty");if(U.length>256)jj("Thread name cannot exceed 256 characters");if(!(await Hq1(W,V)).messages.length)jj("Cannot rename an empty thread.");let O=FT1(V);await(await wB.getOrCreateForThread(O,W)).handle({type:"title",value:U}),I1.info("GOT HERE"),await V.threadSyncService.sync(),I1.info("GOT THERE"),TK.write(oQ.green(`✓ Thread ${W} renamed to "${U}"
5623
5623
  `)),await V.asyncDispose(),process.exit(0)}catch(K){await V.asyncDispose();let W=`Failed to rename thread: ${K instanceof Error?K.message:String(K)}`;jj(W)}}async function $D5(J,Q,Y,X){Wy(X,J);let Z=await Hy(Q,J);try{let V=D00(Y);if(!V)M00(Y);let W=await Hq1(V,Z),U=HG1(W);TK.write(U+`
5624
- `),await Z.asyncDispose(),process.exit(0)}catch(V){await Z.asyncDispose();let K=`Failed to render thread as markdown: ${V instanceof Error?V.message:String(V)}`;jj(K)}}async function GD5(J,Q,Y,X,Z){Wy(Z,J);let V=await Hy(Q,J);try{let K=await Al0(Y),W=await Hq1(K,V),U=X.typing!==!1,N=parseInt(X.wpm||"120",10),O=parseInt(X.messageDelay||"1000",10),A=parseInt(X.toolProgressDelay||"800",10),E=parseInt(X.exitDelay||"3",10)*1000,R=X.indicator!==!1,_=FT1(V),y=W.id;await V.threadStorage.set(y,W);let h=await wB.getOrCreateForThread(_,y);await h.resume();let p=Os1.fromWorker(h),l=new As1(V.threadStorage),o=L8.of([a5.file(process.cwd())]),r=ZN0(void 0,o),q1=new At1(V.mcpService,Q.settings.getWorkspaceRootPath()),K1=Ot1("0.0.1763856110-g40edea",V.settingsStorage);await md0({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new Xt1,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,planFileManager:V.planFileManager,threadID:y,threadFuzzyIndexer:l,worker:p,workerDeps:_,configService:V.configService,internalAPIClient:EV,ampURL:Q.ampURL,startNewThread:async()=>p,switchToThread:async()=>p,ideClient:_F,connectedClientsService:new Oo1,commandRegistry:r,mcpService:V.mcpService,mcpTrustHandler:q1,showJetBrainsInstaller:!1,updateService:K1,isDogfooding:!1,replayMode:{thread:W,typingEnabled:U,baseWpm:N,messageDelayMs:O,toolProgressDelayMs:A,exitDelayMs:E,showIndicator:R}}),await V.asyncDispose(),process.exit(0)}catch(K){await V.asyncDispose(),await uI1(K,Y)}}async function ZD5(J,Q,Y,X,Z){Wy(X,J);let V=await Hy(Q,J);try{let K=D00(Y);if(!K)M00(Y);let W=K,U=await EV.getUserInfo({},{config:V.configService}),N=U.ok?U.result:null,O=Lt1(J,N);if(!O&&!Z)jj("Must specify either --visibility or --support");if(O&&Z)jj("Cannot specify both --visibility and --support at the same time");if(O instanceof Error)jj(O.message);if(O)await V.threadSyncService.updateThreadMeta(W,wt1(O)),TK.write(oQ.green("✓ ")+`Thread ${W} visibility changed to ${O}.
5624
+ `),await Z.asyncDispose(),process.exit(0)}catch(V){await Z.asyncDispose();let K=`Failed to render thread as markdown: ${V instanceof Error?V.message:String(V)}`;jj(K)}}async function GD5(J,Q,Y,X,Z){Wy(Z,J);let V=await Hy(Q,J);try{let K=await Al0(Y),W=await Hq1(K,V),U=X.typing!==!1,N=parseInt(X.wpm||"120",10),O=parseInt(X.messageDelay||"1000",10),A=parseInt(X.toolProgressDelay||"800",10),E=parseInt(X.exitDelay||"3",10)*1000,R=X.indicator!==!1,_=FT1(V),y=W.id;await V.threadStorage.set(y,W);let h=await wB.getOrCreateForThread(_,y);await h.resume();let p=Os1.fromWorker(h),l=new As1(V.threadStorage),o=L8.of([a5.file(process.cwd())]),r=ZN0(void 0,o),q1=new At1(V.mcpService,Q.settings.getWorkspaceRootPath()),K1=Ot1("0.0.1763857589-g40edea",V.settingsStorage);await md0({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new Xt1,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,planFileManager:V.planFileManager,threadID:y,threadFuzzyIndexer:l,worker:p,workerDeps:_,configService:V.configService,internalAPIClient:EV,ampURL:Q.ampURL,startNewThread:async()=>p,switchToThread:async()=>p,ideClient:_F,connectedClientsService:new Oo1,commandRegistry:r,mcpService:V.mcpService,mcpTrustHandler:q1,showJetBrainsInstaller:!1,updateService:K1,isDogfooding:!1,replayMode:{thread:W,typingEnabled:U,baseWpm:N,messageDelayMs:O,toolProgressDelayMs:A,exitDelayMs:E,showIndicator:R}}),await V.asyncDispose(),process.exit(0)}catch(K){await V.asyncDispose(),await uI1(K,Y)}}async function ZD5(J,Q,Y,X,Z){Wy(X,J);let V=await Hy(Q,J);try{let K=D00(Y);if(!K)M00(Y);let W=K,U=await EV.getUserInfo({},{config:V.configService}),N=U.ok?U.result:null,O=Lt1(J,N);if(!O&&!Z)jj("Must specify either --visibility or --support");if(O&&Z)jj("Cannot specify both --visibility and --support at the same time");if(O instanceof Error)jj(O.message);if(O)await V.threadSyncService.updateThreadMeta(W,wt1(O)),TK.write(oQ.green("✓ ")+`Thread ${W} visibility changed to ${O}.
5625
5625
  `);if(Z){await Hq1(W,V);let A=typeof Z==="string"?Z:void 0;await XX4(V.threadService,W,V.configService,A),TK.write(oQ.green("✓ ")+`Thread ${W} has been shared with Amp support. These thread reports will be aggregated and analysed.
5626
5626
  `)}await V.asyncDispose(),process.exit(0)}catch(K){await V.asyncDispose(),jj(`Failed to update thread: ${K instanceof Error?K.message:String(K)}`)}}async function qD5(J,Q,Y,X){Wy(X,J);let Z=await Hy(Q,J),V=FT1(Z);try{let K=await Al0(Y),U=(await Hq1(K,Z)).messages.length-1,N=await wB.getOrCreateForThread(V,K),O=await tG1(N,Z.threadSyncService,U);await Promise.all([Z.threadSyncService.uploadThread(K),Z.threadSyncService.uploadThread(O)]),await Ml0(O),TK.write(`${O}
5627
5627
  `),await Z.asyncDispose(),process.exit(0)}catch(K){Sj.write(`Error forking thread: ${K instanceof Error?K.message:String(K)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1763856110-g40edea",
3
+ "version": "0.0.1763857589-g40edea",
4
4
  "description": "CLI for Amp, the frontier coding agent from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {