@sourcegraph/amp 0.0.1777351004-g64ae1a → 0.0.1777352624-g869aa9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +9 -9
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4642,12 +4642,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,X(Error(`Failed to spawn brew: ${K.message}`))}
|
|
|
4642
4642
|
${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))W+=`
|
|
4643
4643
|
|
|
4644
4644
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4645
|
-
npm install -g @sourcegraph/amp`;X(Error(W))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}l0();l0();WI();async function QK0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Ke(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],W=X.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return _.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(F){return _.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var Zn5="https://static.ampcode.com/cli/cli-version.txt";async function BK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${Zn5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=Ke(A,J),Z=Y<0;return _.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return _.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Fn5=604800000;function $t4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>Fn5)return{ageMs:B};return null}function Ke(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function x81(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?xU(B):void 0;return{sha:$,age:J}}catch{return null}}w1();l0();import{readFile as Xn5,realpath as Dn5}from"node:fs/promises";import{homedir as Gn5}from"node:os";import{dirname as Jt4,join as f81}from"node:path";async function Yt4(A){switch(A){case"binary":case"brew":return Vn5(De());case"npm":case"pnpm":case"yarn":case"bun":return Un5();case"bootstrap":return Kn5()}}async function Vn5(A){let Q=await TG(A,["--version"],5000);if(Q.reason!=="success")return _.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Un5(){try{let A=process.argv[1];if(!A)return null;let Q=await Dn5(A),B=Jt4(Jt4(Q));return await Zt4(f81(B,"package.json"))}catch(A){return _.debug("failed to read installed version from package.json",{error:A}),null}}async function Kn5(){try{let A=process.env.AMP_HOME??f81(Gn5(),".amp");return await Zt4(f81(A,"package","package.json"))}catch(A){return _.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Zt4(A){let Q=await Xn5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return _.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var En5=3600000,Wn5=5000;function b81(A,Q,B={}){let $=new FA,J=$.pipe(Q6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??En5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=new KD().scoped("update");if(Y>0){if(await yU(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await Hn5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await yU(Wn5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let W=Math.min(K,E);await yU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function Hn5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await eU0(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await BK0(A);else{let V=await IP();X=await QK0(A,V)}if(!(X.latestVersion&&X.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await Yt4(Z);if(V&&Ke(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Ke(A,V)<0){let U=await uH(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(X.currentVersionAge!==void 0&&X.latestVersionAge!==void 0){let V=X.currentVersionAge-X.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:X.currentVersionAge,latestVersionAge:X.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==De()){if(B.debug("non-standard binary path, showing warning"),!G())D("update-available-unrecognized-path");return J}if(Y==="warn"){if(!G())D("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!G())D("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!G())D("update-available");return J}try{await Ue(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await uH(X.latestVersion),U={from:X.currentVersion,to:X.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}WI();import{stderr as SG}from"node:process";function Ft4(A){let Q=new hI().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($)=>{await M81($.force||!1,$.verbose||!1,"0.0.
|
|
4645
|
+
npm install -g @sourcegraph/amp`;X(Error(W))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}l0();l0();WI();async function QK0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Ke(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],W=X.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return _.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(F){return _.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var Zn5="https://static.ampcode.com/cli/cli-version.txt";async function BK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${Zn5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=Ke(A,J),Z=Y<0;return _.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return _.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Fn5=604800000;function $t4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>Fn5)return{ageMs:B};return null}function Ke(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function x81(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?xU(B):void 0;return{sha:$,age:J}}catch{return null}}w1();l0();import{readFile as Xn5,realpath as Dn5}from"node:fs/promises";import{homedir as Gn5}from"node:os";import{dirname as Jt4,join as f81}from"node:path";async function Yt4(A){switch(A){case"binary":case"brew":return Vn5(De());case"npm":case"pnpm":case"yarn":case"bun":return Un5();case"bootstrap":return Kn5()}}async function Vn5(A){let Q=await TG(A,["--version"],5000);if(Q.reason!=="success")return _.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Un5(){try{let A=process.argv[1];if(!A)return null;let Q=await Dn5(A),B=Jt4(Jt4(Q));return await Zt4(f81(B,"package.json"))}catch(A){return _.debug("failed to read installed version from package.json",{error:A}),null}}async function Kn5(){try{let A=process.env.AMP_HOME??f81(Gn5(),".amp");return await Zt4(f81(A,"package","package.json"))}catch(A){return _.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Zt4(A){let Q=await Xn5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return _.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var En5=3600000,Wn5=5000;function b81(A,Q,B={}){let $=new FA,J=$.pipe(Q6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??En5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=new KD().scoped("update");if(Y>0){if(await yU(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await Hn5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await yU(Wn5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let W=Math.min(K,E);await yU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function Hn5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await eU0(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await BK0(A);else{let V=await IP();X=await QK0(A,V)}if(!(X.latestVersion&&X.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await Yt4(Z);if(V&&Ke(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Ke(A,V)<0){let U=await uH(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(X.currentVersionAge!==void 0&&X.latestVersionAge!==void 0){let V=X.currentVersionAge-X.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:X.currentVersionAge,latestVersionAge:X.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==De()){if(B.debug("non-standard binary path, showing warning"),!G())D("update-available-unrecognized-path");return J}if(Y==="warn"){if(!G())D("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!G())D("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!G())D("update-available");return J}try{await Ue(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await uH(X.latestVersion),U={from:X.currentVersion,to:X.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}WI();import{stderr as SG}from"node:process";function Ft4(A){let Q=new hI().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($)=>{await M81($.force||!1,$.verbose||!1,"0.0.1777352624-g869aa9"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new hI("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($)=>{await qn5($.targetVersion)});A.addCommand(B)}function zn5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
|
|
4646
4646
|
`),$=!1,B=0}function Y(Z){if(!Q)return;let F=Z.padEnd(B," ");A.write(`\r${F}`),$=!0,B=F.length}return{flushProgressLine:J,renderProgress:Y}}async function qn5(A){let B=process.platform==="win32"&&NP()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=zn5(SG);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")SG.write(n0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4647
4647
|
|
|
4648
4648
|
`));try{if(!A){SG.write(n0.blue(`Checking for updates...
|
|
4649
|
-
`));let F=!1,X;if(NP()){let D=await BK0("0.0.
|
|
4650
|
-
`));let V=await uH("0.0.
|
|
4649
|
+
`));let F=!1,X;if(NP()){let D=await BK0("0.0.1777352624-g869aa9");F=D.hasUpdate,X=D.latestVersion}else{let D=await IP(),G=await QK0("0.0.1777352624-g869aa9",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=x81("0.0.1777352624-g869aa9"),G=D?.age?`released ${D.age} ago`:`built ${xU(new Date("2026-04-28T05:07:34.445Z"))} ago`;SG.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1777352624-g869aa9"} (${G})
|
|
4650
|
+
`));let V=await uH("0.0.1777352624-g869aa9",B);if(V.warning)SG.write(`
|
|
4651
4651
|
`+n0.yellow(V.warning)+`
|
|
4652
4652
|
`);process.exit(0)}if(!X)SG.write(n0.yellow("[WARN] could not find latest version")),process.exit(0);A=X}SG.write(n0.blue(`Updating to version ${A}...
|
|
4653
4653
|
`)),await Ue(A,void 0,(F)=>{$(),SG.write(n0.dim(`Running: ${F}
|
|
@@ -5173,7 +5173,7 @@ Ctrl-X, Y, Z to unlock`;if(K){let x=G.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
5173
5173
|
`,N)])}),P];if(!D&&!K&&G.url){let k=G.url.replace(/^https?:\/\//,"");b.push(new tA({uri:G.url,text:k,style:new u({color:B.secondary,underline:!0})}))}if(j&&!K)b.push(j);let g=new j0({width:50,child:new b0({crossAxisAlignment:"start",mainAxisSize:"min",children:b})}),f=F?new j0({width:oW0,height:rW0}):new X31({width:oW0,height:rW0,agentMode:this.widget.agentMode,colorMode:E.colorMode,visualStyle:this.widget.orbVisualStyle,primaryColor:W?.primary,secondaryColor:W?.secondary,glow:this._glow,backgroundColor:B.background,t:V,fps:0,shockwaves:this._shockwaves,onShockwave:this.handleShockwave,onClick:this.widget.interactive?this.handleOrbClick:void 0,...Z==="disabled"&&{seed:42}});return D4.child(new J1({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[f,new j0({width:2}),g]}))}}l0();C7();fY();w1();var IQ8=["ctrl+x","y","z"];class KB1{state;_message=null;_isOverlayShown=!1;_progress=null;subscription=null;sequenceManager=null;interceptorUnsubscribe=null;configService=null;constructor(A){this.state=A;let Q=A.dispose.bind(A);A.dispose=()=>{this.dispose(),Q()}}get message(){return this._message}get isOverlayShown(){return this._isOverlayShown}get progress(){return this._progress}start(A){this.subscription?.unsubscribe(),this.teardownSequence(),this._message=null,this._isOverlayShown=!1,this.configService=A,this.subscription=QB(A).pipe(Y5((Q)=>Q!=="pending"),N1((Q)=>xA(Q)?Q.mysteriousMessage??null:null),x4((Q,B)=>Q?.id===B?.id)).subscribe((Q)=>{if(!this.state.mounted)return;let B=Q?.id!==this._message?.id;this.state.setState(()=>{if(B){if(this.teardownSequence(),Q)this.setupSequence();this._isOverlayShown=!1}this._message=Q})})}destruct(){if(!this._message)return;let A=this._message.id;hA.markAsReadMysteriousMessage({messageId:A},{config:this.configService}).then((Q)=>{if(!this.state.mounted)return;if(!Q.ok){_.error("Failed to destruct mysterious message",Q.error);return}if(this._message?.id!==A)return;this.state.setState(()=>{this.teardownSequence(),this._message=null,this._isOverlayShown=!1})}).catch((Q)=>{_.error("Failed to destruct mysterious message",Q)})}dispose(){this.teardownSequence(),this.subscription?.unsubscribe(),this.subscription=null}setupSequence(){this.sequenceManager=new Iu(new Map([[new Nu(IQ8),new _P]])),this.interceptorUnsubscribe=c4.instance.addKeyInterceptor((A)=>{if(!this.sequenceManager)return!1;if(this._isOverlayShown)return!1;let Q=this.sequenceManager.handleKeyEvent(A);if(Q.consumed)return this.state.setState(()=>{if(this._progress=Q.progress,Q.intent)this._isOverlayShown=!0}),!0;if(this._progress)this.state.setState(()=>{this._progress=null});return!1})}teardownSequence(){this.interceptorUnsubscribe?.(),this.interceptorUnsubscribe=null,this.sequenceManager?.dispose(),this.sequenceManager=null,this._progress=null}}class EB1 extends v0{props;constructor(A){super();this.props=A}createState(){return new u9A}}class u9A extends k0{splashOrbExplosion=null;splashOrbExplosionSeq=0;editorTextChangeListener=null;mystery=new KB1(this);initState(){this.subscribeToEditorController(),this.mystery.start(this.widget.props.configService)}didUpdateWidget(A){if(A.props.editorController!==this.widget.props.editorController)this.unsubscribeFromEditorController(A.props.editorController),this.subscribeToEditorController()}dispose(){this.unsubscribeFromEditorController(this.widget.props.editorController),super.dispose()}subscribeToEditorController(){this.editorTextChangeListener=()=>this.setState(),this.widget.props.editorController.addListener(this.editorTextChangeListener)}unsubscribeFromEditorController(A){if(!this.editorTextChangeListener)return;A.removeListener(this.editorTextChangeListener),this.editorTextChangeListener=null}submitPrompt=async(A)=>{this.widget.props.editorController.clear(),this.widget.props.onNewThread(A,this.widget.props.agentMode)};buildHints(){let A=new Set(this.widget.props.hints);if(this.widget.props.previousThreadIDForReference&&this.widget.props.editorController.text.trim()==="")A.add(m00);return A}handleSplashOrbExplode=(A)=>{this.splashOrbExplosionSeq+=1,this.setState(()=>{this.splashOrbExplosion={seq:this.splashOrbExplosionSeq,originX:A.x,originY:A.y}})};handleSplashOrbExplosionComplete=()=>{if(!this.splashOrbExplosion)return;this.setState(()=>{this.splashOrbExplosion=null})};build(A){let{editorController:Q,agentMode:B,threadSettings:$}=this.widget.props,J=uQ.of(A),Y=Q.text.trim()!=="",{deepReasoningEffort:Z,anthropicEffort:F,speedSuffix:X}=hW0(B,$),D=new _4(()=>{let K=JJ(void 0,{isInternalUser:J.isInternalUser});return sA.maybeInvoke(A,new o00(Pc(B,K)))}),G=new Map([[G_,D]]),U=[new J10({child:new Zh({agentMode:B,orbVisualStyle:J.splashOrbVisualStyle,settleAnimation:Y,onOrbExplode:this.handleSplashOrbExplode,mysteriousMessage:this.mystery.message,mysterySequenceProgress:this.mystery.progress,interactive:!this.mystery.isOverlayShown}),editorController:Q,activeThreadID:null,queuedMessages:[],selectedQueuedMessageIndex:null,editorEnabled:!0,hints:this.buildHints(),agentState:"idle",compactionState:"idle",connectionState:"disconnected",pendingSend:!1,agentMode:B,deepReasoningEffort:Z,anthropicEffort:F,speedSuffix:X,ideStatus:this.widget.props.ideStatus,statusMessageOverride:this.widget.props.connectionErrorMessage,environment:null,previousThreadIDForReference:this.widget.props.previousThreadIDForReference,onSubmit:this.submitPrompt})];if(this.splashOrbExplosion)U.push(new UB1({key:new J6(`splash-orb-explosion-${this.splashOrbExplosion.seq}`),originX:this.splashOrbExplosion.originX,originY:this.splashOrbExplosion.originY,agentMode:B,visualStyle:J.splashOrbVisualStyle,onComplete:this.handleSplashOrbExplosionComplete}));if(this.mystery.isOverlayShown&&this.mystery.message)U.push(new Y10({key:new J6(`mysterious-message-modal-${this.mystery.message.id}`),message:this.mystery.message,onDestruct:()=>this.mystery.destruct()}));return new sA({actions:G,child:new U3({debugLabel:"EmptyThreadShortcuts",shortcuts:new Map([[p1.ctrl("s"),new G_],[p1.alt("s"),new G_]]),child:new vA({children:U})})})}}l0();C7();var CQ8=/^[a-z0-9][a-z0-9-]*$/,wQ8={kind:"fill",modalRows:18};function h9A(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!CQ8.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}class g9A extends v0{props;constructor(A){super();this.props=A}createState(){return new m9A}}class m9A extends k0{allLabels=[];currentLabels=null;loadError=null;currentQuery="";initState(){this.loadAll()}async loadAll(){try{let[A,Q]=await Promise.all([hA.getUserLabels({query:""},{config:this.widget.props.configService}),bu({configService:this.widget.props.configService},this.widget.props.threadID)]);if(!this.mounted)return;this.setState(()=>{if(!A.ok){this.loadError=Error(A.error.message??"Failed to load labels");return}if(this.allLabels=A.result,Q instanceof Error)this.loadError=Q;else this.currentLabels=Q.map((B)=>B.name)})}catch(A){if(_.error("Failed to load labels",A),!this.mounted)return;this.setState(()=>{this.loadError=A instanceof Error?A:Error(String(A))})}}handleQueryChange=(A)=>{if(this.currentQuery===A)return;this.setState(()=>{this.currentQuery=A})};build(A){if(this.loadError)return new r({text:new O(`Failed to load labels: ${this.loadError.message}`),textAlign:"center"});if(this.currentLabels===null)return new r({text:new O("Loading labels…"),textAlign:"center"});let{colors:Q,app:B}=T0.of(A),$=this.currentLabels,J=[{kind:"create"},...this.allLabels.filter((Z)=>!$.includes(Z.name)).map((Z)=>({kind:"label",label:Z}))],Y=this.currentQuery.length>0?h9A(this.currentQuery):null;return new e6({items:J,showBorder:!1,getLabel:(Z)=>Z.kind==="create"?this.currentQuery.trim().toLowerCase():Z.label.name,onAccept:(Z)=>{let F=Z.kind==="create"?this.currentQuery.trim().toLowerCase():Z.label.name;this.widget.props.onSelect(F)},onDismiss:this.widget.props.onDismiss,onQueryChange:this.handleQueryChange,emptyStateText:Y||"Type to create a new label",renderItem:(Z,F)=>{let X=F?B.selectionBackground:void 0,D=F?B.selectionForeground:Q.foreground;if(Z.kind==="create"){let G=this.currentQuery.trim().toLowerCase();return new p0({decoration:X?{color:X}:void 0,padding:M0.symmetric(2,0),child:new r({text:new O("",void 0,[new O("Create new label: ",new u({color:D})),new O(G,new u({color:D,bold:!0}))])})})}return new p0({decoration:X?{color:X}:void 0,padding:M0.symmetric(2,0),child:new r({text:new O(Z.label.name,new u({color:D}))})})},filterItem:(Z,F)=>{if(Z.kind==="create")return this.shouldShowCreateMarker(F);let X=F.trim().toLowerCase();return X.length===0||Z.label.name.includes(X)},sortItems:(Z,F)=>{if(Z.item.kind==="create"&&F.item.kind!=="create")return-1;if(Z.item.kind!=="create"&&F.item.kind==="create")return 1;return F.score-Z.score}})}shouldShowCreateMarker(A){if(A.length===0)return!1;let Q=A.trim().toLowerCase();if(h9A(Q)!==null)return!1;let B=this.currentLabels??[],$=this.allLabels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}}async function MQ8(A,Q,B,$){let J=await A.addLabel(Q,B);if(J instanceof Error)$?.show(`Failed to add label: ${J.message}`,"error")}function p9A(A,Q){return{noun:"label",verb:"add",description:"Add label to thread",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"Cannot add labels to an empty thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;let Z=_9.maybeOf($);B.push(new z6({header:"Add Label",autofocus:!1,minWidth:80,maxWidth:80,bodyFit:wQ8,onDismiss:J,child:new g9A({threadID:Y,configService:A.configService,onDismiss:J,onSelect:(F)=>{J(),MQ8(A,Y,F,Z)}})}))}}}class d9A extends v0{props;constructor(A){super();this.props=A}createState(){return new c9A}}class c9A extends k0{labels=null;loadError=null;initState(){this.loadCurrentLabels()}async loadCurrentLabels(){let A=await bu({configService:this.widget.props.configService},this.widget.props.threadID);if(!this.mounted)return;this.setState(()=>{if(A instanceof Error)this.loadError=A;else this.labels=A})}build(A){if(this.loadError)return new r({text:new O(`Failed to load labels: ${this.loadError.message}`),textAlign:"center"});if(this.labels===null)return new r({text:new O("Loading labels…"),textAlign:"center"});if(this.labels.length===0)return new r({text:new O("This thread has no labels to remove."),textAlign:"center"});return new e6({items:this.labels,getLabel:(Q)=>Q.name,showBorder:!1,onAccept:this.widget.props.onSelect,onDismiss:this.widget.props.onDismiss})}}async function LQ8(A,Q,B,$){let J=await A.removeLabel(Q,B);if(J instanceof Error)$?.show(`Failed to remove label: ${J.message}`,"error")}function l9A(A,Q){return{noun:"label",verb:"remove",description:"Remove label from thread",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"Cannot remove labels from an empty thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;let Z=_9.maybeOf($);B.push(new z6({header:"Remove Label",autofocus:!1,minWidth:80,maxWidth:80,onDismiss:J,child:new d9A({threadID:Y,configService:A.configService,onDismiss:J,onSelect:(F)=>{J(),LQ8(A,Y,F.name,Z)}})}))}}}var i9A=60,OQ8=200,jQ8=100,RQ8=110,PQ8=26;function n9A(A){return A.replace(/\r?\n/g," ")}function _Q8(A){let Q=n9A(A),B=oA(Q);if(B.length<=i9A)return Q;return B.slice(0,i9A).join("")}function TQ8(A,Q,B=process.platform){if(B==="win32"){let $=A.replace(/\\/g,"/").toLowerCase(),J=Q.replace(/\\/g,"/").toLowerCase();return $===J}return A===Q}class sW0 extends v0{props;constructor(A){super();this.props=A}createState(){return new a9A}}class a9A extends k0{filterByWorkspace=!0;cachedEntries=[];scoringLabelCache=new Map;initState(){this.refreshCachedEntries()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.props.entries!==this.widget.props.entries||A.props.currentCwd!==this.widget.props.currentCwd)this.refreshCachedEntries()}handleKeyEvent=(A)=>{if(A.ctrlKey&&A.key.toLowerCase()==="t"||A.altKey&&A.key.toLowerCase()==="w")return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.refreshCachedEntries()}),"handled";return"ignored"};computeFilteredEntries(){let{entries:A,currentCwd:Q}=this.widget.props,B;if(this.filterByWorkspace)B=A.filter((Y)=>Y.cwd===void 0||TQ8(Y.cwd,Q));else B=[...A];B=B.reverse();let $=new Set,J=[];for(let Y of B){if(!$.has(Y.text))$.add(Y.text),J.push(Y);if(J.length>=OQ8)break}return J}refreshCachedEntries(){this.cachedEntries=this.computeFilteredEntries()}handleAccept=(A)=>{this.widget.props.onAccept(A.text)};handleDismiss=()=>{this.widget.props.onDismiss()};getScoringLabel(A){let Q=this.scoringLabelCache.get(A);if(Q!==void 0)return Q;let B=_Q8(A);return this.scoringLabelCache.set(A,B),B}build(A){let Q=T0.of(A),{colors:B,app:$}=Q,J=this.filterByWorkspace?"Showing: current workspace":"Showing: all workspaces";return new z6({header:"Prompt History",maxWidth:RQ8,maxHeight:PQ8,autofocus:!1,footer:[{keys:["Alt+W","Ctrl+T"],label:`toggle filter · ${J}`}],onDismiss:this.handleDismiss,child:new e4({canRequestFocus:!1,skipTraversal:!0,debugLabel:"NeoPromptHistoryPicker",onKey:this.handleKeyEvent,child:new e6({items:this.cachedEntries,showBorder:!1,getLabel:(Y)=>this.getScoringLabel(Y.text),filterItem:(Y,Z)=>{if(!Z)return!0;return Y.text.toLowerCase().includes(Z.toLowerCase())},sortItems:()=>0,onAccept:this.handleAccept,onDismiss:this.handleDismiss,emptyStateText:this.filterByWorkspace?"No history for this workspace":"No prompt history",maxRenderItems:jQ8,renderItem:(Y,Z)=>{let F=Z?$.selectionBackground:void 0,X=Z?$.selectionForeground:B.foreground,D=n9A(Y.text);return new J1({children:[new k1({child:new p0({decoration:F?{color:F}:void 0,padding:M0.symmetric(2,0),child:new r({text:new O(D,new u({color:X})),maxLines:1,overflow:"ellipsis"})})})]})}})})})}}i8();import{homedir as SQ8}from"node:os";import{relative as kQ8,sep as vQ8}from"node:path";import{fileURLToPath as yQ8}from"node:url";var xQ8="https://ampcode.com/manual#agent-skills";class WB1 extends RA{}class HB1 extends v0{listSkills;onDismiss;cwd;constructor(A){super();this.listSkills=A.listSkills,this.onDismiss=A.onDismiss,this.cwd=A.cwd}createState(){return new o9A}}class o9A extends k0{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 r9A({status:this.status,cwd:this.widget.cwd,onDismiss:this.widget.onDismiss})}}class r9A extends R1{status;cwd;onDismiss;constructor(A){super();this.status=A.status,this.cwd=A.cwd,this.onDismiss=A.onDismiss}build(A){return new z6({header:fQ8(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 sA({actions:new Map([[WB1,new _4(()=>{t6(A,xQ8)})]]),child:new U3({debugLabel:"NeoSkillListShortcuts",shortcuts:new Map([[p1.key("o"),new WB1]]),child:bQ8(A,this.status,this.cwd)})})})}}function fQ8(A){if(A.kind!=="ready")return"Skills";let{skills:Q,errors:B}=A;if(Q.length===0&&B.length===0)return"Skills";if(B.length===0)return`Skills (${Q.length})`;let $=`${B.length} ${N4(B.length,"error")}`;if(Q.length===0)return`Skills (0, ${$})`;return`Skills (${Q.length}, ${$})`}function bQ8(A,Q,B){let{colors:$}=T0.of(A);switch(Q.kind){case"loading":return new J1({mainAxisSize:"min",children:[new K_({color:$.primary}),new j0({width:1}),new r({text:new O("Loading skills...",new u({color:$.foreground,dim:!0}))})]});case"error":return new r({text:new O(Q.message,new u({color:$.destructive}))});case"ready":return hQ8(A,Q.skills,Q.errors,B)}}var uQ8=90;function hQ8(A,Q,B,$){let{colors:J,app:Y}=T0.of(A),Z=new u({color:J.foreground,dim:!0});if(Q.length===0&&B.length===0)return new r({text:new O("No skills reported by the executor yet.",Z)});let F=F4.sizeOf(A).width>=uQ8;return new eH({child:new b0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:cQ8(Q,B,F,{section:new u({color:J.foreground,bold:!0}),name:new u({color:Y.command}),description:new u({color:J.foreground}),location:Z,errorTitle:new u({color:J.destructive,bold:!0}),errorName:new u({color:J.warning,bold:!0}),errorMessage:new u({color:J.destructive}),cwd:$})})})}var gQ8={local:"Local",global:"Global",builtin:"Built-in"},mQ8=["local","global","builtin"],pQ8={"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 dQ8(A){let Q={local:[],global:[],builtin:[]};for(let B of A){let $=B.source??"workspace-agents";Q[pQ8[$]].push(B)}return mQ8.filter((B)=>Q[B].length>0).map((B)=>({label:gQ8[B],skills:Q[B]}))}function cQ8(A,Q,B,$){let J=[];if(dQ8(A).forEach((Y,Z)=>{if(Z>0)J.push(new j0({height:1}));J.push(new r({text:new O(Y.label,$.section)}));for(let F of Y.skills)J.push(new x0({padding:M0.only({left:2}),child:aQ8(F,B,$)}))}),Q.length>0){if(A.length>0)J.push(new j0({height:1}));J.push(new r({text:new O(`Skipped skills with errors (${Q.length}):`,$.errorTitle)}));for(let Y of Q)J.push(new j0({height:1})),J.push(...iQ8(Y,$))}J.push(new j0({height:1})),J.push(new r({text:new O("Create your own:",$.section)}));for(let Y of lQ8)J.push(new x0({padding:M0.only({left:2}),child:new r({text:new O(`"${Y}"`,$.description),maxLines:1,overflow:"ellipsis"})}));return J}var lQ8=["Create a skill for searching our production logs","Create a user skill for my preferred commit message style"];function iQ8(A,Q){let B=[new x0({padding:M0.only({left:2}),child:new r({text:new O(`⚠ ${nQ8(A.path)}`,Q.errorName)})}),new x0({padding:M0.only({left:4}),child:new r({text:new O(A.error,Q.errorMessage)})})];if(A.hint)B.push(new x0({padding:M0.only({left:4}),child:new r({text:new O(A.hint.split(`
|
|
5174
5174
|
`)[0]??"",Q.description)})}));return B.push(new x0({padding:M0.only({left:4}),child:new r({text:new O(s9A(A.path,Q.cwd),Q.location),maxLines:1,overflow:"ellipsis"})})),B}function nQ8(A){try{return new URL(A).pathname.split("/").filter(Boolean).at(-2)??"unknown"}catch{return"unknown"}}function aQ8(A,Q,B){if(Q)return new J1({crossAxisAlignment:"start",children:[new k1({flex:1,child:new r({text:new O(A.name,B.name),maxLines:1,overflow:"ellipsis"})}),new j0({width:2}),new k1({flex:2,child:new x0({padding:M0.only({right:1}),child:new r({text:new O(A.description,B.description),maxLines:1,overflow:"ellipsis"})})})]});return new b0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new J1({crossAxisAlignment:"start",children:[new r({text:new O(A.name,B.name),maxLines:1,overflow:"ellipsis"}),new k1({child:new r({text:new O(` ${s9A(A.baseDir,B.cwd)}`,B.location),maxLines:1,overflow:"ellipsis"})})]}),new x0({padding:M0.only({left:2,right:1}),child:new r({text:new O(A.description,B.description),maxLines:1,overflow:"ellipsis"})})]})}function s9A(A,Q){if(A.startsWith("builtin://"))return"(builtin)";if(!A.startsWith("file://"))return A;let B=yQ8(A),$=kQ8(Q,B);if($&&!$.startsWith(".."))return`./${$}`;let J=SQ8();if(B===J||B.startsWith(J+vQ8))return`~${B.slice(J.length)}`;return B}l0();var t9A=256,A7A={kind:"fill",modalRows:14};function e9A(A,Q){return new z6({header:"Rename Thread failed",tone:"error",minWidth:80,maxWidth:80,bodyFit:A7A,footer:"none",onDismiss:Q,child:new r({text:new O(A)})})}function Q7A(A){return{noun:"thread",verb:"rename",description:"Rename thread title",get status(){return A()?{type:"enabled"}:{type:"disabled",reason:"Cannot rename an empty thread"}},run:(Q,B,$)=>{if(!A())return;let J=_9.maybeOf(B);Q.push(new V_({header:"Rename Thread",placeholder:"Enter new thread title",isRequired:!0,bodyFit:A7A,onDismiss:$,onSubmit:(Y)=>{if(Y.length>t9A){Q.push(e9A(`Thread title cannot exceed ${t9A} characters`,$));return}let Z=A();if(!Z){$();return}try{Z.client.setThreadTitle(Y),$(),J?.show("Thread renamed","success")}catch(F){_.error("Failed to rename thread",{error:F}),Q.push(e9A(`Failed to rename thread: ${F instanceof Error?F.message:String(F)}`,$))}}}))}}}l0();class zB1 extends R1{build(A){let{colors:Q}=T0.of(A);return new r({text:new O("",void 0,[new O(`This thread has been shared with Amp support for debugging and bug prioritization.
|
|
5175
5175
|
`,new u({color:Q.foreground})),new O(`This is not a support request.
|
|
5176
|
-
`,new u({color:Q.foreground,dim:!0})),new O("If you need a reply, post on X @AmpCode or email amp-devs@ampcode.com.",new u({color:Q.foreground,dim:!0}))]),textAlign:"center"})}}var $7A={kind:"fill",modalRows:17};function B7A(A){return new z6({header:A.title,tone:A.tone,minWidth:80,maxWidth:80,bodyFit:$7A,onDismiss:A.onDismiss,child:A.child})}function J7A(A,Q){return{noun:"thread",verb:"share with support",description:"Share with Amp support for debugging",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;B.push(new V_({header:"Share Thread with Support",placeholder:"What went wrong? (Need a reply? Email amp-devs@ampcode.com.)",isRequired:!1,bodyFit:$7A,onDismiss:J,onSubmit:async(Z)=>{try{await A.shareThreadWithSupport(Y,Z||void 0),B.push(B7A({title:"Thread shared",tone:"success",onDismiss:J,child:new zB1}))}catch(F){_.error("Failed to share thread with support",{error:F,threadID:Y}),B.push(B7A({title:"Share with Support failed",tone:"error",onDismiss:J,child:new r({text:new O(`Failed to share thread with support: ${F instanceof Error?F.message:String(F)}`)})}))}}}))}}}var oQ8=["private","workspace","unlisted","public"];class F7A extends R1{props;constructor(A){super();this.props=A}build(A){let{colors:Q,app:B}=T0.of(A);return new e6({items:oQ8,getLabel:($)=>`${Y7A($)} ${Z7A($)}`,showBorder:!1,onAccept:this.props.onSelect,onDismiss:this.props.onDismiss,renderItem:($,J)=>{let Y=J?B.selectionBackground:void 0,Z=J?B.selectionForeground:Q.foreground,F=J?B.selectionForeground:Q.mutedForeground;return new p0({decoration:Y?{color:Y}:void 0,padding:M0.symmetric(1,0),child:new J1({crossAxisAlignment:"center",children:[new k1({child:new r({text:new O(Y7A($),new u({color:Z})),maxLines:1,overflow:"ellipsis"})}),new j0({width:2}),new r({text:new O(Z7A($),new u({color:F})),maxLines:1,overflow:"ellipsis"})]})})}})}}function Y7A(A){switch(A){case"private":return"Private";case"workspace":return"Workspace";case"group":return"Group";case"unlisted":return"Unlisted";case"public":return"Public"}}function Z7A(A){switch(A){case"private":return"Only you can see this thread";case"workspace":return"Visible to workspace members";case"group":return"Visible to group members";case"unlisted":return"Anyone with the link can view";case"public":return"Searchable and on your public profile"}}async function rQ8(A,Q,B,$){let J=await A.setVisibility(Q,B);if(J instanceof RB)$?.show(J.message,"success");else $?.show(J.message,"error")}function X7A(A,Q){return{noun:"thread",verb:"set visibility",description:"Set thread visibility",keywords:["share","private","workspace","public","unlisted","team","group"],get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client?.getThreadId();if(!Y)return;let Z=_9.maybeOf($);B.push(new z6({header:"Set Thread Visibility",autofocus:!1,minWidth:80,maxWidth:80,onDismiss:J,child:new F7A({onDismiss:J,onSelect:(F)=>{J(),rQ8(A,Y,F,Z)}})}))}}}class NB1 extends v0{initialAgentMode;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;history;updateDraftThreadSettings;onNewThread;shareThreadWithSupport;setThreadVisibility;archiveThread;addThreadLabel;removeThreadLabel;configService;connectionErrorMessage;hints;ideStatus;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.shareThreadWithSupport=A.shareThreadWithSupport,this.setThreadVisibility=A.setThreadVisibility,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.connectionErrorMessage=A.connectionErrorMessage,this.hints=A.hints,this.ideStatus=A.ideStatus}createState(){return new D7A}}class D7A extends k0{historyIndex=-1;historyDraft=null;promptHistoryPicker=new oe(this);agentMode;copyOnSelectEnabled=!0;copyOnSelectSubscription=null;expansion=new MQ1;previousThreadIDForReference=null;unregisterCommands=null;initState(){this.agentMode=this.widget.initialAgentMode,this.unregisterCommands=this.registerCommands(),this.subscribeToCopyOnSelectEnabled()}didUpdateWidget(A){if(A.configService!==this.widget.configService)this.subscribeToCopyOnSelectEnabled();if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.historyIndex=-1,this.historyDraft=null,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null;else this.previousThreadIDForReference=null}dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.copyOnSelectSubscription?.unsubscribe(),this.copyOnSelectSubscription=null}registerCommands(){let A=SZ.of(this.context),Q=uQ.of(this.context),B=this,$=()=>{return B.widget.threadContext??null},J=()=>{let X=B.widget.threadContext?.client.getThreadId();if(!X)return null;return xY(new URL(Q.ampURL),X).toString()},F=[...JJ(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:X})=>({noun:"mode",verb:`use ${X}`,description:`Enable ${X} mode`,get status(){if(B.widget.threadContext)return{type:"disabled",reason:"Mode can only be changed on a new thread"};if(X===B.agentMode)return{type:"disabled",reason:`Already using ${X} mode`};return{type:"enabled"}},run:(D,G,V)=>{B.setAgentMode(X),V()}})),{noun:"speed",verb:"toggle speed",description:"Toggle speed (fast/standard) for this thread",keywords:["anthropic","openai","fast","standard","smart","deep"],get status(){let X=B.currentCommandAgentMode();return X==="smart"||x2(X)?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleSpeed(),G()}},{noun:"thread",verb:"toggle thinking blocks",description:"Expand or collapse all thinking blocks",keywords:["thinking","expand","collapse","reasoning"],shortcut:p1.alt("t"),status:{type:"enabled"},run:(X,D,G)=>{B.toggleGlobalThinking(),G()}},{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",keywords:["deep","thinking","reasoning","effort","depth","anthropic","openai","smart","frontier"],shortcut:p1.alt("d"),get status(){return Rc(B.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleReasoningEffort(),G()}},{noun:"prompt",verb:"history",description:"Restore a previous prompt",keywords:["recent","reuse","search"],shortcut:p1.ctrl("r"),status:{type:"enabled"},run:(X,D,G)=>{X.pushWithDismiss((V)=>new sW0({entries:this.widget.history.getAll(),currentCwd:qB1.cwd(),onAccept:(U)=>{this.restorePromptHistory(U),G()},onDismiss:V}))}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",keywords:["identifier","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;sA.maybeInvoke(D,new TZ(V,"Thread ID copied to clipboard","Failed to copy thread ID")),G()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["link","share","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=J();if(!V)return;sA.maybeInvoke(D,new TZ(V,"Thread URL copied to clipboard","Failed to copy thread URL")),G()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",keywords:["markdown","export","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;(async()=>{try{let U=await Q.getThreadMarkdown(V);if(!U){_9.error(D,"Failed to copy thread markdown");return}sA.maybeInvoke(D,new TZ(U,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(U){_.error("Failed to render thread markdown from Neo command palette",{error:U,threadID:V}),_9.error(D,"Failed to copy thread markdown")}finally{G()}})()}},{noun:"thread",verb:"analyze context",description:"Analyze context token usage",keywords:["tokens","usage","window","size","cost"],get status(){let X=B.widget.threadContext;if(!X)return{type:"disabled",reason:"No active thread"};let D=YJ(X.observer.agentMode);if(!Z2A.includes(D))return{type:"disabled",reason:"Context analysis requires Claude Opus 4.7 (smart) or GPT-5.4 (deep)"};return{type:"enabled"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>{return new z6({header:"Context Usage Analysis",minWidth:60,maxWidth:60,chromePadding:M0.symmetric(1,0),footer:[{keys:["Esc"],label:"close"}],onDismiss:G,child:new r00({embedded:!0,contentWidth:58,thread:null,dtwAnalyze:(K)=>{return B.widget.analyzeContextForThread(D,K)},onDismiss:G})})})}},{noun:"skills",verb:"list",description:"List available skills for this thread",keywords:["agent","show"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>new HB1({listSkills:(V)=>B.widget.listSkillsForThread(D,V),onDismiss:G,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start","reset","clear"],sortBoost:101,get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(X,D)=>{sA.maybeInvoke(D,new l00)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web","view","launch"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(X,D,G)=>{let V=J();if(!V)return;try{await t6(D,V)}finally{G()}}},J7A({shareThreadWithSupport:(X,D)=>{return this.widget.shareThreadWithSupport(X,D)}},$),X7A({setVisibility:(X,D)=>this.widget.setThreadVisibility(X,D)},$),N9A({archiveThread:(X)=>this.widget.archiveThread(X)},$),Q7A($),p9A({configService:this.widget.configService,addLabel:(X,D)=>this.widget.addThreadLabel(X,D)},$),l9A({configService:this.widget.configService,removeLabel:(X,D)=>this.widget.removeThreadLabel(X,D)},$)].map((X)=>A.register(X));return()=>{for(let X of F)X()}}currentCommandAgentMode(){return this.widget.threadContext?.observer.agentMode??this.agentMode}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let B=Q.observer.threadSettings().getValue()??{},$=A(B);return Q.client.sendClientUpdateThreadSettings($),this.widget.updateDraftThreadSettings(()=>$),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){let A=this.currentCommandAgentMode();if(A==="smart")return this.updateThreadSettings((Q)=>{let B={...Q};if(B["anthropic.speed"]==="fast")delete B["anthropic.speed"];else B["anthropic.speed"]="fast";return B});if(x2(A))return this.updateThreadSettings((Q)=>{let B={...Q};if(B["openai.speed"]==="fast")B["openai.speed"]="standard";else B["openai.speed"]="fast";return B});return"ignored"}toggleGlobalThinking(){return this.expansion.toggle(),"handled"}toggleReasoningEffort(){let A=this.currentCommandAgentMode(),Q=Rc(A);if(!Q)return"ignored";return this.updateThreadSettings((B)=>{let $=T90(A,B);if(!$)return B;let J=B[$]??Z3(A)?.reasoningEffort,Y=_90(Q,J);return{...B,[$]:Y}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,qB1.cwd()),this.resetHistory()};restorePromptHistory(A){this.resetHistory(),this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd()}handlePromptHistorySelection=(A)=>{this.promptHistoryPicker.disable(),this.restorePromptHistory(A)};navigateHistoryPrevious=()=>{let A=this.widget.history.previous();if(A!==null){if(this.historyIndex===-1)this.historyDraft=this.widget.editorController.text;this.historyIndex++,this.widget.editorController.text=A,this.widget.editorController.moveCursorToStart()}return"handled"};navigateHistoryNext=()=>{let A=this.widget.history.next();if(A!==null)this.historyIndex--,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.widget.editorController.text=this.historyDraft||"",this.widget.editorController.moveCursorToEnd(),this.historyDraft=null;return"handled"};resetHistory(){this.widget.history.reset(),this.historyIndex=-1,this.historyDraft=null}setAgentMode(A){if(this.widget.threadContext)return;this.setState(()=>{this.agentMode=A}),OZ((Q)=>({...Q,agentMode:A}))}buildActions(){let A=new _4(()=>{return this.promptHistoryPicker.enable(),"handled"}),Q=new _4(()=>{return this.navigateHistoryPrevious()}),B=new _4(()=>{return this.navigateHistoryNext()}),$=new _4((Z)=>{return this.setAgentMode(Z.mode),"handled"}),J=new _4(()=>{return this.toggleReasoningEffort()}),Y=new _4(()=>{return this.toggleGlobalThinking()});return new Map([[dH,A],[SW0,B],[TW0,Q],[o00,$],[kW0,J],[RW0,Y]])}build(A){let Q=this.widget.threadContext,$=[Q?new FB1({editorController:this.widget.editorController,copyOnSelectEnabled:this.copyOnSelectEnabled,observingClient:{client:Q.client,observer:Q.observer},hints:this.widget.hints,ideStatus:this.widget.ideStatus,onPromptSubmitted:this.onPromptSubmitted}):new EB1({agentMode:this.agentMode,threadSettings:this.widget.draftThreadSettings,editorController:this.widget.editorController,onNewThread:this.widget.onNewThread,previousThreadIDForReference:this.previousThreadIDForReference,connectionErrorMessage:this.widget.connectionErrorMessage,hints:this.widget.hints,ideStatus:this.widget.ideStatus,configService:this.widget.configService})];if(this.promptHistoryPicker.isEnabled())$.push(new sW0({entries:this.widget.history.getAll(),currentCwd:qB1.cwd(),onAccept:this.handlePromptHistorySelection,onDismiss:this.promptHistoryPicker.disable}));let J=new Map([[p1.ctrl("r"),new dH],[p1.alt("d"),new kW0],[p1.alt("t"),new RW0]]);if(this.promptHistoryPicker.isEnabled())J.set(p1.ctrl("o"),new dH);else J.set(p1.ctrl("n"),new SW0),J.set(p1.ctrl("p"),new TW0);return new sA({actions:this.buildActions(),child:new U3({debugLabel:"NeoThreadShortcuts",shortcuts:J,child:new TX({controller:this.expansion,child:new vA({children:$})})})})}subscribeToCopyOnSelectEnabled(){this.copyOnSelectSubscription?.unsubscribe(),this.copyOnSelectSubscription=this.widget.configService.config.pipe(N1((A)=>A.settings["terminal.copyOnSelect"]??!0),x4()).subscribe((A)=>{if(this.copyOnSelectEnabled===A)return;if(this.copyOnSelectEnabled=A,this.mounted)this.setState()})}}class IB1 extends v0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;isFirstOpen;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,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.initialThreadID=A.initialThreadID,this.isFirstOpen=A.isFirstOpen??!1,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new G7A}}class G7A extends k0{editorController=new x3;commandPalette=new oe(this);commandRegistry=new VQ1;toastController=new e31;exitHintTimer=new ae(this,1000);connectionErrorMessage=new t2(this,null);ideStatus=new t2(this,{});draftThreadSettings={};draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;ideErrorSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;firstOpenDialogVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.clearConnectionError(),this.connectToExistingThread(A)};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await y3A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return x3A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await V6A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await U6A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await K6A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(C$.getInstance().interceptConsole(),this.widget.isFirstOpen)this.firstOpenDialogVisible=!0;if(this.connectionErrorMessage.subscribe(this.widget.clientPool.connectionErrors$.pipe(tE(({threadID:Q,error:B})=>{_.error("Neo failed to connect to thread",{threadID:Q,error:B})}),Y5(({threadID:Q})=>this.isConnectionErrorRelevant(Q)),tE(()=>this.clearActiveClientForConnectionError()),N1(({threadID:Q,error:B})=>{return Q?`Connection failed for ${Q}: ${B.message}`:`Connection failed: ${B.message}`}))),this.ideStatus.subscribe(this.widget.ideManager.status),this.ideErrorSubscription=this.widget.ideManager.errors$.subscribe((Q)=>{if(Q)this.setState(()=>{this.connectionErrorMessage.setValue(Q)})}),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID)this.connectToExistingThread(this.widget.initialThreadID,A);else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new JQ1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=c4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this.widget.neoContext.pluginService?S3A({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,toastController:this.toastController}):[],B=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:($,J,Y)=>{$.pushWithDismiss((Z)=>$B1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Z,onThreadSelected:Y}))}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:($)=>{$.pushWithDismiss((J)=>new wQ1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:J}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async($,J,Y)=>{try{await t6(J,"https://ampcode.com/chronicle")}finally{Y()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{oJ(this.widget.neoContext.settingsFilePath).catch(($)=>{_.error("Failed to open settings file in editor",{error:$})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:($,J,Y)=>{$.pushWithDismiss((Z)=>new IQ1({onCancel:Z,onSelect:(F)=>{this.handleIdeSelection(F),Y()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:($,J)=>{$.pushWithDismiss((Y)=>new HQ1({commands:SZ.of(J).commands,onDismiss:Y}))}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:($)=>{$.pushWithDismiss((J)=>new z6({header:"Amp Version",maxWidth:72,onDismiss:J,child:new r({text:new O(n31({version:"0.0.1777351004-g64ae1a",buildTimestamp:"2026-04-28T04:40:22.678Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:p1.ctrl("c"),status:{type:"enabled"},run:($,J)=>{sA.maybeInvoke(J,new Ah)}},...A,...I3A(this.widget.neoContext.logFilePath)].map(($)=>this.commandRegistry.register($));return()=>{for(let $ of B)$()}}build(A){let Q=this.buildHints(),B=this.connectionErrorMessage.getValue(),$=this.ideStatus.getValue(),J=new NB1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,connectionErrorMessage:B,hints:Q,ideStatus:$}),Y=F4.of(A),F=[new p0({constraints:O1.tight(Y.size.width,Y.size.height),child:J})];if(this.commandPalette.isEnabled())F.push(new UQ1({onDismiss:this.commandPalette.disable}));if(this.switchThreadPickerVisible)F.push($B1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.firstOpenDialogVisible)F.push(new qQ1({onDismiss:this.dismissFirstOpenDialog}));if(F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser&&this.debugOverlayVisible)F.push(new zQ1({top:this.focusDebugVisible?33:1,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)F.push(new NQ1);return new uQ({neoContext:this.widget.neoContext,child:new SZ({commandRegistry:this.commandRegistry,child:new Bw({completionBuilder:this.widget.completionBuilder,child:new _9({controller:this.toastController,child:new sA({actions:this.buildActions(),child:new U3({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[p1.ctrl("c"),new OW0],[p1.ctrl("o"),new jW0],[p1.alt("i"),new PW0],[p1.alt("p"),new fC],[p1.ctrl("t"),new _W0]]),child:new e4({debugLabel:"AppShellFocus",child:new A21({controller:this.toastController,child:new vA({children:F})})})})})})})})})}buildActions(){let A=new _4(()=>{if(aJ.hasAnyCopyableSelection())return aJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new _4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new _4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new _4(()=>{return this.commandPalette.disable(),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null,this.connectionErrorMessage.setValue(null)}),"handled"}),J=new _4(()=>{return c4.instance.stop(),"handled"}),Y=new _4((D)=>{if(!D.text)return"ignored";return c4.instance.tuiInstance.clipboard.writeText(D.text).then(()=>{this.toastController.show(D.successMessage,"success",2000)}).catch((G)=>{_.error("Failed to copy Neo text to clipboard",{error:G}),this.toastController.show(D.failureMessage,"error",2000)}),"handled"}),Z=new _4(()=>{return c4.instance.toggleFrameStatsOverlay(),"handled"}),F=new _4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=new _4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[OW0,A],[l00,$],[Ah,J],[TZ,Y],[a00,B],[jW0,Q],[PW0,F],[fC,Z],[_W0,X]])}ensureDraftThreadSettingsInitialized(){if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=await xK0(this.widget.configService);if(!this.mounted)return;this.setState(()=>{this.draftThreadSettings=A})}catch(A){_.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(su);if(this.exitHintTimer.isActive())A.add(h00);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),c4.instance.stop();else this.exitHintTimer.activate()};dismissFirstOpenDialog=()=>{if(!this.firstOpenDialogVisible)return;this.setState(()=>{this.firstOpenDialogVisible=!1})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let B=A.find((J)=>J.type==="text");if(B&&B.type==="text")this.widget.history.add(B.text,tW0.cwd()),this.widget.history.reset();let $=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings);this.clearConnectionError(),this.sendUserMessage($,A,Q),this.setActiveClient($)};sendUserMessage(A,Q,B){A.observer.markMessageSent();let $=pX0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q){this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient(B),Q)this.sendUserMessage(B,[{type:"text",text:Q}])}catch(B){_.error("Failed to load thread",{error:B,threadID:A}),this.connectionErrorMessage.setValue(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`)}finally{this.setState(()=>{this.connectingToThreadID=null})}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.connectionErrorMessage.setValue(null),this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=tW0.cwd().replace(tW0.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";tW0.stdout.write(_C(B))}handleIdeSelection=async(A)=>{await this.widget.ideManager.connect(A)};dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.ideErrorSubscription?.unsubscribe(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}isConnectionErrorRelevant(A){if(!this.activeThreadContext)return!0;if(!A)return!0;return this.activeThreadContext.client.getThreadId()===A}clearConnectionError(){if(!this.connectionErrorMessage.getValue())return;this.setState(()=>{this.connectionErrorMessage.setValue(null)})}clearActiveClientForConnectionError(){if(!this.activeThreadContext)return;this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.widget.notificationService.detach(),this.writeTerminalTitle(void 0),this.activeThreadContext=null})}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.firstOpenDialogVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}t4();function V7A(A,Q,B,$){let J=ak(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new wZ(G,V),K=new nJ(42),E=new kC(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic",void 0,void 0,C0.default(),K);E.layout(O1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let j=0;j<V;j++)if(W[j].some((P)=>P.char!==" ")){H=j;break}let z=V-1;for(let j=V-1;j>=0;j--)if(W[j].some((P)=>P.char!==" ")){z=j;break}function q(j,P){if(!j)return"";if(j.type==="rgb"){let{r:R,g:b,b:g}=j.value;if(B.getColorDepth()>=24)return`\x1B[${P?38:48};2;${R};${b};${g}m`;let f=LP(R,b,g);return`\x1B[${P?38:48};5;${f}m`}return""}let N=[];if(z>=H)for(let j=H;j<=z;j++){let P="";for(let R=0;R<G;R++){let b=W[j][R],g=b.char,f=q(b.style.fg,!0);P+=f+g+"\x1B[0m"}N.push(P)}let I=N.length,C=Math.max(I,D.length),w=Math.floor((C-I)/2),M=Math.floor((C-D.length)/2);for(let j=0;j<C;j++){let P=" ".repeat(G);if(j>=w&&j<w+I)P=N[j-w];let R=" ",b="";if(j>=M&&j<M+D.length)b=D[j-M];B.write(P+R+b+`
|
|
5176
|
+
`,new u({color:Q.foreground,dim:!0})),new O("If you need a reply, post on X @AmpCode or email amp-devs@ampcode.com.",new u({color:Q.foreground,dim:!0}))]),textAlign:"center"})}}var $7A={kind:"fill",modalRows:17};function B7A(A){return new z6({header:A.title,tone:A.tone,minWidth:80,maxWidth:80,bodyFit:$7A,onDismiss:A.onDismiss,child:A.child})}function J7A(A,Q){return{noun:"thread",verb:"share with support",description:"Share with Amp support for debugging",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;B.push(new V_({header:"Share Thread with Support",placeholder:"What went wrong? (Need a reply? Email amp-devs@ampcode.com.)",isRequired:!1,bodyFit:$7A,onDismiss:J,onSubmit:async(Z)=>{try{await A.shareThreadWithSupport(Y,Z||void 0),B.push(B7A({title:"Thread shared",tone:"success",onDismiss:J,child:new zB1}))}catch(F){_.error("Failed to share thread with support",{error:F,threadID:Y}),B.push(B7A({title:"Share with Support failed",tone:"error",onDismiss:J,child:new r({text:new O(`Failed to share thread with support: ${F instanceof Error?F.message:String(F)}`)})}))}}}))}}}var oQ8=["private","workspace","unlisted","public"];class F7A extends R1{props;constructor(A){super();this.props=A}build(A){let{colors:Q,app:B}=T0.of(A);return new e6({items:oQ8,getLabel:($)=>`${Y7A($)} ${Z7A($)}`,showBorder:!1,onAccept:this.props.onSelect,onDismiss:this.props.onDismiss,renderItem:($,J)=>{let Y=J?B.selectionBackground:void 0,Z=J?B.selectionForeground:Q.foreground,F=J?B.selectionForeground:Q.mutedForeground;return new p0({decoration:Y?{color:Y}:void 0,padding:M0.symmetric(1,0),child:new J1({crossAxisAlignment:"center",children:[new k1({child:new r({text:new O(Y7A($),new u({color:Z})),maxLines:1,overflow:"ellipsis"})}),new j0({width:2}),new r({text:new O(Z7A($),new u({color:F})),maxLines:1,overflow:"ellipsis"})]})})}})}}function Y7A(A){switch(A){case"private":return"Private";case"workspace":return"Workspace";case"group":return"Group";case"unlisted":return"Unlisted";case"public":return"Public"}}function Z7A(A){switch(A){case"private":return"Only you can see this thread";case"workspace":return"Visible to workspace members";case"group":return"Visible to group members";case"unlisted":return"Anyone with the link can view";case"public":return"Searchable and on your public profile"}}async function rQ8(A,Q,B,$){let J=await A.setVisibility(Q,B);if(J instanceof RB)$?.show(J.message,"success");else $?.show(J.message,"error")}function X7A(A,Q){return{noun:"thread",verb:"set visibility",description:"Set thread visibility",keywords:["share","private","workspace","public","unlisted","team","group"],get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client?.getThreadId();if(!Y)return;let Z=_9.maybeOf($);B.push(new z6({header:"Set Thread Visibility",autofocus:!1,minWidth:80,maxWidth:80,onDismiss:J,child:new F7A({onDismiss:J,onSelect:(F)=>{J(),rQ8(A,Y,F,Z)}})}))}}}class NB1 extends v0{initialAgentMode;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;history;updateDraftThreadSettings;onNewThread;shareThreadWithSupport;setThreadVisibility;archiveThread;addThreadLabel;removeThreadLabel;configService;connectionErrorMessage;hints;ideStatus;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.shareThreadWithSupport=A.shareThreadWithSupport,this.setThreadVisibility=A.setThreadVisibility,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.connectionErrorMessage=A.connectionErrorMessage,this.hints=A.hints,this.ideStatus=A.ideStatus}createState(){return new D7A}}class D7A extends k0{historyIndex=-1;historyDraft=null;promptHistoryPicker=new oe(this);agentMode;copyOnSelectEnabled=!0;copyOnSelectSubscription=null;expansion=new MQ1;previousThreadIDForReference=null;unregisterCommands=null;initState(){this.agentMode=this.widget.initialAgentMode,this.unregisterCommands=this.registerCommands(),this.subscribeToCopyOnSelectEnabled()}didUpdateWidget(A){if(A.configService!==this.widget.configService)this.subscribeToCopyOnSelectEnabled();if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.historyIndex=-1,this.historyDraft=null,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null;else this.previousThreadIDForReference=null}dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.copyOnSelectSubscription?.unsubscribe(),this.copyOnSelectSubscription=null}registerCommands(){let A=SZ.of(this.context),Q=uQ.of(this.context),B=this,$=()=>{return B.widget.threadContext??null},J=()=>{let X=B.widget.threadContext?.client.getThreadId();if(!X)return null;return xY(new URL(Q.ampURL),X).toString()},F=[...JJ(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:X})=>({noun:"mode",verb:`use ${X}`,description:`Enable ${X} mode`,get status(){if(B.widget.threadContext)return{type:"disabled",reason:"Mode can only be changed on a new thread"};if(X===B.agentMode)return{type:"disabled",reason:`Already using ${X} mode`};return{type:"enabled"}},run:(D,G,V)=>{B.setAgentMode(X),V()}})),{noun:"speed",verb:"toggle speed",description:"Toggle speed (fast/standard) for this thread",keywords:["anthropic","openai","fast","standard","smart","deep"],get status(){let X=B.currentCommandAgentMode();return X==="smart"||x2(X)?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleSpeed(),G()}},{noun:"thread",verb:"toggle thinking blocks",description:"Expand or collapse all thinking blocks",keywords:["thinking","expand","collapse","reasoning"],shortcut:p1.alt("t"),status:{type:"enabled"},run:(X,D,G)=>{B.toggleGlobalThinking(),G()}},{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",keywords:["deep","thinking","reasoning","effort","depth","anthropic","openai","smart","frontier"],shortcut:p1.alt("d"),get status(){return Rc(B.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleReasoningEffort(),G()}},{noun:"prompt",verb:"history",description:"Restore a previous prompt",keywords:["recent","reuse","search"],shortcut:p1.ctrl("r"),status:{type:"enabled"},run:(X,D,G)=>{X.pushWithDismiss((V)=>new sW0({entries:this.widget.history.getAll(),currentCwd:qB1.cwd(),onAccept:(U)=>{this.restorePromptHistory(U),G()},onDismiss:V}))}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",keywords:["identifier","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;sA.maybeInvoke(D,new TZ(V,"Thread ID copied to clipboard","Failed to copy thread ID")),G()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["link","share","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=J();if(!V)return;sA.maybeInvoke(D,new TZ(V,"Thread URL copied to clipboard","Failed to copy thread URL")),G()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",keywords:["markdown","export","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;(async()=>{try{let U=await Q.getThreadMarkdown(V);if(!U){_9.error(D,"Failed to copy thread markdown");return}sA.maybeInvoke(D,new TZ(U,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(U){_.error("Failed to render thread markdown from Neo command palette",{error:U,threadID:V}),_9.error(D,"Failed to copy thread markdown")}finally{G()}})()}},{noun:"thread",verb:"analyze context",description:"Analyze context token usage",keywords:["tokens","usage","window","size","cost"],get status(){let X=B.widget.threadContext;if(!X)return{type:"disabled",reason:"No active thread"};let D=YJ(X.observer.agentMode);if(!Z2A.includes(D))return{type:"disabled",reason:"Context analysis requires Claude Opus 4.7 (smart) or GPT-5.4 (deep)"};return{type:"enabled"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>{return new z6({header:"Context Usage Analysis",minWidth:60,maxWidth:60,chromePadding:M0.symmetric(1,0),footer:[{keys:["Esc"],label:"close"}],onDismiss:G,child:new r00({embedded:!0,contentWidth:58,thread:null,dtwAnalyze:(K)=>{return B.widget.analyzeContextForThread(D,K)},onDismiss:G})})})}},{noun:"skills",verb:"list",description:"List available skills for this thread",keywords:["agent","show"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>new HB1({listSkills:(V)=>B.widget.listSkillsForThread(D,V),onDismiss:G,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start","reset","clear"],sortBoost:101,get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(X,D)=>{sA.maybeInvoke(D,new l00)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web","view","launch"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(X,D,G)=>{let V=J();if(!V)return;try{await t6(D,V)}finally{G()}}},J7A({shareThreadWithSupport:(X,D)=>{return this.widget.shareThreadWithSupport(X,D)}},$),X7A({setVisibility:(X,D)=>this.widget.setThreadVisibility(X,D)},$),N9A({archiveThread:(X)=>this.widget.archiveThread(X)},$),Q7A($),p9A({configService:this.widget.configService,addLabel:(X,D)=>this.widget.addThreadLabel(X,D)},$),l9A({configService:this.widget.configService,removeLabel:(X,D)=>this.widget.removeThreadLabel(X,D)},$)].map((X)=>A.register(X));return()=>{for(let X of F)X()}}currentCommandAgentMode(){return this.widget.threadContext?.observer.agentMode??this.agentMode}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let B=Q.observer.threadSettings().getValue()??{},$=A(B);return Q.client.sendClientUpdateThreadSettings($),this.widget.updateDraftThreadSettings(()=>$),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){let A=this.currentCommandAgentMode();if(A==="smart")return this.updateThreadSettings((Q)=>{let B={...Q};if(B["anthropic.speed"]==="fast")delete B["anthropic.speed"];else B["anthropic.speed"]="fast";return B});if(x2(A))return this.updateThreadSettings((Q)=>{let B={...Q};if(B["openai.speed"]==="fast")B["openai.speed"]="standard";else B["openai.speed"]="fast";return B});return"ignored"}toggleGlobalThinking(){return this.expansion.toggle(),"handled"}toggleReasoningEffort(){let A=this.currentCommandAgentMode(),Q=Rc(A);if(!Q)return"ignored";return this.updateThreadSettings((B)=>{let $=T90(A,B);if(!$)return B;let J=B[$]??Z3(A)?.reasoningEffort,Y=_90(Q,J);return{...B,[$]:Y}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,qB1.cwd()),this.resetHistory()};restorePromptHistory(A){this.resetHistory(),this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd()}handlePromptHistorySelection=(A)=>{this.promptHistoryPicker.disable(),this.restorePromptHistory(A)};navigateHistoryPrevious=()=>{let A=this.widget.history.previous();if(A!==null){if(this.historyIndex===-1)this.historyDraft=this.widget.editorController.text;this.historyIndex++,this.widget.editorController.text=A,this.widget.editorController.moveCursorToStart()}return"handled"};navigateHistoryNext=()=>{let A=this.widget.history.next();if(A!==null)this.historyIndex--,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.widget.editorController.text=this.historyDraft||"",this.widget.editorController.moveCursorToEnd(),this.historyDraft=null;return"handled"};resetHistory(){this.widget.history.reset(),this.historyIndex=-1,this.historyDraft=null}setAgentMode(A){if(this.widget.threadContext)return;this.setState(()=>{this.agentMode=A}),OZ((Q)=>({...Q,agentMode:A}))}buildActions(){let A=new _4(()=>{return this.promptHistoryPicker.enable(),"handled"}),Q=new _4(()=>{return this.navigateHistoryPrevious()}),B=new _4(()=>{return this.navigateHistoryNext()}),$=new _4((Z)=>{return this.setAgentMode(Z.mode),"handled"}),J=new _4(()=>{return this.toggleReasoningEffort()}),Y=new _4(()=>{return this.toggleGlobalThinking()});return new Map([[dH,A],[SW0,B],[TW0,Q],[o00,$],[kW0,J],[RW0,Y]])}build(A){let Q=this.widget.threadContext,$=[Q?new FB1({editorController:this.widget.editorController,copyOnSelectEnabled:this.copyOnSelectEnabled,observingClient:{client:Q.client,observer:Q.observer},hints:this.widget.hints,ideStatus:this.widget.ideStatus,onPromptSubmitted:this.onPromptSubmitted}):new EB1({agentMode:this.agentMode,threadSettings:this.widget.draftThreadSettings,editorController:this.widget.editorController,onNewThread:this.widget.onNewThread,previousThreadIDForReference:this.previousThreadIDForReference,connectionErrorMessage:this.widget.connectionErrorMessage,hints:this.widget.hints,ideStatus:this.widget.ideStatus,configService:this.widget.configService})];if(this.promptHistoryPicker.isEnabled())$.push(new sW0({entries:this.widget.history.getAll(),currentCwd:qB1.cwd(),onAccept:this.handlePromptHistorySelection,onDismiss:this.promptHistoryPicker.disable}));let J=new Map([[p1.ctrl("r"),new dH],[p1.alt("d"),new kW0],[p1.alt("t"),new RW0]]);if(this.promptHistoryPicker.isEnabled())J.set(p1.ctrl("o"),new dH);else J.set(p1.ctrl("n"),new SW0),J.set(p1.ctrl("p"),new TW0);return new sA({actions:this.buildActions(),child:new U3({debugLabel:"NeoThreadShortcuts",shortcuts:J,child:new TX({controller:this.expansion,child:new vA({children:$})})})})}subscribeToCopyOnSelectEnabled(){this.copyOnSelectSubscription?.unsubscribe(),this.copyOnSelectSubscription=this.widget.configService.config.pipe(N1((A)=>A.settings["terminal.copyOnSelect"]??!0),x4()).subscribe((A)=>{if(this.copyOnSelectEnabled===A)return;if(this.copyOnSelectEnabled=A,this.mounted)this.setState()})}}class IB1 extends v0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;isFirstOpen;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,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.initialThreadID=A.initialThreadID,this.isFirstOpen=A.isFirstOpen??!1,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new G7A}}class G7A extends k0{editorController=new x3;commandPalette=new oe(this);commandRegistry=new VQ1;toastController=new e31;exitHintTimer=new ae(this,1000);connectionErrorMessage=new t2(this,null);ideStatus=new t2(this,{});draftThreadSettings={};draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;ideErrorSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;firstOpenDialogVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.clearConnectionError(),this.connectToExistingThread(A)};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await y3A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return x3A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await V6A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await U6A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await K6A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(C$.getInstance().interceptConsole(),this.widget.isFirstOpen)this.firstOpenDialogVisible=!0;if(this.connectionErrorMessage.subscribe(this.widget.clientPool.connectionErrors$.pipe(tE(({threadID:Q,error:B})=>{_.error("Neo failed to connect to thread",{threadID:Q,error:B})}),Y5(({threadID:Q})=>this.isConnectionErrorRelevant(Q)),tE(()=>this.clearActiveClientForConnectionError()),N1(({threadID:Q,error:B})=>{return Q?`Connection failed for ${Q}: ${B.message}`:`Connection failed: ${B.message}`}))),this.ideStatus.subscribe(this.widget.ideManager.status),this.ideErrorSubscription=this.widget.ideManager.errors$.subscribe((Q)=>{if(Q)this.setState(()=>{this.connectionErrorMessage.setValue(Q)})}),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID)this.connectToExistingThread(this.widget.initialThreadID,A);else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new JQ1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=c4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this.widget.neoContext.pluginService?S3A({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,toastController:this.toastController}):[],B=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:($,J,Y)=>{$.pushWithDismiss((Z)=>$B1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Z,onThreadSelected:Y}))}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:($)=>{$.pushWithDismiss((J)=>new wQ1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:J}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async($,J,Y)=>{try{await t6(J,"https://ampcode.com/chronicle")}finally{Y()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{oJ(this.widget.neoContext.settingsFilePath).catch(($)=>{_.error("Failed to open settings file in editor",{error:$})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:($,J,Y)=>{$.pushWithDismiss((Z)=>new IQ1({onCancel:Z,onSelect:(F)=>{this.handleIdeSelection(F),Y()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:($,J)=>{$.pushWithDismiss((Y)=>new HQ1({commands:SZ.of(J).commands,onDismiss:Y}))}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:($)=>{$.pushWithDismiss((J)=>new z6({header:"Amp Version",maxWidth:72,onDismiss:J,child:new r({text:new O(n31({version:"0.0.1777352624-g869aa9",buildTimestamp:"2026-04-28T05:07:34.445Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:p1.ctrl("c"),status:{type:"enabled"},run:($,J)=>{sA.maybeInvoke(J,new Ah)}},...A,...I3A(this.widget.neoContext.logFilePath)].map(($)=>this.commandRegistry.register($));return()=>{for(let $ of B)$()}}build(A){let Q=this.buildHints(),B=this.connectionErrorMessage.getValue(),$=this.ideStatus.getValue(),J=new NB1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,connectionErrorMessage:B,hints:Q,ideStatus:$}),Y=F4.of(A),F=[new p0({constraints:O1.tight(Y.size.width,Y.size.height),child:J})];if(this.commandPalette.isEnabled())F.push(new UQ1({onDismiss:this.commandPalette.disable}));if(this.switchThreadPickerVisible)F.push($B1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.firstOpenDialogVisible)F.push(new qQ1({onDismiss:this.dismissFirstOpenDialog}));if(F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser&&this.debugOverlayVisible)F.push(new zQ1({top:this.focusDebugVisible?33:1,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)F.push(new NQ1);return new uQ({neoContext:this.widget.neoContext,child:new SZ({commandRegistry:this.commandRegistry,child:new Bw({completionBuilder:this.widget.completionBuilder,child:new _9({controller:this.toastController,child:new sA({actions:this.buildActions(),child:new U3({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[p1.ctrl("c"),new OW0],[p1.ctrl("o"),new jW0],[p1.alt("i"),new PW0],[p1.alt("p"),new fC],[p1.ctrl("t"),new _W0]]),child:new e4({debugLabel:"AppShellFocus",child:new A21({controller:this.toastController,child:new vA({children:F})})})})})})})})})}buildActions(){let A=new _4(()=>{if(aJ.hasAnyCopyableSelection())return aJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new _4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new _4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new _4(()=>{return this.commandPalette.disable(),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null,this.connectionErrorMessage.setValue(null)}),"handled"}),J=new _4(()=>{return c4.instance.stop(),"handled"}),Y=new _4((D)=>{if(!D.text)return"ignored";return c4.instance.tuiInstance.clipboard.writeText(D.text).then(()=>{this.toastController.show(D.successMessage,"success",2000)}).catch((G)=>{_.error("Failed to copy Neo text to clipboard",{error:G}),this.toastController.show(D.failureMessage,"error",2000)}),"handled"}),Z=new _4(()=>{return c4.instance.toggleFrameStatsOverlay(),"handled"}),F=new _4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=new _4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[OW0,A],[l00,$],[Ah,J],[TZ,Y],[a00,B],[jW0,Q],[PW0,F],[fC,Z],[_W0,X]])}ensureDraftThreadSettingsInitialized(){if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=await xK0(this.widget.configService);if(!this.mounted)return;this.setState(()=>{this.draftThreadSettings=A})}catch(A){_.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(su);if(this.exitHintTimer.isActive())A.add(h00);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),c4.instance.stop();else this.exitHintTimer.activate()};dismissFirstOpenDialog=()=>{if(!this.firstOpenDialogVisible)return;this.setState(()=>{this.firstOpenDialogVisible=!1})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let B=A.find((J)=>J.type==="text");if(B&&B.type==="text")this.widget.history.add(B.text,tW0.cwd()),this.widget.history.reset();let $=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings);this.clearConnectionError(),this.sendUserMessage($,A,Q),this.setActiveClient($)};sendUserMessage(A,Q,B){A.observer.markMessageSent();let $=pX0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q){this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient(B),Q)this.sendUserMessage(B,[{type:"text",text:Q}])}catch(B){_.error("Failed to load thread",{error:B,threadID:A}),this.connectionErrorMessage.setValue(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`)}finally{this.setState(()=>{this.connectingToThreadID=null})}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.connectionErrorMessage.setValue(null),this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=tW0.cwd().replace(tW0.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";tW0.stdout.write(_C(B))}handleIdeSelection=async(A)=>{await this.widget.ideManager.connect(A)};dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.ideErrorSubscription?.unsubscribe(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}isConnectionErrorRelevant(A){if(!this.activeThreadContext)return!0;if(!A)return!0;return this.activeThreadContext.client.getThreadId()===A}clearConnectionError(){if(!this.connectionErrorMessage.getValue())return;this.setState(()=>{this.connectionErrorMessage.setValue(null)})}clearActiveClientForConnectionError(){if(!this.activeThreadContext)return;this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.widget.notificationService.detach(),this.writeTerminalTitle(void 0),this.activeThreadContext=null})}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.firstOpenDialogVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}t4();function V7A(A,Q,B,$){let J=ak(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new wZ(G,V),K=new nJ(42),E=new kC(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic",void 0,void 0,C0.default(),K);E.layout(O1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let j=0;j<V;j++)if(W[j].some((P)=>P.char!==" ")){H=j;break}let z=V-1;for(let j=V-1;j>=0;j--)if(W[j].some((P)=>P.char!==" ")){z=j;break}function q(j,P){if(!j)return"";if(j.type==="rgb"){let{r:R,g:b,b:g}=j.value;if(B.getColorDepth()>=24)return`\x1B[${P?38:48};2;${R};${b};${g}m`;let f=LP(R,b,g);return`\x1B[${P?38:48};5;${f}m`}return""}let N=[];if(z>=H)for(let j=H;j<=z;j++){let P="";for(let R=0;R<G;R++){let b=W[j][R],g=b.char,f=q(b.style.fg,!0);P+=f+g+"\x1B[0m"}N.push(P)}let I=N.length,C=Math.max(I,D.length),w=Math.floor((C-I)/2),M=Math.floor((C-D.length)/2);for(let j=0;j<C;j++){let P=" ".repeat(G);if(j>=w&&j<w+I)P=N[j-w];let R=" ",b="";if(j>=M&&j<M+D.length)b=D[j-M];B.write(P+R+b+`
|
|
5177
5177
|
`)}if($)B.write(`
|
|
5178
5178
|
\x1B[90m${$}\x1B[0m
|
|
5179
5179
|
`)}l0();aK0();var sQ8=2000;function U7A(A){let Q=!0,B=!0,$=A.configService.config.subscribe((V)=>{Q=V.settings["notifications.enabled"]??!0,B=V.settings["notifications.system.enabled"]!==!1}),J=0,Y=(V)=>{if(!Q)return;let U=Date.now();if(U-J<sQ8)return;if(J=U,kP())return;if(dU0())cU0();else er(V)},Z=(V)=>{if(!Q||!B)return;if(kP()&&!me()&&!UK0())return;process.stdout.write(vG(`\x1B]777;notify;Amp;${V}\x1B\\`))},F=null,X=null,D=()=>{F?.unsubscribe(),F=null,X=null};return{attach:(V)=>{D(),F=V.subscribe({next:(U)=>{try{let K=X!==null&&IC(X),E=X==="awaiting_approval";if(U==="awaiting_approval"&&!E)Y("requires-user-input"),Z("Waiting for approval");else if((U==="idle"||U==="error")&&(K||E))Y("idle"),Z("Agent is ready")}catch(K){_.debug("Neo notification handling failed",{error:K})}finally{X=U}},error:(U)=>{_.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}l0();FW();z4();w1();function K7A(A,Q){if(!Q)return A;let B=Q.toLowerCase(),$=[];for(let J of A){let Y=tQ8(J,B);if(Y>0)$.push({...J,score:Y})}return $.sort((J,Y)=>{let Z=Y.score-J.score;if(Z!==0)return Z;return A.indexOf(J)-A.indexOf(Y)}),$}function tQ8(A,Q){let B=eQ8(A,Q),$=AB8(A.message.toLowerCase(),Q);return Math.max(B,$)}function eQ8(A,Q){let B=A.hash.toLowerCase(),$=A.shortHash.toLowerCase();if($===Q)return 1000;if($.startsWith(Q))return 900;if(B.startsWith(Q))return 850;if(B.includes(Q)||$.includes(Q))return 400;return 0}function AB8(A,Q){if(A===Q)return 800;if(A.startsWith(Q))return 700;let B=A.indexOf(Q);if(B!==-1)return 600-Math.min(B,500);let $=QB8(A,Q);if($>0)return $;return 0}function QB8(A,Q){let B=0,$=0,J=-1;while(B<A.length&&$<Q.length){if(A[B]===Q[$]){if(J===-1)J=B;$++}B++}if($===Q.length)return 250-Math.min(J,150);return 0}var E7A=":";function q_(A,Q){if(!HP())return;_.debug("[file mention completions]",{event:A,...Q})}function Fh(A){return A.length<=80?A:`${A.slice(0,77)}...`}class N_{fuzzyClient;cachedDirtyFiles=[];cachedCommits=[];refreshPromise;refreshCommitsPromise;constructor(A){this.fuzzyClient=A;this.refreshDirtyFilesInBackground(),this.refreshCommitsInBackground()}async buildOptions(A){if(A.trigger==="@"){let Q=A.query;if(Q.toLowerCase().startsWith(E7A)){let Z=Q.slice(E7A.length);return q_("commit_query_detected",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Z.length,queryPreview:Fh(Z)}),this.buildCommitOptions(Z)}let $=Q.length===0?18:20,J=await this.buildFileOptions(Q,$),Y=this.appendHintOptions(Q,J);return q_("build_options_completed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Q.length,queryPreview:Fh(Q),maxResults:$,fileOptionCount:J.filter((Z)=>Z.type==="file").length,hintOptionCount:Y.filter((Z)=>Z.type==="hint").length,finalOptionCount:Y.length,firstFilePaths:Y.filter((Z)=>Z.type==="file").slice(0,5).map((Z)=>Z.path)}),Y}return[]}async buildFileOptions(A,Q){try{let B=await this.getOpenFiles(),$=this.cachedDirtyFiles;this.refreshDirtyFilesInBackground();let J=await this.fuzzyClient.queryCompletions(A,Q,B,$),Y=J.map((Z)=>d2A(Z));return q_("file_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Fh(A),maxResults:Q,openFilesCount:B?.length??0,dirtyFilesCount:$.length,completionItemCount:J.length,fileOptionCount:Y.length,firstPaths:Y.slice(0,5).map((Z)=>Z.path)}),Y}catch(B){return q_("file_options_failed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Fh(A),maxResults:Q,error:B instanceof Error?B.message:String(B)}),[]}}async getOpenFiles(){let A=await T1(a8.status);if(!A.connected)return;let Q=[];if(A.openFile)Q.push(F1.parse(A.openFile).fsPath);if(A.visibleFiles)for(let B of A.visibleFiles){let $=F1.parse(B).fsPath;if(!Q.includes($))Q.push($)}if(Q.length===0)return;return Q}refreshDirtyFilesInBackground(){if(this.refreshPromise!==void 0)return;this.refreshPromise=ck4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedDirtyFiles=A}).catch(()=>{}).finally(()=>{this.refreshPromise=void 0})}async buildCommitOptions(A){this.refreshCommitsInBackground();let Q=this.cachedCommits;if(!Q.length)return q_("commit_options_empty_cache",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Fh(A)}),[];let B=K7A(Q,A).slice(0,20);return q_("commit_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Fh(A),commitCacheCount:Q.length,resultCount:B.length,firstCommitHashes:B.slice(0,5).map(($)=>$.shortHash)}),B.map(($)=>({type:"commit",hash:$.hash,shortHash:$.shortHash,message:$.message,relativeDate:$.relativeDate}))}refreshCommitsInBackground(){if(this.refreshCommitsPromise!==void 0)return;this.refreshCommitsPromise=lk4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedCommits=A}).catch(()=>{}).finally(()=>{this.refreshCommitsPromise=void 0})}appendHintOptions(A,Q){if(A.length>0)return Q;let B=[{type:"hint",kind:"commit",message:"mention a commit"},{type:"hint",kind:"thread",message:"mention a thread"}];return q_("hint_options_appended",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,fileOptionCount:Q.filter(($)=>$.type==="file").length,hintOptionCount:B.length,hintOnly:Q.length===0,firstFilePaths:Q.filter(($)=>$.type==="file").slice(0,5).map(($)=>$.path)}),[...Q,...B]}}var $B8=[{long:"neo",description:"Use the Neo TUI",type:"boolean",default:!1},{long:"url",short:"u",description:"Amp server URL",type:"string",default:""},{long:"dangerously-allow-all",description:"Disable all command confirmation prompts (agent will execute all commands without asking)",type:"boolean",default:!1},{long:"observe",description:"Connect to an existing thread as observer only (no local executor). Accepts a thread ID or thread URL.",type:"string",default:""}],hg2=G1A({name:"amp neo",description:"Start the Neo TUI",options:$B8,positionals:[],action:async({options:A})=>{let Q=W7A(A);if(A.observe){let B=M3(A.observe)??qB(A.observe);await eW0(Q,{initialThreadID:B,observerOnly:!0});return}await eW0(Q)},subcommands:[{name:"threads",alias:"t",description:"List and manage threads",options:[],positionals:[],subcommands:[{name:"continue",alias:"c",description:"Continue an existing thread",options:[],positionals:[{name:"thread-id",description:"Thread ID to continue"}],action:async({globalOptions:A,positionals:Q})=>{let $=W7A(A);if(!Q["thread-id"]){await eW0($,{openThreadPickerOnStart:!0});return}let J=M3(Q["thread-id"]);if(!J)throw"invalid thread ID";await eW0($,{initialThreadID:J})}}]}]});function JB8(A){if(A)return A;if(process.env.AMP_URL)return process.env.AMP_URL;return x9}function YB8(A){if(process.env.RIVET_PUBLIC_ENDPOINT)return process.env.RIVET_PUBLIC_ENDPOINT;return pJ(A)}var H7A=F1.file(BB8.homedir()),ZB8=process.env.XDG_CONFIG_HOME?F1.file(process.env.XDG_CONFIG_HOME):U1.joinPath(H7A,".config");async function FB8(A){await OZ((Q)=>mK0(Q,A,"interactive"))}function W7A(A){return{url:A.url,dangerouslyAllowAll:A["dangerously-allow-all"]}}async function eW0(A,Q={}){let{initialThreadID:B,openThreadPickerOnStart:$=!1,observerOnly:J=!1}=Q,Y=JB8(A.url),Z={dataDir:void 0,getHook:(M,j)=>{if(M==="url")return Promise.resolve(Y);return j()}},F=await oU0(Z),X=gK0(await Be(Z,F)),D=YB8(Y);if(A.dangerouslyAllowAll)y9("dangerouslyAllowAll",!0);let G=await X.get("apiKey",Y);if(!G)throw new E4("API key required. Please run `amp login` first.",1);let V=ck({storage:F,secretStorage:X,workspaceRoot:g0.of(F1.file(process.cwd())),defaultAmpURL:Y,homeDir:H7A,userConfigDir:ZB8}),U=oO(V),K=LD0({configService:V}),E=new Eu({configService:V});E.pluginExecutorKind="local";let W=Ri({configService:V,fileSystem:L8,platform:E,internalPlugins:Q0A,pluginFilter:process.env.PLUGINS??"off"}),H=Z$0({pluginService:W,toolService:K.toolService}),z=BJ0({configService:V,filesystem:L8}),q={registerToolsWithToolService:()=>({dispose:()=>{}}),getClient:()=>{return},servers:g0.of([]),getPrompt:async()=>null,searchResources:async()=>[],searchPrompts:()=>g0.of([]),getToolsForServer:async()=>{return}},N=process.cwd(),I=async({uri:M})=>{return CC({fileSystem:L8,workspaceRoot:N},M)},C=new Bu(N,{},!0),w=new N_(C);await CB1({ampURL:Y,apiKey:G,rivetEndpoint:D,configService:V,toolService:K.toolService,pluginPlatform:E,pluginService:W,skillService:z,mcpService:q,readFileSystemDirectory:I,completionBuilder:w,workspaceRoot:N,listThreads:()=>U.listThreads(),getThreadFromServer:(M)=>U.getThread(M),isInternalUser:!1,settingsFilePath:F.getSettingsFilePath(),dispose:()=>{return C.dispose(),H.dispose(),K.dispose(),W.dispose()}},{initialThreadID:B,openThreadPickerOnStart:$,observerOnly:J})}async function CB1(A,Q={}){let{initialThreadID:B,initialUserInput:$,openThreadPickerOnStart:J=!1,observerOnly:Y=!1,initialAgentMode:Z}=Q,F=async(z)=>{let q=await A.getThreadFromServer(z);if(!q)return null;return RU0(q)},X=new O31(A.rivetEndpoint,A.apiKey,A.configService,{clientID:zC.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,invokeTool:async(z,q)=>{let N=typeof q.args==="object"&&q.args!==null?q.args:{},I=await _K({toolName:q.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:q.toolCallId,threadID:z});return A.toolService.invokeTool(q.toolName,{args:N},I)},persistLastThreadID:FB8,readFileSystemDirectory:A.readFileSystemDirectory},F),D=await Wu(),G={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(z)=>{let q=await A.getThreadFromServer(z);return q?KU(q):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:bt,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,observerOnly:Y,sessionAgentMode:Z??D.agentMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},V=(z,q)=>{return Sb({ampURL:A.ampURL,configService:A.configService,threadID:z,signal:q})},U=(z,q)=>{return H0A({ampURL:A.ampURL,configService:A.configService,threadID:z,signal:q})},K=new i31,E=C0A(D);OZ(w0A);let W=U7A({configService:A.configService}),H=new Set;try{await pe(new IB1({clientPool:X,analyzeContextForThread:V,listSkillsForThread:U,completionBuilder:A.completionBuilder,history:new nt,ideManager:K,configService:A.configService,initialThreadID:B,notificationService:W,initialUserInput:$,openThreadPickerOnStart:J,neoContext:G,isFirstOpen:E,onThreadArchived:(q)=>{H.add(q)}}));let z=X.lastActiveObservingClient;if(z){let{client:q,observer:N}=z,I=q.getThreadId();if(I){let C={id:I,title:N.title().getValue(),agentMode:N.agentMode,archived:H.has(I)},w=`${A.ampURL.replace(/\/$/,"")}/threads/${I}`;V7A(C,w,process.stdout)}}}finally{process.stdout.write(_C("")),W.unsubscribe(),X.dispose(),await A.dispose?.()}process.exit(0)}Cl();cL();async function XB8(A,Q,B){let $=u70(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=bq($.data);if(!J.success){let X=J.error.issues.map((D)=>D.message).join(", ");throw Error(`Invalid permission entry: ${X}`)}let Y=await Q.get("permissions",B)??[],F=[$.data[0],...Y];await Q.set("permissions",F,B)}async function z7A(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await XB8(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
|
|
@@ -5944,7 +5944,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
|
|
|
5944
5944
|
`),Y=[];for(let Z=0;Z<J.length;Z++){let D=J[Z].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let G of D)if(G.startsWith("\x00")&&G.endsWith("\x01"))Y.push(new O(G.slice(1,-1),new u({color:$.app.keybind,bold:!0})));else Y.push(new O(G,new u({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new O(`
|
|
5945
5945
|
`))}return new p0({decoration:{color:B.colorScheme.background,border:$4.all(new A4($.app.keybind,1,"rounded"))},child:new x0({padding:M0.symmetric(0,1),child:new r({text:new O(void 0,void 0,Y)})})})}}class x$1 extends o2{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=wz0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new v$1({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(A){let Q=A;Q.chartData=this.chartData,Q.highlightIndex=this.highlightIndex,Q.showAxes=this.showAxes,Q.colors=this.colors,Q.markNeedsLayout()}}function d$A(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let F=B;return F>=0&&F<Y?F:null}case"bar":case"stacked-bar":{let F=Z?A2:0,X=$-F;if(X<=0)return null;let D=Q-F;if(D<0||D>=X)return null;let G=Math.max(1,Math.floor(X/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let F=Z?A2:0,X=$-F;if(X<=0)return null;let D=Math.max(0,Math.min(X-1,Q-F));if(Y===1)return 0;let G=X/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function UD8(A,Q,B,$,J,Y,Z,F){if(J<=0||Q<0||Q>=J)return null;let X=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?A2:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=Math.max(1,Math.floor(G/J)),K=D+Q*U+Math.floor(U/2),E=F>0?Z/F:0,W=Math.round((1-E)*(V-1));return{x:K,y:W}}case"line":case"sparkline":case"stacked-area":{let D=Y?A2:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=J>1?D+Math.round(Q/(J-1)*(G-1)):D+Math.floor(G/2),K=F>0?Z/F:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function KD8(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function ED8(A,Q,B,$,J){if(B.length<=1){let F=$(A.value),X=A.meta?` (${A.meta})`:"";return A.label.length+2+F.length+X.length}let Y=A.label.length,Z=0;for(let F of B){let X=F.points[Q];if(!X)continue;Z+=X.value;let D=2+F.name.length+2+$(X.value).length;Y=Math.max(Y,D)}if(J){let F=9+$(Z).length;Y=Math.max(Y,F)}return Y}function WD8(A,Q,B,$,J,Y,Z){let F;try{let E=S1.of(A),W=T0.of(A);F={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:W.app.keybind}}catch{F={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let X=new u({color:F.foreground,bold:!0}),D=new u({color:F.foreground}),G=new u({color:F.foreground,dim:!0}),V=[],U=new u({color:F.foreground,underline:!0}),K=(E,W)=>new O(W,U,void 0,DK0(E),()=>{t6(A,E)});if($.length<=1){if(V.push(new O(`${Q.label}: `,X)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new O(Y(Q.value),D));if(Q.meta)V.push(new O(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new O(`${Q.label}
|
|
5946
5946
|
`,X));let W=0;for(let H=0;H<$.length;H++){let z=$[H],q=z.points[B];if(!q)continue;W+=q.value;let N=z.color??J[H%J.length]??F.foreground;if(V.push(new O("● ",new u({color:N}))),V.push(new O(`${z.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new O(Y(q.value),D));if(H<$.length-1||E)V.push(new O(`
|
|
5947
|
-
`))}if(E)V.push(new O(" ",G)),V.push(new O("Total: ",G)),V.push(new O(Y(W),D))}return new p0({decoration:{color:F.background,border:$4.all(new A4(F.border,1,"rounded"))},child:new r({text:new O(void 0,void 0,V)})})}l0();i8();oL();f9();w8();H7();lo();IF();WQ();C7();A$();ER();t4();_y();Mk();w1();l0();WQ();class f$1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1777351004-g64ae1a"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await y70(Q,this.configService)}catch(Q){_.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Lw extends v0{props;constructor(A){super();this.props=A}createState(){return new c$A}}class c$A extends k0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class l$A extends k0{controller=new x3;focusNode=new L6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=T0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=$4.all(new A4(B.foreground,1,"solid")),X=new w$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new J1({children:[new p0({decoration:{color:B.background},child:new r({text:new O(">",new u({color:B.foreground}))})}),new k1({child:X})]}),G=new p0({padding:M0.symmetric(1,0),child:new r({text:this.widget.props.title?new O(this.widget.props.title,new u({color:$.command,bold:!0})):new O("",void 0,[new O("Command: ",new u({color:B.foreground})),new O(this.widget.props.commandName,new u({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new O("Enter",new u({color:$.keybind}))),V.push(new O(" to submit, ",new u({color:B.foreground,dim:!0})));V.push(new O("Esc",new u({color:$.keybind}))),V.push(new O(" to cancel",new u({color:B.foreground,dim:!0})));let U=new p0({padding:M0.symmetric(1,0),child:new r({text:new O("",void 0,V)})});return new p0({decoration:{border:F,color:B.background},padding:M0.all(1),child:new b0({children:[G,new j0({height:1}),D,new s6,U]})})}}class j10 extends v0{props;constructor(A){super();this.props=A}createState(){return new l$A}}A$();class i$A extends k0{controller=new x3;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new L6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=bY)return!1;let Q=await SX(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=T0.of(A),{colors:B,app:$}=Q,Y=F4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new pG({controller:this.controller,triggers:[new AY],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:c4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new e4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new p0({constraints:new O1({maxHeight:Z}),padding:M0.symmetric(1,0),child:X}),G=new p0({padding:M0.symmetric(1,0),child:new r({text:new O("",void 0,[new O("Command: ",new u({color:B.foreground})),new O(this.widget.props.commandName,new u({color:$.command,bold:!0}))])})}),V=new p0({padding:M0.symmetric(1,0),child:new r({text:this.isConfirmingClearInput?new O("",void 0,[new O("Esc",new u({color:$.keybind})),new O(" again to clear input",new u({color:B.foreground,dim:!0}))]):new O("",void 0,[new O("Press ",new u({color:B.foreground,dim:!0})),new O("Enter",new u({color:$.keybind})),new O(" to submit, ",new u({color:B.foreground,dim:!0})),new O("Esc",new u({color:$.keybind})),new O(" to clear",new u({color:B.foreground,dim:!0}))])})}),U=[G,new j0({height:1}),new k1({child:D}),new j0({height:1}),V];return new p0({decoration:{border:$4.all(new A4(B.foreground,1,"solid")),color:B.background},padding:M0.all(1),child:new b0({children:U})})}}class b$1 extends v0{props;constructor(A){super();this.props=A}createState(){return new i$A}}function n$A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class u$1 extends R1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>n$A(J.pubDate).length));return new e6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,F)=>{let X=T0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new j0({width:H,child:J1.end([new r({text:new O(W,new u({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:M0.symmetric(2,0),child:new J1({children:[new k1({child:new r({text:new O(J.title,new u({color:U})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),E(n$A(J.pubDate),B)]})})}})}}class fB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!fB._instance)fB._instance=new fB;return fB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}l0();class a$A extends k0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){_.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){_.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=T0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),X=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new e6({title:"Add Label",items:X,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let H=this.currentQuery.trim().toLowerCase();return new p0({decoration:K?{color:K}:void 0,padding:M0.symmetric(2,0),child:new r({text:new O("",void 0,[new O("Create new label: ",new u({color:E})),new O(H,new u({color:E,bold:!0}))])})})}return new p0({decoration:K?{color:K}:void 0,padding:M0.symmetric(2,0),child:new r({text:new O(D.name,new u({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class h$1 extends v0{props;constructor(A){super();this.props=A}createState(){return new a$A}}class lG extends v0{props;constructor(A){super();this.props=A}createState(){return new o$A}}class o$A extends k0{_spinner=new M6;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=T0.of(A),{colors:B,app:$}=Q,J=$4.all(new A4(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new r({textAlign:"center",text:new O("",void 0,[new O(Y,new u({color:$.processing})),new O(" ",void 0),new O(this.widget.props.message,new u({color:B.foreground}))])}),X=[new k1({child:new b0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new j0({height:2,child:new p0({padding:M0.symmetric(2,0),child:new r({text:new O("",new u({dim:!0}),[new O("Press ",new u({color:B.foreground})),new O("Esc",new u({color:B.info})),new O(" to cancel",new u({color:B.foreground}))])})})}));let D=new p0({decoration:new o4(B.background,J),child:new j0({width:60,height:7,child:new b0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new GA({debugLabel:"LoadingDialog",child:new e4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class eK extends v0{props;constructor(A){super();this.props=A}createState(){return new r$A}}class r$A extends k0{scrollController=new I6;scrollAreaKey=new P9("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof A9}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=T0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=RE0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=$4.all(new A4(Q.colors.border,1,"solid")),Z=new p0({padding:M0.symmetric(1,0),child:new r({text:new O($.title,new u({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new r({text:new O($.description,new u({color:Q.colors.foreground})),selectable:!0}),X=new k1({child:new s2({child:new p0({padding:M0.symmetric(1,0),child:new J1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new wA({controller:this.scrollController,autofocus:!0,child:F})}),new w2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new p0({padding:M0.symmetric(1,0),child:new r({text:(()=>{if(this.widget.props.onRetry)return new O("",void 0,[new O("Press ",new u({color:Q.colors.foreground,dim:!0})),new O("R",new u({color:Q.app.keybind})),new O(" to retry, ",new u({color:Q.colors.foreground,dim:!0})),new O("Esc",new u({color:Q.app.keybind})),new O(" to cancel",new u({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new O("",new u({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new u({color:Q.app.keybind}),U=new u({color:Q.colors.foreground,dim:!0});return new O("",U,[new O("Press ",U),new O("Escape",V),new O(" to close • Use ",U),new O("↑↓",V),new O(" or ",U),new O("j/k",V),new O(" to scroll",U)])}return new O("Press any key to close",new u({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new GA({debugLabel:"MessageDialog",child:new vA({fit:"expand",children:[new s1({onClick:()=>{},child:new j0}),new e4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new p0({decoration:{border:Y,color:Q.colors.background},padding:M0.all(1),child:new b0({mainAxisAlignment:"center",children:[Z,new j0({height:1}),X,D]})})})]})})}}i8();class s$A extends v0{props;constructor(A){super();this.props=A}createState(){return new t$A}}class t$A extends k0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=t3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=T0.of(A),{app:B}=Q;if(this.plugins.length===0)return new r({text:new O("No plugins found.",new u({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new O(`${Y}/${J} ${N4(J,"plugin")} active`,new u({bold:!0}))),Z>0||F>0)$.push(new O(` (${Z} ${N4(Z,"command")}, ${F} ${N4(F,"tool")})`,new u({dim:!0})));$.push(new O(`
|
|
5947
|
+
`))}if(E)V.push(new O(" ",G)),V.push(new O("Total: ",G)),V.push(new O(Y(W),D))}return new p0({decoration:{color:F.background,border:$4.all(new A4(F.border,1,"rounded"))},child:new r({text:new O(void 0,void 0,V)})})}l0();i8();oL();f9();w8();H7();lo();IF();WQ();C7();A$();ER();t4();_y();Mk();w1();l0();WQ();class f$1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1777352624-g869aa9"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await y70(Q,this.configService)}catch(Q){_.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Lw extends v0{props;constructor(A){super();this.props=A}createState(){return new c$A}}class c$A extends k0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class l$A extends k0{controller=new x3;focusNode=new L6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=T0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=$4.all(new A4(B.foreground,1,"solid")),X=new w$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new J1({children:[new p0({decoration:{color:B.background},child:new r({text:new O(">",new u({color:B.foreground}))})}),new k1({child:X})]}),G=new p0({padding:M0.symmetric(1,0),child:new r({text:this.widget.props.title?new O(this.widget.props.title,new u({color:$.command,bold:!0})):new O("",void 0,[new O("Command: ",new u({color:B.foreground})),new O(this.widget.props.commandName,new u({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new O("Enter",new u({color:$.keybind}))),V.push(new O(" to submit, ",new u({color:B.foreground,dim:!0})));V.push(new O("Esc",new u({color:$.keybind}))),V.push(new O(" to cancel",new u({color:B.foreground,dim:!0})));let U=new p0({padding:M0.symmetric(1,0),child:new r({text:new O("",void 0,V)})});return new p0({decoration:{border:F,color:B.background},padding:M0.all(1),child:new b0({children:[G,new j0({height:1}),D,new s6,U]})})}}class j10 extends v0{props;constructor(A){super();this.props=A}createState(){return new l$A}}A$();class i$A extends k0{controller=new x3;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new L6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=bY)return!1;let Q=await SX(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=T0.of(A),{colors:B,app:$}=Q,Y=F4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new pG({controller:this.controller,triggers:[new AY],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:c4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new e4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new p0({constraints:new O1({maxHeight:Z}),padding:M0.symmetric(1,0),child:X}),G=new p0({padding:M0.symmetric(1,0),child:new r({text:new O("",void 0,[new O("Command: ",new u({color:B.foreground})),new O(this.widget.props.commandName,new u({color:$.command,bold:!0}))])})}),V=new p0({padding:M0.symmetric(1,0),child:new r({text:this.isConfirmingClearInput?new O("",void 0,[new O("Esc",new u({color:$.keybind})),new O(" again to clear input",new u({color:B.foreground,dim:!0}))]):new O("",void 0,[new O("Press ",new u({color:B.foreground,dim:!0})),new O("Enter",new u({color:$.keybind})),new O(" to submit, ",new u({color:B.foreground,dim:!0})),new O("Esc",new u({color:$.keybind})),new O(" to clear",new u({color:B.foreground,dim:!0}))])})}),U=[G,new j0({height:1}),new k1({child:D}),new j0({height:1}),V];return new p0({decoration:{border:$4.all(new A4(B.foreground,1,"solid")),color:B.background},padding:M0.all(1),child:new b0({children:U})})}}class b$1 extends v0{props;constructor(A){super();this.props=A}createState(){return new i$A}}function n$A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class u$1 extends R1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>n$A(J.pubDate).length));return new e6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,F)=>{let X=T0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new j0({width:H,child:J1.end([new r({text:new O(W,new u({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:M0.symmetric(2,0),child:new J1({children:[new k1({child:new r({text:new O(J.title,new u({color:U})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),E(n$A(J.pubDate),B)]})})}})}}class fB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!fB._instance)fB._instance=new fB;return fB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}l0();class a$A extends k0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){_.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){_.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=T0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),X=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new e6({title:"Add Label",items:X,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let H=this.currentQuery.trim().toLowerCase();return new p0({decoration:K?{color:K}:void 0,padding:M0.symmetric(2,0),child:new r({text:new O("",void 0,[new O("Create new label: ",new u({color:E})),new O(H,new u({color:E,bold:!0}))])})})}return new p0({decoration:K?{color:K}:void 0,padding:M0.symmetric(2,0),child:new r({text:new O(D.name,new u({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class h$1 extends v0{props;constructor(A){super();this.props=A}createState(){return new a$A}}class lG extends v0{props;constructor(A){super();this.props=A}createState(){return new o$A}}class o$A extends k0{_spinner=new M6;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=T0.of(A),{colors:B,app:$}=Q,J=$4.all(new A4(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new r({textAlign:"center",text:new O("",void 0,[new O(Y,new u({color:$.processing})),new O(" ",void 0),new O(this.widget.props.message,new u({color:B.foreground}))])}),X=[new k1({child:new b0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new j0({height:2,child:new p0({padding:M0.symmetric(2,0),child:new r({text:new O("",new u({dim:!0}),[new O("Press ",new u({color:B.foreground})),new O("Esc",new u({color:B.info})),new O(" to cancel",new u({color:B.foreground}))])})})}));let D=new p0({decoration:new o4(B.background,J),child:new j0({width:60,height:7,child:new b0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new GA({debugLabel:"LoadingDialog",child:new e4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class eK extends v0{props;constructor(A){super();this.props=A}createState(){return new r$A}}class r$A extends k0{scrollController=new I6;scrollAreaKey=new P9("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof A9}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=T0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=RE0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=$4.all(new A4(Q.colors.border,1,"solid")),Z=new p0({padding:M0.symmetric(1,0),child:new r({text:new O($.title,new u({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new r({text:new O($.description,new u({color:Q.colors.foreground})),selectable:!0}),X=new k1({child:new s2({child:new p0({padding:M0.symmetric(1,0),child:new J1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new wA({controller:this.scrollController,autofocus:!0,child:F})}),new w2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new p0({padding:M0.symmetric(1,0),child:new r({text:(()=>{if(this.widget.props.onRetry)return new O("",void 0,[new O("Press ",new u({color:Q.colors.foreground,dim:!0})),new O("R",new u({color:Q.app.keybind})),new O(" to retry, ",new u({color:Q.colors.foreground,dim:!0})),new O("Esc",new u({color:Q.app.keybind})),new O(" to cancel",new u({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new O("",new u({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new u({color:Q.app.keybind}),U=new u({color:Q.colors.foreground,dim:!0});return new O("",U,[new O("Press ",U),new O("Escape",V),new O(" to close • Use ",U),new O("↑↓",V),new O(" or ",U),new O("j/k",V),new O(" to scroll",U)])}return new O("Press any key to close",new u({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new GA({debugLabel:"MessageDialog",child:new vA({fit:"expand",children:[new s1({onClick:()=>{},child:new j0}),new e4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new p0({decoration:{border:Y,color:Q.colors.background},padding:M0.all(1),child:new b0({mainAxisAlignment:"center",children:[Z,new j0({height:1}),X,D]})})})]})})}}i8();class s$A extends v0{props;constructor(A){super();this.props=A}createState(){return new t$A}}class t$A extends k0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=t3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=T0.of(A),{app:B}=Q;if(this.plugins.length===0)return new r({text:new O("No plugins found.",new u({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new O(`${Y}/${J} ${N4(J,"plugin")} active`,new u({bold:!0}))),Z>0||F>0)$.push(new O(` (${Z} ${N4(Z,"command")}, ${F} ${N4(F,"tool")})`,new u({dim:!0})));$.push(new O(`
|
|
5948
5948
|
|
|
5949
5949
|
`));for(let X of this.plugins){let{icon:D,color:G}=this.statusIcon(X.status),V=this.getRelativePath(X.uri.toString());if($.push(new O(`${D} `,new u({color:G}))),$.push(new O(V,new u({bold:!0}))),$.push(new O(` ${X.status}`,new u({dim:!0}))),$.push(new O(`
|
|
5950
5950
|
`)),X.status==="active"&&X.registeredEvents.length>0)$.push(new O(" Events: ",new u({dim:!0}))),$.push(new O(X.registeredEvents.join(", "),new u({color:B.link}))),$.push(new O(`
|
|
@@ -6130,7 +6130,7 @@ ${o.content||""}`:o.content||"",P0=[],u0=o.baseDir.startsWith("file://")?Qq0(o.b
|
|
|
6130
6130
|
`)}function rZA(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async(B,$)=>{let J=$.optsWithGlobals(),Y=await Q(J),Z=await Y.settings.get("proxy"),F=_54({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),X=await hA.userDisplayBalanceInfo({},{config:F});if(!X.ok){if(X.error.code==="auth-required")process.stderr.write(n0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(n0.red("Error: ")+X.error.message+`
|
|
6131
6131
|
`),process.exit(1)}process.stdout.write(await cK8(X.result.displayText)+`
|
|
6132
6132
|
`),process.exit(0)})}var Vq8=W40.join(NF,"logs","headless.log"),aZ1=W40.join(Ju,"device-id.json"),Uq8=`cli-tui-${LGA(16).toString("hex")}`;async function Kq8(){for(let A of tL)try{if((await A.listConfigs()).length>0)return A}catch(Q){_.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => H4($g(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){x$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
|
|
6133
|
-
`)}function Eq8(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function Z7(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")y9("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")y9("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)y9("internal.model",Wq8(Q.model))}function zGA(A){let Q=A.indexOf(":");if(Q===-1)throw new E4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new E4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Wq8(A){if(!A.includes("="))return zGA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new E4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new E4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new E4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);zGA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new E4("No valid model overrides found in --model flag value.",1);return Q}function Hq8(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function zq8(A){try{return await OGA(A,"utf-8")}catch{return A}}async function qGA(A,Q,B){let $=Hq8(A,Q);if(!$)return;let J=xA(B)?B.features:[],Y=xA(B)?B.user.email:void 0;if(!Jg(J,D9.HARNESS_SYSTEM_PROMPT)&&!(Y&&E7(Y)))throw new E4("You are not allowed to do this.",1);y9("systemPrompt",await zq8($))}function Jg(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function qq8(A){return A!=="pending"}function Zg(A){if(!xA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Nq8(A){let Q=Zg(A);if(Q)return Q.id;if(WW(A))throw Error(A.error.message);throw Error("unreachable")}function Iq8(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 Cq8(A){let $=Iq8(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 E4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function rZ1(A,Q){let B=I51(Error(A.error.message));if(B.message===m7.networkOffline||B.message===m7.networkTimeout)return Cq8(Q);if(B.message!==m7.internalBug)return new E4(B.message,1,B.suggestion);return new E4(A.error.message.replace(/^Error: /,""),1)}var NGA=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; 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??wX,description:`Custom settings file path (overrides the default location ${wX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(_).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${bt})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:R9(),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:nL.SMART.key,description:`Set the agent mode (${JJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(JJ().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neo",long:"neo",type:"switch",description:"Use the Neo TUI",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",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:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",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}],IGA=(A)=>("deprecated"in A)&&A.deprecated===!0,wq8=(A)=>("hidden"in A)&&A.hidden===!0,Mq8=(A)=>("default"in A),Lq8=(A)=>("default"in A)?A.default:void 0,jGA=[{name:"toggle-skills-count",entryPoint:Te}];function Oq8(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new E4(m7.unknownCommand(B),1,Z)}}async function iq0(A){return{...A,getThreadEnvironment:NH,osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new lO(A.fileSystem),generateThreadTitle:mK4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>QB(A.configService),pluginService:A.pluginService}}function RGA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:NH,filesystem:A.fileSystem,threadService:A.threadService}}var PGA="code-tour";function oZ1(A){return A.filter((Q)=>Q.name!==PGA)}function jq8(A){return{...A,skills:A.skills.pipe(N1(oZ1)),getSkills:async()=>oZ1(await A.getSkills()),getSkill:async(Q)=>Q===PGA?void 0:A.getSkill(Q),getSkillsList:async()=>{let Q=oZ1(await A.getSkills());return Oy(Q)}}}var cq0=F1.file(Gq8.homedir()),sZ1=process.env.XDG_CONFIG_HOME?F1.file(process.env.XDG_CONFIG_HOME):U1.joinPath(cq0,".config");function Rq8(A){return Xx4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(dU0())cU0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())Fx4();else er(Q);let B=kP(),$=me();if((!B||$||UK0())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(vG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(vG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(kP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function J9(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;U84("0.0.
|
|
6133
|
+
`)}function Eq8(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function Z7(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")y9("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")y9("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)y9("internal.model",Wq8(Q.model))}function zGA(A){let Q=A.indexOf(":");if(Q===-1)throw new E4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new E4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Wq8(A){if(!A.includes("="))return zGA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new E4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new E4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new E4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);zGA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new E4("No valid model overrides found in --model flag value.",1);return Q}function Hq8(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function zq8(A){try{return await OGA(A,"utf-8")}catch{return A}}async function qGA(A,Q,B){let $=Hq8(A,Q);if(!$)return;let J=xA(B)?B.features:[],Y=xA(B)?B.user.email:void 0;if(!Jg(J,D9.HARNESS_SYSTEM_PROMPT)&&!(Y&&E7(Y)))throw new E4("You are not allowed to do this.",1);y9("systemPrompt",await zq8($))}function Jg(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function qq8(A){return A!=="pending"}function Zg(A){if(!xA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Nq8(A){let Q=Zg(A);if(Q)return Q.id;if(WW(A))throw Error(A.error.message);throw Error("unreachable")}function Iq8(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 Cq8(A){let $=Iq8(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 E4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function rZ1(A,Q){let B=I51(Error(A.error.message));if(B.message===m7.networkOffline||B.message===m7.networkTimeout)return Cq8(Q);if(B.message!==m7.internalBug)return new E4(B.message,1,B.suggestion);return new E4(A.error.message.replace(/^Error: /,""),1)}var NGA=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; 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??wX,description:`Custom settings file path (overrides the default location ${wX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(_).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${bt})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:R9(),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:nL.SMART.key,description:`Set the agent mode (${JJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(JJ().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neo",long:"neo",type:"switch",description:"Use the Neo TUI",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",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:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",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}],IGA=(A)=>("deprecated"in A)&&A.deprecated===!0,wq8=(A)=>("hidden"in A)&&A.hidden===!0,Mq8=(A)=>("default"in A),Lq8=(A)=>("default"in A)?A.default:void 0,jGA=[{name:"toggle-skills-count",entryPoint:Te}];function Oq8(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new E4(m7.unknownCommand(B),1,Z)}}async function iq0(A){return{...A,getThreadEnvironment:NH,osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new lO(A.fileSystem),generateThreadTitle:mK4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>QB(A.configService),pluginService:A.pluginService}}function RGA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:NH,filesystem:A.fileSystem,threadService:A.threadService}}var PGA="code-tour";function oZ1(A){return A.filter((Q)=>Q.name!==PGA)}function jq8(A){return{...A,skills:A.skills.pipe(N1(oZ1)),getSkills:async()=>oZ1(await A.getSkills()),getSkill:async(Q)=>Q===PGA?void 0:A.getSkill(Q),getSkillsList:async()=>{let Q=oZ1(await A.getSkills());return Oy(Q)}}}var cq0=F1.file(Gq8.homedir()),sZ1=process.env.XDG_CONFIG_HOME?F1.file(process.env.XDG_CONFIG_HOME):U1.joinPath(cq0,".config");function Rq8(A){return Xx4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(dU0())cU0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())Fx4();else er(Q);let B=kP(),$=me();if((!B||$||UK0())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(vG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(vG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(kP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function J9(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;U84("0.0.1777352624-g869aa9");let Y=ck({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(F1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:cq0,userConfigDir:sZ1});f7A(Y);let Z=await Y.getLatest();_.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let m=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(m),_.info("API key lookup before login",{found:Boolean(m),ampURL:A.ampURL,deferAuth:$}),!m)if($)_.info("No API key found, continuing startup with deferred auth");else{q5.write(`No API key found. Starting login flow...
|
|
6134
6134
|
`);let p=await Pq8(A),h=await A.secrets.get("apiKey",A.ampURL);if(_.info("Login flow completed",{success:p,storedKeyPresent:Boolean(h),ampURL:A.ampURL}),!p)await OK(),process.exit(1);F=!0}}{let m=await Y.getLatest(),p=m.settings.url,h=m.secrets.isSet?.[p];_.info("Config secrets state after login",{configURL:p,apiKeySet:h?.apiKey??!1})}let X=T1(QB(Y).pipe(Y5(qq8))),D=$?"pending":await X;if(!$)_.info("Server status resolved",{status:"ready",isAuthenticated:xA(D),isError:WW(D),errorMessage:WW(D)?D.error.message:void 0});let G=X.then((m)=>Nq8(m));G.catch(()=>{return});let{toolService:V,dispose:U}=LD0({configService:Y}),K=new Map,E=()=>K.clear(),W=new Pm0(Y,A.settings.getWorkspaceRootPath()),H=BJ0({configService:Y,filesystem:L8}),z=tF4({configService:Y,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(m,p,h)=>{let a=`${m}:${p}`,c=K.get(a);if(c)return _.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:p}),c;_.debug("Creating OAuth provider for server",{serverName:m,serverUrl:p});let t=(async()=>{let H0=new JO(A.secrets),n=await H0.getClientInfo(m,p),A0=h?.scopes??n?.scopes,D0=ir4();_.info("OAuth headless mode check",{useHeadless:D0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:q5.isTTY});let W0;if(D0)W0=A.executeMode?lr4():cr4(m);let B0=new Gb0({storage:H0,serverName:m,serverUrl:p,clientId:h?.clientId??n?.clientId,clientSecret:h?.clientSecret??n?.clientSecret,authUrl:h?.authUrl??n?.authUrl,tokenUrl:h?.tokenUrl??n?.tokenUrl,scopes:A0,headlessAuthHandler:W0});return _.debug("OAuth provider created",{serverName:m,serverUrl:p,hasManualClientId:!!(h?.clientId??n?.clientId),willUseDCR:!(h?.clientId??n?.clientId),scopes:A0,headlessMode:D0,executeMode:A.executeMode}),B0})();return K.set(a,t),t}}),q=jt0({configService:Y,filesystem:L8,spawn:nX0}),N;if(J)N=new Map;else if(A.executeMode){let m=await Lk4({toolService:V,providers:[z,q],initialTimeout:15000});N=m.registrations;for(let[p,h]of m.initErrors)_.warn(`${p} provider initialization slow or failed:`,h)}else N=Rt0({toolService:V,providers:[z,q]});if(Q.jetbrains)rL("JetBrains");else if(Q.ide&&_s4())rL("VS Code");else if(Q.ide&&Ts4())rL("Neovim");else if(Q.ide){let m=await Kq8();if(m){let p=r90(m.ideName);if(p)rL(p)}}if(A.executeMode)K84(!0);let I,C=a8.status.pipe(N1((m)=>Boolean(m.connected&&m.authenticated&&m.ideName&&p84(m.ideName))),x4()).subscribe((m)=>{if(m){if(!I)I=V.registerTool(Mk4)}else I?.dispose(),I=void 0}),w;if(!A.executeMode){let m=await A.settings.get("fuzzy.alwaysIncludePaths")??[];w=new Bu(process.cwd(),{alwaysIncludePaths:m},!0)}else w=new class extends Bu{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=new Sd0(oO(Y),{maxThreads:200});_.info("Starting Amp background services");let j=new RB1,P=process.env.PLUGINS??"off",R=Q.headless?$0A():void 0,b=R??new Eu({configService:Y}),g=b instanceof Eu?b:void 0;if(g)g.pluginExecutorKind="local";let f=Ri({configService:Y,fileSystem:L8,platform:b,internalPlugins:jGA,pluginFilter:P}),k=Z$0({pluginService:f,toolService:V}),x={configService:Y,toolService:V,mcpService:z,skillService:H,toolboxService:q,trustStore:W,threadService:M,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:w,fileSystem:L8,terminal:j,pluginService:f,pluginPlatform:g,headlessPluginPlatform:R,serverStatus:D,serverStatusPromise:X,viewerUserIDPromise:G,hasAPIKeyAtStartup:F};return{...x,async asyncDispose(){if(x.mcpService.hasAuthenticatingClients())_.info("Waiting for OAuth authentication to complete before exit..."),await x.mcpService.waitForAuthentication();for(let m of N.values())m.dispose();await x.mcpService.dispose(),E(),await x.threadService.asyncDispose(),x.configService.unsubscribe(),U(),x.fuzzyServer.dispose(),x.settingsStorage[Symbol.dispose](),C.unsubscribe(),I?.dispose(),k.dispose(),await x.pluginService.dispose()}}}async function Pq8(A){if(!A.executeMode){if(!await yK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return q5.write(`Login cancelled. Run the command again to retry.
|
|
6135
6135
|
`),!1}return await _GA(A)}async function _GA(A){let Q=LGA(32).toString("hex"),B=await Uu(A.ampURL,Q),$=new AbortController;try{await ED(B,$.signal)}catch(Y){_.error("Error opening browser",{error:Y})}let J=await Uu(A.ampURL,Q,!1);q5.write(`If your browser does not open automatically, visit:
|
|
6136
6136
|
|
|
@@ -6138,7 +6138,7 @@ ${n0.blue.bold(J)}
|
|
|
6138
6138
|
|
|
6139
6139
|
`);try{return await de4(A.ampURL,Q,A.secrets,$),q5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return _.error("Login failed",{error:Y}),x$.write(`
|
|
6140
6140
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
6141
|
-
`),!1}}function _q8(A){let Q=new hI().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)GP(),process.exit(0);let W=E.originalError??E;Ca4(W)}),U1A(Q,{version:"0.0.
|
|
6141
|
+
`),!1}}function _q8(A){let Q=new hI().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)GP(),process.exit(0);let W=E.originalError??E;Ca4(W)}),U1A(Q,{version:"0.0.1777352624-g869aa9",buildTimestamp:"2026-04-28T05:07:34.445Z",buildType:"'release'"}),Q.addHelpText("after",js4()),Q.configureHelp({formatHelp:Rs4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await E8(H);await fq8(z)}),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(E,W)=>{let H=W.optsWithGlobals(),z=await E8(H);await xq8(z,await Be(H,z.settings))}),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(E,W,H)=>{let z=H.optsWithGlobals(),q=await E8(z);await fr4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,W)=>{let H=W.optsWithGlobals(),z=await E8(H);await br4(z.ampURL,z.secrets),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(E)=>{await lt4({raw:E.raw===!0}),process.exit(process.exitCode??0)}),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(`
|
|
6142
6142
|
`)).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(E,W,H)=>{if(E&&W.apply)throw new E4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let z=W.apply??E;if(!z||z.trim().length===0)q5.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.
|
|
6143
6143
|
|
|
6144
6144
|
`),H.outputHelp(),process.exit(0);let q=M3(z)??qB(z),N=H.optsWithGlobals(),I=await E8(N);Z7(H,N);let C=await J9(I,N),w=!1;try{if(W.checkout&&W.skipCheckout)throw new E4("Choose either --checkout or --skip-checkout, not both.",1);if(WW(C.serverStatus))throw rZ1(C.serverStatus,I.ampURL);let M=xA(C.serverStatus)?C.serverStatus.features:void 0;if(!Jg(M,D9.V2))throw new E4("live-sync is not enabled for your user",1);await ke4({ampURL:I.ampURL,threadId:q,configService:C.configService,threadService:C.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof W.apply==="string",checkoutMode:W.checkout?"always":W.skipCheckout?"never":"prompt",promptForYesNo:yK0}),w=!0}finally{if(await C.asyncDispose(),w)process.exit(0)}});let B=async(E,W,H)=>{ck({storage:W.settings,secretStorage:W.secrets,workspaceRoot:g0.of(F1.file(process.cwd())),defaultAmpURL:W.ampURL,homeDir:cq0,userConfigDir:sZ1});let z={...W,executeMode:!1};await lq0(z,{...E,openThreadSwitcher:!0},H,A)},$=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").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await E8(H);await MGA(H,z,W)});$.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await E8(H);await nq8(H,z,W)}),$.command("continue [threadIDOrURL]").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.").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(E,W,H)=>{let z=H.optsWithGlobals(),q=await E8(z);if(W.pick)x$.write(`${n0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
@@ -6172,8 +6172,8 @@ ${I}
|
|
|
6172
6172
|
|
|
6173
6173
|
This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function Tq8(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await BH0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await BH0()).trimEnd(),stdinInput:null}}function Sq8(A,Q,B){if(A.streamJson&&!Q)throw new E4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new E4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new E4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new E4("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 E4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new E4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new E4("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&&B===""&&!A.streamJsonInput&&!A.headless)throw new E4("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"
|
|
6174
6174
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function lq0(A,Q,B,$){let J=process.hrtime.bigint(),Y=(l,o)=>{let e=Number(process.hrtime.bigint()-o)/1e6,J0=$c4();_.info("Startup phase",{phase:l,phaseMs:Math.round(e),sinceMainMs:J0===null?void 0:Math.round(J0)})},{userInput:Z,stdinInput:F}=await Tq8(Q),X=!!Q.streamJson||!!Q.streamJsonThinking;Sq8({...Q,streamJson:X},A.executeMode,Z),Z7(B,Q);let D=process.hrtime.bigint(),G=Boolean(await A.secrets.get("apiKey",A.ampURL)),V=!A.executeMode&&!Q.headless&&G;_.info("Interactive auth startup mode",{deferInteractiveAuth:V,hasAPIKeyAtStartup:G,executeMode:A.executeMode,headless:Boolean(Q.headless)});let U=await J9(A,Q,{deferAuth:V});Y("runMainThread:createThreadDependencies",D);let{serverStatus:K}=U;if(!V&&WW(K))throw rZ1(K,A.ampURL);let E=xA(K)?K:null,W=E?.user.email,H=!!(W&&E7(W));if(!V)await qGA(B,Q,K);let z=Zg(K),q=z?.features??[],N=z?.team??null,I=vW0(Q,z);if(I instanceof Error)o5(I.message);if(E&&!Lc(Q.mode,W))throw new E4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(Q.headless){if(process.env.AMP_EXECUTOR!=="1"&&(!W||!E7(W)))throw new E4("Headless executor mode is only available for Amp employees",1);let o=await U.secretStorage.get("apiKey",A.ampURL);if(!o)throw new E4("API key required for headless mode. Please run `amp login` first.",1);let e=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(e&&!ZJ(e))throw new E4(`Invalid thread ID: ${e}`,1);let J0=e?void 0:await lq8({dependencies:U,apiKey:o,visibility:I??void 0}),$0=e??J0?.threadId;if(!$0)throw new E4("Failed to resolve headless thread ID",1);let U0=await rr4($0);if(U0.status==="already-running")await U.asyncDispose(),await OK(),process.exit(0);try{await mr4({ampURL:A.ampURL,apiKey:o,workspaceRoot:process.cwd(),threadId:$0,ownerUserId:J0?.ownerUserId,threadVersion:J0?.threadVersion,agentMode:J0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform})}finally{await U0.release(),await U.asyncDispose()}await OK(),process.exit(0)}let C=Q.threadId&&ZJ(Q.threadId)?Q.threadId:void 0,w=Q.observe?M3(Q.observe)??qB(Q.observe):void 0,M=V?await U.serverStatusPromise:K,j=xA(M)&&Jg(M.features,D9.NEO_TUI);if((j||Q.neo||!!w||!1)&&!A.executeMode&&!Q.takeMeBack){if((Q.neo||w)&&!j&&(!xA(M)||!E7(M.user.email)))throw new E4(Q.observe?"--observe is only available for Amp employees":"--neo is only available for Amp employees",1);let l=await U.secretStorage.get("apiKey",A.ampURL);if(!l)throw new E4("API key required. Please run `amp login` first.",1);let o=oO(U.configService),e=new N_(U.fuzzyServer),J0=process.cwd();await CB1({ampURL:A.ampURL,apiKey:l,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??pJ(A.ampURL),configService:U.configService,toolService:U.toolService,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService,skillService:U.skillService,mcpService:U.mcpService,readFileSystemDirectory:({uri:$0})=>CC({fileSystem:U.fileSystem,workspaceRoot:J0},$0),completionBuilder:e,workspaceRoot:J0,listThreads:()=>o.listThreads(),getThreadFromServer:($0)=>o.getThread($0),isInternalUser:xA(M)&&E7(M.user.email),settingsFilePath:U.settingsStorage.getSettingsFilePath()},{initialThreadID:w??C,initialUserInput:Z||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!w,splashOrbVisualStyle:"neo",initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0});return}let R=xA(M)&&Jg(M.features,D9.THREAD_ACTORS_TUI);if(A.executeMode&&!Q.takeMeBack&&R){let l=await U.secretStorage.get("apiKey",A.ampURL);if(!l)throw new E4("API key required. Please run `amp login` first.",1);q31(U.mcpService,A.settings);try{let o=await Yr4({apiKey:l,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:U,userInput:Z,stdinInput:F,stats:!!Q.stats,streamJson:X,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,labels:Q.label,initialThreadID:C});if(await Yg(o,"execute"),Q.archive)await U.threadService.archive(o,!0)}finally{await U.asyncDispose()}await OK(),process.exit(0)}if(!A.executeMode&&!Q.headless)U.skillService=jq8(U.skillService);D=process.hrtime.bigint();let g=await iq0(U);Y("runMainThread:createWorkerDeps",D);let f=A.executeMode?void 0:async(l)=>Yg(l,"interactive"),k={threadService:U.threadService,workerDeps:g,createThread:async(l)=>{let o=V?await U.serverStatusPromise:K,e=await KU0(A.settings,process.cwd(),Zg(o),I);if(e instanceof Error)o5(e.message);return CY1(g,{threadMeta:e?mG(e):void 0,agentMode:l??Q.mode,onFirstAssistantMessage:f})},validateThreadOwnership:async(l,o)=>{if(o?.nonBlockingOwnershipCheck){CGA(l,U.configService,U.viewerUserIDPromise).catch((e)=>{if(e instanceof E4){if(o.onOwnershipError){o.onOwnershipError(e,l);return}xH(e,l);return}_.warn("Failed to validate thread ownership in CLI, allowing to open",{error:e})});return}try{await CGA(l,U.configService,U.viewerUserIDPromise)}catch(e){if(e instanceof E4)throw e;_.warn("Failed to validate thread ownership in CLI, allowing to open",{error:e})}},switchThreadVisibility:I,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:f,handleError:xH},x=async()=>{try{return iZA(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(l){if(l instanceof E4)throw l;throw await xH(l,Q.threadId),Error("handleError should have called process.exit()")}};if(Q.format==="jsonl")x$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6175
|
-
`),await OK(),process.exit(1);let m=(async()=>{if(V){_.info("Skipping initial free tier status fetch until auth is complete");return}try{let l=await U.configService.getLatest(),o=Uc(l),e=await hA.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(o)});if(e.ok)return _.info("User free tier status:",e),e.result;return}catch(l){_.error("Failed to fetch free tier status:",l);return}})(),h=!A.executeMode?new bB1:null,a,c=null;if(h)a=h,c=(async()=>{let l=V?await U.serverStatusPromise:U.serverStatus;if(WW(l))throw rZ1(l,A.ampURL);await qGA(B,Q,l);let o=process.hrtime.bigint(),e=await x();if(Y("runMainThread:createThreadPool",o),h.attach(e),Z){let J0=await T1(e.threadHandles$);if(!J0)throw new E4("No active thread is available yet.",1);await J0.sendMessage({content:[{type:"text",text:Z}]})}})(),c.catch(async(l)=>{let o=l instanceof Error?l:Error(String(l));h.setInitError(o),await xH(l,Q.threadId)});else D=process.hrtime.bigint(),a=await x(),Y("runMainThread:createThreadPool",D);let t=Q.notifications!==void 0?Q.notifications:!A.executeMode,H0=E!==null&&Jg(E.features,D9.TUI_VOICE_NOTIF);if(V)U.serverStatusPromise.then((l)=>{H0=xA(l)&&Jg(l.features,D9.TUI_VOICE_NOTIF)}).catch((l)=>{_.debug("Failed to resolve TUI voice notification feature flag",{error:l})});D=process.hrtime.bigint();let n=await U.configService.getLatest();if(Y("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),Rq8({configService:U.configService,threadService:U.threadService,config:n,useNotificationsForService:t,isTUIVoiceNotifEnabled:()=>H0,threadViewStates$:()=>a.threadHandles$.pipe(n4((l)=>{if(!l)return g0.of({});return h6(l.thread$,l.threadViewState$).pipe(N1(([o,e])=>({[o.id]:e})))}))}),Y("runMainThread:createCliNotificationService",D),A.executeMode){q31(U.mcpService,A.settings);let l={userInput:Z,stdinInput:F,dependencies:U,streamJson:X,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,labels:Q.label},o=await pa4({threadPool:a,...l});if(await Yg(o,"execute"),Q.archive)await U.threadService.archive(o,!0);await U.asyncDispose(),process.exit(0)}let A0=!1,D0=!1;if(Q.jetbrains||Q.ide){await s90();let l=await wD({jetbrainsOnly:Q.jetbrains});if(l.length===0){if(Q.jetbrains)A0=!await U.configService.get("jetbrains.skipInstall")}else if(l.length===1){let o=l[0];if(o)a8.selectConfig(o)}else D0=!0}D=process.hrtime.bigint();let W0=b81("0.0.
|
|
6176
|
-
`);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;_.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await $X4({get:async(F)=>{if(F!==Hi)return;try{let X=await OGA(aZ1,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==Hi)return;await Xq8(W40.dirname(aZ1),{recursive:!0}),await Dq8(aZ1,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:uB0()});E84($);let J=await oU0({...A,workspaceTrust:{current:!0,changes:bx0},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await ee4(A.mcpConfig);J=A0A(J,F)}let Y=W40.dirname(J.getSettingsFilePath());Zx4(Ju,Y),J=n64(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=x9;if(_.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!fq(Z))_.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:gK0(await Be(A,J))}}function kq8(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function vq8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=W40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?Vq8:bt));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function yq8(){Bc4();let A=kq8(process.argv),Q=vq8(process.argv,A),B=Ua4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(Eq8(_),_.info("Starting Amp CLI.",{version:"0.0.
|
|
6175
|
+
`),await OK(),process.exit(1);let m=(async()=>{if(V){_.info("Skipping initial free tier status fetch until auth is complete");return}try{let l=await U.configService.getLatest(),o=Uc(l),e=await hA.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(o)});if(e.ok)return _.info("User free tier status:",e),e.result;return}catch(l){_.error("Failed to fetch free tier status:",l);return}})(),h=!A.executeMode?new bB1:null,a,c=null;if(h)a=h,c=(async()=>{let l=V?await U.serverStatusPromise:U.serverStatus;if(WW(l))throw rZ1(l,A.ampURL);await qGA(B,Q,l);let o=process.hrtime.bigint(),e=await x();if(Y("runMainThread:createThreadPool",o),h.attach(e),Z){let J0=await T1(e.threadHandles$);if(!J0)throw new E4("No active thread is available yet.",1);await J0.sendMessage({content:[{type:"text",text:Z}]})}})(),c.catch(async(l)=>{let o=l instanceof Error?l:Error(String(l));h.setInitError(o),await xH(l,Q.threadId)});else D=process.hrtime.bigint(),a=await x(),Y("runMainThread:createThreadPool",D);let t=Q.notifications!==void 0?Q.notifications:!A.executeMode,H0=E!==null&&Jg(E.features,D9.TUI_VOICE_NOTIF);if(V)U.serverStatusPromise.then((l)=>{H0=xA(l)&&Jg(l.features,D9.TUI_VOICE_NOTIF)}).catch((l)=>{_.debug("Failed to resolve TUI voice notification feature flag",{error:l})});D=process.hrtime.bigint();let n=await U.configService.getLatest();if(Y("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),Rq8({configService:U.configService,threadService:U.threadService,config:n,useNotificationsForService:t,isTUIVoiceNotifEnabled:()=>H0,threadViewStates$:()=>a.threadHandles$.pipe(n4((l)=>{if(!l)return g0.of({});return h6(l.thread$,l.threadViewState$).pipe(N1(([o,e])=>({[o.id]:e})))}))}),Y("runMainThread:createCliNotificationService",D),A.executeMode){q31(U.mcpService,A.settings);let l={userInput:Z,stdinInput:F,dependencies:U,streamJson:X,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,labels:Q.label},o=await pa4({threadPool:a,...l});if(await Yg(o,"execute"),Q.archive)await U.threadService.archive(o,!0);await U.asyncDispose(),process.exit(0)}let A0=!1,D0=!1;if(Q.jetbrains||Q.ide){await s90();let l=await wD({jetbrainsOnly:Q.jetbrains});if(l.length===0){if(Q.jetbrains)A0=!await U.configService.get("jetbrains.skipInstall")}else if(l.length===1){let o=l[0];if(o)a8.selectConfig(o)}else D0=!0}D=process.hrtime.bigint();let W0=b81("0.0.1777352624-g869aa9",U.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let B0=new N31(U.mcpService,A.settings.getWorkspaceRootPath());if(Y("runMainThread:createMcpTrustHandler",D),Z&&A.executeMode){let l=await T1(a.threadHandles$);if(!l)throw new E4("No active thread is available yet.",1);await l.sendMessage({content:[{type:"text",text:Z}]})}D=process.hrtime.bigint();let Z0=await Wu();Y("runMainThread:loadSessionState",D),_.info("Loaded session state:",Z0);let d={...Z0,launchCount:Z0.launchCount+1};OZ((l)=>({...l,launchCount:l.launchCount+1}));try{if(D=process.hrtime.bigint(),await hQA({history:new nt,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:hA,threadPool:a,createSystemPromptDeps:async()=>RGA(U),ideClient:a8,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:B0,updateService:W0,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:A0,showIdePickerHint:D0,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:Uq8,logFile:{path:$},sessionState:d,freeTierStatusPromise:m,workspace:N??null,features:q,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-04-28T05:07:34.445Z"},(l)=>new cB1({...l,threadPool:l.threadPool},(o)=>new NY1({...o,threadState:o.threadState}))),Y("runMainThread:mountApp-returned",D),c)await c}finally{await a.dispose().catch((l)=>{_.error("Failed to dispose thread pool during shutdown",l)})}await U.asyncDispose(),Y("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function E8(A){if(_.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)x$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6176
|
+
`);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;_.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await $X4({get:async(F)=>{if(F!==Hi)return;try{let X=await OGA(aZ1,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==Hi)return;await Xq8(W40.dirname(aZ1),{recursive:!0}),await Dq8(aZ1,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:uB0()});E84($);let J=await oU0({...A,workspaceTrust:{current:!0,changes:bx0},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await ee4(A.mcpConfig);J=A0A(J,F)}let Y=W40.dirname(J.getSettingsFilePath());Zx4(Ju,Y),J=n64(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=x9;if(_.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!fq(Z))_.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:gK0(await Be(A,J))}}function kq8(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function vq8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=W40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?Vq8:bt));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function yq8(){Bc4();let A=kq8(process.argv),Q=vq8(process.argv,A),B=Ua4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(Eq8(_),_.info("Starting Amp CLI.",{version:"0.0.1777352624-g869aa9",buildTimestamp:"2026-04-28T05:07:34.445Z"}),process.platform==="win32"&&NP())as4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new E4(m7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await _q8(B).parseAsync(process.argv)}Jx4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await yq8().catch(xH)});async function xq8(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),q5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6177
6177
|
`);else if(!fq(A.ampURL))q5.write(`Logging in to ${new URL(A.ampURL).hostname}
|
|
6178
6178
|
`);let $=process.env.AMP_API_KEY;if($)q5.write(`API key found in environment variable, storing...
|
|
6179
6179
|
`),await Q.set("apiKey",$,A.ampURL),q5.write(`API key successfully stored.
|