@sourcegraph/amp 0.0.1778518196-gcde0a1 → 0.0.1778531432-g3bd093

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +10 -10
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -5288,12 +5288,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,X(Error(`Failed to spawn brew: ${K.message}`))}
5288
5288
  ${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))z+=`
5289
5289
 
5290
5290
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
5291
- npm install -g @sourcegraph/amp`;X(Error(z))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}p0();p0();KN();async function DX0(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=Ro(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],z=X.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(z)K=Math.floor((W-new Date(z).getTime())/3600000)}return j.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 j.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var kI5="https://static.ampcode.com/cli/cli-version.txt";async function GX0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${kI5}?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=Ro(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var SI5=604800000;function nb4(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>SI5)return{ageMs:B};return null}function Ro(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 Ye0(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?oV(B):void 0;return{sha:$,age:J}}catch{return null}}L1();p0();import{readFile as vI5,realpath as yI5}from"node:fs/promises";import{homedir as xI5}from"node:os";import{dirname as ab4,join as Ze0}from"node:path";async function ob4(A){switch(A){case"binary":case"brew":return fI5(Mo());case"npm":case"pnpm":case"yarn":case"bun":return bI5();case"bootstrap":return uI5()}}async function fI5(A){let Q=await fD(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function bI5(){try{let A=process.argv[1];if(!A)return null;let Q=await yI5(A),B=ab4(ab4(Q));return await rb4(Ze0(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function uI5(){try{let A=process.env.AMP_HOME??Ze0(xI5(),".amp");return await rb4(Ze0(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function rb4(A){let Q=await vI5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var hI5=3600000,gI5=5000;function Fe0(A,Q,B={}){let $=new m4,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??hI5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=j.getChild("update");if(Y>0){if(await eV(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await mI5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await eV(gI5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let z=Math.min(K,E);await eV(z),E-=z}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function mI5(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 DI(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await GX0(A);else{let V=await Pj();X=await DX0(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 ob4(Z);if(V&&Ro(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Ro(A,V)<0){let U=await kz(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!==Mo()){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 jo(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await kz(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}}KN();import{stderr as bD}from"node:process";function sb4(A){let Q=new mN().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 nt0($.force||!1,$.verbose||!1,"0.0.1778518196-gcde0a1"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new mN("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 dI5($.targetVersion)});A.addCommand(B)}function pI5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
5291
+ npm install -g @sourcegraph/amp`;X(Error(z))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}p0();p0();KN();async function DX0(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=Ro(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],z=X.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(z)K=Math.floor((W-new Date(z).getTime())/3600000)}return j.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 j.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var kI5="https://static.ampcode.com/cli/cli-version.txt";async function GX0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${kI5}?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=Ro(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var SI5=604800000;function nb4(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>SI5)return{ageMs:B};return null}function Ro(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 Ye0(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?oV(B):void 0;return{sha:$,age:J}}catch{return null}}L1();p0();import{readFile as vI5,realpath as yI5}from"node:fs/promises";import{homedir as xI5}from"node:os";import{dirname as ab4,join as Ze0}from"node:path";async function ob4(A){switch(A){case"binary":case"brew":return fI5(Mo());case"npm":case"pnpm":case"yarn":case"bun":return bI5();case"bootstrap":return uI5()}}async function fI5(A){let Q=await fD(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function bI5(){try{let A=process.argv[1];if(!A)return null;let Q=await yI5(A),B=ab4(ab4(Q));return await rb4(Ze0(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function uI5(){try{let A=process.env.AMP_HOME??Ze0(xI5(),".amp");return await rb4(Ze0(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function rb4(A){let Q=await vI5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var hI5=3600000,gI5=5000;function Fe0(A,Q,B={}){let $=new m4,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??hI5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=j.getChild("update");if(Y>0){if(await eV(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await mI5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await eV(gI5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let z=Math.min(K,E);await eV(z),E-=z}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function mI5(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 DI(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await GX0(A);else{let V=await Pj();X=await DX0(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 ob4(Z);if(V&&Ro(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Ro(A,V)<0){let U=await kz(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!==Mo()){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 jo(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await kz(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}}KN();import{stderr as bD}from"node:process";function sb4(A){let Q=new mN().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 nt0($.force||!1,$.verbose||!1,"0.0.1778531432-g3bd093"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new mN("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 dI5($.targetVersion)});A.addCommand(B)}function pI5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
5292
5292
  `),$=!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 dI5(A){let B=process.platform==="win32"&&Rj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=pI5(bD);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")bD.write(n0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
5293
5293
 
5294
5294
  `));try{if(!A){bD.write(n0.blue(`Checking for updates...
5295
- `));let F=!1,X;if(Rj()){let D=await GX0("0.0.1778518196-gcde0a1");F=D.hasUpdate,X=D.latestVersion}else{let D=await Pj(),G=await DX0("0.0.1778518196-gcde0a1",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=Ye0("0.0.1778518196-gcde0a1"),G=D?.age?`released ${D.age} ago`:`built ${oV(new Date("2026-05-11T16:53:36.885Z"))} ago`;bD.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1778518196-gcde0a1"} (${G})
5296
- `));let V=await kz("0.0.1778518196-gcde0a1",B);if(V.warning)bD.write(`
5295
+ `));let F=!1,X;if(Rj()){let D=await GX0("0.0.1778531432-g3bd093");F=D.hasUpdate,X=D.latestVersion}else{let D=await Pj(),G=await DX0("0.0.1778531432-g3bd093",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=Ye0("0.0.1778531432-g3bd093"),G=D?.age?`released ${D.age} ago`:`built ${oV(new Date("2026-05-11T20:34:42.741Z"))} ago`;bD.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1778531432-g3bd093"} (${G})
5296
+ `));let V=await kz("0.0.1778531432-g3bd093",B);if(V.warning)bD.write(`
5297
5297
  `+n0.yellow(V.warning)+`
5298
5298
  `);process.exit(0)}if(!X)bD.write(n0.yellow("[WARN] could not find latest version")),process.exit(0);A=X}bD.write(n0.blue(`Updating to version ${A}...
5299
5299
  `)),await jo(A,void 0,(F)=>{$(),bD.write(n0.dim(`Running: ${F}
@@ -5700,7 +5700,7 @@ ${$}`).join(`
5700
5700
  `).length,J=new p({text:new C(A,new v({color:B}))});if($<=MG0)return J;return new U0({width:1/0,height:MG0,child:new ZQ({autofocus:!1,controller:Q,child:J})})}function fy5(){return new Map([[C1.key("PageUp"),new LG0],[C1.key("PageDown"),new x41],[C1.ctrl("u"),new LG0],[C1.shift("Home"),new f41],[C1.shift("End"),new b41]])}function by5(A,Q,B){return Math.max(Q,Math.min(A,B))}var u41=8,An4=1,Qn4=u41-1;class h41 extends P4{}class g41 extends P4{}class OG0 extends P4{}class jG0 extends P4{}class m41 extends P4{}class p41 extends P4{}class d41 extends T0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new Bn4}}class Bn4 extends _0{messageScroll=new hA;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,B=uy5(Q,this.messageScroll),$=hy5(Q.options.message),J=$?new l4({actions:this.buildScrollActions(),child:new Y5({debugLabel:"NeoSelectDialogScrollShortcuts",shortcuts:my5(),child:B})}):B,Y=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if($)Y.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return Y.push({keys:["Esc"],label:"cancel"}),new yA({header:Q.options.title,minWidth:64,maxWidth:80,footer:Y,autofocus:!1,onDismiss:Q.onCancel,child:J})}buildScrollActions(){let A=(Q)=>{let B=py5(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo(B)};return new Map([[h41,new c1(()=>A(-An4))],[g41,new c1(()=>A(An4))],[OG0,new c1(()=>A(-Qn4))],[jG0,new c1(()=>A(Qn4))],[m41,new c1(()=>this.messageScroll.jumpTo(0))],[p41,new c1(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function uy5(A,Q){let B=A.options.options.map(($)=>({value:$,label:$}));return new F9({options:B,body:gy5(A.options.message,Q),onSelect:($)=>{if($===null){A.onCancel();return}A.onSelect($)},padding:K0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!1})}function hy5(A){if(A===void 0)return!1;return A.split(`
5701
5701
  `).length>u41}function gy5(A,Q){if(A===void 0)return;let B=A.split(`
5702
5702
  `).length,$=Math.min(B,u41);return new U0({width:1/0,height:$,child:new ZQ({autofocus:!1,controller:Q,child:new p({text:new C(A)})})})}function my5(){return new Map([[C1.key("PageUp"),new OG0],[C1.key("PageDown"),new jG0],[C1.ctrl("u"),new OG0],[C1.ctrl("d"),new jG0],[C1.ctrl("y"),new h41],[C1.ctrl("e"),new g41],[C1.shift("Home"),new m41],[C1.shift("End"),new p41]])}function py5(A,Q,B){return Math.max(Q,Math.min(A,B))}class c41{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];statusItems=new Map;disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}hasBlockingDialog(){return this.activeDialog!==null}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];switch(A.kind){case"input":return[new Vs({key:new yz(A),header:A.options.title??"Input",helpText:A.options.helpText,initialValue:A.options.initialValue,isRequired:!1,onSubmit:(Q)=>this.resolveInputDialog(A,Q),onDismiss:()=>this.resolveInputDialog(A,void 0)})];case"confirm":return[new y41({key:new yz(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)})];case"select":return[new d41({key:new yz(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})]}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.neoContext.pluginPlatform;if(!A)return;A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.neoContext.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}clearPluginPlatformStatusHandlers(){let A=this.options.neoContext.pluginPlatform;if(!A)return;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null}subscribePluginCommands(){let A=this.options.neoContext.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let B=A.map(($)=>this.createPluginCommand($)).map(($)=>this.options.commandRegistry.register($));this.unregisterPluginCommands=()=>{for(let $ of B)$()}}showNewPluginErrorToasts(A){let Q=new Set;for(let B of A){if(B.status!=="error")continue;if(ad(B.errorMessage))continue;let $=`${B.uri.toString()}
5703
- ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter(($)=>$.status==="active").map(($)=>$.uri.toString())),B=[];for(let[$,J]of this.statusItems){if(Q.has(J.pluginURI))continue;B.push($)}if(B.length===0)return;this.updateStatusItemState(()=>{for(let $ of B)this.statusItems.delete($)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:{type:"enabled"},run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"input",options:A,resolve:Q})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(!1);return}this.enqueueDialog({kind:"confirm",options:A,resolve:Q})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"select",options:A,resolve:Q})})};createStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let $=this.statusItemKey(A,Q),J={pluginURI:A,id:Q};if(B!==void 0)J.value=B;this.statusItems.set($,J)})};updateStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:B})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[];for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}enqueueDialog(A){if(this.activeDialog){this.queuedDialogs.push(A);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveConfirmDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveSelectDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}ql();O2();import{readFile as dy5}from"node:fs/promises";import l41 from"node:os";function cy5(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function $n4(A,Q){try{return{path:Q,contents:fh0(await dy5(A,"utf8"))}}catch{return null}}async function Jn4(A,Q){let B=[],$=cy5(),J=await DA.getThread({thread:Q},{config:A.configService}),Y=J.ok?J.result.thread.data:null;B.push({path:`${$}/thread.json`,contents:JSON.stringify($J(Y),null,2)});let Z=await $n4(Gx(Q),`${$}/logs/${Q}.log`);if(Z)B.push(Z);let F=await $n4(A.settingsFilePath,`${$}/settings/global.json`);if(F)B.push(F);let X=await DI()??"unknown",D=await DA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1778518196-gcde0a1",clientOS:`${l41.platform()} ${l41.release()} ${l41.arch()}`,installMethod:X}},{config:A.configService});if(!D.ok)throw Error(`Failed to submit report: ${D.error.message}`);return D.result.reportID}class i41{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}p0();E9();O2();async function Yn4(A,Q,B){let $;switch(B){case"private":$="This thread's visibility has been updated to private";break;case"workspace":$="This thread's visibility has been updated to workspace";break;case"group":$="This thread's visibility has been updated to group";break;case"unlisted":$="This thread's visibility has been updated to unlisted. Anyone on the Internet with the link can view it.";break;case"public":$="This thread's visibility has been updated to public. Anyone on the Internet can see it on your public profile, and it is publicly searchable.";break}try{let J=await DA.setThreadMeta({thread:Q,meta:wJ(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let F=PB(new URL(A.ampURL),Q).toString();try{await C4.instance.tuiInstance.clipboard.writeText(F),Y=!0}catch(X){j.error("Failed to copy thread URL after visibility update",{error:X})}}let Z=Y?`${$} Link copied to clipboard.`:$;return new eQ(Z)}catch(J){let Y=J instanceof Error?J.message:String(J);if(Y.includes("no-workspace"))return Error("You are not a member of any workspace.");if(Y.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(Y.includes("no-groups"))return Error("You are not a member of any groups.");return j.error("Unexpected failure to update thread visibility",{error:J}),Error(`Failed to update thread visibility for ${Q}`)}}class RG0 extends I5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new n41(this.offstage)}updateRenderObject(A){if(A instanceof n41)A.offstage=this.offstage}}class n41 extends F4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class a41{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class o41 extends T0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Zn4}}class Zn4 extends _0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new yj,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new yj,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new RG0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new n4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new RG0({key:$.key,offstage:!J,child:Y}))}return new QA({fit:"expand",children:Q})}}class s41 extends H1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=ly5(Q);return new yA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:K0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new g6({items:Q,showBorder:!1,getLabel:($)=>{let J=r41($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",z=J.item.noun?.toLowerCase()??"";if(E!==z)return E<z?-1:1;return 0}let Z=ej($.item.verb.toLowerCase(),Y),F=ej(J.item.verb.toLowerCase(),Y);if(Z!==F)return F-Z;let X=ej(r41($.item),Y),D=ej(r41(J.item),Y);if(X!==D)return D-X;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=P0.of(J);return new p({text:new C($.status.reason,new v({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new Fn4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class Fn4 extends H1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=P0.of(Y),{colors:F,app:X}=Z,D=B?X.selectionBackground:void 0,G=B?X.selectionForeground:F.foreground,V=B?G:F.mutedForeground,U=new p({text:new C(Q.noun?.toLowerCase()??"",new v({color:V,dim:$||!B})),textAlign:"right"}),K=[new C(Q.verb.toLowerCase(),new v({color:G,bold:!0,dim:$}))];if($)K.push(new C(" (unavailable)",new v({color:G,dim:!0})));let E=p.spans(K),z=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)z.push({child:iy5(Q.shortcut,Z,$)});return new Xn4({columns:z,padding:K0.horizontal(1),backgroundColor:D})}}function r41(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function ly5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,y4(B.noun)):Q},0)}function iy5(A,Q,B){let{colors:$,app:J}=Q,Y=new v({color:$.mutedForeground,dim:B}),Z=[];for(let F of A.modifiers()){if(Z.length>0)Z.push(new C(" ",Y));Z.push(new C(F,new v({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new C(" ",Y));return Z.push(new C(A.key,new v({color:J.keybind,bold:!0,dim:B}))),p.spans(Z)}class Xn4 extends H1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let F=0;F<Q.length;F++){let X=Q[F];if(F>0&&B>0)Y.push(new U0({width:B}));if(X.fixedWidth!==void 0)Y.push(new U0({width:X.fixedWidth,child:X.child}));else if(X.expanded)Y.push(new _1({child:X.child}));else Y.push(X.child)}let Z=new r0({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new h0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class t41{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class $Z extends q6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=$Z.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType($Z)?.commandRegistry??null}}class e41 extends T0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Dn4}}class Dn4 extends _0{modalStack=new a41;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=$Z.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=$Z.of(A).commands,B=new s41({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new o41({root:B,controller:this.modalStack})}}var AA1=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]},{input:"S",keys:["Alt"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],QA1=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class PG0 extends H1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=A4.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[F,X]=this.renderRow(Z),D;if(J)D=new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[F,new x0({padding:K0.only({left:4}),child:X})]});else D=new r0({crossAxisAlignment:"start",children:[new _1({flex:1,child:F}),new U0({width:1}),new _1({flex:1,child:X})]});Y.push(new x0({padding:K0.horizontal(6),child:D}))}return new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class BA1 extends T0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new Gn4}}class Gn4 extends _0{scrollController;initState(){this.scrollController=new hA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=R1.of(A).colorScheme,J=P0.of(A).app,Y=A4.of(A),Z=new v({color:B.primary,bold:!0}),F=new v({color:B.secondary,bold:!0}),X=new v({color:J.keybind}),D=new v({color:J.command}),G=new v({color:B.foreground}),V=new v({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,z=K-4,W=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((L)=>{let P=L.noun?.toLowerCase();return P!=="dev"&&P!=="debug"&&!L.id.startsWith("debug-")&&!H.has(L.id)})].sort((L,P)=>{let S=(L.noun??"").toLowerCase(),T=(P.noun??"").toLowerCase(),x=S.localeCompare(T);if(x!==0)return x;let h=L.verb.toLowerCase(),u=P.verb.toLowerCase(),k=h.localeCompare(u);if(k!==0)return k;return L.id.localeCompare(P.id)}),I=new vA({autofocus:!0,controller:this.scrollController,child:new h0({constraints:new w1(W,W,0,Number.POSITIVE_INFINITY),child:new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new t1({child:new p({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5703
+ ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter(($)=>$.status==="active").map(($)=>$.uri.toString())),B=[];for(let[$,J]of this.statusItems){if(Q.has(J.pluginURI))continue;B.push($)}if(B.length===0)return;this.updateStatusItemState(()=>{for(let $ of B)this.statusItems.delete($)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:{type:"enabled"},run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"input",options:A,resolve:Q})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(!1);return}this.enqueueDialog({kind:"confirm",options:A,resolve:Q})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"select",options:A,resolve:Q})})};createStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let $=this.statusItemKey(A,Q),J={pluginURI:A,id:Q};if(B!==void 0)J.value=B;this.statusItems.set($,J)})};updateStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:B})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[];for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}enqueueDialog(A){if(this.activeDialog){this.queuedDialogs.push(A);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveConfirmDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveSelectDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}ql();O2();import{readFile as dy5}from"node:fs/promises";import l41 from"node:os";function cy5(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function $n4(A,Q){try{return{path:Q,contents:fh0(await dy5(A,"utf8"))}}catch{return null}}async function Jn4(A,Q){let B=[],$=cy5(),J=await DA.getThread({thread:Q},{config:A.configService}),Y=J.ok?J.result.thread.data:null;B.push({path:`${$}/thread.json`,contents:JSON.stringify($J(Y),null,2)});let Z=await $n4(Gx(Q),`${$}/logs/${Q}.log`);if(Z)B.push(Z);let F=await $n4(A.settingsFilePath,`${$}/settings/global.json`);if(F)B.push(F);let X=await DI()??"unknown",D=await DA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1778531432-g3bd093",clientOS:`${l41.platform()} ${l41.release()} ${l41.arch()}`,installMethod:X}},{config:A.configService});if(!D.ok)throw Error(`Failed to submit report: ${D.error.message}`);return D.result.reportID}class i41{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}p0();E9();O2();async function Yn4(A,Q,B){let $;switch(B){case"private":$="This thread's visibility has been updated to private";break;case"workspace":$="This thread's visibility has been updated to workspace";break;case"group":$="This thread's visibility has been updated to group";break;case"unlisted":$="This thread's visibility has been updated to unlisted. Anyone on the Internet with the link can view it.";break;case"public":$="This thread's visibility has been updated to public. Anyone on the Internet can see it on your public profile, and it is publicly searchable.";break}try{let J=await DA.setThreadMeta({thread:Q,meta:wJ(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let F=PB(new URL(A.ampURL),Q).toString();try{await C4.instance.tuiInstance.clipboard.writeText(F),Y=!0}catch(X){j.error("Failed to copy thread URL after visibility update",{error:X})}}let Z=Y?`${$} Link copied to clipboard.`:$;return new eQ(Z)}catch(J){let Y=J instanceof Error?J.message:String(J);if(Y.includes("no-workspace"))return Error("You are not a member of any workspace.");if(Y.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(Y.includes("no-groups"))return Error("You are not a member of any groups.");return j.error("Unexpected failure to update thread visibility",{error:J}),Error(`Failed to update thread visibility for ${Q}`)}}class RG0 extends I5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new n41(this.offstage)}updateRenderObject(A){if(A instanceof n41)A.offstage=this.offstage}}class n41 extends F4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class a41{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class o41 extends T0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Zn4}}class Zn4 extends _0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new yj,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new yj,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new RG0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new n4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new RG0({key:$.key,offstage:!J,child:Y}))}return new QA({fit:"expand",children:Q})}}class s41 extends H1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=ly5(Q);return new yA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:K0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new g6({items:Q,showBorder:!1,getLabel:($)=>{let J=r41($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",z=J.item.noun?.toLowerCase()??"";if(E!==z)return E<z?-1:1;return 0}let Z=ej($.item.verb.toLowerCase(),Y),F=ej(J.item.verb.toLowerCase(),Y);if(Z!==F)return F-Z;let X=ej(r41($.item),Y),D=ej(r41(J.item),Y);if(X!==D)return D-X;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=P0.of(J);return new p({text:new C($.status.reason,new v({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new Fn4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class Fn4 extends H1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=P0.of(Y),{colors:F,app:X}=Z,D=B?X.selectionBackground:void 0,G=B?X.selectionForeground:F.foreground,V=B?G:F.mutedForeground,U=new p({text:new C(Q.noun?.toLowerCase()??"",new v({color:V,dim:$||!B})),textAlign:"right"}),K=[new C(Q.verb.toLowerCase(),new v({color:G,bold:!0,dim:$}))];if($)K.push(new C(" (unavailable)",new v({color:G,dim:!0})));let E=p.spans(K),z=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)z.push({child:iy5(Q.shortcut,Z,$)});return new Xn4({columns:z,padding:K0.horizontal(1),backgroundColor:D})}}function r41(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function ly5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,y4(B.noun)):Q},0)}function iy5(A,Q,B){let{colors:$,app:J}=Q,Y=new v({color:$.mutedForeground,dim:B}),Z=[];for(let F of A.modifiers()){if(Z.length>0)Z.push(new C(" ",Y));Z.push(new C(F,new v({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new C(" ",Y));return Z.push(new C(A.key,new v({color:J.keybind,bold:!0,dim:B}))),p.spans(Z)}class Xn4 extends H1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let F=0;F<Q.length;F++){let X=Q[F];if(F>0&&B>0)Y.push(new U0({width:B}));if(X.fixedWidth!==void 0)Y.push(new U0({width:X.fixedWidth,child:X.child}));else if(X.expanded)Y.push(new _1({child:X.child}));else Y.push(X.child)}let Z=new r0({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new h0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class t41{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class $Z extends q6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=$Z.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType($Z)?.commandRegistry??null}}class e41 extends T0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Dn4}}class Dn4 extends _0{modalStack=new a41;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=$Z.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=$Z.of(A).commands,B=new s41({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new o41({root:B,controller:this.modalStack})}}var AA1=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]},{input:"S",keys:["Alt"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],QA1=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class PG0 extends H1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=A4.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[F,X]=this.renderRow(Z),D;if(J)D=new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[F,new x0({padding:K0.only({left:4}),child:X})]});else D=new r0({crossAxisAlignment:"start",children:[new _1({flex:1,child:F}),new U0({width:1}),new _1({flex:1,child:X})]});Y.push(new x0({padding:K0.horizontal(6),child:D}))}return new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class BA1 extends T0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new Gn4}}class Gn4 extends _0{scrollController;initState(){this.scrollController=new hA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=R1.of(A).colorScheme,J=P0.of(A).app,Y=A4.of(A),Z=new v({color:B.primary,bold:!0}),F=new v({color:B.secondary,bold:!0}),X=new v({color:J.keybind}),D=new v({color:J.command}),G=new v({color:B.foreground}),V=new v({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,z=K-4,W=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((L)=>{let P=L.noun?.toLowerCase();return P!=="dev"&&P!=="debug"&&!L.id.startsWith("debug-")&&!H.has(L.id)})].sort((L,P)=>{let S=(L.noun??"").toLowerCase(),T=(P.noun??"").toLowerCase(),x=S.localeCompare(T);if(x!==0)return x;let h=L.verb.toLowerCase(),u=P.verb.toLowerCase(),k=h.localeCompare(u);if(k!==0)return k;return L.id.localeCompare(P.id)}),I=new vA({autofocus:!0,controller:this.scrollController,child:new h0({constraints:new w1(W,W,0,Number.POSITIVE_INFINITY),child:new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new t1({child:new p({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5704
5704
  `,Z)})}),new U0({height:1}),new x0({padding:K0.horizontal(2),child:new p({text:new C(`Editor Shortcuts
5705
5705
  `,F)})}),new PG0({items:AA1.filter((L)=>L.submitOnEnterOnly===void 0||L.submitOnEnterOnly===this.widget.submitOnEnter),renderRow:(L)=>{let P=[];for(let T of L.methods){let x=this.buildCleanKeyCombination(T);P.push(x)}let S=P.join(", ");return[new p({text:new C(S,X)}),new p({text:new C(L.description,G)})]}}),new U0({height:1}),new x0({padding:K0.horizontal(2),child:new p({text:new C(`Scrolling & Navigation
5706
5706
  `,F)})}),new PG0({items:QA1,renderRow:(L)=>{let P=[];for(let T of L.methods){let x=this.buildCleanKeyCombination(T);P.push(x)}let S=P.join(", ");return[new p({text:new C(S,X)}),new p({text:new C(L.description,G)})]}}),new U0({height:1}),new x0({padding:K0.horizontal(2),child:new p({text:new C(`Command Palette Commands
@@ -5801,7 +5801,7 @@ Ctrl-X, Y, Z to unlock`;if(E){let V0=G.text.replace(/`([^`]+)`/g,"$1")+`
5801
5801
  `))}function Ag5(A,Q){let{colors:B,app:$}=Q;switch(A){case"pending":return{icon:"◌",color:B.warning};case"registered":return{icon:"•",color:B.mutedForeground};case"failed":return{icon:"✗",color:$.toolError};case"duplicate":return{icon:"◇",color:B.warning};default:return{icon:"?",color:B.foreground}}}function hr4(A,Q){let B=A.replace(/\s+/g," ").trim();if(y4(B)<=Q)return B;let $="...",J=y4($);if(Q<=J)return WJ($,Q);return`${WJ(B,Q-J,!0,"")}${$}`}var b61="https://ampcode.com/news/neo",u61=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:b61,href:b61},"","",{text:"Need old Amp for a bit? Use ",keybind:"amp --take-me-back"}]}];function Qg5(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:b61,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function Bg5(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var gf=50,zR=40,x61=1000,$g5=420,Jg5=760,Yg5=-250,Zg5=1100,ZV0=33,dr4=0.999,Fg5=2.1,Xg5=720,Dg5=420,sr4="Meet the new",tr4="Amp",er4="CLI",h61=L4(sr4).length,Gg5=L4(tr4).length,Vg5=L4(er4).length,FV0={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},cr4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},lr4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},ir4=[FV0,cr4,lr4,FV0,cr4,lr4,FV0],Ug5=FV0;class g61 extends T0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??Bg5(),this.introStages=this.variant==="npm-migration"?Qg5(this.binaryInstallCommand):u61,this.dismissible=this.variant!=="npm-migration"}createState(){return new As4}}class As4 extends _0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=x61;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new v9(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=JZ(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=dr4,this.firstStageHintVisible=this.animationProgress>=dr4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:x61,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=JZ(A/Jg5);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},ZV0)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let B=performance.now()-this.stageTransitionStartedAt,$=JZ(B/$g5);if(this.setState(()=>{if(this.stageTransitionProgress=$,$>=1)this.previousIntroStage=null}),$>=1)this.stopStageTransitionTimer()},ZV0)}startProgressAnimation({from:A,to:Q,durationMs:B,onComplete:$}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=B,this.onAnimationComplete=$,this.animationProgress=A,this.animationTimer=setInterval(()=>{let J=performance.now()-this.startedAt,Y=JZ(J/this.animationDurationMs),Z=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*mf(Y);if(this.setState(()=>{this.animationProgress=Z}),Y>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},ZV0)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,x61+Yg5),Q=A+Zg5;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?JZ((A-this.firstStageTitleRevealStartedAt)/Xg5):this.firstStageTitleRevealProgress,B=this.firstStageHintRevealStartedAt?JZ((A-this.firstStageHintRevealStartedAt)/Dg5):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=B}),Q>=1&&B>=1)this.stopFirstStageRevealTimer()},ZV0)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=nr4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:ar4(nr4(this.previousIntroStage),A,mf(this.stageTransitionProgress));return this.dismissProgress>0?ar4(Q,Ug5,mf(this.dismissProgress)):Q}build(A){let Q=R1.of(A).colorScheme,B=P0.of(A),$=this.currentOrbPalette(),J=tQ(1,"frontier",$),Y=A4.of(A).size,F=this.widget.animationProgress??this.animationProgress,X=Math.max(Y.width/gf,Y.height/zR)*Fg5,D=X+(1-X)*F,G=mf(this.dismissProgress),V=Math.max(gf,Math.round(gf*D)),U=Math.max(zR,Math.round(zR*D)),K=Math.round((Y.width-V)/2),E=Math.round((Y.height-U)/2),z=Math.max(0,Math.floor((Y.width-gf)/2)),W=-Math.floor(zR/2),H=Math.round(K+(z-K)*F),q=Math.round(E+(W-E)*F),N=H+V/2,I=q+U/2,w=Kg5({dismissProgress:this.dismissProgress,easedDismissProgress:G,introOrbScale:D,normalOrbCenterX:N,normalOrbCenterY:I,size:Y}),O=Math.max(gf,Math.round(gf*w.orbScale)),L=Math.max(zR,Math.round(zR*w.orbScale)),P=w.orbCenterX,S=w.orbCenterY,T=Math.round(P-O/2),x=Math.round(S-L/2),h=Math.max(3,Math.min(Y.height-5,Math.floor(zR/2)+2)),u=Math.max(h+3,Y.height-3),k=w.textDissolveProgress,f=this.isFinalIntroStage()?w.backdropDissolveProgress:0,d=this.firstStageTitleVisible&&k<1,l=d&&this.firstStageHintVisible,g=l&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),c=this.introStage===0?this.firstStageTitleRevealProgress:1,r=this.introStage===0?this.firstStageHintRevealProgress:1,A0=Math.max(24,Math.min(74,Y.width-4)),w0=Math.min(12,Math.max(8,Y.height-h-6)),V0=Math.max(0,Math.floor((Y.width-A0)/2)),N0=Math.max(0,Math.min(Y.height-w0,Math.floor(Y.height*0.55-w0/2))),j0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new yx({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new yx({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new n4({autofocus:!0,canRequestFocus:!0,debugLabel:"NeoWelcomeTakeover",onKey:(Q0)=>{if(Q0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&Q0.key==="c"&&Q0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&Q0.key==="q")return this.widget.onQuit?.(),"handled";if((Q0.key===" "||Q0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(Q0.key==="Escape"||Q0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(Q0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(Q0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new QA({fit:"expand",children:[new Qs4({color:Q.background,dissolveProgress:f}),new QA({fit:"expand",children:[new k1({onClick:()=>{},child:U0.expand()}),new NA({left:T,top:x,width:O,height:L,child:j0}),...d?[new NA({left:V0,top:N0,width:A0,height:w0,child:zg5({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:A0,height:w0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:J,link:B.app.link,keybind:B.app.keybind,titleRevealProgress:c,dissolveProgress:k,context:A})})]:[],...l?[...g?[new NA({left:V0,top:Math.max(0,u-1),width:A0,height:1,child:new p({text:wg5({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:k}),textAlign:"center"})})]:[],new NA({left:V0,top:u,width:A0,height:1,child:Mg5({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:B.app.keybind,revealProgress:r,dissolveProgress:k,context:A})})]:[]]})]})})}}class Qs4 extends Z8{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new Bs4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class Bs4 extends F4{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=Math.floor(this.size.width),Z=Math.floor(this.size.height),F={bg:this.color},X=JZ(this.dissolveProgress);if(X<=0){A.fill($,J,Y,Z," ",F);return}if(X>=1)return;for(let D=0;D<Z;D++)for(let G=0;G<Y;G++)if(!Eg5(G,D,Y,Z,X))A.fill($+G,J+D,1,1," ",F)}}function JZ(A){return Math.min(1,Math.max(0,A))}function mf(A){return 1-(1-A)**3}function nr4(A){return ir4[A]??ir4[0]}function ar4(A,Q,B){return{primary:xj(A.primary,Q.primary,B),secondary:xj(A.secondary,Q.secondary,B)}}function Kg5({dismissProgress:A,easedDismissProgress:Q,introOrbScale:B,normalOrbCenterX:$,normalOrbCenterY:J,size:Y}){return{orbScale:B+(B*0.86-B)*Q,orbCenterX:$+(Y.width*0.54-$)*Q,orbCenterY:J-Y.height*0.44*Q,textDissolveProgress:JZ(A/0.52),backdropDissolveProgress:mf(JZ((A-0.12)/0.88))}}function Eg5(A,Q,B,$,J){let Y=$<=1?0:Q/($-1),Z=$s4(A+Q*Math.max(1,B));return(1-Y)*0.72+Z*0.28<J}function zg5({introStages:A,stage:Q,previousStage:B,progress:$,direction:J,width:Y,height:Z,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E}){if(B===null||$>=1)return f61({introStages:A,stage:Q,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E});let z=mf($),W=J*Math.round((1-z)*Y),H=-J*Math.round(z*Y);return new uz(new QA({fit:"expand",children:[new NA({left:H,top:0,width:Y,height:Z,child:f61({introStages:A,stage:B,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:B===0?1:U,dissolveProgress:K,context:E})}),new NA({left:W,top:0,width:Y,height:Z,child:f61({introStages:A,stage:Q,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E})})]}))}function f61({introStages:A,stage:Q,foreground:B,mutedForeground:$,accent:J,link:Y,keybind:Z,titleRevealProgress:F,dissolveProgress:X,context:D}){let G=A[Q]??A[0]??u61[0],V=new v({color:J,bold:!0}),U=new v({color:B}),K=A===u61&&Q===0,E=[...G.title===null?[]:[new p({text:K?XV0(qg5({progress:F,foreground:J,pulseColor:J}),X):new C(J$(G.title,X),V),textAlign:"center"})],...G.body.length>0?[Wg5()]:[],...G.body.map((z)=>Hg5(z,U,$,Y,Z,X,D))];return new t1({child:new x0({padding:K0.horizontal(1),child:new y0({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:E})})})}function Wg5(){return U0.height(1)}function Hg5(A,Q,B,$,J,Y,Z){if(typeof A==="string")return new p({text:new C(J$(A,Y),Q),textAlign:"center"});if("codeBlock"in A)return new Y3({onCopy:(F,X)=>{if(X)l5.success(Z,"Copied to clipboard",2000)},child:new y0({mainAxisSize:"min",children:A.codeBlock.map((F)=>new p({text:new C(J$(F,Y),new v({color:J})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let F=new p({text:new C("",void 0,[new C(J$(A.text,Y),new v({color:B,dim:!0})),new C(J$(A.keybind,Y,L4(A.text).length),new v({color:J}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new t1({child:new Y3({child:F})});return F}if("highlightText"in A){let F=UA.createSpan(A.href,A.linkText,new v({color:$,underline:!0})),X=sD.of(Z),D=new C("",void 0,[new C(A.text,Q),new C(A.highlightText,new v({color:J})),new C(A.textAfterHighlight,Q),new C(F.text,F.style,F.children,F.hyperlink,()=>{nA(Z,A.href,{forceExternal:!1,onShowImagePreview:X})}),new C(A.textAfter,Q)]);return new p({text:XV0(D,Y),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new y0({mainAxisSize:"min",children:[new p({text:new C(J$(A.text,Y),Q),textAlign:"center"}),new t1({child:new r0({mainAxisSize:"min",children:[UA.createWidget(Z,A.href,J$(A.linkText,Y),new v({color:$,underline:!0})),new p({text:new C(J$(A.textAfter,Y),Q)})]})})]});let F=UA.createSpan(A.href,A.linkText,new v({color:$,underline:!0})),X=sD.of(Z),D=new C("",void 0,[new C(A.text,Q),new C(F.text,F.style,F.children,F.hyperlink,()=>{nA(Z,A.href,{forceExternal:!1,onShowImagePreview:X})}),new C(A.textAfter,Q)]);return new p({text:XV0(D,Y),textAlign:"center"})}if(Y>0)return new p({text:new C(J$(A.text,Y),new v({color:$,underline:!0})),textAlign:"center"});return new t1({child:UA.createWidget(Z,A.href,A.text,new v({color:$,underline:!0}))})}function qg5({progress:A,foreground:Q,pulseColor:B}){let $=new v({color:Q,bold:!0}),J=new v({color:Ig5({progress:A,foreground:Q,pulseColor:B}),bold:!0});return new C("",void 0,[new C(Ng5(A).padEnd(h61," "),$),new C(" ",$),new C(or4(tr4,Gg5,A,0.72),$),new C(" ",$),new C(or4(er4,Vg5,A,0.88),J)])}function Ng5(A){let Q=L4(sr4),B=Math.min(h61,Math.ceil(JZ(A/0.62)*h61));return Q.slice(0,B).join("")}function or4(A,Q,B,$){return B>=$?A:"".padEnd(Q," ")}function Ig5({progress:A,foreground:Q,pulseColor:B}){if(A<0.88||A>=1)return Q;let $=JZ((A-0.88)/0.12);return Math.cos($*Math.PI*4)*(1-$)>0.12?B:Q}function wg5({stage:A,featureStageCount:Q,foreground:B,dissolveProgress:$}){return new C(J$(`${A}/${Q}`,$),new v({color:B,dim:!0}))}function Cg5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y}){let Z=new v({color:$}),F=new v({color:B,dim:!0}),X=Q?A?"Enter":"Space":"Esc",D=Q?A?" to get started":" to continue":" to quit, or use ",G=Q?"":"amp --take-me-back",V=Q?"":" to use the old version",U=`${D}${G}${V}`;if(!Q)return new C("",void 0,[new C(X,Z),new C(D,F),new C(G,Z),new C(V,F)]);let K=rr4(X,J),E=rr4(U,JZ((J*(L4(X).length+L4(U).length)-L4(X).length)/L4(U).length));return new C("",void 0,[new C(J$(K,Y),Z),new C(J$(E.slice(0,D.length),Y),F),new C(J$(E.slice(D.length,D.length+G.length),Y),Z),new C(J$(E.slice(D.length+G.length),Y),F)])}function Mg5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y,context:Z}){if(Q)return new p({text:Cg5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y}),textAlign:"center"});let F=new v({color:$}),X=new v({color:B,dim:!0});return new Y3({onCopy:(D,G)=>{if(G)l5.success(Z,"Copied to clipboard",2000)},child:new p({text:new C("",void 0,[new C("q",F),new C(" to quit, or use ",X),new C("amp --take-me-back",F),new C(" to use the old version",X)]),textAlign:"center",selectable:!0})})}function rr4(A,Q){let B=L4(A),$=Math.min(B.length,Math.ceil(JZ(Q)*B.length));return B.slice(0,$).join("").padEnd(B.length," ")}function XV0(A,Q,B=0){if(Q<=0)return A;let $=B+L4(A.text??"").length,J=A.children?.map((Y)=>{let Z=XV0(Y,Q,$);return $+=L4(Y.toPlainText()).length,Z});return new C(A.text?J$(A.text,Q,B):A.text,A.style,J,A.hyperlink,A.onClick)}function J$(A,Q,B=0){if(Q<=0)return A;return L4(A).map((J,Y)=>{if(J.trim()==="")return J;return $s4(B+Y)<Q?" ":J}).join("")}function $s4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}p0();O2();function aI(A,Q){let{colors:B,dim:$}=Q,J=[];if(A.totalCostUSD===null)return J;let Y=A.costBreakdown,Z=Y?.freeUSD??0,F=Y?.paidUSD??0;if(Z===0&&F===0)return J;let D={decimalPlaces:"more-if-tiny",intent:"cost"};if(F===0)J.push(new C(nU(Z,D),new v({color:B.foreground,dim:$}))),J.push(new C(" (free)",new v({color:B.foreground,dim:$})));else if(Z>0)J.push(new C(nU(Z,D),new v({color:B.foreground,dim:$}))),J.push(new C(" (free)",new v({color:B.foreground,dim:$}))),J.push(new C(" + ",new v({color:B.foreground,dim:$}))),J.push(new C(nU(F,D),new v({color:B.foreground,dim:$,bold:!$})));else J.push(new C(nU(F,D),new v({color:B.foreground,dim:$,bold:!$})));return J}class m61 extends P4{}class p61 extends P4{}function Lg5(A,Q){if(Q.code==="auth-required")return"You must be logged in to view thread usage. Run `amp login` first.";if(Q.code==="thread-not-found")return`Thread ${A} not found.`;return`Failed to load thread usage: ${Q.message??Q.code}`}function Og5(A,Q){let B=P0.of(Q),{colors:$}=B,J=aI(A,{colors:{foreground:$.foreground}}),Y=[];if(J.length>0)Y.push(new C("Total: ",new v({color:$.mutedForeground}))),Y.push(...J);else if(A.totalCostUSD===null)Y.push(new C("Usage information is currently unavailable."));else Y.push(new C("No usage recorded for this thread yet."));if(A.costBreakdownURL)Y.push(new C(`
5802
5802
 
5803
5803
  `)),Y.push(new C("Details: ",new v({color:$.mutedForeground}))),Y.push(new C(A.costBreakdownURL,new v({color:B.app.link})));return new p({text:new C("",void 0,Y)})}function jg5(A,Q,B){let $=Og5(A,Q);if(!A.costBreakdownURL)return new yA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new c1(()=>{return l4.maybeInvoke(Q,new b9(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new c1(()=>{return nA(Q,J),"handled"});return new yA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new l4({actions:new Map([[m61,Y],[p61,Z]]),child:new Y5({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[C1.key("o"),new p61],[C1.key("y"),new m61]]),child:new d4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function Js4(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await DA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(Lg5(J,Y.error),"error",5000),$();return}Q.push(jg5(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}function Rg5({ampURL:A,threadID:Q,logPath:B}){return[`Debug thread ${PB(new URL(A),Q).toString()} (cli log: ${B}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
5804
- `)}class d61 extends T0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;onThreadArchived;onActiveThreadChange;initialUserInput;getDefaultNewThreadVisibility;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.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new Zs4}}class Zs4 extends _0{editorController=new O8;commandPalette=new Xr(this);commandRegistry=new t41;toastController=new N01;exitHintTimer=new tx(this,1000);ideStatus=new g8(this,{});threadNavigationHistory=new i41;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;agentStateSubscription=null;activeThreadIDSubscription=null;currentTitleText=void 0;currentAgentBusy=!1;currentTerminalTitle=void 0;terminalTitleSpinner=new H6;terminalTitleSpinnerTimer=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>Jn4({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return Yn4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await ad4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await od4({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 rd4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(sB.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(k30(Q.settings)))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new c41({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,Q=this.widget.neoContext.pluginService?ri4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((F)=>bA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:F,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},Js4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new GA1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new y61({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await nA(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{CJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((F)=>new XA1({onCancel:F,onSelect:(X)=>{this.handleIdeSelection(X),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new $A1({commands:$Z.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new yA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new p({text:new C(U01({version:"0.0.1778518196-gcde0a1",buildTimestamp:"2026-05-11T16:53:36.885Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:C1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{l4.maybeInvoke(Y,new Rf)}},...Q,...ui4(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new v61({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,sendFeedbackReport:this.sendFeedbackReport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B,statusItems:this.pluginIntegration?.getStatusItems()??[]}),J=A4.of(A),Y=J.capabilities.animationSupport!=="disabled",F=[new h0({constraints:w1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())F.push(new n4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new e41({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)F.push(bA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)F.push(new n4({debugLabel:"NeoWelcomeDialogOverlay",child:new g61({onDismiss:this.dismissNeoWelcome,onQuit:()=>C4.instance.stop(),animationsEnabled:Y,variant:this.widget.neoWelcomeVariant})}));if(F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)F.push(new ZA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:Ss.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)F.push(new FA1);return new T3({neoContext:this.widget.neoContext,child:new $Z({commandRegistry:this.commandRegistry,child:new uI({completionBuilder:this.widget.completionBuilder,child:new l5({controller:this.toastController,child:new l4({actions:this.buildActions(),child:new Y5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[C1.ctrl("c"),new WG0],[C1.ctrl("o"),new HG0],[C1.alt("i"),new NG0],[C1.alt("p"),new CI],[C1.ctrl("t"),new IG0]]),child:new d4({debugLabel:"AppShellFocus",child:new I01({controller:this.toastController,child:new JA1({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new QA({children:F})})})})})})})})})})}buildActions(){let A=new c1(()=>{if(IJ.hasAnyCopyableSelection())return IJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new c1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new c1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new c1(()=>{return this.startNewDraftThread(),"handled"}),J=new c1(()=>{return C4.instance.stop(),"handled"}),Y=new c1((U)=>{if(!U.text)return"ignored";return C4.instance.tuiInstance.clipboard.writeText(U.text).then((K)=>{if(K.ok)this.toastController.show(U.successMessage,"success",2000);else this.toastController.show(`${U.failureMessage}: ${K.userFacingErrorMessage}`,"error",4000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new c1(()=>{return C4.instance.toggleFrameStatsOverlay(),"handled"}),F=new c1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=new c1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=Gx(U);return C4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new c1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new c1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await C4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new c1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[WG0,A],[Bs,$],[Rf,J],[b9,Y],[Ys,B],[HG0,Q],[NG0,F],[Zs,X],[Fs,D],[Xs,G],[CI,Z],[IG0,V]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.currentAgentBusy=!1,this.syncTerminalTitleSpinner(),this.clearTerminalTitle(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{this.startNewDraftThread({prompt:Rg5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:Gx(A)}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await mx(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=tB(Q),J=pX0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return mX0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Ys4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(dZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Ys4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(bI);if(this.exitHintTimer.isActive())A.add(wf);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),C4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null,$)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),Y=A.find((D)=>D.type==="text");if(Y&&Y.type==="text")this.widget.history.add(Y.text,Ss.cwd()),this.widget.history.reset();let Z=B?void 0:await this.widget.getDefaultNewThreadVisibility?.(),F=B??Z??null,X=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,F?wJ(F):void 0);this.sendUserMessage(X,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(X)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=tB(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};NJ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=LY0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}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={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{await A.client.reconnect(),this.toastController.update(B,Q?`Reconnected ${Q}`:"Reconnected thread","success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{await A.client.disconnectAndWait(),this.toastController.update(B,Q?`Disconnected ${Q}`:"Disconnected thread","success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)}),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.currentTitleText=Q,this.updateTerminalTitle()}}),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=A.agentState().subscribe({next:(Q)=>{let B=Q!=="idle"&&Q!=="error";if(B===this.currentAgentBusy)return;this.currentAgentBusy=B,this.syncTerminalTitleSpinner(),this.updateTerminalTitle()}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}clearTerminalTitle(){this.currentTitleText=void 0,this.updateTerminalTitle()}updateTerminalTitle(){let A=Ss.cwd().replace(Ss.env.HOME||"","~"),Q=this.currentAgentBusy?`${this.terminalTitleSpinner.toBraille()} `:"",B=this.currentTitleText?`${Q}amp - ${this.currentTitleText} - ${A}`:this.currentAgentBusy?`${Q}amp - ${A}`:"";if(B===this.currentTerminalTitle)return;this.currentTerminalTitle=B,Ss.stdout.write(KI(B))}syncTerminalTitleSpinner(){if(this.currentAgentBusy){if(this.terminalTitleSpinnerTimer)return;this.terminalTitleSpinnerTimer=setInterval(()=>{this.terminalTitleSpinner.step(),this.updateTerminalTitle()},200);return}if(this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function Ys4(A,Q,B){let $={...A};for(let J of Pg5(Q,B)){if(!dZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Pg5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}i4();function Fs4(A,Q,B,$){let J=eT(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 rY(G,V),K=new v9(42),E=new WI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,E0.default(),K);E.layout(w1.tight(G,V)),E.paint(U,0,0);let z=U.getBuffer().getCells(),W=0;for(let P=0;P<V;P++)if(z[P].some((S)=>S.char!==" ")){W=P;break}let H=V-1;for(let P=V-1;P>=0;P--)if(z[P].some((S)=>S.char!==" ")){H=P;break}function q(P,S){if(!P)return"";if(P.type==="rgb"){let{r:T,g:x,b:h}=P.value;if(B.getColorDepth()>=24)return`\x1B[${S?38:48};2;${T};${x};${h}m`;let u=Sj(T,x,h);return`\x1B[${S?38:48};5;${u}m`}return""}let N=[];if(H>=W)for(let P=W;P<=H;P++){let S="";for(let T=0;T<G;T++){let x=z[P][T],h=x.char,u=q(x.style.fg,!0);S+=u+h+"\x1B[0m"}N.push(S)}let I=N.length,w=Math.max(I,D.length),O=Math.floor((w-I)/2),L=Math.floor((w-D.length)/2);for(let P=0;P<w;P++){let S=" ".repeat(G);if(P>=O&&P<O+I)S=N[P-O];let T=" ",x="";if(P>=L&&P<L+D.length)x=D[P-L];B.write(S+T+x+`
5804
+ `)}class d61 extends T0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;onThreadArchived;onActiveThreadChange;initialUserInput;getDefaultNewThreadVisibility;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.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new Zs4}}class Zs4 extends _0{editorController=new O8;commandPalette=new Xr(this);commandRegistry=new t41;toastController=new N01;exitHintTimer=new tx(this,1000);ideStatus=new g8(this,{});threadNavigationHistory=new i41;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;agentStateSubscription=null;activeThreadIDSubscription=null;currentTitleText=void 0;currentAgentBusy=!1;currentTerminalTitle=void 0;terminalTitleSpinner=new H6;terminalTitleSpinnerTimer=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>Jn4({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return Yn4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await ad4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await od4({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 rd4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(sB.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(k30(Q.settings)))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new c41({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,Q=this.widget.neoContext.pluginService?ri4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((F)=>bA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:F,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},Js4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new GA1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new y61({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await nA(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{CJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((F)=>new XA1({onCancel:F,onSelect:(X)=>{this.handleIdeSelection(X),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new $A1({commands:$Z.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new yA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new p({text:new C(U01({version:"0.0.1778531432-g3bd093",buildTimestamp:"2026-05-11T20:34:42.741Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:C1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{l4.maybeInvoke(Y,new Rf)}},...Q,...ui4(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new v61({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,sendFeedbackReport:this.sendFeedbackReport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B,statusItems:this.pluginIntegration?.getStatusItems()??[]}),J=A4.of(A),Y=J.capabilities.animationSupport!=="disabled",F=[new h0({constraints:w1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())F.push(new n4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new e41({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)F.push(bA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)F.push(new n4({debugLabel:"NeoWelcomeDialogOverlay",child:new g61({onDismiss:this.dismissNeoWelcome,onQuit:()=>C4.instance.stop(),animationsEnabled:Y,variant:this.widget.neoWelcomeVariant})}));if(F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)F.push(new ZA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:Ss.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)F.push(new FA1);return new T3({neoContext:this.widget.neoContext,child:new $Z({commandRegistry:this.commandRegistry,child:new uI({completionBuilder:this.widget.completionBuilder,child:new l5({controller:this.toastController,child:new l4({actions:this.buildActions(),child:new Y5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[C1.ctrl("c"),new WG0],[C1.ctrl("o"),new HG0],[C1.alt("i"),new NG0],[C1.alt("p"),new CI],[C1.ctrl("t"),new IG0]]),child:new d4({debugLabel:"AppShellFocus",child:new I01({controller:this.toastController,child:new JA1({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new QA({children:F})})})})})})})})})})}buildActions(){let A=new c1(()=>{if(IJ.hasAnyCopyableSelection())return IJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new c1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new c1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new c1(()=>{return this.startNewDraftThread(),"handled"}),J=new c1(()=>{return C4.instance.stop(),"handled"}),Y=new c1((U)=>{if(!U.text)return"ignored";return C4.instance.tuiInstance.clipboard.writeText(U.text).then((K)=>{if(K.ok)this.toastController.show(U.successMessage,"success",2000);else this.toastController.show(`${U.failureMessage}: ${K.userFacingErrorMessage}`,"error",4000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new c1(()=>{return C4.instance.toggleFrameStatsOverlay(),"handled"}),F=new c1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=new c1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=Gx(U);return C4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new c1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new c1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await C4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new c1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[WG0,A],[Bs,$],[Rf,J],[b9,Y],[Ys,B],[HG0,Q],[NG0,F],[Zs,X],[Fs,D],[Xs,G],[CI,Z],[IG0,V]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.currentAgentBusy=!1,this.syncTerminalTitleSpinner(),this.clearTerminalTitle(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{this.startNewDraftThread({prompt:Rg5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:Gx(A)}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await mx(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=tB(Q),J=pX0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return mX0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Ys4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(dZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Ys4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(bI);if(this.exitHintTimer.isActive())A.add(wf);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),C4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null,$)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),Y=A.find((D)=>D.type==="text");if(Y&&Y.type==="text")this.widget.history.add(Y.text,Ss.cwd()),this.widget.history.reset();let Z=B?void 0:await this.widget.getDefaultNewThreadVisibility?.(),F=B??Z??null,X=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,F?wJ(F):void 0);this.sendUserMessage(X,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(X)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=tB(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};NJ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=LY0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}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={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{await A.client.reconnect(),this.toastController.update(B,Q?`Reconnected ${Q}`:"Reconnected thread","success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{await A.client.disconnectAndWait(),this.toastController.update(B,Q?`Disconnected ${Q}`:"Disconnected thread","success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)}),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.currentTitleText=Q,this.updateTerminalTitle()}}),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=A.agentState().subscribe({next:(Q)=>{let B=Q!=="idle"&&Q!=="error";if(B===this.currentAgentBusy)return;this.currentAgentBusy=B,this.syncTerminalTitleSpinner(),this.updateTerminalTitle()}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}clearTerminalTitle(){this.currentTitleText=void 0,this.updateTerminalTitle()}updateTerminalTitle(){let A=Ss.cwd().replace(Ss.env.HOME||"","~"),Q=this.currentAgentBusy?`${this.terminalTitleSpinner.toBraille()} `:"",B=this.currentTitleText?`${Q}amp - ${this.currentTitleText} - ${A}`:this.currentAgentBusy?`${Q}amp - ${A}`:"";if(B===this.currentTerminalTitle)return;this.currentTerminalTitle=B,Ss.stdout.write(KI(B))}syncTerminalTitleSpinner(){if(this.currentAgentBusy){if(this.terminalTitleSpinnerTimer)return;this.terminalTitleSpinnerTimer=setInterval(()=>{this.terminalTitleSpinner.step(),this.updateTerminalTitle()},200);return}if(this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function Ys4(A,Q,B){let $={...A};for(let J of Pg5(Q,B)){if(!dZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Pg5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}i4();function Fs4(A,Q,B,$){let J=eT(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 rY(G,V),K=new v9(42),E=new WI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,E0.default(),K);E.layout(w1.tight(G,V)),E.paint(U,0,0);let z=U.getBuffer().getCells(),W=0;for(let P=0;P<V;P++)if(z[P].some((S)=>S.char!==" ")){W=P;break}let H=V-1;for(let P=V-1;P>=0;P--)if(z[P].some((S)=>S.char!==" ")){H=P;break}function q(P,S){if(!P)return"";if(P.type==="rgb"){let{r:T,g:x,b:h}=P.value;if(B.getColorDepth()>=24)return`\x1B[${S?38:48};2;${T};${x};${h}m`;let u=Sj(T,x,h);return`\x1B[${S?38:48};5;${u}m`}return""}let N=[];if(H>=W)for(let P=W;P<=H;P++){let S="";for(let T=0;T<G;T++){let x=z[P][T],h=x.char,u=q(x.style.fg,!0);S+=u+h+"\x1B[0m"}N.push(S)}let I=N.length,w=Math.max(I,D.length),O=Math.floor((w-I)/2),L=Math.floor((w-D.length)/2);for(let P=0;P<w;P++){let S=" ".repeat(G);if(P>=O&&P<O+I)S=N[P-O];let T=" ",x="";if(P>=L&&P<L+D.length)x=D[P-L];B.write(S+T+x+`
5805
5805
  `)}if($)B.write(`
5806
5806
  \x1B[90m${$}\x1B[0m
5807
5807
  `)}p0();sX0();var _g5=2000;function Xs4(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<_g5)return;if(J=U,hj())return;if(tF0())eF0();else DZ0(V)},Z=(V)=>{if(!Q||!B)return;if(hj()&&!Ar()&&!kx())return;process.stdout.write(hD(`\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&&BQ(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){j.debug("Neo notification handling failed",{error:K})}finally{X=U}},error:(U)=>{j.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}function Tg5({initialUserInput:A,showNeoWelcome:Q,hideNeoWelcome:B,neoWelcomeVariant:$,neoWelcomeDismissed:J}){if(B)return{show:!1,markDismissedOnDismiss:!1};if($==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let Y=!A&&!J;return{show:Y,markDismissedOnDismiss:Y}}async function kg5(A){await NJ((Q)=>cX0(Q,A,"interactive"))}async function Ds4(A,Q={}){let{initialThreadID:B,initialUserInput:$,getDefaultNewThreadVisibility:J,openThreadPickerOnStart:Y=!1,observerOnly:Z=!1,initialAgentMode:F,initialReasoningEffort:X,showNeoWelcome:D=!1,hideNeoWelcome:G=!1,neoWelcomeVariant:V="intro"}=Q,U=V==="npm-migration",K=async(S)=>{let T=await A.getThreadFromServer(S);if(!T)return null;return bF0(T)},E=async(S)=>{let T=await A.getThreadFromServer(S);if(!T)throw Error(`Thread ${S} not found`);let x=await nY(S,A.configService,A.apiKey,{usesThreadActors:!0}),k=await OU({endpoint:A.rivetEndpoint}).threadActor.getOrCreate([S],{params:{wsToken:x.wsToken},createWithInput:{threadId:x.threadId,threadVersion:x.threadVersion,ownerUserId:x.ownerUserId,...x.agentMode?{agentMode:x.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:Nx4(T)}),skipReadyWait:!0});if(!k.ok&&k.status!==409)throw Error(`Thread import failed (${k.status}): ${await k.text()}`);try{await nx4(S,A.configService,A.apiKey,{executorType:"local-client"})}catch(f){j.warn("failed to mark thread as imported on server",{threadID:S,error:f instanceof Error?f.message:String(f)})}},z=new le0(A.rivetEndpoint,A.apiKey,A.configService,{clientID:AI.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(S)=>A.pluginService.event.toolCall(S),requestPluginToolResult:(S)=>A.pluginService.event.toolResult(S),pluginService:A.pluginService,invokeTool:async(S,T)=>{let x=typeof T.args==="object"&&T.args!==null?T.args:{},h=await JI({toolName:T.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:T.toolCallId,threadId:S});return A.toolService.invokeTool(T.toolName,{args:x},h)},persistLastThreadID:kg5,readFileSystemDirectory:A.readFileSystemDirectory},K,E),W=await II(),H=Tg5({initialUserInput:$,showNeoWelcome:D,hideNeoWelcome:G,neoWelcomeVariant:V,neoWelcomeDismissed:W.neoWelcomeDismissed}),q={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(S)=>{let T=await A.getThreadFromServer(S);return T?SV(T):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:la,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:U?!1:Z,sessionAgentMode:F??W.agentMode,explicitReasoningEffort:X,lastReasoningEffortByMode:W.lastReasoningEffortByMode,lastSpeedByMode:W.lastSpeedByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},N=(S,T)=>{return Zx({ampURL:A.ampURL,configService:A.configService,threadID:S,signal:T})},I=(S,T)=>{return oh4({ampURL:A.ampURL,configService:A.configService,threadID:S,signal:T})},w=new V01,O=Xs4({configService:A.configService}),L=await A.configService.getLatest();C4.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:L.settings["terminal.animation"]===!1}});let P=new Set;try{await Qr(new d61({clientPool:z,analyzeContextForThread:N,listSkillsForThread:I,completionBuilder:A.completionBuilder,history:new Go,ideManager:w,configService:A.configService,initialThreadID:U?void 0:B,notificationService:O,initialUserInput:U?void 0:$,getDefaultNewThreadVisibility:J,openThreadPickerOnStart:U?!1:Y,neoContext:q,showNeoWelcome:H.show,neoWelcomeVariant:V,onActiveThreadChange:A.setActiveThreadID,onNeoWelcomeDismissed:H.markDismissedOnDismiss?()=>{NJ(eh4).catch((T)=>{j.warn("Failed to mark Neo welcome as dismissed",{error:T})})}:void 0,onThreadArchived:(T)=>{P.add(T)}}));let S=z.lastActiveObservingClient;if(S){let{client:T,observer:x}=S,h=T.getThreadId();if(h){let u={id:h,title:x.title().getValue(),agentMode:x.agentMode,archived:P.has(h)},k=`${A.ampURL.replace(/\/$/,"")}/threads/${h}`;Fs4(u,k,process.stdout)}}}finally{process.stdout.write(KI("")),O.unsubscribe(),z.dispose(),await A.dispose?.()}process.exit(0)}lp();eK();async function Sg5(A,Q,B){let $=C80(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=yH($.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 Gs4(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await Sg5(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
@@ -7504,7 +7504,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
7504
7504
  `),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 C(G.slice(1,-1),new v({color:$.app.keybind,bold:!0})));else Y.push(new C(G,new v({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new C(`
7505
7505
  `))}return new h0({decoration:{color:B.colorScheme.background,border:l1.all(new i1($.app.keybind,1,"rounded"))},child:new x0({padding:K0.symmetric(0,1),child:new p({text:new C(void 0,void 0,Y)})})})}}class r51 extends Z8{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=wU0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new a51({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 _0A(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?d8: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?d8: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 mi5(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?d8: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,z=Math.round((1-E)*(V-1));return{x:K,y:z}}case"line":case"sparkline":case"stacked-area":{let D=Y?d8: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 pi5(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function di5(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 ci5(A,Q,B,$,J,Y,Z){let F;try{let E=R1.of(A),z=P0.of(A);F={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:z.app.keybind}}catch{F={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let X=new v({color:F.foreground,bold:!0}),D=new v({color:F.foreground}),G=new v({color:F.foreground,dim:!0}),V=[],U=new v({color:F.foreground,underline:!0}),K=(E,z)=>new C(z,U,void 0,Sz(E),()=>{nA(A,E)});if($.length<=1){if(V.push(new C(`${Q.label}: `,X)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new C(Y(Q.value),D));if(Q.meta)V.push(new C(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new C(`${Q.label}
7506
7506
  `,X));let z=0;for(let W=0;W<$.length;W++){let H=$[W],q=H.points[B];if(!q)continue;z+=q.value;let N=H.color??J[W%J.length]??F.foreground;if(V.push(new C("● ",new v({color:N}))),V.push(new C(`${H.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new C(Y(q.value),D));if(W<$.length-1||E)V.push(new C(`
7507
- `))}if(E)V.push(new C(" ",G)),V.push(new C("Total: ",G)),V.push(new C(Y(z),D))}return new h0({decoration:{color:F.background,border:l1.all(new i1(F.border,1,"rounded"))},child:new p({text:new C(void 0,void 0,V)})})}p0();L3();W8();B3();u7();k7();E9();O2();PQ();kV();i4();iS();NT();L1();p0();E9();class s51{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.1778518196-gcde0a1"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await R30(Q,this.configService)}catch(Q){j.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 Fw extends T0{props;constructor(A){super();this.props=A}createState(){return new T0A}}class T0A extends _0{_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 k0A extends _0{controller=new O8;focusNode=new D6({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=P0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=l1.all(new i1(B.foreground,1,"solid")),X=new eB({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 r0({children:[new h0({decoration:{color:B.background},child:new p({text:new C(">",new v({color:B.foreground}))})}),new _1({child:X})]}),G=new h0({padding:K0.symmetric(1,0),child:new p({text:this.widget.props.title?new C(this.widget.props.title,new v({color:$.command,bold:!0})):new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new C("Enter",new v({color:$.keybind}))),V.push(new C(" to submit, ",new v({color:B.foreground,dim:!0})));V.push(new C("Esc",new v({color:$.keybind}))),V.push(new C(" to cancel",new v({color:B.foreground,dim:!0})));let U=new h0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,V)})});return new h0({decoration:{border:F,color:B.background},padding:K0.all(1),child:new y0({children:[G,new U0({height:1}),D,new Z5,U]})})}}class os extends T0{props;constructor(A){super();this.props=A}createState(){return new k0A}}PQ();class S0A extends _0{controller=new O8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new D6({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>=s9)return!1;let Q=await eF(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=P0.of(A),{colors:B,app:$}=Q,Y=A4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new eD({controller:this.controller,triggers:[new PJ],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 d4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new h0({constraints:new w1({maxHeight:Z}),padding:K0.symmetric(1,0),child:X}),G=new h0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=new h0({padding:K0.symmetric(1,0),child:new p({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new v({color:$.keybind})),new C(" again to clear input",new v({color:B.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new v({color:B.foreground,dim:!0})),new C("Enter",new v({color:$.keybind})),new C(" to submit, ",new v({color:B.foreground,dim:!0})),new C("Esc",new v({color:$.keybind})),new C(" to clear",new v({color:B.foreground,dim:!0}))])})}),U=[G,new U0({height:1}),new _1({child:D}),new U0({height:1}),V];return new h0({decoration:{border:l1.all(new i1(B.foreground,1,"solid")),color:B.background},padding:K0.all(1),child:new y0({children:U})})}}class t51 extends T0{props;constructor(A){super();this.props=A}createState(){return new S0A}}function v0A(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 e51 extends H1{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)=>v0A(J.pubDate).length));return new g6({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=P0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(z,W)=>new U0({width:W,child:r0.end([new p({text:new C(z,new v({color:K}))})])});return new h0({decoration:V?{color:V}:void 0,padding:K0.symmetric(2,0),child:new r0({children:[new _1({child:new p({text:new C(J.title,new v({color:U})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),E(v0A(J.pubDate),B)]})})}})}}class VB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!VB._instance)VB._instance=new VB;return VB._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()}}p0();class y0A extends _0{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){j.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){j.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=P0.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 g6({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 W=this.currentQuery.trim().toLowerCase();return new h0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C("",void 0,[new C("Create new label: ",new v({color:E})),new C(W,new v({color:E,bold:!0}))])})})}return new h0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C(D.name,new v({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 A31 extends T0{props;constructor(A){super();this.props=A}createState(){return new y0A}}class BG extends T0{props;constructor(A){super();this.props=A}createState(){return new x0A}}class x0A extends _0{_spinner=new H6;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=P0.of(A),{colors:B,app:$}=Q,J=l1.all(new i1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new p({textAlign:"center",text:new C("",void 0,[new C(Y,new v({color:$.processing})),new C(" ",void 0),new C(this.widget.props.message,new v({color:B.foreground}))])}),X=[new _1({child:new y0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new U0({height:2,child:new h0({padding:K0.symmetric(2,0),child:new p({text:new C("",new v({dim:!0}),[new C("Press ",new v({color:B.foreground})),new C("Esc",new v({color:B.info})),new C(" to cancel",new v({color:B.foreground}))])})})}));let D=new h0({decoration:new b4(B.background,J),child:new U0({width:60,height:7,child:new y0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new n4({debugLabel:"LoadingDialog",child:new d4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class rU extends T0{props;constructor(A){super();this.props=A}createState(){return new f0A}}class f0A extends _0{scrollController=new hA;scrollAreaKey=new Z2("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 x2}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=P0.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=TD0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=l1.all(new i1(Q.colors.border,1,"solid")),Z=new h0({padding:K0.symmetric(1,0),child:new p({text:new C($.title,new v({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new p({text:new C($.description,new v({color:Q.colors.foreground})),selectable:!0}),X=new _1({child:new Y3({child:new h0({padding:K0.symmetric(1,0),child:new r0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new vA({controller:this.scrollController,autofocus:!0,child:F})}),new G2({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 h0({padding:K0.symmetric(1,0),child:new p({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new v({color:Q.colors.foreground,dim:!0})),new C("R",new v({color:Q.app.keybind})),new C(" to retry, ",new v({color:Q.colors.foreground,dim:!0})),new C("Esc",new v({color:Q.app.keybind})),new C(" to cancel",new v({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new v({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new v({color:Q.app.keybind}),U=new v({color:Q.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",V),new C(" to close • Use ",U),new C("↑↓",V),new C(" or ",U),new C("j/k",V),new C(" to scroll",U)])}return new C("Press any key to close",new v({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new n4({debugLabel:"MessageDialog",child:new QA({fit:"expand",children:[new k1({onClick:()=>{},child:new U0}),new d4({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 h0({decoration:{border:Y,color:Q.colors.background},padding:K0.all(1),child:new y0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),X,D]})})})]})})}}L3();e1();class b0A extends T0{props;constructor(A){super();this.props=A}createState(){return new u0A}}class u0A extends _0{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=o0.file(this.widget.props.cwd),B=Z1.relativePath(Q,_A(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return v5(A)}statusIcon(A){let Q=m8.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=P0.of(A),{app:B}=Q;if(this.plugins.length===0)return new p({text:new C("No plugins found.",new v({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 C(`${Y}/${J} ${K4(J,"plugin")} active`,new v({bold:!0}))),Z>0||F>0)$.push(new C(` (${Z} ${K4(Z,"command")}, ${F} ${K4(F,"tool")})`,new v({dim:!0})));$.push(new C(`
7507
+ `))}if(E)V.push(new C(" ",G)),V.push(new C("Total: ",G)),V.push(new C(Y(z),D))}return new h0({decoration:{color:F.background,border:l1.all(new i1(F.border,1,"rounded"))},child:new p({text:new C(void 0,void 0,V)})})}p0();L3();W8();B3();u7();k7();E9();O2();PQ();kV();i4();iS();NT();L1();p0();E9();class s51{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.1778531432-g3bd093"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await R30(Q,this.configService)}catch(Q){j.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 Fw extends T0{props;constructor(A){super();this.props=A}createState(){return new T0A}}class T0A extends _0{_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 k0A extends _0{controller=new O8;focusNode=new D6({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=P0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=l1.all(new i1(B.foreground,1,"solid")),X=new eB({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 r0({children:[new h0({decoration:{color:B.background},child:new p({text:new C(">",new v({color:B.foreground}))})}),new _1({child:X})]}),G=new h0({padding:K0.symmetric(1,0),child:new p({text:this.widget.props.title?new C(this.widget.props.title,new v({color:$.command,bold:!0})):new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new C("Enter",new v({color:$.keybind}))),V.push(new C(" to submit, ",new v({color:B.foreground,dim:!0})));V.push(new C("Esc",new v({color:$.keybind}))),V.push(new C(" to cancel",new v({color:B.foreground,dim:!0})));let U=new h0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,V)})});return new h0({decoration:{border:F,color:B.background},padding:K0.all(1),child:new y0({children:[G,new U0({height:1}),D,new Z5,U]})})}}class os extends T0{props;constructor(A){super();this.props=A}createState(){return new k0A}}PQ();class S0A extends _0{controller=new O8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new D6({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>=s9)return!1;let Q=await eF(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=P0.of(A),{colors:B,app:$}=Q,Y=A4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new eD({controller:this.controller,triggers:[new PJ],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 d4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new h0({constraints:new w1({maxHeight:Z}),padding:K0.symmetric(1,0),child:X}),G=new h0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=new h0({padding:K0.symmetric(1,0),child:new p({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new v({color:$.keybind})),new C(" again to clear input",new v({color:B.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new v({color:B.foreground,dim:!0})),new C("Enter",new v({color:$.keybind})),new C(" to submit, ",new v({color:B.foreground,dim:!0})),new C("Esc",new v({color:$.keybind})),new C(" to clear",new v({color:B.foreground,dim:!0}))])})}),U=[G,new U0({height:1}),new _1({child:D}),new U0({height:1}),V];return new h0({decoration:{border:l1.all(new i1(B.foreground,1,"solid")),color:B.background},padding:K0.all(1),child:new y0({children:U})})}}class t51 extends T0{props;constructor(A){super();this.props=A}createState(){return new S0A}}function v0A(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 e51 extends H1{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)=>v0A(J.pubDate).length));return new g6({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=P0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(z,W)=>new U0({width:W,child:r0.end([new p({text:new C(z,new v({color:K}))})])});return new h0({decoration:V?{color:V}:void 0,padding:K0.symmetric(2,0),child:new r0({children:[new _1({child:new p({text:new C(J.title,new v({color:U})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),E(v0A(J.pubDate),B)]})})}})}}class VB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!VB._instance)VB._instance=new VB;return VB._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()}}p0();class y0A extends _0{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){j.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){j.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=P0.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 g6({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 W=this.currentQuery.trim().toLowerCase();return new h0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C("",void 0,[new C("Create new label: ",new v({color:E})),new C(W,new v({color:E,bold:!0}))])})})}return new h0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C(D.name,new v({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 A31 extends T0{props;constructor(A){super();this.props=A}createState(){return new y0A}}class BG extends T0{props;constructor(A){super();this.props=A}createState(){return new x0A}}class x0A extends _0{_spinner=new H6;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=P0.of(A),{colors:B,app:$}=Q,J=l1.all(new i1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new p({textAlign:"center",text:new C("",void 0,[new C(Y,new v({color:$.processing})),new C(" ",void 0),new C(this.widget.props.message,new v({color:B.foreground}))])}),X=[new _1({child:new y0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new U0({height:2,child:new h0({padding:K0.symmetric(2,0),child:new p({text:new C("",new v({dim:!0}),[new C("Press ",new v({color:B.foreground})),new C("Esc",new v({color:B.info})),new C(" to cancel",new v({color:B.foreground}))])})})}));let D=new h0({decoration:new b4(B.background,J),child:new U0({width:60,height:7,child:new y0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new n4({debugLabel:"LoadingDialog",child:new d4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class rU extends T0{props;constructor(A){super();this.props=A}createState(){return new f0A}}class f0A extends _0{scrollController=new hA;scrollAreaKey=new Z2("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 x2}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=P0.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=TD0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=l1.all(new i1(Q.colors.border,1,"solid")),Z=new h0({padding:K0.symmetric(1,0),child:new p({text:new C($.title,new v({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new p({text:new C($.description,new v({color:Q.colors.foreground})),selectable:!0}),X=new _1({child:new Y3({child:new h0({padding:K0.symmetric(1,0),child:new r0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new vA({controller:this.scrollController,autofocus:!0,child:F})}),new G2({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 h0({padding:K0.symmetric(1,0),child:new p({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new v({color:Q.colors.foreground,dim:!0})),new C("R",new v({color:Q.app.keybind})),new C(" to retry, ",new v({color:Q.colors.foreground,dim:!0})),new C("Esc",new v({color:Q.app.keybind})),new C(" to cancel",new v({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new v({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new v({color:Q.app.keybind}),U=new v({color:Q.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",V),new C(" to close • Use ",U),new C("↑↓",V),new C(" or ",U),new C("j/k",V),new C(" to scroll",U)])}return new C("Press any key to close",new v({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new n4({debugLabel:"MessageDialog",child:new QA({fit:"expand",children:[new k1({onClick:()=>{},child:new U0}),new d4({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 h0({decoration:{border:Y,color:Q.colors.background},padding:K0.all(1),child:new y0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),X,D]})})})]})})}}L3();e1();class b0A extends T0{props;constructor(A){super();this.props=A}createState(){return new u0A}}class u0A extends _0{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=o0.file(this.widget.props.cwd),B=Z1.relativePath(Q,_A(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return v5(A)}statusIcon(A){let Q=m8.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=P0.of(A),{app:B}=Q;if(this.plugins.length===0)return new p({text:new C("No plugins found.",new v({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 C(`${Y}/${J} ${K4(J,"plugin")} active`,new v({bold:!0}))),Z>0||F>0)$.push(new C(` (${Z} ${K4(Z,"command")}, ${F} ${K4(F,"tool")})`,new v({dim:!0})));$.push(new C(`
7508
7508
 
7509
7509
  `));for(let X of this.plugins){let{icon:D,color:G}=this.statusIcon(X.status),V=this.getRelativePath(X.uri);if($.push(new C(`${D} `,new v({color:G}))),$.push(new C(V,new v({bold:!0}))),$.push(new C(` ${X.status}`,new v({dim:!0}))),$.push(new C(`
7510
7510
  `)),X.status==="active"&&X.registeredEvents.length>0)$.push(new C(" Events: ",new v({dim:!0}))),$.push(new C(X.registeredEvents.join(", "),new v({color:B.link}))),$.push(new C(`
@@ -7682,7 +7682,7 @@ ${s.content||""}`:s.content||"",f0=[],u0=s.baseDir.startsWith("file://")?rU0(s.b
7682
7682
  `)}function NAA(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=Z04({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),X=await DA.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+`
7683
7683
  `),process.exit(1)}process.stdout.write(await Xr5(X.result.displayText)+`
7684
7684
  `),process.exit(0)})}var T03=vt.join(y$,"logs","headless.log"),$91=vt.join(Px,"device-id.json"),k03=`cli-tui-${i3A(16).toString("hex")}`;async function S03(){for(let A of mM)try{if((await A.listConfigs()).length>0)return A}catch(Q){j.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => v4(kb(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){fJ.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
7685
- `)}function v03(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 h2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")FY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")FY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)FY("internal.model",f03(Q.model))}function g3A(A){let Q=A.indexOf(":");if(Q===-1)throw new Z4(`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 Z4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function y03(A){if(A===void 0)return;let Q=A.trim();if(ne1(Q))return Q;throw new Z4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function x03(A,Q){if(hX(A,Q))return;let B=p$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new Z4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function f03(A){if(!A.includes("="))return g3A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new Z4(`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 Z4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new Z4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);g3A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new Z4("No valid model overrides found in --model flag value.",1);return Q}function b03(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 u03(A){try{return await n3A(A,"utf-8")}catch{return A}}async function J91(A,Q,B){let $=b03(A,Q);if(!$)return;let J=mA(B)?B.features:[],Y=mA(B)?B.user.email:void 0;if(!pK0(J,x$.HARNESS_SYSTEM_PROMPT)&&!(Y&&_7(Y)))throw new Z4("You are not allowed to do this.",1);FY("systemPrompt",await u03($))}function pK0(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function h03(A){return A!=="pending"}function Mw(A){if(!mA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function g03(A){let Q=Mw(A);if(Q)return Q.id;if(uX(A))throw Error(A.error.message);throw Error("unreachable")}function m03(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 p03(A){let $=m03(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 Z4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function yt(A,Q){let B=rr0(Error(A.error.message));if(B.message===D7.networkOffline||B.message===D7.networkTimeout)return p03(Q);if(B.message!==D7.internalBug)return new Z4(B.message,1,B.suggestion);return new Z4(A.error.message.replace(/^Error: /,""),1)}async function d03(){if(process.versions.bun)return!1;try{return await DI()==="npm"}catch(A){return j.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var m3A=[{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??dF,description:`Custom settings file path (overrides the default location ${dF})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${la})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:Z9(),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:hM.SMART.key,description:`Set the agent mode (${g$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(g$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"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}],p3A=(A)=>("deprecated"in A)&&A.deprecated===!0,c03=(A)=>("hidden"in A)&&A.hidden===!0,l03=(A)=>("default"in A),i03=(A)=>("default"in A)?A.default:void 0;function hK0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=y03(Q.effort);if(B!==void 0)x03(Q.mode,B);return B}function n03(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 Z4(D7.unknownCommand(B),1,Z)}}async function dK0(A){return{...A,getThreadEnvironment:Iz,getEnvironmentData:(Q,B)=>YD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new LL(A.fileSystem),generateThreadTitle:ZF4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>jQ(A.configService),pluginService:A.pluginService}}function a3A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:Iz,getEnvironmentData:(Q,B)=>YD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var gK0=o0.file(_03.homedir()),Y91=process.env.XDG_CONFIG_HOME?o0.file(process.env.XDG_CONFIG_HOME):Z1.joinPath(gK0,".config");function a03(A){return yR4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(tF0())eF0();else DZ0(Q);let B=hj(),$=Ar();if((!B||$||kx())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(hD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(hD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(hj()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function c8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;ue1("0.0.1778518196-gcde0a1");let Y=v30({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(o0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:gK0,userConfigDir:Y91});xs4(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let c=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(c),j.info("API key lookup before login",{found:Boolean(c),ampURL:A.ampURL,deferAuth:$}),!c)if($)j.info("No API key found, continuing startup with deferred auth");else{G5.write(`No API key found. Starting login flow...
7685
+ `)}function v03(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 h2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")FY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")FY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)FY("internal.model",f03(Q.model))}function g3A(A){let Q=A.indexOf(":");if(Q===-1)throw new Z4(`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 Z4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function y03(A){if(A===void 0)return;let Q=A.trim();if(ne1(Q))return Q;throw new Z4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function x03(A,Q){if(hX(A,Q))return;let B=p$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new Z4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function f03(A){if(!A.includes("="))return g3A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new Z4(`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 Z4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new Z4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);g3A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new Z4("No valid model overrides found in --model flag value.",1);return Q}function b03(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 u03(A){try{return await n3A(A,"utf-8")}catch{return A}}async function J91(A,Q,B){let $=b03(A,Q);if(!$)return;let J=mA(B)?B.features:[],Y=mA(B)?B.user.email:void 0;if(!pK0(J,x$.HARNESS_SYSTEM_PROMPT)&&!(Y&&_7(Y)))throw new Z4("You are not allowed to do this.",1);FY("systemPrompt",await u03($))}function pK0(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function h03(A){return A!=="pending"}function Mw(A){if(!mA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function g03(A){let Q=Mw(A);if(Q)return Q.id;if(uX(A))throw Error(A.error.message);throw Error("unreachable")}function m03(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 p03(A){let $=m03(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 Z4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function yt(A,Q){let B=rr0(Error(A.error.message));if(B.message===D7.networkOffline||B.message===D7.networkTimeout)return p03(Q);if(B.message!==D7.internalBug)return new Z4(B.message,1,B.suggestion);return new Z4(A.error.message.replace(/^Error: /,""),1)}async function d03(){if(process.versions.bun)return!1;try{return await DI()==="npm"}catch(A){return j.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var m3A=[{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??dF,description:`Custom settings file path (overrides the default location ${dF})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${la})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:Z9(),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:hM.SMART.key,description:`Set the agent mode (${g$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(g$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"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}],p3A=(A)=>("deprecated"in A)&&A.deprecated===!0,c03=(A)=>("hidden"in A)&&A.hidden===!0,l03=(A)=>("default"in A),i03=(A)=>("default"in A)?A.default:void 0;function hK0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=y03(Q.effort);if(B!==void 0)x03(Q.mode,B);return B}function n03(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 Z4(D7.unknownCommand(B),1,Z)}}async function dK0(A){return{...A,getThreadEnvironment:Iz,getEnvironmentData:(Q,B)=>YD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new LL(A.fileSystem),generateThreadTitle:ZF4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>jQ(A.configService),pluginService:A.pluginService}}function a3A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:Iz,getEnvironmentData:(Q,B)=>YD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var gK0=o0.file(_03.homedir()),Y91=process.env.XDG_CONFIG_HOME?o0.file(process.env.XDG_CONFIG_HOME):Z1.joinPath(gK0,".config");function a03(A){return yR4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(tF0())eF0();else DZ0(Q);let B=hj(),$=Ar();if((!B||$||kx())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(hD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(hD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(hj()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function c8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;ue1("0.0.1778531432-g3bd093");let Y=v30({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(o0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:gK0,userConfigDir:Y91});xs4(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let c=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(c),j.info("API key lookup before login",{found:Boolean(c),ampURL:A.ampURL,deferAuth:$}),!c)if($)j.info("No API key found, continuing startup with deferred auth");else{G5.write(`No API key found. Starting login flow...
7686
7686
  `);let r=await o03(A),A0=await A.secrets.get("apiKey",A.ampURL);if(j.info("Login flow completed",{success:r,storedKeyPresent:Boolean(A0),ampURL:A.ampURL}),!r)await jz(),process.exit(1);F=!0}}{let c=await Y.getLatest(),r=c.settings.url,A0=c.secrets.isSet?.[r];j.info("Config secrets state after login",{configURL:r,apiKeySet:A0?.apiKey??!1})}let X=T1(jQ(Y).pipe(A5(h03))),D=$?"pending":await X;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:mA(D),isError:uX(D),errorMessage:uX(D)?D.error.message:void 0});let G=X.then((c)=>g03(c));G.catch(()=>{return});let V=!Q.takeMeBack&&mA(D)&&pK0(D.features,x$.THREAD_ACTORS_TUI),U=V?"all":process.env.PLUGINS??"permissions",{toolService:K,dispose:E}=_R4({configService:Y}),z=new Map,W=()=>z.clear(),H=new xf0(Y,A.settings.getWorkspaceRootPath()),q=xJ4({configService:Y,filesystem:R3}),N=L74({configService:Y,trustStore:H,skillMCPServers:q.skillMCPServers,uploadImageAttachments:V,createOAuthProvider:async(c,r,A0)=>{let w0=`${c}:${r}`,V0=z.get(w0);if(V0)return j.debug("Reusing existing OAuth provider for server",{serverName:c,serverUrl:r}),V0;j.debug("Creating OAuth provider for server",{serverName:c,serverUrl:r});let N0=(async()=>{let X0=new nM(A.secrets),j0=await X0.getClientInfo(c,r),Q0=A0?.scopes??j0?.scopes,I0=Sf4();j.info("OAuth headless mode check",{useHeadless:I0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:G5.isTTY});let n;if(I0)n=A.executeMode?kf4():Tf4(c);let a=new lS0({storage:X0,serverName:c,serverUrl:r,clientId:A0?.clientId??j0?.clientId,clientSecret:A0?.clientSecret??j0?.clientSecret,authUrl:A0?.authUrl??j0?.authUrl,tokenUrl:A0?.tokenUrl??j0?.tokenUrl,scopes:Q0,headlessAuthHandler:n});return j.debug("OAuth provider created",{serverName:c,serverUrl:r,hasManualClientId:!!(A0?.clientId??j0?.clientId),willUseDCR:!(A0?.clientId??j0?.clientId),scopes:Q0,headlessMode:I0,executeMode:A.executeMode}),a})();return z.set(w0,N0),N0}}),I=fn0({configService:Y,filesystem:R3,spawn:_Y0}),w=Q.headless?Ws4():void 0,O=w??new DV0({configService:Y}),L=O instanceof DV0?O:void 0;if(L)L.pluginExecutorKind="local";let P=new s1(null),S=ef0({configService:Y,fileSystem:R3,platform:O,loadGlobalPlugins:Rt0(Y),pluginFilter:U,activeThread$:P}),T=LQ4(S),x=[N,I,T],h;if(J)h=new Map;else if(A.executeMode){let c=await YO4({toolService:K,providers:x,initialTimeout:15000});h=c.registrations;for(let[r,A0]of c.initErrors)j.warn(`${r} provider initialization slow or failed:`,A0)}else h=bn0({toolService:K,providers:x});if(Q.jetbrains)xM("JetBrains");else if(Q.ide&&qb4())xM("VS Code");else if(Q.ide&&Nb4())xM("Neovim");else if(Q.ide){let c=await S03();if(c){let r=d30(c.ideName);if(r)xM(r)}}if(A.executeMode)he1(!0);let u,k=h3.status.pipe(N1((c)=>Boolean(c.connected&&c.authenticated&&c.ideName&&f04(c.ideName))),_4()).subscribe((c)=>{if(c){if(!u)u=K.registerTool(JO4)}else u?.dispose(),u=void 0}),f;if(!A.executeMode){let c=await A.settings.get("fuzzy.alwaysIncludePaths")??[];f=new oF0(process.cwd(),{alwaysIncludePaths:c},!0)}else f=new class extends oF0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let d=new th0(jl(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let l=new r61,g={configService:Y,toolService:K,mcpService:N,skillService:q,toolboxService:I,trustStore:H,threadService:d,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:f,fileSystem:R3,terminal:l,pluginService:S,pluginPlatform:L,headlessPluginPlatform:w,activeThread$:P,serverStatus:D,serverStatusPromise:X,viewerUserIDPromise:G,hasAPIKeyAtStartup:F};return{...g,async asyncDispose(){if(g.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await g.mcpService.waitForAuthentication();for(let c of h.values())c.dispose();await g.mcpService.dispose(),W(),await g.threadService.asyncDispose(),g.configService.unsubscribe(),E(),g.fuzzyServer.dispose(),g.settingsStorage[Symbol.dispose](),k.unsubscribe(),u?.dispose(),await g.pluginService.dispose()}}}async function o03(A){if(!A.executeMode){if(!await hX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return G5.write(`Login cancelled. Run the command again to retry.
7687
7687
  `),!1}return await o3A(A)}async function o3A(A){let Q=i3A(32).toString("hex"),B=await gx(A.ampURL,Q),$=new AbortController;try{await xX(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await gx(A.ampURL,Q,!1);G5.write(`If your browser does not open automatically, visit:
7688
7688
 
@@ -7690,7 +7690,7 @@ ${n0.blue.bold(J)}
7690
7690
 
7691
7691
  `);try{return await fh4(A.ampURL,Q,A.secrets,$),G5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return j.error("Login failed",{error:Y}),fJ.write(`
7692
7692
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
7693
- `),!1}}async function r03(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new Z4("No Amp API key found. Run `amp login` first.",1);let J=j03("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(F)=>Y(F??1))})}function s03(A){let Q=new mN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)Hj(),process.exit(0);let H=W.originalError??W;Ev4(H)}),cg4(Q,{version:"0.0.1778518196-gcde0a1",buildTimestamp:"2026-05-11T16:53:36.885Z",buildType:"'release'"}),Q.addHelpText("after",zb4()),Q.configureHelp({formatHelp:Wb4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await i5(q);await Z13(N)}),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(W,H)=>{let q=H.optsWithGlobals(),N=await i5(q);await Y13(N,await ht0(q,N.settings))}),Vv4(Q,i5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...W)=>{let H=W.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=W.filter((w)=>w!==H).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=H.optsWithGlobals(),I=await i5(N);await r03(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(W,H,q)=>{let N=q.optsWithGlobals(),I=await i5(N);await Cf4(W??"get",I.ampURL,I.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(W,H)=>{let q=H.optsWithGlobals(),N=await i5(q);await Mf4(N.ampURL,N.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(W)=>{await xu4({raw:W.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(`
7693
+ `),!1}}async function r03(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new Z4("No Amp API key found. Run `amp login` first.",1);let J=j03("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(F)=>Y(F??1))})}function s03(A){let Q=new mN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)Hj(),process.exit(0);let H=W.originalError??W;Ev4(H)}),cg4(Q,{version:"0.0.1778531432-g3bd093",buildTimestamp:"2026-05-11T20:34:42.741Z",buildType:"'release'"}),Q.addHelpText("after",zb4()),Q.configureHelp({formatHelp:Wb4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await i5(q);await Z13(N)}),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(W,H)=>{let q=H.optsWithGlobals(),N=await i5(q);await Y13(N,await ht0(q,N.settings))}),Vv4(Q,i5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...W)=>{let H=W.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=W.filter((w)=>w!==H).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=H.optsWithGlobals(),I=await i5(N);await r03(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(W,H,q)=>{let N=q.optsWithGlobals(),I=await i5(N);await Cf4(W??"get",I.ampURL,I.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(W,H)=>{let q=H.optsWithGlobals(),N=await i5(q);await Mf4(N.ampURL,N.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(W)=>{await xu4({raw:W.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(`
7694
7694
  `)).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(W,H,q)=>{if(W&&H.apply)throw new Z4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let N=H.apply??W;if(!N||N.trim().length===0)G5.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.
7695
7695
 
7696
7696
  `),q.outputHelp(),process.exit(0);let I=M2(N)??zJ(N),w=q.optsWithGlobals(),O=await i5(w);h2(q,w);let L=await c8(O,w),P=!1;try{if(H.checkout&&H.skipCheckout)throw new Z4("Choose either --checkout or --skip-checkout, not both.",1);if(uX(L.serverStatus))throw yt(L.serverStatus,O.ampURL);let S=mA(L.serverStatus)?L.serverStatus.features:void 0;if(!pK0(S,x$.V2))throw new Z4("live-sync is not enabled for your user",1);await Oh4({ampURL:O.ampURL,threadId:I,configService:L.configService,threadService:L.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:hX0}),P=!0}finally{if(await L.asyncDispose(),P)process.exit(0)}});let J=async(W,H,q)=>{v30({storage:H.settings,secretStorage:H.secrets,workspaceRoot:g0.of(o0.file(process.cwd())),defaultAmpURL:H.ampURL,homeDir:gK0,userConfigDir:Y91});let N={...H,executeMode:!1};await mK0(N,{...W,openThreadSwitcher:!0},q,A)},Y=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(W,H)=>{let q=H.optsWithGlobals(),N=await i5(q);await l3A(q,N,H)});Y.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await i5(q);await H13(q,N,H)}),Y.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(W,H,q)=>{let N=q.optsWithGlobals(),I=await i5(N);if(H.pick)fJ.write(`${n0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -7723,8 +7723,8 @@ ${O}
7723
7723
  `))}),H.args.length>0)n03(N,H);await mK0(N,q,H,A)}),sb4(Q),Q}async function Sb(A,Q){await NJ((B)=>cX0(B,A,Q))}async function d3A(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([DA.getThreadLinkInfo({thread:A},{config:Q}),B]);if(j.getChild("fetchAndStartThread").info(`Ownership check in ${Date.now()-$}ms`),J.ok){let Z=J.result.creatorUserID;if(Z&&Z!==Y&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new Z4(`Cannot resume thread created by another user.
7724
7724
 
7725
7725
  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 r3A(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await VV0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await VV0()).trimEnd(),stdinInput:null}}function s3A(A,Q,B){if(A.streamJson&&!Q)throw new Z4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new Z4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new Z4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new Z4("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 Z4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new Z4("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 Z4("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 Z4("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"
7726
- Or pipe via stdin: echo "your message" | amp --execute`)}function t03(A,Q){if(MA4([c50.parse({tool:"*",action:"allow"})]),e44({bypass:!0}),Ns4(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:l61})}async function mK0(A,Q,B,$){if(Q.headless)return e03(A,Q,B);let J=await c8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),F=mA(Y)&&pK0(Y.features,x$.THREAD_ACTORS_TUI),X=F&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await J.asyncDispose(),new Z4("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!F)throw await J.asyncDispose(),new Z4("--show-welcome is only available with the new Amp CLI feature flag",1);if(X){let D=!A.executeMode&&await d03();return t03(Z,J.pluginService),A13(A,Q,B,J,{showNpmMigrationWelcome:D})}else{if(Q.threadId&&MQ(Q.threadId)){let D=await DA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new Z4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return Q13(A,Q,B,$,{dependencies:J})}}async function e03(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=mr0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};h2(B,Q);let J=process.hrtime.bigint(),Y=await c8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(uX(Z))throw yt(Z,A.ampURL);let F=mA(Z)?Z:null,X=F?.user.email;await J91(B,Q,Z);let D=Mw(Z),G=rx(Q,D);if(G instanceof Error)O5(G.message);if(F&&!Jk(Q.mode,X))throw new Z4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!X||!_7(X)))throw new Z4("Headless executor mode is only available for Amp employees",1);UF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new Z4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!MQ(K))throw new Z4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await z13({dependencies:Y,apiKey:U,visibility:G??void 0}),z=K??E?.threadId;if(!z)throw new Z4("Failed to resolve headless thread ID",1);let W=await ff4(z);if(W.status==="already-running")await Y.asyncDispose(),await jz(),process.exit(0);try{await Rf4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:z,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await jz(),process.exit(0)}async function A13(A,Q,B,$,J){let{userInput:Y,stdinInput:Z}=await r3A(Q),F=!!Q.streamJson||!!Q.streamJsonThinking;s3A({...Q,streamJson:F},A.executeMode,Y),h2(B,Q),Jv4(),UF0();let X=Q.threadId&&MQ(Q.threadId)?Q.threadId:void 0,D=Q.observe?M2(Q.observe)??zJ(Q.observe):void 0,G=await $.serverStatusPromise;if(uX(G))throw yt(G,A.ampURL);let V=Mw(G),U=rx(Q,V);if(U instanceof Error)O5(U.message);let K=null,E=()=>{return K??=(async()=>{let H=await ia(A.settings,process.cwd(),V,U);if(H instanceof Error)O5(H.message);return H})(),K},z=await $.secretStorage.get("apiKey",A.ampURL);if(!z)throw new Z4("API key required. Please run `amp login` first.",1);let W=mA(G)&&_7(G.user.email);if(A.executeMode){me0($.mcpService,A.settings);try{let H=hK0(B,Q),q=await II(),N=X?H:gX0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),I=X?void 0:mX0(await mx($.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),w=X?void 0:await E(),O=await Af4({apiKey:z,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:Y,stdinInput:Z,stats:!!Q.stats,streamJson:F,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:X,initialThreadMeta:w?wJ(w):void 0,initialSettings:I});if(await Sb(O,"execute"),Q.archive)await $.threadService.archive(O,!0)}finally{await $.asyncDispose()}await jz(),process.exit(0)}else{let H=hK0(B,Q),q=J.showNpmMigrationWelcome?"npm-migration":"intro",N=jl($.configService),I=new rs($.fuzzyServer),w=process.cwd();await Ds4({ampURL:A.ampURL,apiKey:z,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??gF(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:O})=>Nx({fileSystem:$.fileSystem,workspaceRoot:w},O),completionBuilder:I,workspaceRoot:w,listThreads:()=>N.listThreads(),getThreadFromServer:(O)=>N.getThread(O),toolboxes:$.toolboxService.toolboxes,isInternalUser:W,settingsFilePath:$.settingsStorage.getSettingsFilePath(),setActiveThreadID:(O)=>$.activeThread$.next(O)},{initialThreadID:D??X,initialUserInput:Y||void 0,getDefaultNewThreadVisibility:E,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!D,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function Q13(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(X0,j0)=>{let Q0=Number(process.hrtime.bigint()-j0)/1e6,I0=mr0();j.info("Startup phase",{phase:X0,phaseMs:Math.round(Q0),sinceMainMs:I0===null?void 0:Math.round(I0)})},{userInput:F,stdinInput:X}=await r3A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;s3A({...Q,streamJson:D},A.executeMode,F),h2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await c8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&uX(E))throw yt(E,A.ampURL);let z=mA(E)?E:null,W=z?.user.email,H=!!(W&&_7(W));if(H)UF0();if(!K)await J91(B,Q,E);let q=Mw(E),N=q?.features??[],I=q?.team??null,w=rx(Q,q);if(w instanceof Error)O5(w.message);if(z&&!Jk(Q.mode,W))throw new Z4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&MQ(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let L=await dK0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(X0)=>Sb(X0,"interactive"),S={threadService:V.threadService,workerDeps:L,createThread:async(X0)=>{let j0=K?await V.serverStatusPromise:E,Q0=await ia(A.settings,process.cwd(),Mw(j0),w);if(Q0 instanceof Error)O5(Q0.message);return T81(L,{threadMeta:Q0?wJ(Q0):void 0,agentMode:X0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(X0,j0)=>{if(j0?.nonBlockingOwnershipCheck){d3A(X0,V.configService,V.viewerUserIDPromise).catch((Q0)=>{if(Q0 instanceof Z4){if(j0.onOwnershipError){j0.onOwnershipError(Q0,X0);return}Rz(Q0,X0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await d3A(X0,V.configService,V.viewerUserIDPromise)}catch(Q0){if(Q0 instanceof Z4)throw Q0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:Rz},T=async()=>{try{return zAA(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(X0){if(X0 instanceof Z4)throw X0;throw await Rz(X0,Q.threadId),Error("handleError should have called process.exit()")}},x=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let X0=await V.configService.getLatest(),j0=fm(X0),Q0=await DA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(j0)});if(Q0.ok)return j.info("User free tier status:",Q0),Q0.result;return}catch(X0){j.error("Failed to fetch free tier status:",X0);return}})(),u=!A.executeMode?new Q51:null,k,f=null;if(u)k=u,f=(async()=>{let X0=K?await V.serverStatusPromise:V.serverStatus;if(uX(X0))throw yt(X0,A.ampURL);await J91(B,Q,X0);let j0=process.hrtime.bigint(),Q0=await T();if(Z("runMainThread:createThreadPool",j0),u.attach(Q0),F){let I0=await T1(Q0.threadHandles$);if(!I0)throw new Z4("No active thread is available yet.",1);await I0.sendMessage({content:[{type:"text",text:F}]})}})(),f.catch(async(X0)=>{let j0=X0 instanceof Error?X0:Error(String(X0));u.setInitError(j0),await Rz(X0,Q.threadId)});else G=process.hrtime.bigint(),k=await T(),Z("runMainThread:createThreadPool",G);let d=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let l=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),a03({configService:V.configService,threadService:V.threadService,config:l,useNotificationsForService:d,threadViewStates$:()=>k.threadHandles$.pipe(h4((X0)=>{if(!X0)return g0.of({});return P6(X0.thread$,X0.threadViewState$).pipe(N1(([j0,Q0])=>({[j0.id]:Q0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){me0(V.mcpService,A.settings);let X0=hK0(B,Q),j0=await II(),Q0=O?X0:gX0({agentMode:Q.mode,explicitEffort:X0,sessionState:j0}),I0={userInput:F,stdinInput:X,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,reasoningEffort:Q0,labels:Q.label},n=await xv4({threadPool:k,...I0});if(await Sb(n,"execute"),Q.archive)await V.threadService.archive(n,!0);await V.asyncDispose(),process.exit(0)}let g=!1,c=!1;if(Q.jetbrains||Q.ide){await c30();let X0=await mX({jetbrainsOnly:Q.jetbrains});if(X0.length===0){if(Q.jetbrains)g=!await V.configService.get("jetbrains.skipInstall")}else if(X0.length===1){let j0=X0[0];if(j0)h3.selectConfig(j0)}else c=!0}G=process.hrtime.bigint();let r=Fe0("0.0.1778518196-gcde0a1",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let A0=new pe0(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),F&&A.executeMode){let X0=await T1(k.threadHandles$);if(!X0)throw new Z4("No active thread is available yet.",1);await X0.sendMessage({content:[{type:"text",text:F}]})}G=process.hrtime.bigint();let w0=await II();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let V0=hK0(B,Q),N0={...w0,launchCount:w0.launchCount+1,lastReasoningEffortByMode:V0?{...w0.lastReasoningEffortByMode,[Q.mode]:V0}:w0.lastReasoningEffortByMode};NJ((X0)=>({...X0,launchCount:X0.launchCount+1}));try{if(G=process.hrtime.bigint(),await _t4({history:new Go,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:DA,threadPool:k,createSystemPromptDeps:async()=>a3A(V),ideClient:h3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:A0,updateService:r,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:g,showIdePickerHint:c,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:k03,logFile:{path:$},sessionState:N0,freeTierStatusPromise:x,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-11T16:53:36.885Z"},(X0)=>new X51({...X0,threadPool:X0.threadPool},(j0)=>new P81({...j0,threadState:j0.threadState}))),Z("runMainThread:mountApp-returned",G),f)await f}finally{await k.dispose().catch((X0)=>{j.error("Failed to dispose thread pool during shutdown",X0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function i5(A){if(j.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)fJ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7727
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await _74({get:async(F)=>{if(F!==hd)return;try{let X=await n3A($91,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==hd)return;await R03(vt.dirname($91),{recursive:!0}),await P03($91,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:W90()});ge1($);let J=await sf4({...A,workspaceTrust:{current:!0,changes:pT0},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 ih4(A.mcpConfig);J=nh4(J,F)}let Y=vt.dirname(J.getSettingsFilePath());vR4(Px,Y),J=qs1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=T7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!vH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:ks4(await ht0(A,J))}}function B13(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 $13(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=vt.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?T03:la));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function J13(){tS4();let A=B13(process.argv),Q=$13(process.argv,A),B=Yv4(Q);fZ0("silent");let $=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(v03(j),j.info("Starting Amp CLI.",{version:"0.0.1778518196-gcde0a1",buildTimestamp:"2026-05-11T16:53:36.885Z"}),process.platform==="win32"&&Rj())ub4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new Z4(D7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await s03(B).parseAsync(process.argv)}kR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await J13().catch(Rz)});async function Y13(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"),G5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7726
+ Or pipe via stdin: echo "your message" | amp --execute`)}function t03(A,Q){if(MA4([c50.parse({tool:"*",action:"allow"})]),e44({bypass:!0}),Ns4(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:l61})}async function mK0(A,Q,B,$){if(Q.headless)return e03(A,Q,B);let J=await c8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),F=mA(Y)&&pK0(Y.features,x$.THREAD_ACTORS_TUI),X=F&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await J.asyncDispose(),new Z4("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!F)throw await J.asyncDispose(),new Z4("--show-welcome is only available with the new Amp CLI feature flag",1);if(X){let D=!A.executeMode&&await d03();return t03(Z,J.pluginService),A13(A,Q,B,J,{showNpmMigrationWelcome:D})}else{if(Q.threadId&&MQ(Q.threadId)){let D=await DA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new Z4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return Q13(A,Q,B,$,{dependencies:J})}}async function e03(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=mr0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};h2(B,Q);let J=process.hrtime.bigint(),Y=await c8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(uX(Z))throw yt(Z,A.ampURL);let F=mA(Z)?Z:null,X=F?.user.email;await J91(B,Q,Z);let D=Mw(Z),G=rx(Q,D);if(G instanceof Error)O5(G.message);if(F&&!Jk(Q.mode,X))throw new Z4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!X||!_7(X)))throw new Z4("Headless executor mode is only available for Amp employees",1);UF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new Z4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!MQ(K))throw new Z4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await z13({dependencies:Y,apiKey:U,visibility:G??void 0}),z=K??E?.threadId;if(!z)throw new Z4("Failed to resolve headless thread ID",1);let W=await ff4(z);if(W.status==="already-running")await Y.asyncDispose(),await jz(),process.exit(0);try{await Rf4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:z,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await jz(),process.exit(0)}async function A13(A,Q,B,$,J){let{userInput:Y,stdinInput:Z}=await r3A(Q),F=!!Q.streamJson||!!Q.streamJsonThinking;s3A({...Q,streamJson:F},A.executeMode,Y),h2(B,Q),Jv4(),UF0();let X=Q.threadId&&MQ(Q.threadId)?Q.threadId:void 0,D=Q.observe?M2(Q.observe)??zJ(Q.observe):void 0,G=await $.serverStatusPromise;if(uX(G))throw yt(G,A.ampURL);let V=Mw(G),U=rx(Q,V);if(U instanceof Error)O5(U.message);let K=null,E=()=>{return K??=(async()=>{let H=await ia(A.settings,process.cwd(),V,U);if(H instanceof Error)O5(H.message);return H})(),K},z=await $.secretStorage.get("apiKey",A.ampURL);if(!z)throw new Z4("API key required. Please run `amp login` first.",1);let W=mA(G)&&_7(G.user.email);if(A.executeMode){me0($.mcpService,A.settings);try{let H=hK0(B,Q),q=await II(),N=X?H:gX0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),I=X?void 0:mX0(await mx($.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),w=X?void 0:await E(),O=await Af4({apiKey:z,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:Y,stdinInput:Z,stats:!!Q.stats,streamJson:F,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:X,initialThreadMeta:w?wJ(w):void 0,initialSettings:I});if(await Sb(O,"execute"),Q.archive)await $.threadService.archive(O,!0)}finally{await $.asyncDispose()}await jz(),process.exit(0)}else{let H=hK0(B,Q),q=J.showNpmMigrationWelcome?"npm-migration":"intro",N=jl($.configService),I=new rs($.fuzzyServer),w=process.cwd();await Ds4({ampURL:A.ampURL,apiKey:z,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??gF(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:O})=>Nx({fileSystem:$.fileSystem,workspaceRoot:w},O),completionBuilder:I,workspaceRoot:w,listThreads:()=>N.listThreads(),getThreadFromServer:(O)=>N.getThread(O),toolboxes:$.toolboxService.toolboxes,isInternalUser:W,settingsFilePath:$.settingsStorage.getSettingsFilePath(),setActiveThreadID:(O)=>$.activeThread$.next(O)},{initialThreadID:D??X,initialUserInput:Y||void 0,getDefaultNewThreadVisibility:E,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!D,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function Q13(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(X0,j0)=>{let Q0=Number(process.hrtime.bigint()-j0)/1e6,I0=mr0();j.info("Startup phase",{phase:X0,phaseMs:Math.round(Q0),sinceMainMs:I0===null?void 0:Math.round(I0)})},{userInput:F,stdinInput:X}=await r3A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;s3A({...Q,streamJson:D},A.executeMode,F),h2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await c8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&uX(E))throw yt(E,A.ampURL);let z=mA(E)?E:null,W=z?.user.email,H=!!(W&&_7(W));if(H)UF0();if(!K)await J91(B,Q,E);let q=Mw(E),N=q?.features??[],I=q?.team??null,w=rx(Q,q);if(w instanceof Error)O5(w.message);if(z&&!Jk(Q.mode,W))throw new Z4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&MQ(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let L=await dK0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(X0)=>Sb(X0,"interactive"),S={threadService:V.threadService,workerDeps:L,createThread:async(X0)=>{let j0=K?await V.serverStatusPromise:E,Q0=await ia(A.settings,process.cwd(),Mw(j0),w);if(Q0 instanceof Error)O5(Q0.message);return T81(L,{threadMeta:Q0?wJ(Q0):void 0,agentMode:X0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(X0,j0)=>{if(j0?.nonBlockingOwnershipCheck){d3A(X0,V.configService,V.viewerUserIDPromise).catch((Q0)=>{if(Q0 instanceof Z4){if(j0.onOwnershipError){j0.onOwnershipError(Q0,X0);return}Rz(Q0,X0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await d3A(X0,V.configService,V.viewerUserIDPromise)}catch(Q0){if(Q0 instanceof Z4)throw Q0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:Rz},T=async()=>{try{return zAA(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(X0){if(X0 instanceof Z4)throw X0;throw await Rz(X0,Q.threadId),Error("handleError should have called process.exit()")}},x=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let X0=await V.configService.getLatest(),j0=fm(X0),Q0=await DA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(j0)});if(Q0.ok)return j.info("User free tier status:",Q0),Q0.result;return}catch(X0){j.error("Failed to fetch free tier status:",X0);return}})(),u=!A.executeMode?new Q51:null,k,f=null;if(u)k=u,f=(async()=>{let X0=K?await V.serverStatusPromise:V.serverStatus;if(uX(X0))throw yt(X0,A.ampURL);await J91(B,Q,X0);let j0=process.hrtime.bigint(),Q0=await T();if(Z("runMainThread:createThreadPool",j0),u.attach(Q0),F){let I0=await T1(Q0.threadHandles$);if(!I0)throw new Z4("No active thread is available yet.",1);await I0.sendMessage({content:[{type:"text",text:F}]})}})(),f.catch(async(X0)=>{let j0=X0 instanceof Error?X0:Error(String(X0));u.setInitError(j0),await Rz(X0,Q.threadId)});else G=process.hrtime.bigint(),k=await T(),Z("runMainThread:createThreadPool",G);let d=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let l=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),a03({configService:V.configService,threadService:V.threadService,config:l,useNotificationsForService:d,threadViewStates$:()=>k.threadHandles$.pipe(h4((X0)=>{if(!X0)return g0.of({});return P6(X0.thread$,X0.threadViewState$).pipe(N1(([j0,Q0])=>({[j0.id]:Q0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){me0(V.mcpService,A.settings);let X0=hK0(B,Q),j0=await II(),Q0=O?X0:gX0({agentMode:Q.mode,explicitEffort:X0,sessionState:j0}),I0={userInput:F,stdinInput:X,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,reasoningEffort:Q0,labels:Q.label},n=await xv4({threadPool:k,...I0});if(await Sb(n,"execute"),Q.archive)await V.threadService.archive(n,!0);await V.asyncDispose(),process.exit(0)}let g=!1,c=!1;if(Q.jetbrains||Q.ide){await c30();let X0=await mX({jetbrainsOnly:Q.jetbrains});if(X0.length===0){if(Q.jetbrains)g=!await V.configService.get("jetbrains.skipInstall")}else if(X0.length===1){let j0=X0[0];if(j0)h3.selectConfig(j0)}else c=!0}G=process.hrtime.bigint();let r=Fe0("0.0.1778531432-g3bd093",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let A0=new pe0(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),F&&A.executeMode){let X0=await T1(k.threadHandles$);if(!X0)throw new Z4("No active thread is available yet.",1);await X0.sendMessage({content:[{type:"text",text:F}]})}G=process.hrtime.bigint();let w0=await II();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let V0=hK0(B,Q),N0={...w0,launchCount:w0.launchCount+1,lastReasoningEffortByMode:V0?{...w0.lastReasoningEffortByMode,[Q.mode]:V0}:w0.lastReasoningEffortByMode};NJ((X0)=>({...X0,launchCount:X0.launchCount+1}));try{if(G=process.hrtime.bigint(),await _t4({history:new Go,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:DA,threadPool:k,createSystemPromptDeps:async()=>a3A(V),ideClient:h3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:A0,updateService:r,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:g,showIdePickerHint:c,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:k03,logFile:{path:$},sessionState:N0,freeTierStatusPromise:x,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-11T20:34:42.741Z"},(X0)=>new X51({...X0,threadPool:X0.threadPool},(j0)=>new P81({...j0,threadState:j0.threadState}))),Z("runMainThread:mountApp-returned",G),f)await f}finally{await k.dispose().catch((X0)=>{j.error("Failed to dispose thread pool during shutdown",X0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function i5(A){if(j.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)fJ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7727
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await _74({get:async(F)=>{if(F!==hd)return;try{let X=await n3A($91,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==hd)return;await R03(vt.dirname($91),{recursive:!0}),await P03($91,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:W90()});ge1($);let J=await sf4({...A,workspaceTrust:{current:!0,changes:pT0},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 ih4(A.mcpConfig);J=nh4(J,F)}let Y=vt.dirname(J.getSettingsFilePath());vR4(Px,Y),J=qs1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=T7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!vH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:ks4(await ht0(A,J))}}function B13(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 $13(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=vt.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?T03:la));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function J13(){tS4();let A=B13(process.argv),Q=$13(process.argv,A),B=Yv4(Q);fZ0("silent");let $=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(v03(j),j.info("Starting Amp CLI.",{version:"0.0.1778531432-g3bd093",buildTimestamp:"2026-05-11T20:34:42.741Z"}),process.platform==="win32"&&Rj())ub4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new Z4(D7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await s03(B).parseAsync(process.argv)}kR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await J13().catch(Rz)});async function Y13(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"),G5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7728
7728
  `);else if(!vH(A.ampURL))G5.write(`Logging in to ${new URL(A.ampURL).hostname}
7729
7729
  `);let $=process.env.AMP_API_KEY;if($)G5.write(`API key found in environment variable, storing...
7730
7730
  `),await Q.set("apiKey",$,A.ampURL),G5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1778518196-gcde0a1",
3
+ "version": "0.0.1778531432-g3bd093",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {