@sourcegraph/amp 0.0.1764777697-g907e30 → 0.0.1764792095-g2a447e
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +10 -10
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4013,15 +4013,15 @@ Actual: ${G}`)}async function Lq8(J,Q,Y){let{execSync:X}=await import("node:ch
|
|
|
4013
4013
|
${D}`;if(G==="pnpm"&&D.includes("Unable to find the global bin directory"))M+=`
|
|
4014
4014
|
|
|
4015
4015
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4016
|
-
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(U)=>{if(!H)H=!0,q(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}z0();z0();async function b41(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),V=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=await V.json(),K=q["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=Iq8(J,K),H=W<0,z,U;if(q.time){let D=q.time[J],M=q.time[K],L=Date.now();if(D)z=Math.floor((L-new Date(D).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return x.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 x.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function Iq8(J,Q){let Y=(V)=>{let[q,K]=V.split("-");return{parts:q?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let V=0;V<Z;V++){let q=X.parts[V]||0,K=G.parts[V]||0;if(q<K)return-1;if(q>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}o0();function g41(J,Q){let Y=new l4,X=Y.pipe(T8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new Eq().scoped("update"),Z=X.subscribe({next:(V)=>{G.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){G.debug("using fake update status for testing",{status:V}),await oT(500),Y.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:q});let K=YO(),W=await b41(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,D=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 h41();if(!q)q=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:q});if(q==="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 vm(W.latestVersion,z);let U=await aB(W.latestVersion),D={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",D),Y.next("updated");else G.warn("success with warning",D),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(V){G.debug("check failed",{error:V})}finally{await oT(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as mK}from"node:process";function a96(J){let Q=new pA().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 Kj1(X.force||!1,X.verbose||!1,"0.0.
|
|
4016
|
+
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(U)=>{if(!H)H=!0,q(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}z0();z0();async function b41(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),V=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=await V.json(),K=q["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=Iq8(J,K),H=W<0,z,U;if(q.time){let D=q.time[J],M=q.time[K],L=Date.now();if(D)z=Math.floor((L-new Date(D).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return x.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 x.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function Iq8(J,Q){let Y=(V)=>{let[q,K]=V.split("-");return{parts:q?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let V=0;V<Z;V++){let q=X.parts[V]||0,K=G.parts[V]||0;if(q<K)return-1;if(q>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}o0();function g41(J,Q){let Y=new l4,X=Y.pipe(T8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new Eq().scoped("update"),Z=X.subscribe({next:(V)=>{G.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){G.debug("using fake update status for testing",{status:V}),await oT(500),Y.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:q});let K=YO(),W=await b41(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,D=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 h41();if(!q)q=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:q});if(q==="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 vm(W.latestVersion,z);let U=await aB(W.latestVersion),D={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",D),Y.next("updated");else G.warn("success with warning",D),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(V){G.debug("check failed",{error:V})}finally{await oT(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as mK}from"node:process";function a96(J){let Q=new pA().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 Kj1(X.force||!1,X.verbose||!1,"0.0.1764792095-g2a447e"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new pA("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await Pq8(X.targetVersion)});J.addCommand(Y)}async function Pq8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")mK.write(f4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4017
4017
|
|
|
4018
4018
|
`));try{if(!J){mK.write(f4.blue(`Checking for updates...
|
|
4019
|
-
`));let X=YO(),{hasUpdate:G,latestVersion:Z}=await b41("0.0.
|
|
4020
|
-
`));let q=await aB("0.0.
|
|
4019
|
+
`));let X=YO(),{hasUpdate:G,latestVersion:Z}=await b41("0.0.1764792095-g2a447e",X);if(!G){mK.write(f4.green(`✓ Amp CLI is already up to date: ${"0.0.1764792095-g2a447e"} (${"released"} ${"2025-12-03T20:06:57.705Z"})
|
|
4020
|
+
`));let q=await aB("0.0.1764792095-g2a447e");if(q.warning)mK.write(`
|
|
4021
4021
|
`+f4.yellow(q.warning)+`
|
|
4022
4022
|
`);process.exit(0)}if(!Z)mK.write(f4.yellow("[WARN] could not find latest version")),process.exit(0);J=Z}mK.write(f4.blue(`Updating to version ${J}...
|
|
4023
4023
|
`)),await vm(J,void 0,(X)=>{mK.write(f4.dim(`Running: ${X}
|
|
4024
|
-
`))});let Q="released";mK.write(f4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-12-
|
|
4024
|
+
`))});let Q="released";mK.write(f4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-12-03T20:06:57.705Z"})
|
|
4025
4025
|
`));let Y=await aB(J);if(Y.warning)mK.write(`
|
|
4026
4026
|
`+f4.yellow(Y.warning)+`
|
|
4027
4027
|
`);process.exit(0)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);mK.write(f4.red.bold("Error: ")+Y+`
|
|
@@ -4653,7 +4653,7 @@ exit code: ${Z}`,new J1({color:X.foreground,dim:!0,italic:!0})));if(V)q.push(new
|
|
|
4653
4653
|
`,M),...L])})];if(H.url){let v=H.url.replace(/^https?:\/\//,"");k.push(new I7({uri:H.url,text:v,style:new J1({color:Y.secondary,underline:!0})}))}if(T)k.push(new X0({height:1})),k.push(T);let y=new X0({width:40,child:new b0({crossAxisAlignment:"start",mainAxisSize:"min",children:k})});return x4.child(new T6({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new _S1({width:$y1,height:Vy1,agentMode:this.widget.agentMode,glow:this._glow,t:A,fps:0,shockwaves:this._shockwaves,onShockwave:I,...V==="disabled"&&{seed:42}}),new X0({width:2}),y]}))}}z0();m8();N4();j7();m8();o0();function KL8(J,Q){return`${J}:${Q}`}class qy1{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(AM()).subscribe((Z)=>{this.threadsMap.set(Q,Z);let V=this.subthreadsMap.get(Q)||[],q=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:Z,subthreads:V,workerStatus:q})});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 V of Z){let q=KL8(Q,V.toolUse.id);if(this.subthreadPatchSubs.has(q))continue;let K=this.threadService.observePatches(V.threadID).pipe(AM()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:V})});this.subthreadPatchSubs.set(q,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]=PA(Y,X)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.subthreadsSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();for(let J of this.subthreadPatchSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.subthreadsSubs.clear(),this.workerStatusSubs.clear(),this.subthreadPatchSubs.clear(),this.workers.clear(),this.threadsMap.clear(),this.subthreadsMap.clear()}}function WL8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Y,subthread:X}=Q,G=J.subagents[X.threadID];if(!G){if(G={subThreadID:Y.id,parentToolID:X.toolUse.id,taskDescription:X.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=iJ(J.mainThread);G.isCompleted=vY6(W,X.toolUse.id)}}let Z=HL8(Y,G.agentState),V=G.agentState===Z?G:{...G,agentState:Z},q={...J.tools},K=Wj(Y).items.filter((W)=>W.type==="toolResult");for(let W of K)q[W.id]={id:W.id,subthreadID:Y.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[X.threadID]:V},tools:q,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),V={...J.subagents};for(let z of X){let U=V[z.threadID];if(!U)continue;let D=vY6(Z,z.toolUse.id);V[z.threadID]={...U,isCompleted:D}}let{items:q}=Wj(Y),K=PA(Y,G),W=MI({messages:Y.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:V,items:q,viewState:K,todosList:H,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=PA(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function Wj(J){let Q=[],Y=new Map,X=new Set;for(let[G,Z]of J.messages.entries()){let V=`${Z.role}-${G}`;switch(Z.role){case"assistant":{let q=Z.state.type==="streaming";for(let W of Z.content)if(W.type==="tool_use"){if(Y.set(W.id,W),q)X.add(W.id)}if(Z.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,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 D of U.content)if(D.type==="tool_result"&&D.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:q?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:V,message:Z});break;case"user":{let q=Z.content.some((K)=>K.type==="text"&&K.text.trim()||K.type==="image");for(let K of Z.content)if(K.type==="tool_result"){let W=Y.get(K.toolUseID)??LX(J,K.toolUseID);if(!W)throw Error(`(bug) tool use ${K.toolUseID} not found`);Q.push({type:"toolResult",id:K.toolUseID,toolUse:W,toolResult:K})}if(q)Q.push({type:"message",id:V,message:Z});break}}}return{items:Q}}function vY6(J,Q){let Y=J.get(Q);return(Y&&z3(Y.run))??!1}function HL8(J,Q){let Y=J.messages.at(-1);if(Y?.content.some((G)=>G.type==="tool_result"&&G.run.status==="blocked-on-user"))return x.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(Wj(J).items.some((G)=>G.type==="toolResult"&&G.toolResult.run.status==="in-progress")){let G=Q?.type==="running-tools"?Q.startTime:Date.now();return x.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 x.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return x.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 x.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:Z,hasStartTime:!!Z}),{type:"running-tools",startTime:Z}}default:return x.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return x.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class Ky1 extends c0{props;constructor(J){super();this.props=J}createState(){return new fY6}}class fY6 extends p0{state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new qy1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Y=Q.mainThread.subscribe((Z)=>{this.dispatch({type:"main-thread-patch",thread:Z.mainThread,subthreads:Z.subthreads,workerStatus:Z.workerStatus})});this.subscriptions.push(Y);let X=Q.subthreads.subscribe((Z)=>{this.dispatch({type:"subthread-patch",thread:Z.thread,subthread:Z.subthread})});this.subscriptions.push(X);let G=Q.workerStatus.subscribe((Z)=>{this.dispatch({type:"worker-status-change",workerStatus:Z.status})});this.subscriptions.push(G)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=WL8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((Z)=>({toolUse:Z.toolUse,toolRun:Z.toolRun,subthreadID:Z.subthreadID})),Q={};for(let Z of Object.values(this.state.subagents)){let V=J.filter((q)=>q.subthreadID===Z.subThreadID);Q[Z.parentToolID]=V}let Y=(Z)=>Z===I5||Z===Y9||Z===DX,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:V}of G){let q=[],K;if(V.status==="in-progress"||V.status==="done"||V.status==="error"||V.status==="cancelled")K=V.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++}`;q.push({toolUse:BI(z.tool_name,z.input,U),toolRun:{status:z.status}})}}Q[Z]=q}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker,this.recentThreadIDs)}}class Wy1 extends c0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new hY6}}class hY6 extends p0{build(J){let Y=G6.of(J).colors,{todos:X,title:G="TODOs"}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new X0({width:0,height:0});let Z=X.map((V)=>this.buildTodoItem(V,Y));return new l0({child:new q6({padding:F0.symmetric(1,0),child:new b0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new y1({text:new i(G,new J1({bold:!0,color:Y.foreground}))}),...Z]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),X=J.status==="completed",G=new J1({bold:J.status==="in-progress",color:Q.foreground,dim:X}),Z=new J1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:X});return new T6({crossAxisAlignment:"start",children:[new y1({text:new i(Y,G)}),new X0({width:1}),new e6({child:new y1({text:new i(J.content,Z)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Hy1 extends I6{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=G6.of(J),Y=Q.colors.primary,X=Q.colors.foreground;return new l0({decoration:new K8(void 0,new P4(new F4(Y,1,"rounded"),new F4(Y,1,"rounded"),void 0,new F4(Y,1,"rounded"))),child:new q6({padding:F0.horizontal(1),child:new b0({children:[new T6({crossAxisAlignment:"start",children:[new e6({child:new y1({text:new i(this.ad.content,new J1({color:X}))})}),new X0({width:4}),new I7({uri:"https://ampcode.com/free",text:"Ad",style:new J1({color:X,dim:!0})})]}),new T6({crossAxisAlignment:"start",children:[new pS1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:F0.horizontal(1),color:Y,reverse:!0}),new X0({width:2}),new y1({text:new i(this.ad.destinationUrlHostname,new J1({color:X,dim:!0}))})]})]})})})}}class zy1 extends c0{props;constructor(J){super();this.props=J}createState(){return new bY6(this.props.autofocus??!0)}}class bY6 extends p0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(q)=>{if(q.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(q.ctrlKey&&q.key==="c"||q.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=m4.sizeOf(J),X=Math.min(60,Y.width-4),G=Y.height-4,Z=[];if(this.widget.props.title)Z.push(new y1({text:new i(this.widget.props.title,new J1({bold:!0,color:D1.blue}))}),new X0({height:1}));if(this.widget.props.message)Z.push(new y1({text:new i(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)Z.push(new X0({height:1}));let V=[];if(this.widget.props.showCopyOption)V.push(new y1({text:new i("Enter to copy",new J1({dim:!0}))}));return V.push(new y1({text:new i("Escape to close",new J1({dim:!0}))})),Z.push(new T6({children:V.flatMap((q,K)=>K<V.length-1?[q,new X0({width:1}),new y1({text:new i("•",new J1({dim:!0}))}),new X0({width:1})]:[q]),mainAxisSize:"min"})),new x4({child:new l0({constraints:new A6(X,X,0,G),decoration:new K8(D1.default(),new P4(new F4(D1.blue,1,"rounded"),new F4(D1.blue,1,"rounded"),new F4(D1.blue,1,"rounded"),new F4(D1.blue,1,"rounded"))),padding:new F0(2,2,2,2),child:new I8({autofocus:this.autofocus,onKey:Q,child:new b0({children:Z,mainAxisSize:"min"})})})})}}function zL8(J){let Q=Math.floor(J/60),Y=J%60;if(Q===0)return`${Y}s`;return`${Q}:${Y.toString().padStart(2,"0")}`}function FL8(J){if(J<0.01)return"<$0.01";return`$${J.toFixed(2)}`}function UL8(J){if(J<=60)return"~ 1m";if(J<=120)return"~ 2m";if(J<=300)return"~ 5m";return"~ 10m"}function gY6(J,Q={}){if(J.secondsRemaining===null)return null;if(J.secondsRemaining===0)return{text:"cache expired",urgency:"expired"};let Y=J.secondsRemaining<=60,X=Q.isIdle!==!1&&Y,G=X?zL8(J.secondsRemaining):UL8(J.secondsRemaining),Z=FL8(J.potentialSavingsUSD);if(Q.isNarrow)return{text:G,urgency:X?"warning":"normal"};if(Q.prominent&&X)return{text:`${G} left - respond now to save up to ${Z}`,urgency:"warning"};return{text:`${G} (save up to ${Z})`,urgency:X?"warning":"normal"}}class V51 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,V51.prototype)}}class q51 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,q51.prototype)}}function Fy1(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})}BH();z0();import{spawn as BL8}from"node:child_process";import{promises as NL8}from"node:fs";function mY6(J){return J.kind==="executable"}function uY6(J){return J.kind==="markdown"}var Rz=50000,pY6=300000;async function Uy1(J,Q,Y,X={}){let{timeoutMs:G=pY6,signal:Z,source:V}=X;try{let q=await Y.getCommand(J,V);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Y.isCommandAvailable(J,V))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(x.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),uY6(q))return await DL8(q,Q);else if(mY6(q))return await ML8(q,Q,G,Z);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return x.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function DL8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await NL8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>Rz?Y.slice(0,Rz)+`
|
|
4654
4654
|
... (output truncated at ${Rz} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function ML8(J,Q,Y=pY6,X){return new Promise((G)=>{let[Z,V]=LL8(J,Q);x.debug("Spawning command",{spawnCommand:Z,spawnArgs:V.slice(0,10),filePath:J.filePath,timeoutMs:Y});let q=UR0(X),K=!1,W=setTimeout(()=>{K=!0,q.abort(),x.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=BL8(Z,V,{stdio:["pipe","pipe","pipe"],signal:q.signal,detached:!0}),z=[],U=[],D=0;H.stdout?.on("data",(M)=>{let L=M.toString();if(D+=L.length,D<=Rz)z.push(L);else{let A=Rz-(D-L.length);if(A>0)z.push(L.slice(0,A))}}),H.stderr?.on("data",(M)=>{let L=M.toString();if(D+=L.length,D<=Rz)U.push(L);else{let A=Rz-(D-L.length);if(A>0)U.push(L.slice(0,A))}}),H.on("close",(M)=>{if(clearTimeout(W),K){G({success:!1,output:z.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(q.signal.aborted){G({success:!1,output:z.join(""),error:"The command was aborted",exitCode:M??void 0});return}let L=M===0||M===1,A=z.join(""),E=U.join(""),I=A;if(!L&&!A.trim()&&E.trim())I=E;else if(E.trim())I+=A?`
|
|
4655
4655
|
${E}`:E;if(D>Rz)I+=`
|
|
4656
|
-
... (output truncated at ${Rz} characters)`;G({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(K)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";G({success:!1,output:z.join(""),error:L})})})}function LL8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return OL8(Y,X?[...X]:null,G,Q);else return AL8(Y,X?[...X]:null,G,Q)}function AL8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function OL8(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]}}z0();x$();p7();aW();CX();e$();NH();YK();m8();j7();xk();o0();var ZX6=z6(WR(),1);import{writeFile as YX6}from"fs/promises";import XX6 from"path";z0();CX();class By1{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.1764777697-g907e30"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await br(Q,this.configService)}catch(Q){x.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 Cu extends c0{props;constructor(J){super();this.props=J}createState(){return new dY6}}class dY6 extends p0{_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 cY6 extends p0{controller=new vZ;focusNode=new S8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=G6.of(J),{colors:Y,app:X}=Q,G=this.widget.props.isRequiredArg??!0,Z=this.controller.text.trim().length>0,V=!G||Z,q=P4.all(new F4(Y.foreground,1,"solid")),K=new DO({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let M=D.trim();if(G&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new T6({children:[new l0({decoration:{color:D1.default()},child:new y1({text:new i(">",new J1({color:Y.foreground}))})}),new e6({child:K})]}),H=new l0({padding:F0.symmetric(1,0),child:new y1({text:new i("",void 0,[new i("Command: ",new J1({color:Y.foreground})),new i(this.widget.props.commandName,new J1({color:D1.yellow,bold:!0}))])})}),z=[];if(V)z.push(new i("Enter",new J1({color:X.keybind}))),z.push(new i(" to submit, ",new J1({color:Y.foreground,dim:!0})));z.push(new i("Esc",new J1({color:X.keybind}))),z.push(new i(" to cancel",new J1({color:Y.foreground,dim:!0})));let U=new l0({padding:F0.symmetric(1,0),child:new y1({text:new i("",void 0,z)})});return new l0({decoration:{border:q,color:D1.default()},padding:F0.all(1),child:new b0({children:[H,new X0({height:1}),W,new K5,U]})})}}class K51 extends c0{props;constructor(J){super();this.props=J}createState(){return new cY6}}NH();class lY6 extends p0{controller=new vZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new S8({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>=BU)return!1;let Q=nC(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=G6.of(J),{colors:Y,app:X}=Q,Z=m4.of(J).size.height,V=Math.max(Math.floor(Z*0.5),10),q=new SO({controller:this.controller,triggers:[new FN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:Z9.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:q}),W=new l0({constraints:new A6({maxHeight:V}),padding:F0.symmetric(1,0),child:K}),H=new l0({padding:F0.symmetric(1,0),child:new y1({text:new i("",void 0,[new i("Command: ",new J1({color:Y.foreground})),new i(this.widget.props.commandName,new J1({color:D1.yellow,bold:!0}))])})}),z=new l0({padding:F0.symmetric(1,0),child:new y1({text:this.isConfirmingClearInput?new i("",void 0,[new i("Esc",new J1({color:X.keybind})),new i(" again to clear input",new J1({color:Y.foreground,dim:!0}))]):new i("",void 0,[new i("Press ",new J1({color:Y.foreground,dim:!0})),new i("Enter",new J1({color:X.keybind})),new i(" to submit, ",new J1({color:Y.foreground,dim:!0})),new i("Esc",new J1({color:X.keybind})),new i(" to clear",new J1({color:Y.foreground,dim:!0}))])})}),U=[H,new X0({height:1}),new e6({child:W}),new X0({height:1}),z];return new l0({decoration:{border:P4.all(new F4(Y.foreground,1,"solid")),color:D1.default()},padding:F0.all(1),child:new b0({children:U})})}}class Hj extends c0{props;constructor(J){super();this.props=J}createState(){return new lY6}}import{isDeepStrictEqual as PL8}from"node:util";var wL8=/[\\/_ +.#"@[({&]/,EL8=/[\\/_ +.#"@[({&]/g,IL8=/[\s-]/,iY6=/[\s-]/g;function H51(J,Q,Y,X,G,Z,V){if(Z===Q.length){if(G===J.length)return 1;return 0.99}let q=`${G},${Z}`;if(V[q]!==void 0)return V[q];let K=X.charAt(Z),W=Y.indexOf(K,G),H=0,z,U,D,M;while(W>=0){if(z=H51(J,Q,Y,X,W+1,Z+1,V),z>H){if(W===G)z*=1;else if(IL8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(G,W-1).match(iY6),M&&G>0)z*=Math.pow(0.999,M.length)}else if(wL8.test(J.charAt(W-1))){if(z*=0.8,D=J.slice(G,W-1).match(EL8),D&&G>0)z*=Math.pow(0.999,D.length)}else if(z*=0.3,G>0)z*=Math.pow(0.999,W-G);if(J.charAt(W)!==Q.charAt(Z))z*=0.9999}if(z<0.1&&(Y.charAt(W-1)===X.charAt(Z+1)||X.charAt(Z+1)===X.charAt(Z)&&Y.charAt(W-1)!==X.charAt(Z))){if(U=H51(J,Q,Y,X,W+1,Z+2,V),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Y.indexOf(K,W+1)}return V[q]=H,H}function W51(J){return J.toLowerCase().replace(iY6," ")}function nY6(J,Q){let Y=H51(J,Q,W51(J),W51(Q),0,0,{}),X=Q.trim().split(/\s+/);if(X.length>1){let G=0,Z=0;for(let q of X){let K=H51(J,q,W51(J),W51(q),0,0,{});if(K===0)return Y;G+=K,Z+=q.length}let V=G/X.length*0.95;return Math.max(Y,V)}return Y}class zj{}class Fj{}class z51{}class F51{}class aY6 extends c0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new oY6}}class oY6 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function RL8(J,Q){if(J==="")return{matches:!0,score:1};let Y=nY6(Q,J);return{matches:Y>0.15,score:Y}}class rY extends c0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new rY6}}class rY6 extends p0{controller=new vZ;focusNode;scrollController=new E7;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new S8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),r8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!PL8(J.props.items,this.widget.props.items)){this.ensureSelectedItemVisible();let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof zj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof Fj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof z51){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Y=Q[this.selectedIndex];if(Y){if(!(this.widget.props.isItemDisabled?.(Y)??!1))this.widget.props.onAccept(Y)}}return"handled"}if(J instanceof F51)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Y)=>!this.widget.props.filterItem||this.widget.props.filterItem(Y,J)).map((Y)=>({item:Y,...RL8(J,this.widget.props.getLabel(Y))})).filter((Y)=>Y.matches).sort(this.widget.props.sortItems?(Y,X)=>this.widget.props.sortItems(Y,X,J):(Y,X)=>X.score-Y.score).map((Y)=>Y.item);if(this.widget.props.maxRenderItems)return Q.slice(0,this.widget.props.maxRenderItems);return Q}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,X=Q.size.height;q91(J,{top:Y,bottom:X},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),r8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Y=this.getFilteredItems();if(J>=0&&J<Y.length){let X=Y[J],G=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!G){if(X)this.widget.props.onAccept(X)}}};build(J){let Q=G6.of(J),{colors:Y}=Q,X=this.getFilteredItems(),G=P4.all(new F4(Y.foreground,1,"solid")),Z=this.widget.props.enabled??!0,V=new DO({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:Z,style:{textColor:Y.foreground,border:null},maxLines:1}),q=new _V({shortcuts:new Map([[new z4("ArrowDown"),new zj],[new z4("ArrowUp"),new Fj],[new z4("Tab"),new zj],[new z4("Tab",{shift:!0}),new Fj],[new z4("n",{ctrl:!0}),new zj],[new z4("p",{ctrl:!0}),new Fj],[new z4("Enter"),new z51],[new z4("Escape"),new F51]]),focusNode:this.focusNode,child:V}),K=new tQ({actions:new Map([[zj,new x8(this.invoke)],[Fj,new x8(this.invoke)],[z51,new x8(this.invoke)],[F51,new x8(this.invoke)]]),child:q}),W=new T6({children:[new l0({decoration:{color:D1.default()},child:new y1({text:new i(">",new J1({color:Y.foreground}))})}),new e6({child:K})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new X0({height:10,child:new x4({child:new y1({text:new i(L,new J1({color:Y.foreground}))})})})}else if(X.length===0&&this.widget.props.emptyStateText)H=new e6({child:new x4({child:new y1({text:new i(this.widget.props.emptyStateText,new J1({color:Y.foreground,dim:!0}))})})});else{let L=X.map((A,E)=>{let I=E===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,T;if(this.widget.props.renderItem)T=this.widget.props.renderItem(A,I,P,J);else{let k=I?D1.yellow:void 0,y=I?D1.black:Y.foreground;T=new l0({decoration:k?{color:k}:void 0,padding:F0.symmetric(2,0),child:new y1({text:new i(this.widget.props.getLabel(A),new J1({color:y,dim:P}))})})}return new aY6(new F8({onClick:(k)=>this.handleItemClick(E,k.clickCount),child:T}),(k)=>{this.itemContexts[E]=k})});H=new b0({children:L,crossAxisAlignment:"start"})}let z=new e6({child:new F8({onScroll:this.handleScroll,opaque:!1,child:new b5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new l0({padding:F0.symmetric(1,0),child:new y1({text:new i(this.widget.props.title,new J1({color:D1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new X0({height:1}),z),this.controller.text!==""){let L=X.length>0?X[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new l0({padding:F0.vertical(1),child:new x4({child:A})}));else U.push(new X0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new l0({decoration:{border:G,color:D1.default()},padding:F0.symmetric(1,0),child:new b0({children:U})})}}class Ny1 extends c0{createState(){return new sY6}}class sY6 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){return new y1({text:new i("●",new J1({color:this.isGreen?D1.green:D1.index(8),bold:!0})),maxLines:1})}}function TL8(J){let Q=new Map,Y=new Map,X=new Map,G=[];for(let V of J)Q.set(V.id,V);for(let V of J){let q=V.parentRelationships.find((K)=>K.role==="child"&&Q.has(K.threadID));if(q){X.set(V.id,q.type);let K=q.threadID,W=Y.get(K)||[];W.push(V),Y.set(K,W)}else G.push(V)}return XG.flatten(G,(V)=>Y.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:X.get(V.item.id)}))}function Dy1(J,Q,Y){return new y1({text:new i(`${J}${Q}`,new J1({color:Y})),maxLines:1})}function CL8(J,Q,Y,X){return[Dy1("+",J,X.success),K5.horizontal(1),Dy1("~",Q,X.warning),K5.horizontal(1),Dy1("-",Y,X.destructive)]}class U51 extends I6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((H)=>H.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((H)=>H.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],X=this.props.currentThreadID,G=[...Q].sort((H,z)=>{if(X){if(H.id===X)return-1;if(z.id===X)return 1}let U=Y.indexOf(H.id),D=Y.indexOf(z.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),Z=TL8(G),V=Math.max(0,...Z.map((H)=>H.description.timeAgo.length)),q=G6.of(J),K=new q6({padding:F0.symmetric(0,1),child:new x4({child:new y1({text:new i("",new J1({color:q.colors.foreground,dim:!0}),[new i("Ctrl+T",new J1({color:D1.blue,dim:!0})),new i(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new J1({color:q.colors.foreground,dim:!0}))])})})});return new rY({items:Z,getLabel:(H)=>H.title,onAccept:(H)=>this.props.onSelect?.(H.id),onDismiss:this.props.onDismiss,onSelectionChange:(H)=>{if(this.props.previewController){if(H)this.props.previewController.select(H.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:1000,footer:this.props.isLoading?void 0:K,renderItem:(H,z,U,D)=>{let M=G6.of(D),{colors:L}=M,A=z?D1.yellow:void 0,E=z?D1.black:L.foreground,I=D1.index(8),P=(Z1,t)=>new X0({width:t,child:T6.end([new y1({text:new i(Z1,new J1({color:I}))})])}),T=this.props.threadViewStates[H.id],k=[],y=H.relationshipType==="handoff",v=new B91;if(H.depth>0){let Z1=[],t=H.ancestorsAreLast.slice(1);for(let F1 of t)Z1.push(new i(v.getAncestorPrefix(F1),new J1({color:v.connectorColor,dim:v.connectorDim})));let p=H.isLast?v.elbow:v.tee,e=v.getConnectorText(p);Z1.push(new i(e,new J1({color:v.connectorColor,dim:v.connectorDim}))),k.push(new y1({text:new i("",void 0,Z1)}))}let b=[],d=this.props.currentThreadID===H.id?new i("(current) ",new J1({color:D1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new i("(visited) ",new J1({color:L.foreground,dim:!0})):null;if(d)b.push(new y1({text:d}));if(T){if(T.state==="active"&&(T.interactionState==="tool-running"||T.interactionState===!1))b.push(new Ny1),b.push(new X0({width:1}))}let m=H.title;if(H.relationshipType==="fork"){let Z1=m.match(/^Forked\((\d+)\): /);if(Z1)m=m.slice(Z1[0].length);else while(m.startsWith("Forked: "))m=m.slice(8);b.push(new y1({text:new i("[fork] ",new J1({color:D1.blue}))}))}else if(y)b.push(new y1({text:new i("[handoff] ",new J1({color:D1.index(208)}))}));if(b.push(new e6({child:new y1({text:new i(m,new J1({color:E})),overflow:"ellipsis",maxLines:1})})),b.push(new X0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let Z1=z?{success:I,warning:I,destructive:I}:L;b.push(...CL8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,Z1)),b.push(new X0({width:2}))}return b.push(P(H.description.timeAgo,V)),new l0({decoration:A?{color:A}:void 0,padding:F0.symmetric(2,0),child:new T6({children:[...k,...b]})})}})}}function tY6(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/60000),G=Math.floor(Y/3600000),Z=Math.floor(Y/86400000);if(X<1)return"just now";if(X<60)return`${X}m ago`;if(G<24)return`${G}h ago`;if(Z<7)return`${Z}d ago`;return J.toLocaleDateString()}class My1 extends I6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((G,Z)=>Z.pubDate.getTime()-G.pubDate.getTime()),Y=Math.max(0,...Q.map((G)=>tY6(G.pubDate).length));return new rY({items:Q,getLabel:(G)=>G.title,onAccept:(G)=>this.props.onSelect?.(G),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(G,Z,V,q)=>{let K=G6.of(q),{colors:W}=K,H=Z?D1.yellow:void 0,z=Z?D1.black:W.foreground,U=D1.index(8),D=G.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new X0({width:A,child:T6.end([new y1({text:new i(L,new J1({color:U}))})])});return new l0({decoration:H?{color:H}:void 0,padding:F0.symmetric(2,0),child:new T6({children:[new e6({child:new y1({text:new i(G.title,new J1({color:z})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new y1({text:new i(D,new J1({color:U})),maxLines:1}),new X0({width:2}),M(tY6(G.pubDate),Y)]})})}})}}class Ly1 extends I6{props;constructor(J){super();this.props=J}build(){return new x4({child:new y1({text:new i("",void 0,[new i(`Forked to new thread:
|
|
4656
|
+
... (output truncated at ${Rz} characters)`;G({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(K)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";G({success:!1,output:z.join(""),error:L})})})}function LL8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return OL8(Y,X?[...X]:null,G,Q);else return AL8(Y,X?[...X]:null,G,Q)}function AL8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function OL8(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]}}z0();x$();p7();aW();CX();e$();NH();YK();m8();j7();xk();o0();var ZX6=z6(WR(),1);import{writeFile as YX6}from"fs/promises";import XX6 from"path";z0();CX();class By1{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.1764792095-g2a447e"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await br(Q,this.configService)}catch(Q){x.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 Cu extends c0{props;constructor(J){super();this.props=J}createState(){return new dY6}}class dY6 extends p0{_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 cY6 extends p0{controller=new vZ;focusNode=new S8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=G6.of(J),{colors:Y,app:X}=Q,G=this.widget.props.isRequiredArg??!0,Z=this.controller.text.trim().length>0,V=!G||Z,q=P4.all(new F4(Y.foreground,1,"solid")),K=new DO({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let M=D.trim();if(G&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new T6({children:[new l0({decoration:{color:D1.default()},child:new y1({text:new i(">",new J1({color:Y.foreground}))})}),new e6({child:K})]}),H=new l0({padding:F0.symmetric(1,0),child:new y1({text:new i("",void 0,[new i("Command: ",new J1({color:Y.foreground})),new i(this.widget.props.commandName,new J1({color:D1.yellow,bold:!0}))])})}),z=[];if(V)z.push(new i("Enter",new J1({color:X.keybind}))),z.push(new i(" to submit, ",new J1({color:Y.foreground,dim:!0})));z.push(new i("Esc",new J1({color:X.keybind}))),z.push(new i(" to cancel",new J1({color:Y.foreground,dim:!0})));let U=new l0({padding:F0.symmetric(1,0),child:new y1({text:new i("",void 0,z)})});return new l0({decoration:{border:q,color:D1.default()},padding:F0.all(1),child:new b0({children:[H,new X0({height:1}),W,new K5,U]})})}}class K51 extends c0{props;constructor(J){super();this.props=J}createState(){return new cY6}}NH();class lY6 extends p0{controller=new vZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new S8({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>=BU)return!1;let Q=nC(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=G6.of(J),{colors:Y,app:X}=Q,Z=m4.of(J).size.height,V=Math.max(Math.floor(Z*0.5),10),q=new SO({controller:this.controller,triggers:[new FN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:Z9.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:q}),W=new l0({constraints:new A6({maxHeight:V}),padding:F0.symmetric(1,0),child:K}),H=new l0({padding:F0.symmetric(1,0),child:new y1({text:new i("",void 0,[new i("Command: ",new J1({color:Y.foreground})),new i(this.widget.props.commandName,new J1({color:D1.yellow,bold:!0}))])})}),z=new l0({padding:F0.symmetric(1,0),child:new y1({text:this.isConfirmingClearInput?new i("",void 0,[new i("Esc",new J1({color:X.keybind})),new i(" again to clear input",new J1({color:Y.foreground,dim:!0}))]):new i("",void 0,[new i("Press ",new J1({color:Y.foreground,dim:!0})),new i("Enter",new J1({color:X.keybind})),new i(" to submit, ",new J1({color:Y.foreground,dim:!0})),new i("Esc",new J1({color:X.keybind})),new i(" to clear",new J1({color:Y.foreground,dim:!0}))])})}),U=[H,new X0({height:1}),new e6({child:W}),new X0({height:1}),z];return new l0({decoration:{border:P4.all(new F4(Y.foreground,1,"solid")),color:D1.default()},padding:F0.all(1),child:new b0({children:U})})}}class Hj extends c0{props;constructor(J){super();this.props=J}createState(){return new lY6}}import{isDeepStrictEqual as PL8}from"node:util";var wL8=/[\\/_ +.#"@[({&]/,EL8=/[\\/_ +.#"@[({&]/g,IL8=/[\s-]/,iY6=/[\s-]/g;function H51(J,Q,Y,X,G,Z,V){if(Z===Q.length){if(G===J.length)return 1;return 0.99}let q=`${G},${Z}`;if(V[q]!==void 0)return V[q];let K=X.charAt(Z),W=Y.indexOf(K,G),H=0,z,U,D,M;while(W>=0){if(z=H51(J,Q,Y,X,W+1,Z+1,V),z>H){if(W===G)z*=1;else if(IL8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(G,W-1).match(iY6),M&&G>0)z*=Math.pow(0.999,M.length)}else if(wL8.test(J.charAt(W-1))){if(z*=0.8,D=J.slice(G,W-1).match(EL8),D&&G>0)z*=Math.pow(0.999,D.length)}else if(z*=0.3,G>0)z*=Math.pow(0.999,W-G);if(J.charAt(W)!==Q.charAt(Z))z*=0.9999}if(z<0.1&&(Y.charAt(W-1)===X.charAt(Z+1)||X.charAt(Z+1)===X.charAt(Z)&&Y.charAt(W-1)!==X.charAt(Z))){if(U=H51(J,Q,Y,X,W+1,Z+2,V),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Y.indexOf(K,W+1)}return V[q]=H,H}function W51(J){return J.toLowerCase().replace(iY6," ")}function nY6(J,Q){let Y=H51(J,Q,W51(J),W51(Q),0,0,{}),X=Q.trim().split(/\s+/);if(X.length>1){let G=0,Z=0;for(let q of X){let K=H51(J,q,W51(J),W51(q),0,0,{});if(K===0)return Y;G+=K,Z+=q.length}let V=G/X.length*0.95;return Math.max(Y,V)}return Y}class zj{}class Fj{}class z51{}class F51{}class aY6 extends c0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new oY6}}class oY6 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function RL8(J,Q){if(J==="")return{matches:!0,score:1};let Y=nY6(Q,J);return{matches:Y>0.15,score:Y}}class rY extends c0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new rY6}}class rY6 extends p0{controller=new vZ;focusNode;scrollController=new E7;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new S8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),r8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!PL8(J.props.items,this.widget.props.items)){this.ensureSelectedItemVisible();let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof zj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof Fj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof z51){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Y=Q[this.selectedIndex];if(Y){if(!(this.widget.props.isItemDisabled?.(Y)??!1))this.widget.props.onAccept(Y)}}return"handled"}if(J instanceof F51)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Y)=>!this.widget.props.filterItem||this.widget.props.filterItem(Y,J)).map((Y)=>({item:Y,...RL8(J,this.widget.props.getLabel(Y))})).filter((Y)=>Y.matches).sort(this.widget.props.sortItems?(Y,X)=>this.widget.props.sortItems(Y,X,J):(Y,X)=>X.score-Y.score).map((Y)=>Y.item);if(this.widget.props.maxRenderItems)return Q.slice(0,this.widget.props.maxRenderItems);return Q}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,X=Q.size.height;q91(J,{top:Y,bottom:X},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),r8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Y=this.getFilteredItems();if(J>=0&&J<Y.length){let X=Y[J],G=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!G){if(X)this.widget.props.onAccept(X)}}};build(J){let Q=G6.of(J),{colors:Y}=Q,X=this.getFilteredItems(),G=P4.all(new F4(Y.foreground,1,"solid")),Z=this.widget.props.enabled??!0,V=new DO({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:Z,style:{textColor:Y.foreground,border:null},maxLines:1}),q=new _V({shortcuts:new Map([[new z4("ArrowDown"),new zj],[new z4("ArrowUp"),new Fj],[new z4("Tab"),new zj],[new z4("Tab",{shift:!0}),new Fj],[new z4("n",{ctrl:!0}),new zj],[new z4("p",{ctrl:!0}),new Fj],[new z4("Enter"),new z51],[new z4("Escape"),new F51]]),focusNode:this.focusNode,child:V}),K=new tQ({actions:new Map([[zj,new x8(this.invoke)],[Fj,new x8(this.invoke)],[z51,new x8(this.invoke)],[F51,new x8(this.invoke)]]),child:q}),W=new T6({children:[new l0({decoration:{color:D1.default()},child:new y1({text:new i(">",new J1({color:Y.foreground}))})}),new e6({child:K})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new X0({height:10,child:new x4({child:new y1({text:new i(L,new J1({color:Y.foreground}))})})})}else if(X.length===0&&this.widget.props.emptyStateText)H=new e6({child:new x4({child:new y1({text:new i(this.widget.props.emptyStateText,new J1({color:Y.foreground,dim:!0}))})})});else{let L=X.map((A,E)=>{let I=E===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,T;if(this.widget.props.renderItem)T=this.widget.props.renderItem(A,I,P,J);else{let k=I?D1.yellow:void 0,y=I?D1.black:Y.foreground;T=new l0({decoration:k?{color:k}:void 0,padding:F0.symmetric(2,0),child:new y1({text:new i(this.widget.props.getLabel(A),new J1({color:y,dim:P}))})})}return new aY6(new F8({onClick:(k)=>this.handleItemClick(E,k.clickCount),child:T}),(k)=>{this.itemContexts[E]=k})});H=new b0({children:L,crossAxisAlignment:"start"})}let z=new e6({child:new F8({onScroll:this.handleScroll,opaque:!1,child:new b5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new l0({padding:F0.symmetric(1,0),child:new y1({text:new i(this.widget.props.title,new J1({color:D1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new X0({height:1}),z),this.controller.text!==""){let L=X.length>0?X[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new l0({padding:F0.vertical(1),child:new x4({child:A})}));else U.push(new X0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new l0({decoration:{border:G,color:D1.default()},padding:F0.symmetric(1,0),child:new b0({children:U})})}}class Ny1 extends c0{createState(){return new sY6}}class sY6 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){return new y1({text:new i("●",new J1({color:this.isGreen?D1.green:D1.index(8),bold:!0})),maxLines:1})}}function TL8(J){let Q=new Map,Y=new Map,X=new Map,G=[];for(let V of J)Q.set(V.id,V);for(let V of J){let q=V.parentRelationships.find((K)=>K.role==="child"&&Q.has(K.threadID));if(q){X.set(V.id,q.type);let K=q.threadID,W=Y.get(K)||[];W.push(V),Y.set(K,W)}else G.push(V)}return XG.flatten(G,(V)=>Y.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:X.get(V.item.id)}))}function Dy1(J,Q,Y){return new y1({text:new i(`${J}${Q}`,new J1({color:Y})),maxLines:1})}function CL8(J,Q,Y,X){return[Dy1("+",J,X.success),K5.horizontal(1),Dy1("~",Q,X.warning),K5.horizontal(1),Dy1("-",Y,X.destructive)]}class U51 extends I6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((H)=>H.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((H)=>H.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],X=this.props.currentThreadID,G=[...Q].sort((H,z)=>{if(X){if(H.id===X)return-1;if(z.id===X)return 1}let U=Y.indexOf(H.id),D=Y.indexOf(z.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),Z=TL8(G),V=Math.max(0,...Z.map((H)=>H.description.timeAgo.length)),q=G6.of(J),K=new q6({padding:F0.symmetric(0,1),child:new x4({child:new y1({text:new i("",new J1({color:q.colors.foreground,dim:!0}),[new i("Ctrl+T",new J1({color:D1.blue,dim:!0})),new i(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new J1({color:q.colors.foreground,dim:!0}))])})})});return new rY({items:Z,getLabel:(H)=>H.title,onAccept:(H)=>this.props.onSelect?.(H.id),onDismiss:this.props.onDismiss,onSelectionChange:(H)=>{if(this.props.previewController){if(H)this.props.previewController.select(H.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:1000,footer:this.props.isLoading?void 0:K,renderItem:(H,z,U,D)=>{let M=G6.of(D),{colors:L}=M,A=z?D1.yellow:void 0,E=z?D1.black:L.foreground,I=D1.index(8),P=(Z1,t)=>new X0({width:t,child:T6.end([new y1({text:new i(Z1,new J1({color:I}))})])}),T=this.props.threadViewStates[H.id],k=[],y=H.relationshipType==="handoff",v=new B91;if(H.depth>0){let Z1=[],t=H.ancestorsAreLast.slice(1);for(let F1 of t)Z1.push(new i(v.getAncestorPrefix(F1),new J1({color:v.connectorColor,dim:v.connectorDim})));let p=H.isLast?v.elbow:v.tee,e=v.getConnectorText(p);Z1.push(new i(e,new J1({color:v.connectorColor,dim:v.connectorDim}))),k.push(new y1({text:new i("",void 0,Z1)}))}let b=[],d=this.props.currentThreadID===H.id?new i("(current) ",new J1({color:D1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new i("(visited) ",new J1({color:L.foreground,dim:!0})):null;if(d)b.push(new y1({text:d}));if(T){if(T.state==="active"&&(T.interactionState==="tool-running"||T.interactionState===!1))b.push(new Ny1),b.push(new X0({width:1}))}let m=H.title;if(H.relationshipType==="fork"){let Z1=m.match(/^Forked\((\d+)\): /);if(Z1)m=m.slice(Z1[0].length);else while(m.startsWith("Forked: "))m=m.slice(8);b.push(new y1({text:new i("[fork] ",new J1({color:D1.blue}))}))}else if(y)b.push(new y1({text:new i("[handoff] ",new J1({color:D1.index(208)}))}));if(b.push(new e6({child:new y1({text:new i(m,new J1({color:E})),overflow:"ellipsis",maxLines:1})})),b.push(new X0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let Z1=z?{success:I,warning:I,destructive:I}:L;b.push(...CL8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,Z1)),b.push(new X0({width:2}))}return b.push(P(H.description.timeAgo,V)),new l0({decoration:A?{color:A}:void 0,padding:F0.symmetric(2,0),child:new T6({children:[...k,...b]})})}})}}function tY6(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/60000),G=Math.floor(Y/3600000),Z=Math.floor(Y/86400000);if(X<1)return"just now";if(X<60)return`${X}m ago`;if(G<24)return`${G}h ago`;if(Z<7)return`${Z}d ago`;return J.toLocaleDateString()}class My1 extends I6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((G,Z)=>Z.pubDate.getTime()-G.pubDate.getTime()),Y=Math.max(0,...Q.map((G)=>tY6(G.pubDate).length));return new rY({items:Q,getLabel:(G)=>G.title,onAccept:(G)=>this.props.onSelect?.(G),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(G,Z,V,q)=>{let K=G6.of(q),{colors:W}=K,H=Z?D1.yellow:void 0,z=Z?D1.black:W.foreground,U=D1.index(8),D=G.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new X0({width:A,child:T6.end([new y1({text:new i(L,new J1({color:U}))})])});return new l0({decoration:H?{color:H}:void 0,padding:F0.symmetric(2,0),child:new T6({children:[new e6({child:new y1({text:new i(G.title,new J1({color:z})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new y1({text:new i(D,new J1({color:U})),maxLines:1}),new X0({width:2}),M(tY6(G.pubDate),Y)]})})}})}}class Ly1 extends I6{props;constructor(J){super();this.props=J}build(){return new x4({child:new y1({text:new i("",void 0,[new i(`Forked to new thread:
|
|
4657
4657
|
|
|
4658
4658
|
`,new J1({color:D1.white,dim:!0})),new i(`"${this.props.newThreadTitle||"Untitled"}"`,new J1({color:D1.white}))]),textAlign:"center"})})}}z0();class eY6 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){x.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){x.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){if(J.length===0)return null;if(J.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(J))return"Label must be lowercase alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null}buildItemsWithCreateOption(){let J=this.widget.props.currentLabels||[],Y=[...this.labels.filter((X)=>!J.includes(X.name))];if(this.currentQuery.trim().length>0&&!this.isLoading){let X=this.currentQuery.trim().toLowerCase(),G=this.labels.some((V)=>V.name===X),Z=J.includes(X);if(!G&&!Z&&this.isValidLabelName(X))Y.unshift({id:"__create__",name:X,createdAt:"",__isCreateMarker:!0})}return Y}build(J){let Q=G6.of(J),{colors:Y}=Q,X=this.currentQuery.trim().toLowerCase(),G=X.length>0?this.getValidationError(X):null;return new rY({title:"Add Label",items:this.buildItemsWithCreateOption(),getLabel:(Z)=>Z.name,onAccept:(Z)=>{this.widget.props.onSelect(Z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:G||"Type to create a new label",renderItem:(Z,V,q,K)=>{let W=V?D1.yellow:void 0,H=V?D1.black:Y.foreground;if("__isCreateMarker"in Z&&Z.__isCreateMarker)return new l0({decoration:W?{color:W}:void 0,padding:F0.symmetric(2,0),child:new y1({text:new i("",void 0,[new i("Create: ",new J1({color:H})),new i(Z.name,new J1({color:H,bold:!0}))])})});return new l0({decoration:W?{color:W}:void 0,padding:F0.symmetric(2,0),child:new y1({text:new i(Z.name,new J1({color:H}))})})},filterItem:(Z,V)=>{let q=this.currentQuery;if(this.currentQuery=V,q!==V)this.setState();if("__isCreateMarker"in Z&&Z.__isCreateMarker)return!0;let W=V.trim().toLowerCase();return W.length===0||Z.name.includes(W)}})}}class Ay1 extends c0{props;constructor(J){super();this.props=J}createState(){return new eY6}}class sK extends c0{props;constructor(J){super();this.props=J}createState(){return new JX6}}class JX6 extends p0{_spinner=new fZ;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=G6.of(J),{colors:Y}=Q,X=P4.all(new F4(Y.foreground,1,"solid")),G=this._spinner.toBraille(),Z=new y1({textAlign:"center",text:new i("",void 0,[new i(G,new J1({color:D1.yellow})),new i(" ",void 0),new i(this.widget.props.message,new J1({color:Y.foreground}))])}),q=[new e6({child:new b0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)q.push(new X0({height:2,child:new l0({padding:F0.symmetric(2,0),child:new y1({text:new i("",new J1({dim:!0}),[new i("Press ",new J1({color:Y.foreground})),new i("Esc",new J1({color:Y.info})),new i(" to cancel",new J1({color:Y.foreground}))])})})}));let K=new l0({decoration:new K8(D1.default(),X),child:new X0({width:60,height:7,child:new b0({mainAxisAlignment:"start",children:q})})});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 xV extends c0{props;constructor(J){super();this.props=J}createState(){return new QX6}}class QX6 extends p0{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof kV}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=H91(Q);return{title:W.title,type:W.type,description:W.description}})(),X=Y.type==="error"?D1.red:D1.yellow,G=P4.all(new F4(D1.default(),1,"solid")),Z=new l0({padding:F0.symmetric(1,0),child:new y1({text:new i(Y.title,new J1({color:X,bold:!0}))})}),V=this.isWidgetMessage(Q)?Q.widget:new y1({text:new i(Y.description,new J1({color:D1.default()})),selectable:!0}),q=new e6({child:new UO({child:new l0({padding:F0.symmetric(1,0),child:V})})}),K=new l0({padding:F0.symmetric(1,0),child:new y1({text:this.widget.props.onRetry?new i("",void 0,[new i("Press ",new J1({color:D1.default(),dim:!0})),new i("R",new J1({color:D1.yellow})),new i(" to retry, ",new J1({color:D1.default(),dim:!0})),new i("Esc",new J1({color:D1.yellow})),new i(" to cancel",new J1({color:D1.default(),dim:!0}))]):new i("Press any key to close",new J1({color:D1.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 l0({decoration:{border:G,color:D1.default()},padding:F0.all(1),child:new b0({mainAxisAlignment:"center",children:[Z,new X0({height:1}),q,K]})})})}}class Oy1 extends I6{build(){return new x4({child:new y1({text:new i("",void 0,[new i(`✓ Thread Shared
|
|
4659
4659
|
|
|
@@ -4752,7 +4752,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
4752
4752
|
`)?`${q}...`:G,W=new J1({color:D1.index(8)}),H=[new i(K,W)];if(V>0){let z=new J1({color:Y.success});for(let U=1;U<=V;U++)H.push(new i(" ")),H.push(new i(`[${U}]`,z))}return new q6({padding:F0.only({bottom:0}),child:new T6({crossAxisAlignment:"start",children:[new q6({padding:F0.only({right:1}),child:new y1({text:new i("•",new J1({color:D1.index(8)}))})}),new e6({child:new y1({text:new i("",void 0,H)})})]})})}}class ey1 extends c0{createState(){return new QG6}}class QG6 extends p0{_animationTimer;_visible=!0;initState(){super.initState(),this._startAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._visible=!this._visible})},500)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=new J1({color:D1.red}),Y=new J1({color:this._visible?D1.red:D1.transparent()});return new T6({children:[new y1({text:new i("⏺",Y)}),new X0({width:1}),new y1({text:new i("Replay",Q)})]})}}class Jx1 extends I6{entry;width;constructor({key:J,entry:Q,width:Y}){super({key:J});this.entry=Q,this.width=Y}build(J){let Y=G6.of(J).colors.mutedForeground,X=this.entry,G=X.authors[0]?.name||"Community";if(G.includes("@"))G=G.split("@")[0]??G;let Z=" · ",V=50,q=this.truncateToWidth(X.title,V),K=`${Z}${q}`,W=Math.max(1,this.width-K.length-2),H=X.description.replace(/\s+/g," ").trim(),z=`@${G}: ${H}`,U=this.truncateToWidth(z,W),D=new y1({text:new i(U,new J1({color:Y,dim:!0}))}),M=new y1({text:new i(K,new J1({color:Y,dim:!0}))});return new F8({onClick:()=>FQ(J,X.link),cursor:"pointer",child:new X0({width:this.width,height:1,child:new q6({padding:F0.horizontal(1),child:new T6({children:[new e6({child:new Yu(new X0({width:W,height:1,child:D}))}),M]})})})})}truncateToWidth(J,Q){if(J.length<=Q)return J;return J.slice(0,Q-1)+"…"}}o0();function gA8(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/3600000),G=Math.floor(X/24),Z=Math.floor(G/7),V=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`${V}mo ago`}class Qx1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList().subscribe((G)=>{X.unsubscribe(),Y(G)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(Y6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((X)=>{if(!Q.trim())return!0;let G=X.title?.toLowerCase()||"untitled",Z=X.id.toLowerCase(),V=Q.toLowerCase();return G.includes(V)||Z.includes(V)}).map((X)=>{let G=new Date(X.userLastInteractedAt),Z=gA8(G),V=X.id.slice(-8),q=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:Z,title:X.title||"Untitled",shortThreadID:V},diffStats:X.summaryStats?.diffStats,workspaceURI:q,parentRelationships:X.parentRelationships}})}}z0();m8();class Yx1{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new E7;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){x.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){x.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(AM()).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 YG6(J,Q){switch(J){case"update-available":return[new i("A newer Amp is available. Run ",new J1({color:Q.foreground,dim:!0})),new i("amp update",new J1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new i("Update complete, run ",new J1({color:Q.foreground,dim:!0})),new i("amp update",new J1({color:Q.warning})),new i(" to see warnings",new J1({color:Q.foreground,dim:!0}))];case"update-error":return[new i("Update failed, run ",new J1({color:Q.foreground,dim:!0})),new i("amp update",new J1({color:Q.warning})),new i(" to see warnings",new J1({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function cA8(J){return new Promise((Q)=>{uA8("git",["branch","--show-current"],{cwd:J},(Y,X)=>{if(Y){Q(null);return}let G=X.trim();Q(G||null)})})}class WG6 extends c0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new Kx1}}class Kx1 extends p0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;isShowingContextDetailOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;paletteShowOptions=null;threadsForPicker=[];isLoadingThreads=!1;threadPreviewController=new Yx1;previewThread=null;planScrollController=(()=>{let J=new E7;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new E7;return J.followMode=!1,J})();filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new S8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new S8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;threadFeedReader=null;currentThreadFeedEntry=null;threadFeedEntries=[];threadFeedSubscription=null;threadFeedRotationTimer=null;threadFeedHidden=!1;threadFeedTickerQueue=[];hasSubmittedFirstMessage=!1;currentUserInfo=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;previousThreadIdForHint=null;pendingMCPServers=[];mcpTrustSubscription=null;mcpServers=[];mcpServersSubscription=null;cacheTimerState=null;cacheTimerSubscription=null;agentModeController=null;freeTierStatus=void 0;agentModePulseSeq=0;agentModeSlideProgress=null;agentModeSlideTimer=null;updateState="hidden";updateServiceSubscription=null;toastController=new rS1;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];async initThreadFeed(){let J=await F6(this.widget.dependencies.configService.config);if(J.settings["feed.enabled"]===!1)this.threadFeedHidden=!0;let Q=J.settings.url,Y=Q.includes("localhost")||Q.includes("127.0.0.1");try{let V=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService});if(V.ok){let q=V.result,K="user"in q?q.user:q;this.currentUserInfo={username:K.username??void 0,displayName:K.displayName??void 0};let W="ffe10a0c-6c42-41ce-a3a6-38990fd6caf8";if(!Y&&q.team?.id!==W)return}else return}catch(V){x.debug("Failed to fetch user info for thread feed filtering",V);return}let X="/threads.rss",G=async(V,q)=>{let K=V instanceof Request?V.url:V.toString();return $J(K,q,this.widget.dependencies.configService)},Z=Ko0();Z.get("entries").then((V)=>{if(V){let q=this.filterEntries(V);if(this.threadFeedEntries=q,q.length>0&&!this.currentThreadFeedEntry){let K=[...q].sort((H,z)=>z.pubDate.getTime()-H.pubDate.getTime());this.threadFeedTickerQueue=[...K,...this.threadFeedTickerQueue];let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}),this.threadFeedReader=new zS1(Z,G,{url:X}),this.threadFeedSubscription=this.threadFeedReader.stream().subscribe({next:(V)=>{try{let q=this.filterEntries(V);if(q.length>0){this.threadFeedEntries=[...q,...this.threadFeedEntries];let K=[...q].sort((W,H)=>H.pubDate.getTime()-W.pubDate.getTime());if(this.threadFeedTickerQueue=[...K,...this.threadFeedTickerQueue],!this.currentThreadFeedEntry){let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}catch(q){x.error("Thread feed: error in next handler",q)}},error:(V)=>{x.error("Thread feed error:",V)}}),this.resetThreadFeedRotation()}filterEntries(J){if(!this.currentUserInfo)return J;let{username:Q,displayName:Y}=this.currentUserInfo;return J.filter((X)=>{return!X.authors.some((G)=>{let Z=G.name;if(!Z)return!1;return Q&&Z===Q||Y&&Z===Y||Q&&Z.includes(Q)})})}rotateThreadFeed(){if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);this.threadFeedRotationTimer=setInterval(()=>{let J=this.getNextFeedEntry();if(J)this.setState(()=>{this.currentThreadFeedEntry=J})},30000)}resetThreadFeedRotation(){this.rotateThreadFeed()}getNextFeedEntry(){if(this.threadFeedTickerQueue.length>0)return this.threadFeedTickerQueue.shift();return null}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.worker.thread.id;this.recordNavigation(J);let Q=await this.widget.dependencies.startNewThread();return this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,this.widget.dependencies.switchWorker(Q),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.previousThreadIdForHint=J}),Q};async startReplay(){let J=this.widget.dependencies.replayMode;if(!J)return;let{thread:Q,typingEnabled:Y,baseWpm:X}=J,G=Q.messages;for(let Z=0;Z<G.length;Z++){if(this.replayAbortController.signal.aborted)break;let V=G[Z];if(!V)continue;if(Z>0)await this.replaySleep(J.messageDelayMs);if(V.role==="user"&&Y){let W=V.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
|
|
4753
4753
|
`);if(W)await this.replayTypeMessage(W,X)}if(V.role==="assistant"){let W=V.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={...V,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let D=J.thread.id;this.getMessageScrollController(D).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),V]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,V],this.textController.clear()});let q=J.thread.id;this.getMessageScrollController(q).scrollToBottom()}await this.replaySleep(J.exitDelayMs),Z9.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Y=J.split(/(?<=\s)/),X=60000/Q;for(let G of Y){if(this.replayAbortController.signal.aborted)break;if(this.looksLikePastedContent(G.trim())){await this.replaySleep(150),this.textController.text=this.textController.text+G,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{}),await this.replaySleep(300);continue}let Z=X/G.length;for(let V of G){this.textController.text=this.textController.text+V,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let q=0.8+Math.random()*0.4,K=Z*q;await this.replaySleep(K)}}}looksLikePastedContent(J){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(J))return!0;if(J.startsWith("/")&&J.length>10)return!0;if(/^[a-z]:\\/i.test(J))return!0;if(/^[a-f0-9]{7,40}$/i.test(J))return!0;if(/^T-[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(J))return!0;return!1}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return this.agentModeController?.getEffectiveMode()??"smart"}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let 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 i(this.submitDisabledHint,new J1({color:J.foreground,dim:!0}));if(this.isExiting)return new i("Exiting...",new J1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new i("",void 0,[new i("Ctrl+C",new J1({color:Q.keybind})),new i(" again to exit",new J1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new i("",void 0,[new i("Esc",new J1({color:Q.keybind})),new i(" again to clear input",new J1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new i("",void 0,[new i("Escape",new J1({color:Q.keybind})),new i(" to close help",new J1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let G=this.getEffectiveAgentMode(),Z=qx1(G);return new i("",void 0,[new i("Images aren't supported in ",new J1({color:J.warning,dim:!1})),new i(G,new J1({color:Z})),new i(" mode.",new J1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new i("",void 0,[new i("Esc",new J1({color:Q.keybind})),new i(" again to cancel",new J1({color:J.foreground,dim:!0}))]);return new i("",void 0,[new i("Esc",new J1({color:Q.keybind})),new i(" to cancel",new J1({color:J.foreground,dim:!0}))])}if(this.statusMessage)return new i(this.statusMessage,new J1({color:J.foreground,dim:!0}));let Y=YG6(this.updateState,J);if(Y)return new i("",void 0,Y);let X=this.widget.dependencies.worker.thread;if(X.agentMode==="plan"&&ZO(X))return new i("",void 0,[new i("Ctrl+O",new J1({color:Q.keybind})),new i(" → Execute Plan",new J1({color:J.foreground,dim:!0}))]);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker: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){x.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((V)=>V===J);if(Z===void 0||Z<=0)return;try{let V=await z2.getOrCreateForThread(Y,G),q=await rT(V,X,Z-1);await this.switchToExistingThread(q)}catch(V){x.error("Failed to fork thread:",V),this.showErrorMessage(`Failed to fork thread: ${V}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Y,worker:X}=this.widget.dependencies,G=Y.mainThread;if(!G)return;let Z=G.messages.findIndex((V)=>V.messageId!==void 0&&V.messageId===J.messageId);if(Z===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let V=$N(Q);if(V)await X.handle({type:"thread:truncate",fromIndex:Z}),this.invokeBashCommand(V.cmd,{visibility:V.visibility});else{let q=[{type:"text",text:Q}];if(this.imageAttachments.length>0)q.push(...this.imageAttachments);let K={content:q,agentMode:G.agentMode},W=Z===0;if(G.agentMode&&!W&&K.agentMode!==G.agentMode){x.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(V){x.error("Failed to edit message:",V)}};getAffectedFiles=async(J)=>{let{worker:Q}=this.widget.dependencies;try{return(await Q.getFilesAffectedByTruncation(J)).map(n2)}catch(Y){return x.error("Failed to get affected files:",Y),[]}};textController=new vZ;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new E7);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let G=this.searchElementTreeByKey(X,Q);if(G)return G}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{this.toastController.show("Selection copied to clipboard","success",2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Y=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Y}`:"";process.stdout.write(Ij1(X))}}_handleTextCopy(J){if(J&&J.length>0)this.toastController.show("Selection copied to clipboard","success",2000)}textFieldKey=new r7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Y=$N(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}),r8.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Q)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.showCommandPalette({type:"standalone",commandId:"continue",onSubmit:()=>{this.threadPreviewController.clear(),this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null}),r8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};showCommandPalette(J){if(this.setState(()=>{this.isShowingPalette=!this.isShowingPalette,this.paletteShowOptions=J??null}),this.isShowingPalette)this.loadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new Ey1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.widget.dependencies.isDogfooding,this.paletteConfig)}return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Ry1(this.widget.dependencies.fuzzyServer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})};getCommandPaletteContext=(J)=>{let{threadState:Q,recentThreadIDs:Y}=this.widget.dependencies;if(!Q.mainThread)return null;let X=h0.file(process.cwd()),G=E6(X);return{recentThreadIDs:Y,currentThreadID:Q.mainThread.id,context:J,worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let Z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),Z},setImageAttachments:(Z)=>{this.setState(()=>{this.imageAttachments=Z})},editorDispatch:(Z)=>{switch(Z.type){case"set-input":this.textController.clear(),this.textController.insertText(Z.input);break;case"insert-text":this.textController.insertText(Z.text);break;case"clear":this.textController.clear();break}},submitMessage:(Z)=>{return this.proceedWithUserMessage(Z)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,mcpService:this.widget.dependencies.mcpService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus?.canUseAmpFree??!1,switchToThread:async(Z)=>{return await this.switchToExistingThread(Z),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(Z,V,q)=>{let K=this.widget.dependencies.threadState.mainThread?.id;if(!K)throw Error("No active thread");let W=setTimeout(()=>{q.throwIfAborted()},60000);try{let H=await this.widget.dependencies.threadService.generateHandoffPrompt(K,Z,V,this.widget.dependencies.configService,q);return clearTimeout(W),H}catch(H){throw clearTimeout(W),H}},handleHandoff:async(Z,V)=>{let{goal:q,generatedPrompt:K,images:W}=V;if(!q&&!K)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let H=this.widget.dependencies.threadState.mainThread?.id;if(!H)return{ok:!1,error:Error("No active thread")};let z=setTimeout(()=>Z.abort(new V51("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let U=await this.widget.dependencies.threadService.createHandoffThread(H,{goal:q,generatedPrompt:K,images:W},this.widget.dependencies.configService,Z.signal);return clearTimeout(z),await this.switchToExistingThread(U),{ok:!0}}catch(U){if(clearTimeout(z),U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")))throw Z.signal.reason;throw U}}catch(H){return x.error("Failed to create handoff thread",H),{ok:!1,error:H instanceof Error?H:Error(String(H))}}},getGuidanceFiles:async(Z)=>{if(!Q.mainThread)return[];return(await $t({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,Z)).map((q)=>({uri:q.uri,type:q.type}))},openIdePicker:()=>{this.openIdePicker()},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(Z)=>{this.agentModeController?.setMode(Z)},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,handleExecutePlan:async()=>{try{let Z=Q.mainThread?.id;if(!Z){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let V=await this.widget.dependencies.threadService.createPlanExecutionThread(Z,"smart");await this.switchToExistingThread(V)}catch(Z){x.error("Failed to execute plan",Z),this.setState(()=>{this.displayMessage=Error(`Failed to execute plan: ${Z instanceof Error?Z.message:String(Z)}`)})}},planFileManager:this.widget.dependencies.planFileManager,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:G,threadViewStates:this.widget.dependencies.workerController.threadViewStates,currentThreadFeedEntry:this.currentThreadFeedEntry,threadFeedEntries:this.threadFeedEntries,threadFeedHidden:this.threadFeedHidden,setThreadFeedHidden:(Z)=>{this.setState(()=>{this.threadFeedHidden=Z})},showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:this.widget.dependencies.features??[],showStatusMessage:(Z,V=2000)=>{if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=Z}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},V)}}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new Qx1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await cA8(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===ZN).subscribe({next:(V)=>{this.setState(()=>{if(this.bashInvocations.find((K)=>K.id===X))this.bashInvocations=this.bashInvocations.map((K)=>K.id===X?{...K,toolRun:V}:K);else{let K={id:X,args:G,toolRun:V,startTime:Y,abortController:Z,hidden:Q===ZN};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})};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0})};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.agentModeController.toggle())this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};startAgentModeSlide=()=>{if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer);this.setState(()=>{this.agentModeSlideProgress=0});let J=800,Q=16,Y=Q/J;this.agentModeSlideTimer=setInterval(()=>{this.setState(()=>{if(this.agentModeSlideProgress!==null){if(this.agentModeSlideProgress=Math.min(1,this.agentModeSlideProgress+Y),this.agentModeSlideProgress>=1){if(this.agentModeSlideProgress=null,this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null}}})},Q)};handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!Ky(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=BU)return!1;let Y=nC(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)})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleCloseMysteryModal=()=>{this.setState(()=>{this.isShowingMysteriousMessageModal=!1})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(!Q.ok)x.error("Failed to destruct mysterious message",Q.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Q)=>{x.error("Failed to destruct mysterious message",Q)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Y,unlink:X,rmdir:G,writeFile:Z}=await import("node:fs/promises"),{tmpdir:V}=await import("node:os"),q=await import("node:path");try{let K=await Q(q.join(V(),"amp-edit-")),W=q.join(K,"message.amp.md");await Z(W,J,"utf-8"),await CV(W);try{let H=await Y(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")x.error("Failed to read temporary file",H)}try{await X(W),await G(K)}catch(H){x.warn("Failed to clean up temporary file",H)}}catch(K){x.error("Error opening editor:",K)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=$N(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{this.setState(()=>{})};initState(){if(tX.getInstance().interceptConsole(),this.freeTierStatus=this.widget.dependencies.freeTierStatus,this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();Z9.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),Z9.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),Z9.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Y)=>{r8.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})})}),F6(this.widget.dependencies.configService.config).then((Y)=>{this.paletteConfig=Y,this.agentModeController=new MS1({initialCliMode:this.widget.dependencies.initialAgentMode,sessionState:this.widget.dependencies.sessionState??null,freeTierStatus:this.freeTierStatus?{canUseAmpFree:this.freeTierStatus.canUseAmpFree,eligible:this.freeTierStatus.eligible,workspaceAllowsAmpFree:this.freeTierStatus.workspaceAllowsAmpFree}:void 0,initialSettings:Y.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.getCurrentWorker()?.thread??this.widget.dependencies.worker.thread}),this.agentModeController.addListener(this.agentModeListener)}),this.updateGitBranch(),this.adSubscription=ij1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{let Y=this.agentModeController?.getMode();return(Y&&s9(Y)||this.randomAd===null)&&lj1(this.lastUserInteractionTime)}).subscribe({next:(Y)=>{if(Y){let X=pA8(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (x51(),y51)).then(({recordAdEvent:G})=>{let Z=this.widget.dependencies.worker.thread,V=Z.messages[Z.messages.length-1];G("viewed",{adId:Y.id,advertiserId:Y.advertiserId,threadId:Z.id,messageId:V?.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}),r8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}});let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Y)=>{this.setState(()=>{this.pendingMCPServers=Y})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((Y)=>{this.setState(()=>{this.mcpServers=Y})}),this.cacheTimerSubscription=this.widget.dependencies.worker.cacheTimer.subscribe((Y)=>{this.setState(()=>{this.cacheTimerState=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){x.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}]}}),x.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),x.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.mysteriousMessageSubscription=Z81(this.widget.dependencies.configService).pipe(d5((Y)=>Y!=="pending"),Y6((Y)=>$81(Y)?Y.mysteriousMessage??null:null),w4((Y,X)=>Y?.id===X?.id)).subscribe((Y)=>{this.setState(()=>{if(Y?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=Y,Y&&!this.mysterySequenceManager)this.mysterySequenceManager=new J91(new Map([[new e81(Kx1.MYSTERY_SEQUENCE),new Fu]])),this.mysteryKeyInterceptorUnsubscribe=Z9.instance.addKeyInterceptor((X)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let G=this.mysterySequenceManager.handleKeyEvent(X);if(G.consumed){if(G.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=G.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!Y)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Y)=>{let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initThreadFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.cacheTimerSubscription)this.cacheTimerSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.threadFeedSubscription)this.threadFeedSubscription.unsubscribe();if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null;if(this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(Ij1("")),this.shouldUseProgressBar())process.stdout.write(h56())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((q)=>q.type==="toolResult").map((q)=>({toolUse:q.toolUse,toolRun:q.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((q)=>q.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??[]:[],V=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:V}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){x.error("No current tool confirmation found");return}let Y=Q.tools[0]?.useBlock;if(!Y){x.error("No tool use block found in confirmation");return}if(J==="allow-all-session")T$("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 x.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")||[],V=[...G,...Z];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",V,"global")}if(J==="connect-github"){let G=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await FQ(this.context,G);return}if(J==="disable-librarian"){let G=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!G.includes(DX))await this.widget.dependencies.settingsStorage.set("tools.disable",[...G,DX],"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 z2.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(G);else await this.widget.dependencies.worker.handle(G)}catch(G){x.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.agentModeController?.setMode("smart"),this.setState(()=>{this.dismissedEphemeralErrorKey=null}),c41({agentMode:"smart"}),await this.startAndSwitchToNewThread();break}case"handoff":{if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);this.showCommandPalette({type:"normal",commandId:"handoff"});break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Q}=this.widget.dependencies;await J.deny();try{await CV(Q.getSettingsFilePath())}catch(Y){let X=Y instanceof Error?Y.message:String(Y);await this.showErrorMessage(`Failed to open settings: ${X}`)}};cancelStreamingMessage=async()=>{await z2.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{x.info(`[switchToExistingThread] Switching to thread: ${J}`);let X=await this.widget.dependencies.switchToThread(J);if(x.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${X.thread.agentMode}`),this.widget.dependencies.worker=X,this.widget.dependencies.threadID=X.thread.id,this.widget.dependencies.switchWorker(X),x.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null),X.thread.draft)if(x.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof X.thread.draft==="string")this.textController.insertText(X.thread.draft);else{let G=X.thread.draft.filter((q)=>q.type==="text"),Z=X.thread.draft.filter((q)=>q.type==="image"),V=G.map((q)=>q.text).join(`
|
|
4754
4754
|
`);if(V)this.textController.insertText(V);if(Z.length>0)this.setState(()=>{this.imageAttachments=Z})}}catch(X){throw x.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=s2(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(Y)this.startAgentModeSlide();if(await Q.handle({type:"user:message",message:{content:G,agentMode:X}}),Y)c41({agentMode:X});this.scrollMessageViewToBottom(),this.setState(()=>{if(this.imageAttachments=[],!this.hasSubmittedFirstMessage)this.hasSubmittedFirstMessage=!0}),r8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((X)=>X.type==="handoff"&&X.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();c41({agentMode:Q}).catch((Y)=>{x.warn("Failed to save session state on exit:",Y)}).finally(()=>{Z9.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=dA8();if(J===Q)return"~";if(J.startsWith(Q+yu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(yu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(yu.sep),"…",Q.slice(-2).join(yu.sep)].join(yu.sep)}build(J){let Q=m4.of(J),Y=G6.of(J),X=Y.base;this.themeColors=X;let{colors:G,app:Z}=Y;this.themeApp=Z;let V=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,q=V.thread.agentMode&&s9(V.thread.agentMode),K=q&&this.randomAd!==null,W=!q&&this.currentThreadFeedEntry!==null&&!this.threadFeedHidden,H=Boolean(K),{threadState:z}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),D=this.widget.dependencies.replayMode,M=Boolean(D),L=z.items,A=z.mainThread||void 0,E=z.subagentToolsByParentID,I=z.todosList;if(M){let n6={...D.thread,messages:this.replayDisplayedMessages};L=Wj(n6).items,A=n6,E={};let r6=MI({messages:this.replayDisplayedMessages});I=Array.isArray(r6)?r6:[]}let P=A?.id,T=A,k=M?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),y=(n6)=>new X51({key:new r7(`preview-message-view-${n6.id}`),items:Wj(n6).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:n6,focusNode:new S8({debugLabel:"PreviewFocus"})}),v=this.previewThread,b=v?v.messages.length>2000?new b0({mainAxisSize:"max",children:[new e6({child:new X0}),new q6({padding:F0.all(2),child:new x4({child:new y1({text:new i("Thread too long for preview",new J1({color:G.mutedForeground,dim:!0}))})})})]}):y(v):k?new $51({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal}):new X51({key:P?new r7(`message-view-${P}`):void 0,items:L,subagentToolsByParentID:E,controller:P?this.getMessageScrollController(P):new E7,autofocus:!1,onCopy:M?void 0:this._handleTextCopy.bind(this),thread:T,onMessageEditSubmit:M?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:M?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:M?void 0:this.forkMessage,getAffectedFiles:M?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),d=Math.max(Math.floor(Q.size.height*0.4),12),m=this.getCurrentEphemeralError(),n=Q.size.width<40,Z1=z.mainThread?uN0(z.mainThread):void 0,t=Iz(J),p=this.buildBottomWidget(m,U,G,Y,z,I,d,H,M,Z1,this.cacheTimerState??void 0,Q,t),e=new M91({threadViewState:z.viewState,threadTokenUsage:Z1,threadID:P??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,mcpServers:this.mcpServers,isNarrow:n,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),F1=new N91({bashInvocations:this.bashInvocations}),K1=[];if(W&&this.currentThreadFeedEntry)K1.push(new Jx1({entry:this.currentThreadFeedEntry,width:Q.size.width}));let o=this.getEffectiveAgentMode(),r=this.currentShellModeStatus,l=qx1(o),W1=!r?o.length+1:0,_1=Q.capabilities.animationSupport,s=_1==="disabled"?0:_1==="slow"?30:60,m1=kq(o)?.uiHints?.fasterAnimation?3:1,j1=s>0&&this.agentModePulseSeq>0?new d9({children:[p,new a5({top:0,left:1,right:1,height:1,child:new oy1({color:l,trigger:this.agentModePulseSeq,fps:s,speed:m1,leftOffset:W1})})]}):p;K1.push(new e6({child:b}),F1);let T0=new d9({children:[new b0({mainAxisSize:"min",children:[K?new Hy1({ad:this.randomAd,onButtonClick:async()=>{let n6=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (x51(),y51)).then(({recordAdEvent:I9})=>{let R4=this.widget.dependencies.worker.thread,EJ=R4.messages[R4.messages.length-1];I9("clicked",{adId:n6.id,advertiserId:n6.advertiserId,threadId:R4.id,messageId:EJ?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:n6.metadata?.matchType,matchedPatterns:n6.metadata?.matchedPatterns,candidateAdPoolCount:n6.metadata?.candidateAdPoolCount,clientRegion:n6.metadata?.clientRegion})});if(!await FQ(this.context,n6.shortDestinationUrl)){let R4=Z9.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:R4,url:n6.shortDestinationUrl}})}}}):new X0({height:0}),new l0({constraints:new A6(0,Q.size.width,0,d),child:j1})]}),H?new a5({top:0,left:0,right:0,child:new FG6({userHeight:this.bottomGridUserHeight,maxHeight:d,onInitializeHeight:(n6)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(n6,d)})},onDrag:(n6)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(n6.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let r6=Math.floor(n6.localPosition.y)-this.bottomGridDragStartY,I9=Math.max(4,this.bottomGridDragStartHeight-r6),R4=Math.min(I9,d),EJ=Math.floor(R4);if(this.bottomGridUserHeight!==EJ)this.setState(()=>{this.bottomGridUserHeight=EJ})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new X0({height:0})]});K1.push(T0,new X0({height:1,child:new q6({padding:F0.horizontal(1),child:e})}));let C1=new b0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:K1}),z1=M&&D?.showIndicator!==!1?new d9({children:[C1,new a5({top:0,left:0,child:new ey1})]}):C1,Y1=new x8(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((r6)=>{x.error("Failed to mark message as interrupted:",r6)}),this.cancelStreamingMessage().catch((r6)=>{x.error("Failed to cancel streaming message:",r6)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return x.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),O1=new x8(()=>{return this.onExitPressed(),"handled"}),A1=new x8(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),R1=new x8(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),S1=new x8(()=>{return LJ.instance.toggleAll(),"handled"}),d1=new x8(()=>{return this.widget.dependencies.configService.getLatest().then((n6)=>{T$("internal.showCost",!(n6.settings["internal.showCost"]??!0))}),"handled"}),b1=new x8(()=>{return Z9.instance.toggleFrameStatsOverlay(),"handled"}),r1=new x8(()=>{return Z9.instance.tuiInstance.getScreen().markForRefresh(),r8.instance.requestFrame(),"handled"}),V0=new x8(()=>{return this.toggleAgentMode(),"handled"}),q0=new x8(()=>{let r6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:I9}=this.widget.dependencies,R4=I9.mainThread?.id;return R4?this.getMessageScrollController(R4):null})();if(r6){let I9=Math.max(Math.floor(Q.size.height*0.4),10),R4=Q.size.height-I9;r6.animatePageUp(R4,100)}return"handled"}),k0=new x8(()=>{let r6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:I9}=this.widget.dependencies,R4=I9.mainThread?.id;return R4?this.getMessageScrollController(R4):null})();if(r6){let I9=Math.max(Math.floor(Q.size.height*0.4),10),R4=Q.size.height-I9;r6.animatePageDown(R4,100)}return"handled"}),v6=new x8(()=>{let r6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:I9}=this.widget.dependencies,R4=I9.mainThread?.id;return R4?this.getMessageScrollController(R4):null})();if(r6)r6.animateTo(0,100);return"handled"}),c6=new x8(()=>{let r6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:I9}=this.widget.dependencies,R4=I9.mainThread?.id;return R4?this.getMessageScrollController(R4):null})();if(r6)r6.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),Z8=new x8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:n6}=this.widget.dependencies;if(!n6.mainThread?.messages.some((I9)=>I9.role==="user"||DI(I9)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),V9=new x8((n6)=>{if(n6.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),G5=new x8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return W91().then(async(n6)=>{if(n6)try{this.handleInsertImage(n6)}finally{try{let{unlink:r6}=await import("node:fs/promises");await r6(n6)}catch{}}}),"handled"}),E0=new Map([[z4.ctrl("c"),new $u],[z4.ctrl("l"),new Hu],[z4.ctrl("o"),new $91],[z4.ctrl("v"),new Gu],[z4.alt("s"),new sC],[z4.ctrl("s"),new sC],[z4.alt("p"),new Wu],[z4.ctrl("r"),new qu],[z4.alt("d"),new Ku],[z4.ctrl("t"),new zu],[z4.key("PageUp"),new Y91],[z4.key("PageDown"),new X91],[z4.key("Home"),new G91],[z4.key("End"),new Z91],[z4.key("Escape"),new Zu],[z4.ctrl("p"),new tC("previous")],[z4.ctrl("n"),new tC("next")],[z4.key("Tab"),new Uu]]);if(!i3())E0.set(z4.key("ArrowUp"),new Uu);if(!1)E0.set(z4.alt("c"),new Vu);let V4=new x8(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),W8=new x8(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),s8=new x8(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),K7=new Map([[Zu,Y1],[Hu,r1],[sC,V0],[$91,V4],[Gu,G5],[Vu,A1],[r81,R1],[qu,S1],[Ku,d1],[Wu,b1],[zu,W8],[$u,O1],[Y91,q0],[X91,k0],[G91,v6],[Z91,c6],[Uu,Z8],[tC,V9],[Fu,s8]]),t8=[z1];if(this.isShowingConsoleOverlay)t8.push(new jy1);if(this.isShowingHelp&&this.paletteConfig)t8.push(new yy1({commands:this.getPaletteCommands().getAllCommands()}));if(this.isShowingMCPStatusModal)t8.push(new Sk1({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)t8.push(new ty1({message:this.mysteriousMessage,onClose:this.handleCloseMysteryModal,onDestruct:this.handleDestructMysteriousMessage}));if(this.adActionModal)t8.push(new zy1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(n6)=>{let r6=this.adActionModal.url;if(n6==="copy")try{await Z9.instance.tuiInstance.clipboard.writeText(r6),this.setState(()=>{this.displayMessage=new YG("Link copied to clipboard")})}catch(I9){x.error("Failed to copy to clipboard",{error:I9}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:n6}=this.widget.dependencies;t8.push(new ry1({servers:this.pendingMCPServers,onAlwaysTrust:n6.trustAlways.bind(n6),onTrustOnce:n6.trustOnce.bind(n6),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:n6.deny.bind(n6)}))}if(this.isShowingFileChangesOverlay)t8.push(new V_1({threadData:z}));if(this.isShowingCostBreakdownOverlay&&z.mainThread)t8.push(new _y1({thread:z.mainThread}));if(this.isShowingContextDetailOverlay)t8.push(new Sy1({thread:z.mainThread??void 0,tokenUsage:Z1??void 0,cacheTimerState:this.cacheTimerState??void 0,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})}}));if(this.isShowingConfirmationOverlay)t8.push(new Ty1({details:this.confirmationOverlayContent}));let W7=this.getCommandPaletteContext(J);if(W7&&this.isShowingPalette&&this.paletteConfig)t8.push(new x4({child:new l0({constraints:A6.loose(80,20),child:new Py1({commandContext:W7,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})})}));if(this.isShowingIdePicker)t8.push(new vy1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let m5=new d9({children:t8});if(this.isShowingJetBrainsInstaller)return new NO({child:new tQ({actions:K7,child:new _V({shortcuts:E0,debugLabel:"jetbrains-installer-shortcuts",child:new ay1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new Oz({controller:this.toastController,child:new NO({child:new sS1({controller:this.toastController,child:new tQ({actions:K7,child:new _V({shortcuts:E0,debugLabel:"main-app-shortcuts",child:m5})})})})})}buildScrollableTodoList(J,Q,Y){return new HG6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Y})}buildBottomWidget(J,Q,Y,X,G,Z,V,q,K,W,H,z,U){if(J)return new ky1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Cy1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new sy1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let D=U91(X),M=this.agentModeController?.isInRestrictedFreeMode()??!1,L=new SO({key:this.textFieldKey,controller:this.textController,triggers:K?[]:[new FN],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":M?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!M&&!this.isShowingStandalonePalette(),shellPromptRules:D,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker,clipboard:Z9.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,previousThreadId:this.previousThreadIdForHint&&(G.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let o=this.previousThreadIdForHint;if(o)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${o} `},onDoubleAtTrigger:K?void 0:()=>{let o=this.textController.text,r=this.textController.cursorPosition,W1=o.slice(0,r).lastIndexOf("@@");this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:()=>{if(W1!==-1){let _1=this.textController.text,s=_1.slice(0,W1)+_1.slice(W1+2);this.textController.text=s,this.textController.cursorPosition=W1}},onSubmit:()=>{this.dismissPalette()},onCancel:()=>{this.dismissPalette()}})}}),A=G.mainThread?.queuedMessages??[],E=Array.isArray(Z)&&Z.length>0,I=Array.isArray(A)&&A.length>0,P=G.mainThread?.agentMode==="plan"&&ZO(G.mainThread),T,k;if(P){if(T=new Yu(new G51({thread:G.mainThread,onExecute:async()=>{let o=this.getCommandPaletteContext();if(o)await this.getPaletteCommands().execute("execute-plan",o,void 0,new AbortController)},onEdit:async()=>{try{let o=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:r}=await this.widget.dependencies.planFileManager.ensureSync(G.mainThread.id);Z9.instance.tuiInstance.suspend();let{execSync:l}=await import("child_process");l(`${o} "${r}"`,{stdio:"inherit"}),Z9.instance.tuiInstance.resume()}catch(o){x.error("Failed to edit plan",o),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:X}),{clipBehavior:"antiAlias"}),I)k=new k51({queuedMessages:A});else if(E)k=this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!M,X)}else T=I?new k51({queuedMessages:A}):void 0,k=E?this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!M,X):void 0;let y=[],v=this.currentShellModeStatus;if(v)y.push({child:new y1({text:new i(v==="hidden"?"shell mode (incognito)":"shell mode",new J1({color:v==="hidden"?X.app.shellModeHidden:X.app.shellMode}))}),position:"top-left"});let d=this.connectedClientsStatus&&this.connectedClientsStatus.enabled?this.connectedClientsStatusExpanded?(this.connectedClientsStatus?.clientID?.length??7)+3:3:0,m=this.agentModeController?.getVisibleModes()??[];if(!v&&m.length>1){let o=this.previewThread,r=o?o.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),l=qx1(r),W1=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,_1=s2(W1.thread)>0,s=this.agentModeSlideProgress!==null,m1,j1;if(s){m1="top-left";let C1=z.size.width-r.length-4-d;j1=Math.floor(this.agentModeSlideProgress*C1)}else if(_1)m1="top-right",j1=d;else m1="top-left",j1=void 0;if(o)y.push({child:new y1({text:new i(r,new J1({color:l}))}),position:m1,offsetX:j1});else{let T0=!_1&&!s,C1=new y1({text:new i(r,new J1({color:l}))});y.push({child:T0?new F8({child:C1,onClick:this.toggleAgentMode,cursor:"pointer"}):C1,position:m1,offsetX:j1})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let o=this.connectedClientsStatus,r=o.mode||"disconnected",l=!!o.errorMessage,W1=o.clientID||"unknown",_1,s;if(l)_1="●",s=D1.red;else if(r==="presence")_1="○",s=D1.yellow;else if(r==="connected"&&o.connected)_1="●",s=D1.green;else _1="○",s=D1.yellow;let m1=this.connectedClientsStatusExpanded?`${W1} ${_1}`:_1;y.push({child:new F8({child:new y1({text:new i(m1,new J1({color:s}))}),onClick:this.toggleConnectedClientsStatus,cursor:"pointer"}),position:"top-right",offsetX:-2})}let n=K?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:G.mainThread?.env?.initial.trees?.[0]?.uri,Z1;if(n)Z1=h0.parse(n).fsPath;else Z1=process.cwd();let t=this.toHomeRelative(Z1),p=this.shorten(t),e=!K&&this.currentGitBranch?`${p} (${this.currentGitBranch})`:p;y.push({child:new y1({text:new i(e,new J1({color:Y.foreground,dim:!0}))}),position:"bottom-right"});let F1=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(s2(F1.thread)>0&&!v){let o=[],r=new J1({color:Y.foreground,dim:!0}),l=new i(" · ",r);if(U&&G.mainThread){let W1=he(G.mainThread);if(W1>0)o.push(new i(SV(W1),r))}if(W){if(o.length>0)o.push(l);let W1=W.totalInputTokens/W.maxInputTokens,_1=Math.round(W1*100),s=Math.max(0,Math.min(_1,100)),m1=D91(W1,W.maxInputTokens),j1=r;if(m1==="danger")j1=new J1({color:Y.destructive});else if(m1==="warning")j1=new J1({color:Y.warning});else if(m1==="recommendation")j1=new J1({color:X.app.recommendation});o.push(new i(`${s}%`,j1))}if(U&&H){let W1=G.viewState.state==="active"&&G.viewState.inferenceState==="idle",_1=gY6(H,{isNarrow:!0,isIdle:W1});if(_1){if(o.length>0)o.push(l);let s=r;if(_1.urgency==="warning")s=new J1({color:Y.warning});o.push(new i(_1.text,s))}}if(o.length>0){let W1=new y1({text:new i("",void 0,o)});y.push({child:U?new F8({child:W1,onClick:this.showContextDetailOverlay,cursor:"pointer"}):W1,position:"top-left"})}}return new Y_1({leftChild:new e6({child:L}),rightChild1:T,rightChild2:k,maxHeight:V,overlayTexts:y,borderColor:M||!this.isTextfieldAndAutocompleteFocused?D1.index(8):void 0,hasBanner:q,userHeight:this.bottomGridUserHeight,onInitializeHeight:(o)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(o,V)})},onDrag:(o)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(o.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let r=Math.floor(o.localPosition.y)-this.bottomGridDragStartY,l=Math.max(4,this.bottomGridDragStartHeight-r),W1=Math.min(l,V),_1=Math.floor(W1);if(this.bottomGridUserHeight!==_1)this.setState(()=>{this.bottomGridUserHeight=_1})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!q})}}async function Wx1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)Z9.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let X=()=>null,Z=!1,V=new Bz(Z,1000,J.inspectorPort),q=J.features?.find((A)=>A.name==="amp-connect")?.enabled??!1,K=new Ky1({threadService:J.threadService,worker:J.worker,builder:(A,E,I,P,T,k)=>{if(X=T,J.threadDependencies&&q)NS1(J.threadDependencies,J.configService,T,P,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((b)=>{x.error("Failed to start automatic presence:",b)});let y=T(),v={...J,worker:y,threadID:y.thread.id};return new WG6({...v,threadState:E,workerController:I,switchWorker:P,getCurrentWorker:T,recentThreadIDs:k})}}),W=new X_1({configService:J.configService,child:K}),H=new kk1({configService:J.configService,child:W}),z=new dS1(H),U=new G6({data:eC.fromBaseTheme(xZ.default()),child:z});try{await gj1(U,{onRootElementMounted:(A)=>{if(x.info("TUI input ready for user interaction"),Z)V.start(A)}})}finally{if(Z)V.stop();if(J.threadDependencies&&q){let{stopGlobalSession:A}=await Promise.resolve().then(() => (DS1(),g36));A()}}let M=X()?.thread.id||J.threadID,L=await J.threadService.get(M);if(L&&L.messages.length>0){let A=`${J.ampURL.replace(/\/$/,"")}/threads/${M}`;$26(L,A,J.stdout)}}function qx1(J){let Y=kq(J)?.uiHints?.secondaryColor;if(Y)return D1.rgb(Y.r,Y.g,Y.b);return lA8(J)}class HG6 extends c0{props;constructor(J){super();this.props=J}createState(){return new zG6}}class zG6 extends p0{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 T6({crossAxisAlignment:"stretch",children:[new e6({child:new b5({controller:Y,autofocus:!1,child:new Wy1({todos:Q})})}),new B2({controller:Y,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:G,offset:Z}=Y,V=this.viewportHeight,q=G+V;return{totalContentHeight:Math.max(q,0),viewportHeight:Math.max(V,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 V of Z){if(V&&"size"in V){let K=V.size;if(typeof K?.height==="number"&&K.height>0)return K.height}let q=Q(V,G+1);if(q>0)return q}}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 FG6 extends I6{props;constructor(J){super();this.props=J}build(J){return new F8({child:new X0({height:1}),cursor:h9.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 lA8(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 D1.index(Y[X])}bj1();try{if(process.platform==="win32")await Promise.resolve().then(() => z6(kj(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){nZ.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
4755
|
-
`)}var gv1=bv1.join(BU0||bv1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function zP8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),V=Y||"Warning",q=!1;J.warn(Z,{name:V,code:X})}}function lZ(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")T$("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")T$("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")T$("model.sonnet",Q.useSonnet)}async function uv1(J){try{await KP8(bv1.dirname(gv1),{recursive:!0}),await WP8(gv1,J,"utf-8")}catch(Q){x.debug("Failed to save last thread ID",Q)}}async function FP8(){try{return(await mV6(gv1,"utf-8")).trim()}catch(J){return null}}var hV6=[{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??CZ,description:`Custom settings file path (overrides the default location ${CZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(x).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${dC1})`},{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:i3(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:HI.SMART.key,description:`Set the agent mode (${mG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:mG().map((J)=>J.mode)}],bV6=(J)=>("deprecated"in J)&&J.deprecated===!0,UP8=(J)=>("hidden"in J)&&J.hidden===!0,BP8=(J)=>("default"in J),NP8=(J)=>("default"in J)?J.default:void 0;function DP8(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((q)=>Y.includes(q)||q.includes(Y)),V="Run amp --help for a list of available commands.";if(Z.length>0)V=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new C8(TZ.unknownCommand(Y),1,V)}}var uV6=null;function hP5(){return uV6}function Yp(J){return{...J,getThreadEnvironment:L41,vfs:MC0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new cv(J.fileSystem),generateThreadTitle:No0,deleteThread:(Q)=>J.threadService.delete(Q)}}var pv1=h0.file(HP8.homedir()),pV6=process.env.XDG_CONFIG_HOME?h0.file(process.env.XDG_CONFIG_HOME):n0.joinPath(pv1,".config");async function iZ(J,Q){tN0("0.0.
|
|
4755
|
+
`)}var gv1=bv1.join(BU0||bv1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function zP8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),V=Y||"Warning",q=!1;J.warn(Z,{name:V,code:X})}}function lZ(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")T$("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")T$("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")T$("model.sonnet",Q.useSonnet)}async function uv1(J){try{await KP8(bv1.dirname(gv1),{recursive:!0}),await WP8(gv1,J,"utf-8")}catch(Q){x.debug("Failed to save last thread ID",Q)}}async function FP8(){try{return(await mV6(gv1,"utf-8")).trim()}catch(J){return null}}var hV6=[{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??CZ,description:`Custom settings file path (overrides the default location ${CZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(x).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${dC1})`},{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:i3(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:HI.SMART.key,description:`Set the agent mode (${mG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:mG().map((J)=>J.mode)}],bV6=(J)=>("deprecated"in J)&&J.deprecated===!0,UP8=(J)=>("hidden"in J)&&J.hidden===!0,BP8=(J)=>("default"in J),NP8=(J)=>("default"in J)?J.default:void 0;function DP8(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((q)=>Y.includes(q)||q.includes(Y)),V="Run amp --help for a list of available commands.";if(Z.length>0)V=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new C8(TZ.unknownCommand(Y),1,V)}}var uV6=null;function hP5(){return uV6}function Yp(J){return{...J,getThreadEnvironment:L41,vfs:MC0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new cv(J.fileSystem),generateThreadTitle:No0,deleteThread:(Q)=>J.threadService.delete(Q)}}var pv1=h0.file(HP8.homedir()),pV6=process.env.XDG_CONFIG_HOME?h0.file(process.env.XDG_CONFIG_HOME):n0.joinPath(pv1,".config");async function iZ(J,Q){tN0("0.0.1764792095-g2a447e");let Y=oV1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([h0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:pv1,userConfigDir:pV6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (x51(),y51));X(Y);let G=await Y.getLatest();x.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let{toolService:Z,dispose:V}=Te0({configService:Y}),q=new Map,K=()=>q.clear(),W=new cB1(Y,J.settings.getWorkspaceRootPath()),H=PT0({configService:Y,trustStore:W,createOAuthProvider:async(t,p,e)=>{let F1=`${t}:${p}`,K1=q.get(F1);if(K1)return x.debug("Reusing existing OAuth provider for server",{serverName:t,serverUrl:p}),K1;x.debug("Creating OAuth provider for server",{serverName:t,serverUrl:p});let o=(async()=>{let r=new iM(J.secrets),l=await r.getClientInfo(t,p),W1=e?.scopes??l?.scopes,_1=new zB1({storage:r,serverName:t,serverUrl:p,clientId:e?.clientId??l?.clientId,clientSecret:e?.clientSecret??l?.clientSecret,scopes:W1});return x.debug("OAuth provider created",{serverName:t,serverUrl:p,hasManualClientId:!!(e?.clientId??l?.clientId),willUseDCR:!(e?.clientId??l?.clientId),scopes:W1}),_1})();return q.set(F1,o),o}}),z=D61({configService:Y,filesystem:X9,spawn:kA}),{initializeToolProviders:U,startToolProviders:D}=await Promise.resolve().then(() => (fV6(),vV6)),M;if(J.executeMode){let t=await U({toolService:Z,providers:[H,z],initialTimeout:15000});M=t.registrations;for(let[p,e]of t.initErrors)x.warn(`${p} provider initialization slow or failed:`,e)}else M=D({toolService:Z,providers:[H,z]});if(Q.jetbrains)AI("JetBrains");else if(Q.ide&&_96())AI("VS Code");else if(Q.ide&&k96())AI("Neovim");if(J.executeMode)eN0(!0);let L,A=N3.status.pipe(Y6((t)=>Boolean(t.connected&&t.authenticated)),w4()).subscribe((t)=>{if(t){if(!L)L=Z.registerTool(Bs0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode)E=new S41(process.cwd(),{},!0);else E=new class extends S41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(C5.write(`No API key found. Starting login flow...
|
|
4756
4756
|
`),!await MP8(J))await JO(),process.exit(1)}let I=await oj0({isDevelopment:!1}),P=new dP1(I,Y),T=new gP1(I,{lazy:!0}),k=new JN1(P,(t,p)=>{let e=z2.get(t);if(e)e.handle(p).catch((F1)=>{x.error("Failed to apply artifact delta",F1)})}),y=Q.notifications!==void 0?Q.notifications:!J.executeMode,v=je0({playNotificationSound:async(t)=>{if(y){Ce0(t);let p=fj1(),e=hj1();if((!p||e)&&G.settings["notifications.system.enabled"]!==!1){if(t==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(t==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:P,configService:Y});x.info("Starting Amp background services");let b=Mo0({threadService:P,threadHistoryService:T,configService:Y,isExtensionDevelopment:!1}),d;N3.status.subscribe((t)=>{d=t});let m=new k$1({workspaceRoots:[h0.file(process.cwd())],getCurrentFile:()=>{if(!d?.openFile)return;try{return h0.parse(d.openFile)}catch(t){x.warn("Failed to parse current file URI",{uri:d.openFile,error:t});return}},getOpenFiles:()=>{if(!d?.visibleFiles?.length)return[];let t=d.openFile;return d.visibleFiles.filter((p)=>p!==t).map((p)=>{try{return h0.parse(p)}catch(e){return x.warn("Failed to parse visible file URI",{uri:p,error:e}),null}}).filter((p)=>p!==null)}}),n=new mj1,Z1={codebaseContextService:m,configService:Y,toolService:Z,mcpService:H,trustStore:W,threadService:P,threadHistoryService:T,threadSyncService:b,planFileManager:k,threadStorage:I,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,notificationService:v,fileSystem:Q.jetbrains||Q.ide?BC0:X9,terminal:n};return{...Z1,async asyncDispose(){if(Z1.mcpService.hasAuthenticatingClients())x.info("Waiting for OAuth authentication to complete before exit..."),await Z1.mcpService.waitForAuthentication();for(let t of M.values())t.dispose();await Z1.mcpService.dispose(),K(),await Z1.threadService.asyncDispose(),Z1.configService.unsubscribe(),V(),Z1.fuzzyServer.dispose(),Z1.threadSyncService.dispose(),Z1.settingsStorage[Symbol.dispose](),A.unsubscribe(),L?.dispose()}}}async function MP8(J){if(!J.executeMode){if(!await Uj1("Would you like to log in to Amp? [(y)es, (n)o]: "))return C5.write(`Login cancelled. Run the command again to retry.
|
|
4757
4757
|
`),!1}return await dV6(J)}async function dV6(J){let Q=qP8(32).toString("hex"),Y=await Fj1(J.ampURL,Q),X=new AbortController;try{await cW(Y,X.signal)}catch(Z){x.error("Error opening browser",{error:Z})}let G=await Fj1(J.ampURL,Q,!1);C5.write(`If your browser does not open automatically, visit:
|
|
4758
4758
|
|
|
@@ -4762,7 +4762,7 @@ ${f4.blue.bold(G)}
|
|
|
4762
4762
|
Login successful! You can now use the Amp CLI.
|
|
4763
4763
|
`),!0}catch(Z){return x.error("Login failed",{error:Z}),nZ.write(`
|
|
4764
4764
|
Login failed: ${Z instanceof Error?Z.message:String(Z)}
|
|
4765
|
-
`),!1}}function LP8(){let J=new pA().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)MC(),process.exit(0);let z=H.originalError??H;P86(z)}),J.option("-V, --version","Print the version number and exit",()=>{C5.write(`0.0.
|
|
4765
|
+
`),!1}}function LP8(){let J=new pA().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)MC(),process.exit(0);let z=H.originalError??H;P86(z)}),J.option("-V, --version","Print the version number and exit",()=>{C5.write(`0.0.1764792095-g2a447e (released 2025-12-03T20:06:57.705Z)
|
|
4766
4766
|
`),process.exit(0)}),J.addHelpText("after",C96()),J.configureHelp({formatHelp:j96}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await ZY(U);await EP8(D)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await ZY(U);await wP8(D,await Yj1(U,D.settings))});let Q=async(H,z,U)=>{oV1({storage:z.settings,secretStorage:z.secrets,workspaceRoots:J0.of([h0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:pv1,userConfigDir:pV6});let D={...z,executeMode:!1};await mv1(D,{...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(),D=await ZY(U);await gV6(U,D,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(),D=await ZY(U);await SP8(U,D,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 D=U.optsWithGlobals(),M=await ZY(D);if(z.pick)nZ.write(`${f4.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
4767
4767
|
`);if(z.last||H||M.executeMode)await jP8(D,M,H,U);else await Q(D,M,U)}),Y.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await ZY(D);await CP8(D,M,H,U)}),Y.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await ZY(U);await gV6(U,D,z)}),Y.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support [message]","Share thread with Amp support for debugging").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await ZY(D);await TP8(D,M,H,U,z.support)}),Y.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(H,z,U,D)=>{let M=D.optsWithGlobals(),L=await ZY(M);await IP8(M,L,H,z,D)}),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 D=U.optsWithGlobals(),M=await ZY(D);await PP8(D,M,H,U)}),Y.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await ZY(D);await RP8(D,M,H,z,U)}),M76(J,async(H,z)=>{let U=await ZY(z);lZ(H,z);let D=await iZ(U,z);return{context:U,mcpService:D.mcpService,toolService:D.toolService,toolServices:D.toolService,configService:D.configService,cleanupTerminal:MC,asyncDispose:D.asyncDispose.bind(D)}}),z56(J,async(H)=>{let z=H.optsWithGlobals();return await ZY(z)}),Y56(J,async(H)=>{let z=await ZY(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(U)=>{lZ(U,H);let D=await iZ(z,H);return{mcpService:D.mcpService,settings:z.settings,asyncDispose:D.asyncDispose.bind(D)}}}});function G(H,z,U){let M=typeof H.description==="string"?H.description:U===void 0?H.description(!0):H.description(U),L=new yK(z,M),A=NP8(H);if(A)L.default(A);if(L.hidden=UP8(H)||bV6(H),"choices"in H)L.choices([...H.choices]);return L}for(let H of hV6)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 yK("-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 V=new yK("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(V);let q=new yK("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(q);let K=new yK("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(K);let W=new yK("--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 yK("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return P76(J),J.action(async(H,z)=>{let U=H,D=await ZY(U);if(z.getOptionValueSourceWithGlobals("tryOpus")==="cli")C5.write(f4.yellow(`Opus 4.5 is now the default in Amp's smart mode. Rerun without --try-opus.
|
|
4768
4768
|
`)),process.exit(0);if(Object.keys(U).forEach((L)=>{let A=hV6.find((E)=>E.name===L);if(A&&bV6(A)&&!BP8(A))nZ.write(f4.yellow(`Warning: '--${L}' flag is deprecated
|
|
@@ -4770,8 +4770,8 @@ Login failed: ${Z instanceof Error?Z.message:String(Z)}
|
|
|
4770
4770
|
Or pipe via stdin: echo "your message" | amp --execute`);lZ(Y,Q);let V=await iZ(J,Q);uV6=V;let q=Yp(V),K=async(n)=>{let Z1=await mV6(n,"utf-8"),t=JSON.parse(Z1);if(!f$(t.id))throw new C8(TZ.invalidThreadId);return w71(V,{visibility:X,agentMode:Q.mode,thread:t})},W=async(n)=>{if(!f$(n))throw new C8(TZ.invalidThreadId);try{let[t,p]=await Promise.all([B5.getThreadLinkInfo({thread:n},{config:V.configService}),B5.getUserInfo({},{config:V.configService})]);if(t.ok&&p.ok){let e=t.result.creatorUserID,F1=p.result.id;if(e&&e!==F1&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new C8(`Cannot resume thread created by another user.
|
|
4771
4771
|
|
|
4772
4772
|
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(t){if(t instanceof C8)throw t;x.warn("Failed to validate thread ownership in CLI, allowing to open",{error:t})}let Z1=await V.threadService.get(n)??void 0;return x.info(`[fetchAndStartThread] Loaded thread ${n}, agentMode: ${Z1?.agentMode??"undefined"}`),w71(V,{visibility:X,agentMode:Z1?void 0:Q.mode,thread:Z1})},H=async()=>{try{if(Q.threadId)return W(Q.threadId);else return w71(V,{visibility:X,agentMode:Q.mode})}catch(n){if(n instanceof C8)throw n;throw await Em(n,Q.threadId),Error("handleError should have called process.exit()")}},z=async()=>{return w71(V,{visibility:X,agentMode:Q.mode})};if(Q.format==="jsonl")nZ.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
4773
|
-
`),await JO(),process.exit(1);if(J.executeMode&&Q.remote)await F56(G,Z,V.configService),await V.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)Z56(V.mcpService,J.settings),await m86(U,U.threadID,G,Z,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await V.asyncDispose(),process.exit(0);let D=!1,M=!1;if(Q.jetbrains||Q.ide){await WL0();let n=fI({jetbrainsOnly:Q.jetbrains});if(n.length===0){if(Q.jetbrains)M=!await V.configService.get("jetbrains.skipInstall")}else if(n.length===1){let Z1=n[0];if(Z1)N3.selectConfig(Z1)}else D=!0}let L=g41("0.0.
|
|
4774
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await z96({...J,workspaceTrust:{current:!0,changes:fk},getHook:process.env.AMP_URL?(Z,V)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let Z=await X56(J.mcpConfig);X=G56(X,Z)}let G=await X.get("url","global");if(!G)G=MY;if(!hF(G))x.info("Targeting custom Amp server",{ampURL:G});return X=UB0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:U56(await Yj1(J,X))}}function AP8(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,(q,K)=>K.toUpperCase()),V=J[Y+1];if(V&&!V.startsWith("--"))Q[Z]=V,Y++}}return Q}async function OP8(){let J=AP8(process.argv);if(N86({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),zP8(x),x.info("Starting Amp CLI.",{version:"0.0.
|
|
4773
|
+
`),await JO(),process.exit(1);if(J.executeMode&&Q.remote)await F56(G,Z,V.configService),await V.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)Z56(V.mcpService,J.settings),await m86(U,U.threadID,G,Z,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await V.asyncDispose(),process.exit(0);let D=!1,M=!1;if(Q.jetbrains||Q.ide){await WL0();let n=fI({jetbrainsOnly:Q.jetbrains});if(n.length===0){if(Q.jetbrains)M=!await V.configService.get("jetbrains.skipInstall")}else if(n.length===1){let Z1=n[0];if(Z1)N3.selectConfig(Z1)}else D=!0}let L=g41("0.0.1764792095-g2a447e",V.settingsStorage),A=new l01(V.threadStorage),E=J0.of([h0.file(process.cwd())]),I=d$1(void 0,E),P=new m41(V.mcpService,J.settings.getWorkspaceRootPath());if(G)U.handle({type:"user:message",message:{content:[{type:"text",text:G}]}});let T=(async()=>{try{let n=await B5.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(n.ok)return x.info("User free tier status:",n),n.result}catch(n){x.error("Failed to fetch free tier status:",n)}})(),k=(async()=>{try{let n=await B5.getUserInfo({},{config:V.configService});if(n.ok)return n.result}catch(n){x.debug("Failed to fetch user workspace info:",n)}})(),[y,v]=await Promise.all([T,k]),b=v?.email,d=b&&(b.endsWith("@sourcegraph.com")||b.endsWith("@ampcode.com")||b==="auth-bypass-user@example.com"),m=await D56();x.info("Loaded session state:",m),await Wx1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new E41,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,planFileManager:V.planFileManager,threadID:U.threadID,threadFuzzyIndexer:A,worker:U,workerDeps:q,configService:V.configService,internalAPIClient:B5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:N3,connectedClientsService:new On,commandRegistry:I,mcpService:V.mcpService,mcpTrustHandler:P,showJetBrainsInstaller:M,showIdePicker:D,openThreadSwitcher:Q.openThreadSwitcher,updateService:L,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:m,freeTierStatus:y,workspace:v?.team??null,features:v?.features??[],isDogfooding:d||!1,threadDependencies:V,initialAgentMode:Y.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function ZY(J){if(J.interactive)nZ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
4774
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await z96({...J,workspaceTrust:{current:!0,changes:fk},getHook:process.env.AMP_URL?(Z,V)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let Z=await X56(J.mcpConfig);X=G56(X,Z)}let G=await X.get("url","global");if(!G)G=MY;if(!hF(G))x.info("Targeting custom Amp server",{ampURL:G});return X=UB0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:U56(await Yj1(J,X))}}function AP8(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,(q,K)=>K.toUpperCase()),V=J[Y+1];if(V&&!V.startsWith("--"))Q[Z]=V,Y++}}return Q}async function OP8(){let J=AP8(process.argv);if(N86({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),zP8(x),x.info("Starting Amp CLI.",{version:"0.0.1764792095-g2a447e",buildTimestamp:"2025-12-03T20:06:57.705Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new C8(TZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await LP8().parseAsync(process.argv)}kP1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await OP8().catch(Em)});async function wP8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),C5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
4775
4775
|
`);else if(!hF(J.ampURL))C5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
4776
4776
|
`);let Y=process.env.AMP_API_KEY;if(Y)C5.write(`API key found in environment variable, storing...
|
|
4777
4777
|
`),await Q.set("apiKey",Y,J.ampURL),C5.write(`API key successfully stored.
|
|
@@ -4784,7 +4784,7 @@ This thread belongs to a different user and cannot be continued for security rea
|
|
|
4784
4784
|
`);else C5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
|
|
4785
4785
|
`);process.exit(0)}async function IP8(J,Q,Y,X,G){lZ(G,J);let Z=await iZ(Q,J);try{let V=E71(Y);if(!V)I71(Y);let q=V,K=X.trim();if(K.length===0)cZ("Thread name cannot be empty");if(K.length>256)cZ("Thread name cannot exceed 256 characters");if(!(await yj(q,Z)).messages.length)cZ("Cannot rename an empty thread.");let H=Yp(Z);await(await z2.getOrCreateForThread(H,q)).handle({type:"title",value:K}),x.info("GOT HERE"),await Z.threadSyncService.sync(),x.info("GOT THERE"),C5.write(f4.green(`✓ Thread ${q} renamed to "${K}"
|
|
4786
4786
|
`)),await Z.asyncDispose(),process.exit(0)}catch(V){await Z.asyncDispose();let q=`Failed to rename thread: ${V instanceof Error?V.message:String(V)}`;cZ(q)}}async function PP8(J,Q,Y,X){lZ(X,J);let G=await iZ(Q,J);try{let Z=E71(Y);if(!Z)I71(Y);let q=await yj(Z,G),K=aT(q);C5.write(K+`
|
|
4787
|
-
`),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let V=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;cZ(V)}}async function RP8(J,Q,Y,X,G){lZ(G,J);let Z=await iZ(Q,J);try{let V=await dv1(Y),q=await yj(V,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,D=X.indicator!==!1,M=Yp(Z),L=q.id;await Z.threadStorage.set(L,q);let A=await z2.getOrCreateForThread(M,L);await A.resume();let E=c01.fromWorker(A),I=new l01(Z.threadStorage),P=J0.of([h0.file(process.cwd())]),T=d$1(void 0,P),k=new m41(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=g41("0.0.
|
|
4787
|
+
`),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let V=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;cZ(V)}}async function RP8(J,Q,Y,X,G){lZ(G,J);let Z=await iZ(Q,J);try{let V=await dv1(Y),q=await yj(V,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,D=X.indicator!==!1,M=Yp(Z),L=q.id;await Z.threadStorage.set(L,q);let A=await z2.getOrCreateForThread(M,L);await A.resume();let E=c01.fromWorker(A),I=new l01(Z.threadStorage),P=J0.of([h0.file(process.cwd())]),T=d$1(void 0,P),k=new m41(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=g41("0.0.1764792095-g2a447e",Z.settingsStorage);await Wx1({codebaseContextService:Z.codebaseContextService,stdout:process.stdout,history:new E41,fuzzyServer:Z.fuzzyServer,settingsStorage:Z.settingsStorage,threadService:Z.threadService,threadHistoryService:Z.threadHistoryService,threadSyncService:Z.threadSyncService,planFileManager:Z.planFileManager,threadID:L,threadFuzzyIndexer:I,worker:E,workerDeps:M,configService:Z.configService,internalAPIClient:B5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:N3,connectedClientsService:new On,commandRegistry:T,mcpService:Z.mcpService,mcpTrustHandler:k,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:q,typingEnabled:K,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:D}}),await Z.asyncDispose(),process.exit(0)}catch(V){await Z.asyncDispose(),await Em(V,Y)}}async function TP8(J,Q,Y,X,G){lZ(X,J);let Z=await iZ(Q,J);try{let V=E71(Y);if(!V)I71(Y);let q=V,K=await B5.getUserInfo({},{config:Z.configService}),W=K.ok?K.result:null,H=u41(J,W);if(!H&&!G)cZ("Must specify either --visibility or --support");if(H&&G)cZ("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)cZ(H.message);if(H)await Z.threadSyncService.updateThreadMeta(q,p41(H)),C5.write(f4.green("✓ ")+`Thread ${q} visibility changed to ${H}.
|
|
4788
4788
|
`);if(G){await yj(q,Z);let z=typeof G==="string"?G:void 0;await dj0(Z.threadService,q,Z.configService,z),C5.write(f4.green("✓ ")+`Thread ${q} has been shared with Amp support. These thread reports will be aggregated and analysed.
|
|
4789
4789
|
`)}await Z.asyncDispose(),process.exit(0)}catch(V){await Z.asyncDispose(),cZ(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function CP8(J,Q,Y,X){lZ(X,J);let G=await iZ(Q,J),Z=Yp(G);try{let V=await dv1(Y),K=(await yj(V,G)).messages.length-1,W=await z2.getOrCreateForThread(Z,V),H=await rT(W,G.threadSyncService,K);await Promise.all([G.threadSyncService.uploadThread(V),G.threadSyncService.uploadThread(H)]),await uv1(H),C5.write(`${H}
|
|
4790
4790
|
`),await G.asyncDispose(),process.exit(0)}catch(V){nZ.write(`Error forking thread: ${V instanceof Error?V.message:String(V)}
|