@sourcegraph/amp 0.0.1780803750-g55245f → 0.0.1780818304-g58b217

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 +13 -13
  2. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -2777,7 +2777,7 @@ ${B}`}async function X46(A,Q){if(!Q?.forceExternal&&Q?.onShowImagePreview&&FW4(A
2777
2777
  `).length,E=new D0({text:new g(A,new A0({color:$}))});if(B<=w80)return E;return new y0({width:1/0,height:w80,child:new vB({autofocus:!1,controller:Q,child:E})})}function PB6(){return new Map([[wA.key("PageUp"),new u80],[wA.key("PageDown"),new kg0],[wA.ctrl("u"),new u80],[wA.shift("Home"),new fg0],[wA.shift("End"),new xg0]])}function TB6(A,Q,$){return Math.max(Q,Math.min(A,$))}var yg0=8,hN4=1,gN4=yg0-1;class bg0 extends G4{}class hg0 extends G4{}class M80 extends G4{}class O80 extends G4{}class gg0 extends G4{}class mg0 extends G4{}class dg0 extends d0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new mN4}}class mN4 extends m0{messageScroll=new a6;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,$=vB6(Q,this.messageScroll),B=_B6(Q.options.message),E=B?new N4({actions:this.buildScrollActions(),child:new rQ({debugLabel:"SelectDialogScrollShortcuts",shortcuts:kB6(),child:$})}):$,D=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if(B)D.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return D.push({keys:["Esc"],label:"cancel"}),new E1({header:Q.options.title,minWidth:64,maxWidth:80,footer:D,autofocus:!1,onDismiss:Q.onCancel,child:E})}buildScrollActions(){let A=(Q)=>{let $=fB6(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo($)};return new Map([[bg0,new cA(()=>A(-hN4))],[hg0,new cA(()=>A(hN4))],[M80,new cA(()=>A(-gN4))],[O80,new cA(()=>A(gN4))],[gg0,new cA(()=>this.messageScroll.jumpTo(0))],[mg0,new cA(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function vB6(A,Q){let $=A.options.options.map((E)=>({value:E,label:E})),B=Math.max(0,$.findIndex((E)=>E.value===A.options.initialValue));return new xX({options:$,selectedIndex:B,body:SB6(A.options.message,Q),onSelect:(E)=>{if(E===null){A.onCancel();return}A.onSelect(E)},padding:c0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!0,wrapOptions:!0})}function _B6(A){if(A===void 0)return!1;return A.split(`
2778
2778
  `).length>yg0}function SB6(A,Q){if(A===void 0)return;let $=A.split(`
2779
2779
  `).length,B=Math.min($,yg0);return new y0({width:1/0,height:B,child:new vB({autofocus:!1,controller:Q,child:new D0({text:new g(A)})})})}function kB6(){return new Map([[wA.key("PageUp"),new M80],[wA.key("PageDown"),new O80],[wA.ctrl("u"),new M80],[wA.ctrl("d"),new O80],[wA.ctrl("y"),new bg0],[wA.ctrl("e"),new hg0],[wA.shift("Home"),new gg0],[wA.shift("End"),new mg0]])}function fB6(A,Q,$){return Math.max(Q,Math.min(A,$))}var xB6=3,yB6=2097152,bB6=new ZB("PluginDialogOverlay");function L80(A,Q,$){if($!==void 0)return{type:"response",id:A,error:$};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}function hB6(A){let Q=new TextEncoder().encode(JSON.stringify(A)).byteLength;if(Q<=yB6)return;throw Error(`thread.messages response is too large (${Q} bytes). Request fewer messages.`)}class cg0{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];resolvingDialog=null;pendingOwnerUIRequests=new Map;pendingActorUIRequests=new Map;stateBackedRequestIDs=new Set;pluginUIRespondRequestCounter=0;statusItems=new Map;blockingConfirmDialog=!1;disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelOwnerUIRequests(),this.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}handlePluginMessage(A,Q){let $=A.message;if($.type==="response"){this.cancelOwnerUIRequest($.id),this.cancelActorUIRequest($.id);return}if($.type==="event"){if(this.handlePluginUIStateEvent($,Q))return;this.handlePluginEvent($);return}if(this.stateBackedRequestIDs.has($.id))return;if(!O30($.method)){if($.method==="thread.messages")this.handleThreadMessagesRequest($,Q);return}this.handleOwnerUIRequest($,Q)}cancelOwnerUIRequests(){let A=[...this.pendingOwnerUIRequests.values(),...this.pendingActorUIRequests.values()];this.pendingOwnerUIRequests.clear(),this.pendingActorUIRequests.clear(),this.stateBackedRequestIDs.clear();for(let Q of A)Q.abort()}hasBlockingDialog(){return this.activeDialog!==null}hasBlockingConfirmDialog(){return this.activeDialog?.kind==="confirm"}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];return[new E6({key:bB6,debugLabel:"PluginDialogOverlay",autofocus:!1,canRequestFocus:!0,child:this.buildActiveDialog(A)})]}buildActiveDialog(A){switch(A.kind){case"input":return new Rl({key:new CK(A),header:A.options.title??"Input",helpText:A.options.helpText,initialValue:A.options.initialValue,isRequired:!1,onSubmit:(Q)=>this.resolveInputDialog(A,Q),onDismiss:()=>this.resolveInputDialog(A,void 0)});case"confirm":return new Sg0({key:new CK(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)});case"select":return new dg0({key:new CK(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.context.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,this.options.readThreadMessages)A.readThreadMessagesHandler=this.readThreadMessages;if(this.options.readThreadTitle)A.readThreadTitleHandler=this.readThreadTitle;if(this.options.subscribeThreadTitle)A.subscribeThreadTitleHandler=this.subscribeThreadTitle;A.runAgentHandler=this.options.context.observerOnly?async()=>{throw Error("agent.run is only available from an executor-owned plugin runtime")}:this.options.runAgent??(async()=>{throw Error("agent.run is not available in this context")}),A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}handlePluginEvent(A){if(A.event!=="ui.notify")return;let Q=A.data;if(typeof Q.message==="string")this.options.toastController.show(Q.message,"success")}async handleThreadMessagesRequest(A,Q){try{let{options:$,threadID:B}=this.parseThreadMessagesRequestParams(A.params),E=await this.readThreadMessages($,B);hB6(E),Q(L80(A.id,E))}catch($){Q(L80(A.id,void 0,$ instanceof Error?$.message:String($)))}}parseThreadMessagesRequestParams(A){if(!A||typeof A!=="object")return{options:void 0,threadID:void 0};let Q=A;return{options:Q.options,threadID:typeof Q.threadID==="string"?Q.threadID:void 0}}async handleOwnerUIRequest(A,Q){let $=new AbortController;this.pendingOwnerUIRequests.set(A.id,$);try{let B=await this.dispatchOwnerUIRequest(A,$.signal);if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(L80(A.id,B))}catch(B){if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(L80(A.id,void 0,B instanceof Error?B.message:String(B)))}}dispatchOwnerUIRequest(A,Q){switch(A.method){case"ui.input":return this.showInputDialog(A.params.options,Q);case"ui.confirm":return this.showConfirmDialog(A.params.options,Q);case"ui.select":return this.showSelectDialog(A.params.options,Q);default:throw Error(`Unknown owner UI request method: ${A.method}`)}}cancelOwnerUIRequest(A){let Q=this.pendingOwnerUIRequests.get(A);if(!Q)return;this.pendingOwnerUIRequests.delete(A),Q.abort()}cancelActorUIRequest(A){let Q=this.pendingActorUIRequests.get(A);if(!Q)return;this.pendingActorUIRequests.delete(A),Q.abort()}buildPluginUIRespondRequest(A,Q,$){this.pluginUIRespondRequestCounter+=1;let B={requestId:A};if($!==void 0)B.error=$;else if(Q!==void 0)B.result=Q;return{type:"request",id:`plugin-ui-respond-${A}-${this.pluginUIRespondRequestCounter}`,method:"plugin.ui.respond",params:B}}async handleActorUIRequest(A,Q){let $=new AbortController;this.pendingActorUIRequests.set(A.requestId,$);let B={type:"request",id:A.requestId,method:A.method,params:A.params};try{let E=await this.dispatchOwnerUIRequest(B,$.signal);if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,E))}catch(E){if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,void 0,E instanceof Error?E.message:String(E)))}}upsertActorUIState(A,Q){if(this.stateBackedRequestIDs.add(A.requestId),A.status!=="pending"){this.cancelActorUIRequest(A.requestId);return}if(this.pendingActorUIRequests.has(A.requestId))return;this.handleActorUIRequest(A,Q)}handlePluginUISnapshot(A,Q){let $=new Set(A.requests.map((B)=>B.requestId));for(let B of this.pendingActorUIRequests.keys())if(!$.has(B))this.cancelActorUIRequest(B);for(let B of this.stateBackedRequestIDs)if(!$.has(B))this.stateBackedRequestIDs.delete(B);for(let B of A.requests)this.upsertActorUIState(B,Q)}handlePluginUIRequestAdded(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestSettled(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestRemoved(A){this.cancelActorUIRequest(A.requestId),this.stateBackedRequestIDs.delete(A.requestId)}handlePluginUIStateEvent(A,Q){if(A.event==="plugin.ui.snapshot"){let $=zF4.safeParse(A.data);if($.success)this.handlePluginUISnapshot($.data,Q);return!0}if(A.event==="plugin.ui.request_added"){let $=WF4.safeParse(A.data);if($.success)this.handlePluginUIRequestAdded($.data,Q);return!0}if(A.event==="plugin.ui.request_settled"){let $=CF4.safeParse(A.data);if($.success)this.handlePluginUIRequestSettled($.data,Q);return!0}if(A.event==="plugin.ui.request_removed"){let $=HF4.safeParse(A.data);if($.success)this.handlePluginUIRequestRemoved($.data);return!0}return!1}clearPluginPlatformStatusHandlers(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.readThreadMessagesHandler===this.readThreadMessages)A.readThreadMessagesHandler=null;if(A.readThreadTitleHandler===this.readThreadTitle)A.readThreadTitleHandler=null;if(A.subscribeThreadTitleHandler===this.subscribeThreadTitle)A.subscribeThreadTitleHandler=null;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null;if(A.runAgentHandler===this.options.runAgent)A.runAgentHandler=null}subscribePluginCommands(){let A=this.options.context.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let $=A.map((B)=>this.createPluginCommand(B)).map((B)=>this.options.commandRegistry.register(B));this.unregisterPluginCommands=()=>{for(let B of $)B()}}showNewPluginErrorToasts(A){let Q=new Set;for(let $ of A){if($.status!=="error")continue;if(jh($.errorMessage))continue;let B=`${$.uri.toString()}
2780
- ${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,E]of this.statusItems){if(Q.has(E.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(E){S.error("Neo plugin command failed",{error:E,command:A}),this.options.toastController.show(E instanceof Error?E.message:String(E),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),E={pluginURI:A,id:Q};if($!==void 0)E.value=$;this.statusItems.set(B,E)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};readThreadTitle=(A)=>{let Q=this.options.readThreadTitle;if(!Q)return Promise.reject(Error("thread.title is not available - no active thread"));return Q(A)};subscribeThreadTitle=(A,Q)=>{let $=this.options.subscribeThreadTitle;if(!$)throw Error("thread.title.subscribe is not available - no active thread");return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,xB6)}scheduleResolvingDialogAdvance(A,Q){cQ.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}i0();import{spawnSync as gB6}from"node:child_process";import I9 from"node:process";var dN4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function Pl(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else G1.instance.stop()}var mB6=O4("amp.relaunch",{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],defaultKey:I9.env.NODE_ENV==="development"&&I9.platform==="darwin"?"meta+r":void 0,status:{type:"enabled"},sortBoost:90},(A,{dismiss:Q})=>{Q(),Pl(A)});function cN4(A){return mB6.bind(A)}function dB6(A,Q){let{command:$,args:B}=cB6(A),E=I9.execve,D=I9.platform==="win32"||!E,J=D?"spawnSync":"execve";if(S.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:J}),D){let U=gB6($,B,{cwd:Q,env:I9.env,stdio:"inherit"});if(U.error)return S.error("Failed to relaunch Amp",{error:U.error}),1;return U.status??1}try{if(I9.chdir(Q),$.includes("/"))return E($,[$,...B],I9.env);return E("/usr/bin/env",["env",$,...B],I9.env)}catch(U){return S.error("Failed to relaunch Amp",{error:U}),1}}class pg0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{S.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return dB6(this.requestedThreadIDs,A)}}function cB6(A){let Q=A.length>0?["threads","continue",...A]:[],$=pB6(I9.argv),B=iB6();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let E=I9.argv[1],D=E&&lB6(E)?[E]:[];return{command:I9.execPath,args:[...D,...$,...Q]}}function pB6(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let E=$[B];if(!E?.startsWith("--"))continue;let[D,J]=E.split("=",2);if(!D)continue;let U=D.slice(2),Y=U.startsWith("no-")?U.slice(3):U;if(dN4.booleans.has(Y)){Q.push(E);continue}if(!dN4.options.has(U))continue;if(J!==void 0){Q.push(E);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(E,Z),B+=1}return Q}function lB6(A){return A!==I9.execPath&&!A.startsWith("/$bunfs/")}function iB6(){if(I9.env.NODE_ENV!=="development")return null;let A=I9.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=nB6(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function nB6(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var aB6=48;class lg0{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new Ol({width:aB6,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keymapKey:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as tB6}from"node:fs/promises";import ng0 from"node:os";var oB6=["command","args","url","transport","_target"];function ig0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function rB6(A){if(typeof A!=="string")return A;let Q=A.indexOf("?");return Q===-1?A:A.slice(0,Q)}function sB6(A){if(!ig0(A))return A;let Q={};for(let[$,B]of Object.entries(A)){if(!ig0(B)){Q[$]=B;continue}let E={};for(let D of oB6){if(!(D in B))continue;E[D]=D==="url"?rB6(B[D]):B[D]}Q[$]=E}return Q}function pN4(A){let Q=PO(A,[],{allowTrailingComma:!0});if(!ig0(Q))return uP(A);let $={...Q};for(let B of Object.keys($))if(B==="mcpServers"||B==="amp.mcpServers")$[B]=sB6($[B]);return uP(JSON.stringify($,null,2))}F$();function eB6(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function lN4(A,Q,$=uP){try{return{path:Q,contents:$(await tB6(A,"utf8"))}}catch{return null}}async function j80(A,Q){let $=[],B=eB6(),E=await j4.getThread({thread:Q},{config:A.configService}),D=E.ok?E.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(nD(D),null,2)});let J=await lN4(fP(Q),`${B}/logs/${Q}.log`);if(J)$.push(J);let U=await lN4(A.settingsFilePath,`${B}/settings/global.json`,pN4);if(U)$.push(U);let Y=await sY()??"unknown",Z=await j4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1780803750-g55245f",clientOS:`${ng0.platform()} ${ng0.release()} ${ng0.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class ag0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var A36=86400000;class og0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??A36)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>Pl(this.options))}}class sg0 extends eA{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((E)=>E.status.type!=="hidden"),$=$36(Q),B="";return new E1({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:c0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new j5({items:Q,showBorder:!1,getLabel:(E)=>{let D=rg0(E);return E.keywords&&E.keywords.length>0?`${D} ${E.keywords.join(" ").toLowerCase()}`:D},onQueryChange:(E)=>{B=E},sortItems:(E,D,J)=>{B=J;let U=J.trim().toLowerCase();if(U===""){let V=E.item.status.type==="disabled"?1:0,K=D.item.status.type==="disabled"?1:0;if(V!==K)return V-K;let z=E.item.sortBoost??0,W=D.item.sortBoost??0;if(z!==W)return W-z;let C=E.item.noun?.toLowerCase()??"",H=D.item.noun?.toLowerCase()??"";if(C!==H)return C<H?-1:1;return 0}let Y=iN4(E.item,U),Z=iN4(D.item,U);if(Y!==Z)return Y?-1:1;let F=uq(E.item.verb.toLowerCase(),J),X=uq(D.item.verb.toLowerCase(),J);if(F!==X)return X-F;let I=uq(rg0(E.item),J),G=uq(rg0(D.item),J);if(I!==G)return G-I;return D.score-E.score},isItemDisabled:(E)=>E.status.type==="disabled",buildDisabledReasonWidget:(E,D)=>{if(E.status.type!=="disabled")return;let{colors:J}=e0.of(D);return new D0({text:new g(E.status.reason,new A0({color:J.mutedForeground,dim:!0})),textAlign:"center",maxLines:1,overflow:"ellipsis"})},renderItem:(E,D,J,U)=>new nN4({command:E,shortcuts:R80(E,this.props.keymapShortcuts),isSelected:D,isDisabled:J,categoryWidth:$,query:B,buildContext:U}),onAccept:(E)=>{this.props.onAccept(E)},onDismiss:this.props.onDismiss})})}}class nN4 extends eA{props;constructor(A){super();this.props=A}build(A){let{command:Q,shortcuts:$,isSelected:B,isDisabled:E,categoryWidth:D,query:J,buildContext:U}=this.props,Y=e0.of(U),{colors:Z,app:F}=Y,X=B?F.selectionBackground:void 0,I=B?F.selectionForeground:Z.foreground,G=B?I:Z.mutedForeground,V=new D0({text:new g(Q.noun?.toLowerCase()??"",new A0({color:G,dim:E||!B})),textAlign:"right",maxLines:1,overflow:"ellipsis"}),K=Q.verb.toLowerCase();if(E)K+=" (unavailable)";let z=Q36(Q,J);if(z)K+=` (alias: ${z})`;let W=new D0({text:new g(K,new A0({color:I,bold:!0,dim:E})),maxLines:1,overflow:"ellipsis"}),C=[{child:V,fixedWidth:D},{child:W,expanded:!0}];if($.length>0)C.push({child:B36($,Y,E)});return new aN4({columns:C,padding:c0.horizontal(1),backgroundColor:X})}}function rg0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function iN4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function Q36(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function $36(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,RA($.noun)):Q},0)}function B36(A,Q,$){let{app:B}=Q,E=new A0({color:B.keybind,bold:!0,dim:$}),D=[];for(let J=0;J<A.length;J++){if(J>0)D.push(new g(", ",E));D.push(new g(aN(A[J]),E))}return D0.spans(D)}class aN4 extends eA{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:E}=this.props,D=[];for(let U=0;U<Q.length;U++){let Y=Q[U];if(U>0&&$>0)D.push(new y0({width:$}));if(Y.fixedWidth!==void 0)D.push(new y0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)D.push(new P4({child:Y.child}));else D.push(Y.child)}let J=new OA({crossAxisAlignment:"start",children:D});if(!B&&!E)return J;return new GA({decoration:E?{color:E}:void 0,padding:B,child:J})}}class tg0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q,$=new Rq,B=()=>{}){let E=this.findByID(A);if(!E||E.status.type!=="enabled")return!1;return E.run($,Q,B),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class sB extends sQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=sB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(sB)?.commandRegistry??null}}function R80(A,Q){let $=A.id?Q.get(A.id)??[]:[];if(!A.shortcut)return $;return new Set(Array.from(Q.values()).flatMap((E)=>E.map((D)=>ec(D).toString()))).has(A.shortcut.toString())?$:[...$,A.shortcut]}class eg0 extends d0{keymapShortcuts;onDismiss;constructor(A){super();this.keymapShortcuts=A.keymapShortcuts??new Map,this.onDismiss=A.onDismiss}createState(){return new oN4}}class oN4 extends m0{modalStack=new Rq;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=sB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=sB.of(A).commands,$=new sg0({commands:Q,keymapShortcuts:this.widget.keymapShortcuts,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new $l({root:$,controller:this.modalStack})}}var rN4=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],sN4=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class P80 extends eA{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=X4.of(A).size.width<50,B=[];for(let E of this.items){let[D,J]=this.renderRow(E),U;if($)U=new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[D,new mA({padding:c0.only({left:4}),child:J})]});else U=new OA({crossAxisAlignment:"start",children:[new P4({flex:1,child:D}),new y0({width:1}),new P4({flex:1,child:J})]});B.push(new mA({padding:c0.horizontal(6),child:U}))}return new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function tN4(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return RX(Q.join("+"))}function T80(A){return A.replaceAll("Opt","Alt").replaceAll("Cmd","Meta").replaceAll("←","ArrowLeft").replaceAll("→","ArrowRight").replaceAll("↑","ArrowUp").replaceAll("↓","ArrowDown").replaceAll("Pg Up","PageUp").replaceAll("Pg Down","PageDown")}function E36(A){let Q=tN4(A);return Q.includes("Ctrl/Cmd")?[T80(Q.replace("Ctrl/Cmd","Ctrl")),T80(Q.replace("Ctrl/Cmd","Cmd"))]:[T80(Q)]}class Am0 extends eA{commands;keymapShortcuts;onDismiss;constructor(A){super();this.commands=A.commands,this.keymapShortcuts=A.keymapShortcuts,this.onDismiss=A.onDismiss}build(A){let Q=e0.of(A),{colors:$,app:B}=Q,E=X4.of(A),D=new A0({color:$.secondary,bold:!0}),J=new A0({color:B.keybind}),U=new A0({color:B.command}),Y=new A0({color:$.foreground}),Z=Math.max(40,Math.min(80,E.size.width-4)),X=[...this.commands.filter((z)=>{let W=z.noun?.toLowerCase();return W!=="dev"&&W!=="debug"&&z.status.type!=="hidden"})].sort((z,W)=>{let C=(z.noun??"").toLowerCase(),H=(W.noun??"").toLowerCase(),N=C.localeCompare(H);if(N!==0)return N;return z.verb.toLowerCase().localeCompare(W.verb.toLowerCase())}),I=(z)=>{let W=z.methods.map((C)=>tN4(C)).join(", ");return[new D0({text:new g(W,J)}),new D0({text:new g(z.description,Y)})]},G=new Set(Array.from(this.keymapShortcuts.values()).flatMap((z)=>z.map((W)=>T80(aN(ec(W)))))),V=(z)=>z.flatMap((W)=>{let C=W.methods.filter((H)=>E36(H).every((N)=>!G.has(N)));return C.length>0?[{...W,methods:C}]:[]}),K=new vB({autofocus:!0,child:new GA({constraints:new A4(Z,Z,0,Number.POSITIVE_INFINITY),child:new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new mA({padding:c0.horizontal(2),child:new D0({text:new g(`Editor Shortcuts
2780
+ ${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,E]of this.statusItems){if(Q.has(E.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(E){S.error("Neo plugin command failed",{error:E,command:A}),this.options.toastController.show(E instanceof Error?E.message:String(E),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),E={pluginURI:A,id:Q};if($!==void 0)E.value=$;this.statusItems.set(B,E)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};readThreadTitle=(A)=>{let Q=this.options.readThreadTitle;if(!Q)return Promise.reject(Error("thread.title is not available - no active thread"));return Q(A)};subscribeThreadTitle=(A,Q)=>{let $=this.options.subscribeThreadTitle;if(!$)throw Error("thread.title.subscribe is not available - no active thread");return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,xB6)}scheduleResolvingDialogAdvance(A,Q){cQ.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}i0();import{spawnSync as gB6}from"node:child_process";import I9 from"node:process";var dN4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function Pl(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else G1.instance.stop()}var mB6=O4("amp.relaunch",{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],defaultKey:I9.env.NODE_ENV==="development"&&I9.platform==="darwin"?"meta+r":void 0,status:{type:"enabled"},sortBoost:90},(A,{dismiss:Q})=>{Q(),Pl(A)});function cN4(A){return mB6.bind(A)}function dB6(A,Q){let{command:$,args:B}=cB6(A),E=I9.execve,D=I9.platform==="win32"||!E,J=D?"spawnSync":"execve";if(S.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:J}),D){let U=gB6($,B,{cwd:Q,env:I9.env,stdio:"inherit"});if(U.error)return S.error("Failed to relaunch Amp",{error:U.error}),1;return U.status??1}try{if(I9.chdir(Q),$.includes("/"))return E($,[$,...B],I9.env);return E("/usr/bin/env",["env",$,...B],I9.env)}catch(U){return S.error("Failed to relaunch Amp",{error:U}),1}}class pg0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{S.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return dB6(this.requestedThreadIDs,A)}}function cB6(A){let Q=A.length>0?["threads","continue",...A]:[],$=pB6(I9.argv),B=iB6();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let E=I9.argv[1],D=E&&lB6(E)?[E]:[];return{command:I9.execPath,args:[...D,...$,...Q]}}function pB6(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let E=$[B];if(!E?.startsWith("--"))continue;let[D,J]=E.split("=",2);if(!D)continue;let U=D.slice(2),Y=U.startsWith("no-")?U.slice(3):U;if(dN4.booleans.has(Y)){Q.push(E);continue}if(!dN4.options.has(U))continue;if(J!==void 0){Q.push(E);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(E,Z),B+=1}return Q}function lB6(A){return A!==I9.execPath&&!A.startsWith("/$bunfs/")}function iB6(){if(I9.env.NODE_ENV!=="development")return null;let A=I9.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=nB6(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function nB6(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var aB6=48;class lg0{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new Ol({width:aB6,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keymapKey:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as tB6}from"node:fs/promises";import ng0 from"node:os";var oB6=["command","args","url","transport","_target"];function ig0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function rB6(A){if(typeof A!=="string")return A;let Q=A.indexOf("?");return Q===-1?A:A.slice(0,Q)}function sB6(A){if(!ig0(A))return A;let Q={};for(let[$,B]of Object.entries(A)){if(!ig0(B)){Q[$]=B;continue}let E={};for(let D of oB6){if(!(D in B))continue;E[D]=D==="url"?rB6(B[D]):B[D]}Q[$]=E}return Q}function pN4(A){let Q=PO(A,[],{allowTrailingComma:!0});if(!ig0(Q))return uP(A);let $={...Q};for(let B of Object.keys($))if(B==="mcpServers"||B==="amp.mcpServers")$[B]=sB6($[B]);return uP(JSON.stringify($,null,2))}F$();function eB6(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function lN4(A,Q,$=uP){try{return{path:Q,contents:$(await tB6(A,"utf8"))}}catch{return null}}async function j80(A,Q){let $=[],B=eB6(),E=await j4.getThread({thread:Q},{config:A.configService}),D=E.ok?E.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(nD(D),null,2)});let J=await lN4(fP(Q),`${B}/logs/${Q}.log`);if(J)$.push(J);let U=await lN4(A.settingsFilePath,`${B}/settings/global.json`,pN4);if(U)$.push(U);let Y=await sY()??"unknown",Z=await j4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1780818304-g58b217",clientOS:`${ng0.platform()} ${ng0.release()} ${ng0.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class ag0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var A36=86400000;class og0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??A36)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>Pl(this.options))}}class sg0 extends eA{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((E)=>E.status.type!=="hidden"),$=$36(Q),B="";return new E1({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:c0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new j5({items:Q,showBorder:!1,getLabel:(E)=>{let D=rg0(E);return E.keywords&&E.keywords.length>0?`${D} ${E.keywords.join(" ").toLowerCase()}`:D},onQueryChange:(E)=>{B=E},sortItems:(E,D,J)=>{B=J;let U=J.trim().toLowerCase();if(U===""){let V=E.item.status.type==="disabled"?1:0,K=D.item.status.type==="disabled"?1:0;if(V!==K)return V-K;let z=E.item.sortBoost??0,W=D.item.sortBoost??0;if(z!==W)return W-z;let C=E.item.noun?.toLowerCase()??"",H=D.item.noun?.toLowerCase()??"";if(C!==H)return C<H?-1:1;return 0}let Y=iN4(E.item,U),Z=iN4(D.item,U);if(Y!==Z)return Y?-1:1;let F=uq(E.item.verb.toLowerCase(),J),X=uq(D.item.verb.toLowerCase(),J);if(F!==X)return X-F;let I=uq(rg0(E.item),J),G=uq(rg0(D.item),J);if(I!==G)return G-I;return D.score-E.score},isItemDisabled:(E)=>E.status.type==="disabled",buildDisabledReasonWidget:(E,D)=>{if(E.status.type!=="disabled")return;let{colors:J}=e0.of(D);return new D0({text:new g(E.status.reason,new A0({color:J.mutedForeground,dim:!0})),textAlign:"center",maxLines:1,overflow:"ellipsis"})},renderItem:(E,D,J,U)=>new nN4({command:E,shortcuts:R80(E,this.props.keymapShortcuts),isSelected:D,isDisabled:J,categoryWidth:$,query:B,buildContext:U}),onAccept:(E)=>{this.props.onAccept(E)},onDismiss:this.props.onDismiss})})}}class nN4 extends eA{props;constructor(A){super();this.props=A}build(A){let{command:Q,shortcuts:$,isSelected:B,isDisabled:E,categoryWidth:D,query:J,buildContext:U}=this.props,Y=e0.of(U),{colors:Z,app:F}=Y,X=B?F.selectionBackground:void 0,I=B?F.selectionForeground:Z.foreground,G=B?I:Z.mutedForeground,V=new D0({text:new g(Q.noun?.toLowerCase()??"",new A0({color:G,dim:E||!B})),textAlign:"right",maxLines:1,overflow:"ellipsis"}),K=Q.verb.toLowerCase();if(E)K+=" (unavailable)";let z=Q36(Q,J);if(z)K+=` (alias: ${z})`;let W=new D0({text:new g(K,new A0({color:I,bold:!0,dim:E})),maxLines:1,overflow:"ellipsis"}),C=[{child:V,fixedWidth:D},{child:W,expanded:!0}];if($.length>0)C.push({child:B36($,Y,E)});return new aN4({columns:C,padding:c0.horizontal(1),backgroundColor:X})}}function rg0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function iN4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function Q36(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function $36(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,RA($.noun)):Q},0)}function B36(A,Q,$){let{app:B}=Q,E=new A0({color:B.keybind,bold:!0,dim:$}),D=[];for(let J=0;J<A.length;J++){if(J>0)D.push(new g(", ",E));D.push(new g(aN(A[J]),E))}return D0.spans(D)}class aN4 extends eA{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:E}=this.props,D=[];for(let U=0;U<Q.length;U++){let Y=Q[U];if(U>0&&$>0)D.push(new y0({width:$}));if(Y.fixedWidth!==void 0)D.push(new y0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)D.push(new P4({child:Y.child}));else D.push(Y.child)}let J=new OA({crossAxisAlignment:"start",children:D});if(!B&&!E)return J;return new GA({decoration:E?{color:E}:void 0,padding:B,child:J})}}class tg0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q,$=new Rq,B=()=>{}){let E=this.findByID(A);if(!E||E.status.type!=="enabled")return!1;return E.run($,Q,B),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class sB extends sQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=sB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(sB)?.commandRegistry??null}}function R80(A,Q){let $=A.id?Q.get(A.id)??[]:[];if(!A.shortcut)return $;return new Set(Array.from(Q.values()).flatMap((E)=>E.map((D)=>ec(D).toString()))).has(A.shortcut.toString())?$:[...$,A.shortcut]}class eg0 extends d0{keymapShortcuts;onDismiss;constructor(A){super();this.keymapShortcuts=A.keymapShortcuts??new Map,this.onDismiss=A.onDismiss}createState(){return new oN4}}class oN4 extends m0{modalStack=new Rq;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=sB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=sB.of(A).commands,$=new sg0({commands:Q,keymapShortcuts:this.widget.keymapShortcuts,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new $l({root:$,controller:this.modalStack})}}var rN4=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],sN4=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class P80 extends eA{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=X4.of(A).size.width<50,B=[];for(let E of this.items){let[D,J]=this.renderRow(E),U;if($)U=new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[D,new mA({padding:c0.only({left:4}),child:J})]});else U=new OA({crossAxisAlignment:"start",children:[new P4({flex:1,child:D}),new y0({width:1}),new P4({flex:1,child:J})]});B.push(new mA({padding:c0.horizontal(6),child:U}))}return new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function tN4(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return RX(Q.join("+"))}function T80(A){return A.replaceAll("Opt","Alt").replaceAll("Cmd","Meta").replaceAll("←","ArrowLeft").replaceAll("→","ArrowRight").replaceAll("↑","ArrowUp").replaceAll("↓","ArrowDown").replaceAll("Pg Up","PageUp").replaceAll("Pg Down","PageDown")}function E36(A){let Q=tN4(A);return Q.includes("Ctrl/Cmd")?[T80(Q.replace("Ctrl/Cmd","Ctrl")),T80(Q.replace("Ctrl/Cmd","Cmd"))]:[T80(Q)]}class Am0 extends eA{commands;keymapShortcuts;onDismiss;constructor(A){super();this.commands=A.commands,this.keymapShortcuts=A.keymapShortcuts,this.onDismiss=A.onDismiss}build(A){let Q=e0.of(A),{colors:$,app:B}=Q,E=X4.of(A),D=new A0({color:$.secondary,bold:!0}),J=new A0({color:B.keybind}),U=new A0({color:B.command}),Y=new A0({color:$.foreground}),Z=Math.max(40,Math.min(80,E.size.width-4)),X=[...this.commands.filter((z)=>{let W=z.noun?.toLowerCase();return W!=="dev"&&W!=="debug"&&z.status.type!=="hidden"})].sort((z,W)=>{let C=(z.noun??"").toLowerCase(),H=(W.noun??"").toLowerCase(),N=C.localeCompare(H);if(N!==0)return N;return z.verb.toLowerCase().localeCompare(W.verb.toLowerCase())}),I=(z)=>{let W=z.methods.map((C)=>tN4(C)).join(", ");return[new D0({text:new g(W,J)}),new D0({text:new g(z.description,Y)})]},G=new Set(Array.from(this.keymapShortcuts.values()).flatMap((z)=>z.map((W)=>T80(aN(ec(W)))))),V=(z)=>z.flatMap((W)=>{let C=W.methods.filter((H)=>E36(H).every((N)=>!G.has(N)));return C.length>0?[{...W,methods:C}]:[]}),K=new vB({autofocus:!0,child:new GA({constraints:new A4(Z,Z,0,Number.POSITIVE_INFINITY),child:new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new mA({padding:c0.horizontal(2),child:new D0({text:new g(`Editor Shortcuts
2781
2781
  `,D)})}),new P80({items:V(rN4).filter((z)=>z.submitOnEnterOnly===void 0||z.submitOnEnterOnly===!0),renderRow:I}),new y0({height:1}),new mA({padding:c0.horizontal(2),child:new D0({text:new g(`Scrolling & Navigation
2782
2782
  `,D)})}),new P80({items:V(sN4),renderRow:I}),new y0({height:1}),new mA({padding:c0.horizontal(2),child:new D0({text:new g(`Command Palette Commands
2783
2783
  `,D)})}),new P80({items:X,renderRow:(z)=>{let W=z.noun?`${z.noun}: ${z.verb}`:z.verb,H=R80(z,this.keymapShortcuts).map(aN).join(", ");return[new D0({text:H?new g("",void 0,[new g(W,U),new g(` ${H}`,J)]):new g(W,U)}),new D0({text:new g(z.description,Y)})]}}),new y0({height:1})]})})});return new E1({header:"Amp CLI — Help & Keymap",minWidth:Z,maxWidth:Z,maxHeight:E.size.height,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.onDismiss,child:K})}}class zT extends sQ{completionBuilder;constructor({completionBuilder:A,child:Q}){super({child:Q});this.completionBuilder=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(zT);if(!Q)throw Error("No CompletionBuilderProvider found in widget tree");return Q.completionBuilder}}var D36=250,J36=2000;class Qm0 extends d0{configReloadEvents;toastController;child;constructor(A){super();this.configReloadEvents=A.configReloadEvents,this.toastController=A.toastController,this.child=A.child}createState(){return new eN4}}class eN4 extends m0{subscription=null;toastTimer=null;pendingToastType=null;lastToast=null;initState(){this.subscribeToConfigReloadEvents()}didUpdateWidget(A){if(A.configReloadEvents===this.widget.configReloadEvents)return;this.clearPendingToast(),this.subscribeToConfigReloadEvents()}dispose(){this.subscription?.unsubscribe(),this.subscription=null,this.clearPendingToast(),super.dispose()}build(A){return this.widget.child}subscribeToConfigReloadEvents(){this.subscription?.unsubscribe(),this.subscription=this.widget.configReloadEvents.subscribe((A)=>{this.scheduleToast(A)})}scheduleToast(A){if(this.pendingToastType=U36(this.pendingToastType,A),this.toastTimer)clearTimeout(this.toastTimer);this.toastTimer=setTimeout(()=>{if(!this.mounted)return;this.flushToast()},D36),this.toastTimer.unref()}flushToast(){let A=this.pendingToastType;if(this.clearPendingToast(),!A)return;let Q=Date.now();if(Y36(this.lastToast,A,Q))return;this.lastToast={type:A,shownAt:Q},Z36(this.widget.toastController,A)}clearPendingToast(){if(this.toastTimer)clearTimeout(this.toastTimer),this.toastTimer=null;this.pendingToastType=null}}function U36(A,Q){return A==="failed"||Q.type==="failed"?"failed":"succeeded"}function Y36(A,Q,$){return A?.type===Q&&$-A.shownAt<J36}function Z36(A,Q){switch(Q){case"succeeded":A.show("Config reloaded","success",1500);break;case"failed":A.show("Config reload failed","error",5000);break}}class MQ extends sQ{context;constructor({context:A,child:Q}){super({child:Q});this.context=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(MQ);if(!Q)throw Error("No ContextProvider found in widget tree");return Q.context}}i0();f8();var _80=80,F36=15,X36=1,Aq4=-_80,I36=16,G36=Yb0(_80,_80);function Qq4({ampURL:A,threadID:Q,logPath:$}){return[`Debug thread ${hG(new URL(A),Q).toString()} (cli log: ${$}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
@@ -2904,13 +2904,13 @@ Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)H=this.widget.centerContent
2904
2904
  - Real life (in person)
2905
2905
 
2906
2906
  `,new A0({color:Q.foreground})),textAlign:"left"}),new D0({text:new g("All diagnostics data is deleted after 7 days. Amp team members can only access the diagnostics data if you provide the report ID.",new A0({color:Q.foreground,dim:!0})),textAlign:"left"})]})}}var SL4={kind:"fill",modalRows:19};function e26(A){return new E1({header:"Sending Report",tone:"default",minWidth:80,maxWidth:80,bodyFit:SL4,onDismiss:A,child:new kL4})}class kL4 extends eA{build(A){let{colors:Q}=e0.of(A);return new OA({mainAxisSize:"min",children:[new iX({color:Q.primary}),new y0({width:1}),new D0({text:new g("Gathering and sending diagnostics data...",new A0({color:Q.foreground,dim:!0}))})]})}}function _L4(A){return new E1({header:A.title,tone:A.tone,barrierOpaque:!0,minWidth:80,maxWidth:80,bodyFit:SL4,onDismiss:A.onDismiss,child:A.child})}var fL4=O4("feedback.sendReportWithDiagnostics",{noun:"feedback",verb:"send report with diagnostics",description:"Send a report with diagnostics to Amp support",keywords:["bug","support"],status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},(A,{controller:Q,context:$,dismiss:B})=>{let E=A.getThreadContext()?.client.getThreadId();if(!E)return;Q.push(e26(B)),A.sendFeedbackReport(E).then(async(D)=>{try{await G1.instance.tuiInstance.clipboard.writeText(D),DQ.maybeOf($)?.show("Copied report ID to clipboard","success",3000)}catch(J){S.warn("Failed to copy report ID to clipboard",{error:J,reportID:D})}Q.push(_L4({title:"Report Sent",tone:"success",onDismiss:B,child:new fc0(D)}))}).catch((D)=>{S.error("Failed to share thread with support",{error:D,threadID:E}),Q.push(_L4({title:"Report failed",tone:"error",onDismiss:B,child:new D0({text:new g(`Failed to send report: ${D instanceof Error?D.message:String(D)}`)})}))})});E3();import{homedir as AU6}from"node:os";import{relative as QU6,sep as $U6}from"node:path";import{fileURLToPath as BU6}from"node:url";var EU6="https://ampcode.com/manual#agent-skills",DU6="You need to start a new thread to see skills. You can mention skills in your first message.";class xc0 extends G4{}class yc0 extends d0{listSkills;onDismiss;cwd;constructor(A){super();this.listSkills=A.listSkills,this.onDismiss=A.onDismiss,this.cwd=A.cwd}createState(){return new xL4}}class xL4 extends m0{status={kind:"loading"};abortController=null;initState(){this.abortController=new AbortController,this.loadSkills()}dispose(){this.abortController?.abort()}async loadSkills(){try{let A=await this.widget.listSkills(this.abortController?.signal);if(!this.mounted)return;this.setState(()=>{this.status={kind:"ready",skills:A.skills,errors:A.errors}})}catch(A){if(!this.mounted)return;this.setState(()=>{this.status={kind:"error",message:A instanceof Error?A.message:"Unknown error"}})}}build(A){return new c90({status:this.status,cwd:this.widget.cwd,onDismiss:this.widget.onDismiss})}}class c90 extends eA{status;cwd;onDismiss;constructor(A){super();this.status=A.status,this.cwd=A.cwd,this.onDismiss=A.onDismiss}build(A){return new E1({header:JU6(this.status),onDismiss:this.onDismiss,minWidth:80,maxWidth:120,maxHeight:40,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"},{keys:["o"],label:"open manual"}],child:new N4({actions:new Map([[xc0,new cA(()=>{z$(A,EU6)})]]),child:new rQ({debugLabel:"SkillListShortcuts",shortcuts:new Map([[wA.key("o"),new xc0]]),child:UU6(A,this.status,this.cwd)})})})}}function JU6(A){if(A.kind!=="ready")return"Skills";let{skills:Q,errors:$}=A;if(Q.length===0&&$.length===0)return"Skills";if($.length===0)return`Skills (${Q.length})`;let B=`${$.length} ${z1($.length,"error")}`;if(Q.length===0)return`Skills (0, ${B})`;return`Skills (${Q.length}, ${B})`}function UU6(A,Q,$){let{colors:B}=e0.of(A);switch(Q.kind){case"loading":return d90(new OA({mainAxisSize:"min",children:[new iX({color:B.primary}),new y0({width:1}),new D0({text:new g("Loading skills...",new A0({color:B.foreground,dim:!0}))})]}));case"no-thread":return d90(new D0({text:new g(DU6,new A0({color:B.foreground}))}));case"error":return d90(new D0({text:new g(Q.message,new A0({color:B.destructive}))}));case"ready":return ZU6(A,Q.skills,Q.errors,$)}}function d90(A){return new VQ({autofocus:!0,debugLabel:"SkillListBody",child:A})}var YU6=90;function ZU6(A,Q,$,B){let{colors:E,app:D}=e0.of(A),J=new A0({color:E.foreground,dim:!0});if(Q.length===0&&$.length===0)return d90(new D0({text:new g("No skills reported by the executor yet.",J)}));let U=X4.sizeOf(A).width>=YU6;return new vB({child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:VU6(Q,$,U,{section:new A0({color:E.foreground,bold:!0}),name:new A0({color:D.command}),description:new A0({color:E.foreground}),location:J,errorTitle:new A0({color:E.destructive,bold:!0}),errorName:new A0({color:E.warning,bold:!0}),errorMessage:new A0({color:E.destructive}),cwd:B})})})}var FU6={local:"Local",global:"Global",builtin:"Built-in"},XU6=["local","global","builtin"],IU6={"workspace-agents":"local","workspace-claude":"local","user-agents":"global","user-amp":"global","user-claude":"global",plugin:"global",toolbox:"global","custom-path":"global",builtin:"builtin"};function GU6(A){let Q={local:[],global:[],builtin:[]};for(let $ of A){let B=$.source??"workspace-agents";Q[IU6[B]].push($)}return XU6.filter(($)=>Q[$].length>0).map(($)=>({label:FU6[$],skills:Q[$]}))}function VU6(A,Q,$,B){let E=[];if(GU6(A).forEach((D,J)=>{if(J>0)E.push(new y0({height:1}));E.push(new D0({text:new g(D.label,B.section)}));for(let U of D.skills)E.push(new mA({padding:c0.only({left:2}),child:CU6(U,$,B)}))}),Q.length>0){if(A.length>0)E.push(new y0({height:1}));E.push(new D0({text:new g(`Skipped skills with errors (${Q.length}):`,B.errorTitle)}));for(let D of Q)E.push(new y0({height:1})),E.push(...zU6(D,B))}E.push(new y0({height:1})),E.push(new D0({text:new g("Create your own:",B.section)}));for(let D of KU6)E.push(new mA({padding:c0.only({left:2}),child:new D0({text:new g(`"${D}"`,B.description),maxLines:1,overflow:"ellipsis"})}));return E}var KU6=["Create a skill for searching our production logs","Create a user skill for my preferred commit message style"];function zU6(A,Q){let $=[new mA({padding:c0.only({left:2}),child:new D0({text:new g(`⚠ ${WU6(A.path)}`,Q.errorName)})}),new mA({padding:c0.only({left:4}),child:new D0({text:new g(A.error,Q.errorMessage)})})];if(A.hint)$.push(new mA({padding:c0.only({left:4}),child:new D0({text:new g(A.hint.split(`
2907
- `)[0]??"",Q.description)})}));return $.push(new mA({padding:c0.only({left:4}),child:new D0({text:new g(yL4(A.path,Q.cwd),Q.location),maxLines:1,overflow:"ellipsis"})})),$}function WU6(A){try{return new URL(A).pathname.split("/").filter(Boolean).at(-2)??"unknown"}catch{return"unknown"}}function CU6(A,Q,$){if(Q)return new OA({crossAxisAlignment:"start",children:[new P4({flex:1,child:new D0({text:new g(A.name,$.name),maxLines:1,overflow:"ellipsis"})}),new y0({width:2}),new P4({flex:2,child:new mA({padding:c0.only({right:1}),child:new D0({text:new g(A.description,$.description),maxLines:1,overflow:"ellipsis"})})})]});return new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new OA({crossAxisAlignment:"start",children:[new D0({text:new g(A.name,$.name),maxLines:1,overflow:"ellipsis"}),new P4({child:new D0({text:new g(` ${yL4(A.baseDir,$.cwd)}`,$.location),maxLines:1,overflow:"ellipsis"})})]}),new mA({padding:c0.only({left:2,right:1}),child:new D0({text:new g(A.description,$.description),maxLines:1,overflow:"ellipsis"})})]})}function yL4(A,Q){if(A.startsWith("builtin://"))return"(builtin)";if(!A.startsWith("file://"))return A;let $=BU6(A),B=QU6(Q,$);if(B&&!B.startsWith(".."))return`./${B}`;let E=AU6();if($===E||$.startsWith(E+$U6))return`~${$.slice(E.length)}`;return $}var qU6=5000,wU6={attach:()=>{},detach:()=>{},unsubscribe:()=>{}};function uU6(A){let Q=bL4(A);return Q?{type:"rgb",value:Q}:void 0}function bL4(A){let Q=A?.match(/^#([0-9a-f]{6})$/i);if(!Q?.[1])return;return{r:Number.parseInt(Q[1].slice(0,2),16),g:Number.parseInt(Q[1].slice(2,4),16),b:Number.parseInt(Q[1].slice(4,6),16)}}function MU6(A){return{r:Math.round(A.r*0.55),g:Math.round(A.g*0.55),b:Math.round(A.b*0.55)}}async function OU6(A){return new Promise((Q)=>{HU6("git",["branch","--show-current"],{cwd:A},($,B)=>{if($){Q(null);return}let E=B.trim();Q(E||null)})})}function LU6(A,Q){let $=U4(g0.file(A)),B={workspaceRoot:$,workingDirectory:$};if(Q)B.git={branch:Q};return B}var jU6=Gq0.filter((A)=>A!==L00).sort((A,Q)=>A.localeCompare(Q)).map((A)=>({mode:A,command:O4(`mode.use.${A}`,{noun:"mode",verb:`use ${A}`,description:`Enable ${A} mode`,status:(Q)=>{if(Q.getThreadContext())return{type:"hidden"};return A===Q.agentMode?{type:"disabled",reason:`Already using ${A} mode`}:{type:"enabled"}}},(Q,{dismiss:$})=>{Q.setAgentMode(A),$()})})),RU6=O4("mode.toggle",{noun:"mode",verb:"switch",description:"Switch to the next available mode",defaultKey:"ctrl+s",status:(A)=>A.getThreadContext()?{type:"hidden"}:{type:"enabled"}},(A,{dismiss:Q})=>{A.toggleAgentMode(),Q()}),PU6=O4("speed.toggleFast",{noun:"speed",verb:(A)=>{if(A.isFastSpeedEnabled())return"disable fast";let Q=A.speedCostMultiplierLabel();return Q?`use fast (${Q} cost)`:"use fast"},description:"Toggle fast speed for this thread",status:(A)=>A.speedToggleCommandStatus()},(A,{dismiss:Q})=>{A.toggleSpeed(),Q()}),TU6=O4("thread.toggleDetails",{noun:"thread",verb:"toggle details",description:"Expand or collapse tool and activity details",keywords:["expand","thinking"],defaultKey:"alt+t",status:{type:"enabled"}},(A,{dismiss:Q})=>{A.toggleWorkDetails(),Q()}),vU6=O4("mode.toggleReasoningEffort",{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",defaultKey:"alt+d",status:(A)=>{if(A.getThreadContext())return{type:"hidden"};return dC(A.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}}},(A,{dismiss:Q})=>{A.toggleReasoningEffort(),Q()}),_U6=O4("thread.copyID",{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},(A,{context:Q,dismiss:$})=>{let B=A.getThreadContext()?.client.getThreadId();if(!B)return;N4.maybeInvoke(Q,new IB(B,"Thread ID copied to clipboard","Failed to copy thread ID")),$()}),SU6=O4("thread.copyURL",{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["share"],status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},(A,{context:Q,dismiss:$})=>{let B=A.getThreadURL();if(!B)return;N4.maybeInvoke(Q,new IB(B,"Thread URL copied to clipboard","Failed to copy thread URL")),$()}),kU6=O4("thread.copyMarkdown",{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},async(A,{context:Q,dismiss:$})=>{let B=A.getThreadContext()?.client.getThreadId();if(!B)return;try{let E=await A.appContext.getThreadMarkdown(B);if(!E){DQ.error(Q,"Failed to copy thread markdown");return}N4.maybeInvoke(Q,new IB(E,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(E){S.error("Failed to render thread markdown from Neo command palette",{error:E,threadID:B}),DQ.error(Q,"Failed to copy thread markdown")}finally{$()}}),fU6=O4("thread.analyzeContext",{noun:"thread",verb:"analyze context",description:"Show token usage by prompt section for this thread",keywords:["tokens"],status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},(A,{controller:Q,dismiss:$})=>{let B=A.getThreadContext()?.client.getThreadId();if(!B)return;Q.push(new Kc0({threadID:B,analyzeContext:A.widget.analyzeContextForThread,onDismiss:$}))}),xU6=O4("skills.list",{noun:"skills",verb:"list",description:"List available skills for this thread",status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{let B=A.getThreadContext()?.client.getThreadId();if(!B){Q.push(new c90({status:{kind:"no-thread"},onDismiss:$,cwd:A.appContext.workspaceRoot}));return}Q.push(new yc0({listSkills:(E)=>A.widget.listSkillsForThread(B,E),onDismiss:$,cwd:A.appContext.workspaceRoot}))}),yU6=O4("thread.new",{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start"],sortBoost:101,status:(A)=>{if(A.isEditorUploadLocked)return{type:"disabled",reason:"Prompt editor is not available"};return A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}}},(A,{context:Q})=>{if(!A.isEditorUploadLocked)N4.maybeInvoke(Q,new Lq)}),bU6=O4("thread.openInBrowser",{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web"],status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},async(A,{context:Q,dismiss:$})=>{let B=A.getThreadURL();if(!B)return;try{await z$(Q,B)}finally{$()}}),hU6=[PU6,TU6,RU6,vU6,_U6,SU6,kU6,fU6,xU6,yU6,bU6,fL4,tO4,eO4,vL4,ML4,jL4];class bc0 extends d0{initialAgentMode;initialPluginAgentModeKey;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;editorFocusNode;history;updateDraftThreadSettings;onNewThread;sendFeedbackReport;archiveThread;addThreadLabel;removeThreadLabel;configService;hints;ideStatus;statusItems;pluginConfirmationBlocked;notificationService;notice;onDismissNotice;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.initialPluginAgentModeKey=A.initialPluginAgentModeKey,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.editorFocusNode=A.editorFocusNode,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.sendFeedbackReport=A.sendFeedbackReport,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.hints=A.hints,this.ideStatus=A.ideStatus,this.statusItems=A.statusItems??[],this.pluginConfirmationBlocked=A.pluginConfirmationBlocked,this.notificationService=A.notificationService,this.notice=A.notice,this.onDismissNotice=A.onDismissNotice}createState(){return new hL4}}class hL4 extends m0{agentMode;pluginAgentModes=[];selectedPluginAgentMode=null;desiredPluginAgentModeKey=null;pluginAgentModesSubscription=null;copyOnSelectEnabled=!0;configSubscription=null;expansion=new cm0;previousThreadIDForReference=null;unregisterCommands=null;configSettingsForReasoning={};currentGitBranch=null;useLocalEnvironmentFallbackForActiveThread=!1;fastModeToastID=null;statusMessage=null;statusMessageTimer=null;isEditorUploadLocked=!1;initState(){this.agentMode=this.widget.initialAgentMode,this.subscribeToPluginAgentModes(),this.applyInitialPluginAgentMode(),this.subscribeToConfigSettings(),this.updateGitBranch()}applyInitialPluginAgentMode(){if(!this.widget.initialPluginAgentModeKey||this.widget.threadContext)return;this.desiredPluginAgentModeKey=this.widget.initialPluginAgentModeKey,this.selectedPluginAgentMode=this.pluginAgentModes.find((A)=>A.key===this.widget.initialPluginAgentModeKey)??null}didUpdateWidget(A){if(A.configService!==this.widget.configService)this.subscribeToConfigSettings();if(MQ.of(this.context).pluginService!==MQ.of(this.context).pluginService)this.subscribeToPluginAgentModes();if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.isEditorUploadLocked=!1,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null,this.useLocalEnvironmentFallbackForActiveThread=!0;else this.previousThreadIDForReference=null,this.useLocalEnvironmentFallbackForActiveThread=A.threadContext===null}dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.configSubscription?.unsubscribe(),this.configSubscription=null,this.pluginAgentModesSubscription?.unsubscribe(),this.pluginAgentModesSubscription=null,this.statusMessageTimer)clearTimeout(this.statusMessageTimer),this.statusMessageTimer=null}updateGitBranch=async()=>{let A=MQ.of(this.context).workspaceRoot,Q=await OU6(A);if(!this.mounted)return;this.setState(()=>{this.currentGitBranch=Q})};subscribeToPluginAgentModes(){this.pluginAgentModesSubscription?.unsubscribe(),this.pluginAgentModesSubscription=null;let A=MQ.of(this.context).pluginService?.agentModes;if(!A){this.syncPluginAgentModes([]);return}this.syncPluginAgentModes(A.list()),this.pluginAgentModesSubscription=A.changed.subscribe({next:()=>this.syncPluginAgentModes(A.list())})}syncPluginAgentModes(A){this.setState(()=>{let Q=this.selectedPluginAgentMode?.key??this.desiredPluginAgentModeKey;if(this.pluginAgentModes=A,Q){let $=A.find((B)=>B.key===Q)??null;this.selectedPluginAgentMode=$,this.desiredPluginAgentModeKey=$?.key??Q}}),this.refreshCommands()}refreshCommands(){this.unregisterCommands?.(),this.unregisterCommands=this.registerCommands()}get appContext(){return MQ.of(this.context)}get configService(){return this.widget.configService}getThreadContext(){return this.widget.threadContext??null}getThreadURL(){let A=this.getThreadContext()?.client.getThreadId();return A?hG(new URL(this.appContext.ampURL),A).toString():null}archiveThread(A){return this.widget.archiveThread(A)}addLabel(A,Q){return this.widget.addThreadLabel(A,Q)}removeLabel(A,Q){return this.widget.removeThreadLabel(A,Q)}sendFeedbackReport(A){return this.widget.sendFeedbackReport(A)}createPluginModeCommands(){let A=this;return this.pluginAgentModes.map((Q)=>({id:`pluginMode.use.${Q.key}`,noun:"mode",verb:`use ${Q.label}`,description:Q.description??`Enable ${Q.label} mode`,get status(){if(A.widget.threadContext)return{type:"hidden"};if(Q.key===A.selectedPluginAgentMode?.key)return{type:"disabled",reason:`Already using ${Q.label} mode`};return{type:"enabled"}},run:($,B,E)=>{A.setPluginAgentMode(Q),E()}}))}registerCommands(){let A=sB.of(this.context),Q=new Set(BY(void 0,{isInternalUser:this.appContext.isInternalUser}).map(({mode:E})=>E)),B=[...jU6.filter(({mode:E})=>Q.has(E)).map(({command:E})=>E.bind(this)),...this.createPluginModeCommands(),...hU6.map((E)=>E.bind(this))].map((E)=>A.register(E));return()=>{for(let E of B)E()}}currentCommandAgentMode(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.agentMode;return this.widget.threadContext?.observer.agentMode??this.agentMode}currentThreadSettings(){return this.widget.threadContext?.observer.threadSettings().getValue()??this.widget.draftThreadSettings}currentCommandSpeedModel(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.selectedPluginAgentMode.agent.model;return T6(this.currentCommandAgentMode())?.primaryModel}currentCommandModeLabel(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.selectedPluginAgentMode.label;return this.currentCommandAgentMode()}currentSpeedSettingKey(){let A=this.currentCommandSpeedModel();return A?Y50(A):void 0}speedCostMultiplierLabel(){let A=this.currentCommandSpeedModel();return A?qy0(A):void 0}isFastSpeedEnabled(){let A=this.currentSpeedSettingKey();return A!==void 0&&this.currentThreadSettings()[A]==="fast"}speedToggleCommandStatus(){if(this.currentSpeedSettingKey()===void 0)return{type:"hidden"};return{type:"enabled"}}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let $=Q.observer.threadSettings().getValue()??{},B=A($);return Q.client.sendClientUpdateThreadSettings(B).catch((E)=>{S.warn("Failed to update thread settings",{error:E})}),this.widget.updateDraftThreadSettings(()=>B),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){return this.setSpeed(this.isFastSpeedEnabled()?"normal":"fast")}setSpeed(A){let Q=this.currentSpeedSettingKey();if(Q===void 0)return"ignored";let $=A==="normal"?"standard":"fast",B=this.updateThreadSettings((E)=>{return{...E,[Q]:$}});if(!(this.selectedPluginAgentMode&&!this.widget.threadContext))this.rememberSpeedForMode(this.currentCommandAgentMode(),$);if(A==="fast")this.showFastModeToast();return B}showFastModeToast(){let A=DQ.maybeOf(this.context);if(!A)return;if(this.fastModeToastID!==null)A.dismiss(this.fastModeToastID);let Q=this.currentCommandModeLabel(),$=this.speedCostMultiplierLabel()??"2.5x";this.fastModeToastID=A.show(`↯${Q} costs ${$} the standard rate for this mode`,"warning",qU6)}dismissFastModeToast(){if(this.fastModeToastID===null)return;DQ.maybeOf(this.context)?.dismiss(this.fastModeToastID),this.fastModeToastID=null}toggleWorkDetails(){return this.expansion.toggle(!1),"handled"}rememberReasoningEffortForMode(A,Q){let $=MQ.of(this.context);$.lastReasoningEffortByMode={...$.lastReasoningEffortByMode??{},[A]:Q}}rememberSpeedForMode(A,Q){let $=MQ.of(this.context);$.lastSpeedByMode={...$.lastSpeedByMode??{},[A]:Q}}applyStickySpeedForMode(A,Q){let $=oN(Q),B=Z50(MQ.of(this.context),Q);if($===void 0||B===void 0)return A;return{...A,[$]:B}}toggleReasoningEffort(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return"ignored";let A=this.currentCommandAgentMode(),Q=dC(A);if(!Q)return"ignored";return this.updateThreadSettings(($)=>{let B=wy0(A,$,this.configSettingsForReasoning),E=qhA(Q,B);return this.rememberReasoningEffortForMode(A,E),{...$,"reasoning.effort":E}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,NU6.cwd()),this.resetHistory()};handleEditorUploadLockChange=(A)=>{if(this.isEditorUploadLocked===A)return;this.setState(()=>{this.isEditorUploadLocked=A})};resetHistory(){this.widget.history.reset()}setAgentMode=(A)=>{if(this.widget.threadContext)return;if(A!==this.agentMode)this.dismissFastModeToast();this.setState(()=>{this.agentMode=A,this.selectedPluginAgentMode=null,this.desiredPluginAgentModeKey=null}),this.widget.updateDraftThreadSettings((Q)=>{let $=Hy0(MQ.of(this.context),A),B={...Q};delete B["reasoning.effort"];let E=$??wy0(A,B,this.configSettingsForReasoning);if(E===void 0){let D={...Q};return delete D["reasoning.effort"],this.applyStickySpeedForMode(D,A)}return this.applyStickySpeedForMode({...Q,"reasoning.effort":E},A)})};setPluginAgentMode=(A)=>{if(this.widget.threadContext)return;this.dismissFastModeToast(),this.setState(()=>{this.selectedPluginAgentMode=A,this.desiredPluginAgentModeKey=A?.key??null})};toggleAgentMode(){let A=BY(void 0,{isInternalUser:this.appContext.isInternalUser});if(this.selectedPluginAgentMode){let $=this.pluginAgentModes.findIndex((E)=>E.key===this.selectedPluginAgentMode?.key),B=$===-1?void 0:this.pluginAgentModes[$+1];if(B)return this.setPluginAgentMode(B),"handled";return this.setPluginAgentMode(null),this.setAgentMode(A[0]?.mode??this.agentMode),"handled"}let Q=whA(this.agentMode,A);if(Q===A[0]?.mode&&this.pluginAgentModes.length>0)return this.setPluginAgentMode(this.pluginAgentModes[0]??null),"handled";return this.setAgentMode(Q),"handled"}buildActions(){let A=new cA((B)=>{return this.setAgentMode(B.mode),"handled"}),Q=new cA(()=>{return this.toggleReasoningEffort()}),$=new cA(()=>{return this.toggleWorkDetails()});return new Map([[qh0,A],[jq,Q],[P70,$]])}build(A){let Q=this.widget.threadContext,$=MQ.of(A),B=bL4(this.selectedPluginAgentMode?.color),E=LU6($.workspaceRoot,this.currentGitBranch),J=[Q?new Vc0({editorController:this.widget.editorController,editorFocusNode:this.widget.editorFocusNode,copyOnSelectEnabled:this.copyOnSelectEnabled,observingClient:{client:Q.client,observer:Q.observer,agentModeDisplay:Q.agentModeDisplay},hints:this.widget.hints,ideStatus:this.widget.ideStatus,statusItems:this.widget.statusItems,pluginConfirmationBlocked:this.widget.pluginConfirmationBlocked,onPromptSubmitted:this.onPromptSubmitted,onEditorUploadLockChange:this.handleEditorUploadLockChange,editorUploadLocked:this.isEditorUploadLocked,notificationService:this.widget.notificationService??wU6,environmentFallback:this.useLocalEnvironmentFallbackForActiveThread?E:null}):new Sc0({agentMode:this.agentMode,pluginAgentModes:this.pluginAgentModes,selectedPluginAgentMode:this.selectedPluginAgentMode,agentModeLabel:this.selectedPluginAgentMode?.label,pluginAgentModeURI:this.selectedPluginAgentMode?.sourceURI,agentModeColor:uU6(this.selectedPluginAgentMode?.color),splashPrimaryColor:B?MU6(B):void 0,splashSecondaryColor:B,threadSettings:this.widget.draftThreadSettings,configSettings:this.configSettingsForReasoning,editorController:this.widget.editorController,editorFocusNode:this.widget.editorFocusNode,visibility:null,onNewThread:this.widget.onNewThread,onAgentModeChange:this.setAgentMode,onPluginAgentModeChange:this.setPluginAgentMode,onEditorUploadLockChange:this.handleEditorUploadLockChange,editorUploadLocked:this.isEditorUploadLocked,previousThreadIDForReference:this.previousThreadIDForReference,hints:this.widget.hints,ideStatus:this.widget.ideStatus,statusItems:this.widget.statusItems,configService:this.widget.configService,environment:E,notice:this.widget.notice??null,onDismissNotice:this.widget.onDismissNotice??(()=>{}),statusMessage:this.statusMessage})],U=new Map([[wA.alt("t"),new P70]]);return new N4({actions:this.buildActions(),child:new rQ({debugLabel:"ThreadShortcuts",shortcuts:U,child:new TT({history:this.isEditorUploadLocked?void 0:this.widget.history,child:new z9({controller:this.expansion,child:new t1({children:J})})})})})}subscribeToConfigSettings(){this.configSubscription?.unsubscribe(),this.configSubscription=this.widget.configService.config.subscribe((A)=>{let Q=A.settings["terminal.copyOnSelect"]??!0;this.expansion.setDefaultExpanded(A.settings["terminal.detailsExpandedByDefault"]??!1);let $=A.settings["internal.model"],B=this.configSettingsForReasoning["internal.model"]!==$;if($===void 0)this.configSettingsForReasoning={};else this.configSettingsForReasoning={"internal.model":$};if(this.copyOnSelectEnabled===Q&&!B)return;if(this.copyOnSelectEnabled=Q,this.mounted)this.setState()})}}i0();f8();E4();class sX extends G4{direction;constructor(A){super();this.direction=A}}class p90 extends G4{}class Ji extends G4{}class l90 extends G4{index;constructor(A){super();this.index=A}}function hc0(A){return A.length+2}class gc0 extends d0{props;constructor(A){super();this.props=A}createState(){return new gL4}}class gL4 extends m0{selectedIndex=0;initState(){super.initState(),this.selectedIndex=this.findSelectableIndex(this.widget.props.initialSelectedIndex??0)}didUpdateWidget(A){this.selectedIndex=this.findSelectableIndex(this.selectedIndex)}isSelectable(A){let Q=this.widget.props.entries[A];return Q?.type==="item"&&(Q.enabled??!0)}findSelectableIndex(A){let{entries:Q}=this.widget.props;if(Q.length===0)return 0;let $=Math.max(0,Math.min(A,Q.length-1));if(this.isSelectable($))return $;for(let B=1;B<Q.length;B++){let E=$+B;if(E<Q.length&&this.isSelectable(E))return E;let D=$-B;if(D>=0&&this.isSelectable(D))return D}return 0}moveSelection(A){let Q=this.findNextSelectableIndex(A);if(Q===this.selectedIndex)return;this.setState(()=>{this.selectedIndex=Q})}findNextSelectableIndex(A){let{entries:Q}=this.widget.props;for(let $=this.selectedIndex+A;$>=0&&$<Q.length;$+=A)if(this.isSelectable($))return $;return this.selectedIndex}acceptIndex(A){let Q=this.widget.props.entries[A];if(Q?.type!=="item"||!(Q.enabled??!0))return;this.setState(()=>{this.selectedIndex=A}),this.widget.props.onAccept(Q.value)}invoke=(A)=>{if(A instanceof sX)return this.moveSelection(A.direction),"handled";if(A instanceof p90)return this.acceptIndex(this.selectedIndex),"handled";if(A instanceof Ji)return this.widget.props.onDismiss(),"handled";if(A instanceof l90)return this.acceptIndex(A.index),"handled";return"ignored"};buildShortcuts(){let A=new Map([[wA.key("ArrowDown"),new sX(1)],[wA.key("j"),new sX(1)],[wA.ctrl("n"),new sX(1)],[wA.key("ArrowUp"),new sX(-1)],[wA.key("k"),new sX(-1)],[wA.ctrl("p"),new sX(-1)],[wA.key("Enter"),new p90],[wA.key("Escape"),new Ji],[wA.ctrl("."),new Ji]]);return this.widget.props.entries.forEach((Q,$)=>{if(Q.type==="item"&&Q.shortcut)A.set(Q.shortcut,new l90($))}),A}buildActions(){return new Map([[sX,new cA(this.invoke)],[p90,new cA(this.invoke)],[Ji,new cA(this.invoke)],[l90,new cA(this.invoke)]])}build(A){let Q=e0.of(A),$=gU6(this.widget.props.entries,X4.of(A).supportsEmojiWidth);return new GA({width:this.widget.props.width,height:hc0(this.widget.props.entries),decoration:new u1(Q.colors.background,U1.all(new Y1(Q.colors.border,1,"solid"))),child:new N4({actions:this.buildActions(),child:new rQ({debugLabel:"ContextPickerShortcuts",shortcuts:this.buildShortcuts(),child:new VQ({autofocus:!0,debugLabel:"ContextPicker",child:new UA({mainAxisSize:"min",crossAxisAlignment:"stretch",children:this.widget.props.entries.map((B,E)=>this.buildEntry(B,E,$,Q))})})})})})}buildEntry(A,Q,$,B){if(A.type==="separator")return new GA({height:1,decoration:{border:new U1(new Y1(B.colors.border,1,"solid"))}});let E=Q===this.selectedIndex,D=A.enabled??!0,J=new A0({color:E?B.app.selectionForeground:B.colors.foreground,dim:!D}),U=new A0({color:E?B.app.selectionForeground:B.app.keybind,bold:!0,dim:!D});return new iA({onClick:()=>this.acceptIndex(Q),child:new GA({padding:c0.symmetric(1,0),decoration:E?new u1(B.app.selectionBackground):void 0,child:new OA({crossAxisAlignment:"start",children:[new P4({child:new D0({text:new g(A.label,J),maxLines:1,overflow:"ellipsis"})}),new y0({width:1}),new y0({width:$,child:new D0({text:new g(mL4(A),U),textAlign:"right",maxLines:1,overflow:"ellipsis"})})]})})})}}function gU6(A,Q){return A.reduce(($,B)=>{return B.type==="item"?Math.max($,RA(mL4(B),Q)):$},0)}function mL4(A){return A.shortcutLabel??A.shortcut?.toString().toLowerCase()??""}var mU6=36,dU6=24,cU6=72;class dL4 extends d0{child;onContext;constructor(A,Q){super();this.child=A;this.onContext=Q}createState(){return new cL4}}class cL4 extends m0{build(A){return this.widget.onContext(A),this.widget.child}}function pU6(A){return A.reduce((Q,$)=>Math.max(Q,RA(_T($.description.timeAgo))),0)}function pL4(A){return Math.max(dU6,Math.min(A,cU6))}class mc0 extends G4{}class dc0 extends G4{}class cc0 extends G4{}var lU6=O4("thread.toggleSidebar",{noun:"thread",verb:"toggle sidebar",description:"Show or hide the thread sidebar",defaultKey:"alt+s",status:{type:"enabled"}},(A,{dismiss:Q})=>{Q(),A.toggleVisibility()});class pc0{options;focusScopeNode=new a7({debugLabel:"ThreadListSidebar"});initialized=!1;visible=!1;hasRenderedSidebar=!1;width=mU6;pickerController=new gp;constructor(A){this.options=A}isVisible(){return this.ensureInitialized(),this.visible}visibleWidth(){return this.isVisible()?this.width:0}buildBody(A){return new OA({crossAxisAlignment:"stretch",children:[this.buildSlot(),new P4({child:A})]})}buildSlot(){let A=this.isVisible();if(!this.hasRenderedSidebar)return new y0({width:0});let Q={activeThreadID:this.options.getActiveThreadID(),currentWorkspaceURI:U4(g0.file(this.options.getWorkspaceRoot())),width:this.width,loadThreads:this.options.loadThreads,pickerController:this.pickerController,archiveThread:this.options.archiveThread,onSelectThread:this.options.onSelectThread,onDismiss:this.close,onResizeWidth:this.resize};if(this.options.observeThreadSummaries)Q.observeThreadSummaries=this.options.observeThreadSummaries;return new y0({width:A?this.width:0,child:new E6({focusScopeNode:this.focusScopeNode,debugLabel:"ThreadListSidebar",onFocusChange:this.handleFocusChange,child:new lL4(Q)})})}commands(){return[lU6.bind({toggleVisibility:this.toggleVisibility})]}shortcutEntries(){return[[wA.alt("s"),new v70]]}actionEntries(){return[[v70,new cA(()=>this.toggleFromShortcut())]]}toggleFromShortcut=()=>{if(this.isVisible()){if(this.focusScopeNode.hasFocus)return this.close(),"handled";if(this.options.isBlocked())return"ignored";return this.pickerController.requestFocus(),"handled"}if(this.options.isBlocked())return"ignored";return this.pickerController.requestFocus(),this.setVisible(!0),"handled"};toggleVisibility=()=>{if(this.isVisible()){this.close();return}if(this.options.isBlocked())return;this.pickerController.requestFocus(),this.setVisible(!0)};close=()=>{this.options.focusMainContent(),this.setVisible(!1)};setVisible(A){if(this.ensureInitialized(),this.visible===A)return;if(A)this.hasRenderedSidebar=!0;this.options.state.setState(()=>{this.visible=A}),eD((Q)=>({...Q,threadListSidebarVisible:A})).catch((Q)=>{S.warn("Failed to save thread sidebar visibility state",{error:Q instanceof Error?Q.message:String(Q)})})}ensureInitialized(){if(this.initialized)return;this.initialized=!0,this.visible=this.options.getInitialVisible(),this.hasRenderedSidebar=this.visible}handleFocusChange=(A)=>{this.options.state.setState()};dispose(){this.focusScopeNode.dispose()}resize=(A)=>{let Q=pL4(A);if(Q===this.width)return;this.options.state.setState(()=>{this.width=Q})}}class lL4 extends d0{props;constructor(A){super();this.props=A}createState(){return new iL4}}class iL4 extends m0{threads=[];isLoading=!0;isSwitchingThread=!1;hasError=!1;filterByWorkspace=!0;contextMenu=null;pendingThreadMutations=new Map;canonicalThreadSummariesByID=new Map;archivedCanonicalThreadIDs=new Set;liveThreadIDsObservedInCurrentWorkspace=new Set;liveThreadSummaries=null;resizeSession=null;isResizeHandleHovered=!1;threadItemContexts=new Map;threadSummarySubscription=null;observedThreadSummaries;shortcuts=new Map([[wA.alt("w"),new mc0],[wA.ctrl("."),new dc0],[wA.key("e"),new cc0]]);actions=new Map([[mc0,new cA(()=>{return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.contextMenu=null}),"handled"})],[dc0,new cA(()=>this.openContextMenu())],[cc0,new cA(()=>this.archiveSelectedThread())]]);get isBusy(){return this.isLoading}get isResizeActive(){return this.resizeSession!==null||this.isResizeHandleHovered}didUpdateWidget(A){if(super.didUpdateWidget(A),this.contextMenu&&(A.props.width!==this.widget.props.width||A.props.currentWorkspaceURI!==this.widget.props.currentWorkspaceURI))this.contextMenu=null;if(A.props.observeThreadSummaries!==this.widget.props.observeThreadSummaries)this.startThreadSummaryUpdates();if(A.props.activeThreadID!==this.widget.props.activeThreadID)this.rememberActiveLiveThreadInCurrentWorkspace()}initState(){super.initState(),this.startThreadSummaryUpdates()}dispose(){this.threadSummarySubscription?.unsubscribe(),this.threadSummarySubscription=null,super.dispose()}startThreadSummaryUpdates(){this.threadSummarySubscription?.unsubscribe(),this.threadSummarySubscription=null,this.liveThreadSummaries=null,this.observedThreadSummaries=this.widget.props.observeThreadSummaries;let A=this.widget.props.observeThreadSummaries;if(!A){this.loadThreadSummaries();return}let Q=A();if(!Q){this.loadThreadSummaries();return}this.loadThreadSummaries(),this.threadSummarySubscription=Q.subscribe({next:($)=>this.applyLiveThreadSummaries($),error:($)=>{if(S.error("Failed to observe threads for Neo sidebar",{error:$}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}})}async loadThreadSummaries(){let A=this.observedThreadSummaries;try{let Q=await this.widget.props.loadThreads(),$=tl(Q);if(!this.mounted||A!==this.observedThreadSummaries)return;this.archivedCanonicalThreadIDs.clear();for(let B of Q)if(B.archived)this.archivedCanonicalThreadIDs.add(B.id);this.applyCanonicalThreadSummaries($)}catch(Q){if(S.error("Failed to load threads for Neo sidebar",{error:Q}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}applyCanonicalThreadSummaries(A){this.canonicalThreadSummariesByID.clear();for(let Q of A)this.canonicalThreadSummariesByID.set(Q.id,Q);this.applyThreadSummaries(this.liveThreadSummaries?this.mergeLiveMetadata():A)}applyLiveThreadSummaries(A){this.liveThreadSummaries=A,this.rememberActiveLiveThreadInCurrentWorkspace();let Q=this.mergeLiveMetadata();if(Q.length===0&&this.canonicalThreadSummariesByID.size===0&&this.isLoading)return;this.applyThreadSummaries(Q)}rememberActiveLiveThreadInCurrentWorkspace(){let A=this.widget.props.activeThreadID;if(A&&this.liveThreadSummaries?.some((Q)=>Q.id===A&&Q.updatedAt))this.liveThreadIDsObservedInCurrentWorkspace.add(A)}mergeLiveMetadata(){let A=new Map((this.liveThreadSummaries??[]).map((B)=>[B.id,B])),Q=(this.liveThreadSummaries??[]).flatMap((B)=>{if(this.archivedCanonicalThreadIDs.has(B.id))return[];let E=this.canonicalThreadSummariesByID.get(B.id);if(!E){if(!B.updatedAt)return[];return[B]}return[this.mergeLiveThreadSummary(E,B)]}),$=Array.from(this.canonicalThreadSummariesByID.values()).filter((B)=>!A.has(B.id));return[...Q,...$]}mergeLiveThreadSummary(A,Q){return{...A,...Q,updatedAt:Q.updatedAt??A.updatedAt,description:Q.updatedAt?Q.description:A.description,workspaceURI:A.workspaceURI,relationships:A.relationships,diffStats:A.diffStats,agentMode:A.agentMode,details:A.details,archived:A.archived}}applyThreadSummaries(A){if(!this.mounted)return;this.setState(()=>{let Q=rK(A).flat(),$=this.widget.props.pickerController.selectedItem?.id??this.widget.props.activeThreadID;this.widget.props.pickerController.selectedItem=Q.find((B)=>B.id===$)??Q.find((B)=>B.id===this.widget.props.activeThreadID)??null,this.threads=Q,this.isLoading=!1,this.hasError=!1})}handleSelectThread=async(A)=>{if(this.isSwitchingThread)return;this.setState(()=>{this.isSwitchingThread=!0});try{await this.widget.props.onSelectThread(A)}catch(Q){S.error("Failed to switch thread from Neo sidebar",{error:Q,threadID:A})}finally{if(this.mounted)this.setState(()=>{this.isSwitchingThread=!1})}};getOptimisticThreads(){return this.threads.flatMap((A)=>{if(this.pendingThreadMutations.get(A.id)?.kind==="archive")return[];return[A]})}getThreadsForDisplay(){let A=this.getOptimisticThreads();return this.filterByWorkspace?A.filter((Q)=>this.threadMatchesCurrentWorkspace(Q)):A}threadMatchesCurrentWorkspace(A){if(A.workspaceURI)return A.workspaceURI===this.widget.props.currentWorkspaceURI;return this.canonicalThreadSummariesByID.has(A.id)||this.liveThreadIDsObservedInCurrentWorkspace.has(A.id)||A.id===this.widget.props.activeThreadID}buildContextMenuEntries(){return[{type:"item",value:"archive",label:"Archive Thread",shortcut:wA.key("a"),shortcutLabel:"a"},{type:"separator"},{type:"item",value:"copy-id",label:"Copy ID",shortcut:wA.ctrl("c"),shortcutLabel:"ctrl+c"},{type:"item",value:"copy-url",label:"Copy URL",shortcut:new wA("c",{shift:!0,ctrl:!0}),shortcutLabel:"shift+ctrl+c"}]}openContextMenu(){let A=this.widget.props.pickerController.selectedItem;if(!A||this.isBusy||this.isSwitchingThread||this.hasError)return"ignored";let Q=this.buildContextMenuEntries(),$=hc0(Q),B=this.getContextMenuWidth(),E=this.getContextMenuPosition(A.id,$,B);return this.setState(()=>{this.contextMenu={threadID:A.id,left:E.left,top:E.top,width:B,height:$}}),"handled"}archiveSelectedThread(){let A=this.widget.props.pickerController.selectedItem?.id;if(!A||this.contextMenu||this.isBusy||this.isSwitchingThread||this.hasError)return"ignored";return this.archiveThread(A),"handled"}getContextMenuWidth(){let A=Math.max(24,this.widget.props.width-3);return Math.max(1,Math.min(A,this.widget.props.width-2))}getContextMenuPosition(A,Q,$){let B=Math.max(0,Math.min(2,this.widget.props.width-$)),E=1,D=this.threadItemContexts.get(A)?.findRenderObject(),J=this.context.findRenderObject();if(!(D instanceof bA)||!(J instanceof bA))return{left:B,top:1};let U=D.localToGlobal({x:0,y:0}),Y=J.localToGlobal({x:0,y:0}),Z=U.y-Y.y,F=Z+D.size.height,X=X4.sizeOf(this.context).height,I=Math.max(1,Math.min(J.size.height,X-Y.y)),K=I-F>=Q||Z<I/2?F:Z-Q,z=Math.max(0,I-Q);return{left:B,top:Math.max(0,Math.min(K,z))}}closeContextMenu=()=>{if(!this.contextMenu)return;this.setState(()=>{this.contextMenu=null})};handleContextMenuAccept=(A)=>{let Q=this.contextMenu?.threadID;if(!Q)return;if(this.closeContextMenu(),A==="archive"){this.archiveThread(Q);return}if(A==="copy-id"){N4.maybeInvoke(this.context,new IB(Q,"Thread ID copied to clipboard","Failed to copy thread ID"));return}N4.maybeInvoke(this.context,new IB(this.getThreadURL(Q),"Thread URL copied to clipboard","Failed to copy thread URL"))};beginOptimisticArchive(A){if(this.pendingThreadMutations.has(A))return!1;if(!this.threads.some(($)=>$.id===A))return!1;let Q={kind:"archive",fallbackSelectedThreadID:null};return this.setState(()=>{this.pendingThreadMutations.set(A,Q)}),cQ.instance.addPostFrameCallback(()=>{if(!this.mounted)return;let $=this.pendingThreadMutations.get(A);if($?.kind!=="archive")return;$.fallbackSelectedThreadID=this.widget.props.pickerController.selectedItem?.id??null}),!0}commitOptimisticArchive(A){if(this.pendingThreadMutations.get(A)?.kind!=="archive")return;this.pendingThreadMutations.delete(A),this.canonicalThreadSummariesByID.delete(A),this.threads=this.threads.filter(($)=>$.id!==A)}rollbackOptimisticArchive(A){let Q=this.pendingThreadMutations.get(A);if(Q?.kind!=="archive")return;let $=this.threads.find((B)=>B.id===A);if(!$){this.pendingThreadMutations.delete(A);return}this.setState(()=>{this.pendingThreadMutations.delete(A);let B=this.widget.props.pickerController.selectedItem?.id??null;if(B===null||B===Q.fallbackSelectedThreadID)this.widget.props.pickerController.selectedItem=$})}async archiveThread(A){let Q=DQ.maybeOf(this.context);if(!this.beginOptimisticArchive(A))return;try{let $=await this.widget.props.archiveThread(A);if(!this.mounted)return;if($){this.rollbackOptimisticArchive(A),Q?.show($.message,"error");return}this.commitOptimisticArchive(A),Q?.show("Archived thread")}catch($){if(S.error("Failed to archive thread from Neo sidebar context menu",{error:$,threadID:A}),!this.mounted)return;this.rollbackOptimisticArchive(A),Q?.show("Failed to archive thread","error")}}getThreadURL(A){return hG(new URL(MQ.of(this.context).ampURL),A).toString()}buildContextMenuOverlay(){let A=this.contextMenu;if(!A||!this.getThreadsForDisplay().some((Q)=>Q.id===A.threadID))return null;return new m1({left:A.left,top:A.top,width:A.width,height:A.height,child:new E6({debugLabel:"ThreadListSidebarContextMenu",onFocusChange:(Q)=>{if(!Q)this.closeContextMenu()},child:new gc0({entries:this.buildContextMenuEntries(),width:A.width,onAccept:this.handleContextMenuAccept,onDismiss:this.closeContextMenu})})})}buildContextMenuBackdrop(){return new m1({left:0,top:0,right:0,bottom:0,child:new iA({onClick:()=>this.closeContextMenu(),child:y0.expand()})})}buildThreadItem(A,Q,$,B,E){let D=e0.of(E),{app:J,colors:U}=D,Y=A.id===this.widget.props.activeThreadID,Z=!Q&&!Y,F=Q?J.selectionForeground:U.foreground,X=Q?J.selectionForeground:U.mutedForeground,G=R90(A.agentState)?new oX({color:Q?J.selectionForeground:U.primary}):void 0,V=_T(A.description.timeAgo),K=new GA({padding:c0.symmetric(1,0),child:new OA({children:[new y0({width:2,child:G}),new P4({child:new D0({text:new g(A.title,new A0({color:F,dim:Z})),overflow:"ellipsis",maxLines:1})}),new y0({width:2}),new y0({width:$,child:OA.end([new D0({text:new g(V,new A0({color:X,dim:Z}))})])})]})}),z=B?new UA({children:[this.buildInactiveSeparator(E),K],crossAxisAlignment:"stretch"}):K;return new dL4(z,(W)=>{this.threadItemContexts.set(A.id,W)})}buildInactiveSeparator(A){let Q=e0.of(A).colors;return new GA({padding:c0.only({left:2,right:1,top:1}),child:new D0({text:new g("──── Inactive in last 24h ────",new A0({color:Q.mutedForeground,dim:!0})),overflow:"ellipsis",maxLines:1})})}handleResizeHandlePress=(A)=>{if(A.button!=="left")return;this.setState(()=>{this.resizeSession={baseWidthColumns:this.widget.props.width,startColumn:Math.floor(A.position.x)}})};handleResizeHandleDrag=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;let Q=Math.floor(A.position.x)-this.resizeSession.startColumn,$=pL4(this.resizeSession.baseWidthColumns+Q);if($!==this.widget.props.width)this.widget.props.onResizeWidth($)};handleResizeHandleRelease=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;this.setState(()=>{this.resizeSession=null})};handleResizeHandleEnter=()=>{if(this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!0})};handleResizeHandleExit=()=>{if(!this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!1})};buildResizeHandle(){return new m1({top:0,right:0,bottom:0,width:1,child:new iA({cursor:o1.EW_RESIZE,onClick:this.handleResizeHandlePress,onDrag:this.handleResizeHandleDrag,onRelease:this.handleResizeHandleRelease,onEnter:this.handleResizeHandleEnter,onExit:this.handleResizeHandleExit,child:new y0({width:1})})})}build(A){let Q=e0.of(A),$=this.getThreadsForDisplay(),B=this.hasError?[]:$,E=pU6(B),D=rK(B)[1]?.[0]?.id;this.threadItemContexts.clear();let J=this.isResizeActive?2:1,U=new U1(void 0,new Y1(Q.colors.border,J),void 0,void 0),Y=this.buildContextMenuOverlay(),Z=[new GA({decoration:new u1(Q.colors.background,U),child:new N4({actions:this.actions,child:new rQ({shortcuts:this.shortcuts,debugLabel:"ThreadListSidebarFilter",child:new j5({items:B,getLabel:(F)=>`${F.title} ${F.id}`,controller:this.widget.props.pickerController,autofocus:!1,acceptOnClick:!0,onAccept:(F)=>void this.handleSelectThread(F.id),renderItem:(F,X,I,G)=>this.buildThreadItem(F,X,E,F.id===D,G),enabled:!this.isBusy,isLoading:this.isBusy,hidePrompt:!0,loadingText:"Loading threads...",emptyStateText:this.hasError?"Failed to load threads":void 0,emptyStateWidget:this.hasError?void 0:(F)=>yd0(F,this.filterByWorkspace),maxRenderItems:200,showBorder:!1})})})}),this.buildResizeHandle()];if(Y)Z.push(this.buildContextMenuBackdrop()),Z.push(Y);return new GA({width:this.widget.props.width,child:new t1({fit:"expand",children:Z})})}}E3();class lc0 extends d0{toolboxes;onDismiss;constructor(A){super();this.toolboxes=A.toolboxes,this.onDismiss=A.onDismiss}createState(){return new aL4}}class aL4 extends m0{toolboxes=new p3(this,[]);initState(){this.toolboxes.subscribe(this.widget.toolboxes)}didUpdateWidget(A){if(A.toolboxes!==this.widget.toolboxes)this.toolboxes.subscribe(this.widget.toolboxes)}build(A){return new oL4({toolboxes:this.toolboxes.getValue(),onDismiss:this.widget.onDismiss})}}class oL4 extends d0{toolboxes;onDismiss;constructor(A){super();this.toolboxes=A.toolboxes,this.onDismiss=A.onDismiss}createState(){return new rL4}}class rL4 extends m0{scrollController=new a6;canScroll=!1;initState(){this.scrollController.followMode=!1,this.scrollController.jumpTo(0),this.scrollController.addListener(this.updateCanScroll)}dispose(){this.scrollController.removeListener(this.updateCanScroll),this.scrollController.dispose()}updateCanScroll=()=>{let A=this.scrollController.maxScrollExtent>0;if(A===this.canScroll)return;this.setState(()=>{this.canScroll=A})};build(A){return new E1({header:"Toolboxes",onDismiss:this.widget.onDismiss,minWidth:80,maxWidth:120,maxHeight:40,autofocus:!1,footer:iU6(this.canScroll),child:new vB({controller:this.scrollController,child:nU6(A,this.widget.toolboxes)})})}}function iU6(A){let Q=[{keys:["Esc"],label:"close"}];if(A)Q.push({keys:["↑↓","j/k"],label:"scroll"});return Q}function nU6(A,Q){let $=aU6(A,Q);return new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new D0({text:new g("",void 0,$),selectable:!0})]})}function aU6(A,Q){let $=e0.of(A),{colors:B}=$,E=new A0({color:B.foreground,dim:!0}),D=new A0({color:B.foreground,bold:!0});if(Q.length===0)return[new g("No toolboxes found.",E)];let J=[];for(let U of Q){let Y=U.tools.length,Z=U.tools.filter((F)=>F.status==="registered").length;if(U.discovering){let F=U.tools.filter((X)=>X.status!=="pending").length;J.push(new g(U.path,D)),J.push(new g(` discovering ${F}/${Y}...
2907
+ `)[0]??"",Q.description)})}));return $.push(new mA({padding:c0.only({left:4}),child:new D0({text:new g(yL4(A.path,Q.cwd),Q.location),maxLines:1,overflow:"ellipsis"})})),$}function WU6(A){try{return new URL(A).pathname.split("/").filter(Boolean).at(-2)??"unknown"}catch{return"unknown"}}function CU6(A,Q,$){if(Q)return new OA({crossAxisAlignment:"start",children:[new P4({flex:1,child:new D0({text:new g(A.name,$.name),maxLines:1,overflow:"ellipsis"})}),new y0({width:2}),new P4({flex:2,child:new mA({padding:c0.only({right:1}),child:new D0({text:new g(A.description,$.description),maxLines:1,overflow:"ellipsis"})})})]});return new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new OA({crossAxisAlignment:"start",children:[new D0({text:new g(A.name,$.name),maxLines:1,overflow:"ellipsis"}),new P4({child:new D0({text:new g(` ${yL4(A.baseDir,$.cwd)}`,$.location),maxLines:1,overflow:"ellipsis"})})]}),new mA({padding:c0.only({left:2,right:1}),child:new D0({text:new g(A.description,$.description),maxLines:1,overflow:"ellipsis"})})]})}function yL4(A,Q){if(A.startsWith("builtin://"))return"(builtin)";if(!A.startsWith("file://"))return A;let $=BU6(A),B=QU6(Q,$);if(B&&!B.startsWith(".."))return`./${B}`;let E=AU6();if($===E||$.startsWith(E+$U6))return`~${$.slice(E.length)}`;return $}var qU6=5000,wU6={attach:()=>{},detach:()=>{},unsubscribe:()=>{}};function uU6(A){let Q=bL4(A);return Q?{type:"rgb",value:Q}:void 0}function bL4(A){let Q=A?.match(/^#([0-9a-f]{6})$/i);if(!Q?.[1])return;return{r:Number.parseInt(Q[1].slice(0,2),16),g:Number.parseInt(Q[1].slice(2,4),16),b:Number.parseInt(Q[1].slice(4,6),16)}}function MU6(A){return{r:Math.round(A.r*0.55),g:Math.round(A.g*0.55),b:Math.round(A.b*0.55)}}async function OU6(A){return new Promise((Q)=>{HU6("git",["branch","--show-current"],{cwd:A},($,B)=>{if($){Q(null);return}let E=B.trim();Q(E||null)})})}function LU6(A,Q){let $=U4(g0.file(A)),B={workspaceRoot:$,workingDirectory:$};if(Q)B.git={branch:Q};return B}var jU6=Gq0.filter((A)=>A!==L00).sort((A,Q)=>A.localeCompare(Q)).map((A)=>({mode:A,command:O4(`mode.use.${A}`,{noun:"mode",verb:`use ${A}`,description:`Enable ${A} mode`,status:(Q)=>{if(Q.getThreadContext())return{type:"hidden"};return A===Q.agentMode?{type:"disabled",reason:`Already using ${A} mode`}:{type:"enabled"}}},(Q,{dismiss:$})=>{Q.setAgentMode(A),$()})})),RU6=O4("mode.toggle",{noun:"mode",verb:"switch",description:"Switch to the next available mode",defaultKey:"ctrl+s",status:(A)=>A.getThreadContext()?{type:"hidden"}:{type:"enabled"}},(A,{dismiss:Q})=>{A.toggleAgentMode(),Q()}),PU6=O4("speed.toggleFast",{noun:"speed",verb:(A)=>{if(A.isFastSpeedEnabled())return"disable fast";let Q=A.speedCostMultiplierLabel();return Q?`use fast (${Q} cost)`:"use fast"},description:"Toggle fast speed for this thread",status:(A)=>A.speedToggleCommandStatus()},(A,{dismiss:Q})=>{A.toggleSpeed(),Q()}),TU6=O4("thread.toggleDetails",{noun:"thread",verb:"toggle details",description:"Expand or collapse tool and activity details",keywords:["expand","thinking"],defaultKey:"alt+t",status:{type:"enabled"}},(A,{dismiss:Q})=>{A.toggleWorkDetails(),Q()}),vU6=O4("mode.toggleReasoningEffort",{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",defaultKey:"alt+d",status:(A)=>{if(A.getThreadContext())return{type:"hidden"};return dC(A.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}}},(A,{dismiss:Q})=>{A.toggleReasoningEffort(),Q()}),_U6=O4("thread.copyID",{noun:"thread",verb:"copy ID",description:"Copy thread ID",status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},(A,{context:Q,dismiss:$})=>{let B=A.getThreadContext()?.client.getThreadId();if(!B)return;N4.maybeInvoke(Q,new IB(B,"Thread ID copied to clipboard","Failed to copy thread ID")),$()}),SU6=O4("thread.copyURL",{noun:"thread",verb:"copy URL",description:"Copy thread URL",keywords:["share"],status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},(A,{context:Q,dismiss:$})=>{let B=A.getThreadURL();if(!B)return;N4.maybeInvoke(Q,new IB(B,"Thread URL copied to clipboard","Failed to copy thread URL")),$()}),kU6=O4("thread.copyMarkdown",{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},async(A,{context:Q,dismiss:$})=>{let B=A.getThreadContext()?.client.getThreadId();if(!B)return;try{let E=await A.appContext.getThreadMarkdown(B);if(!E){DQ.error(Q,"Failed to copy thread markdown");return}N4.maybeInvoke(Q,new IB(E,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(E){S.error("Failed to render thread markdown from Neo command palette",{error:E,threadID:B}),DQ.error(Q,"Failed to copy thread markdown")}finally{$()}}),fU6=O4("thread.analyzeContext",{noun:"thread",verb:"analyze context",description:"Show token usage by prompt section for this thread",keywords:["tokens"],status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},(A,{controller:Q,dismiss:$})=>{let B=A.getThreadContext()?.client.getThreadId();if(!B)return;Q.push(new Kc0({threadID:B,analyzeContext:A.widget.analyzeContextForThread,onDismiss:$}))}),xU6=O4("skills.list",{noun:"skills",verb:"list",description:"List available skills for this thread",status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{let B=A.getThreadContext()?.client.getThreadId();if(!B){Q.push(new c90({status:{kind:"no-thread"},onDismiss:$,cwd:A.appContext.workspaceRoot}));return}Q.push(new yc0({listSkills:(E)=>A.widget.listSkillsForThread(B,E),onDismiss:$,cwd:A.appContext.workspaceRoot}))}),yU6=O4("thread.new",{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start"],sortBoost:101,status:(A)=>{if(A.isEditorUploadLocked)return{type:"disabled",reason:"Prompt editor is not available"};return A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}}},(A,{context:Q})=>{if(!A.isEditorUploadLocked)N4.maybeInvoke(Q,new Lq)}),bU6=O4("thread.openInBrowser",{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web"],status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},async(A,{context:Q,dismiss:$})=>{let B=A.getThreadURL();if(!B)return;try{await z$(Q,B)}finally{$()}}),hU6=[PU6,TU6,RU6,vU6,_U6,SU6,kU6,fU6,xU6,yU6,bU6,fL4,tO4,eO4,vL4,ML4,jL4];class bc0 extends d0{initialAgentMode;initialPluginAgentModeKey;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;editorFocusNode;history;updateDraftThreadSettings;onNewThread;sendFeedbackReport;archiveThread;addThreadLabel;removeThreadLabel;configService;hints;ideStatus;statusItems;pluginConfirmationBlocked;notificationService;notice;onDismissNotice;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.initialPluginAgentModeKey=A.initialPluginAgentModeKey,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.editorFocusNode=A.editorFocusNode,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.sendFeedbackReport=A.sendFeedbackReport,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.hints=A.hints,this.ideStatus=A.ideStatus,this.statusItems=A.statusItems??[],this.pluginConfirmationBlocked=A.pluginConfirmationBlocked,this.notificationService=A.notificationService,this.notice=A.notice,this.onDismissNotice=A.onDismissNotice}createState(){return new hL4}}class hL4 extends m0{agentMode;pluginAgentModes=[];selectedPluginAgentMode=null;desiredPluginAgentModeKey=null;pluginAgentModesSubscription=null;copyOnSelectEnabled=!0;configSubscription=null;expansion=new cm0;previousThreadIDForReference=null;unregisterCommands=null;configSettingsForReasoning={};currentGitBranch=null;useLocalEnvironmentFallbackForActiveThread=!1;fastModeToastID=null;statusMessage=null;statusMessageTimer=null;isEditorUploadLocked=!1;initState(){this.agentMode=this.widget.initialAgentMode,this.subscribeToPluginAgentModes(),this.applyInitialPluginAgentMode(),this.subscribeToConfigSettings(),this.updateGitBranch()}applyInitialPluginAgentMode(){if(!this.widget.initialPluginAgentModeKey||this.widget.threadContext)return;this.desiredPluginAgentModeKey=this.widget.initialPluginAgentModeKey,this.selectedPluginAgentMode=this.pluginAgentModes.find((A)=>A.key===this.widget.initialPluginAgentModeKey)??null}didUpdateWidget(A){if(A.configService!==this.widget.configService)this.subscribeToConfigSettings();if(MQ.of(this.context).pluginService!==MQ.of(this.context).pluginService)this.subscribeToPluginAgentModes();if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.isEditorUploadLocked=!1,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null,this.useLocalEnvironmentFallbackForActiveThread=!0;else this.previousThreadIDForReference=null,this.useLocalEnvironmentFallbackForActiveThread=A.threadContext===null}dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.configSubscription?.unsubscribe(),this.configSubscription=null,this.pluginAgentModesSubscription?.unsubscribe(),this.pluginAgentModesSubscription=null,this.statusMessageTimer)clearTimeout(this.statusMessageTimer),this.statusMessageTimer=null}updateGitBranch=async()=>{let A=MQ.of(this.context).workspaceRoot,Q=await OU6(A);if(!this.mounted)return;this.setState(()=>{this.currentGitBranch=Q})};subscribeToPluginAgentModes(){this.pluginAgentModesSubscription?.unsubscribe(),this.pluginAgentModesSubscription=null;let A=MQ.of(this.context).pluginService?.agentModes;if(!A){this.syncPluginAgentModes([]);return}this.syncPluginAgentModes(A.list()),this.pluginAgentModesSubscription=A.changed.subscribe({next:()=>this.syncPluginAgentModes(A.list())})}syncPluginAgentModes(A){this.setState(()=>{let Q=this.selectedPluginAgentMode?.key??this.desiredPluginAgentModeKey;if(this.pluginAgentModes=A,Q){let $=A.find((B)=>B.key===Q)??null;this.selectedPluginAgentMode=$,this.desiredPluginAgentModeKey=$?.key??Q}}),this.refreshCommands()}refreshCommands(){this.unregisterCommands?.(),this.unregisterCommands=this.registerCommands()}get appContext(){return MQ.of(this.context)}get configService(){return this.widget.configService}getThreadContext(){return this.widget.threadContext??null}getThreadURL(){let A=this.getThreadContext()?.client.getThreadId();return A?hG(new URL(this.appContext.ampURL),A).toString():null}archiveThread(A){return this.widget.archiveThread(A)}addLabel(A,Q){return this.widget.addThreadLabel(A,Q)}removeLabel(A,Q){return this.widget.removeThreadLabel(A,Q)}sendFeedbackReport(A){return this.widget.sendFeedbackReport(A)}createPluginModeCommands(){let A=this;return this.pluginAgentModes.map((Q)=>({id:`pluginMode.use.${Q.key}`,noun:"mode",verb:`use ${Q.label}`,description:Q.description??`Enable ${Q.label} mode`,get status(){if(A.widget.threadContext)return{type:"hidden"};if(Q.key===A.selectedPluginAgentMode?.key)return{type:"disabled",reason:`Already using ${Q.label} mode`};return{type:"enabled"}},run:($,B,E)=>{A.setPluginAgentMode(Q),E()}}))}registerCommands(){let A=sB.of(this.context),Q=new Set(BY(void 0,{isInternalUser:this.appContext.isInternalUser}).map(({mode:E})=>E)),B=[...jU6.filter(({mode:E})=>Q.has(E)).map(({command:E})=>E.bind(this)),...this.createPluginModeCommands(),...hU6.map((E)=>E.bind(this))].map((E)=>A.register(E));return()=>{for(let E of B)E()}}currentCommandAgentMode(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.agentMode;return this.widget.threadContext?.observer.agentMode??this.agentMode}currentThreadSettings(){return this.widget.threadContext?.observer.threadSettings().getValue()??this.widget.draftThreadSettings}currentCommandSpeedModel(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.selectedPluginAgentMode.agent.model;return T6(this.currentCommandAgentMode())?.primaryModel}currentCommandModeLabel(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.selectedPluginAgentMode.label;return this.currentCommandAgentMode()}currentSpeedSettingKey(){let A=this.currentCommandSpeedModel();return A?Y50(A):void 0}speedCostMultiplierLabel(){let A=this.currentCommandSpeedModel();return A?qy0(A):void 0}isFastSpeedEnabled(){let A=this.currentSpeedSettingKey();return A!==void 0&&this.currentThreadSettings()[A]==="fast"}speedToggleCommandStatus(){if(this.currentSpeedSettingKey()===void 0)return{type:"hidden"};return{type:"enabled"}}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let $=Q.observer.threadSettings().getValue()??{},B=A($);return Q.client.sendClientUpdateThreadSettings(B).catch((E)=>{S.warn("Failed to update thread settings",{error:E})}),this.widget.updateDraftThreadSettings(()=>B),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){return this.setSpeed(this.isFastSpeedEnabled()?"normal":"fast")}setSpeed(A){let Q=this.currentSpeedSettingKey();if(Q===void 0)return"ignored";let $=A==="normal"?"standard":"fast",B=this.updateThreadSettings((E)=>{return{...E,[Q]:$}});if(!(this.selectedPluginAgentMode&&!this.widget.threadContext))this.rememberSpeedForMode(this.currentCommandAgentMode(),$);if(A==="fast")this.showFastModeToast();return B}showFastModeToast(){let A=DQ.maybeOf(this.context);if(!A)return;if(this.fastModeToastID!==null)A.dismiss(this.fastModeToastID);let Q=this.currentCommandModeLabel(),$=this.speedCostMultiplierLabel()??"2.5x";this.fastModeToastID=A.show(`↯${Q} costs ${$} the standard rate for this mode`,"warning",qU6)}dismissFastModeToast(){if(this.fastModeToastID===null)return;DQ.maybeOf(this.context)?.dismiss(this.fastModeToastID),this.fastModeToastID=null}toggleWorkDetails(){return this.expansion.toggle(!1),"handled"}rememberReasoningEffortForMode(A,Q){let $=MQ.of(this.context);$.lastReasoningEffortByMode={...$.lastReasoningEffortByMode??{},[A]:Q}}rememberSpeedForMode(A,Q){let $=MQ.of(this.context);$.lastSpeedByMode={...$.lastSpeedByMode??{},[A]:Q}}applyStickySpeedForMode(A,Q){let $=oN(Q),B=Z50(MQ.of(this.context),Q);if($===void 0||B===void 0)return A;return{...A,[$]:B}}toggleReasoningEffort(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return"ignored";let A=this.currentCommandAgentMode(),Q=dC(A);if(!Q)return"ignored";return this.updateThreadSettings(($)=>{let B=wy0(A,$,this.configSettingsForReasoning),E=qhA(Q,B);return this.rememberReasoningEffortForMode(A,E),{...$,"reasoning.effort":E}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,NU6.cwd()),this.resetHistory()};handleEditorUploadLockChange=(A)=>{if(this.isEditorUploadLocked===A)return;this.setState(()=>{this.isEditorUploadLocked=A})};resetHistory(){this.widget.history.reset()}setAgentMode=(A)=>{if(this.widget.threadContext)return;if(A!==this.agentMode)this.dismissFastModeToast();this.setState(()=>{this.agentMode=A,this.selectedPluginAgentMode=null,this.desiredPluginAgentModeKey=null}),this.widget.updateDraftThreadSettings((Q)=>{let $=Hy0(MQ.of(this.context),A),B={...Q};delete B["reasoning.effort"];let E=$??wy0(A,B,this.configSettingsForReasoning);if(E===void 0){let D={...Q};return delete D["reasoning.effort"],this.applyStickySpeedForMode(D,A)}return this.applyStickySpeedForMode({...Q,"reasoning.effort":E},A)})};setPluginAgentMode=(A)=>{if(this.widget.threadContext)return;this.dismissFastModeToast(),this.setState(()=>{this.selectedPluginAgentMode=A,this.desiredPluginAgentModeKey=A?.key??null})};toggleAgentMode(){let A=BY(void 0,{isInternalUser:this.appContext.isInternalUser});if(this.selectedPluginAgentMode){let $=this.pluginAgentModes.findIndex((E)=>E.key===this.selectedPluginAgentMode?.key),B=$===-1?void 0:this.pluginAgentModes[$+1];if(B)return this.setPluginAgentMode(B),"handled";return this.setPluginAgentMode(null),this.setAgentMode(A[0]?.mode??this.agentMode),"handled"}let Q=whA(this.agentMode,A);if(Q===A[0]?.mode&&this.pluginAgentModes.length>0)return this.setPluginAgentMode(this.pluginAgentModes[0]??null),"handled";return this.setAgentMode(Q),"handled"}buildActions(){let A=new cA((B)=>{return this.setAgentMode(B.mode),"handled"}),Q=new cA(()=>{return this.toggleReasoningEffort()}),$=new cA(()=>{return this.toggleWorkDetails()});return new Map([[qh0,A],[jq,Q],[P70,$]])}build(A){let Q=this.widget.threadContext,$=MQ.of(A),B=bL4(this.selectedPluginAgentMode?.color),E=LU6($.workspaceRoot,this.currentGitBranch),J=[Q?new Vc0({editorController:this.widget.editorController,editorFocusNode:this.widget.editorFocusNode,copyOnSelectEnabled:this.copyOnSelectEnabled,observingClient:{client:Q.client,observer:Q.observer,agentModeDisplay:Q.agentModeDisplay},hints:this.widget.hints,ideStatus:this.widget.ideStatus,statusItems:this.widget.statusItems,pluginConfirmationBlocked:this.widget.pluginConfirmationBlocked,onPromptSubmitted:this.onPromptSubmitted,onEditorUploadLockChange:this.handleEditorUploadLockChange,editorUploadLocked:this.isEditorUploadLocked,notificationService:this.widget.notificationService??wU6,environmentFallback:this.useLocalEnvironmentFallbackForActiveThread?E:null}):new Sc0({agentMode:this.agentMode,pluginAgentModes:this.pluginAgentModes,selectedPluginAgentMode:this.selectedPluginAgentMode,agentModeLabel:this.selectedPluginAgentMode?.label,pluginAgentModeURI:this.selectedPluginAgentMode?.sourceURI,agentModeColor:uU6(this.selectedPluginAgentMode?.color),splashPrimaryColor:B?MU6(B):void 0,splashSecondaryColor:B,threadSettings:this.widget.draftThreadSettings,configSettings:this.configSettingsForReasoning,editorController:this.widget.editorController,editorFocusNode:this.widget.editorFocusNode,visibility:null,onNewThread:this.widget.onNewThread,onAgentModeChange:this.setAgentMode,onPluginAgentModeChange:this.setPluginAgentMode,onEditorUploadLockChange:this.handleEditorUploadLockChange,editorUploadLocked:this.isEditorUploadLocked,previousThreadIDForReference:this.previousThreadIDForReference,hints:this.widget.hints,ideStatus:this.widget.ideStatus,statusItems:this.widget.statusItems,configService:this.widget.configService,environment:E,notice:this.widget.notice??null,onDismissNotice:this.widget.onDismissNotice??(()=>{}),statusMessage:this.statusMessage})],U=new Map([[wA.alt("t"),new P70]]);return new N4({actions:this.buildActions(),child:new rQ({debugLabel:"ThreadShortcuts",shortcuts:U,child:new TT({history:this.isEditorUploadLocked?void 0:this.widget.history,child:new z9({controller:this.expansion,child:new t1({children:J})})})})})}subscribeToConfigSettings(){this.configSubscription?.unsubscribe(),this.configSubscription=this.widget.configService.config.subscribe((A)=>{let Q=A.settings["terminal.copyOnSelect"]??!0;this.expansion.setDefaultExpanded(A.settings["terminal.detailsExpandedByDefault"]??!1);let $=A.settings["internal.model"],B=this.configSettingsForReasoning["internal.model"]!==$;if($===void 0)this.configSettingsForReasoning={};else this.configSettingsForReasoning={"internal.model":$};if(this.copyOnSelectEnabled===Q&&!B)return;if(this.copyOnSelectEnabled=Q,this.mounted)this.setState()})}}i0();f8();E4();class sX extends G4{direction;constructor(A){super();this.direction=A}}class p90 extends G4{}class Ji extends G4{}class l90 extends G4{index;constructor(A){super();this.index=A}}function hc0(A){return A.length+2}class gc0 extends d0{props;constructor(A){super();this.props=A}createState(){return new gL4}}class gL4 extends m0{selectedIndex=0;initState(){super.initState(),this.selectedIndex=this.findSelectableIndex(this.widget.props.initialSelectedIndex??0)}didUpdateWidget(A){this.selectedIndex=this.findSelectableIndex(this.selectedIndex)}isSelectable(A){let Q=this.widget.props.entries[A];return Q?.type==="item"&&(Q.enabled??!0)}findSelectableIndex(A){let{entries:Q}=this.widget.props;if(Q.length===0)return 0;let $=Math.max(0,Math.min(A,Q.length-1));if(this.isSelectable($))return $;for(let B=1;B<Q.length;B++){let E=$+B;if(E<Q.length&&this.isSelectable(E))return E;let D=$-B;if(D>=0&&this.isSelectable(D))return D}return 0}moveSelection(A){let Q=this.findNextSelectableIndex(A);if(Q===this.selectedIndex)return;this.setState(()=>{this.selectedIndex=Q})}findNextSelectableIndex(A){let{entries:Q}=this.widget.props;for(let $=this.selectedIndex+A;$>=0&&$<Q.length;$+=A)if(this.isSelectable($))return $;return this.selectedIndex}acceptIndex(A){let Q=this.widget.props.entries[A];if(Q?.type!=="item"||!(Q.enabled??!0))return;this.setState(()=>{this.selectedIndex=A}),this.widget.props.onAccept(Q.value)}invoke=(A)=>{if(A instanceof sX)return this.moveSelection(A.direction),"handled";if(A instanceof p90)return this.acceptIndex(this.selectedIndex),"handled";if(A instanceof Ji)return this.widget.props.onDismiss(),"handled";if(A instanceof l90)return this.acceptIndex(A.index),"handled";return"ignored"};buildShortcuts(){let A=new Map([[wA.key("ArrowDown"),new sX(1)],[wA.key("j"),new sX(1)],[wA.ctrl("n"),new sX(1)],[wA.key("ArrowUp"),new sX(-1)],[wA.key("k"),new sX(-1)],[wA.ctrl("p"),new sX(-1)],[wA.key("Enter"),new p90],[wA.key("Escape"),new Ji],[wA.ctrl("."),new Ji]]);return this.widget.props.entries.forEach((Q,$)=>{if(Q.type==="item"&&Q.shortcut)A.set(Q.shortcut,new l90($))}),A}buildActions(){return new Map([[sX,new cA(this.invoke)],[p90,new cA(this.invoke)],[Ji,new cA(this.invoke)],[l90,new cA(this.invoke)]])}build(A){let Q=e0.of(A),$=gU6(this.widget.props.entries,X4.of(A).supportsEmojiWidth);return new GA({width:this.widget.props.width,height:hc0(this.widget.props.entries),decoration:new u1(Q.colors.background,U1.all(new Y1(Q.colors.border,1,"solid"))),child:new N4({actions:this.buildActions(),child:new rQ({debugLabel:"ContextPickerShortcuts",shortcuts:this.buildShortcuts(),child:new VQ({autofocus:!0,debugLabel:"ContextPicker",child:new UA({mainAxisSize:"min",crossAxisAlignment:"stretch",children:this.widget.props.entries.map((B,E)=>this.buildEntry(B,E,$,Q))})})})})})}buildEntry(A,Q,$,B){if(A.type==="separator")return new GA({height:1,decoration:{border:new U1(new Y1(B.colors.border,1,"solid"))}});let E=Q===this.selectedIndex,D=A.enabled??!0,J=new A0({color:E?B.app.selectionForeground:B.colors.foreground,dim:!D}),U=new A0({color:E?B.app.selectionForeground:B.app.keybind,bold:!0,dim:!D});return new iA({onClick:()=>this.acceptIndex(Q),child:new GA({padding:c0.symmetric(1,0),decoration:E?new u1(B.app.selectionBackground):void 0,child:new OA({crossAxisAlignment:"start",children:[new P4({child:new D0({text:new g(A.label,J),maxLines:1,overflow:"ellipsis"})}),new y0({width:1}),new y0({width:$,child:new D0({text:new g(mL4(A),U),textAlign:"right",maxLines:1,overflow:"ellipsis"})})]})})})}}function gU6(A,Q){return A.reduce(($,B)=>{return B.type==="item"?Math.max($,RA(mL4(B),Q)):$},0)}function mL4(A){return A.shortcutLabel??A.shortcut?.toString().toLowerCase()??""}var mU6=36,dU6=24,cU6=72;class dL4 extends d0{child;onContext;constructor(A,Q){super();this.child=A;this.onContext=Q}createState(){return new cL4}}class cL4 extends m0{build(A){return this.widget.onContext(A),this.widget.child}}function pU6(A){return A.reduce((Q,$)=>Math.max(Q,RA(_T($.description.timeAgo))),0)}function pL4(A){return Math.max(dU6,Math.min(A,cU6))}class mc0 extends G4{}class dc0 extends G4{}class cc0 extends G4{}var lU6=O4("thread.toggleSidebar",{noun:"thread",verb:"toggle sidebar",description:"Show or hide the thread sidebar",defaultKey:"alt+s",status:{type:"enabled"}},(A,{dismiss:Q})=>{Q(),A.toggleVisibility()});class pc0{options;focusScopeNode=new a7({debugLabel:"ThreadListSidebar"});initialized=!1;visible=!1;hasRenderedSidebar=!1;width=mU6;pickerController=new gp;constructor(A){this.options=A}isVisible(){return this.ensureInitialized(),this.visible}visibleWidth(){return this.isVisible()?this.width:0}buildBody(A){return new OA({crossAxisAlignment:"stretch",children:[this.buildSlot(),new P4({child:A})]})}buildSlot(){let A=this.isVisible();if(!this.hasRenderedSidebar)return new y0({width:0});let Q={activeThreadID:this.options.getActiveThreadID(),currentWorkspaceURI:U4(g0.file(this.options.getWorkspaceRoot())),width:this.width,loadThreads:this.options.loadThreads,pickerController:this.pickerController,archiveThread:this.options.archiveThread,onSelectThread:this.options.onSelectThread,onDismiss:this.close,onResizeWidth:this.resize};if(this.options.observeThreadSummaries)Q.observeThreadSummaries=this.options.observeThreadSummaries;return new y0({width:A?this.width:0,child:new E6({focusScopeNode:this.focusScopeNode,debugLabel:"ThreadListSidebar",onFocusChange:this.handleFocusChange,child:new lL4(Q)})})}commands(){return[lU6.bind({toggleVisibility:this.toggleVisibility})]}shortcutEntries(){return[[wA.alt("s"),new v70]]}actionEntries(){return[[v70,new cA(()=>this.toggleFromShortcut())]]}toggleFromShortcut=()=>{if(this.isVisible()){if(this.focusScopeNode.hasFocus)return this.close(),"handled";if(this.options.isBlocked())return"ignored";return this.pickerController.requestFocus(),"handled"}if(this.options.isBlocked())return"ignored";return this.pickerController.requestFocus(),this.setVisible(!0),"handled"};toggleVisibility=()=>{if(this.isVisible()){this.close();return}if(this.options.isBlocked())return;this.pickerController.requestFocus(),this.setVisible(!0)};close=()=>{this.options.focusMainContent(),this.setVisible(!1)};setVisible(A){if(this.ensureInitialized(),this.visible===A)return;if(A)this.hasRenderedSidebar=!0;this.options.state.setState(()=>{this.visible=A}),eD((Q)=>({...Q,threadListSidebarVisible:A})).catch((Q)=>{S.warn("Failed to save thread sidebar visibility state",{error:Q instanceof Error?Q.message:String(Q)})})}ensureInitialized(){if(this.initialized)return;this.initialized=!0,this.visible=this.options.getInitialVisible(),this.hasRenderedSidebar=this.visible}handleFocusChange=(A)=>{this.options.state.setState()};dispose(){this.focusScopeNode.dispose()}resize=(A)=>{let Q=pL4(A);if(Q===this.width)return;this.options.state.setState(()=>{this.width=Q})}}class lL4 extends d0{props;constructor(A){super();this.props=A}createState(){return new iL4}}class iL4 extends m0{threads=[];isLoading=!0;isSwitchingThread=!1;hasError=!1;filterByWorkspace=!0;contextMenu=null;pendingThreadMutations=new Map;canonicalThreadSummariesByID=new Map;archivedCanonicalThreadIDs=new Set;liveThreadIDsObservedInCurrentWorkspace=new Set;liveThreadSummaries=null;resizeSession=null;isResizeHandleHovered=!1;threadItemContexts=new Map;threadSummarySubscription=null;observedThreadSummaries;shortcuts=new Map([[wA.alt("w"),new mc0],[wA.ctrl("."),new dc0],[wA.key("e"),new cc0]]);actions=new Map([[mc0,new cA(()=>{return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.contextMenu=null}),"handled"})],[dc0,new cA(()=>this.openContextMenu())],[cc0,new cA(()=>this.archiveSelectedThread())]]);get isBusy(){return this.isLoading}get isResizeActive(){return this.resizeSession!==null||this.isResizeHandleHovered}didUpdateWidget(A){if(super.didUpdateWidget(A),this.contextMenu&&(A.props.width!==this.widget.props.width||A.props.currentWorkspaceURI!==this.widget.props.currentWorkspaceURI))this.contextMenu=null;if(A.props.observeThreadSummaries!==this.widget.props.observeThreadSummaries)this.startThreadSummaryUpdates();if(A.props.activeThreadID!==this.widget.props.activeThreadID)this.rememberActiveLiveThreadInCurrentWorkspace()}initState(){super.initState(),this.startThreadSummaryUpdates()}dispose(){this.threadSummarySubscription?.unsubscribe(),this.threadSummarySubscription=null,super.dispose()}startThreadSummaryUpdates(){this.threadSummarySubscription?.unsubscribe(),this.threadSummarySubscription=null,this.liveThreadSummaries=null,this.observedThreadSummaries=this.widget.props.observeThreadSummaries;let A=this.widget.props.observeThreadSummaries;if(!A){this.loadThreadSummaries();return}let Q=A();if(!Q){this.loadThreadSummaries();return}this.loadThreadSummaries(),this.threadSummarySubscription=Q.subscribe({next:($)=>this.applyLiveThreadSummaries($),error:($)=>{if(S.error("Failed to observe threads for Neo sidebar",{error:$}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}})}async loadThreadSummaries(){let A=this.observedThreadSummaries;try{let Q=await this.widget.props.loadThreads(),$=tl(Q);if(!this.mounted||A!==this.observedThreadSummaries)return;this.archivedCanonicalThreadIDs.clear();for(let B of Q)if(B.archived)this.archivedCanonicalThreadIDs.add(B.id);this.applyCanonicalThreadSummaries($)}catch(Q){if(S.error("Failed to load threads for Neo sidebar",{error:Q}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}applyCanonicalThreadSummaries(A){this.canonicalThreadSummariesByID.clear();for(let Q of A)this.canonicalThreadSummariesByID.set(Q.id,Q);this.applyThreadSummaries(this.liveThreadSummaries?this.mergeLiveMetadata():A)}applyLiveThreadSummaries(A){this.liveThreadSummaries=A,this.rememberActiveLiveThreadInCurrentWorkspace();let Q=this.mergeLiveMetadata();if(Q.length===0&&this.canonicalThreadSummariesByID.size===0&&this.isLoading)return;this.applyThreadSummaries(Q)}rememberActiveLiveThreadInCurrentWorkspace(){let A=this.widget.props.activeThreadID;if(A&&this.liveThreadSummaries?.some((Q)=>Q.id===A&&Q.updatedAt))this.liveThreadIDsObservedInCurrentWorkspace.add(A)}mergeLiveMetadata(){let A=new Map((this.liveThreadSummaries??[]).map((B)=>[B.id,B])),Q=(this.liveThreadSummaries??[]).flatMap((B)=>{if(this.archivedCanonicalThreadIDs.has(B.id))return[];let E=this.canonicalThreadSummariesByID.get(B.id);if(!E){if(!B.updatedAt)return[];return[B]}return[this.mergeLiveThreadSummary(E,B)]}),$=Array.from(this.canonicalThreadSummariesByID.values()).filter((B)=>!A.has(B.id));return[...Q,...$]}mergeLiveThreadSummary(A,Q){return{...A,...Q,updatedAt:Q.updatedAt??A.updatedAt,description:Q.updatedAt?Q.description:A.description,workspaceURI:A.workspaceURI,relationships:A.relationships,diffStats:A.diffStats,agentMode:A.agentMode,details:A.details,archived:A.archived}}applyThreadSummaries(A){if(!this.mounted)return;this.setState(()=>{let Q=rK(A).flat(),$=this.widget.props.pickerController.selectedItem?.id??this.widget.props.activeThreadID;this.widget.props.pickerController.selectedItem=Q.find((B)=>B.id===$)??Q.find((B)=>B.id===this.widget.props.activeThreadID)??null,this.threads=Q,this.isLoading=!1,this.hasError=!1})}handleSelectThread=async(A)=>{if(this.isSwitchingThread)return;this.setState(()=>{this.isSwitchingThread=!0});try{await this.widget.props.onSelectThread(A)}catch(Q){S.error("Failed to switch thread from Neo sidebar",{error:Q,threadID:A})}finally{if(this.mounted)this.setState(()=>{this.isSwitchingThread=!1})}};getOptimisticThreads(){return this.threads.flatMap((A)=>{if(this.pendingThreadMutations.get(A.id)?.kind==="archive")return[];return[A]})}getThreadsForDisplay(){let A=this.getOptimisticThreads();return this.filterByWorkspace?A.filter((Q)=>this.threadMatchesCurrentWorkspace(Q)):A}threadMatchesCurrentWorkspace(A){if(A.workspaceURI)return A.workspaceURI===this.widget.props.currentWorkspaceURI;return this.canonicalThreadSummariesByID.has(A.id)||this.liveThreadIDsObservedInCurrentWorkspace.has(A.id)||A.id===this.widget.props.activeThreadID}buildContextMenuEntries(){return[{type:"item",value:"archive",label:"Archive Thread",shortcut:wA.key("a"),shortcutLabel:"a"},{type:"separator"},{type:"item",value:"copy-id",label:"Copy ID",shortcut:wA.ctrl("c"),shortcutLabel:"ctrl+c"},{type:"item",value:"copy-url",label:"Copy URL",shortcut:new wA("c",{shift:!0,ctrl:!0}),shortcutLabel:"shift+ctrl+c"}]}openContextMenu(){let A=this.widget.props.pickerController.selectedItem;if(!A||this.isBusy||this.isSwitchingThread||this.hasError)return"ignored";let Q=this.buildContextMenuEntries(),$=hc0(Q),B=this.getContextMenuWidth(),E=this.getContextMenuPosition(A.id,$,B);return this.setState(()=>{this.contextMenu={threadID:A.id,left:E.left,top:E.top,width:B,height:$}}),"handled"}archiveSelectedThread(){let A=this.widget.props.pickerController.selectedItem?.id;if(!A||this.contextMenu||this.isBusy||this.isSwitchingThread||this.hasError)return"ignored";return this.archiveThread(A),"handled"}getContextMenuWidth(){let A=Math.max(24,this.widget.props.width-3);return Math.max(1,Math.min(A,this.widget.props.width-2))}getContextMenuPosition(A,Q,$){let B=Math.max(0,Math.min(2,this.widget.props.width-$)),E=1,D=this.threadItemContexts.get(A)?.findRenderObject(),J=this.context.findRenderObject();if(!(D instanceof bA)||!(J instanceof bA))return{left:B,top:1};let U=D.localToGlobal({x:0,y:0}),Y=J.localToGlobal({x:0,y:0}),Z=U.y-Y.y,F=Z+D.size.height,X=X4.sizeOf(this.context).height,I=Math.max(1,Math.min(J.size.height,X-Y.y)),K=I-F>=Q||Z<I/2?F:Z-Q,z=Math.max(0,I-Q);return{left:B,top:Math.max(0,Math.min(K,z))}}closeContextMenu=()=>{if(!this.contextMenu)return;this.setState(()=>{this.contextMenu=null})};handleContextMenuAccept=(A)=>{let Q=this.contextMenu?.threadID;if(!Q)return;if(this.closeContextMenu(),A==="archive"){this.archiveThread(Q);return}if(A==="copy-id"){N4.maybeInvoke(this.context,new IB(Q,"Thread ID copied to clipboard","Failed to copy thread ID"));return}N4.maybeInvoke(this.context,new IB(this.getThreadURL(Q),"Thread URL copied to clipboard","Failed to copy thread URL"))};beginOptimisticArchive(A){if(this.pendingThreadMutations.has(A))return!1;if(!this.threads.some(($)=>$.id===A))return!1;let Q={kind:"archive",fallbackSelectedThreadID:null};return this.setState(()=>{this.pendingThreadMutations.set(A,Q)}),cQ.instance.addPostFrameCallback(()=>{if(!this.mounted)return;let $=this.pendingThreadMutations.get(A);if($?.kind!=="archive")return;$.fallbackSelectedThreadID=this.widget.props.pickerController.selectedItem?.id??null}),!0}commitOptimisticArchive(A){if(this.pendingThreadMutations.get(A)?.kind!=="archive")return;this.pendingThreadMutations.delete(A),this.canonicalThreadSummariesByID.delete(A),this.threads=this.threads.filter(($)=>$.id!==A)}rollbackOptimisticArchive(A){let Q=this.pendingThreadMutations.get(A);if(Q?.kind!=="archive")return;let $=this.threads.find((B)=>B.id===A);if(!$){this.pendingThreadMutations.delete(A);return}this.setState(()=>{this.pendingThreadMutations.delete(A);let B=this.widget.props.pickerController.selectedItem?.id??null;if(B===null||B===Q.fallbackSelectedThreadID)this.widget.props.pickerController.selectedItem=$})}async archiveThread(A){let Q=DQ.maybeOf(this.context);if(!this.beginOptimisticArchive(A))return;try{let $=await this.widget.props.archiveThread(A);if(!this.mounted)return;if($){this.rollbackOptimisticArchive(A),Q?.show($.message,"error");return}this.commitOptimisticArchive(A),Q?.show("Archived thread")}catch($){if(S.error("Failed to archive thread from Neo sidebar context menu",{error:$,threadID:A}),!this.mounted)return;this.rollbackOptimisticArchive(A),Q?.show("Failed to archive thread","error")}}getThreadURL(A){return hG(new URL(MQ.of(this.context).ampURL),A).toString()}buildContextMenuOverlay(){let A=this.contextMenu;if(!A||!this.getThreadsForDisplay().some((Q)=>Q.id===A.threadID))return null;return new m1({left:A.left,top:A.top,width:A.width,height:A.height,child:new E6({debugLabel:"ThreadListSidebarContextMenu",onFocusChange:(Q)=>{if(!Q)this.closeContextMenu()},child:new gc0({entries:this.buildContextMenuEntries(),width:A.width,onAccept:this.handleContextMenuAccept,onDismiss:this.closeContextMenu})})})}buildContextMenuBackdrop(){return new m1({left:0,top:0,right:0,bottom:0,child:new iA({onClick:()=>this.closeContextMenu(),child:y0.expand()})})}buildThreadItem(A,Q,$,B,E){let D=e0.of(E),{app:J,colors:U}=D,Y=A.id===this.widget.props.activeThreadID,Z=!Q&&!Y,F=Q?J.selectionForeground:U.foreground,X=Q?J.selectionForeground:U.mutedForeground,G=R90(A.agentState)?new oX({color:Q?J.selectionForeground:U.primary}):void 0,V=_T(A.description.timeAgo),K=new GA({padding:c0.symmetric(1,0),child:new OA({children:[new y0({width:2,child:G}),new P4({child:new D0({text:new g(A.title,new A0({color:F,dim:Z})),overflow:"ellipsis",maxLines:1})}),new y0({width:2}),new y0({width:$,child:OA.end([new D0({text:new g(V,new A0({color:X,dim:Z}))})])})]})}),z=B?new UA({children:[this.buildInactiveSeparator(E),K],crossAxisAlignment:"stretch"}):K;return new dL4(z,(W)=>{this.threadItemContexts.set(A.id,W)})}buildInactiveSeparator(A){let Q=e0.of(A).colors;return new GA({padding:c0.only({left:2,right:1,top:1}),child:new D0({text:new g("──── Inactive in last 24h ────",new A0({color:Q.mutedForeground,dim:!0})),overflow:"ellipsis",maxLines:1})})}handleResizeHandlePress=(A)=>{if(A.button!=="left")return;this.setState(()=>{this.resizeSession={baseWidthColumns:this.widget.props.width,startColumn:Math.floor(A.position.x)}})};handleResizeHandleDrag=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;let Q=Math.floor(A.position.x)-this.resizeSession.startColumn,$=pL4(this.resizeSession.baseWidthColumns+Q);if($!==this.widget.props.width)this.widget.props.onResizeWidth($)};handleResizeHandleRelease=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;this.setState(()=>{this.resizeSession=null})};handleResizeHandleEnter=()=>{if(this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!0})};handleResizeHandleExit=()=>{if(!this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!1})};buildResizeHandle(){return new m1({top:0,right:0,bottom:0,width:1,child:new iA({cursor:o1.EW_RESIZE,onClick:this.handleResizeHandlePress,onDrag:this.handleResizeHandleDrag,onRelease:this.handleResizeHandleRelease,onEnter:this.handleResizeHandleEnter,onExit:this.handleResizeHandleExit,child:new y0({width:1})})})}build(A){let Q=e0.of(A),$=this.getThreadsForDisplay(),B=this.hasError?[]:$,E=pU6(B),D=rK(B)[1]?.[0]?.id;this.threadItemContexts.clear();let J=this.isResizeActive?2:1,U=new U1(void 0,new Y1(Q.colors.border,J),void 0,void 0),Y=this.buildContextMenuOverlay(),Z=[new GA({decoration:new u1(Q.colors.background,U),child:new N4({actions:this.actions,child:new rQ({shortcuts:this.shortcuts,debugLabel:"ThreadListSidebarFilter",child:new j5({items:B,getLabel:(F)=>`${F.title} ${F.id}`,controller:this.widget.props.pickerController,autofocus:!1,acceptOnClick:!0,onAccept:(F)=>void this.handleSelectThread(F.id),renderItem:(F,X,I,G)=>this.buildThreadItem(F,X,E,F.id===D,G),enabled:!this.isBusy,isLoading:this.isBusy,hidePrompt:!0,loadingText:"Loading threads...",emptyStateText:this.hasError?"Failed to load threads":void 0,emptyStateWidget:this.hasError?void 0:(F)=>yd0(F,this.filterByWorkspace),maxRenderItems:200,showBorder:!1})})})}),this.buildResizeHandle()];if(Y)Z.push(this.buildContextMenuBackdrop()),Z.push(Y);return new GA({width:this.widget.props.width,child:new t1({fit:"expand",children:Z})})}}E3();class lc0 extends d0{toolboxes;onDismiss;constructor(A){super();this.toolboxes=A.toolboxes,this.onDismiss=A.onDismiss}createState(){return new aL4}}class aL4 extends m0{toolboxes=new p3(this,[]);initState(){this.toolboxes.subscribe(this.widget.toolboxes)}didUpdateWidget(A){if(A.toolboxes!==this.widget.toolboxes)this.toolboxes.subscribe(this.widget.toolboxes)}build(A){return new oL4({toolboxes:this.toolboxes.getValue(),onDismiss:this.widget.onDismiss})}}class oL4 extends d0{toolboxes;onDismiss;constructor(A){super();this.toolboxes=A.toolboxes,this.onDismiss=A.onDismiss}createState(){return new rL4}}class rL4 extends m0{scrollController=new a6;canScroll=!1;initState(){this.scrollController.followMode=!1,this.scrollController.jumpTo(0),this.scrollController.addListener(this.updateCanScroll)}dispose(){this.scrollController.removeListener(this.updateCanScroll),this.scrollController.dispose()}updateCanScroll=()=>{let A=this.scrollController.maxScrollExtent>0;if(A===this.canScroll)return;this.setState(()=>{this.canScroll=A})};build(A){return new E1({header:"Toolboxes",onDismiss:this.widget.onDismiss,minWidth:80,maxWidth:120,maxHeight:40,autofocus:!1,footer:iU6(this.canScroll),child:new vB({controller:this.scrollController,child:nU6(A,this.widget.toolboxes)})})}}function iU6(A){let Q=[{keys:["Esc"],label:"close"}];if(A)Q.push({keys:["↑↓","j/k"],label:"scroll"});return Q}function nU6(A,Q){let $=aU6(A,Q);return new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new D0({text:new g("",void 0,$),selectable:!0})]})}function aU6(A,Q){let $=e0.of(A),{colors:B}=$,E=new A0({color:B.foreground,dim:!0}),D=new A0({color:B.foreground,bold:!0});if(Q.length===0)return[new g("No toolboxes found.",E)];let J=[];for(let U of Q){let Y=U.tools.length,Z=U.tools.filter((F)=>F.status==="registered").length;if(U.discovering){let F=U.tools.filter((X)=>X.status!=="pending").length;J.push(new g(U.path,D)),J.push(new g(` discovering ${F}/${Y}...
2908
2908
  `,E))}else if(J.push(new g(U.path,D)),Y>0)J.push(new g(` ${Z}/${Y} ${z1(Y,"tool")}
2909
2909
  `,E));else J.push(new g(`
2910
2910
  `));if(U.tools.length===0)J.push(new g(` └─ No tools available
2911
2911
  `,E));else for(let F of U.tools)oU6(J,F,$);J.push(new g(`
2912
2912
  `))}return J}function oU6(A,Q,$){let{colors:B,app:E}=$,D=rU6(Q.status,$);if(A.push(new g(` ${D.icon} `,new A0({color:D.color}))),A.push(new g(Q.name,new A0({color:Q.status==="pending"?B.warning:E.command}))),Q.status==="pending")A.push(new g(" discovering...",new A0({color:B.foreground,dim:!0})));else if(Q.description)A.push(new g(` ${nL4(Q.description,50)}`,new A0({color:B.foreground,dim:!0})));if(Q.error)A.push(new g(` ${nL4(Q.error,40)}`,new A0({color:E.toolError})));A.push(new g(`
2913
- `))}function rU6(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function nL4(A,Q){let $=A.replace(/\s+/g," ").trim();if(RA($)<=Q)return $;let B="...",E=RA(B);if(Q<=E)return o7(B,Q);return`${o7($,Q-E,!0,"")}${B}`}var ac0="https://ampcode.com/news/neo",oc0=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:ac0,href:ac0}]}];function sU6(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:ac0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function tU6(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var fT=50,aq=40,ic0=1000,eU6=420,AY6=760,QY6=-250,$Y6=1100,i90=33,sL4=0.999,BY6=2.1,EY6=720,DY6=420,Dj4="Meet the new",Jj4="Amp",Uj4="CLI",rc0=Q4(Dj4).length,JY6=Q4(Jj4).length,UY6=Q4(Uj4).length,n90={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},tL4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},eL4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},Aj4=[n90,tL4,eL4,n90,tL4,eL4,n90],YY6=n90;class sc0 extends d0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??tU6(),this.introStages=this.variant==="npm-migration"?sU6(this.binaryInstallCommand):oc0,this.dismissible=this.variant!=="npm-migration"}createState(){return new Yj4}}class Yj4 extends m0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=ic0;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new P5(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=LE(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=sL4,this.firstStageHintVisible=this.animationProgress>=sL4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:ic0,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=LE(A/AY6);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},i90)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=LE($/eU6);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},i90)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let E=performance.now()-this.startedAt,D=LE(E/this.animationDurationMs),J=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*xT(D);if(this.setState(()=>{this.animationProgress=J}),D>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},i90)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,ic0+QY6),Q=A+$Y6;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?LE((A-this.firstStageTitleRevealStartedAt)/EY6):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?LE((A-this.firstStageHintRevealStartedAt)/DY6):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},i90)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=Qj4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:$j4(Qj4(this.previousIntroStage),A,xT(this.stageTransitionProgress));return this.dismissProgress>0?$j4(Q,YY6,xT(this.dismissProgress)):Q}build(A){let Q=S4.of(A).colorScheme,$=e0.of(A),B=this.currentOrbPalette(),E=e7(1,"deep",B),D=X4.of(A).size,U=this.widget.animationProgress??this.animationProgress,Y=Math.max(D.width/fT,D.height/aq)*BY6,Z=Y+(1-Y)*U,F=xT(this.dismissProgress),X=Math.max(fT,Math.round(fT*Z)),I=Math.max(aq,Math.round(aq*Z)),G=Math.round((D.width-X)/2),V=Math.round((D.height-I)/2),K=Math.max(0,Math.floor((D.width-fT)/2)),z=-Math.floor(aq/2),W=Math.round(G+(K-G)*U),C=Math.round(V+(z-V)*U),H=W+X/2,N=C+I/2,w=ZY6({dismissProgress:this.dismissProgress,easedDismissProgress:F,introOrbScale:Z,normalOrbCenterX:H,normalOrbCenterY:N,size:D}),u=Math.max(fT,Math.round(fT*w.orbScale)),L=Math.max(aq,Math.round(aq*w.orbScale)),R=w.orbCenterX,_=w.orbCenterY,P=Math.round(R-u/2),f=Math.round(_-L/2),h=Math.max(3,Math.min(D.height-5,Math.floor(aq/2)+2)),x=Math.max(h+3,D.height-3),v=w.textDissolveProgress,k=this.isFinalIntroStage()?w.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&v<1,d=c&&this.firstStageHintVisible,b=d&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,a=Math.max(24,Math.min(74,D.width-4)),X0=Math.min(12,Math.max(8,D.height-h-6)),t=Math.max(0,Math.floor((D.width-a)/2)),Z0=Math.max(0,Math.min(D.height-X0,Math.floor(D.height*0.55-X0/2))),R0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new bK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new bK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new E6({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(B0)=>{if(B0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&B0.key==="c"&&B0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&B0.key==="q")return this.widget.onQuit?.(),"handled";if((B0.key===" "||B0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(B0.key==="Escape"||B0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(B0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(B0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new t1({fit:"expand",children:[new Zj4({color:Q.background,dissolveProgress:k}),new t1({fit:"expand",children:[new iA({onClick:()=>{},child:y0.expand()}),new m1({left:P,top:f,width:u,height:L,child:R0}),...c?[new m1({left:t,top:Z0,width:a,height:X0,child:XY6({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:a,height:X0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:E,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:v,context:A})})]:[],...d?[...b?[new m1({left:t,top:Math.max(0,x-1),width:a,height:1,child:new D0({text:WY6({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new m1({left:t,top:x,width:a,height:1,child:HY6({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:v,context:A})})]:[]]})]})})}}class Zj4 extends XB{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new Fj4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class Fj4 extends bA{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height),U={bg:this.color},Y=LE(this.dissolveProgress);if(Y<=0){A.fill(B,E,D,J," ",U);return}if(Y>=1)return;for(let Z=0;Z<J;Z++)for(let F=0;F<D;F++)if(!FY6(F,Z,D,J,Y))A.fill(B+F,E+Z,1,1," ",U)}}function LE(A){return Math.min(1,Math.max(0,A))}function xT(A){return 1-(1-A)**3}function Qj4(A){return Aj4[A]??Aj4[0]}function $j4(A,Q,$){return{primary:Mq(A.primary,Q.primary,$),secondary:Mq(A.secondary,Q.secondary,$)}}function ZY6({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:E,size:D}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(D.width*0.54-B)*Q,orbCenterY:E-D.height*0.44*Q,textDissolveProgress:LE(A/0.52),backdropDissolveProgress:xT(LE((A-0.12)/0.88))}}function FY6(A,Q,$,B,E){let D=B<=1?0:Q/(B-1),J=Xj4(A+Q*Math.max(1,$));return(1-D)*0.72+J*0.28<E}function XY6({introStages:A,stage:Q,previousStage:$,progress:B,direction:E,width:D,height:J,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return nc0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let K=xT(B),z=E*Math.round((1-K)*D),W=-E*Math.round(K*D);return new Xq(new t1({fit:"expand",children:[new m1({left:W,top:0,width:D,height:J,child:nc0({introStages:A,stage:$,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new m1({left:z,top:0,width:D,height:J,child:nc0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function nc0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:E,link:D,keybind:J,titleRevealProgress:U,dissolveProgress:Y,context:Z}){let F=A[Q]??A[0]??oc0[0],X=new A0({color:E,bold:!0}),I=new A0({color:$}),G=A===oc0&&Q===0,V=[...F.title===null?[]:[new D0({text:G?a90(VY6({progress:U,foreground:E,pulseColor:E}),Y):new g($8(F.title,Y),X),textAlign:"center"})],...F.body.length>0?[IY6()]:[],...F.body.map((K)=>GY6(K,I,B,D,J,Y,Z))];return new pQ({child:new mA({padding:c0.horizontal(1),child:new UA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function IY6(){return y0.height(1)}function GY6(A,Q,$,B,E,D,J){if(typeof A==="string")return new D0({text:new g($8(A,D),Q),textAlign:"center"});if("codeBlock"in A)return new M5({onCopy:(U,Y)=>{if(Y)DQ.success(J,"Copied to clipboard",2000)},child:new UA({mainAxisSize:"min",children:A.codeBlock.map((U)=>new D0({text:new g($8(U,D),new A0({color:E})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let U=new D0({text:new g("",void 0,[new g($8(A.text,D),new A0({color:$,dim:!0})),new g($8(A.keybind,D,Q4(A.text).length),new A0({color:E}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new pQ({child:new M5({child:U})});return U}if("highlightText"in A){let U=t$.createSpan(A.href,A.linkText,new A0({color:B,underline:!0})),Y=lX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(A.highlightText,new A0({color:E})),new g(A.textAfterHighlight,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{z$(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:a90(Z,D),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new UA({mainAxisSize:"min",children:[new D0({text:new g($8(A.text,D),Q),textAlign:"center"}),new pQ({child:new OA({mainAxisSize:"min",children:[t$.createWidget(J,A.href,$8(A.linkText,D),new A0({color:B,underline:!0})),new D0({text:new g($8(A.textAfter,D),Q)})]})})]});let U=t$.createSpan(A.href,A.linkText,new A0({color:B,underline:!0})),Y=lX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{z$(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:a90(Z,D),textAlign:"center"})}if(D>0)return new D0({text:new g($8(A.text,D),new A0({color:B,underline:!0})),textAlign:"center"});return new pQ({child:t$.createWidget(J,A.href,A.text,new A0({color:B,underline:!0}))})}function VY6({progress:A,foreground:Q,pulseColor:$}){let B=new A0({color:Q,bold:!0}),E=new A0({color:zY6({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new g("",void 0,[new g(KY6(A).padEnd(rc0," "),B),new g(" ",B),new g(Bj4(Jj4,JY6,A,0.72),B),new g(" ",B),new g(Bj4(Uj4,UY6,A,0.88),E)])}function KY6(A){let Q=Q4(Dj4),$=Math.min(rc0,Math.ceil(LE(A/0.62)*rc0));return Q.slice(0,$).join("")}function Bj4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function zY6({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=LE((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function WY6({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new g($8(`${A}/${Q}`,B),new A0({color:$,dim:!0}))}function CY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}){let J=new A0({color:B}),U=new A0({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit",F="",X="",I=`${Z}`;if(!Q)return new g("",void 0,[new g(Y,J),new g(Z,U),new g("",J),new g("",U)]);let G=Ej4(Y,E),V=Ej4(I,LE((E*(Q4(Y).length+Q4(I).length)-Q4(Y).length)/Q4(I).length));return new g("",void 0,[new g($8(G,D),J),new g($8(V.slice(0,Z.length),D),U),new g($8(V.slice(Z.length,Z.length+0),D),J),new g($8(V.slice(Z.length+0),D),U)])}function HY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D,context:J}){if(Q)return new D0({text:CY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}),textAlign:"center"});let U=new A0({color:B}),Y=new A0({color:$,dim:!0});return new M5({onCopy:(Z,F)=>{if(F)DQ.success(J,"Copied to clipboard",2000)},child:new D0({text:new g("",void 0,[new g("q",U),new g(" to quit",Y)]),textAlign:"center",selectable:!0})})}function Ej4(A,Q){let $=Q4(A),B=Math.min($.length,Math.ceil(LE(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function a90(A,Q,$=0){if(Q<=0)return A;let B=$+Q4(A.text??"").length,E=A.children?.map((D)=>{let J=a90(D,Q,B);return B+=Q4(D.toPlainText()).length,J});return new g(A.text?$8(A.text,Q,$):A.text,A.style,E,A.hyperlink,A.onClick)}function $8(A,Q,$=0){if(Q<=0)return A;return Q4(A).map((E,D)=>{if(E.trim()==="")return E;return Xj4($+D)<Q?" ":E}).join("")}function Xj4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function qY6(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function Ij4(A){A.client.cancelAgentLoop().catch((Q)=>{S.warn("Failed to cancel plugin agent run",{error:Q})})}function wY6(A,Q={}){return new Promise(($,B)=>{if(Q.signal?.aborted){Ij4(A),B(Error("Agent run cancelled"));return}let E=!1,D=null,J=setTimeout(()=>{D?.(),Y.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),U=()=>{clearTimeout(J),Y.unsubscribe(),Ij4(A),B(Error("Agent run cancelled"))};if(Q.signal!==void 0)Q.signal.addEventListener("abort",U,{once:!0}),D=()=>Q.signal?.removeEventListener("abort",U);let Y=A.observer.agentState().subscribe((Z)=>{if(m3(Z)){E=!0;return}if(!E)return;let F=qY6(A);if(F===null)return;clearTimeout(J),D?.(),Y.unsubscribe(),$(F)})})}var uY6=O4("thread.switch",{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100},(A,{controller:Q,dismiss:$})=>{Q.pushWithDismiss((B)=>hd0({activeThreadID:A.getActiveThreadID(),loadThreads:A.loadThreads,loadThreadTail:A.appContext.loadThreadTail,onSelectThread:A.onSwitchThread,onDismiss:B,onThreadSelected:$}))}),MY6=O4("thread.switchToPrevious",{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],status:(A)=>A.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},(A,{dismiss:Q})=>{A.navigateBack(),Q()}),OY6=O4("thread.switchToNext",{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],status:(A)=>A.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},(A,{dismiss:Q})=>{A.navigateForward(),Q()}),LY6=O4("mcp.info",{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new km0({mcpServers:A.appContext.mcpServers,onDismiss:$}))}),jY6=O4("toolbox.list",{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"}},(A,{controller:Q})=>{Q.pushWithDismiss(($)=>new lc0({toolboxes:A.appContext.toolboxes,onDismiss:$}))}),RY6=O4("news.open",{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"}},async(A,{context:Q,dismiss:$})=>{try{await z$(Q,"https://ampcode.com/chronicle")}finally{$()}}),PY6=O4("settings.openInEditor",{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"}},(A)=>{wK(A.appContext.settingsFilePath).catch((Q)=>{S.error("Failed to open settings file in editor",{error:Q})})}),TY6=O4("ide.connect",{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.pushWithDismiss((B)=>new Sm0({onCancel:B,onSelect:(E)=>{A.handleIdeSelection(E),$()}}))}),vY6=O4("amp.help",{noun:"amp",verb:"help",description:"Show help & keymaps",keywords:["manual","?"],status:{type:"enabled"}},(A,{controller:Q,context:$,dismiss:B})=>{Q.push(new Am0({commands:sB.of($).commands,keymapShortcuts:A.getKeymapShortcuts(),onDismiss:B}))}),_Y6=O4("amp.showWelcome",{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"}},(A,{dismiss:Q})=>{Q(),A.showWelcome()}),SY6=O4("amp.endCredits",{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"}},(A,{dismiss:Q})=>{Q(),A.showEndCredits()}),kY6=O4("amp.showVersion",{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new E1({header:"Amp Version",maxWidth:72,onDismiss:$,child:new D0({text:new g(V50({version:"0.0.1780803750-g55245f",buildTimestamp:"2026-06-07T03:47:39.209Z",buildType:"release"}))})}))}),fY6=O4("amp.quit",{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],status:{type:"enabled"}},(A,{context:Q})=>{N4.maybeInvoke(Q,new vK)});class tc0 extends d0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new Vj4}}class Vj4 extends m0{editorController=new EZ;commandPalette=new sy0(this);commandRegistry=new tg0;keymapCommandRunner=new uh0(this.commandRegistry,()=>this.context);toastController=new Jb0;relaunchNotificationController=new lg0;exitHintTimer=new Hp(this,1000);ideStatus=new p3(this,{});threadNavigationHistory=new ag0;appShortcutManager=new tc;keymapController=new zy0({runCommand:(A)=>this.keymapCommandRunner.run(A),getCommandDescription:(A)=>{let Q=this.commandRegistry.findByID(A);return Q?.status.type==="enabled"?Q.description:null},onBindingsChange:()=>{if(this.syncAppShortcutManager(),this.mounted)this.setState()},onHintChange:()=>{if(this.mounted)this.setState()}});draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new bl;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;editorFocusNode=new a7({debugLabel:"EditorPanel"});loadThreads=async()=>{return this.widget.context.listThreads()};focusEditor=()=>{this.editorFocusNode.requestFocus()};focusEditorAfterNextFrame(){cQ.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.focusEditor()},"Neo focus editor")}analyzeContextForThread=async(A,Q)=>{return vI4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};onSelectSidebarThread=async(A)=>{this.focusEditor(),await this.onSwitchThread(A)};threadListSidebar=new pc0({state:this,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),archiveThread:(A)=>this.archiveThread(A),onSelectThread:this.onSelectSidebarThread,focusMainContent:this.focusEditor,getInitialVisible:()=>this.widget.context.threadListSidebarVisible});sendFeedbackReport=async(A)=>j80({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await zW4({configService:this.widget.configService},A);if(Q===null){let $=this.activeThreadContext?.client.getThreadId()??null;if(this.widget.clientPool.disconnectThread(A),this.widget.onThreadArchived?.(A),$===A)this.startNewDraftThread()}return Q};addThreadLabel=async(A,Q)=>{let $=await VC4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await KC4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(jX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.syncAppShortcutManager(),this.keymapController.connect(($)=>G1.instance.addKeyInterceptor($,{position:"front"})),this.notices=new Rg0(this.widget.configService,($)=>this.setState($)),cQ.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(S.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.keymapController.sync($.settings.keymap??{}),this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(P00($.settings)))}),this.updateRelaunchIntegration=new og0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new cg0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,readThreadTitle:this.readPluginThreadTitle,subscribeThreadTitle:this.subscribePluginThreadTitle,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new Oh0({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=G1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}createCommands(){let A={appContext:this.widget.context,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSwitchThread:this.onSwitchThread,canNavigateBack:()=>this.threadNavigationHistory.canNavigateBack(),canNavigateForward:()=>this.threadNavigationHistory.canNavigateForward(),navigateBack:()=>this.navigateBack(),navigateForward:()=>this.navigateForward(),handleIdeSelection:this.handleIdeSelection,getKeymapShortcuts:()=>this.keymapController.getShortcuts(),showWelcome:()=>this.showWelcome(),showEndCredits:()=>this.showEndCredits()},Q=this.widget.context.pluginService?fN4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[];return[cN4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),uY6.bind(A),...this.threadListSidebar.commands(),MY6.bind(A),yw4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),OY6.bind(A),LY6.bind(A),jY6.bind(A),RY6.bind(A),PY6.bind(A),TY6.bind(A),vY6.bind(A),_Y6.bind(A),SY6.bind(A),kY6.bind(A),fY6.bind(A),...Q,...FC4(this.widget.context.logFilePath)]}registerAppCommands(){let Q=this.createCommands().map(($)=>this.commandRegistry.register($));return()=>{for(let $ of Q)$()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,E=new bc0({initialAgentMode:this.widget.context.sessionAgentMode,initialPluginAgentModeKey:this.widget.context.initialPluginAgentModeKey,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,editorFocusNode:this.editorFocusNode,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(V)=>this.notices.dismiss(V)}),D=X4.of(A),J=D.capabilities.animationSupport!=="disabled",U=this.threadListSidebar.visibleWidth(),Y=Math.max(0,D.size.width-U),F=[new GA({constraints:A4.tight(D.size.width,D.size.height),child:this.threadListSidebar.buildBody(E)})];if(this.commandPalette.isEnabled())F.push(new E6({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new eg0({keymapShortcuts:this.keymapController.getShortcuts(),onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)F.push(hd0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)F.push(new E6({debugLabel:"WelcomeDialogOverlay",child:new sc0({onDismiss:this.dismissWelcome,onQuit:()=>G1.instance.stop(),animationsEnabled:J,variant:this.widget.welcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new E6({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new Tm0({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)F.push(new $m0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:o90.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,observerSnapshot$:this.activeThreadContext?.observer.observerSnapshot()??null}));if(this.focusDebugVisible)F.push(new vm0);if(this.endCreditsVisible)F.push(new Mm0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));let I=this.keymapController.getHint(),G=h70(this.exitHintTimer.isActive()?{key:"Ctrl+C",description:"again to exit"}:I?{key:I.leader,description:"...",options:I.options}:null);if(G)F.push(G);return new MQ({context:this.widget.context,child:new sB({commandRegistry:this.commandRegistry,child:new zT({completionBuilder:this.widget.completionBuilder,child:new DQ({controller:this.toastController,child:new N4({actions:this.buildActions(),child:new rQ({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),manager:this.appShortcutManager,child:this.keymapCommandRunner.captureContext(new VQ({debugLabel:"AppShellFocus",canRequestFocus:!1,skipTraversal:!0,child:new Ub0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new Qm0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new Oq({left:U,width:Y,child:this.keymapCommandRunner.buildModalStack(new t1({children:F}))})})})}))})})})})})})}buildShortcuts(){let A=new Map,Q=new Set,$=(E,D)=>{A.set(E,D),Q.add(E.toString())},B=(E,D)=>{if(Q.has(E.toString()))return;$(E,D)};for(let E of this.keymapController.getBindings())if(E.activator instanceof wA)$(E.activator,new R70(E.commandID));B(wA.ctrl("c"),new O70),B(wA.ctrl("o"),new j70),B(wA.alt("i"),new T70),B(wA.alt("p"),new nc),B(wA.ctrl("."),new S70),B(wA.ctrl("t"),new x70);for(let[E,D]of this.threadListSidebar.shortcutEntries())B(E,D);if(o90.env.NODE_ENV==="development"&&o90.platform==="darwin")B(wA.meta("r"),new L70);return A}syncAppShortcutManager(){for(let A of this.appShortcutManager.getAllShortcuts().keys())this.appShortcutManager.removeShortcut(A);for(let[A,Q]of this.buildShortcuts())this.appShortcutManager.addShortcut(A,Q)}buildActions(){let A=new cA(()=>{if(b2.hasAnyCopyableSelection())return b2.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new cA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new cA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new cA((G)=>{return this.keymapCommandRunner.run(G.commandID)?"handled":"ignored"}),E=new cA(()=>{return this.startNewDraftThread(),"handled"}),D=new cA(()=>{return G1.instance.stop(),"handled"}),J=new cA(()=>{return Pl({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),U=new cA((G)=>{if(!G.text)return"ignored";return G1.instance.tuiInstance.clipboard.writeText(G.text).then((V)=>{if(V.ok)this.toastController.show(G.successMessage,"success",2000);else this.toastController.show(`${G.failureMessage}: ${V.userFacingErrorMessage}`,"error",4000)}).catch((V)=>{S.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Y=new cA(()=>{return G1.instance.toggleFrameStatsOverlay(),"handled"}),Z=new cA(()=>this.notices.dismissCurrent()?"handled":"ignored"),F=new cA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=$q4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),I=new cA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[O70,A],[Lq,E],[vK,D],[L70,J],[IB,U],[Ql,$],[R70,B],[j70,Q],[T70,F],...this.threadListSidebar.actionEntries(),[S70,Z],...X,[nc,Y],[x70,I]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt;this.focusEditorAfterNextFrame()}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await hP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){S.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=oN(Q),E=Z50(this.widget.context,Q);if(B!==void 0&&E!==void 0)$={...$,[B]:E};return U50($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Gj4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(m9(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Gj4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(TK);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),G1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),eD((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{S.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")G1.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1}),this.focusEditorAfterNextFrame()};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,E,D)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),U=A.find(N00);if(U)this.widget.history.add(U.text,o90.cwd()),this.widget.history.reset();let Y=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Z=$??Y??null,F=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Z??void 0,E,D);if(this.sendUserMessage(F,A,E?void 0:Q,E?void 0:B),!E)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(F)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=oN(A),E=B?Q[B]:void 0;if(E!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:E};eD((D)=>{let J={...D,agentMode:A};if($!==void 0)J={...J,lastReasoningEffortByMode:{...J.lastReasoningEffortByMode??{},[A]:$}};if(E!==void 0)J={...J,lastSpeedByMode:{...J.lastSpeedByMode??{},[A]:E}};return J}).catch((D)=>{S.warn("Failed to persist Neo session defaults for new message",{error:D instanceof Error?D.message:String(D)})})}sendUserMessage(A,Q,$,B,E){let D=D50(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q,$)=>{let B=this.activeThreadContext;if(!B){if(Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}throw Error("appendToThread is not available - no active thread")}let E=B.client.getThreadId();if(Q&&E!==Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}for(let D of A)this.sendUserMessage(B,[{type:"text",text:D.content}],void 0,void 0,$)};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return yoA(boA($.observer.protocolMessages()),A)};readPluginThreadTitle=async(A)=>{let Q=this.activeThreadContext;if(!Q)throw Error("thread.title is not available - no active thread");let $=Q.client.getThreadId();if(A&&$!==A)throw Error("thread.title is only available for the active thread");return Q.observer.title().getValue()??null};subscribePluginThreadTitle=(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.title.subscribe is not available - no active thread");let B=$.client.getThreadId();if(A&&B!==A)throw Error("thread.title.subscribe is only available for the active thread");return $.observer.title().subscribe((E)=>{Q.next(E??null)})};runPluginAgent=async(A,Q,$)=>{await this.ensureDraftThreadSettingsInitialized();let B=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1,executorClientID:iY.parse(`neo-subagent-${NY6()}`)});this.sendUserMessage(B,[{type:"text",text:Q.message}]);try{let E=await wY6(B,{timeoutMs:Q.timeoutMs,signal:$}),D=B.client.getThreadId();return D?{threadID:D,text:E}:{text:E}}finally{this.widget.clientPool.disconnect(B)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(E)=>this.promptExecutorAlreadyConnected(E)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(S.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){S.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(E)=>{A.sendPluginMessage(E)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(E)=>{A.sendPluginMessage(E)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){S.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.keymapController.dispose(),this.keymapCommandRunner.dispose(),this.unregisterCommands?.(),this.unregisterCommands=null,this.threadListSidebar.dispose(),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),this.editorFocusNode.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function Gj4(A,Q,$){let B={...A};for(let E of xY6(Q,$)){if(!m9(A[E],Q[E]))continue;let D=$[E];if(D===void 0)delete B[E];else B[E]=D}return B}function xY6(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}function Kj4(){return PI4()}function mY6(A,Q){let $=dY6(A,Q),B=new Map(A.map((J)=>[J.id,J.description])),E=Object.entries($),D=E.map(([J,U],Y)=>{let Z=Y===E.length-1?"":",",F=` ${JSON.stringify(J)}: ${JSON.stringify(U)}${Z}`,I=` // ${(J==="leader"?"Leader key for <leader> shortcuts":B.get(J)??"Configured, not discovered").replaceAll(/[\r\n\u2028\u2029]/g," ")}`;return U===null?P0.dim(F+I):F+P0.dim(I)});return D.unshift("{"),D.push("}"),D.join(`
2913
+ `))}function rU6(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function nL4(A,Q){let $=A.replace(/\s+/g," ").trim();if(RA($)<=Q)return $;let B="...",E=RA(B);if(Q<=E)return o7(B,Q);return`${o7($,Q-E,!0,"")}${B}`}var ac0="https://ampcode.com/news/neo",oc0=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:ac0,href:ac0}]}];function sU6(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:ac0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function tU6(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var fT=50,aq=40,ic0=1000,eU6=420,AY6=760,QY6=-250,$Y6=1100,i90=33,sL4=0.999,BY6=2.1,EY6=720,DY6=420,Dj4="Meet the new",Jj4="Amp",Uj4="CLI",rc0=Q4(Dj4).length,JY6=Q4(Jj4).length,UY6=Q4(Uj4).length,n90={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},tL4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},eL4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},Aj4=[n90,tL4,eL4,n90,tL4,eL4,n90],YY6=n90;class sc0 extends d0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??tU6(),this.introStages=this.variant==="npm-migration"?sU6(this.binaryInstallCommand):oc0,this.dismissible=this.variant!=="npm-migration"}createState(){return new Yj4}}class Yj4 extends m0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=ic0;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new P5(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=LE(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=sL4,this.firstStageHintVisible=this.animationProgress>=sL4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:ic0,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=LE(A/AY6);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},i90)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=LE($/eU6);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},i90)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let E=performance.now()-this.startedAt,D=LE(E/this.animationDurationMs),J=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*xT(D);if(this.setState(()=>{this.animationProgress=J}),D>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},i90)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,ic0+QY6),Q=A+$Y6;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?LE((A-this.firstStageTitleRevealStartedAt)/EY6):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?LE((A-this.firstStageHintRevealStartedAt)/DY6):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},i90)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=Qj4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:$j4(Qj4(this.previousIntroStage),A,xT(this.stageTransitionProgress));return this.dismissProgress>0?$j4(Q,YY6,xT(this.dismissProgress)):Q}build(A){let Q=S4.of(A).colorScheme,$=e0.of(A),B=this.currentOrbPalette(),E=e7(1,"deep",B),D=X4.of(A).size,U=this.widget.animationProgress??this.animationProgress,Y=Math.max(D.width/fT,D.height/aq)*BY6,Z=Y+(1-Y)*U,F=xT(this.dismissProgress),X=Math.max(fT,Math.round(fT*Z)),I=Math.max(aq,Math.round(aq*Z)),G=Math.round((D.width-X)/2),V=Math.round((D.height-I)/2),K=Math.max(0,Math.floor((D.width-fT)/2)),z=-Math.floor(aq/2),W=Math.round(G+(K-G)*U),C=Math.round(V+(z-V)*U),H=W+X/2,N=C+I/2,w=ZY6({dismissProgress:this.dismissProgress,easedDismissProgress:F,introOrbScale:Z,normalOrbCenterX:H,normalOrbCenterY:N,size:D}),u=Math.max(fT,Math.round(fT*w.orbScale)),L=Math.max(aq,Math.round(aq*w.orbScale)),R=w.orbCenterX,_=w.orbCenterY,P=Math.round(R-u/2),f=Math.round(_-L/2),h=Math.max(3,Math.min(D.height-5,Math.floor(aq/2)+2)),x=Math.max(h+3,D.height-3),v=w.textDissolveProgress,k=this.isFinalIntroStage()?w.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&v<1,d=c&&this.firstStageHintVisible,b=d&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,a=Math.max(24,Math.min(74,D.width-4)),X0=Math.min(12,Math.max(8,D.height-h-6)),t=Math.max(0,Math.floor((D.width-a)/2)),Z0=Math.max(0,Math.min(D.height-X0,Math.floor(D.height*0.55-X0/2))),R0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new bK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new bK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new E6({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(B0)=>{if(B0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&B0.key==="c"&&B0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&B0.key==="q")return this.widget.onQuit?.(),"handled";if((B0.key===" "||B0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(B0.key==="Escape"||B0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(B0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(B0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new t1({fit:"expand",children:[new Zj4({color:Q.background,dissolveProgress:k}),new t1({fit:"expand",children:[new iA({onClick:()=>{},child:y0.expand()}),new m1({left:P,top:f,width:u,height:L,child:R0}),...c?[new m1({left:t,top:Z0,width:a,height:X0,child:XY6({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:a,height:X0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:E,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:v,context:A})})]:[],...d?[...b?[new m1({left:t,top:Math.max(0,x-1),width:a,height:1,child:new D0({text:WY6({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new m1({left:t,top:x,width:a,height:1,child:HY6({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:v,context:A})})]:[]]})]})})}}class Zj4 extends XB{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new Fj4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class Fj4 extends bA{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height),U={bg:this.color},Y=LE(this.dissolveProgress);if(Y<=0){A.fill(B,E,D,J," ",U);return}if(Y>=1)return;for(let Z=0;Z<J;Z++)for(let F=0;F<D;F++)if(!FY6(F,Z,D,J,Y))A.fill(B+F,E+Z,1,1," ",U)}}function LE(A){return Math.min(1,Math.max(0,A))}function xT(A){return 1-(1-A)**3}function Qj4(A){return Aj4[A]??Aj4[0]}function $j4(A,Q,$){return{primary:Mq(A.primary,Q.primary,$),secondary:Mq(A.secondary,Q.secondary,$)}}function ZY6({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:E,size:D}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(D.width*0.54-B)*Q,orbCenterY:E-D.height*0.44*Q,textDissolveProgress:LE(A/0.52),backdropDissolveProgress:xT(LE((A-0.12)/0.88))}}function FY6(A,Q,$,B,E){let D=B<=1?0:Q/(B-1),J=Xj4(A+Q*Math.max(1,$));return(1-D)*0.72+J*0.28<E}function XY6({introStages:A,stage:Q,previousStage:$,progress:B,direction:E,width:D,height:J,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return nc0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let K=xT(B),z=E*Math.round((1-K)*D),W=-E*Math.round(K*D);return new Xq(new t1({fit:"expand",children:[new m1({left:W,top:0,width:D,height:J,child:nc0({introStages:A,stage:$,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new m1({left:z,top:0,width:D,height:J,child:nc0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function nc0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:E,link:D,keybind:J,titleRevealProgress:U,dissolveProgress:Y,context:Z}){let F=A[Q]??A[0]??oc0[0],X=new A0({color:E,bold:!0}),I=new A0({color:$}),G=A===oc0&&Q===0,V=[...F.title===null?[]:[new D0({text:G?a90(VY6({progress:U,foreground:E,pulseColor:E}),Y):new g($8(F.title,Y),X),textAlign:"center"})],...F.body.length>0?[IY6()]:[],...F.body.map((K)=>GY6(K,I,B,D,J,Y,Z))];return new pQ({child:new mA({padding:c0.horizontal(1),child:new UA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function IY6(){return y0.height(1)}function GY6(A,Q,$,B,E,D,J){if(typeof A==="string")return new D0({text:new g($8(A,D),Q),textAlign:"center"});if("codeBlock"in A)return new M5({onCopy:(U,Y)=>{if(Y)DQ.success(J,"Copied to clipboard",2000)},child:new UA({mainAxisSize:"min",children:A.codeBlock.map((U)=>new D0({text:new g($8(U,D),new A0({color:E})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let U=new D0({text:new g("",void 0,[new g($8(A.text,D),new A0({color:$,dim:!0})),new g($8(A.keybind,D,Q4(A.text).length),new A0({color:E}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new pQ({child:new M5({child:U})});return U}if("highlightText"in A){let U=t$.createSpan(A.href,A.linkText,new A0({color:B,underline:!0})),Y=lX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(A.highlightText,new A0({color:E})),new g(A.textAfterHighlight,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{z$(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:a90(Z,D),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new UA({mainAxisSize:"min",children:[new D0({text:new g($8(A.text,D),Q),textAlign:"center"}),new pQ({child:new OA({mainAxisSize:"min",children:[t$.createWidget(J,A.href,$8(A.linkText,D),new A0({color:B,underline:!0})),new D0({text:new g($8(A.textAfter,D),Q)})]})})]});let U=t$.createSpan(A.href,A.linkText,new A0({color:B,underline:!0})),Y=lX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{z$(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:a90(Z,D),textAlign:"center"})}if(D>0)return new D0({text:new g($8(A.text,D),new A0({color:B,underline:!0})),textAlign:"center"});return new pQ({child:t$.createWidget(J,A.href,A.text,new A0({color:B,underline:!0}))})}function VY6({progress:A,foreground:Q,pulseColor:$}){let B=new A0({color:Q,bold:!0}),E=new A0({color:zY6({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new g("",void 0,[new g(KY6(A).padEnd(rc0," "),B),new g(" ",B),new g(Bj4(Jj4,JY6,A,0.72),B),new g(" ",B),new g(Bj4(Uj4,UY6,A,0.88),E)])}function KY6(A){let Q=Q4(Dj4),$=Math.min(rc0,Math.ceil(LE(A/0.62)*rc0));return Q.slice(0,$).join("")}function Bj4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function zY6({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=LE((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function WY6({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new g($8(`${A}/${Q}`,B),new A0({color:$,dim:!0}))}function CY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}){let J=new A0({color:B}),U=new A0({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit",F="",X="",I=`${Z}`;if(!Q)return new g("",void 0,[new g(Y,J),new g(Z,U),new g("",J),new g("",U)]);let G=Ej4(Y,E),V=Ej4(I,LE((E*(Q4(Y).length+Q4(I).length)-Q4(Y).length)/Q4(I).length));return new g("",void 0,[new g($8(G,D),J),new g($8(V.slice(0,Z.length),D),U),new g($8(V.slice(Z.length,Z.length+0),D),J),new g($8(V.slice(Z.length+0),D),U)])}function HY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D,context:J}){if(Q)return new D0({text:CY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}),textAlign:"center"});let U=new A0({color:B}),Y=new A0({color:$,dim:!0});return new M5({onCopy:(Z,F)=>{if(F)DQ.success(J,"Copied to clipboard",2000)},child:new D0({text:new g("",void 0,[new g("q",U),new g(" to quit",Y)]),textAlign:"center",selectable:!0})})}function Ej4(A,Q){let $=Q4(A),B=Math.min($.length,Math.ceil(LE(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function a90(A,Q,$=0){if(Q<=0)return A;let B=$+Q4(A.text??"").length,E=A.children?.map((D)=>{let J=a90(D,Q,B);return B+=Q4(D.toPlainText()).length,J});return new g(A.text?$8(A.text,Q,$):A.text,A.style,E,A.hyperlink,A.onClick)}function $8(A,Q,$=0){if(Q<=0)return A;return Q4(A).map((E,D)=>{if(E.trim()==="")return E;return Xj4($+D)<Q?" ":E}).join("")}function Xj4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function qY6(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function Ij4(A){A.client.cancelAgentLoop().catch((Q)=>{S.warn("Failed to cancel plugin agent run",{error:Q})})}function wY6(A,Q={}){return new Promise(($,B)=>{if(Q.signal?.aborted){Ij4(A),B(Error("Agent run cancelled"));return}let E=!1,D=null,J=setTimeout(()=>{D?.(),Y.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),U=()=>{clearTimeout(J),Y.unsubscribe(),Ij4(A),B(Error("Agent run cancelled"))};if(Q.signal!==void 0)Q.signal.addEventListener("abort",U,{once:!0}),D=()=>Q.signal?.removeEventListener("abort",U);let Y=A.observer.agentState().subscribe((Z)=>{if(m3(Z)){E=!0;return}if(!E)return;let F=qY6(A);if(F===null)return;clearTimeout(J),D?.(),Y.unsubscribe(),$(F)})})}var uY6=O4("thread.switch",{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100},(A,{controller:Q,dismiss:$})=>{Q.pushWithDismiss((B)=>hd0({activeThreadID:A.getActiveThreadID(),loadThreads:A.loadThreads,loadThreadTail:A.appContext.loadThreadTail,onSelectThread:A.onSwitchThread,onDismiss:B,onThreadSelected:$}))}),MY6=O4("thread.switchToPrevious",{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],status:(A)=>A.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},(A,{dismiss:Q})=>{A.navigateBack(),Q()}),OY6=O4("thread.switchToNext",{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],status:(A)=>A.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},(A,{dismiss:Q})=>{A.navigateForward(),Q()}),LY6=O4("mcp.info",{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new km0({mcpServers:A.appContext.mcpServers,onDismiss:$}))}),jY6=O4("toolbox.list",{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"}},(A,{controller:Q})=>{Q.pushWithDismiss(($)=>new lc0({toolboxes:A.appContext.toolboxes,onDismiss:$}))}),RY6=O4("news.open",{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"}},async(A,{context:Q,dismiss:$})=>{try{await z$(Q,"https://ampcode.com/chronicle")}finally{$()}}),PY6=O4("settings.openInEditor",{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"}},(A)=>{wK(A.appContext.settingsFilePath).catch((Q)=>{S.error("Failed to open settings file in editor",{error:Q})})}),TY6=O4("ide.connect",{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.pushWithDismiss((B)=>new Sm0({onCancel:B,onSelect:(E)=>{A.handleIdeSelection(E),$()}}))}),vY6=O4("amp.help",{noun:"amp",verb:"help",description:"Show help & keymaps",keywords:["manual","?"],status:{type:"enabled"}},(A,{controller:Q,context:$,dismiss:B})=>{Q.push(new Am0({commands:sB.of($).commands,keymapShortcuts:A.getKeymapShortcuts(),onDismiss:B}))}),_Y6=O4("amp.showWelcome",{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"}},(A,{dismiss:Q})=>{Q(),A.showWelcome()}),SY6=O4("amp.endCredits",{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"}},(A,{dismiss:Q})=>{Q(),A.showEndCredits()}),kY6=O4("amp.showVersion",{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new E1({header:"Amp Version",maxWidth:72,onDismiss:$,child:new D0({text:new g(V50({version:"0.0.1780818304-g58b217",buildTimestamp:"2026-06-07T07:50:20.537Z",buildType:"release"}))})}))}),fY6=O4("amp.quit",{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],status:{type:"enabled"}},(A,{context:Q})=>{N4.maybeInvoke(Q,new vK)});class tc0 extends d0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new Vj4}}class Vj4 extends m0{editorController=new EZ;commandPalette=new sy0(this);commandRegistry=new tg0;keymapCommandRunner=new uh0(this.commandRegistry,()=>this.context);toastController=new Jb0;relaunchNotificationController=new lg0;exitHintTimer=new Hp(this,1000);ideStatus=new p3(this,{});threadNavigationHistory=new ag0;appShortcutManager=new tc;keymapController=new zy0({runCommand:(A)=>this.keymapCommandRunner.run(A),getCommandDescription:(A)=>{let Q=this.commandRegistry.findByID(A);return Q?.status.type==="enabled"?Q.description:null},onBindingsChange:()=>{if(this.syncAppShortcutManager(),this.mounted)this.setState()},onHintChange:()=>{if(this.mounted)this.setState()}});draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new bl;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;editorFocusNode=new a7({debugLabel:"EditorPanel"});loadThreads=async()=>{return this.widget.context.listThreads()};focusEditor=()=>{this.editorFocusNode.requestFocus()};focusEditorAfterNextFrame(){cQ.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.focusEditor()},"Neo focus editor")}analyzeContextForThread=async(A,Q)=>{return vI4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};onSelectSidebarThread=async(A)=>{this.focusEditor(),await this.onSwitchThread(A)};threadListSidebar=new pc0({state:this,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),archiveThread:(A)=>this.archiveThread(A),onSelectThread:this.onSelectSidebarThread,focusMainContent:this.focusEditor,getInitialVisible:()=>this.widget.context.threadListSidebarVisible});sendFeedbackReport=async(A)=>j80({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await zW4({configService:this.widget.configService},A);if(Q===null){let $=this.activeThreadContext?.client.getThreadId()??null;if(this.widget.clientPool.disconnectThread(A),this.widget.onThreadArchived?.(A),$===A)this.startNewDraftThread()}return Q};addThreadLabel=async(A,Q)=>{let $=await VC4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await KC4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(jX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.syncAppShortcutManager(),this.keymapController.connect(($)=>G1.instance.addKeyInterceptor($,{position:"front"})),this.notices=new Rg0(this.widget.configService,($)=>this.setState($)),cQ.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(S.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.keymapController.sync($.settings.keymap??{}),this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(P00($.settings)))}),this.updateRelaunchIntegration=new og0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new cg0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,readThreadTitle:this.readPluginThreadTitle,subscribeThreadTitle:this.subscribePluginThreadTitle,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new Oh0({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=G1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}createCommands(){let A={appContext:this.widget.context,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSwitchThread:this.onSwitchThread,canNavigateBack:()=>this.threadNavigationHistory.canNavigateBack(),canNavigateForward:()=>this.threadNavigationHistory.canNavigateForward(),navigateBack:()=>this.navigateBack(),navigateForward:()=>this.navigateForward(),handleIdeSelection:this.handleIdeSelection,getKeymapShortcuts:()=>this.keymapController.getShortcuts(),showWelcome:()=>this.showWelcome(),showEndCredits:()=>this.showEndCredits()},Q=this.widget.context.pluginService?fN4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[];return[cN4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),uY6.bind(A),...this.threadListSidebar.commands(),MY6.bind(A),yw4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),OY6.bind(A),LY6.bind(A),jY6.bind(A),RY6.bind(A),PY6.bind(A),TY6.bind(A),vY6.bind(A),_Y6.bind(A),SY6.bind(A),kY6.bind(A),fY6.bind(A),...Q,...FC4(this.widget.context.logFilePath)]}registerAppCommands(){let Q=this.createCommands().map(($)=>this.commandRegistry.register($));return()=>{for(let $ of Q)$()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,E=new bc0({initialAgentMode:this.widget.context.sessionAgentMode,initialPluginAgentModeKey:this.widget.context.initialPluginAgentModeKey,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,editorFocusNode:this.editorFocusNode,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(V)=>this.notices.dismiss(V)}),D=X4.of(A),J=D.capabilities.animationSupport!=="disabled",U=this.threadListSidebar.visibleWidth(),Y=Math.max(0,D.size.width-U),F=[new GA({constraints:A4.tight(D.size.width,D.size.height),child:this.threadListSidebar.buildBody(E)})];if(this.commandPalette.isEnabled())F.push(new E6({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new eg0({keymapShortcuts:this.keymapController.getShortcuts(),onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)F.push(hd0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)F.push(new E6({debugLabel:"WelcomeDialogOverlay",child:new sc0({onDismiss:this.dismissWelcome,onQuit:()=>G1.instance.stop(),animationsEnabled:J,variant:this.widget.welcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new E6({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new Tm0({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)F.push(new $m0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:o90.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,observerSnapshot$:this.activeThreadContext?.observer.observerSnapshot()??null}));if(this.focusDebugVisible)F.push(new vm0);if(this.endCreditsVisible)F.push(new Mm0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));let I=this.keymapController.getHint(),G=h70(this.exitHintTimer.isActive()?{key:"Ctrl+C",description:"again to exit"}:I?{key:I.leader,description:"...",options:I.options}:null);if(G)F.push(G);return new MQ({context:this.widget.context,child:new sB({commandRegistry:this.commandRegistry,child:new zT({completionBuilder:this.widget.completionBuilder,child:new DQ({controller:this.toastController,child:new N4({actions:this.buildActions(),child:new rQ({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),manager:this.appShortcutManager,child:this.keymapCommandRunner.captureContext(new VQ({debugLabel:"AppShellFocus",canRequestFocus:!1,skipTraversal:!0,child:new Ub0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new Qm0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new Oq({left:U,width:Y,child:this.keymapCommandRunner.buildModalStack(new t1({children:F}))})})})}))})})})})})})}buildShortcuts(){let A=new Map,Q=new Set,$=(E,D)=>{A.set(E,D),Q.add(E.toString())},B=(E,D)=>{if(Q.has(E.toString()))return;$(E,D)};for(let E of this.keymapController.getBindings())if(E.activator instanceof wA)$(E.activator,new R70(E.commandID));B(wA.ctrl("c"),new O70),B(wA.ctrl("o"),new j70),B(wA.alt("i"),new T70),B(wA.alt("p"),new nc),B(wA.ctrl("."),new S70),B(wA.ctrl("t"),new x70);for(let[E,D]of this.threadListSidebar.shortcutEntries())B(E,D);if(o90.env.NODE_ENV==="development"&&o90.platform==="darwin")B(wA.meta("r"),new L70);return A}syncAppShortcutManager(){for(let A of this.appShortcutManager.getAllShortcuts().keys())this.appShortcutManager.removeShortcut(A);for(let[A,Q]of this.buildShortcuts())this.appShortcutManager.addShortcut(A,Q)}buildActions(){let A=new cA(()=>{if(b2.hasAnyCopyableSelection())return b2.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new cA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new cA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new cA((G)=>{return this.keymapCommandRunner.run(G.commandID)?"handled":"ignored"}),E=new cA(()=>{return this.startNewDraftThread(),"handled"}),D=new cA(()=>{return G1.instance.stop(),"handled"}),J=new cA(()=>{return Pl({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),U=new cA((G)=>{if(!G.text)return"ignored";return G1.instance.tuiInstance.clipboard.writeText(G.text).then((V)=>{if(V.ok)this.toastController.show(G.successMessage,"success",2000);else this.toastController.show(`${G.failureMessage}: ${V.userFacingErrorMessage}`,"error",4000)}).catch((V)=>{S.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Y=new cA(()=>{return G1.instance.toggleFrameStatsOverlay(),"handled"}),Z=new cA(()=>this.notices.dismissCurrent()?"handled":"ignored"),F=new cA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=$q4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),I=new cA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[O70,A],[Lq,E],[vK,D],[L70,J],[IB,U],[Ql,$],[R70,B],[j70,Q],[T70,F],...this.threadListSidebar.actionEntries(),[S70,Z],...X,[nc,Y],[x70,I]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt;this.focusEditorAfterNextFrame()}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await hP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){S.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=oN(Q),E=Z50(this.widget.context,Q);if(B!==void 0&&E!==void 0)$={...$,[B]:E};return U50($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Gj4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(m9(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Gj4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(TK);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),G1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),eD((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{S.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")G1.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1}),this.focusEditorAfterNextFrame()};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,E,D)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),U=A.find(N00);if(U)this.widget.history.add(U.text,o90.cwd()),this.widget.history.reset();let Y=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Z=$??Y??null,F=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Z??void 0,E,D);if(this.sendUserMessage(F,A,E?void 0:Q,E?void 0:B),!E)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(F)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=oN(A),E=B?Q[B]:void 0;if(E!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:E};eD((D)=>{let J={...D,agentMode:A};if($!==void 0)J={...J,lastReasoningEffortByMode:{...J.lastReasoningEffortByMode??{},[A]:$}};if(E!==void 0)J={...J,lastSpeedByMode:{...J.lastSpeedByMode??{},[A]:E}};return J}).catch((D)=>{S.warn("Failed to persist Neo session defaults for new message",{error:D instanceof Error?D.message:String(D)})})}sendUserMessage(A,Q,$,B,E){let D=D50(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q,$)=>{let B=this.activeThreadContext;if(!B){if(Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}throw Error("appendToThread is not available - no active thread")}let E=B.client.getThreadId();if(Q&&E!==Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}for(let D of A)this.sendUserMessage(B,[{type:"text",text:D.content}],void 0,void 0,$)};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return yoA(boA($.observer.protocolMessages()),A)};readPluginThreadTitle=async(A)=>{let Q=this.activeThreadContext;if(!Q)throw Error("thread.title is not available - no active thread");let $=Q.client.getThreadId();if(A&&$!==A)throw Error("thread.title is only available for the active thread");return Q.observer.title().getValue()??null};subscribePluginThreadTitle=(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.title.subscribe is not available - no active thread");let B=$.client.getThreadId();if(A&&B!==A)throw Error("thread.title.subscribe is only available for the active thread");return $.observer.title().subscribe((E)=>{Q.next(E??null)})};runPluginAgent=async(A,Q,$)=>{await this.ensureDraftThreadSettingsInitialized();let B=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1,executorClientID:iY.parse(`neo-subagent-${NY6()}`)});this.sendUserMessage(B,[{type:"text",text:Q.message}]);try{let E=await wY6(B,{timeoutMs:Q.timeoutMs,signal:$}),D=B.client.getThreadId();return D?{threadID:D,text:E}:{text:E}}finally{this.widget.clientPool.disconnect(B)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(E)=>this.promptExecutorAlreadyConnected(E)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(S.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){S.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(E)=>{A.sendPluginMessage(E)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(E)=>{A.sendPluginMessage(E)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){S.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.keymapController.dispose(),this.keymapCommandRunner.dispose(),this.unregisterCommands?.(),this.unregisterCommands=null,this.threadListSidebar.dispose(),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),this.editorFocusNode.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function Gj4(A,Q,$){let B={...A};for(let E of xY6(Q,$)){if(!m9(A[E],Q[E]))continue;let D=$[E];if(D===void 0)delete B[E];else B[E]=D}return B}function xY6(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}function Kj4(){return PI4()}function mY6(A,Q){let $=dY6(A,Q),B=new Map(A.map((J)=>[J.id,J.description])),E=Object.entries($),D=E.map(([J,U],Y)=>{let Z=Y===E.length-1?"":",",F=` ${JSON.stringify(J)}: ${JSON.stringify(U)}${Z}`,I=` // ${(J==="leader"?"Leader key for <leader> shortcuts":B.get(J)??"Configured, not discovered").replaceAll(/[\r\n\u2028\u2029]/g," ")}`;return U===null?P0.dim(F+I):F+P0.dim(I)});return D.unshift("{"),D.push("}"),D.join(`
2914
2914
  `)+`
2915
2915
  `}function dY6(A,Q){let $=Ky0(Q),B=Q.leader,E={leader:B===null||typeof B==="string"&&f2(B)?B:Gy0};for(let D of A){let J=$.filter((Y)=>Y.commandID===D.id).map((Y)=>Y.key),U=D.defaultKey?[...J,D.defaultKey]:J;if(U.length===0)E[D.id]=null;if(U.length===1)E[D.id]=U[0];if(U.length>1)E[D.id]=U}for(let[D,J]of Object.entries(Q)){if(D==="leader"||E[D]!==void 0)continue;E[D]=J}return E}async function cY6(A){await bY6(gY6.dirname(A),{recursive:!0});try{await hY6(A,`{
2916
2916
  }
@@ -3070,13 +3070,13 @@ ${K}`))}},error:(V)=>{if(!G)G=!0,Z(Error(`Failed to spawn brew: ${V.message}`))}
3070
3070
  ${K}`;if(J==="pnpm"&&K.includes("Unable to find the global bin directory"))z+=`
3071
3071
 
3072
3072
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
3073
- npm install -g ${D}`;Z(Error(z))}},error:(V)=>{if(!I)I=!0,Z(Error(`Failed to spawn ${J}: ${V.message}`))},complete:()=>{if(!I)I=!0,Y()}})})}i0();hA();i0();import{readFile as ZI6,realpath as FI6}from"node:fs/promises";import{dirname as GP4,join as XI6}from"node:path";async function VP4(A){switch(A){case"binary":case"brew":return II6(Ki());case"npm":case"pnpm":case"yarn":case"bun":return GI6()}}async function II6(A){let Q=await HK(A,["--version"],5000);if(Q.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function GI6(){try{let A=process.argv[1];if(!A)return null;let Q=await FI6(A),$=GP4(GP4(Q));return await VI6(XI6($,"package.json"))}catch(A){return S.debug("failed to read installed version from package.json",{error:A}),null}}async function VI6(A){let Q=await ZI6(A,"utf8"),$=JSON.parse(Q);if(!$.name||!Ly0($.name))return S.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}i0();import{spawn as KI6}from"node:child_process";function xp0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return S.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var CE0=null,Wi=null;function KP4(A){return new Promise((Q)=>{let $=KI6("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(E)=>{B+=E.toString()}),$.on("close",(E,D)=>{if(E!==0||D==="SIGTERM"){Q(null);return}let J=B.trim();Q(J&&J!=="undefined"?J:null)}),$.on("error",()=>{Q(null)})})}async function HE0(){if(CE0)return CE0;if(Wi)return Wi;Wi=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return xp0(A);let Q=await KP4("@sourcegraph:registry");if(Q)return xp0(Q);let $=await KP4("registry");if($)return xp0($);return"https://registry.npmjs.org"})();try{return CE0=await Wi,CE0}finally{Wi=null}}var zI6=3600000,WI6=5000;function yp0(A,Q,$={}){let B=new L4,E=B.pipe(_$({shouldCountRefs:!1})),D=$.startDelayMs??0,J=$.checkIntervalMs??zI6,U=!1,Y=()=>{U=!0};return setImmediate(async()=>{let Z=S.getChild("update");if(D>0){if(await LV(D),U)return}let F=E.subscribe({next:(I)=>{Z.debug("emit new state",I)}}),X=A;try{while(!U){let I=await CI6(X,Q,Z,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await LV(WI6),U)return;B.next("hidden")}if(J<=0)return;let G=1000,V=J;while(V>0&&!U){let K=Math.min(G,V);await LV(K),V-=K}}}finally{F.unsubscribe(),B.complete()}}),{state:E,dispose:Y}}async function CI6(A,Q,$,B){let E={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),E.stop=!0,E;let D=await Q.get("updates.mode");if(D==="disabled")return $.debug("checking disabled"),E.stop=!0,E;let J=await sY(),U=J==="binary"||J==="brew",Y=U?void 0:await NK();$.debug("checking",{currentVersion:A,mode:D,packageManager:J,isBinaryDistribution:U,npmPackageName:Y});let Z;if(U)Z=await X50(A);else{let I=await HE0();Z=await F50(A,I,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),E;let F=(I)=>{B.next(I),E.emittedVisibleState=!0};if(J){let I=await VP4(J);if(I&&Ap(I,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Z.latestVersion}),E.updatedTo=I,Ap(A,I)<0){let G=await PX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),F("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),F("updated-with-warning")}return E}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let I=Z.currentVersionAge-Z.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!D)D=J==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:J,mode:D});if(J==="brew"){if(!X())F("update-available-brew");return E}if(J==="binary"&&process.execPath!==Ki()){if($.debug("non-standard binary path, showing warning"),!X())F("update-available-unrecognized-path");return E}if(D==="warn"){if(!X())F("update-available");return E}if(!J){if($.debug("auto-update not supported, falling back to warn mode"),!X())F("update-available");return E}try{await zi(Z.latestVersion,J),E.updatedTo=Z.latestVersion;let I=await PX(Z.latestVersion),G={from:Z.currentVersion,to:Z.latestVersion,...I};if(I.status==="same")$.info("success",G),F("updated");else $.warn("success with warning",G),F("updated-with-warning")}catch(I){F("update-error")}return E}catch(D){return $.debug("check failed",{error:D}),E}}Kg();import{stderr as IJ}from"node:process";function zP4(A){let Q=new MX().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(B)=>{await Tp0(B.force||!1,B.verbose||!1,"0.0.1780803750-g55245f"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new MX("update").alias("up").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(B)=>{await qI6(B.targetVersion)});A.addCommand($)}function HI6(A){let Q=Boolean(A.isTTY),$=0,B=!1;function E(){if(!Q||!B)return;A.write(`
3073
+ npm install -g ${D}`;Z(Error(z))}},error:(V)=>{if(!I)I=!0,Z(Error(`Failed to spawn ${J}: ${V.message}`))},complete:()=>{if(!I)I=!0,Y()}})})}i0();hA();i0();import{readFile as ZI6,realpath as FI6}from"node:fs/promises";import{dirname as GP4,join as XI6}from"node:path";async function VP4(A){switch(A){case"binary":case"brew":return II6(Ki());case"npm":case"pnpm":case"yarn":case"bun":return GI6()}}async function II6(A){let Q=await HK(A,["--version"],5000);if(Q.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function GI6(){try{let A=process.argv[1];if(!A)return null;let Q=await FI6(A),$=GP4(GP4(Q));return await VI6(XI6($,"package.json"))}catch(A){return S.debug("failed to read installed version from package.json",{error:A}),null}}async function VI6(A){let Q=await ZI6(A,"utf8"),$=JSON.parse(Q);if(!$.name||!Ly0($.name))return S.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}i0();import{spawn as KI6}from"node:child_process";function xp0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return S.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var CE0=null,Wi=null;function KP4(A){return new Promise((Q)=>{let $=KI6("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(E)=>{B+=E.toString()}),$.on("close",(E,D)=>{if(E!==0||D==="SIGTERM"){Q(null);return}let J=B.trim();Q(J&&J!=="undefined"?J:null)}),$.on("error",()=>{Q(null)})})}async function HE0(){if(CE0)return CE0;if(Wi)return Wi;Wi=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return xp0(A);let Q=await KP4("@sourcegraph:registry");if(Q)return xp0(Q);let $=await KP4("registry");if($)return xp0($);return"https://registry.npmjs.org"})();try{return CE0=await Wi,CE0}finally{Wi=null}}var zI6=3600000,WI6=5000;function yp0(A,Q,$={}){let B=new L4,E=B.pipe(_$({shouldCountRefs:!1})),D=$.startDelayMs??0,J=$.checkIntervalMs??zI6,U=!1,Y=()=>{U=!0};return setImmediate(async()=>{let Z=S.getChild("update");if(D>0){if(await LV(D),U)return}let F=E.subscribe({next:(I)=>{Z.debug("emit new state",I)}}),X=A;try{while(!U){let I=await CI6(X,Q,Z,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await LV(WI6),U)return;B.next("hidden")}if(J<=0)return;let G=1000,V=J;while(V>0&&!U){let K=Math.min(G,V);await LV(K),V-=K}}}finally{F.unsubscribe(),B.complete()}}),{state:E,dispose:Y}}async function CI6(A,Q,$,B){let E={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),E.stop=!0,E;let D=await Q.get("updates.mode");if(D==="disabled")return $.debug("checking disabled"),E.stop=!0,E;let J=await sY(),U=J==="binary"||J==="brew",Y=U?void 0:await NK();$.debug("checking",{currentVersion:A,mode:D,packageManager:J,isBinaryDistribution:U,npmPackageName:Y});let Z;if(U)Z=await X50(A);else{let I=await HE0();Z=await F50(A,I,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),E;let F=(I)=>{B.next(I),E.emittedVisibleState=!0};if(J){let I=await VP4(J);if(I&&Ap(I,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Z.latestVersion}),E.updatedTo=I,Ap(A,I)<0){let G=await PX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),F("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),F("updated-with-warning")}return E}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let I=Z.currentVersionAge-Z.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!D)D=J==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:J,mode:D});if(J==="brew"){if(!X())F("update-available-brew");return E}if(J==="binary"&&process.execPath!==Ki()){if($.debug("non-standard binary path, showing warning"),!X())F("update-available-unrecognized-path");return E}if(D==="warn"){if(!X())F("update-available");return E}if(!J){if($.debug("auto-update not supported, falling back to warn mode"),!X())F("update-available");return E}try{await zi(Z.latestVersion,J),E.updatedTo=Z.latestVersion;let I=await PX(Z.latestVersion),G={from:Z.currentVersion,to:Z.latestVersion,...I};if(I.status==="same")$.info("success",G),F("updated");else $.warn("success with warning",G),F("updated-with-warning")}catch(I){F("update-error")}return E}catch(D){return $.debug("check failed",{error:D}),E}}Kg();import{stderr as IJ}from"node:process";function zP4(A){let Q=new MX().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(B)=>{await Tp0(B.force||!1,B.verbose||!1,"0.0.1780818304-g58b217"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new MX("update").alias("up").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(B)=>{await qI6(B.targetVersion)});A.addCommand($)}function HI6(A){let Q=Boolean(A.isTTY),$=0,B=!1;function E(){if(!Q||!B)return;A.write(`
3074
3074
  `),B=!1,$=0}function D(J){if(!Q)return;let U=J.padEnd($," ");A.write(`\r${U}`),B=!0,$=U.length}return{flushProgressLine:E,renderProgress:D}}function NI6(A){if(A.source==="npm"&&A.latestVersionAge!==void 0&&A.latestVersionAge>36)IJ.write(P0.yellow(`The latest Amp CLI version reported by npm is older than expected. Be aware that you may be using an npm proxy with a corporate policy to delay package updates.
3075
3075
  `))}async function qI6(A){let $=process.platform==="win32"&&tN()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:B,renderProgress:E}=HI6(IJ);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")IJ.write(P0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
3076
3076
 
3077
3077
  `));try{if(!A){IJ.write(P0.blue(`Checking for updates...
3078
- `));let U=!1,Y;if(tN()){let Z=await X50("0.0.1780803750-g55245f");U=Z.hasUpdate,Y=Z.latestVersion}else{let Z=await HE0(),F=await NK(),X=await F50("0.0.1780803750-g55245f",Z,F);NI6(X),U=X.hasUpdate,Y=X.latestVersion}if(!U){let Z=Qp("0.0.1780803750-g55245f"),F=Z?.age?`released ${Z.age} ago`:`built ${MV(new Date("2026-06-07T03:47:39.209Z"))} ago`;IJ.write(P0.green(`✓ Amp is already up to date on version ${"0.0.1780803750-g55245f"} (${F})
3079
- `));let X=await PX("0.0.1780803750-g55245f",$);if(X.warning)IJ.write(`
3078
+ `));let U=!1,Y;if(tN()){let Z=await X50("0.0.1780818304-g58b217");U=Z.hasUpdate,Y=Z.latestVersion}else{let Z=await HE0(),F=await NK(),X=await F50("0.0.1780818304-g58b217",Z,F);NI6(X),U=X.hasUpdate,Y=X.latestVersion}if(!U){let Z=Qp("0.0.1780818304-g58b217"),F=Z?.age?`released ${Z.age} ago`:`built ${MV(new Date("2026-06-07T07:50:20.537Z"))} ago`;IJ.write(P0.green(`✓ Amp is already up to date on version ${"0.0.1780818304-g58b217"} (${F})
3079
+ `));let X=await PX("0.0.1780818304-g58b217",$);if(X.warning)IJ.write(`
3080
3080
  `+P0.yellow(X.warning)+`
3081
3081
  `);process.exit(0)}if(!Y)IJ.write(P0.yellow("[WARN] could not find latest version")),process.exit(0);A=Y}IJ.write(P0.blue(`Updating to version ${A}...
3082
3082
  `)),await zi(A,void 0,(U)=>{B(),IJ.write(P0.dim(`Running: ${U}
@@ -5025,13 +5025,13 @@ function execute() {
5025
5025
  `),A.exit(1);return}let B=$.spec;WW6(A)(B),A.exit(0)}E3();hA();var wv4=k4(M40(),1);function NW6(A,Q){if(!A)return;let $=A[Q];if(!$||typeof $!=="object")return;return $}function qW6(A){let Q=new L4,$=()=>Q.next();return process.once("SIGINT",$),A.pipe(hH0(Q),LO((B)=>{if(B.status==="error")throw Error(`Tool execution error: ${JSON.stringify(B.error)}`);else if(B.status==="rejected-by-user")throw Error("Tool execution was rejected by user");else if(B.status==="cancelled")throw Error("Tool execution was cancelled")}),OO(()=>{process.off("SIGINT",$)}))}async function uv4(A){let{toolName:Q,rawArgs:$,stdinInput:B,only:E,stream:D,threadDeps:J,stdout:U,stderr:Y,exit:Z}=A,F=J.toolService;try{let I=(await n4(F.tools)).find((H)=>H.spec.name===Q);if(!I){Y.write(`Error: Tool '${Q}' not found
5026
5026
  `),Z(1);return}let G=LW6($),V=I.spec,K;if(B)try{K=JSON.parse(B)}catch(H){Y.write(`Error: Invalid JSON input from stdin: ${H instanceof Error?H.message:"Unknown error"}
5027
5027
  `),Z(1);return}else try{K=wW6(G,V.inputSchema,Q)}catch(H){Y.write(`Error: ${H instanceof Error?H.message:"Unknown error"}
5028
- `),Z(1);return}let z=OW6(K,V.inputSchema,Q);if(z){Y.write(`Error: ${z}
5029
- `),Z(1);return}let W=await Ez({toolName:Q,configService:J.configService,toolService:F,mcpService:J.mcpService,skillService:J.skillService}),C=qW6(F.invokeTool(Q,{args:K},W));if(D)await SkA(C.pipe(LO((H)=>{let N={status:H.status};if("result"in H)N.result=H.result;if("error"in H)N.error=H.error;if("progress"in H)N.progress=H.progress;U.write(`${JSON.stringify(N)}
5028
+ `),Z(1);return}let z=OW6(K,V.inputSchema,Q);if(z)Y.write(`Warning: ${z}
5029
+ `);let W=await Ez({toolName:Q,configService:J.configService,toolService:F,mcpService:J.mcpService,skillService:J.skillService}),C=qW6(F.invokeTool(Q,{args:K},W));if(D)await SkA(C.pipe(LO((H)=>{let N={status:H.status};if("result"in H)N.result=H.result;if("error"in H)N.error=H.error;if("progress"in H)N.progress=H.progress;U.write(`${JSON.stringify(N)}
5030
5030
  `)}))),Z(0);else{let H=await PG(C);if(H.status!=="done")throw Error("Expected done status");let N=H.result,w=N;if(E&&N&&typeof N==="object"&&!Array.isArray(N)&&E in N)w=N[E];if(typeof w==="string")U.write(w);else U.write(JSON.stringify(w,null,2));U.write(`
5031
5031
  `),Z(0)}}catch(X){Y.write(`Error invoking tool '${Q}': ${X instanceof Error?X.message:"Unknown error"}
5032
5032
  `),Z(1)}}function wW6(A,Q,$){let B={};for(let[E,D]of Object.entries(A)){let J=NW6(Q.properties,E),U=J?.type;if(Array.isArray(D)){let Y=J?.items?.type??"string";B[E]=D.map((Z)=>zl0(Z,Y,$,E))}else if(U==="array"){let Y=J?.items?.type??"string";B[E]=[zl0(D,Y,$,E)]}else B[E]=zl0(D,U,$,E)}return B}function zl0(A,Q,$,B){if(!Q||Q==="string")return A;if(Q==="number"){let E=Number(A);if(Number.isNaN(E))throw Error(`${$} expects --${B} to be a number, got '${A}'`);return E}if(Q==="boolean"){if(A==="true")return!0;if(A==="false")return!1;if(A!=="true"&&A!=="false")throw Error(`${$} expects --${B} to be a boolean (true/false), got '${A}'`);return Boolean(A)}return A}function uW6(A){return typeof A==="object"&&A!==null&&"type"in A&&typeof A.type==="string"}function Wl0(A,Q){if(!uW6(Q))return null;let $={key:A,type:Q.type,description:Q.description,children:[]};if($.type==="object")$.children=Object.entries(Q.properties??{}).map(([B,E])=>Wl0(A?`${A}.${B}`:B,E)).filter((B)=>B!==null);else if($.type==="array"&&Q.items){if($.type=`array of ${Q.items.type}`,Q.items.type==="object")$.children=Wl0(null,Q.items)?.children??[]}return $}function Mv4(A,Q){let $=" ".repeat(Q),B=A.key?`--${A.key}`:"item",E=A.description?`: ${A.description}`:"",D=`${$}${B} (${A.type})${E}`;if(A.children.length===0)return D;let J=A.children.map((U)=>Mv4(U,Q+1));return[D,...J].join(`
5033
5033
  `)}function MW6(A){if(!A.properties||Object.keys(A.properties).length===0)return"(no parameters)";return Object.keys(A.properties).map(($)=>{let B=A.properties?A.properties[$]:void 0;return Wl0($,B)}).filter(($)=>$!==null).map(($)=>Mv4($,0)).join(`
5034
- `)}function OW6(A,Q,$){try{let E=new wv4.default({allErrors:!0}).compile(Q);if(E(A))return null;let J=E.errors??[];if(J.length===0)return`Invalid input for tool '${$}'`;let U=J.filter((X)=>X.keyword==="required"),Y=J.filter((X)=>X.keyword==="type"),Z=J.filter((X)=>!["required","type"].includes(X.keyword)),F=[];if(U.length>0){let X=U.map((I)=>{let V=I.params?.missingProperty;return V?`--${V}`:"unknown parameter"});F.push(`Missing required ${z1(X.length,"parameter")}: ${X.join(", ")}`)}for(let X of Y){let I=X.instancePath?X.instancePath.replace(/^\//,""):"unknown",G=I?`--${I}`:"parameter",K=X.params?.type??"unknown";F.push(`Parameter ${G} must be of type ${K}`)}for(let X of Z){let I=X.instancePath?X.instancePath.replace(/^\//,""):"unknown",G=I?`--${I}`:"parameter";F.push(`Parameter ${G}: ${X.message}`)}if(Q.properties&&Object.keys(Q.properties).length>0)F.push(`
5034
+ `)}function OW6(A,Q,$){try{let E=new wv4.default({allErrors:!0,validateFormats:!1}).compile(Q);if(E(A))return null;let J=E.errors??[];if(J.length===0)return`Invalid input for tool '${$}'`;let U=J.filter((X)=>X.keyword==="required"),Y=J.filter((X)=>X.keyword==="type"),Z=J.filter((X)=>!["required","type"].includes(X.keyword)),F=[];if(U.length>0){let X=U.map((I)=>{let V=I.params?.missingProperty;return V?`--${V}`:"unknown parameter"});F.push(`Missing required ${z1(X.length,"parameter")}: ${X.join(", ")}`)}for(let X of Y){let I=X.instancePath?X.instancePath.replace(/^\//,""):"unknown",G=I?`--${I}`:"parameter",K=X.params?.type??"unknown";F.push(`Parameter ${G} must be of type ${K}`)}for(let X of Z){let I=X.instancePath?X.instancePath.replace(/^\//,""):"unknown",G=I?`--${I}`:"parameter";F.push(`Parameter ${G}: ${X.message}`)}if(Q.properties&&Object.keys(Q.properties).length>0)F.push(`
5035
5035
  Available parameters:`),F.push(MW6(Q));return F.join(`
5036
5036
  `)}catch(B){return`Failed to validate input for tool '${$}': ${B instanceof Error?B.message:"Unknown validation error"}`}}function Ov4(){return!process.stdin.isTTY&&process.stdin.readable}function LW6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let E=B.slice(2),D=A[$+1];if(D&&!D.startsWith("--")){if(Q[E])if(Array.isArray(Q[E]))Q[E].push(D);else Q[E]=[Q[E],D];else Q[E]=D;$++}}}return Q}function jW6(){let A=process.env.AMP_TOOLBOX;if(!A)return Zy;let Q=A.split(":").map((B)=>B.trim()).filter(Boolean),$=Q.filter((B)=>!Lv4.isAbsolute(B));if($.length>0)throw Error(`AMP_TOOLBOX must contain absolute paths only. Found relative paths: ${$.join(", ")}
5037
5037
  See https://ampcode.com/manual#toolboxes`);return Q[0]||Zy}function jv4(A,Q){let $=A.command("tools").alias("tool").description("Tool management commands");return RW6($,Q),PW6($,Q),TW6($,Q),vW6($,Q),$}function RW6(A,Q){A.command("list").alias("ls").description("List all active tools (including MCP tools)").option("--json","output as a single JSON array").option("--mode <mode>","filter tools by agent mode (default: smart)","smart").action(async($,B)=>{let E=B.optsWithGlobals(),D=await Q(B,E),J=0;await Wv4({json:E.json,isTTY:D.context.isTTY,mode:E.mode,toolService:D.toolService,configService:D.configService,mcpService:D.mcpService,skillService:D.skillService,pluginService:D.pluginService,getThreadEnvironment:D.getThreadEnvironment,serverStatus:D.serverStatus,toolboxService:D.toolboxService,stderr:process.stderr,stdout:process.stdout,exit:(U)=>{J=U}}),await D.asyncDispose(),D.cleanupTerminal(),process.exit(J)})}function PW6(A,Q){A.command("show").argument("<tool>","The tool for which to show details").description("Show details about an active tool").option("--json","output as a single JSON object").option("--mode <mode>","filter tools by agent mode (default: smart)","smart").action(async($,B,E)=>{let D=E.optsWithGlobals(),J=await Q(E,D),U=0,Y=J.toolService;await qv4({toolName:$,json:D.json,isTTY:J.context.isTTY,mode:D.mode,toolService:Y,mcpService:J.mcpService,stdout:process.stdout,exit:(Z)=>{U=Z}}),await J.asyncDispose(),J.cleanupTerminal(),process.exit(U)})}function TW6(A,Q){A.command("make").argument("<tool-name>","A descriptive name like run-tests or build-project").description("Sets up a skeleton tool in your toolbox").option("--force","Overwrite an existing tool if it already exists").option("--bun","Create a Bun/TypeScript tool (default)").option("--zsh","Create a Zsh shell script tool").option("--bash","Create a Bash shell script tool").action(async($,B,E)=>{let D="bun";if(B.zsh)D="zsh";else if(B.bash)D="bash";else if(B.bun)D="bun";try{let J=jW6();await Nv4({fs:Hv4,toolName:$,toolboxDir:J,force:B.force,language:D,stdout:process.stdout,exit:process.exit})}catch(J){process.stdout.write(`${J instanceof Error?J.message:String(J)}
@@ -5051,7 +5051,7 @@ Start Amp from a smaller directory.`};function eX(A,Q){if(!TR4())return;S.debug(
5051
5051
  `)}function yv4(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async($,B)=>{let E=B.optsWithGlobals(),D=await Q(E),J=await cT(D),U=await j4.userDisplayBalanceInfo({},{config:J});if(!U.ok){if(U.error.code==="auth-required")process.stderr.write(P0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(P0.red("Error: ")+U.error.message+`
5052
5052
  `),process.exit(1)}process.stdout.write(await AC6(U.result.displayText)+`
5053
5053
  `),process.exit(0)})}var Mw6=ti.join(oU,"logs","headless.log"),ii0=ti.join(ty,"device-id.json");EI4();async function Ow6(){let A=await Promise.all(lC.map(async(Q)=>{try{return{query:Q,hasConfigs:(await Q.listConfigs()).length>0}}catch($){return S.debug("Failed to detect query-based IDE integration",{ideName:Q.ideName,error:$}),{query:Q,hasConfigs:!1}}}));for(let Q of A)if(Q.hasConfigs)return Q.query;return}function Ff4(){Ow6().then((A)=>{if(A){let Q=p00(A.ideName);if(Q)hC(Q)}})}try{if(process.platform==="win32")await Promise.resolve().then(() => k4(Hv(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){H7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
5054
- `)}function Lw6(A){process.emitWarning=(Q,$,B,E)=>{let D=typeof Q==="string"?Q:Q.message||String(Q),J=$||"Warning",U=!1;A.warn(D,{name:J,code:B})}}function _B(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")k00("dangerouslyAllowAll",Q.dangerouslyAllowAll)}function jw6(A,Q){if(!p9(Q))return;if(!MC(Q.user.email)){if(A.model)throw new VA("The --model flag is only available for Amp employees.",1);k00("internal.model",void 0);return}if(A.model)k00("internal.model",Tw6(A.model))}function Ef4(A){let Q=A.indexOf(":");if(Q===-1)throw new VA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new VA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Rw6(A){if(A===void 0)return;let Q=A.trim();if(sy(Q))return Q;throw new VA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function Pw6(A,Q){if(dC(A))return;throw new VA(`Reasoning effort "${Q}" is not available for ${A} mode.`,1)}function Tw6(A){if(!A.includes("="))return Ef4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let E=B.indexOf("=");if(E===-1)throw new VA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let D=B.slice(0,E).trim(),J=B.slice(E+1).trim();if(!D)throw new VA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!J)throw new VA(`Missing model value for mode "${D}". Expected "${D}=provider:model".`,1);Ef4(J),Q[D]=J}if(Object.keys(Q).length===0)throw new VA("No valid model overrides found in --model flag value.",1);return Q}function LD0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new d30(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new d30(`${Q} must be an integer <= ${$.max}`);return B}function vw6(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}async function _w6(A,Q){let $=await j4.getUserInfo({},{config:A});return $.ok?vw6($.result.features,Q):!1}function Sw6(A){return A!=="pending"}function Kw(A){if(!p9(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function kw6(A){let Q=Kw(A);if(Q)return Q.id;if(gC(A))throw Error(A.error.message);throw Error("unreachable")}function fw6(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function xw6(A){let B=fw6(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new VA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function oi0(A,Q){let $=Ap0(Error(A.error.message));if($.message===q3.networkOffline||$.message===q3.networkTimeout)return xw6(Q);if($.message!==q3.internalBug)return new VA($.message,1,$.suggestion);return new VA(A.error.message.replace(/^Error: /,""),1)}async function yw6(){if(process.versions.bun)return!1;try{return await sY()==="npm"}catch(A){return S.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var Df4=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??eJ,description:`Custom settings file path (overrides the default location ${eJ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${lc})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:D9(),description:(A)=>A?"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:(A)=>A?"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:(A)=>A?"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:"mode",long:"mode",short:"m",type:"option",default:i9.SMART.key,description:`Set the agent mode (${BY({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],Jf4=(A)=>("deprecated"in A)&&A.deprecated===!0,bw6=(A)=>("hidden"in A)&&A.hidden===!0,hw6=(A)=>("default"in A),gw6=(A)=>("default"in A)?A.default:void 0;function Uf4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=Rw6(Q.effort);if($!==void 0){if(ei(Q.mode))Pw6(Q.mode,$)}return $}var mw6="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function ei(A){return Object.values(i9).some((Q)=>Q.key===A)}function dw6(A,Q){if(ei(A))return A;throw new VA(`${Q} does not support plugin-defined agent modes`,1)}function Xf4(A,Q){if(ei(Q))return{agentMode:Q};let $=A.agentModes.list().find((E)=>E.key===Q||E.label===Q);if(!$){let E=BY({}).map((U)=>U.mode).join(", "),D=A.agentModes.list().map((U)=>U.label).join(", "),J=D?` Plugin modes: ${D}.`:"";throw new VA(`Unknown agent mode '${Q}'. Built-in modes: ${E}.${J}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:i9.SMART.key,agent:$.agent,agentModeDisplay:B,pluginAgentModeKey:$.key}}async function cw6(A,Q,$){if(A.getOptionValueSourceWithGlobals("mode")!=="cli")return;return await Q.initialized,Xf4(Q,$)}function pw6(A,Q){let $=Q.args[0],B=Q.commands.map((D)=>D.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let D=B.filter((U)=>$.includes(U)||U.includes($)),J="Run amp --help for a list of available commands.";if(D.length>0)J=`Did you mean: ${D.join(", ")}? Or run amp --help for all commands.`;throw new VA(q3.unknownCommand($),1,J)}}var jD0=g0.file(uw6.homedir()),ni0=process.env.XDG_CONFIG_HOME?g0.file(process.env.XDG_CONFIG_HOME):BA.joinPath(jD0,".config");async function e$(A,Q,$){let B=$?.deferAuth??!1,E=$?.skipToolProviders??!1;$hA("0.0.1780803750-g55245f");let D=y00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:process.cwd(),defaultAmpURL:A.ampURL,homeDir:jD0,userConfigDir:ni0}),J=A.secrets.get("apiKey",A.ampURL),U=eO(D),Y=null,Z=()=>{return},F=new Promise((B0)=>{Z=B0}),X=J.then(async(B0)=>{if(!B0&&!B)await F;return Y??=U.subscribe(()=>{}),n4(U.pipe(Y5(Sw6)))});X.catch(()=>{return}),Gv4(D);let I=await D.getLatest();S.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let B0=await J;if(G=Boolean(B0),S.info("API key lookup before login",{found:Boolean(B0),ampURL:A.ampURL,deferAuth:B}),!B0)if(B)S.info("No API key found, continuing startup with deferred auth");else{fQ.write(`No API key found. Starting login flow...
5054
+ `)}function Lw6(A){process.emitWarning=(Q,$,B,E)=>{let D=typeof Q==="string"?Q:Q.message||String(Q),J=$||"Warning",U=!1;A.warn(D,{name:J,code:B})}}function _B(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")k00("dangerouslyAllowAll",Q.dangerouslyAllowAll)}function jw6(A,Q){if(!p9(Q))return;if(!MC(Q.user.email)){if(A.model)throw new VA("The --model flag is only available for Amp employees.",1);k00("internal.model",void 0);return}if(A.model)k00("internal.model",Tw6(A.model))}function Ef4(A){let Q=A.indexOf(":");if(Q===-1)throw new VA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new VA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Rw6(A){if(A===void 0)return;let Q=A.trim();if(sy(Q))return Q;throw new VA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function Pw6(A,Q){if(dC(A))return;throw new VA(`Reasoning effort "${Q}" is not available for ${A} mode.`,1)}function Tw6(A){if(!A.includes("="))return Ef4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let E=B.indexOf("=");if(E===-1)throw new VA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let D=B.slice(0,E).trim(),J=B.slice(E+1).trim();if(!D)throw new VA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!J)throw new VA(`Missing model value for mode "${D}". Expected "${D}=provider:model".`,1);Ef4(J),Q[D]=J}if(Object.keys(Q).length===0)throw new VA("No valid model overrides found in --model flag value.",1);return Q}function LD0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new d30(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new d30(`${Q} must be an integer <= ${$.max}`);return B}function vw6(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}async function _w6(A,Q){let $=await j4.getUserInfo({},{config:A});return $.ok?vw6($.result.features,Q):!1}function Sw6(A){return A!=="pending"}function Kw(A){if(!p9(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function kw6(A){let Q=Kw(A);if(Q)return Q.id;if(gC(A))throw Error(A.error.message);throw Error("unreachable")}function fw6(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function xw6(A){let B=fw6(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new VA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function oi0(A,Q){let $=Ap0(Error(A.error.message));if($.message===q3.networkOffline||$.message===q3.networkTimeout)return xw6(Q);if($.message!==q3.internalBug)return new VA($.message,1,$.suggestion);return new VA(A.error.message.replace(/^Error: /,""),1)}async function yw6(){if(process.versions.bun)return!1;try{return await sY()==="npm"}catch(A){return S.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var Df4=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??eJ,description:`Custom settings file path (overrides the default location ${eJ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${lc})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:D9(),description:(A)=>A?"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:(A)=>A?"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:(A)=>A?"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:"mode",long:"mode",short:"m",type:"option",default:i9.SMART.key,description:`Set the agent mode (${BY({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],Jf4=(A)=>("deprecated"in A)&&A.deprecated===!0,bw6=(A)=>("hidden"in A)&&A.hidden===!0,hw6=(A)=>("default"in A),gw6=(A)=>("default"in A)?A.default:void 0;function Uf4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=Rw6(Q.effort);if($!==void 0){if(ei(Q.mode))Pw6(Q.mode,$)}return $}var mw6="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function ei(A){return Object.values(i9).some((Q)=>Q.key===A)}function dw6(A,Q){if(ei(A))return A;throw new VA(`${Q} does not support plugin-defined agent modes`,1)}function Xf4(A,Q){if(ei(Q))return{agentMode:Q};let $=A.agentModes.list().find((E)=>E.key===Q||E.label===Q);if(!$){let E=BY({}).map((U)=>U.mode).join(", "),D=A.agentModes.list().map((U)=>U.label).join(", "),J=D?` Plugin modes: ${D}.`:"";throw new VA(`Unknown agent mode '${Q}'. Built-in modes: ${E}.${J}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:i9.SMART.key,agent:$.agent,agentModeDisplay:B,pluginAgentModeKey:$.key}}async function cw6(A,Q,$){if(A.getOptionValueSourceWithGlobals("mode")!=="cli")return;return await Q.initialized,Xf4(Q,$)}function pw6(A,Q){let $=Q.args[0],B=Q.commands.map((D)=>D.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let D=B.filter((U)=>$.includes(U)||U.includes($)),J="Run amp --help for a list of available commands.";if(D.length>0)J=`Did you mean: ${D.join(", ")}? Or run amp --help for all commands.`;throw new VA(q3.unknownCommand($),1,J)}}var jD0=g0.file(uw6.homedir()),ni0=process.env.XDG_CONFIG_HOME?g0.file(process.env.XDG_CONFIG_HOME):BA.joinPath(jD0,".config");async function e$(A,Q,$){let B=$?.deferAuth??!1,E=$?.skipToolProviders??!1;$hA("0.0.1780818304-g58b217");let D=y00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:process.cwd(),defaultAmpURL:A.ampURL,homeDir:jD0,userConfigDir:ni0}),J=A.secrets.get("apiKey",A.ampURL),U=eO(D),Y=null,Z=()=>{return},F=new Promise((B0)=>{Z=B0}),X=J.then(async(B0)=>{if(!B0&&!B)await F;return Y??=U.subscribe(()=>{}),n4(U.pipe(Y5(Sw6)))});X.catch(()=>{return}),Gv4(D);let I=await D.getLatest();S.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let B0=await J;if(G=Boolean(B0),S.info("API key lookup before login",{found:Boolean(B0),ampURL:A.ampURL,deferAuth:B}),!B0)if(B)S.info("No API key found, continuing startup with deferred auth");else{fQ.write(`No API key found. Starting login flow...
5055
5055
  `);let C0=await lw6(A),l=await A.secrets.get("apiKey",A.ampURL);if(S.info("Login flow completed",{success:C0,storedKeyPresent:Boolean(l),ampURL:A.ampURL}),!C0)await oY(),process.exit(1);G=!0,Z()}}{let B0=await D.getLatest(),C0=B0.settings.url,l=B0.secrets.isSet?.[C0];S.info("Config secrets state after login",{configURL:C0,apiKeySet:l?.apiKey??!1})}let V=B?"pending":await X;if(!B)S.info("Server status resolved",{status:"ready",isAuthenticated:p9(V),isError:gC(V),errorMessage:gC(V)?V.error.message:void 0});jw6(Q,V);let K=X.then((B0)=>kw6(B0));K.catch(()=>{return});let z=p9(V),W=!1;if(process.env.AMP_DISABLE_PLUGINS==="1")S.warn("Ignoring AMP_DISABLE_PLUGINS outside development");let C=W?"off":"all",{toolService:H,dispose:N}=TJ4({configService:D}),w=new Map,u=()=>w.clear(),L=new YO0(D,A.settings.getWorkspaceRootPath()),R=IeA({configService:D}),_=UoA({configService:D,trustStore:L,skillMCPServers:R.skillMCPServers,uploadImageAttachments:z,createOAuthProvider:async(B0,C0,l)=>{let i=`${B0}:${C0}`,$0=w.get(i);if($0)return S.debug("Reusing existing OAuth provider for server",{serverName:B0,serverUrl:C0}),$0;S.debug("Creating OAuth provider for server",{serverName:B0,serverUrl:C0});let s=(async()=>{let E0=new tC(A.secrets),Q0=await E0.getClientInfo(B0,C0),G0=l?.scopes??Q0?.scopes,V0=nR4();S.info("OAuth headless mode check",{useHeadless:V0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:fQ.isTTY});let w0;if(V0)w0=A.executeMode?iR4():lR4(B0);let I0=new Aw0({storage:E0,serverName:B0,serverUrl:C0,clientId:l?.clientId??Q0?.clientId,clientSecret:l?.clientSecret??Q0?.clientSecret,authUrl:l?.authUrl??Q0?.authUrl,tokenUrl:l?.tokenUrl??Q0?.tokenUrl,scopes:G0,headlessAuthHandler:w0});return S.debug("OAuth provider created",{serverName:B0,serverUrl:C0,hasManualClientId:!!(l?.clientId??Q0?.clientId),willUseDCR:!(l?.clientId??Q0?.clientId),scopes:G0,headlessMode:V0,executeMode:A.executeMode}),I0})();return w.set(i,s),s}}),P=Uj0({configService:D,spawn:MQ0}),f=Q.headless?RT4():void 0,h=f??new kE0({configService:D}),x=h instanceof kE0?h:void 0;if(x)x.pluginExecutorKind="local";let v=new H4(null),k=null,c=z&&!W?[..._T4(I.settings)?[{name:"permissions",entryPoint:Dl0}]:[],{name:"thread-visibility",entryPoint:fT4(D,()=>X.then(Kw),()=>k,(B0)=>{k=B0}),alwaysLoad:!0}]:[],d=wO0({configService:D,platform:h,loadGlobalPlugins:Np0(D),pluginFilter:C,activeThread$:v,internalPlugins:c}),b=UrA(d),p=[_,P,b],n;if(E)n=new Map;else if(A.executeMode){let B0=await b04({toolService:H,providers:p,initialTimeout:15000});n=B0.registrations;for(let[C0,l]of B0.initErrors)S.warn(`${C0} provider initialization slow or failed:`,l)}else n=Yj0({toolService:H,providers:p});if(Q.jetbrains)hC("JetBrains");else if(Q.ide&&EG4())hC("VS Code");else if(Q.ide&&DG4())hC("Neovim");else if(Q.ide&&A.executeMode)Ff4();if(A.executeMode)BhA(!0);let a,X0=S3.status.pipe(tA((B0)=>Boolean(B0.connected&&B0.authenticated&&B0.ideName&&DgA(B0.ideName))),FQ()).subscribe((B0)=>{if(B0){if(!a)a=H.registerTool(y04)}else a?.dispose(),a=void 0}),t;if(!A.executeMode){let B0=await A.settings.get("fuzzy.alwaysIncludePaths")??[];t=new IE0(process.cwd(),{alwaysIncludePaths:B0},!0)}else t=new class extends IE0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let Z0=Yg(D);S.info("Starting Amp background services");let K0=new Kl0,R0={configService:D,toolService:H,mcpService:_,skillService:R,toolboxService:P,trustStore:L,threadRemote:Z0,setThreadMeta:Z0.setThreadMeta,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:t,terminal:K0,pluginService:d,pluginPlatform:x,headlessPluginPlatform:f,activeThread$:v,serverStatus:V,serverStatusPromise:X,viewerUserIDPromise:K,hasAPIKeyAtStartup:G,consumeDraftNewThreadVisibility:()=>{let B0=k;return k=null,B0}};return{...R0,async asyncDispose(){if(R0.mcpService.hasAuthenticatingClients())S.info("Waiting for OAuth authentication to complete before exit..."),await R0.mcpService.waitForAuthentication();for(let B0 of n.values())B0.dispose();await R0.mcpService.dispose(),u(),R0.configService.unsubscribe(),Y?.unsubscribe(),N(),R0.fuzzyServer.dispose(),R0.settingsStorage[Symbol.dispose](),X0.unsubscribe(),a?.dispose(),await R0.pluginService.dispose()}}}async function lw6(A){if(!A.executeMode){if(!await vE0("Would you like to log in to Amp? [(y)es, (n)o]: "))return fQ.write(`Login cancelled. Run the command again to retry.
5056
5056
  `),!1}return await If4(A)}async function If4(A){let Q=Hw6(32).toString("hex"),$=await tp0(A.ampURL,Q),B=new AbortController;try{await aJ($,B.signal)}catch(D){S.error("Error opening browser",{error:D})}let E=await tp0(A.ampURL,Q,!1);fQ.write(`If your browser does not open automatically, visit:
5057
5057
 
@@ -5059,7 +5059,7 @@ ${P0.blue.bold(E)}
5059
5059
 
5060
5060
  `);try{return await ZT4(A.ampURL,Q,A.secrets,B),fQ.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(D){return S.error("Login failed",{error:D}),H7.write(`
5061
5061
  Login failed: ${D instanceof Error?D.message:String(D)}
5062
- `),!1}}async function iw6(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new VA("No Amp API key found. Run `amp login` first.",1);let E=Cw6("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((D,J)=>{E.on("error",J),E.on("close",(U)=>D(U??1))})}function nw6(A){let Q=new MX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, unlisted, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)Az(),process.exit(0);let N=H.originalError??H;Mj4(N)}),oI4(Q,{version:"0.0.1780803750-g55245f",buildTimestamp:"2026-06-07T03:47:39.209Z",buildType:"release"}),Q.addHelpText("after",AP4()),Q.configureHelp({formatHelp:QP4}),Q.command("logout").description("Log out by removing stored API key").action(async(H,N)=>{let w=N.optsWithGlobals(),u=await nQ(w);await Eu6(u)}),Q.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,N)=>{let w=N.optsWithGlobals(),u=await nQ(w);await Bu6(u,await Zl0(w,u.settings))}),nT4(Q,nQ);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...H)=>{let N=H.find((R)=>typeof R==="object"&&R!==null&&typeof R.optsWithGlobals==="function")??B,w=H.filter((R)=>R!==N).flatMap((R)=>Array.isArray(R)?R:typeof R==="string"?[R]:[]),u=N.optsWithGlobals(),L=await nQ(u);await iw6(L.ampURL,L.secrets,w),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await nQ(u);await SR4(H??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit [args...]",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements Git signing helper interfaces. Used inside sandboxes for commit signing.").allowUnknownOption(!0).allowExcessArguments(!0).action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await nQ(u);await fR4(L,H),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(H)=>{await SP4({raw:H.raw===!0}),process.exit(process.exitCode??0)}),_v4(Q,{createContext:nQ,createThreadDependencies:e$,initializeCLIOverrides:_B}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
5062
+ `),!1}}async function iw6(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new VA("No Amp API key found. Run `amp login` first.",1);let E=Cw6("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((D,J)=>{E.on("error",J),E.on("close",(U)=>D(U??1))})}function nw6(A){let Q=new MX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, unlisted, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)Az(),process.exit(0);let N=H.originalError??H;Mj4(N)}),oI4(Q,{version:"0.0.1780818304-g58b217",buildTimestamp:"2026-06-07T07:50:20.537Z",buildType:"release"}),Q.addHelpText("after",AP4()),Q.configureHelp({formatHelp:QP4}),Q.command("logout").description("Log out by removing stored API key").action(async(H,N)=>{let w=N.optsWithGlobals(),u=await nQ(w);await Eu6(u)}),Q.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,N)=>{let w=N.optsWithGlobals(),u=await nQ(w);await Bu6(u,await Zl0(w,u.settings))}),nT4(Q,nQ);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...H)=>{let N=H.find((R)=>typeof R==="object"&&R!==null&&typeof R.optsWithGlobals==="function")??B,w=H.filter((R)=>R!==N).flatMap((R)=>Array.isArray(R)?R:typeof R==="string"?[R]:[]),u=N.optsWithGlobals(),L=await nQ(u);await iw6(L.ampURL,L.secrets,w),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await nQ(u);await SR4(H??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit [args...]",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements Git signing helper interfaces. Used inside sandboxes for commit signing.").allowUnknownOption(!0).allowExcessArguments(!0).action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await nQ(u);await fR4(L,H),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(H)=>{await SP4({raw:H.raw===!0}),process.exit(process.exitCode??0)}),_v4(Q,{createContext:nQ,createThreadDependencies:e$,initializeCLIOverrides:_B}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
5063
5063
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(H,N,w)=>{if(H&&N.apply)throw new VA("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let u=N.apply??H;if(!u||u.trim().length===0)fQ.write(`live-sync watches a v2 thread and mirrors its live changes locally. Use --apply <thread-id> to materialize the current snapshot once and exit.
5064
5064
 
5065
5065
  `),w.outputHelp(),process.exit(0);let L=D3(u)??B8(u),R=w.optsWithGlobals(),_=await nQ(R);_B(w,R);let P=await e$(_,R),f=!1;try{if(N.checkout&&N.skipCheckout)throw new VA("Choose either --checkout or --skip-checkout, not both.",1);if(gC(P.serverStatus))throw oi0(P.serverStatus,_.ampURL);await sP4({ampURL:_.ampURL,threadId:L,configService:P.configService,threadSnapshotReader:{get:P.threadRemote.getThread},apiKey:process.env.AMP_API_KEY,applyOnce:typeof N.apply==="string",checkoutMode:N.checkout?"always":N.skipCheckout?"never":"prompt",promptForYesNo:vE0}),f=!0}finally{if(await P.asyncDispose(),f)process.exit(0)}});let E=async(H,N,w)=>{y00({storage:N.settings,secretStorage:N.secrets,workspaceRoot:process.cwd(),defaultAmpURL:N.ampURL,homeDir:jD0,userConfigDir:ni0});let u={...N,executeMode:!1};await ai0(u,{...H,openThreadSwitcher:!0},w)},D=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").option("--limit <number>","Maximum number of threads to return",(H)=>LD0(H,"--limit",{min:1,max:500})).option("--offset <number>","Number of threads to skip",(H)=>LD0(H,"--offset",{min:0})).action(async(H,N)=>{let w=N.optsWithGlobals(),u=await nQ(w);await Zf4(w,u,N)});D.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, unlisted, workspace, group)").action(async(H,N)=>{let w=N.optsWithGlobals(),u=await nQ(w);await Wu6(w,u,N)}),D.command("continue [threadIDOrURLs...]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly. When multiple thread are given, all are resumed and the first is shown in the foreground.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await nQ(u),R=Array.isArray(H)?H:[];if(N.pick)H7.write(`${P0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -5084,8 +5084,8 @@ ${_}
5084
5084
 
5085
5085
  `)},async input(){return},async confirm(){return!1},async select(){return},async ask(){return{result:"uncertain",probability:0.5,reason:"AI not available"}}},loadGlobalPlugins:Np0(u),pluginFilter:process.env.PLUGINS??"all"}),asyncDispose:async()=>{}}}),eT4(Q,async(H)=>{let N=H.optsWithGlobals(),w=await nQ(N);_B(H,N);let u=await e$(w,N),L=await u.secretStorage.get("apiKey",w.ampURL);if(!L)throw await u.asyncDispose(),new VA("API key required. Please run `amp login` first.",1);return{configService:u.configService,actorOptions:{apiKey:L,ampURL:w.ampURL,workspaceRoot:process.cwd(),dependencies:u},cleanupTerminal:Az,asyncDispose:u.asyncDispose.bind(u)}}),$v4(Q,async(H)=>{let N=H.optsWithGlobals(),w=await nQ(N);_B(H,N);let u=await e$(w,N),L=await u.secretStorage.get("apiKey",w.ampURL);if(!L)throw await u.asyncDispose(),new VA("API key required. Please run `amp login` first.",1);return{configService:u.configService,actorOptions:{apiKey:L,ampURL:w.ampURL,workspaceRoot:process.cwd(),dependencies:u},cleanupTerminal:Az,asyncDispose:u.asyncDispose.bind(u)}}),Fv4(Q,async(H)=>{let N=H.optsWithGlobals(),w=await nQ(N);_B(H,N);let u=await e$(w,N);return{settings:w.settings,configService:u.configService,skillService:u.skillService,asyncDispose:u.asyncDispose.bind(u)}}),uT4(Q,async(H)=>{let N=H.optsWithGlobals();return await nQ(N)}),KT4(Q,async(H)=>{let N=await nQ(H);return{settings:N.settings,secretStorage:N.secrets,getThreadDeps:async(w)=>{_B(w,H);let u=await e$(N,H);return{mcpService:u.mcpService,settings:N.settings,asyncDispose:u.asyncDispose.bind(u)}}}}),QI4(Q,nQ),zj4(Q,async(H)=>rH0(await Fl0(H))),yv4(Q,nQ),Xv4(Q,nQ);function Z(H,N,w){let L=typeof H.description==="string"?H.description:w===void 0?H.description(!0):H.description(w),R=new sD(N,L),_=gw6(H);if(_)R.default(_);if(R.hidden=bw6(H)||Jf4(H),"choices"in H&&Array.isArray(H.choices))if("hiddenChoices"in H){let P=[...H.choices],f=Array.isArray(H.hiddenChoices)?H.hiddenChoices:[],h=new Set([...P,...f]);R.argParser((x)=>{if(!h.has(x))throw new d30(`Allowed choices are ${P.join(", ")}.`);return x})}else R.choices([...H.choices]);return R}for(let H of Df4){switch(H.type){case"flag":{Q.addOption(Z(H,`--${H.long}`)),Q.addOption(Z(H,`--no-${H.long}`,!1));break}case"switch":{Q.addOption(Z(H,`--${H.long}`,!0));break}case"optional-option":{Q.addOption(Z(H,`${"short"in H?`-${H.short}, `:""}--${H.long} [value]`));break}default:{Q.addOption(Z(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}if("aliases"in H&&Array.isArray(H.aliases))for(let N of H.aliases){let w=new sD(`--${N}`,H.description);w.hidden=!0,w.implies({[H.name]:!0}),Q.addOption(w)}}Q.hook("preAction",(H,N)=>{let w=N.optsWithGlobals();if(w.takeMeBack)J6(mw6);if(w.archive&&!process.env.AMP_SDK_VERSION)J6("--archive is now the default and has been removed. Rerun without --archive. (If you want to not archive, use --no-archive-after-execute.)")});let F=new sD("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);Q.addOption(F);let X=new sD("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp(!0);Q.addOption(X);let I=new sD("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);Q.addOption(I);let G=new sD("--stream-json-thinking","Include thinking blocks in stream JSON output (non-Claude Code extension). Implies --stream-json.").default(!1);Q.addOption(G);let V=new sD("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);Q.addOption(V);let K=new sD("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);Q.addOption(K);let z=new sD("--no-archive-after-execute","When used with --execute on a new thread, leave the thread unarchived after the command finishes.");Q.addOption(z);let W=new sD("--archive").default(!1).hideHelp(!0);Q.addOption(W);let C=new sD("-l, --label <label>","When used with --execute, add a label to the thread. Repeat the flag for multiple labels.").argParser((H,N)=>{if(N===void 0)return[H];return[...N,H]});return Q.addOption(C),Q.action(async(H,N)=>{let w=H,u=await nQ(w);if(Object.keys(w).forEach((L)=>{let R=Df4.find((_)=>_.name===L);if(R&&Jf4(R)&&!hw6(R))H7.write(P0.yellow(`Warning: '--${L}' flag is deprecated
5086
5086
  `))}),N.args.length>0)pw6(u,N);await ai0(u,w,N)}),zP4(Q),Q}async function Gf4(A,Q){await eD(($)=>gP($,A,Q))}async function aw6(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await Xl0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await Xl0()).trimEnd(),stdinInput:null}}function ow6(A,Q,$){if(A.remote&&!Q)throw new VA("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(A.streamJson&&!Q)throw new VA("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new VA("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new VA("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new VA("The --stats and --stream-json flags are mutually exclusive output formats",1,'Use one or the other: amp --execute "your message" --stats OR amp --execute "your message" --stream-json');if(A.stats&&!Q)throw new VA("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archiveAfterExecute===!1&&!Q)throw new VA("The --no-archive-after-execute flag requires --execute mode",1,'Use: amp --execute "your message" --no-archive-after-execute');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new VA("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&$===""&&!A.streamJsonInput&&!A.headless)throw new VA("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
5087
- Or pipe via stdin: echo "your message" | amp --execute`)}function rw6(){TdA([f00.parse({tool:"*",action:"allow"})]),EdA({bypass:!0})}function sw6(A){if(A.threadId&&!k7(A.threadId))delete A.threadId}async function ai0(A,Q,$){if(Q.headless)return tw6(A,Q,$);let B=await e$(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new VA("Cannot use --show-welcome and --hide-welcome together",1);let E=!A.executeMode&&await yw6();return rw6(),sw6(Q),ew6(A,Q,$,B,{showNpmMigrationWelcome:E})}async function tw6(A,Q,$){let B=(z,W)=>{let C=Number(process.hrtime.bigint()-W)/1e6,H=BI4();S.info("Startup phase",{phase:z,phaseMs:Math.round(C),sinceMainMs:H===null?void 0:Math.round(H)})};_B($,Q);let E=process.hrtime.bigint(),D=await e$(A,Q);B("runMainThread:createThreadDependencies",E);let{serverStatus:J}=D;if(gC(J))throw oi0(J,A.ampURL);let U=p9(J)?J:null,Y=U?.user.email,Z=Kw(J),F=qi(Q,Z);if(F instanceof Error)J6(F.message);if(U&&ei(Q.mode)&&!O00(Q.mode,Y))throw new VA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);Uy0();let X=await D.secretStorage.get("apiKey",A.ampURL);if(!X)throw new VA("API key required for headless mode. Please run `amp login` first.",1);let I=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(I&&!k7(I))throw new VA(`Invalid thread ID: ${I}`,1);let G=I?void 0:await Ku6({dependencies:D,apiKey:X,visibility:F??void 0}),V=I??G?.threadId;if(!V)throw new VA("Failed to resolve headless thread ID",1);let K=await sR4(V);if(K.status==="already-running")await D.asyncDispose(),await oY(),process.exit(0);try{await hR4({ampURL:A.ampURL,apiKey:X,workspaceRoot:process.cwd(),threadId:V,ownerUserId:G?.ownerUserId,threadVersion:G?.threadVersion,agentMode:G?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized,D.pluginService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,setActiveThreadID:(z)=>D.activeThread$.next(z)})}finally{await K.release(),await D.asyncDispose()}await oY(),process.exit(0)}async function ew6(A,Q,$,B,E){let{userInput:D,stdinInput:J}=await aw6(Q),U=!!Q.streamJson||!!Q.streamJsonThinking;ow6({...Q,streamJson:U},A.executeMode,D),_B($,Q),FI4(),Uy0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),F=Q.observe?D3(Q.observe)??B8(Q.observe):void 0,X=await B.serverStatusPromise;if(gC(X))throw oi0(X,A.ampURL);let I=Kw(X),G=()=>_w6(B.configService,AfA.V2_LOCAL_THREAD_CHANGES),V=qi(Q,I);if(V instanceof Error)J6(V.message);if(A.executeMode&&Q.remote){if(!ei(Q.mode))throw new VA("Remote execute mode does not support plugin-defined agent modes",1);if(!p9(X)||!MC(X.user.email))throw new VA("Remote execute mode is only available for Amp employees",1);await gT4(D,J,B.configService,Q.mode),await B.asyncDispose(),await oY(),process.exit(0)}let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let N=await r90(A.settings,process.cwd(),I,V);if(N instanceof Error)J6(N.message);return N})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new VA("API key required. Please run `amp login` first.",1);let C=p9(X)&&MC(X.user.email);if(A.executeMode){if(Z.length>1)throw new VA("Execute mode can only resume one thread.",1);HT4(B.mcpService,A.settings);try{await B.pluginService.initialized;let H=Xf4(B.pluginService,Q.mode),N=Uf4($,Q),w=await rN(),u=Y?N:Ny0({agentMode:H.agentMode,explicitEffort:N,sessionState:w}),L=Y?void 0:U50(await hP(B.configService),{agentMode:H.agentMode,explicitEffort:N,sessionState:w}),R=Y?void 0:await z(),{threadID:_}=await dT({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:D,stdinInput:J,stats:!!Q.stats,streamJson:U,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:H.agentMode,reasoningEffort:H.agent?void 0:u,agent:H.agent,labels:Q.label,initialThreadID:Y,initialThreadMeta:R,initialSettings:L});if(await Gf4(_,"execute"),Q.archive||!Y&&Q.archiveAfterExecute!==!1)await B.threadRemote.archiveThread(_,!0)}finally{await B.asyncDispose()}await oY(),process.exit(0)}else{let H=Uf4($,Q),N=await cw6($,B.pluginService,Q.mode),w=E.showNpmMigrationWelcome?"npm-migration":"intro",u=yp0("0.0.1780803750-g55245f",B.settingsStorage,{startDelayMs:3000}),L=new ep0(B.mcpService,A.settings.getWorkspaceRootPath()),R=Yg(B.configService),_=new Hl0(B.fuzzyServer),P=process.cwd();await jP4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??Z7(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:f})=>bT({workspaceRoot:P},f),canUseV2LocalThreadChanges:G,completionBuilder:_,updateService:u,workspaceRoot:P,listThreads:()=>R.listThreads(),getThreadFromServer:(f)=>R.getThread(f),getThreadTail:async(f,h)=>{let x=await j4.getThreadTail({thread:f,limit:h},{config:B.configService});if(!x.ok){if(x.error.code==="thread-not-found")return null;throw Error(x.error.message??x.error.code)}return{...x.result.thread.data,messages:x.result.messages}},toolboxes:B.toolboxService.toolboxes,isInternalUser:C,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:L,setActiveThreadID:(f)=>B.activeThread$.next(f),dispose:()=>{return L.dispose(),u.dispose(),B.asyncDispose()}},{initialThreadIDs:F?[F]:Z,initialUserInput:D||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?Ff4:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,hideWelcome:!!Q.hideWelcome,showWelcome:Q.showWelcome,welcomeVariant:w,initialAgentMode:N?.agentMode,initialPluginAgentModeKey:N?.pluginAgentModeKey,initialReasoningEffort:H}),process.exit(0)}}async function nQ(A){if(S.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)H7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5088
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await IoA({get:async(U)=>{if(U!==Hh)return;try{let Y=await qw6(ii0,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(U,Y)=>{if(U!==Hh)return;await Nw6(ti.dirname(ii0),{recursive:!0}),await ww6(ii0,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:t40()});EhA(B);let E=await Fl0({...A,workspaceTrust:{current:!0,changes:Fy},getHook:process.env.AMP_URL?(U,Y)=>{if(U==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let U=await WT4(A.mcpConfig);E=CT4(E,U)}let D=ti.dirname(E.getSettingsFilePath());kJ4(ty,D),E=rH0(E);let J=await E.get("url","admin")??await E.get("url","global");if(!J)J=S8;if(S.info("Resolved Amp URL",{ampURL:J,settingsFile:E.getSettingsFilePath(),workspaceRoot:E.getWorkspaceRootPath()}),!iO(J))S.info("Targeting custom Amp server",{ampURL:J});return{executeMode:Q,isTTY:$,ampURL:J,settings:E,secrets:Bv4(await Zl0(A,E))}}function Au6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let D=B.slice(2).replace(/-([a-z])/g,(U,Y)=>Y.toUpperCase()),J=A[$+1];if(J&&!J.startsWith("--"))Q[D]=J,$++}}return Q}function Qu6(A,Q){let $=A.includes("--headless")||A.some((E)=>E.startsWith("--headless=")),B=ti.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?Mw6:lc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function $u6(){$I4();let A=Au6(process.argv),Q=Qu6(process.argv,A),$=XI4(Q);oB0("silent");let B=process.argv.includes("--no-color"),E=process.argv.includes("--color"),D=process.stdout.isTTY&&process.stderr.isTTY;if(B||!E&&!D)P0.level=0;if(Lw6(S),S.info("Starting Amp CLI.",{version:"0.0.1780803750-g55245f",buildTimestamp:"2026-06-07T03:47:39.209Z"}),process.platform==="win32"&&tN())XP4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new VA(q3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await nw6($).parseAsync(process.argv)}_J4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await $u6().catch(s90)});async function Bu6(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),fQ.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5087
+ Or pipe via stdin: echo "your message" | amp --execute`)}function rw6(){TdA([f00.parse({tool:"*",action:"allow"})]),EdA({bypass:!0})}function sw6(A){if(A.threadId&&!k7(A.threadId))delete A.threadId}async function ai0(A,Q,$){if(Q.headless)return tw6(A,Q,$);let B=await e$(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new VA("Cannot use --show-welcome and --hide-welcome together",1);let E=!A.executeMode&&await yw6();return rw6(),sw6(Q),ew6(A,Q,$,B,{showNpmMigrationWelcome:E})}async function tw6(A,Q,$){let B=(z,W)=>{let C=Number(process.hrtime.bigint()-W)/1e6,H=BI4();S.info("Startup phase",{phase:z,phaseMs:Math.round(C),sinceMainMs:H===null?void 0:Math.round(H)})};_B($,Q);let E=process.hrtime.bigint(),D=await e$(A,Q);B("runMainThread:createThreadDependencies",E);let{serverStatus:J}=D;if(gC(J))throw oi0(J,A.ampURL);let U=p9(J)?J:null,Y=U?.user.email,Z=Kw(J),F=qi(Q,Z);if(F instanceof Error)J6(F.message);if(U&&ei(Q.mode)&&!O00(Q.mode,Y))throw new VA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);Uy0();let X=await D.secretStorage.get("apiKey",A.ampURL);if(!X)throw new VA("API key required for headless mode. Please run `amp login` first.",1);let I=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(I&&!k7(I))throw new VA(`Invalid thread ID: ${I}`,1);let G=I?void 0:await Ku6({dependencies:D,apiKey:X,visibility:F??void 0}),V=I??G?.threadId;if(!V)throw new VA("Failed to resolve headless thread ID",1);let K=await sR4(V);if(K.status==="already-running")await D.asyncDispose(),await oY(),process.exit(0);try{await hR4({ampURL:A.ampURL,apiKey:X,workspaceRoot:process.cwd(),threadId:V,ownerUserId:G?.ownerUserId,threadVersion:G?.threadVersion,agentMode:G?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized,D.pluginService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,setActiveThreadID:(z)=>D.activeThread$.next(z)})}finally{await K.release(),await D.asyncDispose()}await oY(),process.exit(0)}async function ew6(A,Q,$,B,E){let{userInput:D,stdinInput:J}=await aw6(Q),U=!!Q.streamJson||!!Q.streamJsonThinking;ow6({...Q,streamJson:U},A.executeMode,D),_B($,Q),FI4(),Uy0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),F=Q.observe?D3(Q.observe)??B8(Q.observe):void 0,X=await B.serverStatusPromise;if(gC(X))throw oi0(X,A.ampURL);let I=Kw(X),G=()=>_w6(B.configService,AfA.V2_LOCAL_THREAD_CHANGES),V=qi(Q,I);if(V instanceof Error)J6(V.message);if(A.executeMode&&Q.remote){if(!ei(Q.mode))throw new VA("Remote execute mode does not support plugin-defined agent modes",1);if(!p9(X)||!MC(X.user.email))throw new VA("Remote execute mode is only available for Amp employees",1);await gT4(D,J,B.configService,Q.mode),await B.asyncDispose(),await oY(),process.exit(0)}let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let N=await r90(A.settings,process.cwd(),I,V);if(N instanceof Error)J6(N.message);return N})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new VA("API key required. Please run `amp login` first.",1);let C=p9(X)&&MC(X.user.email);if(A.executeMode){if(Z.length>1)throw new VA("Execute mode can only resume one thread.",1);HT4(B.mcpService,A.settings);try{await B.pluginService.initialized;let H=Xf4(B.pluginService,Q.mode),N=Uf4($,Q),w=await rN(),u=Y?N:Ny0({agentMode:H.agentMode,explicitEffort:N,sessionState:w}),L=Y?void 0:U50(await hP(B.configService),{agentMode:H.agentMode,explicitEffort:N,sessionState:w}),R=Y?void 0:await z(),{threadID:_}=await dT({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:D,stdinInput:J,stats:!!Q.stats,streamJson:U,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:H.agentMode,reasoningEffort:H.agent?void 0:u,agent:H.agent,labels:Q.label,initialThreadID:Y,initialThreadMeta:R,initialSettings:L});if(await Gf4(_,"execute"),Q.archive||!Y&&Q.archiveAfterExecute!==!1)await B.threadRemote.archiveThread(_,!0)}finally{await B.asyncDispose()}await oY(),process.exit(0)}else{let H=Uf4($,Q),N=await cw6($,B.pluginService,Q.mode),w=E.showNpmMigrationWelcome?"npm-migration":"intro",u=yp0("0.0.1780818304-g58b217",B.settingsStorage,{startDelayMs:3000}),L=new ep0(B.mcpService,A.settings.getWorkspaceRootPath()),R=Yg(B.configService),_=new Hl0(B.fuzzyServer),P=process.cwd();await jP4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??Z7(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:f})=>bT({workspaceRoot:P},f),canUseV2LocalThreadChanges:G,completionBuilder:_,updateService:u,workspaceRoot:P,listThreads:()=>R.listThreads(),getThreadFromServer:(f)=>R.getThread(f),getThreadTail:async(f,h)=>{let x=await j4.getThreadTail({thread:f,limit:h},{config:B.configService});if(!x.ok){if(x.error.code==="thread-not-found")return null;throw Error(x.error.message??x.error.code)}return{...x.result.thread.data,messages:x.result.messages}},toolboxes:B.toolboxService.toolboxes,isInternalUser:C,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:L,setActiveThreadID:(f)=>B.activeThread$.next(f),dispose:()=>{return L.dispose(),u.dispose(),B.asyncDispose()}},{initialThreadIDs:F?[F]:Z,initialUserInput:D||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?Ff4:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,hideWelcome:!!Q.hideWelcome,showWelcome:Q.showWelcome,welcomeVariant:w,initialAgentMode:N?.agentMode,initialPluginAgentModeKey:N?.pluginAgentModeKey,initialReasoningEffort:H}),process.exit(0)}}async function nQ(A){if(S.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)H7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5088
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await IoA({get:async(U)=>{if(U!==Hh)return;try{let Y=await qw6(ii0,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(U,Y)=>{if(U!==Hh)return;await Nw6(ti.dirname(ii0),{recursive:!0}),await ww6(ii0,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:t40()});EhA(B);let E=await Fl0({...A,workspaceTrust:{current:!0,changes:Fy},getHook:process.env.AMP_URL?(U,Y)=>{if(U==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let U=await WT4(A.mcpConfig);E=CT4(E,U)}let D=ti.dirname(E.getSettingsFilePath());kJ4(ty,D),E=rH0(E);let J=await E.get("url","admin")??await E.get("url","global");if(!J)J=S8;if(S.info("Resolved Amp URL",{ampURL:J,settingsFile:E.getSettingsFilePath(),workspaceRoot:E.getWorkspaceRootPath()}),!iO(J))S.info("Targeting custom Amp server",{ampURL:J});return{executeMode:Q,isTTY:$,ampURL:J,settings:E,secrets:Bv4(await Zl0(A,E))}}function Au6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let D=B.slice(2).replace(/-([a-z])/g,(U,Y)=>Y.toUpperCase()),J=A[$+1];if(J&&!J.startsWith("--"))Q[D]=J,$++}}return Q}function Qu6(A,Q){let $=A.includes("--headless")||A.some((E)=>E.startsWith("--headless=")),B=ti.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?Mw6:lc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function $u6(){$I4();let A=Au6(process.argv),Q=Qu6(process.argv,A),$=XI4(Q);oB0("silent");let B=process.argv.includes("--no-color"),E=process.argv.includes("--color"),D=process.stdout.isTTY&&process.stderr.isTTY;if(B||!E&&!D)P0.level=0;if(Lw6(S),S.info("Starting Amp CLI.",{version:"0.0.1780818304-g58b217",buildTimestamp:"2026-06-07T07:50:20.537Z"}),process.platform==="win32"&&tN())XP4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new VA(q3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await nw6($).parseAsync(process.argv)}_J4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await $u6().catch(s90)});async function Bu6(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),fQ.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5089
5089
  `);else if(!iO(A.ampURL))fQ.write(`Logging in to ${new URL(A.ampURL).hostname}
5090
5090
  `);let B=process.env.AMP_API_KEY;if(B)fQ.write(`API key found in environment variable, storing...
5091
5091
  `),await Q.set("apiKey",B,A.ampURL),fQ.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1780803750-g55245f",
3
+ "version": "0.0.1780818304-g58b217",
4
4
  "description": "Renamed to @ampcode/cli - see https://ampcode.com/news/npm-package-changes",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
@@ -8,7 +8,7 @@
8
8
  "amp": "node_modules/@ampcode/cli/bin/amp.exe"
9
9
  },
10
10
  "dependencies": {
11
- "@ampcode/cli": "0.0.1780803750-g55245f"
11
+ "@ampcode/cli": "0.0.1780818304-g58b217"
12
12
  },
13
13
  "files": [
14
14
  "dist/main.js",