@sourcegraph/amp 0.0.1766016110-gbafd5c → 0.0.1766044881-gb9246f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +9 -9
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -3797,11 +3797,11 @@ Actual: ${X}`)}async function ZV8(J,Q,Y){let{execSync:Z}=await import("node:ch
3797
3797
  ${B}`;if(X==="pnpm"&&B.includes("Unable to find the global bin directory"))D+=`
3798
3798
 
3799
3799
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
3800
- npm install -g @sourcegraph/amp`;K(Error(D))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}B0();B0();async function M81(J,Q){let Z=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Z}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=KV8(J,q),H=W<0,F,U;if(K.time){let B=K.time[J],D=K.time[q],L=Date.now();if(B)F=Math.floor((L-new Date(B).getTime())/3600000);if(D)U=Math.floor((L-new Date(D).getTime())/3600000)}return v.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:F,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:F,latestVersionAge:U,source:"npm"}}catch(X){return v.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function KV8(J,Q){let Y=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Z=Y(J),X=Y(Q),G=Math.max(Z.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Z.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Z.label===X.label)return 0;if(!Z.label&&X.label)return 1;if(Z.label&&!X.label)return-1;if(Z.label&&X.label)return Z.label<X.label?-1:1;return 0}s0();function D81(J,Q){let Y=new d4,Z=Y.pipe(L8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new fK().scoped("update"),G=Z.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await sB(500),Y.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=_O(),W=await M81(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,B=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},F=await N81();if(!K)K=F==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:K});if(K==="warn"){if(!H())Y.next("update-available");return}if(!F){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(F==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await am(W.latestVersion,F);let U=await MN(W.latestVersion),B={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",B),Y.next("updated");else X.warn("success with warning",B),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await sB(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:Z}}import{stderr as rq}from"node:process";function H56(J){let Q=new NO().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(Z)=>{await nS1(Z.force||!1,Z.verbose||!1,"0.0.1766016110-gbafd5c"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new NO("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(Z)=>{await qV8(Z.targetVersion)});J.addCommand(Y)}async function qV8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")rq.write(C6.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
3800
+ npm install -g @sourcegraph/amp`;K(Error(D))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}B0();B0();async function M81(J,Q){let Z=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Z}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=KV8(J,q),H=W<0,F,U;if(K.time){let B=K.time[J],D=K.time[q],L=Date.now();if(B)F=Math.floor((L-new Date(B).getTime())/3600000);if(D)U=Math.floor((L-new Date(D).getTime())/3600000)}return v.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:F,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:F,latestVersionAge:U,source:"npm"}}catch(X){return v.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function KV8(J,Q){let Y=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Z=Y(J),X=Y(Q),G=Math.max(Z.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Z.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Z.label===X.label)return 0;if(!Z.label&&X.label)return 1;if(Z.label&&!X.label)return-1;if(Z.label&&X.label)return Z.label<X.label?-1:1;return 0}s0();function D81(J,Q){let Y=new d4,Z=Y.pipe(L8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new fK().scoped("update"),G=Z.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await sB(500),Y.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=_O(),W=await M81(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,B=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},F=await N81();if(!K)K=F==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:K});if(K==="warn"){if(!H())Y.next("update-available");return}if(!F){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(F==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await am(W.latestVersion,F);let U=await MN(W.latestVersion),B={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",B),Y.next("updated");else X.warn("success with warning",B),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await sB(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:Z}}import{stderr as rq}from"node:process";function H56(J){let Q=new NO().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(Z)=>{await nS1(Z.force||!1,Z.verbose||!1,"0.0.1766044881-gb9246f"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new NO("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(Z)=>{await qV8(Z.targetVersion)});J.addCommand(Y)}async function qV8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")rq.write(C6.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
3801
3801
 
3802
3802
  `));try{if(!J){rq.write(C6.blue(`Checking for updates...
3803
- `));let Y=_O(),{hasUpdate:Z,latestVersion:X}=await M81("0.0.1766016110-gbafd5c",Y);if(!Z){rq.write(C6.green(`✓ Amp CLI is already up to date: ${"0.0.1766016110-gbafd5c"} (${"released"} ${"2025-12-18T00:07:15.449Z"}${`, ${iP(new Date("2025-12-18T00:07:15.449Z"))} ago`})
3804
- `));let V=await MN("0.0.1766016110-gbafd5c");if(V.warning)rq.write(`
3803
+ `));let Y=_O(),{hasUpdate:Z,latestVersion:X}=await M81("0.0.1766044881-gb9246f",Y);if(!Z){rq.write(C6.green(`✓ Amp CLI is already up to date: ${"0.0.1766044881-gb9246f"} (${"released"} ${"2025-12-18T08:06:38.200Z"}${`, ${iP(new Date("2025-12-18T08:06:38.200Z"))} ago`})
3804
+ `));let V=await MN("0.0.1766044881-gb9246f");if(V.warning)rq.write(`
3805
3805
  `+C6.yellow(V.warning)+`
3806
3806
  `);process.exit(0)}if(!X)rq.write(C6.yellow("[WARN] could not find latest version")),process.exit(0);J=X}rq.write(C6.blue(`Updating to version ${J}...
3807
3807
  `)),await am(J,void 0,(Y)=>{rq.write(C6.dim(`Running: ${Y}
@@ -4496,7 +4496,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let d=W.text.replace(/`([^`]+)`/g,"$1")+`
4496
4496
  `,A)])}),k];if(!q&&!U&&W.url){let b=W.url.replace(/^https?:\/\//,"");f.push(new o5({uri:W.url,text:b,style:new J1({color:Y.secondary,underline:!0})}))}if(C&&!U)f.push(C);let m=new X0({width:40,child:new v0({crossAxisAlignment:"start",mainAxisSize:"min",children:f})});return j4.child(new N6({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new U_1({width:sx1,height:tx1,agentMode:this.widget.agentMode,glow:this._glow,t:H,fps:0,shockwaves:this._shockwaves,onShockwave:P,...V==="disabled"&&{seed:42}}),new X0({width:2}),m]}))}}B0();A8();m4();C7();A8();s0();function DD8(J,Q){return`${J}:${Q}`}class ex1{threadService;workers=new Map;threadsMap=new Map;subthreadsMap=new Map;mainThreadSubs=new Map;subthreadsSubs=new Map;workerStatusSubs=new Map;subthreadPatchSubs=new Map;mainThreadObservable;subthreadObservable;workerStatusObservable;emitMainThread=null;emitSubthread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new Q0((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.subthreadObservable=new Q0((Q)=>{return this.emitSubthread=(Y)=>Q.next(Y),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new Q0((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(tD()).subscribe((G)=>{this.threadsMap.set(Q,G);let V=this.subthreadsMap.get(Q)||[],K=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:G,subthreads:V,workerStatus:K})});this.mainThreadSubs.set(Q,Y);let Z=J.status.subscribe((G)=>{if(this.workers.set(Q,G),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:G})});this.workerStatusSubs.set(Q,Z);let X=J.subthreads.subscribe((G)=>{this.subthreadsMap.set(Q,G);for(let V of G){let K=DD8(Q,V.toolUse.id);if(this.subthreadPatchSubs.has(K))continue;let q=this.threadService.observePatches(V.threadID).pipe(tD()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:V})});this.subthreadPatchSubs.set(K,q)}});this.subthreadsSubs.set(Q,X)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Y=this.workerStatusSubs.get(J);if(Y)Y.unsubscribe(),this.workerStatusSubs.delete(J);let Z=this.subthreadsSubs.get(J);if(Z)Z.unsubscribe(),this.subthreadsSubs.delete(J);for(let[X,G]of this.subthreadPatchSubs.entries())if(X.startsWith(`${J}:`))G.unsubscribe(),this.subthreadPatchSubs.delete(X);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new Q0((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),subthreads:new Q0((Q)=>{return this.subthreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new Q0((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 Z=this.workers.get(Q);if(Z)J[Q]=JO(Y,Z)}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 LD8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Y,subthread:Z}=Q,X=J.subagents[Z.threadID];if(!X){if(X={subThreadID:Y.id,parentToolID:Z.toolUse.id,taskDescription:Z.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=eJ(J.mainThread);X.isCompleted=MZ6(W,Z.toolUse.id)}}let G=AD8(Y,X.agentState),V=X.agentState===G?X:{...X,agentState:G},K={...J.tools},q=kj(Y).items.filter((W)=>W.type==="toolResult");for(let W of q)K[W.id]={id:W.id,subthreadID:Y.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[Z.threadID]:V},tools:K,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Y,subthreads:Z,workerStatus:X}=Q,G=eJ(Y),V={...J.subagents};for(let F of Z){let U=V[F.threadID];if(!U)continue;let B=MZ6(G,F.toolUse.id);V[F.threadID]={...U,isCompleted:B}}let{items:K}=kj(Y),q=JO(Y,X),W=zU({messages:Y.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:V,items:K,viewState:q,todosList:H,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=JO(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function kj(J){let Q=[],Y=new Map,Z=new Set;for(let[X,G]of J.messages.entries()){let V=`${G.role}-${X}`;switch(G.role){case"assistant":{let K=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(Y.set(W.id,W),K)Z.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,message:G});for(let W of G.content)if(W.type==="tool_use"){let H=!1;for(let F=X+1;F<J.messages.length;F++){let U=J.messages[F];if(U){for(let B of U.content)if(B.type==="tool_result"&&B.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:K?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:V,message:G});break;case"user":{let K=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=Y.get(q.toolUseID)??hZ(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(K)Q.push({type:"message",id:V,message:G});break}}}return{items:Q}}function MZ6(J,Q){let Y=J.get(Q);return(Y&&M3(Y.run))??!1}function AD8(J,Q){let Y=J.messages.at(-1);if(Y?.content.some((X)=>X.type==="tool_result"&&X.run.status==="blocked-on-user"))return v.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(kj(J).items.some((X)=>X.type==="toolResult"&&X.toolResult.run.status==="in-progress")){let X=Q?.type==="running-tools"?Q.startTime:Date.now();return v.info("Subagent status: running-tools",{threadID:J.id,startTime:X,hasStartTime:!!X}),{type:"running-tools",startTime:X}}if(Y&&Y.role==="assistant"&&Y.state.type==="streaming")switch(Y.content.at(-1)?.type){case"text":return v.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return v.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let G=Q?.type==="running-tools"?Q.startTime:Date.now();return v.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}default:return v.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return v.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class Jv1 extends c0{props;constructor(J){super();this.props=J}createState(){return new DZ6}}class DZ6 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 ex1(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((G)=>{this.dispatch({type:"main-thread-patch",thread:G.mainThread,subthreads:G.subthreads,workerStatus:G.workerStatus})});this.subscriptions.push(Y);let Z=Q.subthreads.subscribe((G)=>{this.dispatch({type:"subthread-patch",thread:G.thread,subthread:G.subthread})});this.subscriptions.push(Z);let X=Q.workerStatus.subscribe((G)=>{this.dispatch({type:"worker-status-change",workerStatus:G.status})});this.subscriptions.push(X)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=LD8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((G)=>({toolUse:G.toolUse,toolRun:G.toolRun,subthreadID:G.subthreadID})),Q={};for(let G of Object.values(this.state.subagents)){let V=J.filter((K)=>K.subthreadID===G.subThreadID);Q[G.parentToolID]=V}let Y=(G)=>G===c5||G===D9||G===lK,Z=new Map;for(let G of this.state.items)if(G.type==="toolResult"&&Y(G.toolUse.name))Z.set(G.toolUse.id,{toolUseId:G.toolUse.id,toolName:G.toolUse.name,toolRun:G.toolResult.run});let X=Array.from(Z.values());for(let{toolUseId:G,toolRun:V}of X){let K=[],q;if(V.status==="in-progress"||V.status==="done"||V.status==="error"||V.status==="cancelled")q=V.progress;if(q){let W=0;for(let H of q)if(H.tool_uses)for(let F of H.tool_uses){let U=`${G}:progress:${W++}`;K.push({toolUse:cI(F.tool_name,F.input,U),toolRun:{status:F.status}})}}Q[G]=K}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker,this.recentThreadIDs)}}class Qv1 extends c0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new LZ6}}class LZ6 extends p0{build(J){let Y=G6.of(J).colors,{todos:Z,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Z)||Z.length===0)return new X0({width:0,height:0});let G=Z.map((V)=>this.buildTodoItem(V,Y));return new m0({child:new z6({padding:F0.symmetric(1,0),child:new v0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new y1({text:new l(X,new J1({bold:!0,color:Y.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),Z=J.status==="completed",X=new J1({bold:J.status==="in-progress",color:Q.foreground,dim:Z}),G=new J1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Z});return new N6({crossAxisAlignment:"start",children:[new y1({text:new l(Y,X)}),new X0({width:1}),new a6({child:new y1({text:new l(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Yv1 extends b6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Y,onButtonClick:Z}){super({key:J});this.ad=Q,this.onDismiss=Y,this.onButtonClick=Z}build(J){let Q=G6.of(J),Y=Q.colors.primary,Z=Q.colors.foreground;return new m0({decoration:new T8(void 0,new B4(new W4(Y,1,"rounded"),new W4(Y,1,"rounded"),void 0,new W4(Y,1,"rounded"))),child:new z6({padding:F0.horizontal(1),child:new v0({children:[new N6({crossAxisAlignment:"start",children:[new a6({child:new y1({text:new l(this.ad.content,new J1({color:Z}))})}),new X0({width:4}),new o5({uri:"https://ampcode.com/free",text:"Ad",style:new J1({color:Z,dim:!0})})]}),new N6({crossAxisAlignment:"start",children:[new P_1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:F0.horizontal(1),color:Y,reverse:!0}),new X0({width:2}),new y1({text:new l(this.ad.destinationUrlHostname,new J1({color:Z,dim:!0}))})]})]})})})}}class Zv1 extends c0{props;constructor(J){super();this.props=J}createState(){return new AZ6(this.props.autofocus??!0)}}class AZ6 extends p0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(K)=>{if(K.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(K.ctrlKey&&K.key==="c"||K.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=C4.sizeOf(J),Z=Math.min(60,Y.width-4),X=Y.height-4,G=[];if(this.widget.props.title)G.push(new y1({text:new l(this.widget.props.title,new J1({bold:!0,color:N1.blue}))}),new X0({height:1}));if(this.widget.props.message)G.push(new y1({text:new l(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)G.push(new X0({height:1}));let V=[];if(this.widget.props.showCopyOption)V.push(new y1({text:new l("Enter to copy",new J1({dim:!0}))}));return V.push(new y1({text:new l("Escape to close",new J1({dim:!0}))})),G.push(new N6({children:V.flatMap((K,q)=>q<V.length-1?[K,new X0({width:1}),new y1({text:new l("•",new J1({dim:!0}))}),new X0({width:1})]:[K]),mainAxisSize:"min"})),new j4({child:new m0({constraints:new A6(Z,Z,0,X),decoration:new T8(N1.default(),new B4(new W4(N1.blue,1,"rounded"),new W4(N1.blue,1,"rounded"),new W4(N1.blue,1,"rounded"),new W4(N1.blue,1,"rounded"))),padding:new F0(2,2,2,2),child:new U8({autofocus:this.autofocus,onKey:Q,child:new v0({children:G,mainAxisSize:"min"})})})})}}class a51 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,a51.prototype)}}class o51 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,o51.prototype)}}function Xv1(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})}TH();B0();import{spawn as OD8}from"node:child_process";import{promises as wD8}from"node:fs";function OZ6(J){return J.kind==="executable"}function wZ6(J){return J.kind==="markdown"}var uF=50000,EZ6=300000;async function $v1(J,Q,Y,Z={}){let{timeoutMs:X=EZ6,signal:G,source:V}=Z;try{let K=await Y.getCommand(J,V);if(!K)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(v.debug("Executing command",{commandName:J,filePath:K.filePath,args:Q}),wZ6(K))return await ED8(K,Q);else if(OZ6(K))return await ID8(K,Q,X,G);else return{success:!1,output:"",error:"Unsupported command type"}}catch(K){return v.error("Failed to execute command",{commandName:J,error:K}),{success:!1,output:"",error:K instanceof Error?K.message:"Unknown error occurred"}}}async function ED8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await wD8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>uF?Y.slice(0,uF)+`
4497
4497
  ... (output truncated at ${uF} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function ID8(J,Q,Y=EZ6,Z){return new Promise((X)=>{let[G,V]=PD8(J,Q);v.debug("Spawning command",{spawnCommand:G,spawnArgs:V.slice(0,10),filePath:J.filePath,timeoutMs:Y});let K=jP0(Z),q=!1,W=setTimeout(()=>{q=!0,K.abort(),v.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=OD8(G,V,{stdio:["pipe","pipe","pipe"],signal:K.signal,detached:!0}),F=[],U=[],B=0;H.stdout?.on("data",(D)=>{let L=D.toString();if(B+=L.length,B<=uF)F.push(L);else{let A=uF-(B-L.length);if(A>0)F.push(L.slice(0,A))}}),H.stderr?.on("data",(D)=>{let L=D.toString();if(B+=L.length,B<=uF)U.push(L);else{let A=uF-(B-L.length);if(A>0)U.push(L.slice(0,A))}}),H.on("close",(D)=>{if(clearTimeout(W),q){X({success:!1,output:F.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(K.signal.aborted){X({success:!1,output:F.join(""),error:"The command was aborted",exitCode:D??void 0});return}let L=D===0||D===1,A=F.join(""),w=U.join(""),I=A;if(!L&&!A.trim()&&w.trim())I=w;else if(w.trim())I+=A?`
4498
4498
  ${w}`:w;if(B>uF)I+=`
4499
- ... (output truncated at ${uF} characters)`;X({success:L,output:I.trim(),error:!L?w.trim()||"Command failed":void 0,exitCode:D??void 0})}),H.on("error",(D)=>{clearTimeout(W);let L=D.message;if(q)L=`Command timed out after ${Y}ms`;else if(D.message.includes("operation was aborted")||D.name==="AbortError")L="The command was aborted";X({success:!1,output:F.join(""),error:L})})})}function PD8(J,Q){let{filePath:Y,interpreter:Z,extension:X}=J;if(process.platform==="win32")return TD8(Y,Z?[...Z]:null,X,Q);else return RD8(Y,Z?[...Z]:null,X,Q)}function RD8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];else return[J,Z]}function TD8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Z]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Z]];case".exe":return[J,Z];default:return[J,Z]}}B0();q$();X7();dP();HH();iY();XV();CH();Bq();A8();yg();C7();g_();s0();var eZ6=F6(hL(),1);import{writeFile as rZ6}from"fs/promises";import sZ6 from"path";B0();iY();class Gv1{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.1766016110-gbafd5c"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Js(Q,this.configService)}catch(Q){v.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Xw extends c0{props;constructor(J){super();this.props=J}createState(){return new IZ6}}class IZ6 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 PZ6 extends p0{controller=new qZ;focusNode=new M8({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:Z}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=B4.all(new W4(Y.foreground,1,"solid")),q=new vF({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(B)=>{let D=B.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new N6({children:[new m0({decoration:{color:N1.default()},child:new y1({text:new l(">",new J1({color:Y.foreground}))})}),new a6({child:q})]}),H=new m0({padding:F0.symmetric(1,0),child:new y1({text:new l("",void 0,[new l("Command: ",new J1({color:Y.foreground})),new l(this.widget.props.commandName,new J1({color:N1.yellow,bold:!0}))])})}),F=[];if(V)F.push(new l("Enter",new J1({color:Z.keybind}))),F.push(new l(" to submit, ",new J1({color:Y.foreground,dim:!0})));F.push(new l("Esc",new J1({color:Z.keybind}))),F.push(new l(" to cancel",new J1({color:Y.foreground,dim:!0})));let U=new m0({padding:F0.symmetric(1,0),child:new y1({text:new l("",void 0,F)})});return new m0({decoration:{border:K,color:N1.default()},padding:F0.all(1),child:new v0({children:[H,new X0({height:1}),W,new f5,U]})})}}class ou extends c0{props;constructor(J){super();this.props=J}createState(){return new PZ6}}CH();class RZ6 extends p0{controller=new qZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new M8({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>=kU)return!1;let Q=Hj(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:Z}=Q,G=C4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new Zw({controller:this.controller,triggers:[new KW],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(B)=>{this.widget.props.onSubmit(B.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:_8.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new U8({focusNode:this.focusNode,child:K}),W=new m0({constraints:new A6({maxHeight:V}),padding:F0.symmetric(1,0),child:q}),H=new m0({padding:F0.symmetric(1,0),child:new y1({text:new l("",void 0,[new l("Command: ",new J1({color:Y.foreground})),new l(this.widget.props.commandName,new J1({color:N1.yellow,bold:!0}))])})}),F=new m0({padding:F0.symmetric(1,0),child:new y1({text:this.isConfirmingClearInput?new l("",void 0,[new l("Esc",new J1({color:Z.keybind})),new l(" again to clear input",new J1({color:Y.foreground,dim:!0}))]):new l("",void 0,[new l("Press ",new J1({color:Y.foreground,dim:!0})),new l("Enter",new J1({color:Z.keybind})),new l(" to submit, ",new J1({color:Y.foreground,dim:!0})),new l("Esc",new J1({color:Z.keybind})),new l(" to clear",new J1({color:Y.foreground,dim:!0}))])})}),U=[H,new X0({height:1}),new a6({child:W}),new X0({height:1}),F];return new m0({decoration:{border:B4.all(new W4(Y.foreground,1,"solid")),color:N1.default()},padding:F0.all(1),child:new v0({children:U})})}}class _j extends c0{props;constructor(J){super();this.props=J}createState(){return new RZ6}}import{isDeepStrictEqual as kD8}from"node:util";var CD8=/[\\/_ +.#"@[({&]/,jD8=/[\\/_ +.#"@[({&]/g,SD8=/[\s-]/,TZ6=/[\s-]/g;function s51(J,Q,Y,Z,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Z.charAt(G),W=Y.indexOf(q,X),H=0,F,U,B,D;while(W>=0){if(F=s51(J,Q,Y,Z,W+1,G+1,V),F>H){if(W===X)F*=1;else if(SD8.test(J.charAt(W-1))){if(F*=0.9,D=J.slice(X,W-1).match(TZ6),D&&X>0)F*=Math.pow(0.999,D.length)}else if(CD8.test(J.charAt(W-1))){if(F*=0.8,B=J.slice(X,W-1).match(jD8),B&&X>0)F*=Math.pow(0.999,B.length)}else if(F*=0.3,X>0)F*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))F*=0.9999}if(F<0.1&&(Y.charAt(W-1)===Z.charAt(G+1)||Z.charAt(G+1)===Z.charAt(G)&&Y.charAt(W-1)!==Z.charAt(G))){if(U=s51(J,Q,Y,Z,W+1,G+2,V),U*0.1>F)F=U*0.1}if(F>H)H=F;W=Y.indexOf(q,W+1)}return V[K]=H,H}function r51(J){return J.toLowerCase().replace(TZ6," ")}function CZ6(J,Q){let Y=s51(J,Q,r51(J),r51(Q),0,0,{}),Z=Q.trim().split(/\s+/);if(Z.length>1){let X=0,G=0;for(let K of Z){let q=s51(J,K,r51(J),r51(K),0,0,{});if(q===0)return Y;X+=q,G+=K.length}let V=X/Z.length*0.95;return Math.max(Y,V)}return Y}class yj{}class xj{}class t51{}class e51{}class jZ6 extends c0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new SZ6}}class SZ6 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function _D8(J,Q){if(J==="")return{matches:!0,score:1};let Y=CZ6(Q,J);return{matches:Y>0.15,score:Y}}class r2 extends c0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new kZ6}}class kZ6 extends p0{controller=new qZ;focusNode;scrollController=new N5;selectedIndex=0;itemContexts=[];cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new M8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),g8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[0]??null)}),this.recomputeFilteredItems();let J=this.cachedFiltered;this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!kD8(J.props.items,this.widget.props.items)){this.recomputeFilteredItems(),this.ensureSelectedItemVisible();let Q=this.cachedFiltered;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 yj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),g8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof xj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),g8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof t51){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 e51)return this.widget.props.onDismiss?.(),"handled";return"ignored"};recomputeFilteredItems(){let J=this.controller.text,Q=this.widget.props.items,Y=Q.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,..._D8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,X)=>this.widget.props.sortItems(Z,X,J):(Z,X)=>X.score-Z.score).map((Z)=>Z.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;m91(J,{top:Y,bottom:Z},{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(),g8.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 Z=Y[J],X=Z?this.widget.props.isItemDisabled?.(Z)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!X){if(Z)this.widget.props.onAccept(Z)}}};build(J){let Q=G6.of(J),{colors:Y}=Q,Z=this.getFilteredItems(),X=B4.all(new W4(Y.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new vF({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Y.foreground,border:null},maxLines:1}),K=new AX({shortcuts:new Map([[new N4("ArrowDown"),new yj],[new N4("ArrowUp"),new xj],[new N4("Tab"),new yj],[new N4("Tab",{shift:!0}),new xj],[new N4("n",{ctrl:!0}),new yj],[new N4("p",{ctrl:!0}),new xj],[new N4("Enter"),new t51],[new N4("Escape"),new e51]]),focusNode:this.focusNode,child:V}),q=new CJ({actions:new Map([[yj,new C8(this.invoke)],[xj,new C8(this.invoke)],[t51,new C8(this.invoke)],[e51,new C8(this.invoke)]]),child:K}),W=new N6({children:[new m0({decoration:{color:N1.default()},child:new y1({text:new l(">",new J1({color:Y.foreground}))})}),new a6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new X0({height:10,child:new j4({child:new y1({text:new l(L,new J1({color:Y.foreground}))})})})}else if(Z.length===0&&this.widget.props.emptyStateText)H=new a6({child:new j4({child:new y1({text:new l(this.widget.props.emptyStateText,new J1({color:Y.foreground,dim:!0}))})})});else{let L=Z.map((A,w)=>{let I=w===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,R;if(this.widget.props.renderItem)R=this.widget.props.renderItem(A,I,P,J);else{let C=I?N1.yellow:void 0,k=I?N1.black:Y.foreground;R=new m0({decoration:C?{color:C}:void 0,padding:F0.symmetric(2,0),child:new y1({text:new l(this.widget.props.getLabel(A),new J1({color:k,dim:P}))})})}return new jZ6(new z8({onClick:(C)=>this.handleItemClick(w,C.clickCount),child:R}),(C)=>{this.itemContexts[w]=C})});H=new v0({children:L,crossAxisAlignment:"start"})}let F=new a6({child:new z8({onScroll:this.handleScroll,opaque:!1,child:new s9({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new m0({padding:F0.symmetric(1,0),child:new y1({text:new l(this.widget.props.title,new J1({color:N1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new X0({height:1}),F),this.controller.text!==""){let L=Z.length>0?Z[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new m0({padding:F0.vertical(1),child:new j4({child:A})}));else U.push(new X0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new m0({decoration:{border:X,color:N1.default()},padding:F0.symmetric(1,0),child:new v0({children:U})})}}function _Z6(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/60000),X=Math.floor(Y/3600000),G=Math.floor(Y/86400000);if(Z<1)return"just now";if(Z<60)return`${Z}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class Vv1 extends b6{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Y=Math.max(0,...Q.map((X)=>_Z6(X.pubDate).length));return new r2({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=G6.of(K),{colors:W}=q,H=G?N1.yellow:void 0,F=G?N1.black:W.foreground,U=N1.index(8),B=(D,L)=>new X0({width:L,child:N6.end([new y1({text:new l(D,new J1({color:U}))})])});return new m0({decoration:H?{color:H}:void 0,padding:F0.symmetric(2,0),child:new N6({children:[new a6({child:new y1({text:new l(X.title,new J1({color:F})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),B(_Z6(X.pubDate),Y)]})})}})}}class Kv1 extends c0{createState(){return new yZ6}}class yZ6 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 l("●",new J1({color:this.isGreen?N1.green:N1.index(8),bold:!0})),maxLines:1})}}function yD8(J){let Q=new Map,Y=new Map,Z=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Z.set(V.id,K.type);let q=K.threadID,W=Y.get(q)||[];W.push(V),Y.set(q,W)}else X.push(V)}return wX.flatten(X,(V)=>Y.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Z.get(V.item.id)}))}function qv1(J,Q,Y){return new y1({text:new l(`${J}${Q}`,new J1({color:Y})),maxLines:1})}function xD8(J,Q,Y,Z){return[qv1("+",J,Z.success),f5.horizontal(1),qv1("~",Q,Z.warning),f5.horizontal(1),qv1("-",Y,Z.destructive)]}class J71 extends b6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((F)=>F.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((F)=>F.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],Z=new Set(Y),X=this.props.currentThreadID,G=[...Q].sort((F,U)=>{if(X){if(F.id===X)return-1;if(U.id===X)return 1}let B=Y.indexOf(F.id),D=Y.indexOf(U.id);if(B!==-1&&D!==-1)return B-D;if(B!==-1)return-1;if(D!==-1)return 1;return 0}),V=yD8(G),K=Math.max(0,...V.map((F)=>F.description.timeAgo.length)),q=G6.of(J),W=new z6({padding:F0.symmetric(0,1),child:new j4({child:new y1({text:new l("",new J1({color:q.colors.foreground,dim:!0}),[new l("Ctrl+T",new J1({color:N1.blue,dim:!0})),new l(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new J1({color:q.colors.foreground,dim:!0}))])})})});return new r2({items:V,getLabel:(F)=>F.title,onAccept:(F)=>this.props.onSelect?.(F.id),onDismiss:this.props.onDismiss,onSelectionChange:(F)=>{if(this.props.previewController){if(F)this.props.previewController.select(F.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(F,U,B,D)=>{let L=G6.of(D),{colors:A}=L,w=U?N1.yellow:void 0,I=U?N1.black:A.foreground,P=N1.index(8),R=(a,p)=>new X0({width:p,child:N6.end([new y1({text:new l(a,new J1({color:P}))})])}),C=this.props.threadViewStates[F.id],k=[],_=F.relationshipType==="handoff",f=new a91;if(F.depth>0){let a=[],p=F.ancestorsAreLast.slice(1);for(let H1 of p)a.push(new l(f.getAncestorPrefix(H1),new J1({color:f.connectorColor,dim:f.connectorDim})));let s=F.isLast?f.elbow:f.tee,Z1=f.getConnectorText(s);a.push(new l(Z1,new J1({color:f.connectorColor,dim:f.connectorDim}))),k.push(new y1({text:new l("",void 0,a)}))}let m=[],b=X===F.id?new l("(current) ",new J1({color:N1.green})):Z.has(F.id)?new l("(visited) ",new J1({color:A.foreground,dim:!0})):null;if(b)m.push(new y1({text:b}));if(C){if(C.state==="active"&&(C.interactionState==="tool-running"||C.inferenceState==="running"))m.push(new Kv1),m.push(new X0({width:1}))}let d=F.title;if(F.relationshipType==="fork"){let a=d.match(/^Forked\((\d+)\): /);if(a)d=d.slice(a[0].length);else while(d.startsWith("Forked: "))d=d.slice(8);m.push(new y1({text:new l("[fork] ",new J1({color:N1.blue}))}))}else if(_)m.push(new y1({text:new l("[handoff] ",new J1({color:N1.index(208)}))}));if(m.push(new a6({child:new y1({text:new l(d,new J1({color:I})),overflow:"ellipsis",maxLines:1})})),m.push(new X0({width:2})),F.diffStats&&(F.diffStats.added>0||F.diffStats.changed>0||F.diffStats.deleted>0)){let a=U?{success:P,warning:P,destructive:P}:A;m.push(...xD8(F.diffStats.added,F.diffStats.changed,F.diffStats.deleted,a)),m.push(new X0({width:2}))}return m.push(R(F.description.timeAgo,K)),new m0({decoration:w?{color:w}:void 0,padding:F0.symmetric(2,0),child:new N6({children:[...k,...m]})})}})}}function xZ6(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/60000),X=Math.floor(Y/3600000),G=Math.floor(Y/86400000);if(Z<1)return"just now";if(Z<60)return`${Z}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class Wv1 extends b6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Y=Math.max(0,...Q.map((X)=>xZ6(X.pubDate).length));return new r2({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=G6.of(K),{colors:W}=q,H=G?N1.yellow:void 0,F=G?N1.black:W.foreground,U=N1.index(8),B=X.authors.map((L)=>L.name).join(", ")||"Community",D=(L,A)=>new X0({width:A,child:N6.end([new y1({text:new l(L,new J1({color:U}))})])});return new m0({decoration:H?{color:H}:void 0,padding:F0.symmetric(2,0),child:new N6({children:[new a6({child:new y1({text:new l(X.title,new J1({color:F})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new y1({text:new l(B,new J1({color:U})),maxLines:1}),new X0({width:2}),D(xZ6(X.pubDate),Y)]})})}})}}class Hv1 extends b6{props;constructor(J){super();this.props=J}build(){return new j4({child:new y1({text:new l("",void 0,[new l(`Forked to new thread:
4499
+ ... (output truncated at ${uF} characters)`;X({success:L,output:I.trim(),error:!L?w.trim()||"Command failed":void 0,exitCode:D??void 0})}),H.on("error",(D)=>{clearTimeout(W);let L=D.message;if(q)L=`Command timed out after ${Y}ms`;else if(D.message.includes("operation was aborted")||D.name==="AbortError")L="The command was aborted";X({success:!1,output:F.join(""),error:L})})})}function PD8(J,Q){let{filePath:Y,interpreter:Z,extension:X}=J;if(process.platform==="win32")return TD8(Y,Z?[...Z]:null,X,Q);else return RD8(Y,Z?[...Z]:null,X,Q)}function RD8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];else return[J,Z]}function TD8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Z]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Z]];case".exe":return[J,Z];default:return[J,Z]}}B0();q$();X7();dP();HH();iY();XV();CH();Bq();A8();yg();C7();g_();s0();var eZ6=F6(hL(),1);import{writeFile as rZ6}from"fs/promises";import sZ6 from"path";B0();iY();class Gv1{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.1766044881-gb9246f"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Js(Q,this.configService)}catch(Q){v.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Xw extends c0{props;constructor(J){super();this.props=J}createState(){return new IZ6}}class IZ6 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 PZ6 extends p0{controller=new qZ;focusNode=new M8({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:Z}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=B4.all(new W4(Y.foreground,1,"solid")),q=new vF({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(B)=>{let D=B.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new N6({children:[new m0({decoration:{color:N1.default()},child:new y1({text:new l(">",new J1({color:Y.foreground}))})}),new a6({child:q})]}),H=new m0({padding:F0.symmetric(1,0),child:new y1({text:new l("",void 0,[new l("Command: ",new J1({color:Y.foreground})),new l(this.widget.props.commandName,new J1({color:N1.yellow,bold:!0}))])})}),F=[];if(V)F.push(new l("Enter",new J1({color:Z.keybind}))),F.push(new l(" to submit, ",new J1({color:Y.foreground,dim:!0})));F.push(new l("Esc",new J1({color:Z.keybind}))),F.push(new l(" to cancel",new J1({color:Y.foreground,dim:!0})));let U=new m0({padding:F0.symmetric(1,0),child:new y1({text:new l("",void 0,F)})});return new m0({decoration:{border:K,color:N1.default()},padding:F0.all(1),child:new v0({children:[H,new X0({height:1}),W,new f5,U]})})}}class ou extends c0{props;constructor(J){super();this.props=J}createState(){return new PZ6}}CH();class RZ6 extends p0{controller=new qZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new M8({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>=kU)return!1;let Q=Hj(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:Z}=Q,G=C4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new Zw({controller:this.controller,triggers:[new KW],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(B)=>{this.widget.props.onSubmit(B.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:_8.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new U8({focusNode:this.focusNode,child:K}),W=new m0({constraints:new A6({maxHeight:V}),padding:F0.symmetric(1,0),child:q}),H=new m0({padding:F0.symmetric(1,0),child:new y1({text:new l("",void 0,[new l("Command: ",new J1({color:Y.foreground})),new l(this.widget.props.commandName,new J1({color:N1.yellow,bold:!0}))])})}),F=new m0({padding:F0.symmetric(1,0),child:new y1({text:this.isConfirmingClearInput?new l("",void 0,[new l("Esc",new J1({color:Z.keybind})),new l(" again to clear input",new J1({color:Y.foreground,dim:!0}))]):new l("",void 0,[new l("Press ",new J1({color:Y.foreground,dim:!0})),new l("Enter",new J1({color:Z.keybind})),new l(" to submit, ",new J1({color:Y.foreground,dim:!0})),new l("Esc",new J1({color:Z.keybind})),new l(" to clear",new J1({color:Y.foreground,dim:!0}))])})}),U=[H,new X0({height:1}),new a6({child:W}),new X0({height:1}),F];return new m0({decoration:{border:B4.all(new W4(Y.foreground,1,"solid")),color:N1.default()},padding:F0.all(1),child:new v0({children:U})})}}class _j extends c0{props;constructor(J){super();this.props=J}createState(){return new RZ6}}import{isDeepStrictEqual as kD8}from"node:util";var CD8=/[\\/_ +.#"@[({&]/,jD8=/[\\/_ +.#"@[({&]/g,SD8=/[\s-]/,TZ6=/[\s-]/g;function s51(J,Q,Y,Z,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Z.charAt(G),W=Y.indexOf(q,X),H=0,F,U,B,D;while(W>=0){if(F=s51(J,Q,Y,Z,W+1,G+1,V),F>H){if(W===X)F*=1;else if(SD8.test(J.charAt(W-1))){if(F*=0.9,D=J.slice(X,W-1).match(TZ6),D&&X>0)F*=Math.pow(0.999,D.length)}else if(CD8.test(J.charAt(W-1))){if(F*=0.8,B=J.slice(X,W-1).match(jD8),B&&X>0)F*=Math.pow(0.999,B.length)}else if(F*=0.3,X>0)F*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))F*=0.9999}if(F<0.1&&(Y.charAt(W-1)===Z.charAt(G+1)||Z.charAt(G+1)===Z.charAt(G)&&Y.charAt(W-1)!==Z.charAt(G))){if(U=s51(J,Q,Y,Z,W+1,G+2,V),U*0.1>F)F=U*0.1}if(F>H)H=F;W=Y.indexOf(q,W+1)}return V[K]=H,H}function r51(J){return J.toLowerCase().replace(TZ6," ")}function CZ6(J,Q){let Y=s51(J,Q,r51(J),r51(Q),0,0,{}),Z=Q.trim().split(/\s+/);if(Z.length>1){let X=0,G=0;for(let K of Z){let q=s51(J,K,r51(J),r51(K),0,0,{});if(q===0)return Y;X+=q,G+=K.length}let V=X/Z.length*0.95;return Math.max(Y,V)}return Y}class yj{}class xj{}class t51{}class e51{}class jZ6 extends c0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new SZ6}}class SZ6 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function _D8(J,Q){if(J==="")return{matches:!0,score:1};let Y=CZ6(Q,J);return{matches:Y>0.15,score:Y}}class r2 extends c0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new kZ6}}class kZ6 extends p0{controller=new qZ;focusNode;scrollController=new N5;selectedIndex=0;itemContexts=[];cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new M8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),g8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[0]??null)}),this.recomputeFilteredItems();let J=this.cachedFiltered;this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!kD8(J.props.items,this.widget.props.items)){this.recomputeFilteredItems(),this.ensureSelectedItemVisible();let Q=this.cachedFiltered;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 yj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),g8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof xj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),g8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof t51){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 e51)return this.widget.props.onDismiss?.(),"handled";return"ignored"};recomputeFilteredItems(){let J=this.controller.text,Q=this.widget.props.items,Y=Q.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,..._D8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,X)=>this.widget.props.sortItems(Z,X,J):(Z,X)=>X.score-Z.score).map((Z)=>Z.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;m91(J,{top:Y,bottom:Z},{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(),g8.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 Z=Y[J],X=Z?this.widget.props.isItemDisabled?.(Z)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!X){if(Z)this.widget.props.onAccept(Z)}}};build(J){let Q=G6.of(J),{colors:Y}=Q,Z=this.getFilteredItems(),X=B4.all(new W4(Y.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new vF({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Y.foreground,border:null},maxLines:1}),K=new AX({shortcuts:new Map([[new N4("ArrowDown"),new yj],[new N4("ArrowUp"),new xj],[new N4("Tab"),new yj],[new N4("Tab",{shift:!0}),new xj],[new N4("n",{ctrl:!0}),new yj],[new N4("p",{ctrl:!0}),new xj],[new N4("Enter"),new t51],[new N4("Escape"),new e51]]),focusNode:this.focusNode,child:V}),q=new CJ({actions:new Map([[yj,new C8(this.invoke)],[xj,new C8(this.invoke)],[t51,new C8(this.invoke)],[e51,new C8(this.invoke)]]),child:K}),W=new N6({children:[new m0({decoration:{color:N1.default()},child:new y1({text:new l(">",new J1({color:Y.foreground}))})}),new a6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new X0({height:10,child:new j4({child:new y1({text:new l(L,new J1({color:Y.foreground}))})})})}else if(Z.length===0&&this.widget.props.emptyStateText)H=new a6({child:new j4({child:new y1({text:new l(this.widget.props.emptyStateText,new J1({color:Y.foreground,dim:!0}))})})});else{let L=Z.map((A,w)=>{let I=w===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,R;if(this.widget.props.renderItem)R=this.widget.props.renderItem(A,I,P,J);else{let C=I?N1.yellow:void 0,k=I?N1.black:Y.foreground;R=new m0({decoration:C?{color:C}:void 0,padding:F0.symmetric(2,0),child:new y1({text:new l(this.widget.props.getLabel(A),new J1({color:k,dim:P}))})})}return new jZ6(new z8({onClick:(C)=>this.handleItemClick(w,C.clickCount),child:R}),(C)=>{this.itemContexts[w]=C})});H=new v0({children:L,crossAxisAlignment:"start"})}let F=new a6({child:new z8({onScroll:this.handleScroll,opaque:!1,child:new s9({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new m0({padding:F0.symmetric(1,0),child:new y1({text:new l(this.widget.props.title,new J1({color:N1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new X0({height:1}),F),this.controller.text!==""){let L=Z.length>0?Z[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new m0({padding:F0.vertical(1),child:new j4({child:A})}));else U.push(new X0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new m0({decoration:{border:X,color:N1.default()},padding:F0.symmetric(1,0),child:new v0({children:U})})}}function _Z6(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/60000),X=Math.floor(Y/3600000),G=Math.floor(Y/86400000);if(Z<1)return"just now";if(Z<60)return`${Z}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class Vv1 extends b6{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Y=Math.max(0,...Q.map((X)=>_Z6(X.pubDate).length));return new r2({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=G6.of(K),{colors:W}=q,H=G?N1.yellow:void 0,F=G?N1.black:W.foreground,U=N1.index(8),B=(D,L)=>new X0({width:L,child:N6.end([new y1({text:new l(D,new J1({color:U}))})])});return new m0({decoration:H?{color:H}:void 0,padding:F0.symmetric(2,0),child:new N6({children:[new a6({child:new y1({text:new l(X.title,new J1({color:F})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),B(_Z6(X.pubDate),Y)]})})}})}}class Kv1 extends c0{createState(){return new yZ6}}class yZ6 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 l("●",new J1({color:this.isGreen?N1.green:N1.index(8),bold:!0})),maxLines:1})}}function yD8(J){let Q=new Map,Y=new Map,Z=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Z.set(V.id,K.type);let q=K.threadID,W=Y.get(q)||[];W.push(V),Y.set(q,W)}else X.push(V)}return wX.flatten(X,(V)=>Y.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Z.get(V.item.id)}))}function qv1(J,Q,Y){return new y1({text:new l(`${J}${Q}`,new J1({color:Y})),maxLines:1})}function xD8(J,Q,Y,Z){return[qv1("+",J,Z.success),f5.horizontal(1),qv1("~",Q,Z.warning),f5.horizontal(1),qv1("-",Y,Z.destructive)]}class J71 extends b6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((F)=>F.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((F)=>F.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],Z=new Set(Y),X=this.props.currentThreadID,G=[...Q].sort((F,U)=>{if(X){if(F.id===X)return-1;if(U.id===X)return 1}let B=Y.indexOf(F.id),D=Y.indexOf(U.id);if(B!==-1&&D!==-1)return B-D;if(B!==-1)return-1;if(D!==-1)return 1;return 0}),V=yD8(G),K=Math.max(0,...V.map((F)=>F.description.timeAgo.length)),q=G6.of(J),W=new z6({padding:F0.symmetric(0,1),child:new j4({child:new y1({text:new l("",new J1({color:q.colors.foreground,dim:!0}),[new l("Ctrl+T",new J1({color:N1.blue,dim:!0})),new l(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new J1({color:q.colors.foreground,dim:!0}))])})})});return new r2({items:V,getLabel:(F)=>F.title,onAccept:(F)=>this.props.onSelect?.(F.id),onDismiss:this.props.onDismiss,onSelectionChange:(F)=>{if(this.props.previewController){if(F)this.props.previewController.select(F.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(F,U,B,D)=>{let L=G6.of(D),{colors:A}=L,w=U?N1.yellow:void 0,I=U?N1.black:A.foreground,P=N1.index(8),R=(a,p)=>new X0({width:p,child:N6.end([new y1({text:new l(a,new J1({color:P}))})])}),C=this.props.threadViewStates[F.id],k=[],_=F.relationshipType==="handoff",f=new a91;if(F.depth>0){let a=[],p=F.ancestorsAreLast.slice(1);for(let H1 of p)a.push(new l(f.getAncestorPrefix(H1),new J1({color:f.connectorColor,dim:f.connectorDim})));let s=F.isLast?f.elbow:f.tee,Z1=f.getConnectorText(s);a.push(new l(Z1,new J1({color:f.connectorColor,dim:f.connectorDim}))),k.push(new y1({text:new l("",void 0,a)}))}let m=[],b=X===F.id?new l("(current) ",new J1({color:N1.green})):Z.has(F.id)?new l("(visited) ",new J1({color:A.foreground,dim:!0})):null;if(b)m.push(new y1({text:b}));if(C){if(C.state==="active"&&(C.interactionState==="tool-running"||C.inferenceState==="running"))m.push(new Kv1),m.push(new X0({width:1}))}let d=F.title;if(F.relationshipType==="fork"){let a=d.match(/^Forked\((\d+)\): /);if(a)d=d.slice(a[0].length);else while(d.startsWith("Forked: "))d=d.slice(8);m.push(new y1({text:new l("[fork] ",new J1({color:N1.blue}))}))}else if(_)m.push(new y1({text:new l("[handoff] ",new J1({color:N1.index(208)}))}));if(m.push(new a6({child:new y1({text:new l(d,new J1({color:I})),overflow:"ellipsis",maxLines:1})})),m.push(new X0({width:2})),F.diffStats&&(F.diffStats.added>0||F.diffStats.changed>0||F.diffStats.deleted>0)){let a=U?{success:P,warning:P,destructive:P}:A;m.push(...xD8(F.diffStats.added,F.diffStats.changed,F.diffStats.deleted,a)),m.push(new X0({width:2}))}return m.push(R(F.description.timeAgo,K)),new m0({decoration:w?{color:w}:void 0,padding:F0.symmetric(2,0),child:new N6({children:[...k,...m]})})}})}}function xZ6(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/60000),X=Math.floor(Y/3600000),G=Math.floor(Y/86400000);if(Z<1)return"just now";if(Z<60)return`${Z}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class Wv1 extends b6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Y=Math.max(0,...Q.map((X)=>xZ6(X.pubDate).length));return new r2({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=G6.of(K),{colors:W}=q,H=G?N1.yellow:void 0,F=G?N1.black:W.foreground,U=N1.index(8),B=X.authors.map((L)=>L.name).join(", ")||"Community",D=(L,A)=>new X0({width:A,child:N6.end([new y1({text:new l(L,new J1({color:U}))})])});return new m0({decoration:H?{color:H}:void 0,padding:F0.symmetric(2,0),child:new N6({children:[new a6({child:new y1({text:new l(X.title,new J1({color:F})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new y1({text:new l(B,new J1({color:U})),maxLines:1}),new X0({width:2}),D(xZ6(X.pubDate),Y)]})})}})}}class Hv1 extends b6{props;constructor(J){super();this.props=J}build(){return new j4({child:new y1({text:new l("",void 0,[new l(`Forked to new thread:
4500
4500
 
4501
4501
  `,new J1({color:N1.white,dim:!0})),new l(`"${this.props.newThreadTitle||"Untitled"}"`,new J1({color:N1.white}))]),textAlign:"center"})})}}B0();class vZ6 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){v.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){v.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){if(J.length===0)return null;if(J.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(J))return"Label must be lowercase alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!J.includes(Q.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Q=J.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let Y=this.widget.props.currentLabels||[],Z=this.labels.some((G)=>G.name===Q),X=Y.includes(Q);return!Z&&!X}build(J){let Q=G6.of(J),{colors:Y}=Q,Z=this.currentQuery.trim().toLowerCase(),X=Z.length>0?this.getValidationError(Z):null,G=this.getAvailableLabels(),K=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...G];return new r2({title:"Add Label",items:K,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:X||"Type to create a new label",renderItem:(q,W,H,F)=>{let U=W?N1.yellow:void 0,B=W?N1.black:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let L=this.currentQuery.trim().toLowerCase();return new m0({decoration:U?{color:U}:void 0,padding:F0.symmetric(2,0),child:new y1({text:new l("",void 0,[new l("Create new label: ",new J1({color:B})),new l(L,new J1({color:B,bold:!0}))])})})}return new m0({decoration:U?{color:U}:void 0,padding:F0.symmetric(2,0),child:new y1({text:new l(q.name,new J1({color:B}))})})},filterItem:(q,W)=>{if(this.currentQuery!==W)this.currentQuery=W,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(W);let F=W.trim().toLowerCase();return F.length===0||q.name.includes(F)},sortItems:(q,W,H)=>{let F="__isCreateMarker"in q.item&&q.item.__isCreateMarker,U="__isCreateMarker"in W.item&&W.item.__isCreateMarker;if(F&&!U)return-1;if(!F&&U)return 1;return W.score-q.score}})}}class Fv1 extends c0{props;constructor(J){super();this.props=J}createState(){return new vZ6}}class uV extends c0{props;constructor(J){super();this.props=J}createState(){return new hZ6}}class hZ6 extends p0{_spinner=new IX;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,Z=B4.all(new W4(Y.foreground,1,"solid")),X=this._spinner.toBraille(),G=new y1({textAlign:"center",text:new l("",void 0,[new l(X,new J1({color:N1.yellow})),new l(" ",void 0),new l(this.widget.props.message,new J1({color:Y.foreground}))])}),K=[new a6({child:new v0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[G]})})];if(this.widget.props.onAbort)K.push(new X0({height:2,child:new m0({padding:F0.symmetric(2,0),child:new y1({text:new l("",new J1({dim:!0}),[new l("Press ",new J1({color:Y.foreground})),new l("Esc",new J1({color:Y.info})),new l(" to cancel",new J1({color:Y.foreground}))])})})}));let q=new m0({decoration:new T8(N1.default(),Z),child:new X0({width:60,height:7,child:new v0({mainAxisAlignment:"start",children:K})})});if(this.widget.props.onAbort)return new U8({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}class pV extends c0{props;constructor(J){super();this.props=J}createState(){return new fZ6}}class fZ6 extends p0{scrollController=new N5;scrollAreaKey=new NQ("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof OX}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let Y=Q.size;if(typeof Y.height==="number"&&Y.height>0)return this.viewportHeight=Y.height,Y.height}return this.viewportHeight}build(J){let Q=G6.of(J),Y=this.widget.props.message,Z=(()=>{if(this.isWidgetMessage(Y))return{title:Y.title,type:Y.type};if(Y instanceof Error&&Y.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Y.message};if(Y instanceof Error&&Y.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Y.message};let H=c91(Y);return{title:H.title,type:H.type,description:H.description}})(),X=Z.type==="error"?N1.red:N1.yellow,G=B4.all(new W4(N1.default(),1,"solid")),V=new m0({padding:F0.symmetric(1,0),child:new y1({text:new l(Z.title,new J1({color:X,bold:!0}))})}),K=this.isWidgetMessage(Y)?Y.widget:new y1({text:new l(Z.description,new J1({color:N1.default()})),selectable:!0}),q=new a6({child:new yF({child:new m0({padding:F0.symmetric(1,0),child:new N6({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new a6({child:new s9({controller:this.scrollController,autofocus:!0,child:K})}),new L2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let H=this.scrollController.maxScrollExtent,F=this.scrollController.offset,U=this.getViewportHeight(),B=H+U;return{totalContentHeight:Math.max(B,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(F,0)}}})]})})})}),W=new m0({padding:F0.symmetric(1,0),child:new y1({text:this.widget.props.onRetry?new l("",void 0,[new l("Press ",new J1({color:N1.default(),dim:!0})),new l("R",new J1({color:N1.yellow})),new l(" to retry, ",new J1({color:N1.default(),dim:!0})),new l("Esc",new J1({color:N1.yellow})),new l(" to cancel",new J1({color:N1.default(),dim:!0}))]):new l("Press any key to close",new J1({color:N1.default(),dim:!0,italic:!0}))})});return new U8({onKey:(H)=>{if(this.widget.props.onRetry&&H.key==="r")return this.widget.props.onRetry(),"handled";if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new m0({decoration:{border:G,color:N1.default()},padding:F0.all(1),child:new v0({mainAxisAlignment:"center",children:[V,new X0({height:1}),q,W]})})})}}class zv1 extends b6{build(){return new j4({child:new y1({text:new l("",void 0,[new l(`✓ Thread Shared
4502
4502
 
@@ -4606,7 +4606,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
4606
4606
  `)?`${K}...`:X,W=new J1({color:N1.index(8)}),H=[new l(q,W)];if(V>0){let F=new J1({color:Y.success});for(let U=1;U<=V;U++)H.push(new l(" ")),H.push(new l(`[${U}]`,F))}return new z6({padding:F0.only({bottom:0}),child:new N6({crossAxisAlignment:"start",children:[new z6({padding:F0.only({right:1}),child:new y1({text:new l("•",new J1({color:N1.index(8)}))})}),new a6({child:new y1({text:new l("",void 0,H)})})]})})}}class nh1 extends c0{createState(){return new JV6}}class JV6 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:N1.red}),Y=new J1({color:this._visible?N1.red:N1.transparent()});return new N6({children:[new y1({text:new l("⏺",Y)}),new X0({width:1}),new y1({text:new l("Replay",Q)})]})}}class ih1 extends b6{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,Z=this.entry,X=Z.authors[0]?.name||"Community";if(X.includes("@"))X=X.split("@")[0]??X;let G=" · ",V=50,K=this.truncateToWidth(Z.title,V),q=`${G}${K}`,W=Math.max(1,this.width-q.length-2),H=Z.description.replace(/\s+/g," ").trim(),F=`@${X}: ${H}`,U=this.truncateToWidth(F,W),B=new y1({text:new l(U,new J1({color:Y,dim:!0}))}),D=new y1({text:new l(q,new J1({color:Y,dim:!0}))});return new z8({onClick:()=>o2(J,Z.link),cursor:"pointer",child:new X0({width:this.width,height:1,child:new z6({padding:F0.horizontal(1),child:new N6({children:[new a6({child:new zj(new X0({width:W,height:1,child:B}))}),D]})})})})}truncateToWidth(J,Q){if(J.length<=Q)return J;return J.slice(0,Q-1)+"…"}}s0();function iw8(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/3600000),X=Math.floor(Z/24),G=Math.floor(X/7),V=Math.floor(X/30);if(Z<1)return"Just now";if(Z<24)return`${Z}h ago`;if(X<7)return`${X}d ago`;if(G<=4)return`${G}w ago`;return`${V}mo ago`}class ah1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Y)=>{let Z=this.threadHistoryService.observeThreadList().subscribe((X)=>{Z.unsubscribe(),Y(X)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(Z6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((Z)=>{if(!Q.trim())return!0;let X=Z.title?.toLowerCase()||"untitled",G=Z.id.toLowerCase(),V=Q.toLowerCase();return X.includes(V)||G.includes(V)}).map((Z)=>{let X=new Date(Z.userLastInteractedAt),G=iw8(X),V=Z.id.slice(-8),K=Z.env?.initial.trees?.[0]?.uri;return{id:Z.id,title:Z.title||"Untitled",updatedAt:new Date(Z.userLastInteractedAt).toISOString(),description:{timeAgo:G,title:Z.title||"Untitled",shortThreadID:V},diffStats:Z.summaryStats?.diffStats,workspaceURI:K,parentRelationships:Z.parentRelationships,agentMode:Z.agentMode,details:{messageCount:Z.summaryStats?.messageCount}}})}}B0();A8();A8();lf();function QV6(J){let Q=iM0(J),Y=Array.from(Q.entries()).map(([V,K])=>({path:V,diffStats:K})),Z=Ab0(J),G=lI(J)?.totalInputTokens??0;return{filesAffected:Y,totalTokens:G,totalCredits:Z}}class oh1{currentId=null;current=null;statsCache=new Map;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new N5;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){v.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}getCurrentThread(){return this.current}getCurrentStats(){if(!this.current)return null;let J=this.statsCache.get(this.current.id);if(J&&J.version===this.current.v)return J.stats;let Q=QV6(this.current);return this.statsCache.set(this.current.id,{stats:Q,version:this.current.v}),Q}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){v.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(tD()).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 YV6(J,Q){switch(J){case"update-available":return[new l("A newer Amp is available. Run ",new J1({color:Q.foreground,dim:!0})),new l("amp update",new J1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new l("Update complete, run ",new J1({color:Q.foreground,dim:!0})),new l("amp update",new J1({color:Q.warning})),new l(" to see warnings",new J1({color:Q.foreground,dim:!0}))];case"update-error":return[new l("Update failed, run ",new J1({color:Q.foreground,dim:!0})),new l("amp update",new J1({color:Q.warning})),new l(" to see warnings",new J1({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function tw8(J){return new Promise((Q)=>{ow8("git",["branch","--show-current"],{cwd:J},(Y,Z)=>{if(Y){Q(null);return}let X=Z.trim();Q(X||null)})})}class VV6 extends c0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new d71}}class d71 extends p0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;adReadinessTimeout=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;threadCostInfoLastUsageLedgerLength=0;lastInferenceState=void 0;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;paletteShowOptions=null;threadsForPicker=[];clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new oh1;previewThread=null;todoScrollController=(()=>{let J=new N5;return J.followMode=!1,J})();filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new M8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new M8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;imagePreviewIndex=null;adActionModal=null;threadFeedReader=null;currentThreadFeedEntry=null;threadFeedEntries=[];threadFeedSubscription=null;threadFeedRotationTimer=null;threadFeedHidden=!1;threadFeedTickerQueue=[];hasSubmittedFirstMessage=!1;currentUserInfo=null;newsFeedReader=null;newsFeedEntries=[];newsFeedSubscription=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;previousThreadIdForHint=null;pendingMCPServers=[];mcpTrustSubscription=null;pendingOAuthRequest=null;mcpServers=[];mcpServersSubscription=null;agentModeController=null;freeTierStatus={canUseAmpFree:!1};agentModePulseSeq=0;agentModeSlideProgress=null;agentModeSlideTimer=null;updateState="hidden";updateServiceSubscription=null;toastController=new y_1;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];userDisplayBalanceInfo=null;balanceInfoSubscription=null;async initThreadFeed(){let J=await B6(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 K=V.result,q="user"in K?K.user:K;this.currentUserInfo={username:q.username??void 0,displayName:q.displayName??void 0};let W="ffe10a0c-6c42-41ce-a3a6-38990fd6caf8";if(!Y&&K.team?.id!==W)return}else return}catch(V){v.debug("Failed to fetch user info for thread feed filtering",V);return}let Z="/threads.rss",X=async(V,K)=>{let q=V instanceof Request?V.url:V.toString();return a7(q,K,this.widget.dependencies.configService)},G=BT1();G.get("entries").then((V)=>{if(V){let K=this.filterEntries(V);if(this.threadFeedEntries=K,K.length>0&&!this.currentThreadFeedEntry){let q=[...K].sort((H,F)=>F.pubDate.getTime()-H.pubDate.getTime());this.threadFeedTickerQueue=[...q,...this.threadFeedTickerQueue];let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}),this.threadFeedReader=new ok1(G,X,{url:Z}),this.threadFeedSubscription=this.threadFeedReader.stream().subscribe({next:(V)=>{try{let K=this.filterEntries(V);if(K.length>0){this.threadFeedEntries=[...K,...this.threadFeedEntries];let q=[...K].sort((W,H)=>H.pubDate.getTime()-W.pubDate.getTime());if(this.threadFeedTickerQueue=[...q,...this.threadFeedTickerQueue],!this.currentThreadFeedEntry){let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}catch(K){v.error("Thread feed: error in next handler",K)}},error:(V)=>{v.error("Thread feed error:",V)}}),this.resetThreadFeedRotation()}filterEntries(J){if(!this.currentUserInfo)return J;let{username:Q,displayName:Y}=this.currentUserInfo;return J.filter((Z)=>{return!Z.authors.some((X)=>{let G=X.name;if(!G)return!1;return Q&&G===Q||Y&&G===Y||Q&&G.includes(Q)})})}rotateThreadFeed(){if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);this.threadFeedRotationTimer=setInterval(()=>{let J=this.getNextFeedEntry();if(J)this.setState(()=>{this.currentThreadFeedEntry=J})},30000)}resetThreadFeedRotation(){this.rotateThreadFeed()}getNextFeedEntry(){if(this.threadFeedTickerQueue.length>0)return this.threadFeedTickerQueue.shift();return null}async initNewsFeed(){let J=async(Y)=>{return a7(Y,void 0,this.widget.dependencies.configService)},Q=BT1();this.newsFeedReader=new ak1(Q,J,"/news.rss"),this.newsFeedSubscription=this.newsFeedReader.stream().subscribe({next:(Y)=>{if(Y.length>0)this.setState(()=>{this.newsFeedEntries=[...Y,...this.newsFeedEntries]})},error:(Y)=>{v.error("News feed error:",Y)}})}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:Z}=J,X=Q.messages;for(let G=0;G<X.length;G++){if(this.replayAbortController.signal.aborted)break;let V=X[G];if(!V)continue;if(G>0)await this.replaySleep(J.messageDelayMs);if(V.role==="user"&&Y){let W=V.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
4607
4607
  `);if(W)await this.replayTypeMessage(W,Z)}if(V.role==="assistant"){let W=V.content.some((U)=>U.type==="tool_use"),H=X[G+1],F=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&F){let U={...V,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let B=J.thread.id;this.getMessageScrollController(B).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),V]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,V],this.textController.clear()});let K=J.thread.id;this.getMessageScrollController(K).scrollToBottom()}await this.replaySleep(J.exitDelayMs),_8.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Y=J.split(/(?<=\s)/),Z=60000/Q;for(let X of Y){if(this.replayAbortController.signal.aborted)break;if(this.looksLikePastedContent(X.trim())){await this.replaySleep(150),this.textController.text=this.textController.text+X,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{}),await this.replaySleep(300);continue}let G=Z/X.length;for(let V of X){this.textController.text=this.textController.text+V,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let K=0.8+Math.random()*0.4,q=G*K;await this.replaySleep(q)}}}looksLikePastedContent(J){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(J))return!0;if(J.startsWith("/")&&J.length>10)return!0;if(/^[a-z]:\\/i.test(J))return!0;if(/^[a-f0-9]{7,40}$/i.test(J))return!0;if(/^T-[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(J))return!0;return!1}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return this.agentModeController?.getEffectiveMode()??"smart"}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Y=J.items.filter((G)=>G.type==="toolResult").filter((G)=>G.toolResult.run.status==="in-progress"||G.toolResult.run.status==="queued"),Z=J.subagentActiveTools.filter((G)=>G.toolRun.status==="in-progress"||G.toolRun.status==="queued");return[...Y,...Z].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 l(this.submitDisabledHint,new J1({color:J.foreground,dim:!0}));if(this.isExiting)return new l("Exiting...",new J1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new l("",void 0,[new l("Ctrl+C",new J1({color:Q.keybind})),new l(" again to exit",new J1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new l("",void 0,[new l("Esc",new J1({color:Q.keybind})),new l(" again to clear input",new J1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new l("",void 0,[new l("Escape",new J1({color:Q.keybind})),new l(" to close help",new J1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let Z=this.getEffectiveAgentMode(),X=eh1(Z);return new l("",void 0,[new l("Images aren't supported in ",new J1({color:J.warning,dim:!1})),new l(Z,new J1({color:X})),new l(" mode.",new J1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new l("",void 0,[new l("Esc",new J1({color:Q.keybind})),new l(" again to cancel",new J1({color:J.foreground,dim:!0}))]);return new l("",void 0,[new l("Esc",new J1({color:Q.keybind})),new l(" to cancel",new J1({color:J.foreground,dim:!0}))])}if(this.statusMessage)return new l(this.statusMessage,new J1({color:J.foreground,dim:!0}));let Y=YV6(this.updateState,J);if(Y)return new l("",void 0,Y);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Y}=this.widget.dependencies;if(!Q.mainThread?.id)return;let X=Q.mainThread?.messages.findIndex((G)=>G===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),await Y.handle({type:"thread:truncate",fromIndex:X}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(G){v.error("Failed to edit message:",G)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Y,threadSyncService:Z}=this.widget.dependencies,X=Q.mainThread?.id;if(!X)return;let G=Q.mainThread?.messages.findIndex((V)=>V===J);if(G===void 0||G<=0)return;try{let V=await n3.getOrCreateForThread(Y,X),K=await BC(V,Z,G-1);await this.switchToExistingThread(K)}catch(V){v.error("Failed to fork thread:",V),this.showErrorMessage(`Failed to fork thread: ${V}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Y,worker:Z}=this.widget.dependencies,X=Y.mainThread;if(!X)return;let G=X.messages.findIndex((V)=>V.messageId!==void 0&&V.messageId===J.messageId);if(G===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),this.widget.dependencies.history.add(Q);let V=jN(Q);if(V)await Z.handle({type:"thread:truncate",fromIndex:G}),this.invokeBashCommand(V.cmd,{visibility:V.visibility});else{let K=[{type:"text",text:Q}];if(this.imageAttachments.length>0)K.push(...this.imageAttachments);let q={content:K,agentMode:X.agentMode},W=G===0;if(X.agentMode&&!W&&q.agentMode!==X.agentMode){v.error(`Cannot edit message: This thread uses ${X.agentMode} mode. To change mode, create a new thread.`);return}await Z.handle({type:"user:message",message:q,index:G})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){v.error("Failed to edit message:",V)}};getAffectedFiles=async(J)=>{let{worker:Q,threadState:Y}=this.widget.dependencies;try{let Z=Y.mainThread;if(!Z)return[];let X=Z.messages.findIndex((V)=>V===J);if(X===-1)return[];return(await Q.getFilesAffectedByTruncation(X)).map(f3)}catch(Z){return v.error("Failed to get affected files:",Z),[]}};textController=new qZ;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new N5);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 Z=this.searchElementTreeByKey(J.child,Q);if(Z)return Z}if(J?.children)for(let Z of J.children){let X=this.searchElementTreeByKey(Z,Q);if(X)return X}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{this.toastController.show("Selection copied to clipboard","success",2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Y=process.cwd().replace(process.env.HOME||"","~"),Z=Q?`amp - ${Q} - ${Y}`:"";process.stdout.write(Kk1(Z))}}_handleTextCopy(J){if(J&&J.length>0)this.toastController.show("Selection copied to clipboard","success",2000)}textFieldKey=new Y3("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Q=jN(J);this.currentShellModeStatus=Q?.visibility,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),g8.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 Z=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})}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}),g8.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 Tv1(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 Sv1(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 Z=b0.file(process.cwd()),X=y6(Z);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,threadService:this.widget.dependencies.threadService,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,skillService:this.widget.dependencies.skillService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let G=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),G},setImageAttachments:(G)=>{this.setState(()=>{this.imageAttachments=G})},editorDispatch:(G)=>{switch(G.type){case"set-input":this.textController.clear(),this.textController.insertText(G.input);break;case"insert-text":this.textController.insertText(G.text);break;case"clear":this.textController.clear();break}},submitMessage:(G)=>{return this.proceedWithUserMessage(G)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,mcpService:this.widget.dependencies.mcpService,toolboxService:this.widget.dependencies.toolboxService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus.canUseAmpFree,switchToThread:async(G)=>{return await this.switchToExistingThread(G),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(G,V,K)=>{let q=this.widget.dependencies.threadState.mainThread?.id;if(!q)throw Error("No active thread");let W=setTimeout(()=>{K.throwIfAborted()},60000);try{let H=await this.widget.dependencies.threadService.generateHandoffPrompt(q,G,V,this.widget.dependencies.configService,K,this.widget.dependencies.worker.fs.fileSystemReader());return clearTimeout(W),H}catch(H){throw clearTimeout(W),H}},handleHandoff:async(G,V)=>{let{goal:K,generatedPrompt:q,images:W}=V;if(!K&&!q)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let H=this.widget.dependencies.threadState.mainThread?.id;if(!H)return{ok:!1,error:Error("No active thread")};let F=setTimeout(()=>G.abort(new a51("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let U=await this.widget.dependencies.threadService.createHandoffThread(H,{goal:K,generatedPrompt:q,images:W,filesystem:this.widget.dependencies.worker.fs.fileSystemReader()},this.widget.dependencies.configService,G.signal);return clearTimeout(F),await this.switchToExistingThread(U),{ok:!0}}catch(U){if(clearTimeout(F),U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")))throw G.signal.reason;throw U}}catch(H){return v.error("Failed to create handoff thread",H),{ok:!1,error:H instanceof Error?H:Error(String(H))}}},getGuidanceFiles:async(G)=>{if(!Q.mainThread)return[];return(await cs({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,G)).map((K)=>({uri:K.uri,type:K.type}))},openIdePicker:()=>{this.openIdePicker()},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(G)=>{this.agentModeController?.setMode(G)},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.clustersForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:X,threadViewStates:this.widget.dependencies.workerController.threadViewStates,currentThreadFeedEntry:this.currentThreadFeedEntry,threadFeedEntries:this.threadFeedEntries,threadFeedHidden:this.threadFeedHidden,newsFeedEntries:this.newsFeedEntries,setThreadFeedHidden:(G)=>{this.setState(()=>{this.threadFeedHidden=G})},showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:this.widget.dependencies.features,showStatusMessage:(G,V=2000)=>{if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=G}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},V)},showToast:(G,V="success",K)=>{this.toastController.show(G,V,K)}}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new ah1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.clustersForPicker=oZ6(Q),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await tw8(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(),Z=`bash-${Y}-${Math.random().toString(36).substring(7)}`,X={cmd:J},G=new AbortController;this.widget.dependencies.worker.invokeBashTool(X,G.signal,Q===CN).subscribe({next:(V)=>{this.setState(()=>{if(this.bashInvocations.find((q)=>q.id===Z))this.bashInvocations=this.bashInvocations.map((q)=>q.id===Z?{...q,toolRun:V}:q);else{let q={id:Z,args:X,toolRun:V,startTime:Y,abortController:G,hidden:Q===CN};this.bashInvocations=[...this.bashInvocations,q]}})},error:()=>this.removeBashInvocation(Z),complete:()=>this.removeBashInvocation(Z)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=m76(()=>{let J=this.widget.dependencies.threadID;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(Q.ok)this.setState(()=>{this.threadCostInfo=Q.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J,Q)=>{let Y=J!==this.threadCostInfoLastUsageLedgerLength,Z=Q==="idle"&&this.lastInferenceState==="running";if(this.threadCostInfoLastUsageLedgerLength=J,this.lastInferenceState=Q,Y||Z)this.fetchThreadCostInfo()};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.agentModeController.toggle())this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};startAgentModeSlide=()=>{if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer);this.setState(()=>{this.agentModeSlideProgress=0});let J=400,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(!Zx(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>=kU)return!1;let Y=Hj(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)})};handleImageClick=(J)=>{this.setState(()=>{this.imagePreviewIndex=J})};handleImagePreviewDismiss=()=>{this.setState(()=>{this.imagePreviewIndex=null})};handleImageRemove=(J)=>{this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Q,Y)=>Y!==J),this.imagePreviewIndex=null})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(!Q.ok)v.error("Failed to destruct mysterious message",Q.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Q)=>{v.error("Failed to destruct mysterious message",Q)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Y,unlink:Z,rmdir:X,writeFile:G}=await import("node:fs/promises"),{tmpdir:V}=await import("node:os"),K=await import("node:path");try{let q=await Q(K.join(V(),"amp-edit-")),W=K.join(q,"message.amp.md");await G(W,J,"utf-8"),await QG(W);try{let H=await Y(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")v.error("Failed to read temporary file",H)}try{await Z(W),await X(q)}catch(H){v.warn("Failed to clean up temporary file",H)}}catch(q){v.error("Error opening editor:",q)}};onTextSubmitted=async(J)=>{if(!J.trim()&&this.imageAttachments.length===0)return;let Q=jN(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(UX.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();_8.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),_8.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),_8.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Y)=>{g8.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})})}),B6(this.widget.dependencies.configService.config).then((Y)=>{this.paletteConfig=Y,this.agentModeController=new Q_1({initialCliMode:this.widget.dependencies.initialAgentMode,sessionState:this.widget.dependencies.sessionState??null,freeTierStatus:this.freeTierStatus,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.balanceInfoSubscription=x86(async()=>{let Y=await this.widget.dependencies.internalAPIClient.userDisplayBalanceInfo({},{config:this.widget.dependencies.configService});if(!Y.ok)throw Y.error;return Y.result}).subscribe({next:(Y)=>{this.setState(()=>{this.userDisplayBalanceInfo=Y})},error:(Y)=>{v.debug("Failed to fetch user balance info",Y)}}),this.scheduleAdSubscriptionWithIdeReadiness();let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Y)=>{this.setState(()=>{this.pendingMCPServers=Y})}),fS1((Y)=>{this.setState(()=>{this.pendingOAuthRequest=Y})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((Y)=>{this.setState(()=>{this.mcpServers=Y})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Y)=>{let Z=this.isIdeReadyForAdContext();if(this.setState(()=>{this.ideStatus=Y}),!Z&&this.isIdeReadyForAdContext()){if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(!this.adSubscription)this.subscribeToAds()}}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Y)=>{let Z=this.widget.dependencies.getCurrentWorker();if(!Z){v.warn("No active thread worker found to handle IDE message");return}await new Promise((X)=>setTimeout(X,50)),await Z.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}}),v.debug("Message sent from IDE to agent",{message:Y.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Y)=>{this.textController.insertText(Y),v.debug("Appended text to CLI prompt from IDE",{text:Y.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Y)=>{this.setState(()=>{this.connectedClientsStatus=Y})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Y)=>{this.setState(()=>{this.updateState=Y})}),this.mysteriousMessageSubscription=U91(this.widget.dependencies.configService).pipe(E5((Y)=>Y!=="pending"),Z6((Y)=>B91(Y)?Y.mysteriousMessage??null:null),I4((Y,Z)=>Y?.id===Z?.id)).subscribe((Y)=>{this.setState(()=>{if(Y?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=Y,Y&&!this.mysterySequenceManager)this.mysterySequenceManager=new _91(new Map([[new k91(d71.MYSTERY_SEQUENCE),new ju]])),this.mysteryKeyInterceptorUnsubscribe=_8.instance.addKeyInterceptor((Z)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let X=this.mysterySequenceManager.handleKeyEvent(Z);if(X.consumed){if(X.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=X.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!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 Z=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initThreadFeed(),this.initNewsFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener();let Q=this.widget.dependencies.threadID;if(this.threadCostInfoThreadID!==void 0&&this.threadCostInfoThreadID!==Q)this.threadCostInfo=void 0,this.threadCostInfoThreadID=void 0,this.threadCostInfoLastUsageLedgerLength=0,this.fetchThreadCostInfo();let{threadState:Y}=this.widget.dependencies;this.maybeRefetchThreadCostInfo(Y.mainThread?.usageLedger?.events.length??0,Y.viewState.state==="active"?Y.viewState.inferenceState:void 0)}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(this.adSubscription)this.adSubscription.unsubscribe();if(this.balanceInfoSubscription)this.balanceInfoSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(fS1(null),this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.threadFeedSubscription)this.threadFeedSubscription.unsubscribe();if(this.newsFeedSubscription)this.newsFeedSubscription.unsubscribe();if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null;if(this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(Kk1("")),this.shouldUseProgressBar())process.stdout.write(Z76())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,Z=[...J.items.filter((K)=>K.type==="toolResult").map((K)=>({toolUse:K.toolUse,toolRun:K.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((K)=>K.toolRun.status==="blocked-on-user");if(Z.length===0)return null;let X=Z[0],G=X.toolRun.status==="blocked-on-user"?X.toolRun.toAllow??[]:[],V=X.toolRun.status==="blocked-on-user"?X.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:X.toolUse,toAllow:G}],subthreadID:X.subthreadID,reason:V}}shouldUseProgressBar(){return!1}updateProgressBar(){}static AD_READINESS_TIMEOUT_MS=1000;scheduleAdSubscriptionWithIdeReadiness(){if(this.isIdeReadyForAdContext()){this.subscribeToAds();return}this.adReadinessTimeout=setTimeout(()=>{if(this.adReadinessTimeout=null,!this.adSubscription)this.subscribeToAds()},d71.AD_READINESS_TIMEOUT_MS)}isIdeReadyForAdContext(){let J=this.ideStatus;if(!J||!J.enabled)return!1;return Boolean(J.openFile||J.visibleFiles&&J.visibleFiles.length>0)}subscribeToAds(){if(this.adSubscription)return;this.adSubscription=Ck1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{let J=this.agentModeController?.getMode();return(J&&L9(J)||this.randomAd===null)&&Tk1(this.lastUserInteractionTime)},this.widget.dependencies.codebaseContextService).subscribe({next:(J)=>{if(J){let Q=rw8(16).toString("hex");this.lastAdImpressionId=Q,Promise.resolve().then(() => (p71(),u71)).then(({recordAdEvent:Y})=>{let Z=this.widget.dependencies.worker.thread,X=Z.messages[Z.messages.length-1];Y("viewed",{adId:J.id,advertiserId:J.advertiserId,threadId:Z.id,messageId:X?.messageId,impressionId:Q,placement:"tui",matchType:J.metadata?.matchType,matchedPatterns:J.metadata?.matchedPatterns,candidateAdPoolCount:J.metadata?.candidateAdPoolCount,clientRegion:J.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=J}),g8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}})}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){v.error("No current tool confirmation found");return}let Y=Q.tools[0]?.useBlock;if(!Y){v.error("No tool use block found in confirmation");return}if(J==="allow-all-session")pG("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(X){if(X&&X instanceof Error)this.setState(()=>{this.displayMessage=X});else v.error("Failed to write dangerouslyAllowAll setting:",X);return}if(J==="always-guarded"){let X=Q.tools[0]?.toAllow??[],G=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],V=[...X,...G];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",V,"global")}if(J==="connect-github"){let X=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await o2(this.context,X);return}if(J==="disable-librarian"){let X=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!X.includes(lK))await this.widget.dependencies.settingsStorage.set("tools.disable",[...X,lK],"global")}let Z=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let X={type:"user:tool-input",toolUse:Y.id,value:{accepted:Z}};if(Q.subthreadID)await(await n3.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(X);else await this.widget.dependencies.worker.handle(X)}catch(X){v.error("Failed to send tool confirmation:",X)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let 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}),E81({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 QG(Q.getSettingsFilePath())}catch(Y){let Z=Y instanceof Error?Y.message:String(Y);await this.showErrorMessage(`Failed to open settings: ${Z}`)}};cancelStreamingMessage=async()=>{await n3.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 Z=this.widget.dependencies.worker.thread.id;if(Z!==J)this.recordNavigation(Z)}try{v.info(`[switchToExistingThread] Switching to thread: ${J}`);let Z=await this.widget.dependencies.switchToThread(J);if(v.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${Z.thread.agentMode}`),this.widget.dependencies.worker=Z,this.widget.dependencies.threadID=Z.thread.id,this.widget.dependencies.switchWorker(Z),v.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null),Z.thread.draft)if(v.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof Z.thread.draft==="string")this.textController.insertText(Z.thread.draft);else{let X=Z.thread.draft.filter((K)=>K.type==="text"),G=Z.thread.draft.filter((K)=>K.type==="image"),V=X.map((K)=>K.text).join(`
4608
4608
  `);if(V)this.textController.insertText(V);if(G.length>0)this.setState(()=>{this.imageAttachments=G})}}catch(Z){throw v.error("Failed to switch to thread:",J,Z),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=X2(Q.thread)===0,Z=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Y&&Z!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let X=[{type:"text",text:J}];if(this.imageAttachments.length>0)X.push(...this.imageAttachments);if(Y)this.startAgentModeSlide();if(await Q.handle({type:"user:message",message:{content:X,agentMode:Z}}),Y)E81({agentMode:Z});this.scrollMessageViewToBottom(),this.setState(()=>{if(this.imageAttachments=[],!this.hasSubmittedFirstMessage)this.hasSubmittedFirstMessage=!0}),g8.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((Z)=>Z.type==="handoff"&&Z.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();E81({agentMode:Q}).catch((Y)=>{v.warn("Failed to save session state on exit:",Y)}).finally(()=>{_8.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=sw8();if(J===Q)return"~";if(J.startsWith(Q+Up.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Up.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Up.sep),"…",Q.slice(-2).join(Up.sep)].join(Up.sep)}build(J){let Q=C4.of(J),Y=G6.of(J),Z=Y.base;this.themeColors=Z;let{colors:X,app:G}=Y;this.themeApp=G;let V=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,K=V.thread.agentMode&&L9(V.thread.agentMode),q=this.widget.dependencies.features.some((h6)=>h6.name===jk1.UBI&&h6.enabled),W=this.widget.dependencies.freeTierStatus.canUseAmpFree&&q,H=(K||W)&&this.randomAd!==null,F=!K&&this.currentThreadFeedEntry!==null&&!this.threadFeedHidden,U=Boolean(H),{threadState:B}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let D=this.getCurrentConfirmation(),L=this.widget.dependencies.replayMode,A=Boolean(L),w=B.items,I=B.mainThread||void 0,P=B.subagentToolsByParentID,R=B.todosList;if(A){let h6={...L.thread,messages:this.replayDisplayedMessages};w=kj(h6).items,I=h6,P={};let R6=zU({messages:this.replayDisplayedMessages});R=Array.isArray(R6)?R6:[]}let C=I?.id,k=I,_=A?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),f=(h6)=>new c51({key:new Y3(`preview-message-view-${h6.id}`),items:kj(h6).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:h6,focusNode:new M8({debugLabel:"PreviewFocus"})}),m=this.previewThread,b=m?m.messages.length>2000?new v0({mainAxisSize:"max",children:[new a6({child:new X0}),new z6({padding:F0.all(2),child:new j4({child:new y1({text:new l("Thread too long for preview",new J1({color:X.mutedForeground,dim:!0}))})})})]}):f(m):_?new i51({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal,userDisplayBalanceInfo:this.userDisplayBalanceInfo}):new c51({key:C?new Y3(`message-view-${C}`):void 0,items:w,subagentToolsByParentID:P,controller:C?this.getMessageScrollController(C):new N5,autofocus:!1,onCopy:A?void 0:this._handleTextCopy.bind(this),thread:k,onMessageEditSubmit:A?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:A?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:A?void 0:this.forkMessage,getAffectedFiles:A?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode,completionBuilder:A?void 0:this.getCompletionBuilder()}),d=Math.max(Math.floor(Q.size.height*0.4),12),Q1=this.getCurrentEphemeralError(),a=Q.size.width<40,p=B.mainThread?lI(B.mainThread):void 0,s=y51(J),Z1=this.buildBottomWidget(Q1,D,X,Y,B,R,d,U,A,p,Q,s),H1=new $51({threadViewState:B.viewState,threadTokenUsage:p,threadID:C??null,thread:B.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,mcpServers:this.mcpServers,isNarrow:a,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!D,showingEphemeralError:Boolean(B.viewState.state==="active"&&B.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),o=new o91({bashInvocations:this.bashInvocations}),r=[];if(F&&this.currentThreadFeedEntry)r.push(new ih1({entry:this.currentThreadFeedEntry,width:Q.size.width}));let i=this.getEffectiveAgentMode(),W1=this.currentShellModeStatus,T1=eh1(i),e=!W1?i.length+1:0,L1=Q.capabilities.animationSupport,D1=L1==="disabled"?0:L1==="slow"?30:60,e1=iK(i)?.uiHints?.fasterAnimation?3:1,R1=D1>0&&this.agentModePulseSeq>0?new j9({children:[Z1,new B5({top:0,left:1,right:1,height:1,child:new mh1({color:T1,trigger:this.agentModePulseSeq,fps:D1,speed:e1,leftOffset:e})})]}):Z1;r.push(new a6({child:b}),o);let b1=new j9({children:[new v0({mainAxisSize:"min",children:[H?new Yv1({ad:this.randomAd,onButtonClick:async()=>{let h6=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (p71(),u71)).then(({recordAdEvent:F8})=>{let u8=this.widget.dependencies.worker.thread,t3=u8.messages[u8.messages.length-1];F8("clicked",{adId:h6.id,advertiserId:h6.advertiserId,threadId:u8.id,messageId:t3?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:h6.metadata?.matchType,matchedPatterns:h6.metadata?.matchedPatterns,candidateAdPoolCount:h6.metadata?.candidateAdPoolCount,clientRegion:h6.metadata?.clientRegion})});if(!await o2(this.context,h6.shortDestinationUrl)){let u8=_8.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:u8,url:h6.shortDestinationUrl}})}}}):new X0({height:0}),new m0({constraints:new A6(0,Q.size.width,0,d),child:R1})]}),U?new B5({top:0,left:0,right:0,child:new WV6({userHeight:this.bottomGridUserHeight,maxHeight:d,onInitializeHeight:(h6)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(h6,d)})},onDrag:(h6)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(h6.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let R6=Math.floor(h6.localPosition.y)-this.bottomGridDragStartY,F8=Math.max(4,this.bottomGridDragStartHeight-R6),u8=Math.min(F8,d),t3=Math.floor(u8);if(this.bottomGridUserHeight!==t3)this.setState(()=>{this.bottomGridUserHeight=t3})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new X0({height:0})]});r.push(b1,new X0({height:1,child:new z6({padding:F0.horizontal(1),child:H1})}));let V1=new v0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:r}),B1=A&&L?.showIndicator!==!1?new j9({children:[V1,new B5({top:0,left:0,child:new nh1})]}):V1,F1=new C8(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((R6)=>{v.error("Failed to mark message as interrupted:",R6)}),this.cancelStreamingMessage().catch((R6)=>{v.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 v.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),I1=new C8(()=>{return this.onExitPressed(),"handled"}),w1=new C8(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),v1=new C8(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),f1=new C8(()=>{return _J.instance.toggleAll(),"handled"}),o1=new C8(()=>{return this.widget.dependencies.configService.getLatest().then((h6)=>{pG("internal.showDetailedCosts",!(h6.settings["internal.showDetailedCosts"]??!1))}),"handled"}),x1=new C8(()=>{return _8.instance.toggleFrameStatsOverlay(),"handled"}),r1=new C8(()=>{return _8.instance.tuiInstance.getScreen().markForRefresh(),g8.instance.requestFrame(),"handled"}),V0=new C8(()=>{return this.toggleAgentMode(),"handled"}),l0=new C8(()=>{let R6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:F8}=this.widget.dependencies,u8=F8.mainThread?.id;return u8?this.getMessageScrollController(u8):null})();if(R6){let F8=Math.max(Math.floor(Q.size.height*0.4),10),u8=Q.size.height-F8;R6.animatePageUp(u8,100)}return"handled"}),e0=new C8(()=>{let R6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:F8}=this.widget.dependencies,u8=F8.mainThread?.id;return u8?this.getMessageScrollController(u8):null})();if(R6){let F8=Math.max(Math.floor(Q.size.height*0.4),10),u8=Q.size.height-F8;R6.animatePageDown(u8,100)}return"handled"}),M6=new C8(()=>{let R6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:F8}=this.widget.dependencies,u8=F8.mainThread?.id;return u8?this.getMessageScrollController(u8):null})();if(R6)R6.animateTo(0,100);return"handled"}),L6=new C8(()=>{let R6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:F8}=this.widget.dependencies,u8=F8.mainThread?.id;return u8?this.getMessageScrollController(u8):null})();if(R6)R6.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),F4=new C8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:h6}=this.widget.dependencies;if(!h6.mainThread?.messages.some((F8)=>F8.role==="user"||iI(F8)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),W0=new C8((h6)=>{if(h6.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),j0=new C8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return p91().then(async(h6)=>{if(h6)try{this.handleInsertImage(h6)}finally{try{let{unlink:R6}=await import("node:fs/promises");await R6(h6)}catch{}}}),"handled"}),R0=new Map([[N4.ctrl("c"),new wu],[N4.ctrl("l"),new Tu],[N4.ctrl("o"),new b91],[N4.ctrl("v"),new Au],[N4.alt("s"),new Nj],[N4.ctrl("s"),new Nj],[N4.alt("p"),new Ru],[N4.ctrl("r"),new Iu],[N4.alt("d"),new Pu],[N4.ctrl("t"),new Cu],[N4.key("PageUp"),new x91],[N4.key("PageDown"),new v91],[N4.key("Home"),new h91],[N4.key("End"),new f91],[N4.key("Escape"),new Ou],[N4.ctrl("p"),new Mj("previous")],[N4.ctrl("n"),new Mj("next")],[N4.key("Tab"),new Su]]);if(!o3())R0.set(N4.key("ArrowUp"),new Su);if(!1)R0.set(N4.alt("c"),new Eu);let p6=new C8(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),q8=new C8(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),U4=new C8(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),R4=new Map([[Ou,F1],[Tu,r1],[Nj,V0],[b91,p6],[Au,j0],[Eu,w1],[C91,v1],[Iu,f1],[Pu,o1],[Ru,x1],[Cu,q8],[wu,I1],[x91,l0],[v91,e0],[h91,M6],[f91,L6],[Su,F4],[Mj,W0],[ju,U4]]),z4=[B1];if(this.isShowingConsoleOverlay)z4.push(new yv1);if(this.isShowingHelp&&this.paletteConfig)z4.push(new hv1({commands:this.getPaletteCommands().getAllCommands()}));if(this.isShowingMCPStatusModal)z4.push(new wx1({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)z4.push(new dh1({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.adActionModal)z4.push(new Zv1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(h6)=>{let R6=this.adActionModal.url;if(h6==="copy")try{await _8.instance.tuiInstance.clipboard.writeText(R6),this.setState(()=>{this.displayMessage=new qY("Link copied to clipboard")})}catch(F8){v.error("Failed to copy to clipboard",{error:F8}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:h6}=this.widget.dependencies;z4.push(new uh1({servers:this.pendingMCPServers,onAlwaysTrust:h6.trustAlways.bind(h6),onTrustOnce:h6.trustOnce.bind(h6),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:h6.deny.bind(h6)}))}if(this.pendingOAuthRequest)z4.push(new ch1({request:this.pendingOAuthRequest,onDismiss:()=>{this.setState(()=>{this.pendingOAuthRequest=null})}}));if(this.isShowingFileChangesOverlay)z4.push(new i_1({threadData:B}));if(this.isShowingContextDetailOverlay){let h6=this.threadCostInfo?.costBreakdownURL;z4.push(new xv1({thread:B.mainThread??void 0,tokenUsage:p??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:h6?()=>{o2(J,h6)}:void 0}))}if(this.isShowingConfirmationOverlay)z4.push(new kv1({details:this.confirmationOverlayContent}));if(this.imagePreviewIndex!==null&&this.imagePreviewIndex<this.imageAttachments.length){let h6=this.imageAttachments[this.imagePreviewIndex];if(h6)z4.push(new j4({child:new Rh1({image:h6,imageIndex:this.imagePreviewIndex,onDismiss:this.handleImagePreviewDismiss,onRemove:()=>this.handleImageRemove(this.imagePreviewIndex)})}))}let r6=this.getCommandPaletteContext(J);if(r6&&this.isShowingPalette&&this.paletteConfig)z4.push(new j4({child:new jv1({commandContext:r6,mainThread:B.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)z4.push(new bv1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let n6=new j9({children:z4});if(this.isShowingJetBrainsInstaller)return new cO({child:new CJ({actions:R4,child:new AX({shortcuts:R0,debugLabel:"jetbrains-installer-shortcuts",child:new gh1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new xF({controller:this.toastController,child:new cO({child:new x_1({controller:this.toastController,child:new CJ({actions:R4,child:new AX({shortcuts:R0,debugLabel:"main-app-shortcuts",child:n6})})})})})}buildScrollableTodoList(J,Q,Y){return new KV6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Y})}buildBottomWidget(J,Q,Y,Z,X,G,V,K,q,W,H,F){if(J)return new vv1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new _v1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new ph1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let U=i91(Z),B=this.agentModeController?.isInRestrictedFreeMode()??!1,D=new Zw({key:this.textFieldKey,controller:this.textController,triggers:q?[]:[new KW],completionBuilder:q?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:q?void 0:this.onTextSubmitted,theme:Y,placeholder:q?"Press Ctrl+C to exit":B?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!B&&!this.isShowingStandalonePalette(),shellPromptRules:U,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker,clipboard:_8.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,onImageClick:this.handleImageClick,previousThreadId:this.previousThreadIdForHint&&(X.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:q?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 T1=this.textController.text,e=T1.slice(0,W1)+T1.slice(W1+2);this.textController.text=e,this.textController.cursorPosition=W1}},onSubmit:()=>{this.dismissPalette()},onCancel:()=>{this.dismissPalette()}})}}),L=X.mainThread?.queuedMessages??[],A=Array.isArray(G)&&G.length>0,I=Array.isArray(L)&&L.length>0?new lh1({queuedMessages:L}):void 0,P=A?this.buildScrollableTodoList(G,this.isTextfieldAndAutocompleteFocused&&!B,Z):void 0,R=[],C=this.currentShellModeStatus;if(C)R.push({child:new y1({text:new l(C==="hidden"?"shell mode (incognito)":"shell mode",new J1({color:C==="hidden"?Z.app.shellModeHidden:Z.app.shellMode}))}),position:"top-left"});let _=this.connectedClientsStatus&&this.connectedClientsStatus.enabled?this.connectedClientsStatusExpanded?(this.connectedClientsStatus?.clientID?.length??7)+3:3:0,f=this.agentModeController?.getVisibleModes()??[];if(!C&&f.length>1){let o=this.previewThread,r=o?o.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),i=eh1(r),W1=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,T1=o??W1.thread,e=X2(T1)>0,L1=this.agentModeSlideProgress!==null,D1,e1,R1=(Y1)=>Math.pow(Y1,4);if(L1){D1="top-left";let B1=H.size.width-r.length-4-_,F1=R1(this.agentModeSlideProgress);e1=Math.floor(F1*B1)}else if(e)D1="top-right",e1=_;else D1="top-left",e1=void 0;let b1=e&&!L1,V1;if(L1){let Y1=R1(this.agentModeSlideProgress??0);V1=new J1({color:i,dim:Y1>0.3})}else if(b1)V1=new J1({color:Y.foreground,dim:!0});else V1=new J1({color:i});if(o)R.push({child:new y1({text:new l(r,V1)}),position:D1,offsetX:e1});else{let Y1=!e&&!L1,B1=new y1({text:new l(r,V1)});R.push({child:Y1?new z8({child:B1,onClick:this.toggleAgentMode,cursor:"pointer"}):B1,position:D1,offsetX:e1})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let o=this.connectedClientsStatus,r=o.mode||"disconnected",i=!!o.errorMessage,W1=o.clientID||"unknown",T1,e;if(i)T1="●",e=N1.red;else if(r==="presence")T1="○",e=N1.yellow;else if(r==="connected"&&o.connected)T1="●",e=N1.green;else T1="○",e=N1.yellow;let L1=this.connectedClientsStatusExpanded?`${W1} ${T1}`:T1;R.push({child:new z8({child:new y1({text:new l(L1,new J1({color:e}))}),onClick:this.toggleConnectedClientsStatus,cursor:"pointer"}),position:"top-right",offsetX:-2})}let m=q?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:X.mainThread?.env?.initial.trees?.[0]?.uri,b;if(m)b=b0.parse(m).fsPath;else b=process.cwd();let d=this.toHomeRelative(b),Q1=this.shorten(d),a=!q&&this.currentGitBranch?`${Q1} (${this.currentGitBranch})`:Q1;if(R.push({child:new y1({text:new l(a,new J1({color:Y.foreground,dim:!0}))}),position:"bottom-right"}),this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0&&this.textController.text.trim()==="")R.push({child:new y1({text:new l("",void 0,[new l("press ",new J1({color:Y.foreground,dim:!0})),new l("enter",new J1({color:Z.app.keybind})),new l(" to reference the previous thread",new J1({color:Y.foreground,dim:!0}))])}),position:"bottom-left"});let s=this.previewThread,Z1=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(X2(Z1.thread)>0&&!C&&!s){let o=[],r=new J1({color:Y.foreground,dim:!0}),i=new l(" · ",r);if(W){let W1=W.totalInputTokens/W.maxInputTokens,T1=Math.round(W1*100),e=Math.max(0,Math.min(T1,100)),L1=X51(W1,W.maxInputTokens),D1=r;if(L1==="danger")D1=new J1({color:Y.destructive});else if(L1==="warning")D1=new J1({color:Y.warning});else if(L1==="recommendation")D1=new J1({color:Z.app.recommendation});let e1=Math.round(W.maxInputTokens/1000);o.push(new l(`${e}% of ${e1}k`,D1))}if(F&&this.threadCostInfo){let W1=V71(this.threadCostInfo,{colors:{foreground:Y.foreground},dim:!0});if(W1.length>0){if(o.length>0)o.push(i);o.push(...W1)}}if(o.length>0){let W1=new y1({text:new l("",void 0,o)});R.push({child:F?new z8({child:W1,onClick:this.showContextDetailOverlay,cursor:"pointer"}):W1,position:"top-left"})}}return new p_1({leftChild:new a6({child:D}),rightChild1:I,rightChild2:P,maxHeight:V,overlayTexts:R,borderColor:B||!this.isTextfieldAndAutocompleteFocused?N1.index(8):void 0,hasBanner:K,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,i=Math.max(4,this.bottomGridDragStartHeight-r),W1=Math.min(i,V),T1=Math.floor(W1);if(this.bottomGridUserHeight!==T1)this.setState(()=>{this.bottomGridUserHeight=T1})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!K})}}async function Jf1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)_8.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let Z=()=>null,G=!1;if(G)process.env.AMP_INSPECTOR_ENABLED="1";let V=new TF(G,1000,J.inspectorPort),K=J.features.find((A)=>A.name===jk1.AMP_CONNECT)?.enabled??!1,q=new Jv1({threadService:J.threadService,worker:J.worker,builder:(A,w,I,P,R,C)=>{if(Z=R,J.threadDependencies&&K)ek1(J.threadDependencies,J.configService,R,P,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((f)=>{v.error("Failed to start automatic presence:",f)});let k=R(),_={...J,worker:k,threadID:k.thread.id};return new VV6({..._,threadState:w,workerController:I,switchWorker:P,getCurrentWorker:R,recentThreadIDs:C})}}),W=new d_1({configService:J.configService,child:q}),H=new Ex1({configService:J.configService,child:W}),F=new R_1(H),U=new G6({data:Dj.fromBaseTheme(YG.default()),child:F});try{await Ek1(U,{onRootElementMounted:(A)=>{if(v.info("TUI input ready for user interaction"),G)V.start(A),Q26(A)}})}finally{if(G)V.stop(),Y26();if(J.threadDependencies&&K){let{stopGlobalSession:A}=await Promise.resolve().then(() => (J_1(),r36));A()}}let D=Z()?.thread.id||J.threadID,L=await J.threadService.get(D);if(L&&L.messages.length>0){let A=`${J.ampURL.replace(/\/$/,"")}/threads/${D}`;I26(L,A,J.stdout)}}function eh1(J){let Y=iK(J)?.uiHints?.secondaryColor;if(Y)return N1.rgb(Y.r,Y.g,Y.b);return ew8(J)}class KV6 extends c0{props;constructor(J){super();this.props=J}createState(){return new qV6}}class qV6 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:Z}=this.widget.props;return new N6({crossAxisAlignment:"stretch",children:[new a6({child:new s9({controller:Y,autofocus:!1,child:new Qv1({todos:Q})})}),new L2({controller:Y,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:G}=Y,V=this.viewportHeight,K=X+V;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(V,1),scrollOffset:Math.max(G,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(Z,X=0)=>{if(Z&&"size"in Z&&"children"in Z){let G=Z.children||[];for(let V of G){if(V&&"size"in V){let q=V.size;if(typeof q?.height==="number"&&q.height>0)return q.height}let K=Q(V,X+1);if(K>0)return K}}return 0},Y=Q(J);if(Y>0)return Y;if("size"in J){let Z=J.size;if(typeof Z?.height==="number"&&Z.height>0)return Z.height}return this.viewportHeight}}class WV6 extends b6{props;constructor(J){super();this.props=J}build(J){return new z8({child:new X0({height:1}),cursor:A9.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let Z=J.findRenderObject()?.size.height??0;if(Z>0){this.props.onInitializeHeight(Z);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function ew8(J){let Q=0;for(let X=0;X<J.length;X++){let G=J.charCodeAt(X);Q=(Q<<5)-Q+G,Q=Q&Q}let Y=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],Z=Math.abs(Q)%Y.length;return N1.index(Y[Z])}wk1();try{if(process.platform==="win32")await Promise.resolve().then(() => F6(KS(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){MY.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
4609
- `)}var jb1=Cb1.join(qz0||Cb1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function AT8(J){process.emitWarning=function(Q,Y,Z,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Y||"Warning",K=!1;J.warn(G,{name:V,code:Z})}}function iV(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")pG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")pG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")pG("model.sonnet",Q.useSonnet)}async function kb1(J){try{await MT8(Cb1.dirname(jb1),{recursive:!0}),await DT8(jb1,J,"utf-8")}catch(Q){v.debug("Failed to save last thread ID",Q)}}async function OT8(){try{return(await fW6(jb1,"utf-8")).trim()}catch(J){return null}}function wT8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}async function ET8(J){try{let Q=await F5.getUserInfo({},{config:J,signal:AbortSignal.timeout(5000)});if(Q.ok)return Q.result}catch(Q){v.debug("Failed to fetch user info:",Q)}return}var xW6=[{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??r$,description:`Custom settings file path (overrides the default location ${r$})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(v).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${CO})`},{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:o3(),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:uI.SMART.key,description:`Set the agent mode (${K$().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:K$().map((J)=>J.mode).concat("large")}],vW6=(J)=>("deprecated"in J)&&J.deprecated===!0,IT8=(J)=>("hidden"in J)&&J.hidden===!0,PT8=(J)=>("default"in J),RT8=(J)=>("default"in J)?J.default:void 0;function TT8(J,Q){let Y=Q.args[0],Z=Q.commands.map((G)=>G.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let G=Z.filter((K)=>Y.includes(K)||K.includes(Y)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new h8(o$.unknownCommand(Y),1,V)}}var bW6=null;function Aj5(){return bW6}function fp(J){return{...J,getThreadEnvironment:s41,vfs:wT0({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new Bh(J.fileSystem),generateThreadTitle:Po0,deleteThread:(Q)=>J.threadService.delete(Q)}}var _b1=b0.file(LT8.homedir()),gW6=process.env.XDG_CONFIG_HOME?b0.file(process.env.XDG_CONFIG_HOME):i0.joinPath(_b1,".config");async function UG(J,Q){JD0("0.0.1766016110-gbafd5c");let Y=$z1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([b0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:_b1,userConfigDir:gW6}),{initializeCLITelemetry:Z}=await Promise.resolve().then(() => (p71(),u71));Z(Y);let X=await Y.getLatest();v.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=ve0({configService:Y}),K=new Map,q=()=>K.clear(),W=new XM1(Y,J.settings.getWorkspaceRootPath()),H=jk0({configService:Y,filesystem:h9}),F=sR0({configService:Y,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(a,p,s)=>{let Z1=`${a}:${p}`,H1=K.get(Z1);if(H1)return v.debug("Reusing existing OAuth provider for server",{serverName:a,serverUrl:p}),H1;v.debug("Creating OAuth provider for server",{serverName:a,serverUrl:p});let o=(async()=>{let r=new AL(J.secrets),i=await r.getClientInfo(a,p),W1=s?.scopes??i?.scopes,T1=H96();v.info("OAuth headless mode check",{useHeadless:T1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:Z5.isTTY});let e=void 0;if(T1)e=J.executeMode?W96():q96(a);let L1=new JM1({storage:r,serverName:a,serverUrl:p,clientId:s?.clientId??i?.clientId,clientSecret:s?.clientSecret??i?.clientSecret,authUrl:s?.authUrl??i?.authUrl,tokenUrl:s?.tokenUrl??i?.tokenUrl,scopes:W1,headlessAuthHandler:e});return v.debug("OAuth provider created",{serverName:a,serverUrl:p,hasManualClientId:!!(s?.clientId??i?.clientId),willUseDCR:!(s?.clientId??i?.clientId),scopes:W1,headlessMode:T1,executeMode:J.executeMode}),L1})();return K.set(Z1,o),o}}),U=ig({configService:Y,filesystem:h9,spawn:ZN,skillToolboxDirs:H.skillToolboxDirs}),{initializeToolProviders:B,startToolProviders:D}=await Promise.resolve().then(() => (yW6(),_W6)),L;if(J.executeMode){let a=await B({toolService:G,providers:[F,U],initialTimeout:15000});L=a.registrations;for(let[p,s]of a.initErrors)v.warn(`${p} provider initialization slow or failed:`,s)}else L=D({toolService:G,providers:[F,U]});if(Q.jetbrains)oI("JetBrains");else if(Q.ide&&c96())oI("VS Code");else if(Q.ide&&l96())oI("Neovim");if(J.executeMode)QD0(!0);let A,w=j7.status.pipe(Z6((a)=>Boolean(a.connected&&a.authenticated)),I4()).subscribe((a)=>{if(a){if(!A)A=G.registerTool(Ps0)}else A?.dispose(),A=void 0}),I;if(!J.executeMode){let a=await J.settings.get("fuzzy.alwaysIncludePaths")??[];I=new K81(process.cwd(),{alwaysIncludePaths:a},!0)}else I=new class extends K81{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(Z5.write(`No API key found. Starting login flow...
4609
+ `)}var jb1=Cb1.join(qz0||Cb1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function AT8(J){process.emitWarning=function(Q,Y,Z,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Y||"Warning",K=!1;J.warn(G,{name:V,code:Z})}}function iV(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")pG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")pG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")pG("model.sonnet",Q.useSonnet)}async function kb1(J){try{await MT8(Cb1.dirname(jb1),{recursive:!0}),await DT8(jb1,J,"utf-8")}catch(Q){v.debug("Failed to save last thread ID",Q)}}async function OT8(){try{return(await fW6(jb1,"utf-8")).trim()}catch(J){return null}}function wT8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}async function ET8(J){try{let Q=await F5.getUserInfo({},{config:J,signal:AbortSignal.timeout(5000)});if(Q.ok)return Q.result}catch(Q){v.debug("Failed to fetch user info:",Q)}return}var xW6=[{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??r$,description:`Custom settings file path (overrides the default location ${r$})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(v).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${CO})`},{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:o3(),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:uI.SMART.key,description:`Set the agent mode (${K$().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:K$().map((J)=>J.mode).concat("large")}],vW6=(J)=>("deprecated"in J)&&J.deprecated===!0,IT8=(J)=>("hidden"in J)&&J.hidden===!0,PT8=(J)=>("default"in J),RT8=(J)=>("default"in J)?J.default:void 0;function TT8(J,Q){let Y=Q.args[0],Z=Q.commands.map((G)=>G.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let G=Z.filter((K)=>Y.includes(K)||K.includes(Y)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new h8(o$.unknownCommand(Y),1,V)}}var bW6=null;function Aj5(){return bW6}function fp(J){return{...J,getThreadEnvironment:s41,vfs:wT0({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new Bh(J.fileSystem),generateThreadTitle:Po0,deleteThread:(Q)=>J.threadService.delete(Q)}}var _b1=b0.file(LT8.homedir()),gW6=process.env.XDG_CONFIG_HOME?b0.file(process.env.XDG_CONFIG_HOME):i0.joinPath(_b1,".config");async function UG(J,Q){JD0("0.0.1766044881-gb9246f");let Y=$z1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([b0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:_b1,userConfigDir:gW6}),{initializeCLITelemetry:Z}=await Promise.resolve().then(() => (p71(),u71));Z(Y);let X=await Y.getLatest();v.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=ve0({configService:Y}),K=new Map,q=()=>K.clear(),W=new XM1(Y,J.settings.getWorkspaceRootPath()),H=jk0({configService:Y,filesystem:h9}),F=sR0({configService:Y,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(a,p,s)=>{let Z1=`${a}:${p}`,H1=K.get(Z1);if(H1)return v.debug("Reusing existing OAuth provider for server",{serverName:a,serverUrl:p}),H1;v.debug("Creating OAuth provider for server",{serverName:a,serverUrl:p});let o=(async()=>{let r=new AL(J.secrets),i=await r.getClientInfo(a,p),W1=s?.scopes??i?.scopes,T1=H96();v.info("OAuth headless mode check",{useHeadless:T1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:Z5.isTTY});let e=void 0;if(T1)e=J.executeMode?W96():q96(a);let L1=new JM1({storage:r,serverName:a,serverUrl:p,clientId:s?.clientId??i?.clientId,clientSecret:s?.clientSecret??i?.clientSecret,authUrl:s?.authUrl??i?.authUrl,tokenUrl:s?.tokenUrl??i?.tokenUrl,scopes:W1,headlessAuthHandler:e});return v.debug("OAuth provider created",{serverName:a,serverUrl:p,hasManualClientId:!!(s?.clientId??i?.clientId),willUseDCR:!(s?.clientId??i?.clientId),scopes:W1,headlessMode:T1,executeMode:J.executeMode}),L1})();return K.set(Z1,o),o}}),U=ig({configService:Y,filesystem:h9,spawn:ZN,skillToolboxDirs:H.skillToolboxDirs}),{initializeToolProviders:B,startToolProviders:D}=await Promise.resolve().then(() => (yW6(),_W6)),L;if(J.executeMode){let a=await B({toolService:G,providers:[F,U],initialTimeout:15000});L=a.registrations;for(let[p,s]of a.initErrors)v.warn(`${p} provider initialization slow or failed:`,s)}else L=D({toolService:G,providers:[F,U]});if(Q.jetbrains)oI("JetBrains");else if(Q.ide&&c96())oI("VS Code");else if(Q.ide&&l96())oI("Neovim");if(J.executeMode)QD0(!0);let A,w=j7.status.pipe(Z6((a)=>Boolean(a.connected&&a.authenticated)),I4()).subscribe((a)=>{if(a){if(!A)A=G.registerTool(Ps0)}else A?.dispose(),A=void 0}),I;if(!J.executeMode){let a=await J.settings.get("fuzzy.alwaysIncludePaths")??[];I=new K81(process.cwd(),{alwaysIncludePaths:a},!0)}else I=new class extends K81{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(Z5.write(`No API key found. Starting login flow...
4610
4610
  `),!await CT8(J))await jO(),process.exit(1)}let P=await vk0({isDevelopment:!1}),R=new CT1(P,Y),C=new NT1(P,{lazy:!0}),k=Q.notifications!==void 0?Q.notifications:!J.executeMode,_=fe0({playNotificationSound:async(a)=>{if(k){he0(a);let p=Ak1(),s=Ok1();if((!p||s)&&X.settings["notifications.system.enabled"]!==!1){if(a==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(a==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:R,configService:Y});v.info("Starting Amp background services");let f=To0({threadService:R,threadHistoryService:C,configService:Y,isExtensionDevelopment:!1}),m;j7.status.subscribe((a)=>{m=a});let b=new lG1({workspaceRoots:[b0.file(process.cwd())],getCurrentFile:()=>{if(!m?.openFile)return;try{return b0.parse(m.openFile)}catch(a){v.warn("Failed to parse current file URI",{uri:m.openFile,error:a});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let a=m.openFile;return m.visibleFiles.filter((p)=>p!==a).map((p)=>{try{return b0.parse(p)}catch(s){return v.warn("Failed to parse visible file URI",{uri:p,error:s}),null}}).filter((p)=>p!==null)}}),d=new Ik1,Q1={codebaseContextService:b,configService:Y,toolService:G,mcpService:F,skillService:H,toolboxService:U,trustStore:W,threadService:R,threadHistoryService:C,threadSyncService:f,threadStorage:P,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:I,notificationService:_,fileSystem:Q.jetbrains||Q.ide?LT0:h9,terminal:d};return{...Q1,async asyncDispose(){if(Q1.mcpService.hasAuthenticatingClients())v.info("Waiting for OAuth authentication to complete before exit..."),await Q1.mcpService.waitForAuthentication();for(let a of L.values())a.dispose();await Q1.mcpService.dispose(),q(),await Q1.threadService.asyncDispose(),Q1.configService.unsubscribe(),V(),Q1.fuzzyServer.dispose(),Q1.threadSyncService.dispose(),Q1.settingsStorage[Symbol.dispose](),w.unsubscribe(),A?.dispose()}}}async function CT8(J){if(!J.executeMode){if(!await sS1("Would you like to log in to Amp? [(y)es, (n)o]: "))return Z5.write(`Login cancelled. Run the command again to retry.
4611
4611
  `),!1}return await mW6(J)}async function mW6(J){let Q=NT8(32).toString("hex"),Y=await rS1(J.ampURL,Q),Z=new AbortController;try{await QU(Y,Z.signal)}catch(G){v.error("Error opening browser",{error:G})}let X=await rS1(J.ampURL,Q,!1);Z5.write(`If your browser does not open automatically, visit:
4612
4612
 
@@ -4616,7 +4616,7 @@ ${C6.blue.bold(X)}
4616
4616
  Login successful! You can now use the Amp CLI.
4617
4617
  `),!0}catch(G){return v.error("Login failed",{error:G}),MY.write(`
4618
4618
  Login failed: ${G instanceof Error?G.message:String(G)}
4619
- `),!1}}function jT8(){let J=new NO().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)fC(),process.exit(0);let F=H.originalError??H;y86(F)}),J.option("-V, --version","Print the version number and exit",()=>{let F;try{F=`, ${iP(new Date("2025-12-18T00:07:15.449Z"))} ago`}catch{}Z5.write(`0.0.1766016110-gbafd5c (released 2025-12-18T00:07:15.449Z${F??""})
4619
+ `),!1}}function jT8(){let J=new NO().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)fC(),process.exit(0);let F=H.originalError??H;y86(F)}),J.option("-V, --version","Print the version number and exit",()=>{let F;try{F=`, ${iP(new Date("2025-12-18T08:06:38.200Z"))} ago`}catch{}Z5.write(`0.0.1766044881-gb9246f (released 2025-12-18T08:06:38.200Z${F??""})
4620
4620
  `),process.exit(0)}),J.addHelpText("after",u96()),J.configureHelp({formatHelp:p96}),J.command("logout").description("Log out by removing stored API key").action(async(H,F)=>{let U=F.optsWithGlobals(),B=await RQ(U);await yT8(B)}),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,F)=>{let U=F.optsWithGlobals(),B=await RQ(U);await _T8(B,await gS1(U,B.settings))});let Q=async(H,F,U)=>{$z1({storage:F.settings,secretStorage:F.secrets,workspaceRoots:Q0.of([b0.file(process.cwd())]),defaultAmpURL:F.ampURL,homeDir:_b1,userConfigDir:gW6});let B={...F,executeMode:!1};await Sb1(B,{...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,F)=>{let U=F.optsWithGlobals(),B=await RQ(U);await hW6(U,B,F)});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,F)=>{let U=F.optsWithGlobals(),B=await RQ(U);await mT8(U,B,F)}),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,F,U)=>{let B=U.optsWithGlobals(),D=await RQ(B);if(F.pick)MY.write(`${C6.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
4621
4621
  `);if(F.last||H||D.executeMode)await gT8(B,D,H,U);else await Q(B,D,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,F,U)=>{let B=U.optsWithGlobals(),D=await RQ(B);await bT8(B,D,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,F)=>{let U=F.optsWithGlobals(),B=await RQ(U);await hW6(U,B,F)}),Y.command("search <query>").alias("find").summary("Search threads").description(`Search for threads using a query DSL.
4622
4622
 
@@ -4632,8 +4632,8 @@ All matching is case-insensitive. File paths use partial matching.`).option("-n,
4632
4632
  Or pipe via stdin: echo "your message" | amp --execute`);iV(Y,Q);let V=await UG(J,Q);bW6=V;let K=fp(V),q=await ET8(V.configService),W=wT8(q?.email);if((J.executeMode||Q.streamJson)&&L9(Q.mode)&&!W)throw new h8(`Execute mode is not permitted with --mode '${Q.mode}'`,1);let H=async(b)=>{let d=await fW6(b,"utf-8"),Q1=JSON.parse(d);if(!H$(Q1.id))throw new h8(o$.invalidThreadId);return k31(V,{visibility:Z,agentMode:Q.mode,thread:Q1})},F=async(b)=>{if(!H$(b))throw new h8(o$.invalidThreadId);try{let[Q1,a]=await Promise.all([F5.getThreadLinkInfo({thread:b},{config:V.configService}),F5.getUserInfo({},{config:V.configService})]);if(Q1.ok&&a.ok){let p=Q1.result.creatorUserID,s=a.result.id;if(p&&p!==s&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new h8(`Cannot resume thread created by another user.
4633
4633
 
4634
4634
  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(Q1){if(Q1 instanceof h8)throw Q1;v.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q1})}let d=await V.threadService.get(b)??void 0;return v.info(`[fetchAndStartThread] Loaded thread ${b}, agentMode: ${d?.agentMode??"undefined"}`),k31(V,{visibility:Z,agentMode:d?void 0:Q.mode,thread:d})},U=async()=>{try{if(Q.threadId)return F(Q.threadId);else return k31(V,{visibility:Z,agentMode:Q.mode})}catch(b){if(b instanceof h8)throw b;throw await ym(b,Q.threadId),Error("handleError should have called process.exit()")}},B=async()=>{return k31(V,{visibility:Z,agentMode:Q.mode})};if(Q.format==="jsonl")MY.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
4635
- `),await jO(),process.exit(1);if(J.executeMode&&Q.remote)await k56(X,G,V.configService),await V.asyncDispose(),process.exit(0);let D=await U();if(J.executeMode)E56(V.mcpService,J.settings),await o86(D,D.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,W,Q.mode),await V.asyncDispose(),process.exit(0);let L=!1,A=!1,w=!1;if(Q.jetbrains||Q.ide){await UD0();let b=eI({jetbrainsOnly:Q.jetbrains});if(b.length===0){if(Q.jetbrains)A=!await V.configService.get("jetbrains.skipInstall")}else if(b.length===1){let d=b[0];if(d)j7.selectConfig(d)}else w=!0}let I=D81("0.0.1766016110-gbafd5c",V.settingsStorage),P=new I61(V.threadStorage),R=Q0.of([b0.file(process.cwd())]),C=JV1(void 0,R),k=new L81(V.mcpService,J.settings.getWorkspaceRootPath());if(X)D.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let f=await(async()=>{try{let b=await F5.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(b.ok)return v.info("User free tier status:",b),b.result}catch(b){throw v.error("Failed to fetch free tier status:",b),b}})(),m=await v56();v.info("Loaded session state:",m),await Jf1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new Q81,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,threadID:D.threadID,threadFuzzyIndexer:P,worker:D,workerDeps:K,skillService:K.skillService,configService:V.configService,internalAPIClient:F5,ampURL:J.ampURL,startNewThread:B,switchToThread:F,ideClient:j7,connectedClientsService:new ma,commandRegistry:C,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:k,showJetBrainsInstaller:A,showIdePicker:L,showIdePickerHint:w,openThreadSwitcher:Q.openThreadSwitcher,updateService:I,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:m,freeTierStatus:{canUseAmpFree:f.canUseAmpFree},workspace:q?.team??null,features:q?.features??[],isDogfooding:W,threadDependencies:V,initialAgentMode:Y.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function RQ(J){if(J.interactive)MY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4636
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,Z=await P96({...J,workspaceTrust:{current:!0,changes:u_},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await O56(J.mcpConfig);Z=w56(Z,G)}let X=await Z.get("url","global");if(!X)X=_Y;if(!YU(X))v.info("Targeting custom Amp server",{ampURL:X});return Z=KU0(Z),{executeMode:Q,isTTY:Y,ampURL:X,settings:Z,secrets:_56(await gS1(J,Z))}}function ST8(J){let Q={};for(let Y=0;Y<J.length;Y++){let Z=J[Y];if(Z?.startsWith("--")){let G=Z.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Y+1];if(V&&!V.startsWith("--"))Q[G]=V,Y++}}return Q}async function kT8(){let J=ST8(process.argv);if(I86({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),AT8(v),v.info("Starting Amp CLI.",{version:"0.0.1766016110-gbafd5c",buildTimestamp:"2025-12-18T00:07:15.449Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new h8(o$.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await jT8().parseAsync(process.argv)}$T1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await kT8().catch(ym)});async function _T8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),Z5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4635
+ `),await jO(),process.exit(1);if(J.executeMode&&Q.remote)await k56(X,G,V.configService),await V.asyncDispose(),process.exit(0);let D=await U();if(J.executeMode)E56(V.mcpService,J.settings),await o86(D,D.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,W,Q.mode),await V.asyncDispose(),process.exit(0);let L=!1,A=!1,w=!1;if(Q.jetbrains||Q.ide){await UD0();let b=eI({jetbrainsOnly:Q.jetbrains});if(b.length===0){if(Q.jetbrains)A=!await V.configService.get("jetbrains.skipInstall")}else if(b.length===1){let d=b[0];if(d)j7.selectConfig(d)}else w=!0}let I=D81("0.0.1766044881-gb9246f",V.settingsStorage),P=new I61(V.threadStorage),R=Q0.of([b0.file(process.cwd())]),C=JV1(void 0,R),k=new L81(V.mcpService,J.settings.getWorkspaceRootPath());if(X)D.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let f=await(async()=>{try{let b=await F5.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(b.ok)return v.info("User free tier status:",b),b.result}catch(b){throw v.error("Failed to fetch free tier status:",b),b}})(),m=await v56();v.info("Loaded session state:",m),await Jf1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new Q81,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,threadID:D.threadID,threadFuzzyIndexer:P,worker:D,workerDeps:K,skillService:K.skillService,configService:V.configService,internalAPIClient:F5,ampURL:J.ampURL,startNewThread:B,switchToThread:F,ideClient:j7,connectedClientsService:new ma,commandRegistry:C,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:k,showJetBrainsInstaller:A,showIdePicker:L,showIdePickerHint:w,openThreadSwitcher:Q.openThreadSwitcher,updateService:I,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:m,freeTierStatus:{canUseAmpFree:f.canUseAmpFree},workspace:q?.team??null,features:q?.features??[],isDogfooding:W,threadDependencies:V,initialAgentMode:Y.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function RQ(J){if(J.interactive)MY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4636
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,Z=await P96({...J,workspaceTrust:{current:!0,changes:u_},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await O56(J.mcpConfig);Z=w56(Z,G)}let X=await Z.get("url","global");if(!X)X=_Y;if(!YU(X))v.info("Targeting custom Amp server",{ampURL:X});return Z=KU0(Z),{executeMode:Q,isTTY:Y,ampURL:X,settings:Z,secrets:_56(await gS1(J,Z))}}function ST8(J){let Q={};for(let Y=0;Y<J.length;Y++){let Z=J[Y];if(Z?.startsWith("--")){let G=Z.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Y+1];if(V&&!V.startsWith("--"))Q[G]=V,Y++}}return Q}async function kT8(){let J=ST8(process.argv);if(I86({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),AT8(v),v.info("Starting Amp CLI.",{version:"0.0.1766044881-gb9246f",buildTimestamp:"2025-12-18T08:06:38.200Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new h8(o$.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await jT8().parseAsync(process.argv)}$T1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await kT8().catch(ym)});async function _T8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),Z5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4637
4637
  `);else if(!YU(J.ampURL))Z5.write(`Logging in to ${new URL(J.ampURL).hostname}
4638
4638
  `);let Y=process.env.AMP_API_KEY;if(Y)Z5.write(`API key found in environment variable, storing...
4639
4639
  `),await Q.set("apiKey",Y,J.ampURL),Z5.write(`API key successfully stored.
@@ -4646,7 +4646,7 @@ This thread belongs to a different user and cannot be continued for security rea
4646
4646
  `);else Z5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
4647
4647
  `);process.exit(0)}async function xT8(J,Q,Y,Z,X){iV(X,J);let G=await UG(Q,J);try{let V=_31(Y);if(!V)y31(Y);let K=V,q=Z.trim();if(q.length===0)CX("Thread name cannot be empty");if(q.length>256)CX("Thread name cannot exceed 256 characters");if(!(await qS(K,G)).messages.length)CX("Cannot rename an empty thread.");let H=fp(G);await(await n3.getOrCreateForThread(H,K)).handle({type:"title",value:q}),v.info("GOT HERE"),await G.threadSyncService.sync(),v.info("GOT THERE"),Z5.write(C6.green(`✓ Thread ${K} renamed to "${q}"
4648
4648
  `)),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose();let K=`Failed to rename thread: ${V instanceof Error?V.message:String(V)}`;CX(K)}}async function vT8(J,Q,Y,Z){iV(Z,J);let X=await UG(Q,J);try{let G=_31(Y);if(!G)y31(Y);let K=await qS(G,X),q=FC(K);Z5.write(q+`
4649
- `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;CX(V)}}async function hT8(J,Q,Y,Z,X){iV(X,J);let G=await UG(Q,J);try{let V=await yb1(Y),K=await qS(V,G),q=Z.typing!==!1,W=parseInt(Z.wpm||"120",10),H=parseInt(Z.messageDelay||"1000",10),F=parseInt(Z.toolProgressDelay||"800",10),U=parseInt(Z.exitDelay||"3",10)*1000,B=Z.indicator!==!1,D=fp(G),L=K.id;await G.threadStorage.set(L,K);let A=await n3.getOrCreateForThread(D,L);await A.resume();let w=E61.fromWorker(A),I=new I61(G.threadStorage),P=Q0.of([b0.file(process.cwd())]),R=JV1(void 0,P),C=new L81(G.mcpService,Q.settings.getWorkspaceRootPath()),k=D81("0.0.1766016110-gbafd5c",G.settingsStorage),_=ig({configService:G.configService,filesystem:h9,spawn:ZN,skillToolboxDirs:G.skillService.skillToolboxDirs});await Jf1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new Q81,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,threadID:L,threadFuzzyIndexer:I,worker:w,workerDeps:D,skillService:D.skillService,configService:G.configService,internalAPIClient:F5,ampURL:Q.ampURL,startNewThread:async()=>w,switchToThread:async()=>w,ideClient:j7,connectedClientsService:new ma,commandRegistry:R,mcpService:G.mcpService,toolboxService:_,mcpTrustHandler:C,showJetBrainsInstaller:!1,updateService:k,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:F,exitDelayMs:U,showIndicator:B},freeTierStatus:{canUseAmpFree:!0},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await ym(V,Y)}}async function fT8(J,Q,Y,Z,X){iV(Z,J);let G=await UG(Q,J);try{let V=_31(Y);if(!V)y31(Y);let K=V,q=await F5.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=A81(J,W);if(!H&&!X)CX("Must specify either --visibility or --support");if(H&&X)CX("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)CX(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,O81(H)),Z5.write(C6.green("✓ ")+`Thread ${K} visibility changed to ${H}.
4649
+ `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;CX(V)}}async function hT8(J,Q,Y,Z,X){iV(X,J);let G=await UG(Q,J);try{let V=await yb1(Y),K=await qS(V,G),q=Z.typing!==!1,W=parseInt(Z.wpm||"120",10),H=parseInt(Z.messageDelay||"1000",10),F=parseInt(Z.toolProgressDelay||"800",10),U=parseInt(Z.exitDelay||"3",10)*1000,B=Z.indicator!==!1,D=fp(G),L=K.id;await G.threadStorage.set(L,K);let A=await n3.getOrCreateForThread(D,L);await A.resume();let w=E61.fromWorker(A),I=new I61(G.threadStorage),P=Q0.of([b0.file(process.cwd())]),R=JV1(void 0,P),C=new L81(G.mcpService,Q.settings.getWorkspaceRootPath()),k=D81("0.0.1766044881-gb9246f",G.settingsStorage),_=ig({configService:G.configService,filesystem:h9,spawn:ZN,skillToolboxDirs:G.skillService.skillToolboxDirs});await Jf1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new Q81,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,threadID:L,threadFuzzyIndexer:I,worker:w,workerDeps:D,skillService:D.skillService,configService:G.configService,internalAPIClient:F5,ampURL:Q.ampURL,startNewThread:async()=>w,switchToThread:async()=>w,ideClient:j7,connectedClientsService:new ma,commandRegistry:R,mcpService:G.mcpService,toolboxService:_,mcpTrustHandler:C,showJetBrainsInstaller:!1,updateService:k,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:F,exitDelayMs:U,showIndicator:B},freeTierStatus:{canUseAmpFree:!0},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await ym(V,Y)}}async function fT8(J,Q,Y,Z,X){iV(Z,J);let G=await UG(Q,J);try{let V=_31(Y);if(!V)y31(Y);let K=V,q=await F5.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=A81(J,W);if(!H&&!X)CX("Must specify either --visibility or --support");if(H&&X)CX("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)CX(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,O81(H)),Z5.write(C6.green("✓ ")+`Thread ${K} visibility changed to ${H}.
4650
4650
  `);if(X){await qS(K,G);let F=typeof X==="string"?X:void 0;await iC0(G.threadService,K,G.configService,F),Z5.write(C6.green("✓ ")+`Thread ${K} has been shared with Amp support. These thread reports will be aggregated and analysed.
4651
4651
  `)}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),CX(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function bT8(J,Q,Y,Z){iV(Z,J);let X=await UG(Q,J),G=fp(X);try{let V=await yb1(Y),q=(await qS(V,X)).messages.length-1,W=await n3.getOrCreateForThread(G,V),H=await BC(W,X.threadSyncService,q);await Promise.all([X.threadSyncService.uploadThread(V),X.threadSyncService.uploadThread(H)]),await kb1(H),Z5.write(`${H}
4652
4652
  `),await X.asyncDispose(),process.exit(0)}catch(V){MY.write(`Error forking thread: ${V instanceof Error?V.message:String(V)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1766016110-gbafd5c",
3
+ "version": "0.0.1766044881-gb9246f",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {