@sourcegraph/amp 0.0.1763582484-gdd165b → 0.0.1763586382-g73297f

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 +12 -12
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4573,11 +4573,11 @@ Actual: ${G}`)}async function RV8(J,Q,Y){let{execSync:X}=await import("node:ch
4573
4573
  ${N}`;if(G==="pnpm"&&N.includes("Unable to find the global bin directory"))O+=`
4574
4574
 
4575
4575
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4576
- npm install -g @sourcegraph/amp`;V(Error(O))}},error:(U)=>{if(!H)H=!0,V(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,q()}})})}H0();H0();async function s61(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),q=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!q.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let V=await q.json(),K=V["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=kV8(J,K),H=W<0,z,U;if(V.time){let N=V.time[J],O=V.time[K],M=Date.now();if(N)z=Math.floor((M-new Date(N).getTime())/3600000);if(O)U=Math.floor((M-new Date(O).getTime())/3600000)}return v.info("NPM version comparison",{currentVersion:J,latestVersion:K,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:K,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(G){return v.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function kV8(J,Q){let Y=(q)=>{let[V,K]=q.split("-");return{parts:V?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let q=0;q<Z;q++){let V=X.parts[q]||0,K=G.parts[q]||0;if(V<K)return-1;if(V>K)return 1}if(X.label===G.label)return 0;if(!X.label&&G.label)return 1;if(X.label&&!G.label)return-1;if(X.label&&G.label)return X.label<G.label?-1:1;return 0}g0();function t61(J,Q){let Y=new b4,X=Y.pipe(s8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new HV().scoped("update"),Z=X.subscribe({next:(q)=>{G.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){G.debug("using fake update status for testing",{status:q}),await IU(500),Y.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let V=await Q.get("updates.mode");if(V==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:V});let K=hL(),W=await s61(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,N=0.5;if(Math.abs(U)<0.5)return G.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await o61();if(!V)V=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:V});if(V==="warn"){if(!H())Y.next("update-available");return}if(!z){if(G.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}try{await Iu(W.latestVersion,z);let U=await hB(W.latestVersion),N={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",N),Y.next("updated");else G.warn("success with warning",N),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(q){G.debug("check failed",{error:q})}finally{await IU(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as IK}from"node:process";function Y26(J){let Q=new EL().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 cR1(X.force||!1,X.verbose||!1,"0.0.1763582484-gdd165b"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new EL("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 yV8(X.version)});J.addCommand(Y)}async function yV8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")IK.write(C4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4576
+ npm install -g @sourcegraph/amp`;V(Error(O))}},error:(U)=>{if(!H)H=!0,V(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,q()}})})}H0();H0();async function s61(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),q=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!q.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let V=await q.json(),K=V["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=kV8(J,K),H=W<0,z,U;if(V.time){let N=V.time[J],O=V.time[K],M=Date.now();if(N)z=Math.floor((M-new Date(N).getTime())/3600000);if(O)U=Math.floor((M-new Date(O).getTime())/3600000)}return v.info("NPM version comparison",{currentVersion:J,latestVersion:K,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:K,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(G){return v.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function kV8(J,Q){let Y=(q)=>{let[V,K]=q.split("-");return{parts:V?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let q=0;q<Z;q++){let V=X.parts[q]||0,K=G.parts[q]||0;if(V<K)return-1;if(V>K)return 1}if(X.label===G.label)return 0;if(!X.label&&G.label)return 1;if(X.label&&!G.label)return-1;if(X.label&&G.label)return X.label<G.label?-1:1;return 0}g0();function t61(J,Q){let Y=new b4,X=Y.pipe(s8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new HV().scoped("update"),Z=X.subscribe({next:(q)=>{G.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){G.debug("using fake update status for testing",{status:q}),await IU(500),Y.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let V=await Q.get("updates.mode");if(V==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:V});let K=hL(),W=await s61(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,N=0.5;if(Math.abs(U)<0.5)return G.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await o61();if(!V)V=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:V});if(V==="warn"){if(!H())Y.next("update-available");return}if(!z){if(G.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}try{await Iu(W.latestVersion,z);let U=await hB(W.latestVersion),N={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",N),Y.next("updated");else G.warn("success with warning",N),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(q){G.debug("check failed",{error:q})}finally{await IU(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as IK}from"node:process";function Y26(J){let Q=new EL().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 cR1(X.force||!1,X.verbose||!1,"0.0.1763586382-g73297f"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new EL("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 yV8(X.version)});J.addCommand(Y)}async function yV8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")IK.write(C4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4577
4577
 
4578
4578
  `));try{if(!J){IK.write(C4.blue(`Checking for updates...
4579
- `));let Y=hL(),{hasUpdate:X,latestVersion:G}=await s61("0.0.1763582484-gdd165b",Y);if(!X){IK.write(C4.green(`✓ Amp CLI is already up to date.
4580
- `));let Z=await hB("0.0.1763582484-gdd165b");if(Z.warning)IK.write(`
4579
+ `));let Y=hL(),{hasUpdate:X,latestVersion:G}=await s61("0.0.1763586382-g73297f",Y);if(!X){IK.write(C4.green(`✓ Amp CLI is already up to date.
4580
+ `));let Z=await hB("0.0.1763586382-g73297f");if(Z.warning)IK.write(`
4581
4581
  `+C4.yellow(Z.warning)+`
4582
4582
  `);process.exit(0)}if(!G)IK.write(C4.yellow("[WARN] could not find latest version")),process.exit(0);J=G}IK.write(C4.blue(`Updating to version ${J}...
4583
4583
  `)),await Iu(J,void 0,(Y)=>{IK.write(C4.dim(`Running: ${Y}
@@ -5199,7 +5199,7 @@ exit code: ${Z}`,new B1({color:X.foreground,dim:!0,italic:!0})));if(q)V.push(new
5199
5199
  `,U),...N],M=new l0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new l1({text:new $1("",void 0,O)})]});return q8.child(new J6({constraints:new p6(40,120,0,1/0),child:new Z4({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[new F4({flex:1,child:new mC1({width:40,height:40,agentMode:this.agentMode,fps:q==="fast"?60:q==="slow"?15:0,...q==="disabled"&&{seed:42,t:3}})}),new N0({width:1}),new F4({flex:2,child:M})]})}))}}H0();w9();K4();K5();w9();g0();function ZN8(J,Q){return`${J}:${Q}`}class B_1{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 J0((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.subthreadObservable=new J0((Q)=>{return this.emitSubthread=(Y)=>Q.next(Y),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new J0((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(qO()).subscribe((Z)=>{this.threadsMap.set(Q,Z);let q=this.subthreadsMap.get(Q)||[],V=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:Z,subthreads:q,workerStatus:V})});this.mainThreadSubs.set(Q,Y);let X=J.status.subscribe((Z)=>{if(this.workers.set(Q,Z),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:Z})});this.workerStatusSubs.set(Q,X);let G=J.subthreads.subscribe((Z)=>{this.subthreadsMap.set(Q,Z);for(let q of Z){let V=ZN8(Q,q.toolUse.id);if(this.subthreadPatchSubs.has(V))continue;let K=this.threadService.observePatches(q.threadID).pipe(qO()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:q})});this.subthreadPatchSubs.set(V,K)}});this.subthreadsSubs.set(Q,G)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Y=this.workerStatusSubs.get(J);if(Y)Y.unsubscribe(),this.workerStatusSubs.delete(J);let X=this.subthreadsSubs.get(J);if(X)X.unsubscribe(),this.subthreadsSubs.delete(J);for(let[G,Z]of this.subthreadPatchSubs.entries())if(G.startsWith(`${J}:`))Z.unsubscribe(),this.subthreadPatchSubs.delete(G);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new J0((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),subthreads:new J0((Q)=>{return this.subthreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new J0((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]=XL(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 qN8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Y,subthread:X}=Q,G=J.subagents[X.threadID];if(!G){if(G={subThreadID:Y.id,parentToolID:X.toolUse.id,taskDescription:X.toolUse.input?.description??"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=iJ(J.mainThread);G.isCompleted=IY6(W,X.toolUse.id)}}let Z=VN8(Y,G.agentState),q=G.agentState===Z?G:{...G,agentState:Z},V={...J.tools},K=MC(Y).items.filter((W)=>W.type==="toolResult");for(let W of K)V[W.id]={id:W.id,subthreadID:Y.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[X.threadID]:q},tools:V,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Y,subthreads:X,workerStatus:G}=Q,Z=iJ(Y),q={...J.subagents};for(let z of X){let U=q[z.threadID];if(!U)continue;let N=IY6(Z,z.toolUse.id);q[z.threadID]={...U,isCompleted:N}}let{items:V}=MC(Y),K=XL(Y,G),W=pE({messages:Y.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:q,items:V,viewState:K,todosList:H,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=XL(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function MC(J){let Q=[],Y=new Map,X=new Set;for(let[G,Z]of J.messages.entries()){let q=`${Z.role}-${G}`;switch(Z.role){case"assistant":{let V=Z.state.type==="streaming";for(let W of Z.content)if(W.type==="tool_use"){if(Y.set(W.id,W),V)X.add(W.id)}if(Z.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:q,message:Z});for(let W of Z.content)if(W.type==="tool_use"){let H=!1;for(let z=G+1;z<J.messages.length;z++){let U=J.messages[z];if(U){for(let N of U.content)if(N.type==="tool_result"&&N.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:V?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:q,message:Z});break;case"user":{if(Z.content.some((K)=>K.type==="text"&&K.text.trim()||K.type==="image"))Q.push({type:"message",id:q,message:Z});for(let K of Z.content)if(K.type==="tool_result"){let W=Y.get(K.toolUseID)??U$(J,K.toolUseID);if(!W)throw Error(`(bug) tool use ${K.toolUseID} not found`);Q.push({type:"toolResult",id:K.toolUseID,toolUse:W,toolResult:K})}break}}}return{items:Q}}function IY6(J,Q){let Y=J.get(Q);return(Y&&V7(Y.run))??!1}function VN8(J,Q){let Y=J.messages.at(-1);if(Y?.content.some((G)=>G.type==="tool_result"&&G.run.status==="blocked-on-user"))return v.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(MC(J).items.some((G)=>G.type==="toolResult"&&G.toolResult.run.status==="in-progress")){let G=Q?.type==="running-tools"?Q.startTime:Date.now();return v.info("Subagent status: running-tools",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}if(Y&&Y.role==="assistant"&&Y.state.type==="streaming")switch(Y.content.at(-1)?.type){case"text":return v.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return v.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let Z=Q?.type==="running-tools"?Q.startTime:Date.now();return v.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:Z,hasStartTime:!!Z}),{type:"running-tools",startTime:Z}}default:return v.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return v.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class N_1 extends e0{props;constructor(J){super();this.props=J}createState(){return new PY6}}class PY6 extends t0{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 B_1(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((Z)=>{this.dispatch({type:"main-thread-patch",thread:Z.mainThread,subthreads:Z.subthreads,workerStatus:Z.workerStatus})});this.subscriptions.push(Y);let X=Q.subthreads.subscribe((Z)=>{this.dispatch({type:"subthread-patch",thread:Z.thread,subthread:Z.subthread})});this.subscriptions.push(X);let G=Q.workerStatus.subscribe((Z)=>{this.dispatch({type:"worker-status-change",workerStatus:Z.status})});this.subscriptions.push(G)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J)}dispatch(J){this.setState(()=>{this.state=qN8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((Z)=>({toolUse:Z.toolUse,toolRun:Z.toolRun,subthreadID:Z.subthreadID})),Q={};for(let Z of Object.values(this.state.subagents)){let q=J.filter((V)=>V.subthreadID===Z.subThreadID);Q[Z.parentToolID]=q}let Y=(Z)=>Z===n5||Z===t8||Z===_E||Z===_F||Z===kF||Z===kE||Z===yE||Z===F$,X=new Map;for(let Z of this.state.items)if(Z.type==="toolResult"&&Y(Z.toolUse.name))X.set(Z.toolUse.id,{toolUseId:Z.toolUse.id,toolName:Z.toolUse.name,toolRun:Z.toolResult.run});let G=Array.from(X.values());for(let{toolUseId:Z,toolRun:q}of G){let V=[],K;if(q.status==="in-progress"||q.status==="done"||q.status==="error"||q.status==="cancelled")K=q.progress;if(K){let W=0;for(let H of K)if(H.tool_uses)for(let z of H.tool_uses){let U=`${Z}:progress:${W++}`;V.push({toolUse:{type:"tool_use",id:U,name:z.tool_name,input:z.input},toolRun:{status:z.status}})}}Q[Z]=V}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker)}}class D_1 extends e0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new TY6}}class TY6 extends t0{build(J){let Y=x6.of(J).colors,{todos:X,title:G="TODOs"}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new N0({width:0,height:0});let Z=X.map((q)=>this.buildTodoItem(q,Y));return new J6({child:new b6({padding:j0.symmetric(1,0),child:new l0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new l1({text:new $1(G,new B1({bold:!0,color:Y.foreground}))}),...Z]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),X=J.status==="completed",G=new B1({bold:J.status==="in-progress",color:Q.foreground,dim:X}),Z=new B1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:X});return new Z4({crossAxisAlignment:"start",children:[new l1({text:new $1(Y,G)}),new N0({width:1}),new F4({child:new l1({text:new $1(J.content,Z)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class O_1 extends j6{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=x6.of(J),Y=Q.colors.primary,X=Q.colors.foreground;return new J6({decoration:new I8(void 0,new n4(new S4(Y,1,"rounded"),new S4(Y,1,"rounded"),void 0,new S4(Y,1,"rounded"))),child:new b6({padding:j0.horizontal(1),child:new l0({children:[new Z4({crossAxisAlignment:"start",children:[new F4({child:new l1({text:new $1(this.ad.content,new B1({color:X}))})}),new N0({width:4}),new GQ({uri:"https://ampcode.com/free",text:"Ad",style:new B1({color:X,dim:!0}),onError:(G)=>{}})]}),new Z4({crossAxisAlignment:"start",children:[new eC1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:j0.horizontal(1),color:Y,reverse:!0}),new N0({width:2}),new l1({text:new $1(this.ad.destinationUrlHostname,new B1({color:X,dim:!0}))})]})]})})})}}class M_1 extends e0{props;constructor(J){super();this.props=J}createState(){return new RY6(this.props.autofocus??!0)}}class RY6 extends t0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(V)=>{if(V.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(V.ctrlKey&&V.key==="c"||V.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=Z8.sizeOf(J),X=Math.min(60,Y.width-4),G=Y.height-4,Z=[];if(this.widget.props.title)Z.push(new l1({text:new $1(this.widget.props.title,new B1({bold:!0,color:A1.blue}))}),new N0({height:1}));if(this.widget.props.message)Z.push(new l1({text:new $1(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)Z.push(new N0({height:1}));let q=[];if(this.widget.props.showCopyOption)q.push(new l1({text:new $1("Enter to copy",new B1({dim:!0}))}));return q.push(new l1({text:new $1("Escape to close",new B1({dim:!0}))})),Z.push(new Z4({children:q.flatMap((V,K)=>K<q.length-1?[V,new N0({width:1}),new l1({text:new $1("•",new B1({dim:!0}))}),new N0({width:1})]:[V]),mainAxisSize:"min"})),new q8({child:new J6({constraints:new p6(X,X,0,G),decoration:new I8(A1.default(),new n4(new S4(A1.blue,1,"rounded"),new S4(A1.blue,1,"rounded"),new S4(A1.blue,1,"rounded"),new S4(A1.blue,1,"rounded"))),padding:new j0(2,2,2,2),child:new i8({autofocus:this.autofocus,onKey:Q,child:new l0({children:Z,mainAxisSize:"min"})})})})}}class g81 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,g81.prototype)}}class m81 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,m81.prototype)}}function L_1(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})}hF();H0();import{spawn as KN8}from"node:child_process";import{promises as WN8}from"node:fs";function CY6(J){return J.kind==="executable"}function SY6(J){return J.kind==="markdown"}var Wz=50000,jY6=300000;async function A_1(J,Q,Y,X={}){let{timeoutMs:G=jY6,signal:Z,source:q}=X;try{let V=await Y.getCommand(J,q);if(!V)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Y.isCommandAvailable(J,q))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(v.debug("Executing command",{commandName:J,filePath:V.filePath,args:Q}),SY6(V))return await HN8(V,Q);else if(CY6(V))return await zN8(V,Q,G,Z);else return{success:!1,output:"",error:"Unsupported command type"}}catch(V){return v.error("Failed to execute command",{commandName:J,error:V}),{success:!1,output:"",error:V instanceof Error?V.message:"Unknown error occurred"}}}async function HN8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await WN8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>Wz?Y.slice(0,Wz)+`
5200
5200
  ... (output truncated at ${Wz} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function zN8(J,Q,Y=jY6,X){return new Promise((G)=>{let[Z,q]=FN8(J,Q);v.debug("Spawning command",{spawnCommand:Z,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Y});let V=WD0(X),K=!1,W=setTimeout(()=>{K=!0,V.abort(),v.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=KN8(Z,q,{stdio:["pipe","pipe","pipe"],signal:V.signal,detached:!0}),z=[],U=[],N=0;H.stdout?.on("data",(O)=>{let M=O.toString();if(N+=M.length,N<=Wz)z.push(M);else{let L=Wz-(N-M.length);if(L>0)z.push(M.slice(0,L))}}),H.stderr?.on("data",(O)=>{let M=O.toString();if(N+=M.length,N<=Wz)U.push(M);else{let L=Wz-(N-M.length);if(L>0)U.push(M.slice(0,L))}}),H.on("close",(O)=>{if(clearTimeout(W),K){G({success:!1,output:z.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(V.signal.aborted){G({success:!1,output:z.join(""),error:"The command was aborted",exitCode:O??void 0});return}let M=O===0||O===1,L=z.join(""),E=U.join(""),I=L;if(!M&&!L.trim()&&E.trim())I=E;else if(E.trim())I+=L?`
5201
5201
  ${E}`:E;if(N>Wz)I+=`
5202
- ... (output truncated at ${Wz} characters)`;G({success:M,output:I.trim(),error:!M?E.trim()||"Command failed":void 0,exitCode:O??void 0})}),H.on("error",(O)=>{clearTimeout(W);let M=O.message;if(K)M=`Command timed out after ${Y}ms`;else if(O.message.includes("operation was aborted")||O.name==="AbortError")M="The command was aborted";G({success:!1,output:z.join(""),error:M})})})}function FN8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return BN8(Y,X?[...X]:null,G,Q);else return UN8(Y,X?[...X]:null,G,Q)}function UN8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function BN8(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]}}H0();iZ();S5();_W();lZ();cZ();EV();ch();OH();K5();x_();g0();YP();import{writeFile as fY6}from"fs/promises";import hY6 from"path";H0();lZ();class w_1{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.1763582484-gdd165b"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await oo(Q,this.configService)}catch(Q){v.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class E_1 extends e0{props;constructor(J){super();this.props=J}createState(){return new _Y6}}class _Y6 extends t0{_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 kY6 extends t0{controller=new CG;focusNode=new f8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});initState(){this.focusNode.requestFocus()}dispose(){this.focusNode.dispose()}build(J){let Q=x6.of(J),{colors:Y}=Q,X=n4.all(new S4(Y.foreground,1,"solid")),G=new iL({controller:this.controller,focusNode:this.focusNode,placeholder:"Enter command argument...",onSubmitted:(V)=>{this.widget.props.onSubmit(V.trim())},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),Z=new Z4({children:[new J6({decoration:{color:A1.default()},child:new l1({text:new $1(">",new B1({color:Y.foreground}))})}),new F4({child:G})]}),q=new J6({padding:j0.symmetric(1,0),child:new l1({text:new $1("",void 0,[new $1("Command: ",new B1({color:Y.foreground})),new $1(this.widget.props.commandName,new B1({color:A1.yellow,bold:!0}))])})});return new J6({decoration:{border:X,color:A1.default()},padding:j0.all(1),child:new l0({children:[q,new N0({height:1}),Z]})})}}class I_1 extends e0{props;constructor(J){super();this.props=J}createState(){return new kY6}}EV();class yY6 extends t0{controller=new CG;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new f8({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>=bF)return!1;let Q=$C(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=x6.of(J),{colors:Y,app:X}=Q,Z=Z8.of(J).size.height,q=Math.max(Math.floor(Z*0.5),10),V=new qA({controller:this.controller,triggers:[new QN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(N)=>{this.widget.props.onSubmit(N.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:M9.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),K=new i8({focusNode:this.focusNode,child:V}),W=new J6({constraints:new p6({maxHeight:q}),padding:j0.symmetric(1,0),child:K}),H=new J6({padding:j0.symmetric(1,0),child:new l1({text:new $1("",void 0,[new $1("Command: ",new B1({color:Y.foreground})),new $1(this.widget.props.commandName,new B1({color:A1.yellow,bold:!0}))])})}),z=new J6({padding:j0.symmetric(1,0),child:new l1({text:this.isConfirmingClearInput?new $1("",void 0,[new $1("Esc",new B1({color:X.keybind})),new $1(" again to clear input",new B1({color:Y.foreground,dim:!0}))]):new $1("",void 0,[new $1("Press ",new B1({color:Y.foreground,dim:!0})),new $1("Enter",new B1({color:X.keybind})),new $1(" to submit, ",new B1({color:Y.foreground,dim:!0})),new $1("Esc",new B1({color:X.keybind})),new $1(" to clear",new B1({color:Y.foreground,dim:!0}))])})}),U=[H,new N0({height:1}),new F4({child:W}),new N0({height:1}),z];return new J6({decoration:{border:n4.all(new S4(Y.foreground,1,"solid")),color:A1.default()},padding:j0.all(1),child:new l0({children:U})})}}class VA extends e0{props;constructor(J){super();this.props=J}createState(){return new yY6}}class P_1 extends j6{props;constructor(J){super();this.props=J}build(){return new q8({child:new l1({text:new $1("",void 0,[new $1(`Forked to new thread:
5202
+ ... (output truncated at ${Wz} characters)`;G({success:M,output:I.trim(),error:!M?E.trim()||"Command failed":void 0,exitCode:O??void 0})}),H.on("error",(O)=>{clearTimeout(W);let M=O.message;if(K)M=`Command timed out after ${Y}ms`;else if(O.message.includes("operation was aborted")||O.name==="AbortError")M="The command was aborted";G({success:!1,output:z.join(""),error:M})})})}function FN8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return BN8(Y,X?[...X]:null,G,Q);else return UN8(Y,X?[...X]:null,G,Q)}function UN8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function BN8(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]}}H0();iZ();S5();_W();lZ();cZ();EV();ch();OH();K5();x_();g0();YP();import{writeFile as fY6}from"fs/promises";import hY6 from"path";H0();lZ();class w_1{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.1763586382-g73297f"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await oo(Q,this.configService)}catch(Q){v.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class E_1 extends e0{props;constructor(J){super();this.props=J}createState(){return new _Y6}}class _Y6 extends t0{_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 kY6 extends t0{controller=new CG;focusNode=new f8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});initState(){this.focusNode.requestFocus()}dispose(){this.focusNode.dispose()}build(J){let Q=x6.of(J),{colors:Y}=Q,X=n4.all(new S4(Y.foreground,1,"solid")),G=new iL({controller:this.controller,focusNode:this.focusNode,placeholder:"Enter command argument...",onSubmitted:(V)=>{this.widget.props.onSubmit(V.trim())},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),Z=new Z4({children:[new J6({decoration:{color:A1.default()},child:new l1({text:new $1(">",new B1({color:Y.foreground}))})}),new F4({child:G})]}),q=new J6({padding:j0.symmetric(1,0),child:new l1({text:new $1("",void 0,[new $1("Command: ",new B1({color:Y.foreground})),new $1(this.widget.props.commandName,new B1({color:A1.yellow,bold:!0}))])})});return new J6({decoration:{border:X,color:A1.default()},padding:j0.all(1),child:new l0({children:[q,new N0({height:1}),Z]})})}}class I_1 extends e0{props;constructor(J){super();this.props=J}createState(){return new kY6}}EV();class yY6 extends t0{controller=new CG;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new f8({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>=bF)return!1;let Q=$C(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=x6.of(J),{colors:Y,app:X}=Q,Z=Z8.of(J).size.height,q=Math.max(Math.floor(Z*0.5),10),V=new qA({controller:this.controller,triggers:[new QN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(N)=>{this.widget.props.onSubmit(N.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:M9.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),K=new i8({focusNode:this.focusNode,child:V}),W=new J6({constraints:new p6({maxHeight:q}),padding:j0.symmetric(1,0),child:K}),H=new J6({padding:j0.symmetric(1,0),child:new l1({text:new $1("",void 0,[new $1("Command: ",new B1({color:Y.foreground})),new $1(this.widget.props.commandName,new B1({color:A1.yellow,bold:!0}))])})}),z=new J6({padding:j0.symmetric(1,0),child:new l1({text:this.isConfirmingClearInput?new $1("",void 0,[new $1("Esc",new B1({color:X.keybind})),new $1(" again to clear input",new B1({color:Y.foreground,dim:!0}))]):new $1("",void 0,[new $1("Press ",new B1({color:Y.foreground,dim:!0})),new $1("Enter",new B1({color:X.keybind})),new $1(" to submit, ",new B1({color:Y.foreground,dim:!0})),new $1("Esc",new B1({color:X.keybind})),new $1(" to clear",new B1({color:Y.foreground,dim:!0}))])})}),U=[H,new N0({height:1}),new F4({child:W}),new N0({height:1}),z];return new J6({decoration:{border:n4.all(new S4(Y.foreground,1,"solid")),color:A1.default()},padding:j0.all(1),child:new l0({children:U})})}}class VA extends e0{props;constructor(J){super();this.props=J}createState(){return new yY6}}class P_1 extends j6{props;constructor(J){super();this.props=J}build(){return new q8({child:new l1({text:new $1("",void 0,[new $1(`Forked to new thread:
5203
5203
 
5204
5204
  `,new B1({color:A1.white,dim:!0})),new $1(`"${this.props.newThreadTitle||"Untitled"}"`,new B1({color:A1.white}))]),textAlign:"center"})})}}class Hz extends e0{props;constructor(J){super();this.props=J}createState(){return new vY6}}class vY6 extends t0{_spinner=new _K;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=x6.of(J),{colors:Y}=Q,X=n4.all(new S4(Y.foreground,1,"solid")),G=this._spinner.toBraille(),Z=new l1({textAlign:"center",text:new $1("",void 0,[new $1(G,new B1({color:A1.yellow})),new $1(" ",void 0),new $1(this.widget.props.message,new B1({color:Y.foreground}))])}),V=[new F4({child:new l0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)V.push(new N0({height:2,child:new J6({padding:j0.symmetric(2,0),child:new l1({text:new $1("",new B1({dim:!0}),[new $1("Press ",new B1({color:Y.foreground})),new $1("Esc",new B1({color:Y.info})),new $1(" to cancel",new B1({color:Y.foreground}))])})})}));let K=new J6({decoration:new I8(A1.default(),X),child:new N0({width:60,height:7,child:new l0({mainAxisAlignment:"start",children:V})})});if(this.widget.props.onAbort)return new i8({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:K});return K}}class zz extends e0{props;constructor(J){super();this.props=J}createState(){return new xY6}}class xY6 extends t0{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof lB}build(J){let Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let W=a41(Q);return{title:W.title,type:W.type,description:W.description}})(),X=Y.type==="error"?A1.red:A1.yellow,G=n4.all(new S4(A1.default(),1,"solid")),Z=new J6({padding:j0.symmetric(1,0),child:new l1({text:new $1(Y.title,new B1({color:X,bold:!0}))})}),q=this.isWidgetMessage(Q)?Q.widget:new l1({text:new $1(Y.description,new B1({color:A1.default()})),selectable:!0}),V=new F4({child:new dL({child:new J6({padding:j0.symmetric(1,0),child:q})})}),K=new J6({padding:j0.symmetric(1,0),child:new l1({text:this.widget.props.onRetry?new $1("",void 0,[new $1("Press ",new B1({color:A1.default(),dim:!0})),new $1("R",new B1({color:A1.yellow})),new $1(" to retry, ",new B1({color:A1.default(),dim:!0})),new $1("Esc",new B1({color:A1.yellow})),new $1(" to cancel",new B1({color:A1.default(),dim:!0}))]):new $1("Press any key to close",new B1({color:A1.default(),dim:!0,italic:!0}))})});return new i8({onKey:(W)=>{if(this.widget.props.onRetry&&W.key==="r")return this.widget.props.onRetry(),"handled";if(W.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!0,child:new J6({decoration:{border:G,color:A1.default()},padding:j0.all(1),child:new l0({mainAxisAlignment:"center",children:[Z,new N0({height:1}),V,K]})})})}}function T_1(J){if(typeof J==="string")return{text:J,images:[]};let Q=J.filter((X)=>X.type==="text"),Y=J.filter((X)=>X.type==="image");return{text:Q.map((X)=>X.text).join(`
5205
5205
  `),images:Y}}class uY6 extends e0{props;constructor(J){super();this.props=J}createState(){return new gY6}}class gY6 extends t0{stage="generating";generatedPrompt=null;generatedImages=[];error=null;abortController=new AbortController;initState(){super.initState(),U9.instance.addPostFrameCallback(()=>{this.startGeneration()})}async startGeneration(){try{let J=await this.widget.props.generateHandoffPrompt(this.widget.props.text,this.widget.props.images,this.abortController.signal),{text:Q,images:Y}=T_1(J);this.setState(()=>{this.stage="preview",this.generatedPrompt=Q,this.generatedImages=Y})}catch(J){this.setState(()=>{this.stage="generating",this.error=J instanceof Error?J:Error(String(J))})}}async executeHandoff(J,Q){this.setState(()=>{this.stage="executing",this.error=null});try{let Y=[];if(J.trim())Y.push({type:"text",text:J});Y.push(...Q);let X=await this.widget.props.handleHandoff({generatedPrompt:Y,images:[]});if(X.ok)this.widget.props.onDismiss();else this.setState(()=>{this.stage="preview",this.error=X.error})}catch(Y){this.setState(()=>{this.stage="preview",this.error=Y instanceof Error?Y:Error(String(Y))})}}build(J){let Q=()=>{this.abortController.abort(),this.widget.props.onAbort()};if(this.stage==="generating"){let Y=[new Hz({message:"Generating handoff prompt...",onAbort:Q})];if(this.error)Y.push(new zz({message:this.error,onRetry:async()=>{this.abortController=new AbortController,this.setState(()=>{this.error=null}),await this.startGeneration()},onDismiss:this.widget.props.onDismiss}));return new s5({children:Y,fit:"expand"})}if(this.stage==="preview"&&this.generatedPrompt){let X=[new VA({commandName:"handoff",placeholder:"Write a handoff prompt, then press Enter to continue",initialText:this.generatedPrompt,initialImages:this.generatedImages,onSubmit:async(G,Z)=>{await this.executeHandoff(G,Z)},onDismiss:this.widget.props.onDismiss,completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,enabled:this.error===null})];if(this.error)X.push(new zz({message:this.error,onDismiss:()=>this.setState(()=>{this.error=null})}));return new s5({children:X,fit:"expand"})}return new Hz({message:"Creating handoff thread...",onAbort:Q})}}class mY6 extends e0{props;constructor(J){super();this.props=J}createState(){return new pY6}}class pY6 extends t0{result=void 0;isLoading=!1;build(J){let Q=[];if(this.isLoading)Q.push(new Hz({message:"Updating visibility..."}));else if(this.result!==void 0)Q.push(new zz({message:this.result,onDismiss:()=>{this.widget.props.onDismiss()}}));else{let Y=["private","workspace","unlisted","public","support"],X=this.widget.props.workspace?.groups&&this.widget.props.workspace.groups.length>0?["private","workspace","group","unlisted","public","support"]:Y;Q.push(new cB({items:X,getLabel:(G)=>{switch(G){case"private":return"Private - Only you can see this thread";case"workspace":return"Workspace - Visible to workspace members";case"group":return"Group - Visible to group members";case"unlisted":return"Unlisted - Anyone with the link can view";case"public":return"Public - Searchable and on your public profile";case"support":return"Share with Support - Share with Amp support for debugging"}},title:"Select Thread Visibility",onAccept:async(G)=>{this.setState(()=>{this.isLoading=!0});let Z=await this.widget.props.execute(G);this.setState(()=>{this.isLoading=!1,this.result=Z})},onDismiss:this.widget.props.onDismiss}))}return new s5({children:Q,fit:"expand"})}}function DN8(J){return J.startsWith("custom-command-")}function bY6(J){return J.startsWith("agent-mode-")}function ON8(J){return J.replace(/^custom-command-/,"")}class R_1{configService;registry;onExecute;onExecutionComplete;isDogfooding;commands=new Map;latestCustom=[];latestConfig=null;telemetrySubmitter;constructor(J,Q,Y,X,G=!1){this.configService=J;this.registry=Q;this.onExecute=Y;this.onExecutionComplete=X;this.isDogfooding=G;this.configService.config.subscribe((Z)=>{this.latestConfig=Z,this.commands.clear(),this.registerCommands(Z)}),this.registry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new w_1(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService)}async execute(J,Q,Y=[],X,G){this.telemetrySubmitter.submit(J).catch((z)=>{v.debug("Failed to submit command telemetry",z)});let Z=Date.now(),q=`command-${Z}-${Math.random().toString(36).substring(7)}`,V=this.commands.get(J);if(V){this.onExecute({id:q,name:V.id,startTime:Z,abortController:X});try{return await V.execute(Q,X,Y)}finally{this.onExecutionComplete()}}let K=ON8(J),W=this.latestCustom.find((z)=>z.name===K&&(!G||z.source===G));if(!W)return;this.onExecute({id:q,name:W.name,startTime:Z,abortController:X});let H=await A_1(W.name,Y,this.registry,{signal:X.signal,source:W.source});if(this.onExecutionComplete(),H.success){let z=Q.editorState.text,N=z.trim()&&!z.endsWith(`
@@ -5241,13 +5241,13 @@ ${L}
5241
5241
  # Agent Mode
5242
5242
 
5243
5243
  ${K}`,I=new O7({child:new _2({markdown:E})});return new lB(I,"System Prompt")}catch(G){return v.error("Failed to build system prompt",G),Error("Failed to build system prompt")}},isEnabled:()=>this.isDogfooding}),this.register({id:"debug-thread-json",noun:"dev",verb:"open thread JSON",description:"Open thread JSON in editor",execute:async(Y)=>{try{let X=hY6.join("/tmp",`amp-thread-${Y.thread.id}-${Date.now()}.json`),G=JSON.stringify(Y.thread,null,2);await fY6(X,G,"utf-8"),await Yz(X),v.info("Thread JSON written and opened in editor",{file:X});return}catch(X){return v.error("Failed to write thread JSON or open editor",X),Error("Failed to write thread JSON or open editor",{cause:X})}},isEnabled:()=>this.isDogfooding}),this.register({id:"debug-thread-yaml",noun:"dev",verb:"open thread YAML",description:"Open thread YAML in editor",execute:async(Y)=>{try{let X=hY6.join("/tmp",`amp-thread-${Y.thread.id}-${Date.now()}.yaml`),G=XS0.dump(Y.thread);await fY6(X,G,"utf-8"),await Yz(X),v.info("Thread YAML written and opened in editor",{file:X});return}catch(X){return v.error("Failed to write thread YAML or open editor",X),Error("Failed to write thread YAML or open editor",{cause:X})}},isEnabled:()=>this.isDogfooding})}async getCurrentAgentMode(J){let Q=await J.configService.getLatest(),Y=WJ(Q.settings);return J.getInMemoryAgentModeOverride()??Y}getAgentModeSync(J){let Q=WJ(this.latestConfig?.settings??{});return J.getInMemoryAgentModeOverride()??Q}isThreadEmpty(J){return J.thread.messages.length===0}threadHasMessages(J){return!this.isThreadEmpty(J)}getQueuedMessages(J){return J.thread.queuedMessages??[]}hasPromptText(J){return J.editorState.text.trim().length>0}truncatedPromptText(J){let Q=J.editorState.text.trim().replace(/\n/g," ");return Q.length>20?`${Q.slice(0,20)}...`:Q}register(J){if(this.commands.has(J.id))throw Error(`Command with id ${J.id} already registered`);this.commands.set(J.id,J)}createAgentModeCommand(J){return{id:`agent-mode-${J}`,noun:"mode",verb:`use ${J}`,description:`Use ${J} mode`,execute:async(Q)=>{try{if(this.threadHasMessages(Q))return Error("Can only change agent mode for new threads");Q.setInMemoryAgentModeOverride(J)}catch(Y){return v.error("Failed to access agent mode setting",Y),Error("Failed to access agent mode setting")}},isShown:(Q)=>{if(Q.getInMemoryAgentModeOverride()===J)return`Cannot use mode: use ${J} when already in ${J} mode`;if(this.threadHasMessages(Q))return`Can only use mode: use ${J} for new threads`;return!0},isEnabled:(Q)=>J==="plan"?this.latestConfig?.settings["experimental.planMode"]===!0:!0}}getAllCommands(J){let Q=this.latestCustom.filter((q)=>q.available).map((q)=>({id:`custom-command-${q.name}`,noun:"custom",verb:q.name,description:`Run custom command ${q.name}`,source:q.source,customFlow:q.kind==="executable"?(V,K,W)=>{return new I_1({commandName:q.name,onSubmit:async(H)=>{K(L_1(H)),W()},onDismiss:W})}:void 0,execute:(V,K,W)=>this.execute(q.name,V,W??[],K,q.source)})),Y=Array.from(this.commands.values()).filter((q)=>{return q.noun!=="dev"}),X=Array.from(this.commands.values()).filter((q)=>{return q.noun==="dev"}),G=J?Y.filter((q)=>!q.isEnabled||q.isEnabled(J)===!0):Y,Z=this.isDogfooding?X:[];return[...G,...Q,...Z]}}H0();class C_1 extends j6{props;debugLabel="CommandPalette";constructor(J){super();this.props=J}build(J){let{context:Q,enabled:Y,paletteController:X,commands:G,onExecuteResult:Z,onDismiss:q}=this.props,V=G.getAllCommands(Q),K="",W=(U)=>{return V.filter((N)=>{if(U==="")return(N.isShown?N.isShown(Q):!0)===!0;return!0})},H=(U)=>{let N=0;for(let O of W(U))if(O.noun){let M=O.noun.toLowerCase().length;if(M>N)N=M}return N};return new cB({items:V,enabled:Y??!0,isItemDisabled:(U)=>{return(U.isShown?U.isShown(Q):!0)!==!0},buildDisabledReasonWidget:(U)=>{let N=U.isShown?U.isShown(Q):!0;if(typeof N!=="string")return;let O=U.noun?`${U.noun}: ${U.verb}`:void 0;if(!O)return new l1({text:new $1(N,new B1({color:A1.default(),dim:!0}))});let M=[],L=N.indexOf(O);if(L===-1)return new l1({text:new $1(N,new B1({color:A1.default(),dim:!0}))});if(L>0)M.push(new $1(N.slice(0,L),new B1({color:A1.default(),dim:!0})));M.push(new $1(O,new B1({color:A1.yellow,dim:!0})));let E=L+O.length;if(E<N.length)M.push(new $1(N.slice(E),new B1({color:A1.default(),dim:!0})));return new l1({text:new $1(void 0,void 0,M)})},filterItem:(U,N)=>{if(N==="")return(U.isShown?U.isShown(Q):!0)===!0;return!0},getLabel:(U)=>{let N=U.noun?`${U.noun.toLowerCase()} ${U.verb.toLowerCase()}`:U.verb.toLowerCase(),O=U.getPromptText&&U.getPromptText(Q),M=U.aliases?U.aliases.join(" "):"",L=O?`${N} ${O}`:N;return M?`${L} ${M}`:L},sortItems:(U,N,O)=>{if(K=O,O!==""){let M=G.getCommandFollows(U.item.id),L=G.getCommandFollows(N.item.id);if(M.includes(N.item.id))return 1;if(L.includes(U.item.id))return-1}if(N.score!==U.score)return N.score-U.score;return G.getPriority(N.item.id,Q)-G.getPriority(U.item.id,Q)},onAccept:async(U)=>{let N=new AbortController;try{if(U.customFlow){let O=async(L)=>{return N=new AbortController,G.execute(U.id,Q,L,N,U.source)},M=()=>N.abort(new m81(U));X.launchCustomWidget((L)=>U.customFlow(L,O,q,M))}else{if(U.nonBlocking)return G.execute(U.id,Q,void 0,N,U.source).catch((M)=>{v.warn("Non-blocking command failed",{error:M})}),q();let O=await G.execute(U.id,Q,void 0,N,U.source);if(O)Z(O);else q()}}catch(O){Z(O instanceof Error?O:Error(String(O)))}},onDismiss:q,title:"Command Palette",renderItem:(U,N,O,M)=>{let L=x6.of(M),{colors:E}=L,I=N?A1.yellow:void 0,P=N?A1.black:E.foreground,R=O||!N,j=H(K),y=[];if(U.noun)y.push(new $1(U.noun.toLowerCase(),new B1({color:P,dim:R})));let h=new N0({width:j,child:new l1({text:new $1("",void 0,y),textAlign:"right"})}),p=new N0({width:j>0?2:0}),g=[],b=U.verb.toLowerCase(),c=b.match(/^(\$_|md)\s+(.+)$/);if(c)g.push(new $1(c[1],new B1({color:A1.blue,bold:!0,dim:O}))),g.push(new $1(" ")),g.push(new $1(c[2],new B1({color:P,bold:!0,dim:O})));else g.push(new $1(b,new B1({color:P,bold:!0,dim:O})));if(U.noun?.toLowerCase()==="dev")g.push(new $1(" (",new B1({color:P,dim:O}))),g.push(new $1("dev only",new B1({color:A1.blue,dim:O}))),g.push(new $1(")",new B1({color:P,dim:O})));if(O)g.push(new $1(" (unavailable)",new B1({color:P,dim:!0})));let a=U.getPromptText&&U.getPromptText(Q);if(a&&!O)g.push(new $1(' "',new B1({color:P,dim:O}))),g.push(new $1(a,new B1({color:P,dim:O}))),g.push(new $1('"',new B1({color:P,dim:O})));if(K&&U.aliases){let t=K.toLowerCase(),W1=U.aliases.find((F1)=>F1.toLowerCase().includes(t));if(W1)g.push(new $1(" (alias: ",new B1({color:P,dim:O}))),g.push(new $1(W1,new B1({color:P,dim:O}))),g.push(new $1(")",new B1({color:P,dim:O})))}let o=new F4({child:new l1({text:new $1("",void 0,g)})}),m=new N0({width:0});if(U.shortcut){let W1=U.shortcut.toString().split("+"),F1=[];for(let r=0;r<W1.length;r++){let s=W1[r],K1=s==="Ctrl"||s==="Shift"||s==="Alt"||s==="Meta"?A1.blue:A1.index(8);if(F1.push(new $1(s,new B1({color:K1,bold:!0,dim:O}))),r<W1.length-1)F1.push(new $1(" ",new B1({color:A1.index(8),dim:O})))}m=new l1({text:new $1("",void 0,F1)})}else if(U.source){let t=U.source==="workspace"?"Workspace":"Global";m=new l1({text:new $1(t,new B1({color:A1.index(8),dim:O}))})}return new J6({decoration:I?{color:I}:void 0,padding:j0.only({left:1,right:2}),child:new Z4({children:[h,p,o,m],crossAxisAlignment:"start"})})}})}}class S_1 extends e0{props;constructor(J){super();this.props=J}createState(){return new dY6}}class dY6 extends t0{activeModal=null;paletteController={launchCustomWidget:(J)=>{this.setState(()=>{this.activeModal={type:"custom-widget",widgetFactory:J}})}};showMessage(J){this.setState(()=>{this.activeModal={type:"message",message:J,dismiss:()=>{this.widget.props.onDismiss()}}})}build(J){if(!this.widget.props.mainThread)return new N0;let Q=[new C_1({commands:this.widget.props.commands,thread:this.widget.props.mainThread,context:this.widget.props.commandContext,onDismiss:()=>this.widget.props.onDismiss(),paletteController:this.paletteController,onExecuteResult:(Y)=>this.showMessage(Y),enabled:this.activeModal===null})];if(this.activeModal!==null){let Y;switch(this.activeModal.type){case"custom-widget":Y=this.activeModal.widgetFactory(this.widget.props.commandContext);break;case"message":Y=new zz({message:this.activeModal.message,onDismiss:this.activeModal.dismiss});break}Q.push(Y)}return new s5({fit:"expand",children:Q})}}jM();X4();g0();class j_1{fuzzyClient;threadIndexer;constructor(J,Q){this.fuzzyClient=J;this.threadIndexer=Q}async buildOptions(J){if(J.trigger==="@"){let[Q,Y]=await Promise.all([this.buildFileOptions(J.query),this.buildThreadMentionOptions(J.query)]);return[...Q,...Y]}return[]}async buildFileOptions(J){try{let Q=await this.getOpenFiles();return(await this.fuzzyClient.queryCompletions(J,20,Q)).map((X)=>zY6(X))}catch(Q){return[]}}async buildThreadMentionOptions(J){return(await this.threadIndexer.search(J,5)).map(({id:Y,title:X})=>FY6(Y,X,Y))}async getOpenFiles(){let J=await F6(F7.status);if(!J.connected||!J.visibleFiles?.length)return;return J.visibleFiles.map((Q)=>{return p0.parse(Q).fsPath})}}class __1 extends j6{details;constructor({key:J,details:Q}){super(J?{key:J}:{});this.details=Q}build(J){let Y=v4.of(J).colorScheme,X=Z8.of(J),G=new B1({color:Y.primary,bold:!0}),Z=new B1({color:Y.foreground}),q=new B1({color:Y.foreground}),V=new B1({color:Y.secondary,bold:!0}),K=X.size.width,W=X.size.height,H=K-4,z=Math.min(W-4,Math.floor(W*0.6)),U=Math.min(80,H),N=new O7({autofocus:!0,child:new b6({padding:j0.only({left:2,right:2}),child:new l0({crossAxisAlignment:"start",children:[new q8({child:new l1({text:new $1(`Details
5244
- `,G)})}),new N0({height:1}),new l1({text:new $1(this.details,Z)}),new N0({height:1})]})})}),O=new q8({child:new l1({text:new $1("",q,[new $1("Press ",q),new $1("Escape",V),new $1(" to close • Use ",q),new $1("↑↓",V),new $1(" or ",q),new $1("j/k",V),new $1(" to scroll",q)])})}),M=new l0({crossAxisAlignment:"stretch",children:[new F4({child:N}),O]});return new q8({child:new J6({constraints:new p6(U,U,0,z),decoration:new I8(Y.background,n4.all(new S4(Y.primary,1,"rounded"))),child:M})})}}IY();qI();IV();K4();class k_1 extends e0{confirmationRequest;onResponse;onShowOverlay;constructor({key:J,confirmationRequest:Q,onResponse:Y,onShowOverlay:X}){super({key:J});this.confirmationRequest=Q,this.onResponse=Y,this.onShowOverlay=X}createState(){return new cY6}}class cY6 extends t0{initState(){super.initState()}dispose(){super.dispose()}getOverlayContent(){if(this.widget.confirmationRequest.type==="tool-use"&&this.widget.confirmationRequest.tools.length===1){let J=this.widget.confirmationRequest.tools[0];if(!J?.useBlock)return null;if(J.useBlock.name===r9)return J.useBlock.input.cmd;if(J.useBlock.name===v2){let Q=J.useBlock.input;return dW(Q.old_str,Q.new_str,Q.path)}if(J.useBlock.name===T2){let Q=J.useBlock.input,Y=Q.content||"";return dW("",Y,Q.path)}}return null}build(J){let Y=v4.of(J).colorScheme,X=this.formatConfirmationTitle(this.widget.confirmationRequest),G=this.createConfirmationOptions(this.widget.confirmationRequest);return new lY6({title:X,options:G,onSelect:this.widget.onResponse,borderColor:Y.warning,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1,onShowCommand:()=>{let q=this.getOverlayContent();if(q&&this.widget.onShowOverlay)this.widget.onShowOverlay(q)}})}formatConfirmationTitle(J){switch(J.type){case"tool-use":{if(J.tools.length===1){let Q=J.tools[0];if(Q?.useBlock)return this.formatToolConfirmation(Q.useBlock,J.reason);return"Confirm tool call"}return`Confirm ${J.tools.length} tool calls`}case"out-of-credits":return"Insufficient usage balance. Retry?";case"agent-file-creation":return`Create ${V9} file for this codebase?`}}formatToolConfirmation(J,Q){if(J.name===r9){let Y=J.input,X=this.truncateCommand(Y.cmd),Z=Y.cmd!==X?`
5244
+ `,G)})}),new N0({height:1}),new l1({text:new $1(this.details,Z)}),new N0({height:1})]})})}),O=new q8({child:new l1({text:new $1("",q,[new $1("Press ",q),new $1("Escape",V),new $1(" to close • Use ",q),new $1("↑↓",V),new $1(" or ",q),new $1("j/k",V),new $1(" to scroll",q)])})}),M=new l0({crossAxisAlignment:"stretch",children:[new F4({child:N}),O]});return new q8({child:new J6({constraints:new p6(U,U,0,z),decoration:new I8(Y.background,n4.all(new S4(Y.primary,1,"rounded"))),child:M})})}}IY();qI();IV();K4();class k_1 extends e0{confirmationRequest;onResponse;onShowOverlay;constructor({key:J,confirmationRequest:Q,onResponse:Y,onShowOverlay:X}){super({key:J});this.confirmationRequest=Q,this.onResponse=Y,this.onShowOverlay=X}createState(){return new cY6}}class cY6 extends t0{initState(){super.initState()}dispose(){super.dispose()}getOverlayContent(){if(this.widget.confirmationRequest.type==="tool-use"&&this.widget.confirmationRequest.tools.length===1){let J=this.widget.confirmationRequest.tools[0];if(!J?.useBlock)return null;if(J.useBlock.name===r9)return J.useBlock.input.cmd;if(J.useBlock.name===v2){let Q=J.useBlock.input;return dW(Q.old_str,Q.new_str,Q.path)}if(J.useBlock.name===T2){let Q=J.useBlock.input,Y=Q.content||"";return dW("",Y,Q.path)}}return null}build(J){let Y=v4.of(J).colorScheme,X=this.formatConfirmationTitle(this.widget.confirmationRequest),G=this.createConfirmationOptions(this.widget.confirmationRequest);return new lY6({title:X,options:G,onSelect:this.widget.onResponse,borderColor:Y.warning,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1,onShowCommand:()=>{let q=this.getOverlayContent();if(q&&this.widget.onShowOverlay)this.widget.onShowOverlay(q)}})}formatConfirmationTitle(J){switch(J.type){case"tool-use":{if(J.tools.length===1){let Q=J.tools[0];if(Q?.useBlock)return this.formatToolConfirmation(Q.useBlock,J.reason);return"Confirm tool call"}return`Confirm ${J.tools.length} tool calls`}case"out-of-credits":return"Insufficient usage balance. Retry?";case"agent-file-creation":return`Create ${V9} file for this codebase?`}}formatToolConfirmation(J,Q){if(J.name===r9){let X=J.input.cmd??"",G=this.truncateCommand(X),q=X!==G?`
5245
5245
 
5246
5246
  Press ? for full command`:"";return`${`Run this command?
5247
5247
 
5248
- ${X}
5248
+ ${G}
5249
5249
 
5250
- (${Q})`}${Z}`}else if(J.name===v2)return`${`Allow editing file ${J.input.path} (${Q})?`}
5250
+ (${Q})`}${q}`}else if(J.name===v2)return`${`Allow editing file ${J.input.path} (${Q})?`}
5251
5251
 
5252
5252
  Press ? to view full diff`;else if(J.name===T2)return`${`Allow creating file ${J.input.path} (${Q})?`}
5253
5253
 
@@ -5282,7 +5282,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
5282
5282
  `)?`${V}...`:G,W=new B1({color:A1.index(8)}),H=[new $1(K,W)];if(q>0){let z=new B1({color:Y.success});for(let U=1;U<=q;U++)H.push(new $1(" ")),H.push(new $1(`[${U}]`,z))}return new b6({padding:j0.only({bottom:0}),child:new Z4({crossAxisAlignment:"start",children:[new b6({padding:j0.only({right:1}),child:new l1({text:new $1("•",new B1({color:A1.index(8)}))})}),new F4({child:new l1({text:new $1("",void 0,H)})})]})})}}class Qk1 extends e0{createState(){return new j$6}}class j$6 extends t0{_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 B1({color:A1.red}),Y=new B1({color:this._visible?A1.red:A1.transparent()});return new Z4({children:[new l1({text:new $1("⏺",Y)}),new N0({width:1}),new l1({text:new $1("Replay",Q)})]})}}function PD8(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/3600000),G=Math.floor(X/24),Z=Math.floor(G/7),q=Math.floor(G/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;if(Z<=4)return`${Z}w ago`;return`${q}mo ago`}class Yk1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{return{ok:!0,threads:(await new Promise((G)=>{let Z=this.threadHistoryService.observeThreadList().subscribe((q)=>{Z.unsubscribe(),G(q)})})).filter((G)=>{if(!J.trim())return!0;let Z=G.title?.toLowerCase()||"untitled",q=G.id.toLowerCase(),V=J.toLowerCase();return Z.includes(V)||q.includes(V)}).map((G)=>{let Z=new Date(G.userLastInteractedAt),q=PD8(Z),V=G.id.slice(-8),K=G.env?.initial.trees?.[0]?.uri;return{id:G.id,title:G.title||"Untitled",updatedAt:new Date(G.userLastInteractedAt).toISOString(),description:{timeAgo:q,title:G.title||"Untitled",shortThreadID:V},diffStats:G.summaryStats?.diffStats,workspaceURI:K,parentRelationships:G.parentRelationships}})}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}}H0();w9();class $k1{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new h3;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){v.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){v.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(qO()).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 _$6(J,Q){switch(J){case"update-available":return[new $1("A newer Amp is available. Run ",new B1({color:Q.foreground,dim:!0})),new $1("amp update",new B1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new $1("Update complete, run ",new B1({color:Q.foreground,dim:!0})),new $1("amp update",new B1({color:Q.warning})),new $1(" to see warnings",new B1({color:Q.foreground,dim:!0}))];case"update-error":return[new $1("Update failed, run ",new B1({color:Q.foreground,dim:!0})),new $1("amp update",new B1({color:Q.warning})),new $1(" to see warnings",new B1({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function jD8(J){return new Promise((Q)=>{RD8("git",["branch","--show-current"],{cwd:J},(Y,X)=>{if(Y){Q(null);return}let G=X.trim();Q(G||null)})})}class x$6 extends e0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new f$6}}class f$6 extends t0{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;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=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 $k1;previewThread=null;planScrollController=(()=>{let J=new h3;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new h3;return J.followMode=!1,J})();showingSelectionCopiedHint=!1;isShowingStandaloneThreadPicker=!1;filterThreadPickerByWorkspace=!0;agentModePulseSeq=0;currentGitBranch=null;messageViewFocusNode=new f8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new f8({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=zG();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,G=Q.messages;for(let Z=0;Z<G.length;Z++){if(this.replayAbortController.signal.aborted)break;let q=G[Z];if(!q)continue;if(Z>0)await this.replaySleep(J.messageDelayMs);if(q.role==="user"&&Y){let W=q.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
5283
5283
  `);if(W)await this.replayTypeMessage(W,X)}if(q.role==="assistant"){let W=q.content.some((U)=>U.type==="tool_use"),H=G[Z+1],z=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&z){let U={...q,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let N=J.thread.id;this.getMessageScrollController(N).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),q]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,q],this.textController.clear()});let V=J.thread.id;this.getMessageScrollController(V).scrollToBottom()}await this.replaySleep(J.exitDelayMs),M9.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Y=J.split(/(?<=\s)/),X=60000/Q;for(let G of Y){if(this.replayAbortController.signal.aborted)break;let Z=X/G.length;for(let q of G){this.textController.text=this.textController.text+q,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let V=0.8+Math.random()*0.4,K=Z*V;await this.replaySleep(K)}}}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return L41(this.widget.dependencies.worker.thread,this.inMemoryAgentModeOverride?{agentMode:this.inMemoryAgentModeOverride}:null,this.freeTierStatus,{"experimental.agentMode":this.currentAgentMode})}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Y=J.items.filter((Z)=>Z.type==="toolResult").filter((Z)=>Z.toolResult.run.status==="in-progress"||Z.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((Z)=>Z.toolRun.status==="in-progress"||Z.toolRun.status==="queued");return[...Y,...X].length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new $1(this.submitDisabledHint,new B1({color:J.foreground,dim:!0}));if(this.isExiting)return new $1("Exiting...",new B1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new $1("",void 0,[new $1("Ctrl+C",new B1({color:Q.keybind})),new $1(" again to exit",new B1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new $1("",void 0,[new $1("Esc",new B1({color:Q.keybind})),new $1(" again to clear input",new B1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new $1("",void 0,[new $1("Escape",new B1({color:Q.keybind})),new $1(" to close help",new B1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),G=qk1(X);return new $1("",void 0,[new $1("Images aren't supported in ",new B1({color:J.warning,dim:!1})),new $1(X,new B1({color:G})),new $1(" mode.",new B1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0)return new $1("",void 0,[new $1("Esc",new B1({color:Q.keybind})),new $1(" to cancel",new B1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new $1("Selection copied to clipboard",new B1({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new $1(this.showingCannotToggleMessage,new B1({color:J.warning,dim:!1}));let Y=_$6(this.updateState,J);if(Y)return new $1("",void 0,Y);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Y}=this.widget.dependencies;if(!Q.mainThread?.id)return;let G=Q.mainThread?.messages.findIndex((Z)=>Z===J);if(G===void 0||G===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),await Y.handle({type:"thread:truncate",fromIndex:G}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(Z){v.error("Failed to edit message:",Z)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Y,threadSyncService:X}=this.widget.dependencies,G=Q.mainThread?.id;if(!G)return;let Z=Q.mainThread?.messages.findIndex((q)=>q===J);if(Z===void 0||Z<=0)return;try{let q=await q3.getOrCreateForThread(Y,G),V=await TR(q,X,Z-1);await this.switchToExistingThread(V)}catch(q){v.error("Failed to fork thread:",q),this.showErrorMessage(`Failed to fork thread: ${q}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Y,worker:X}=this.widget.dependencies,G=Y.mainThread;if(!G)return;let Z=G.messages.findIndex((q)=>q.messageId!==void 0&&q.messageId===J.messageId);if(Z===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let q=nB(Q);if(q)await X.handle({type:"thread:truncate",fromIndex:Z}),this.invokeBashCommand(q.cmd,{visibility:q.visibility});else{let V=[{type:"text",text:Q}];if(this.imageAttachments.length>0)V.push(...this.imageAttachments);let K={content:V,agentMode:G.agentMode},W=Z===0;if(G.agentMode&&!W&&K.agentMode!==G.agentMode){v.error(`Cannot edit message: This thread uses ${G.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:K,index:Z})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(q){v.error("Failed to edit message:",q)}};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 v.error("Failed to get affected files:",Y),[]}};textController=new CG;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new h3);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let G=this.searchElementTreeByKey(X,Q);if(G)return G}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{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(XC1(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 c2("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=nB(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}),U9.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}),U9.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker)this.autocompleteFocusNode.requestFocus()})}catch(Q){v.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 R_1(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 j_1(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=p0.file(process.cwd()),Y=W6(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,switchToThread:async(X)=>{return await this.switchToExistingThread(X),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(X,G,Z)=>{let q=this.widget.dependencies.threadState.mainThread?.id;if(!q)throw Error("No active thread");let V=setTimeout(()=>{Z.throwIfAborted()},60000);try{let K=await this.widget.dependencies.threadService.generateHandoffPrompt(q,X,G,this.widget.dependencies.configService,Z);return clearTimeout(V),K}catch(K){throw clearTimeout(V),K}},handleHandoff:async(X,G)=>{let{goal:Z,generatedPrompt:q,images:V}=G;if(!Z&&!q)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let K=this.widget.dependencies.threadState.mainThread?.id;if(!K)return{ok:!1,error:Error("No active thread")};let W=setTimeout(()=>X.abort(new g81("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let H=await this.widget.dependencies.threadService.createHandoffThread(K,{goal:Z,generatedPrompt:q,images:V},this.widget.dependencies.configService,X.signal);return clearTimeout(W),await this.switchToExistingThread(H),{ok:!0}}catch(H){if(clearTimeout(W),H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")))throw X.signal.reason;throw H}}catch(K){return v.error("Failed to create handoff thread",K),{ok:!1,error:K instanceof Error?K:Error(String(K))}}},getGuidanceFiles:async(X)=>{if(!J.mainThread)return[];return(await Go({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},J.mainThread,X)).map((Z)=>({uri:Z.uri,type:Z.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(X)=>{this.setState(()=>{this.inMemoryAgentModeOverride=X,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode,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 G=await this.widget.dependencies.threadService.createPlanExecutionThread(X,"smart");await this.switchToExistingThread(G)}catch(X){v.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 Yk1(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 jD8(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{visibility:Q})=>{let Y=Date.now(),X=`bash-${Y}-${Math.random().toString(36).substring(7)}`,G={cmd:J},Z=new AbortController;this.widget.dependencies.worker.invokeBashTool(G,Z.signal,Q===iB).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((K)=>K.id===X))this.bashInvocations=this.bashInvocations.map((K)=>K.id===X?{...K,toolRun:q}:K);else{let K={id:X,args:G,toolRun:q,startTime:Y,abortController:Z,hidden:Q===iB};this.bashInvocations=[...this.bashInvocations,K]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};toggleAgentMode=()=>{let J=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(OV(J.thread)>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.getEffectiveAgentMode(),G=Ab(X,this.cachedVisibleModes);if(G!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=G,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.getEffectiveAgentMode(),Y=Ab(Q,this.cachedVisibleModes);if(Y===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),H5(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(!lh(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>=bF)return!1;let Y=$C(J);if(typeof Y==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Y}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Y,unlink:X,rmdir:G,writeFile:Z}=await import("node:fs/promises"),{tmpdir:q}=await import("node:os"),V=await import("node:path");try{let K=await Q(V.join(q(),"amp-edit-")),W=V.join(K,"message.amp.md");await Z(W,J,"utf-8"),await Yz(W);try{let H=await Y(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")v.error("Failed to read temporary file",H)}try{await X(W),await G(K)}catch(H){v.warn("Failed to clean up temporary file",H)}}catch(K){v.error("Error opening editor:",K)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=nB(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(a$.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();M9.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),M9.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),M9.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Y)=>{U9.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus,F6(this.widget.dependencies.configService.config).then((Y)=>{let X=L41(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,Y.settings);if(v.info(`[initState] Resolved agentMode: ${X}`),this.widget.dependencies.sessionState?.agentMode)this.setState(()=>{this.inMemoryAgentModeOverride=X})}),this.updateGitBranch(),this.adSubscription=IC1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride&&H5(this.inMemoryAgentModeOverride)||this.randomAd===null)&&EC1(this.lastUserInteractionTime)}).subscribe({next:(Y)=>{if(Y){let X=CD8(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (Z91(),G91)).then(({recordAdEvent:G})=>{let Z=this.widget.dependencies.worker.thread,q=Z.messages[Z.messages.length-1];G("viewed",{adId:Y.id,advertiserId:Y.advertiserId,threadId:Z.id,messageId:q?.messageId,impressionId:X,placement:"tui",matchType:Y.metadata?.matchType,matchedPatterns:Y.metadata?.matchedPatterns,candidateAdPoolCount:Y.metadata?.candidateAdPoolCount,clientRegion:Y.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=Y}),U9.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){v.warn("No active thread worker found to handle IDE message");return}await new Promise((G)=>setTimeout(G,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}}),v.debug("Message sent from IDE to agent",{message:Y.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Y)=>{this.textController.insertText(Y),v.debug("Appended text to CLI prompt from IDE",{text:Y.slice(0,100)})}),this.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=zG(Y.settings);if(this.freeTierStatus&&(!this.freeTierStatus.eligible||!this.freeTierStatus.workspaceAllowsAmpFree))X=X.filter((G)=>!H5(G.mode));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(XC1("")),this.shouldUseProgressBar())process.stdout.write(l26())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((V)=>V.type==="toolResult").map((V)=>({toolUse:V.toolUse,toolRun:V.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((V)=>V.toolRun.status==="blocked-on-user");if(X.length===0)return null;let G=X[0],Z=G.toolRun.status==="blocked-on-user"?G.toolRun.toAllow??[]:[],q=G.toolRun.status==="blocked-on-user"?G.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:G.toolUse,toAllow:Z}],subthreadID:G.subthreadID,reason:q}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){v.error("No current tool confirmation found");return}let Y=Q.tools[0]?.useBlock;if(!Y){v.error("No tool use block found in confirmation");return}if(J==="allow-all-session")UZ("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(G){if(G&&G instanceof Error)this.setState(()=>{this.displayMessage=G});else v.error("Failed to write dangerouslyAllowAll setting:",G);return}if(J==="always-guarded"){let G=Q.tools[0]?.toAllow??[],Z=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...G,...Z];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q,"global")}if(J==="connect-github"){let G=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await pJ(G)}catch(Z){v.error("Failed to open settings page:",Z),await this.showErrorMessage(`Cannot open browser. Please go to ${G} to connect to GitHub`)}return}if(J==="disable-librarian"){let G=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!G.includes(F$))await this.widget.dependencies.settingsStorage.set("tools.disable",[...G,F$],"global")}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let G={type:"user:tool-input",toolUse:Y.id,value:{accepted:X}};if(Q.subthreadID)await(await q3.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(G);else await this.widget.dependencies.worker.handle(G)}catch(G){v.error("Failed to send tool confirmation:",G)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Y=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Y)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Y=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Y.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null}),await this.startAndSwitchToNewThread();break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),$41({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 Yz(Q.getSettingsFilePath())}catch(Y){let X=Y instanceof Error?Y.message:String(Y);await this.showErrorMessage(`Failed to open settings: ${X}`)}};cancelStreamingMessage=async()=>{await q3.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{v.info(`[switchToExistingThread] Switching to thread: ${J}`);let X=await this.widget.dependencies.switchToThread(J);v.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${X.thread.agentMode}`);let G=await this.widget.dependencies.configService.getLatest(),Z=L41(X.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,G.settings);if(v.info(`[switchToExistingThread] Thread ${J} resolved agentMode: ${Z}`),this.widget.dependencies.worker=X,this.widget.dependencies.threadID=X.thread.id,this.widget.dependencies.switchWorker(X),this.setState(()=>{v.info("[switchToExistingThread] Clearing inMemoryAgentModeOverride"),this.inMemoryAgentModeOverride=null}),X.thread.draft)if(v.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof X.thread.draft==="string")this.textController.insertText(X.thread.draft);else{let q=X.thread.draft.filter((W)=>W.type==="text"),V=X.thread.draft.filter((W)=>W.type==="image"),K=q.map((W)=>W.text).join(`
5284
5284
  `);if(K)this.textController.insertText(K);if(V.length>0)this.setState(()=>{this.imageAttachments=V})}}catch(X){throw v.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=OV(Q.thread)===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Y&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let G=[{type:"text",text:J}];if(this.imageAttachments.length>0)G.push(...this.imageAttachments);if(await Q.handle({type:"user:message",message:{content:G,agentMode:X}}),Y)$41({agentMode:X});this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]}),U9.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();$41({agentMode:Q}).catch((Y)=>{v.warn("Failed to save session state on exit:",Y)}).finally(()=>{M9.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=SD8();if(J===Q)return"~";if(J.startsWith(Q+Og.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Og.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Og.sep),"…",Q.slice(-2).join(Og.sep)].join(Og.sep)}build(J){let Q=Z8.of(J),Y=x6.of(J),X=Y.base;this.themeColors=X;let{colors:G,app:Z}=Y;this.themeApp=Z;let q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,V=q.thread.agentMode&&H5(q.thread.agentMode)&&this.randomAd!==null,{threadState:K}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let W=this.getCurrentConfirmation(),H=this.widget.dependencies.replayMode,z=Boolean(H),U=K.items,N=K.mainThread||void 0,O=K.subagentToolsByParentID,M=K.todosList;if(z){let G6={...H.thread,messages:this.replayDisplayedMessages};U=MC(G6).items,N=G6,O={};let o6=pE({messages:this.replayDisplayedMessages});M=Array.isArray(o6)?o6:[]}let L=N?.id,E=N,I=z?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),P=(G6)=>new h81({key:new c2(`preview-message-view-${G6.id}`),items:MC(G6).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:G6,focusNode:new f8({debugLabel:"PreviewFocus"})}),R=this.previewThread,j=R?R.messages.length>2000?new l0({mainAxisSize:"max",children:[new F4({child:new N0}),new b6({padding:j0.all(2),child:new q8({child:new l1({text:new $1("Thread too long for preview",new B1({color:G.mutedForeground,dim:!0}))})})})]}):P(R):I?new u81({agentMode:this.getEffectiveAgentMode()}):new h81({key:L?new c2(`message-view-${L}`):void 0,items:U,subagentToolsByParentID:O,controller:L?this.getMessageScrollController(L):new h3,autofocus:!1,onCopy:z?void 0:this._handleTextCopy.bind(this),thread:E,onMessageEditSubmit:z?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:z?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:z?void 0:this.forkMessage,getAffectedFiles:z?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),y=Math.max(Math.floor(Q.size.height*0.4),12),h=this.getCurrentEphemeralError(),p=this.buildBottomWidget(h,W,G,Y,K,M,y,V?this.randomAd:null,z),g=Q.size.width<40,b=K.mainThread?hU0(K.mainThread):void 0,c=new e41({threadViewState:K.viewState,threadTokenUsage:b,threadID:L??null,thread:K.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:g,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!W,showingEphemeralError:Boolean(K.viewState.state==="active"&&K.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),a=new t41({bashInvocations:this.bashInvocations}),o=[],m=this.getEffectiveAgentMode(),t=this.currentShellModeStatus,W1=qk1(m),F1=!t?m.length+1:0,r=Q.capabilities.animationSupport,s=r==="disabled"?0:r==="slow"?30:60,i=UK(m)?.uiHints?.fasterAnimation?3:1,K1=s>0&&this.agentModePulseSeq>0?new s5({children:[p,new f3({top:0,left:1,right:1,height:1,child:new t_1({color:W1,trigger:this.agentModePulseSeq,fps:s,speed:i,leftOffset:F1})})]}):p;o.push(new F4({child:j}),a);let j1=new s5({children:[new l0({mainAxisSize:"min",children:[V?new O_1({ad:this.randomAd,onButtonClick:async()=>{let G6=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (Z91(),G91)).then(({recordAdEvent:o6})=>{let h4=this.widget.dependencies.worker.thread,t4=h4.messages[h4.messages.length-1];o6("clicked",{adId:G6.id,advertiserId:G6.advertiserId,threadId:h4.id,messageId:t4?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:G6.metadata?.matchType,matchedPatterns:G6.metadata?.matchedPatterns,candidateAdPoolCount:G6.metadata?.candidateAdPoolCount,clientRegion:G6.metadata?.clientRegion})});try{await pJ(G6.shortDestinationUrl)}catch(o6){let t4=M9.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:t4,url:G6.shortDestinationUrl}})}}}):new N0({height:0}),new J6({constraints:new p6(0,Q.size.width,0,y),child:K1})]}),V?new f3({top:0,left:0,right:0,child:new u$6({userHeight:this.bottomGridUserHeight,maxHeight:y,onInitializeHeight:(G6)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(G6,y)})},onDrag:(G6)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(G6.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let o6=Math.floor(G6.localPosition.y)-this.bottomGridDragStartY,h4=Math.max(4,this.bottomGridDragStartHeight-o6),t4=Math.min(h4,y),d5=Math.floor(t4);if(this.bottomGridUserHeight!==d5)this.setState(()=>{this.bottomGridUserHeight=d5})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new N0({height:0})]});o.push(j1,new N0({height:1,child:new b6({padding:j0.horizontal(1),child:c})}));let e=new l0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:o}),y1=z?new s5({children:[e,new f3({top:0,left:0,child:new Qk1})]}):e,R1=new l8(()=>{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.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return v.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.markLastUserMessageAsInterrupted().catch((o6)=>{v.error("Failed to mark message as interrupted:",o6)}),this.cancelStreamingMessage().catch((o6)=>{v.error("Failed to cancel streaming message:",o6)}),"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"}),D0=new l8(()=>{return this.onExitPressed(),"handled"}),T1=new l8(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),n1=new l8(()=>{return DJ.instance.toggleAll(),"handled"}),z1=new l8(()=>{return this.widget.dependencies.configService.getLatest().then((G6)=>{UZ("internal.showCost",!(G6.settings["internal.showCost"]??!0))}),"handled"}),Q1=new l8(()=>{return M9.instance.toggleFrameStatsOverlay(),"handled"}),O1=new l8(()=>{return M9.instance.tuiInstance.getScreen().markForRefresh(),U9.instance.requestFrame(),"handled"}),M1=new l8(()=>{return this.toggleAgentMode(),"handled"}),w1=new l8(()=>{let o6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:h4}=this.widget.dependencies,t4=h4.mainThread?.id;return t4?this.getMessageScrollController(t4):null})();if(o6){let h4=Math.max(Math.floor(Q.size.height*0.4),10),t4=Q.size.height-h4;o6.animatePageUp(t4,100)}return"handled"}),L1=new l8(()=>{let o6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:h4}=this.widget.dependencies,t4=h4.mainThread?.id;return t4?this.getMessageScrollController(t4):null})();if(o6){let h4=Math.max(Math.floor(Q.size.height*0.4),10),t4=Q.size.height-h4;o6.animatePageDown(t4,100)}return"handled"}),u1=new l8(()=>{let o6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:h4}=this.widget.dependencies,t4=h4.mainThread?.id;return t4?this.getMessageScrollController(t4):null})();if(o6)o6.animateTo(0,100);return"handled"}),v1=new l8(()=>{let o6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:h4}=this.widget.dependencies,t4=h4.mainThread?.id;return t4?this.getMessageScrollController(t4):null})();if(o6)o6.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),a1=new l8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:G6}=this.widget.dependencies;if(!G6.mainThread?.messages.some((h4)=>h4.role==="user"||mE(h4)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),$0=new l8((G6)=>{if(G6.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),Q0=new l8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return n41().then(async(G6)=>{if(G6)try{this.handleInsertImage(G6)}finally{try{let{unlink:o6}=await import("node:fs/promises");await o6(G6)}catch{}}}),"handled"}),A0=new Map([[V4.ctrl("c"),new lu],[V4.ctrl("l"),new ou],[V4.ctrl("o"),new h41],[V4.ctrl("v"),new du],[V4.alt("s"),new GC],[V4.ctrl("s"),new GC],[V4.alt("p"),new ru],[V4.ctrl("r"),new nu],[V4.alt("d"),new au],[V4.ctrl("t"),new su],[V4.key("PageUp"),new y41],[V4.key("PageDown"),new v41],[V4.key("Home"),new x41],[V4.key("End"),new f41],[V4.key("Escape"),new cu],[V4.ctrl("p"),new ZC("previous")],[V4.ctrl("n"),new ZC("next")],[V4.key("Tab"),new tu]]);if(!u7())A0.set(V4.key("ArrowUp"),new tu);if(!1)A0.set(V4.alt("c"),new iu);let z6=new l8(()=>{if(this.isShowingStandaloneThreadPicker)return"handled";return this.showCommandPalette(),"handled"}),B4=new l8(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),f4=new Map([[cu,R1],[ou,O1],[GC,M1],[h41,z6],[du,Q0],[iu,T1],[nu,n1],[au,z1],[ru,Q1],[su,B4],[lu,D0],[y41,w1],[v41,L1],[x41,u1],[f41,v1],[tu,a1],[ZC,$0]]),V8=[y1];if(this.isShowingConsoleOverlay)V8.push(new y_1);if(this.isShowingHelp){let G6=this.getPaletteCommands().getAllCommands();V8.push(new f_1({commands:G6}))}if(this.adActionModal)V8.push(new M_1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(G6)=>{let o6=this.adActionModal.url;if(G6==="copy")try{await M9.instance.tuiInstance.clipboard.writeText(o6),this.setState(()=>{this.displayMessage=new mY("Link copied to clipboard")})}catch(h4){v.error("Failed to copy to clipboard",{error:h4}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:G6}=this.widget.dependencies;V8.push(new e_1({servers:this.pendingMCPServers,onAlwaysTrust:G6.trustAlways.bind(G6),onTrustOnce:G6.trustOnce.bind(G6),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:G6.deny.bind(G6)}))}if(this.isShowingFileChangesOverlay)V8.push(new LS1({threadData:K}));if(this.isShowingCostBreakdownOverlay&&K.mainThread)V8.push(new v_1({thread:K.mainThread}));if(this.isShowingConfirmationOverlay)V8.push(new __1({details:this.confirmationOverlayContent}));let M0=this.getCommandPaletteContext();if(M0&&this.isShowingPalette)V8.push(new q8({child:new J6({constraints:p6.loose(80,20),child:new S_1({commandContext:M0,mainThread:K.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette})})}));if(this.isShowingIdePicker)V8.push(new b_1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));if(this.isShowingStandaloneThreadPicker){let G6=p0.file(process.cwd()),o6=W6(G6);V8.push(new q8({child:new J6({constraints:p6.loose(80,20),child:new Jg({threads:this.threadsForPicker,title:"Continue Thread",onSelect:this.handleStandaloneThreadSelect,onDismiss:this.dismissStandaloneThreadPicker,previewController:this.threadPreviewController,isLoading:this.isLoadingThreads,currentWorkspaceURI:o6,filterByWorkspace:this.filterThreadPickerByWorkspace,threadViewStates:this.widget.dependencies.workerController.threadViewStates})})}))}let x0=new s5({children:V8});if(this.isShowingJetBrainsInstaller)return new lL({child:new uQ({actions:f4,child:new Dq({shortcuts:A0,debugLabel:"jetbrains-installer-shortcuts",child:new s_1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let d6=new aB({onError:(G6)=>{this.showErrorMessage(G6.message)},child:x0});return new lL({child:new uQ({actions:f4,child:new Dq({shortcuts:A0,debugLabel:"main-app-shortcuts",child:d6})})})}buildScrollableTodoList(J,Q,Y){return new h$6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Y})}buildBottomWidget(J,Q,Y,X,G,Z,q,V,K){if(J)return new x_1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new k_1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new Jk1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let W=X.app,H=s41(X),z=this.isInRestrictedFreeMode(),U=new qA({key:this.textFieldKey,controller:this.textController,triggers:K?[]:[new QN],completionBuilder:K?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:K?void 0:this.onTextSubmitted,theme:Y,placeholder:K?"Press Ctrl+C to exit":z?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!z&&!this.isShowingStandaloneThreadPicker,shellPromptRules:H,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker,clipboard:M9.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage}),N=G.mainThread?.queuedMessages??[],O=Array.isArray(Z)&&Z.length>0,M=Array.isArray(N)&&N.length>0,L=G.mainThread?.agentMode==="plan"&&YC(G.mainThread),E,I;if(L){if(E=new dC1(new b81({thread:G.mainThread,onExecute:async()=>{let b=this.getCommandPaletteContext();if(b)await this.getPaletteCommands().execute("execute-plan",b,void 0,new AbortController)},onEdit:async()=>{try{let b=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:c}=await this.widget.dependencies.planFileManager.ensureSync(G.mainThread.id);M9.instance.tuiInstance.suspend();let{execSync:a}=await import("child_process");a(`${b} "${c}"`,{stdio:"inherit"}),M9.instance.tuiInstance.resume()}catch(b){v.error("Failed to edit plan",b),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:X}),{clipBehavior:"antiAlias"}),M)I=new X91({queuedMessages:N});else if(O)I=this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!z,X)}else E=M?new X91({queuedMessages:N}):void 0,I=O?this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!z,X):void 0;let P=[],R=this.currentShellModeStatus;if(R)P.push({text:new $1(R==="hidden"?"shell mode (incognito)":"shell mode",new B1({color:R==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left"});if(!R&&this.cachedVisibleModes.length>1){let b=this.previewThread,c=b?b.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),a=qk1(c);if(b)P.push({text:new $1(c,new B1({color:a})),position:"top-left",offsetY:0});else{let m=Ab(c,this.cachedVisibleModes)!==c,t=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,W1=OV(t.thread)===0,r=z||!this.hasToggledAgentMode&&m&&W1?new $1("",void 0,[new $1(c,new B1({color:a})),new $1(" (click or ",new B1({color:Y.foreground,dim:!0})),new $1("Ctrl+S",new B1({color:W.keybind})),new $1(" to switch)",new B1({color:Y.foreground,dim:!0}))]):new $1(c,new B1({color:a}));P.push({text:r,position:"top-left",offsetY:0,onClick:W1?this.toggleAgentMode:void 0})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let b=this.connectedClientsStatus,c=b.mode||"disconnected",a=!!b.errorMessage,o=b.clientID||"unknown",m,t;if(a)m="●",t=A1.red;else if(c==="presence")m="○",t=A1.yellow;else if(c==="connected"&&b.connected)m="●",t=A1.green;else m="○",t=A1.yellow;let W1=this.connectedClientsStatusExpanded?`${o} ${m}`:m;P.push({text:new $1(W1,new B1({color:t})),position:"top-right",offsetX:-2,offsetY:0,onClick:this.toggleConnectedClientsStatus})}let j=K?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:G.mainThread?.env?.initial.trees?.[0]?.uri,y;if(j)y=p0.parse(j).fsPath;else y=process.cwd();let h=this.toHomeRelative(y),p=this.shorten(h),g=!K&&this.currentGitBranch?`${p} (${this.currentGitBranch})`:p;return P.push({text:new $1(g,new B1({color:Y.foreground,dim:!0})),position:"bottom-right"}),new HS1({leftChild:new F4({child:U}),rightChild1:E,rightChild2:I,maxHeight:q,overlayTexts:P,borderColor:z||!this.isTextfieldAndAutocompleteFocused?A1.index(8):void 0,hasBanner:V!==null,userHeight:this.bottomGridUserHeight,onInitializeHeight:(b)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(b,q)})},onDrag:(b)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(b.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let c=Math.floor(b.localPosition.y)-this.bottomGridDragStartY,a=Math.max(4,this.bottomGridDragStartHeight-c),o=Math.min(a,q),m=Math.floor(o);if(this.bottomGridUserHeight!==m)this.setState(()=>{this.bottomGridUserHeight=m})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:V===null})}}async function Vk1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)M9.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let X=()=>null,Z=!1,q=new Jz(Z,1000,J.inspectorPort),V=J.features?.find((L)=>L.name==="amp-connect")?.enabled??!1,K=new N_1({threadService:J.threadService,worker:J.worker,builder:(L,E,I,P,R)=>{if(X=R,J.threadDependencies&&V)CC1(J.threadDependencies,J.configService,R,P,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((p)=>{v.error("Failed to start automatic presence:",p)});let j=R(),y=j.thread.id,h={...J,worker:j,threadID:y};return new x$6({...h,threadState:E,workerController:I,switchWorker:P,getCurrentWorker:R})}}),W=new NS1({configService:J.configService,child:K}),H=new FS1({configService:J.configService,child:W}),z=new JS1(H),U=new x6({data:VC.fromBaseTheme(RG.default()),child:z});try{await MC1(U,{onRootElementMounted:(L)=>{if(v.info("TUI input ready for user interaction"),Z)q.start(L)}})}finally{if(Z)q.stop();if(J.threadDependencies&&V){let{stopGlobalSession:L}=await Promise.resolve().then(() => (SC1(),h76));L()}}let O=X()?.thread.id||J.threadID,M=await J.threadService.get(O);if(M&&M.messages.length>0){let L=`${J.ampURL.replace(/\/$/,"")}/threads/${O}`;G36(M,L,J.stdout)}}function qk1(J){return J==="smart"?A1.rgb(145,119,199):J==="rush"?A1.rgb(228,180,2):H5(J)?A1.rgb(0,184,255):J==="plan"?A1.rgb(153,102,255):_D8(J)}class h$6 extends e0{props;constructor(J){super();this.props=J}createState(){return new b$6}}class b$6 extends t0{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 Z4({crossAxisAlignment:"stretch",children:[new F4({child:new O7({controller:Y,autofocus:!1,child:new D_1({todos:Q})})}),new JX({controller:Y,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:G,offset:Z}=Y,q=this.viewportHeight,V=G+q;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(q,1),scrollOffset:Math.max(Z,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(X,G=0)=>{if(X&&"size"in X&&"children"in X){let Z=X.children||[];for(let q of Z){if(q&&"size"in q){let K=q.size;if(typeof K?.height==="number"&&K.height>0)return K.height}let V=Q(q,G+1);if(V>0)return V}}return 0},Y=Q(J);if(Y>0)return Y;if("size"in J){let X=J.size;if(typeof X?.height==="number"&&X.height>0)return X.height}return this.viewportHeight}}class u$6 extends j6{props;constructor(J){super();this.props=J}build(J){return new R8({child:new N0({height:1}),cursor:f9.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 _D8(J){let Q=0;for(let G=0;G<J.length;G++){let Z=J.charCodeAt(G);Q=(Q<<5)-Q+Z,Q=Q&Q}let Y=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Y.length;return A1.index(Y[X])}OC1();try{if(process.platform==="win32")await Promise.resolve().then(() => U6(bC(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){hG.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
5285
- `)}var hy1=fy1.join(Fz0||fy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function sA8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),q=Y||"Warning",V=!1;J.warn(Z,{name:q,code:X})}}function Eq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")UZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")UZ("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")UZ("model.sonnet",Q.useSonnet)}async function uy1(J){try{await aA8(fy1.dirname(hy1),{recursive:!0}),await rA8(hy1,J,"utf-8")}catch(Q){v.debug("Failed to save last thread ID",Q)}}async function tA8(){try{return(await Kq6(hy1,"utf-8")).trim()}catch(J){return null}}var Zq6=[{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??wG,description:`Custom settings file path (overrides the default location ${wG})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(v).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${IR1})`},{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:u7(),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:VR.SMART.key,description:`Set the agent mode (${zG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:zG().map((J)=>J.mode)}],qq6=(J)=>("deprecated"in J)&&J.deprecated===!0,eA8=(J)=>("hidden"in J)&&J.hidden===!0,Jw8=(J)=>("default"in J),Qw8=(J)=>("default"in J)?J.default:void 0;function Yw8(J,Q){let Y=Q.args[0],X=Q.commands.map((Z)=>Z.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let Z=X.filter((V)=>Y.includes(V)||V.includes(Y)),q="Run amp --help for a list of available commands.";if(Z.length>0)q=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new A8(AG.unknownCommand(Y),1,q)}}var Wq6=null;function tW5(){return Wq6}function mg(J){return{...J,getThreadEnvironment:k61,vfs:kD0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new mh(J.fileSystem),generateThreadTitle:j16,deleteThread:(Q)=>J.threadService.delete(Q)}}var gy1=p0.file(oA8.homedir()),Hq6=process.env.XDG_CONFIG_HOME?p0.file(process.env.XDG_CONFIG_HOME):Q6.joinPath(gy1,".config");async function Iq(J,Q){rU0("0.0.1763582484-gdd165b");let Y=lE1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([p0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:gy1,userConfigDir:Hq6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (Z91(),G91));X(Y);let G=await Y.getLatest();v.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let Z=new $L({configService:Y}),q=new Map,V=()=>q.clear(),K=new MP1(Y,J.settings.getWorkspaceRootPath()),W=q16({configService:Y,toolServices:Z,trustStore:K,createOAuthProvider:async(a)=>{let o=q.get(a);if(o)return v.debug("Reusing existing OAuth provider for server",{serverName:a}),o;v.debug("Creating OAuth provider for server",{serverName:a});let m=(async()=>{let t=new AL(J.secrets),W1=await t.getClientInfo(a),F1=new $P1({storage:t,serverName:a,clientId:W1?.clientId,clientSecret:W1?.clientSecret,scopes:W1?.scopes});return v.debug("OAuth provider created",{serverName:a,hasManualClientId:!!W1?.clientId,willUseDCR:!W1?.clientId}),F1})();return q.set(a,m),m}}),H=i11({configService:Y,toolServices:Z,filesystem:z5,spawn:NL}),z=W.initialized.catch((a)=>{v.warn("MCP service initialization failed, continuing anyway:",{error:a})}),U=H.initialized.catch((a)=>{v.warn("Toolbox initialization failed, continuing anyway:",{error:a})}),N=Promise.all([z,U]).then(()=>{});if(Q.jetbrains)cE("JetBrains");else if(Q.ide&&u56())cE("VS Code");else if(Q.ide&&g56())cE("Neovim");if(J.executeMode)oU0(!0);let O,M=F7.status.pipe(s0((a)=>Boolean(a.connected&&a.authenticated)),y4()).subscribe((a)=>{if(a){if(!O)O=Z.registerTool(NT)}else O?.dispose(),O=void 0}),L;if(!J.executeMode)L=new d61(process.cwd(),{},!0);else L=new class extends d61{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(p5.write(`No API key found. Starting login flow...
5285
+ `)}var hy1=fy1.join(Fz0||fy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function sA8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),q=Y||"Warning",V=!1;J.warn(Z,{name:q,code:X})}}function Eq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")UZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")UZ("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")UZ("model.sonnet",Q.useSonnet)}async function uy1(J){try{await aA8(fy1.dirname(hy1),{recursive:!0}),await rA8(hy1,J,"utf-8")}catch(Q){v.debug("Failed to save last thread ID",Q)}}async function tA8(){try{return(await Kq6(hy1,"utf-8")).trim()}catch(J){return null}}var Zq6=[{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??wG,description:`Custom settings file path (overrides the default location ${wG})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(v).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${IR1})`},{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:u7(),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:VR.SMART.key,description:`Set the agent mode (${zG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:zG().map((J)=>J.mode)}],qq6=(J)=>("deprecated"in J)&&J.deprecated===!0,eA8=(J)=>("hidden"in J)&&J.hidden===!0,Jw8=(J)=>("default"in J),Qw8=(J)=>("default"in J)?J.default:void 0;function Yw8(J,Q){let Y=Q.args[0],X=Q.commands.map((Z)=>Z.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let Z=X.filter((V)=>Y.includes(V)||V.includes(Y)),q="Run amp --help for a list of available commands.";if(Z.length>0)q=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new A8(AG.unknownCommand(Y),1,q)}}var Wq6=null;function tW5(){return Wq6}function mg(J){return{...J,getThreadEnvironment:k61,vfs:kD0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new mh(J.fileSystem),generateThreadTitle:j16,deleteThread:(Q)=>J.threadService.delete(Q)}}var gy1=p0.file(oA8.homedir()),Hq6=process.env.XDG_CONFIG_HOME?p0.file(process.env.XDG_CONFIG_HOME):Q6.joinPath(gy1,".config");async function Iq(J,Q){rU0("0.0.1763586382-g73297f");let Y=lE1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([p0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:gy1,userConfigDir:Hq6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (Z91(),G91));X(Y);let G=await Y.getLatest();v.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let Z=new $L({configService:Y}),q=new Map,V=()=>q.clear(),K=new MP1(Y,J.settings.getWorkspaceRootPath()),W=q16({configService:Y,toolServices:Z,trustStore:K,createOAuthProvider:async(a)=>{let o=q.get(a);if(o)return v.debug("Reusing existing OAuth provider for server",{serverName:a}),o;v.debug("Creating OAuth provider for server",{serverName:a});let m=(async()=>{let t=new AL(J.secrets),W1=await t.getClientInfo(a),F1=new $P1({storage:t,serverName:a,clientId:W1?.clientId,clientSecret:W1?.clientSecret,scopes:W1?.scopes});return v.debug("OAuth provider created",{serverName:a,hasManualClientId:!!W1?.clientId,willUseDCR:!W1?.clientId}),F1})();return q.set(a,m),m}}),H=i11({configService:Y,toolServices:Z,filesystem:z5,spawn:NL}),z=W.initialized.catch((a)=>{v.warn("MCP service initialization failed, continuing anyway:",{error:a})}),U=H.initialized.catch((a)=>{v.warn("Toolbox initialization failed, continuing anyway:",{error:a})}),N=Promise.all([z,U]).then(()=>{});if(Q.jetbrains)cE("JetBrains");else if(Q.ide&&u56())cE("VS Code");else if(Q.ide&&g56())cE("Neovim");if(J.executeMode)oU0(!0);let O,M=F7.status.pipe(s0((a)=>Boolean(a.connected&&a.authenticated)),y4()).subscribe((a)=>{if(a){if(!O)O=Z.registerTool(NT)}else O?.dispose(),O=void 0}),L;if(!J.executeMode)L=new d61(process.cwd(),{},!0);else L=new class extends d61{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(p5.write(`No API key found. Starting login flow...
5286
5286
  `),!await $w8(J))await xL(),process.exit(1)}let E=await w16({isDevelopment:!1}),I=new PP1(E,Y),P=new wP1(E,{lazy:!0}),R=new LP1(I,(a,o)=>{let m=q3.get(a);if(m)m.handle(o).catch((t)=>{v.error("Failed to apply artifact delta",t)})}),j=Q.notifications!==void 0?Q.notifications:!J.executeMode,y=h16({playNotificationSound:async(a)=>{if(j){f16(a);let o=NC1(),m=DC1();if((!o||m)&&G.settings["notifications.system.enabled"]!==!1){if(a==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(a==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:I,configService:Y});v.info("Starting Amp background services");let h=k16({threadService:I,threadHistoryService:P,configService:Y,isExtensionDevelopment:!1}),p;F7.status.subscribe((a)=>{p=a});let g=new aX1({workspaceRoots:[p0.file(process.cwd())],getCurrentFile:()=>{if(!p?.openFile)return;try{return p0.parse(p.openFile)}catch(a){v.warn("Failed to parse current file URI",{uri:p.openFile,error:a});return}},getOpenFiles:()=>{if(!p?.visibleFiles?.length)return[];let a=p.openFile;return p.visibleFiles.filter((o)=>o!==a).map((o)=>{try{return p0.parse(o)}catch(m){return v.warn("Failed to parse visible file URI",{uri:o,error:m}),null}}).filter((o)=>o!==null)}}),b=new LC1,c={codebaseContextService:g,configService:Y,toolServices:Z,mcpService:W,trustStore:K,threadService:I,threadHistoryService:P,threadSyncService:h,planFileManager:R,threadStorage:E,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:L,notificationService:y,backgroundInit:N,fileSystem:Q.jetbrains||Q.ide?N16:z5,terminal:b};return{...c,async asyncDispose(){await c.mcpService.dispose(),V(),await c.threadService.asyncDispose(),c.configService.unsubscribe(),c.toolServices.dispose(),c.fuzzyServer.dispose(),c.threadSyncService.dispose(),c.settingsStorage[Symbol.dispose](),M.unsubscribe(),O?.dispose()}}}async function $w8(J){if(!J.executeMode){if(!await aR1("Would you like to log in to Amp? [(y)es, (n)o]: "))return p5.write(`Login cancelled. Run the command again to retry.
5287
5287
  `),!1}return await zq6(J)}async function zq6(J){let Q=nA8(32).toString("hex"),Y=await nR1(J.ampURL,Q),X=new AbortController;try{await pJ(Y,X.signal)}catch(Z){v.error("Error opening browser",{error:Z})}let G=await nR1(J.ampURL,Q,!1);p5.write(`If your browser does not open automatically, visit:
5288
5288
 
@@ -5292,15 +5292,15 @@ ${C4.blue.bold(G)}
5292
5292
  Login successful! You can now use the Amp CLI.
5293
5293
  `),!0}catch(Z){return v.error("Login failed",{error:Z}),hG.write(`
5294
5294
  Login failed: ${Z instanceof Error?Z.message:String(Z)}
5295
- `),!1}}function Xw8(){let J=new EL().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)gR(),process.exit(0);let z=H.originalError??H;y96(z)}),J.option("-V, --version","Print the version number and exit",()=>{p5.write(`0.0.1763582484-gdd165b (released 2025-11-19T20:06:25.191Z)
5295
+ `),!1}}function Xw8(){let J=new EL().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)gR(),process.exit(0);let z=H.originalError??H;y96(z)}),J.option("-V, --version","Print the version number and exit",()=>{p5.write(`0.0.1763586382-g73297f (released 2025-11-19T21:11:26.408Z)
5296
5296
  `),process.exit(0)}),J.addHelpText("after",f56()),J.configureHelp({formatHelp:h56}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await nQ(U);await Vw8(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await nQ(U);await qw8(N,await hR1(U,N.settings))});let Q=async(H,z,U)=>{lE1({storage:z.settings,secretStorage:z.secrets,workspaceRoots:J0.of([p0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:gy1,userConfigDir:Hq6});let N={...z,executeMode:!1};await by1(N,{...H,openThreadSwitcher:!0},U)},Y=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await nQ(U);await Vq6(U,N,z)});Y.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await nQ(U);await Bw8(U,N,z)}),Y.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,z,U)=>{let N=U.optsWithGlobals(),O=await nQ(N);if(z.pick)hG.write(`${C4.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
5297
5297
  `);if(z.last||H||O.executeMode)await Uw8(N,O,H,U);else await Q(N,O,U)}),Y.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,U)=>{let N=U.optsWithGlobals(),O=await nQ(N);await Fw8(N,O,H,U)}),Y.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await nQ(U);await Vq6(U,N,z)}),Y.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(H,z,U)=>{let N=U.optsWithGlobals(),O=await nQ(N);await zw8(N,O,H,U,z.support)}),Y.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(H,z,U,N)=>{let O=N.optsWithGlobals(),M=await nQ(O);await Kw8(O,M,H,z,N)}),Y.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(H,z,U)=>{let N=U.optsWithGlobals(),O=await nQ(N);await Ww8(N,O,H,U)}),Y.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(H,z,U)=>{let N=U.optsWithGlobals(),O=await nQ(N);await Hw8(N,O,H,z,U)}),k76(J,async(H,z)=>{let U=await nQ(z);Eq(H,z);let N=await Iq(U,z);return{context:U,mcpService:N.mcpService,toolService:N.toolServices,toolServices:N.toolServices,configService:N.configService,cleanupTerminal:gR,asyncDispose:N.asyncDispose.bind(N),backgroundInit:N.backgroundInit}}),L26(J,async(H)=>{let z=H.optsWithGlobals();return await nQ(z)}),W26(J,async(H)=>{let z=await nQ(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(U)=>{Eq(U,H);let N=await Iq(z,H);return{mcpService:N.mcpService,settings:z.settings,asyncDispose:N.asyncDispose.bind(N)}}}});function G(H,z,U){let O=typeof H.description==="string"?H.description:U===void 0?H.description(!0):H.description(U),M=new CB(z,O),L=Qw8(H);if(L)M.default(L);if(M.hidden=eA8(H)||qq6(H),"choices"in H)M.choices([...H.choices]);return M}for(let H of Zq6)switch(H.type){case"flag":{J.addOption(G(H,`--${H.long}`)),J.addOption(G(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(G(H,`--${H.long}`,!0));break}default:{J.addOption(G(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let Z=new CB("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(Z);let q=new CB("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(q);let V=new CB("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(V);let K=new CB("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(K);let W=new CB("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_CONNECT==="1"){let H=new CB("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return J.action(async(H,z)=>{let U=H,N=await nQ(U);if(Object.keys(U).forEach((O)=>{let M=Zq6.find((L)=>L.name===O);if(M&&qq6(M)&&!Jw8(M))hG.write(C4.yellow(`Warning: '--${O}' flag is deprecated
5298
5298
  `))}),z.args.length>0)Yw8(N,z);await by1(N,U,z)}),Y26(J),J}async function a91(J,Q){let{thread:Y,visibility:X}=Q,G=Y?.id??LZ(),Z=mg(J);if(Y)await J.threadStorage.set(G,Y);let q=await q3.getOrCreateForThread(Z,G),V=await J.threadStorage.get(G);if(Q.agentMode&&!V?.agentMode&&OV(q.thread)===0)await q.handle({type:"agent-mode",mode:Q.agentMode});if(X)await J.threadSyncService.updateThreadMeta(G,Q41(X));let K=J.threadService.observe(G).subscribe(async(W)=>{if(t3(W,"assistant"))await uy1(G),K.unsubscribe()});return await q.resume(),q}async function by1(J,Q,Y){let X=J41(Q);if(X instanceof Error)fG(X.message);let G,Z=null;if(Q.streamJsonInput)G="";else if(typeof Q.execute==="string"){G=Q.execute;let c=(await rR1()).trimEnd();if(c)Z=c}else G=(await rR1()).trimEnd();if(Q.remote&&!J.executeMode)throw new A8("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new A8("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new A8("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new A8("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if((J.executeMode||Q.streamJson)&&H5(Q.mode))throw new A8(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.stats&&!J.executeMode)throw new A8("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 A8("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&&G===""&&!Q.streamJsonInput)throw new A8("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"
5299
5299
  Or pipe via stdin: echo "your message" | amp --execute`);Eq(Y,Q);let q=await Iq(J,Q);if(J.executeMode||Q.threadId)await q.backgroundInit;Wq6=q;let V=mg(q),K=async(c)=>{let a=await Kq6(c,"utf-8"),o=JSON.parse(a);if(!AZ(o.id))throw new A8(AG.invalidThreadId);return a91(q,{visibility:X,agentMode:Q.mode,thread:o})},W=async(c)=>{if(!AZ(c))throw new A8(AG.invalidThreadId);try{let[o,m]=await Promise.all([L5.getThreadLinkInfo({thread:c},{config:q.configService}),L5.getUserInfo({},{config:q.configService})]);if(o.ok&&m.ok){let t=o.result.creatorUserID,W1=m.result.id;if(t&&t!==W1&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new A8(`Cannot resume thread created by another user.
5300
5300
 
5301
5301
  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(o){if(o instanceof A8)throw o;v.warn("Failed to validate thread ownership in CLI, allowing to open",{error:o})}let a=await q.threadService.get(c)??void 0;return v.info(`[fetchAndStartThread] Loaded thread ${c}, agentMode: ${a?.agentMode??"undefined"}`),a91(q,{visibility:X,agentMode:a?void 0:Q.mode,thread:a})},H=async()=>{try{if(Q.threadId)return W(Q.threadId);else return a91(q,{visibility:X})}catch(c){if(c instanceof A8)throw c;throw await zu(c,Q.threadId),Error("handleError should have called process.exit()")}},z=async()=>{return a91(q,{visibility:X})};if(Q.format==="jsonl")hG.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
5302
- `),await xL(),process.exit(1);if(J.executeMode&&Q.remote)await A26(G,Z,q.configService),await q.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)F26(q.mcpService,J.settings),await a96(U,U.threadID,G,Z,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let N=!1,O=!1;if(Q.jetbrains||Q.ide){await ef0();let c=BT({jetbrainsOnly:Q.jetbrains});if(c.length===0){if(Q.jetbrains)O=!await q.configService.get("jetbrains.skipInstall")}else if(c.length===1){let a=c[0];if(a)F7.selectConfig(a)}else N=!0}let M=t61("0.0.1763582484-gdd165b",q.settingsStorage),L=new e01(q.threadStorage),E=J0.of([p0.file(process.cwd())]),I=ZG1(void 0,E),P=new e61(q.mcpService,J.settings.getWorkspaceRootPath());if(G)U.handle({type:"user:message",message:{content:[{type:"text",text:G}]}});let R=(async()=>{try{let c=await L5.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)});if(c.ok)return v.info("User free tier status:",c),c.result}catch(c){v.error("Failed to fetch free tier status:",c)}})(),j=(async()=>{try{let c=await L5.getUserInfo({},{config:q.configService});if(c.ok)return c.result}catch(c){v.debug("Failed to fetch user workspace info:",c)}})(),[y,h]=await Promise.all([R,j]),p=h?.email,g=p&&(p.endsWith("@sourcegraph.com")||p.endsWith("@ampcode.com")||p==="auth-bypass-user@example.com");if(g)q.toolServices.registerTool(x16);let b=await P26();v.info("Loaded session state:",b),await Vk1({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new f61,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadSyncService:q.threadSyncService,planFileManager:q.planFileManager,threadID:U.threadID,threadFuzzyIndexer:L,worker:U,workerDeps:V,configService:q.configService,internalAPIClient:L5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:F7,connectedClientsService:new s11,commandRegistry:I,mcpService:q.mcpService,mcpTrustHandler:P,showJetBrainsInstaller:O,showIdePicker:N,openThreadSwitcher:Q.openThreadSwitcher,updateService:M,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:b,freeTierStatus:y,workspace:h?.team??null,features:h?.features??[],isDogfooding:g||!1,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function nQ(J){if(J.interactive)hG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5303
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await L56({...J,workspaceTrust:{current:!0,changes:h_},getHook:process.env.AMP_URL?(Z,q)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let Z=await H26(J.mcpConfig);X=z26(X,Z)}let G=await X.get("url","global");if(!G)G=qY;if(!LF(G))v.info("Targeting custom Amp server",{ampURL:G});return X=FF0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:w26(await hR1(J,X))}}function Gw8(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let Z=X.slice(2).replace(/-([a-z])/g,(V,K)=>K.toUpperCase()),q=J[Y+1];if(q&&!q.startsWith("--"))Q[Z]=q,Y++}}return Q}async function Zw8(){let J=Gw8(process.argv);if(I96({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),sA8(v),v.info("Starting Amp CLI.",{version:"0.0.1763582484-gdd165b",buildTimestamp:"2025-11-19T20:06:25.191Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new A8(AG.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Xw8().parseAsync(process.argv)}Ow1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Zw8().catch(zu)});async function qw8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),p5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5302
+ `),await xL(),process.exit(1);if(J.executeMode&&Q.remote)await A26(G,Z,q.configService),await q.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)F26(q.mcpService,J.settings),await a96(U,U.threadID,G,Z,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let N=!1,O=!1;if(Q.jetbrains||Q.ide){await ef0();let c=BT({jetbrainsOnly:Q.jetbrains});if(c.length===0){if(Q.jetbrains)O=!await q.configService.get("jetbrains.skipInstall")}else if(c.length===1){let a=c[0];if(a)F7.selectConfig(a)}else N=!0}let M=t61("0.0.1763586382-g73297f",q.settingsStorage),L=new e01(q.threadStorage),E=J0.of([p0.file(process.cwd())]),I=ZG1(void 0,E),P=new e61(q.mcpService,J.settings.getWorkspaceRootPath());if(G)U.handle({type:"user:message",message:{content:[{type:"text",text:G}]}});let R=(async()=>{try{let c=await L5.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)});if(c.ok)return v.info("User free tier status:",c),c.result}catch(c){v.error("Failed to fetch free tier status:",c)}})(),j=(async()=>{try{let c=await L5.getUserInfo({},{config:q.configService});if(c.ok)return c.result}catch(c){v.debug("Failed to fetch user workspace info:",c)}})(),[y,h]=await Promise.all([R,j]),p=h?.email,g=p&&(p.endsWith("@sourcegraph.com")||p.endsWith("@ampcode.com")||p==="auth-bypass-user@example.com");if(g)q.toolServices.registerTool(x16);let b=await P26();v.info("Loaded session state:",b),await Vk1({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new f61,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadSyncService:q.threadSyncService,planFileManager:q.planFileManager,threadID:U.threadID,threadFuzzyIndexer:L,worker:U,workerDeps:V,configService:q.configService,internalAPIClient:L5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:F7,connectedClientsService:new s11,commandRegistry:I,mcpService:q.mcpService,mcpTrustHandler:P,showJetBrainsInstaller:O,showIdePicker:N,openThreadSwitcher:Q.openThreadSwitcher,updateService:M,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:b,freeTierStatus:y,workspace:h?.team??null,features:h?.features??[],isDogfooding:g||!1,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function nQ(J){if(J.interactive)hG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5303
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await L56({...J,workspaceTrust:{current:!0,changes:h_},getHook:process.env.AMP_URL?(Z,q)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let Z=await H26(J.mcpConfig);X=z26(X,Z)}let G=await X.get("url","global");if(!G)G=qY;if(!LF(G))v.info("Targeting custom Amp server",{ampURL:G});return X=FF0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:w26(await hR1(J,X))}}function Gw8(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let Z=X.slice(2).replace(/-([a-z])/g,(V,K)=>K.toUpperCase()),q=J[Y+1];if(q&&!q.startsWith("--"))Q[Z]=q,Y++}}return Q}async function Zw8(){let J=Gw8(process.argv);if(I96({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),sA8(v),v.info("Starting Amp CLI.",{version:"0.0.1763586382-g73297f",buildTimestamp:"2025-11-19T21:11:26.408Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new A8(AG.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Xw8().parseAsync(process.argv)}Ow1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Zw8().catch(zu)});async function qw8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),p5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5304
5304
  `);else if(!LF(J.ampURL))p5.write(`Logging in to ${new URL(J.ampURL).hostname}
5305
5305
  `);let Y=process.env.AMP_API_KEY;if(Y)p5.write(`API key found in environment variable, storing...
5306
5306
  `),await Q.set("apiKey",Y,J.ampURL),p5.write(`API key successfully stored.
@@ -5313,7 +5313,7 @@ This thread belongs to a different user and cannot be continued for security rea
5313
5313
  `);else p5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
5314
5314
  `);process.exit(0)}async function Kw8(J,Q,Y,X,G){Eq(G,J);let Z=await Iq(Q,J);try{let q=r91(Y);if(!q)o91(Y);let V=q,K=X.trim();if(K.length===0)fG("Thread name cannot be empty");if(K.length>256)fG("Thread name cannot exceed 256 characters");if(!(await uC(V,Z)).messages.length)fG("Cannot rename an empty thread.");let H=mg(Z);await(await q3.getOrCreateForThread(H,V)).handle({type:"title",value:K}),v.info("GOT HERE"),await Z.threadSyncService.sync(),v.info("GOT THERE"),p5.write(C4.green(`✓ Thread ${V} renamed to "${K}"
5315
5315
  `)),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose();let V=`Failed to rename thread: ${q instanceof Error?q.message:String(q)}`;fG(V)}}async function Ww8(J,Q,Y,X){Eq(X,J);let G=await Iq(Q,J);try{let Z=r91(Y);if(!Z)o91(Y);let V=await uC(Z,G),K=ve(V);p5.write(K+`
5316
- `),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let q=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;fG(q)}}async function Hw8(J,Q,Y,X,G){Eq(G,J);let Z=await Iq(Q,J);try{let q=await my1(Y),V=await uC(q,Z),K=X.typing!==!1,W=parseInt(X.wpm||"120",10),H=parseInt(X.messageDelay||"1000",10),z=parseInt(X.toolProgressDelay||"800",10),U=parseInt(X.exitDelay||"3",10)*1000,N=X.indicator!==!1,O=mg(Z),M=V.id;await Z.threadStorage.set(M,V);let L=await q3.getOrCreateForThread(O,M);await L.resume();let E=t01.fromWorker(L),I=new e01(Z.threadStorage),P=J0.of([p0.file(process.cwd())]),R=ZG1(void 0,P),j=new e61(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=t61("0.0.1763582484-gdd165b",Z.settingsStorage);await Vk1({codebaseContextService:Z.codebaseContextService,stdout:process.stdout,history:new f61,fuzzyServer:Z.fuzzyServer,settingsStorage:Z.settingsStorage,threadService:Z.threadService,threadHistoryService:Z.threadHistoryService,threadSyncService:Z.threadSyncService,planFileManager:Z.planFileManager,threadID:M,threadFuzzyIndexer:I,worker:E,workerDeps:O,configService:Z.configService,internalAPIClient:L5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:F7,connectedClientsService:new s11,commandRegistry:R,mcpService:Z.mcpService,mcpTrustHandler:j,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:V,typingEnabled:K,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:N}}),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),await zu(q,Y)}}async function zw8(J,Q,Y,X,G){Eq(X,J);let Z=await Iq(Q,J);try{let q=r91(Y);if(!q)o91(Y);let V=q,K=await L5.getUserInfo({},{config:Z.configService}),W=K.ok?K.result:null,H=J41(J,W);if(!H&&!G)fG("Must specify either --visibility or --support");if(H&&G)fG("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)fG(H.message);if(H)await Z.threadSyncService.updateThreadMeta(V,Q41(H)),p5.write(C4.green("✓ ")+`Thread ${V} visibility changed to ${H}.
5316
+ `),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let q=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;fG(q)}}async function Hw8(J,Q,Y,X,G){Eq(G,J);let Z=await Iq(Q,J);try{let q=await my1(Y),V=await uC(q,Z),K=X.typing!==!1,W=parseInt(X.wpm||"120",10),H=parseInt(X.messageDelay||"1000",10),z=parseInt(X.toolProgressDelay||"800",10),U=parseInt(X.exitDelay||"3",10)*1000,N=X.indicator!==!1,O=mg(Z),M=V.id;await Z.threadStorage.set(M,V);let L=await q3.getOrCreateForThread(O,M);await L.resume();let E=t01.fromWorker(L),I=new e01(Z.threadStorage),P=J0.of([p0.file(process.cwd())]),R=ZG1(void 0,P),j=new e61(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=t61("0.0.1763586382-g73297f",Z.settingsStorage);await Vk1({codebaseContextService:Z.codebaseContextService,stdout:process.stdout,history:new f61,fuzzyServer:Z.fuzzyServer,settingsStorage:Z.settingsStorage,threadService:Z.threadService,threadHistoryService:Z.threadHistoryService,threadSyncService:Z.threadSyncService,planFileManager:Z.planFileManager,threadID:M,threadFuzzyIndexer:I,worker:E,workerDeps:O,configService:Z.configService,internalAPIClient:L5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:F7,connectedClientsService:new s11,commandRegistry:R,mcpService:Z.mcpService,mcpTrustHandler:j,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:V,typingEnabled:K,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:N}}),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),await zu(q,Y)}}async function zw8(J,Q,Y,X,G){Eq(X,J);let Z=await Iq(Q,J);try{let q=r91(Y);if(!q)o91(Y);let V=q,K=await L5.getUserInfo({},{config:Z.configService}),W=K.ok?K.result:null,H=J41(J,W);if(!H&&!G)fG("Must specify either --visibility or --support");if(H&&G)fG("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)fG(H.message);if(H)await Z.threadSyncService.updateThreadMeta(V,Q41(H)),p5.write(C4.green("✓ ")+`Thread ${V} visibility changed to ${H}.
5317
5317
  `);if(G)await uC(V,Z),await Yv0(Z.threadService,V,Z.configService),p5.write(C4.green("✓ ")+`Thread ${V} has been shared with Amp support.
5318
5318
  `);await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),fG(`Failed to update thread: ${q instanceof Error?q.message:String(q)}`)}}async function Fw8(J,Q,Y,X){Eq(X,J);let G=await Iq(Q,J),Z=mg(G);try{let q=await my1(Y),K=(await uC(q,G)).messages.length-1,W=await q3.getOrCreateForThread(Z,q),H=await TR(W,G.threadSyncService,K);await Promise.all([G.threadSyncService.uploadThread(q),G.threadSyncService.uploadThread(H)]),await uy1(H),p5.write(`${H}
5319
5319
  `),await G.asyncDispose(),process.exit(0)}catch(q){hG.write(`Error forking thread: ${q instanceof Error?q.message:String(q)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1763582484-gdd165b",
3
+ "version": "0.0.1763586382-g73297f",
4
4
  "description": "CLI for Amp, the frontier coding agent from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {