@sourcegraph/amp 0.0.1777144048-gff4795 → 0.0.1777147716-gff4795

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +9 -9
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4640,12 +4640,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,X(Error(`Failed to spawn brew: ${K.message}`))}
4640
4640
  ${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))W+=`
4641
4641
 
4642
4642
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4643
- npm install -g @sourcegraph/amp`;X(Error(W))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}l0();l0();EI();async function lU0(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=Be(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],W=X.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return T.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 T.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 iU0(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=Be(A,J),Z=Y<0;return T.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return T.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Ei5=604800000;function Ts4(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>Ei5)return{ageMs:B};return null}function Be(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 M81(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?yU(B):void 0;return{sha:$,age:J}}catch{return null}}O1();l0();import{readFile as Wi5,realpath as Hi5}from"node:fs/promises";import{homedir as zi5}from"node:os";import{dirname as Ss4,join as L81}from"node:path";async function ks4(A){switch(A){case"binary":case"brew":return qi5(tt());case"npm":case"pnpm":case"yarn":case"bun":return Ni5();case"bootstrap":return Ii5()}}async function qi5(A){let Q=await PG(A,["--version"],5000);if(Q.reason!=="success")return T.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Ni5(){try{let A=process.argv[1];if(!A)return null;let Q=await Hi5(A),B=Ss4(Ss4(Q));return await vs4(L81(B,"package.json"))}catch(A){return T.debug("failed to read installed version from package.json",{error:A}),null}}async function Ii5(){try{let A=process.env.AMP_HOME??L81(zi5(),".amp");return await vs4(L81(A,"package","package.json"))}catch(A){return T.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function vs4(A){let Q=await Wi5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return T.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Ci5=3600000,wi5=5000;function O81(A,Q,B={}){let $=new HA,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Ci5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=new VD().scoped("update");if(Y>0){if(await vU(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 vU(wi5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let W=Math.min(K,E);await vU(W),E-=W}}}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 dU0(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await iU0(A);else{let V=await HP();X=await lU0(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 ks4(Z);if(V&&Be(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Be(A,V)<0){let U=await xH(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!==tt()){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 Qe(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await xH(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}}EI();import{stderr as _G}from"node:process";function ys4(A){let Q=new uI().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 V81($.force||!1,$.verbose||!1,"0.0.1777144048-gff4795"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new uI("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 Oi5($.targetVersion)});A.addCommand(B)}function Li5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4643
+ npm install -g @sourcegraph/amp`;X(Error(W))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}l0();l0();EI();async function lU0(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=Be(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],W=X.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return T.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 T.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 iU0(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=Be(A,J),Z=Y<0;return T.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return T.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Ei5=604800000;function Ts4(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>Ei5)return{ageMs:B};return null}function Be(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 M81(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?yU(B):void 0;return{sha:$,age:J}}catch{return null}}O1();l0();import{readFile as Wi5,realpath as Hi5}from"node:fs/promises";import{homedir as zi5}from"node:os";import{dirname as Ss4,join as L81}from"node:path";async function ks4(A){switch(A){case"binary":case"brew":return qi5(tt());case"npm":case"pnpm":case"yarn":case"bun":return Ni5();case"bootstrap":return Ii5()}}async function qi5(A){let Q=await PG(A,["--version"],5000);if(Q.reason!=="success")return T.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Ni5(){try{let A=process.argv[1];if(!A)return null;let Q=await Hi5(A),B=Ss4(Ss4(Q));return await vs4(L81(B,"package.json"))}catch(A){return T.debug("failed to read installed version from package.json",{error:A}),null}}async function Ii5(){try{let A=process.env.AMP_HOME??L81(zi5(),".amp");return await vs4(L81(A,"package","package.json"))}catch(A){return T.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function vs4(A){let Q=await Wi5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return T.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Ci5=3600000,wi5=5000;function O81(A,Q,B={}){let $=new HA,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Ci5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=new VD().scoped("update");if(Y>0){if(await vU(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 vU(wi5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let W=Math.min(K,E);await vU(W),E-=W}}}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 dU0(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await iU0(A);else{let V=await HP();X=await lU0(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 ks4(Z);if(V&&Be(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Be(A,V)<0){let U=await xH(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!==tt()){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 Qe(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await xH(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}}EI();import{stderr as _G}from"node:process";function ys4(A){let Q=new uI().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 V81($.force||!1,$.verbose||!1,"0.0.1777147716-gff4795"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new uI("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 Oi5($.targetVersion)});A.addCommand(B)}function Li5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4644
4644
  `),$=!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 Oi5(A){let B=process.platform==="win32"&&WP()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=Li5(_G);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")_G.write(n0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4645
4645
 
4646
4646
  `));try{if(!A){_G.write(n0.blue(`Checking for updates...
4647
- `));let F=!1,X;if(WP()){let D=await iU0("0.0.1777144048-gff4795");F=D.hasUpdate,X=D.latestVersion}else{let D=await HP(),G=await lU0("0.0.1777144048-gff4795",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=M81("0.0.1777144048-gff4795"),G=D?.age?`released ${D.age} ago`:`built ${yU(new Date("2026-04-25T19:11:23.482Z"))} ago`;_G.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1777144048-gff4795"} (${G})
4648
- `));let V=await xH("0.0.1777144048-gff4795",B);if(V.warning)_G.write(`
4647
+ `));let F=!1,X;if(WP()){let D=await iU0("0.0.1777147716-gff4795");F=D.hasUpdate,X=D.latestVersion}else{let D=await HP(),G=await lU0("0.0.1777147716-gff4795",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=M81("0.0.1777147716-gff4795"),G=D?.age?`released ${D.age} ago`:`built ${yU(new Date("2026-04-25T20:12:25.387Z"))} ago`;_G.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1777147716-gff4795"} (${G})
4648
+ `));let V=await xH("0.0.1777147716-gff4795",B);if(V.warning)_G.write(`
4649
4649
  `+n0.yellow(V.warning)+`
4650
4650
  `);process.exit(0)}if(!X)_G.write(n0.yellow("[WARN] could not find latest version")),process.exit(0);A=X}_G.write(n0.blue(`Updating to version ${A}...
4651
4651
  `)),await Qe(A,void 0,(F)=>{$(),_G.write(n0.dim(`Running: ${F}
@@ -5156,7 +5156,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let x=D.text.replace(/`([^`]+)`/g,"$1")+`
5156
5156
 
5157
5157
  `,new h({color:$.toolSuccess,bold:!0})),new O(`This thread has been shared with Amp support for debugging and bug prioritization.
5158
5158
  `,new h({color:B.foreground})),new O(`This is not a support request.
5159
- `,new h({color:B.foreground,dim:!0})),new O("If you need a reply, post on X @AmpCode or email amp-devs@ampcode.com.",new h({color:B.foreground,dim:!0}))]),textAlign:"center"})})}}function H9A(A){return new D3({header:A.title,minWidth:80,maxWidth:80,chromePadding:M0.symmetric(1,0),footer:"none",onDismiss:A.onDismiss,child:A.child})}function y78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,12),child:new eH({commandName:"Share with Support",title:"Share Thread with Support",placeholder:"What went wrong? (Need a reply? Email amp-devs@ampcode.com.)",isRequiredArg:!1,onSubmit:async($)=>{try{await A.shareThreadWithSupport(Q,$||void 0),B.pushResultPane(H9A({title:"Shared with Support",onDismiss:B.dismissFlow,child:new A10}))}catch(J){T.error("Failed to share thread with support",{error:J,threadID:Q}),B.pushResultPane(H9A({title:"Share with Support failed",onDismiss:B.dismissFlow,child:new t({text:new O(`Failed to share thread with support: ${J instanceof Error?J.message:String(J)}`)})}))}},onDismiss:B.dismissFlow})})})}function z9A(A,Q){return{noun:"thread",verb:"share with support",description:"Share with Amp support for debugging",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;B.push(y78(A,Y,{dismissFlow:J,pushResultPane:(Z)=>B.push(Z)}))}}}class Q10 extends y0{props;constructor(A){super();this.props=A}createState(){return new q9A}}class q9A extends v0{result=void 0;isLoading=!1;build(A){let Q=[];if(this.isLoading)Q.push(new fQ({message:"Updating visibility..."}));else if(this.result!==void 0)Q.push(new l7({message:this.result,onDismiss:()=>{this.widget.props.onDismiss()}}));else{let B=["private","workspace","unlisted","public"],$=this.widget.props.workspace?.groups&&this.widget.props.workspace.groups.length>0?["private","workspace","group","unlisted","public"]:B;Q.push(new k5({items:$,getLabel:(J)=>{switch(J){case"private":return"Private - Only you can see this thread";case"workspace":return"Workspace - Visible to workspace members";case"group":return"Group - Visible to group members";case"unlisted":return"Unlisted - Anyone with the link can view";case"public":return"Public - Searchable and on your public profile"}},title:"Select Thread Visibility",onAccept:async(J)=>{this.setState(()=>{this.isLoading=!0});let Y=await this.widget.props.execute(J);this.setState(()=>{this.isLoading=!1,this.result=Y})},onDismiss:this.widget.props.onDismiss}))}return new CA({children:Q,fit:"expand"})}}function x78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,16),child:new Q10({workspace:null,threadID:Q,execute:($)=>A.setVisibility(Q,$),onDismiss:B})})})}function N9A(A,Q){return{noun:"thread",verb:"set visibility",description:"Set thread visibility",keywords:["share","private","workspace","public","unlisted","team","group"],get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client?.getThreadId();if(!Y)return;B.push(x78(A,Y,J))}}}class oQ1 extends y0{initialAgentMode;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;history;updateDraftThreadSettings;onNewThread;shareThreadWithSupport;setThreadVisibility;archiveThread;addThreadLabel;removeThreadLabel;configService;connectionErrorMessage;hints;ideStatus;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.shareThreadWithSupport=A.shareThreadWithSupport,this.setThreadVisibility=A.setThreadVisibility,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.connectionErrorMessage=A.connectionErrorMessage,this.hints=A.hints,this.ideStatus=A.ideStatus}createState(){return new I9A}}class I9A extends v0{historyIndex=-1;historyDraft=null;promptHistoryPicker=new he(this);agentMode;expansion=new JQ1;previousThreadIDForReference=null;unregisterCommands=null;initState(){this.agentMode=this.widget.initialAgentMode,this.unregisterCommands=this.registerCommands()}didUpdateWidget(A){if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.historyIndex=-1,this.historyDraft=null,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null;else this.previousThreadIDForReference=null}dispose(){this.unregisterCommands?.(),this.unregisterCommands=null}registerCommands(){let A=OX.of(this.context),Q=c7.of(this.context),B=this,$=()=>{return B.widget.threadContext??null},J=()=>{let X=B.widget.threadContext?.client.getThreadId();if(!X)return null;return _Y(new URL(Q.ampURL),X).toString()},F=[...s$(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:X})=>({noun:"mode",verb:`use ${X}`,description:`Enable ${X} mode`,get status(){if(B.widget.threadContext)return{type:"disabled",reason:"Mode can only be changed on a new thread"};if(X===B.agentMode)return{type:"disabled",reason:`Already using ${X} mode`};return{type:"enabled"}},run:(D,G,V)=>{B.setAgentMode(X),V()}})),{noun:"speed",verb:"toggle speed",description:"Toggle speed (fast/standard) for this thread",keywords:["anthropic","openai","fast","standard","smart","deep"],get status(){let X=B.currentCommandAgentMode();return X==="smart"||N3(X)?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleSpeed(),G()}},{noun:"thread",verb:"toggle thinking blocks",description:"Expand or collapse all thinking blocks",keywords:["thinking","expand","collapse","reasoning"],shortcut:o1.alt("t"),status:{type:"enabled"},run:(X,D,G)=>{B.toggleGlobalThinking(),G()}},{noun:"mode",verb:"toggle deep effort",description:"Cycle deep reasoning effort (medium → high → xhigh)",keywords:["deep","thinking","reasoning","effort","depth"],shortcut:o1.alt("d"),get status(){return N3(B.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleDeepReasoningEffort(),G()}},{noun:"prompt",verb:"history",description:"Restore a previous prompt",keywords:["recent","reuse","search"],shortcut:o1.ctrl("r"),status:{type:"enabled"},run:(X,D,G)=>{X.pushWithDismiss((V)=>new hW0({entries:this.widget.history.getAll(),currentCwd:aQ1.cwd(),onAccept:(U)=>{this.restorePromptHistory(U),G()},onDismiss:V}))}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",keywords:["identifier","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;K6.maybeInvoke(D,new hG(V,"Thread ID copied to clipboard","Failed to copy thread ID")),G()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["link","share","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=J();if(!V)return;K6.maybeInvoke(D,new hG(V,"Thread URL copied to clipboard","Failed to copy thread URL")),G()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",keywords:["markdown","export","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;(async()=>{try{let U=await Q.getThreadMarkdown(V);if(!U){fK.error(D,"Failed to copy thread markdown");return}K6.maybeInvoke(D,new hG(U,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(U){T.error("Failed to render thread markdown from Neo command palette",{error:U,threadID:V}),fK.error(D,"Failed to copy thread markdown")}finally{G()}})()}},{noun:"thread",verb:"analyze context",description:"Analyze context token usage",keywords:["tokens","usage","window","size","cost"],get status(){let X=B.widget.threadContext;if(!X)return{type:"disabled",reason:"No active thread"};let D=t$(X.observer.agentMode);if(!w3A.includes(D))return{type:"disabled",reason:"Context analysis requires Claude Opus 4.7 (smart) or GPT-5.4 (deep)"};return{type:"enabled"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>{return new D3({header:"Context Usage Analysis",minWidth:60,maxWidth:60,chromePadding:M0.symmetric(1,0),footer:[{keys:["Esc"],label:"close"}],onDismiss:G,child:new d00({embedded:!0,contentWidth:58,thread:null,dtwAnalyze:(K)=>{return B.widget.analyzeContextForThread(D,K)},onDismiss:G})})})}},{noun:"skills",verb:"list",description:"List available skills for this thread",keywords:["agent","show"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>new nQ1({listSkills:(V)=>B.widget.listSkillsForThread(D,V),onDismiss:G,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start","reset","clear"],sortBoost:101,get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(X,D)=>{K6.maybeInvoke(D,new f00)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web","view","launch"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(X,D,G)=>{let V=J();if(!V)return;try{await V5(D,V)}finally{G()}}},z9A({shareThreadWithSupport:(X,D)=>{return this.widget.shareThreadWithSupport(X,D)}},$),N9A({setVisibility:(X,D)=>this.widget.setThreadVisibility(X,D)},$),x2A({archiveThread:(X)=>this.widget.archiveThread(X)},$),W9A($),B9A({configService:this.widget.configService,addLabel:(X,D)=>this.widget.addThreadLabel(X,D)},$),Y9A({configService:this.widget.configService,removeLabel:(X,D)=>this.widget.removeThreadLabel(X,D)},$)].map((X)=>A.register(X));return()=>{for(let X of F)X()}}currentCommandAgentMode(){return this.widget.threadContext?.observer.agentMode??this.agentMode}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let B=Q.observer.threadSettings().getValue()??{},$=A(B);return Q.client.sendClientUpdateThreadSettings($),this.widget.updateDraftThreadSettings(()=>$),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){let A=this.currentCommandAgentMode();if(A==="smart")return this.updateThreadSettings((Q)=>{let B={...Q};if(B["anthropic.speed"]==="fast")delete B["anthropic.speed"];else B["anthropic.speed"]="fast";return B});if(N3(A))return this.updateThreadSettings((Q)=>{let B={...Q};if(B["openai.speed"]==="fast")B["openai.speed"]="standard";else B["openai.speed"]="fast";return B});return"ignored"}toggleGlobalThinking(){return this.expansion.toggle(),"handled"}toggleDeepReasoningEffort(){if(!N3(this.currentCommandAgentMode()))return"ignored";return this.updateThreadSettings((A)=>{let Q=sE(A);return{...A,"agent.deepReasoningEffort":Q==="medium"?"high":Q==="high"?"xhigh":"medium"}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,aQ1.cwd()),this.resetHistory()};restorePromptHistory(A){this.resetHistory(),this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd()}handlePromptHistorySelection=(A)=>{this.promptHistoryPicker.disable(),this.restorePromptHistory(A)};navigateHistoryPrevious=()=>{let A=this.widget.history.previous();if(A!==null){if(this.historyIndex===-1)this.historyDraft=this.widget.editorController.text;this.historyIndex++,this.widget.editorController.text=A,this.widget.editorController.moveCursorToStart()}return"handled"};navigateHistoryNext=()=>{let A=this.widget.history.next();if(A!==null)this.historyIndex--,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.widget.editorController.text=this.historyDraft||"",this.widget.editorController.moveCursorToEnd(),this.historyDraft=null;return"handled"};resetHistory(){this.widget.history.reset(),this.historyIndex=-1,this.historyDraft=null}setAgentMode(A){if(this.widget.threadContext)return;this.setState(()=>{this.agentMode=A}),NX((Q)=>({...Q,agentMode:A}))}buildActions(){let A=new y4(()=>{return this.promptHistoryPicker.enable(),"handled"}),Q=new y4(()=>{return this.navigateHistoryPrevious()}),B=new y4(()=>{return this.navigateHistoryNext()}),$=new y4((Z)=>{return this.setAgentMode(Z.mode),"handled"}),J=new y4(()=>{return this.toggleDeepReasoningEffort()}),Y=new y4(()=>{return this.toggleGlobalThinking()});return new Map([[gH,A],[IW0,B],[NW0,Q],[g00,$],[CW0,J],[zW0,Y]])}build(A){let Q=this.widget.threadContext,$=[Q?new pQ1({editorController:this.widget.editorController,observingClient:{client:Q.client,observer:Q.observer},hints:this.widget.hints,ideStatus:this.widget.ideStatus,onPromptSubmitted:this.onPromptSubmitted}):new iQ1({agentMode:this.agentMode,threadSettings:this.widget.draftThreadSettings,editorController:this.widget.editorController,onNewThread:this.widget.onNewThread,previousThreadIDForReference:this.previousThreadIDForReference,connectionErrorMessage:this.widget.connectionErrorMessage,hints:this.widget.hints,ideStatus:this.widget.ideStatus})];if(this.promptHistoryPicker.isEnabled())$.push(new hW0({entries:this.widget.history.getAll(),currentCwd:aQ1.cwd(),onAccept:this.handlePromptHistorySelection,onDismiss:this.promptHistoryPicker.disable}));let J=new Map([[o1.ctrl("r"),new gH],[o1.alt("d"),new CW0],[o1.alt("t"),new zW0]]);if(this.promptHistoryPicker.isEnabled())J.set(o1.ctrl("o"),new gH);else J.set(o1.ctrl("n"),new IW0),J.set(o1.ctrl("p"),new NW0);return new K6({actions:this.buildActions(),child:new o3({debugLabel:"NeoThreadShortcuts",shortcuts:J,child:new jX({controller:this.expansion,child:new CA({children:$})})})})}}class rQ1 extends y0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;isFirstOpen;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.isFirstOpen=A.isFirstOpen??!1,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new C9A}}class C9A extends v0{editorController=new I2;commandPalette=new he(this);commandRegistry=new n71;toastController=new g31;exitHintTimer=new ue(this,1000);connectionErrorMessage=new r3(this,null);ideStatus=new r3(this,{});draftThreadSettings={};draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;ideErrorSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;firstOpenDialogVisible=!1;focusDebugVisible=!1;unregisterCommands=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.clearConnectionError(),this.connectToExistingThread(A)};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await m8A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return p8A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await $1A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await J1A({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 Y1A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(H$.getInstance().interceptConsole(),this.widget.isFirstOpen)this.firstOpenDialogVisible=!0;if(this.connectionErrorMessage.subscribe(this.widget.clientPool.connectionErrors$.pipe(aE(({threadID:Q,error:B})=>{T.error("Neo failed to connect to thread",{threadID:Q,error:B})}),N5(({threadID:Q})=>this.isConnectionErrorRelevant(Q)),aE(()=>this.clearActiveClientForConnectionError()),w1(({threadID:Q,error:B})=>{return Q?`Connection failed for ${Q}: ${B.message}`:`Connection failed: ${B.message}`}))),this.ideStatus.subscribe(this.widget.ideManager.status),this.ideErrorSubscription=this.widget.ideManager.errors$.subscribe((Q)=>{if(Q)this.setState(()=>{this.connectionErrorMessage.setValue(Q)})}),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID)this.connectToExistingThread(this.widget.initialThreadID,A);else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=i4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let Q=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(B,$,J)=>{B.pushWithDismiss((Y)=>bQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Y,onThreadSelected:J}))}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new $Q1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:$}))}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{mJ(this.widget.neoContext.settingsFilePath).catch((B)=>{T.error("Failed to open settings file in editor",{error:B})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(B,$,J)=>{B.pushWithDismiss((Y)=>new QQ1({onCancel:Y,onSelect:(Z)=>{this.handleIdeSelection(Z),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(B,$)=>{B.pushWithDismiss((J)=>new t71({commands:OX.of($).commands,onDismiss:J}))}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new D3({header:"Amp Version",maxWidth:72,onDismiss:$,child:new t({text:new O(y31({version:"0.0.1777144048-gff4795",buildTimestamp:"2026-04-25T19:11:23.482Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:o1.ctrl("c"),status:{type:"enabled"},run:(B,$)=>{K6.maybeInvoke($,new du)}},...g8A(this.widget.neoContext.logFilePath)].map((B)=>this.commandRegistry.register(B));return()=>{for(let B of Q)B()}}build(A){let Q=this.buildHints(),B=this.connectionErrorMessage.getValue(),$=this.ideStatus.getValue(),J=new oQ1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,connectionErrorMessage:B,hints:Q,ideStatus:$}),Y=F4.of(A),F=[new u0({constraints:W1.tight(Y.size.width,Y.size.height),child:J})];if(this.commandPalette.isEnabled())F.push(new a71({onDismiss:this.commandPalette.disable}));if(this.switchThreadPickerVisible)F.push(bQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.firstOpenDialogVisible)F.push(new e71({onDismiss:this.dismissFirstOpenDialog}));if(this.focusDebugVisible)F.push(new AQ1);return new c7({neoContext:this.widget.neoContext,child:new OX({commandRegistry:this.commandRegistry,child:new Aw({completionBuilder:this.widget.completionBuilder,child:new fK({controller:this.toastController,child:new K6({actions:this.buildActions(),child:new o3({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[o1.ctrl("c"),new WW0],[o1.ctrl("o"),new HW0],[o1.ctrl("t"),new qW0]]),child:new a4({debugLabel:"AppShellFocus",child:new m31({controller:this.toastController,child:new CA({children:F})})})})})})})})})}buildActions(){let A=new y4(()=>{return this.onExitPressed(),"handled"}),Q=new y4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new y4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new y4(()=>{return this.commandPalette.disable(),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null,this.connectionErrorMessage.setValue(null)}),"handled"}),J=new y4(()=>{return i4.instance.stop(),"handled"}),Y=new y4((F)=>{if(!F.text)return"ignored";return i4.instance.tuiInstance.clipboard.writeText(F.text).then(()=>{this.toastController.show(F.successMessage,"success",2000)}).catch((X)=>{T.error("Failed to copy Neo text to clipboard",{error:X}),this.toastController.show(F.failureMessage,"error",2000)}),"handled"}),Z=new y4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[WW0,A],[f00,$],[du,J],[hG,Y],[h00,B],[HW0,Q],[qW0,Z]])}ensureDraftThreadSettingsInitialized(){if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=await MK0(this.widget.configService);if(!this.mounted)return;this.setState(()=>{this.draftThreadSettings=A})}catch(A){T.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(gu);if(this.exitHintTimer.isActive())A.add(T00);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),i4.instance.stop();else this.exitHintTimer.activate()};dismissFirstOpenDialog=()=>{if(!this.firstOpenDialogVisible)return;this.setState(()=>{this.firstOpenDialogVisible=!1})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let B=A.find((J)=>J.type==="text");if(B&&B.type==="text")this.widget.history.add(B.text,gW0.cwd()),this.widget.history.reset();let $=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings);this.clearConnectionError(),this.sendUserMessage($,A,Q),this.setActiveClient($)};sendUserMessage(A,Q,B){A.observer.markMessageSent();let $=vX0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}async connectToExistingThread(A,Q){this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient(B),Q)this.sendUserMessage(B,[{type:"text",text:Q}])}catch(B){T.error("Failed to load thread",{error:B,threadID:A}),this.connectionErrorMessage.setValue(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`)}finally{this.setState(()=>{this.connectingToThreadID=null})}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.connectionErrorMessage.setValue(null),this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=gW0.cwd().replace(gW0.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";gW0.stdout.write(PC(B))}handleIdeSelection=async(A)=>{await this.widget.ideManager.connect(A)};dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.titleSubscription?.unsubscribe(),this.ideErrorSubscription?.unsubscribe(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}isConnectionErrorRelevant(A){if(!this.activeThreadContext)return!0;if(!A)return!0;return this.activeThreadContext.client.getThreadId()===A}clearConnectionError(){if(!this.connectionErrorMessage.getValue())return;this.setState(()=>{this.connectionErrorMessage.setValue(null)})}clearActiveClientForConnectionError(){if(!this.activeThreadContext)return;this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.widget.notificationService.detach(),this.writeTerminalTitle(void 0),this.activeThreadContext=null})}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.firstOpenDialogVisible}}e4();function w9A(A,Q,B,$){let J=mk(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 EZ(G,V),K=new gJ(42),E=new kC(G,V,G,V,G,V,0,A.agentMode??"smart","intensity",void 0,void 0,C0.default(),K);E.layout(W1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let j=0;j<V;j++)if(W[j].some((P)=>P.char!==" ")){H=j;break}let z=V-1;for(let j=V-1;j>=0;j--)if(W[j].some((P)=>P.char!==" ")){z=j;break}function q(j,P){if(!j)return"";if(j.type==="rgb"){let{r:R,g:b,b:g}=j.value;if(B.getColorDepth()>=24)return`\x1B[${P?38:48};2;${R};${b};${g}m`;let f=IP(R,b,g);return`\x1B[${P?38:48};5;${f}m`}return""}let N=[];if(z>=H)for(let j=H;j<=z;j++){let P="";for(let R=0;R<G;R++){let b=W[j][R],g=b.char,f=q(b.style.fg,!0);P+=f+g+"\x1B[0m"}N.push(P)}let I=N.length,C=Math.max(I,D.length),w=Math.floor((C-I)/2),M=Math.floor((C-D.length)/2);for(let j=0;j<C;j++){let P=" ".repeat(G);if(j>=w&&j<w+I)P=N[j-w];let R=" ",b="";if(j>=M&&j<M+D.length)b=D[j-M];B.write(P+R+b+`
5159
+ `,new h({color:B.foreground,dim:!0})),new O("If you need a reply, post on X @AmpCode or email amp-devs@ampcode.com.",new h({color:B.foreground,dim:!0}))]),textAlign:"center"})})}}function H9A(A){return new D3({header:A.title,minWidth:80,maxWidth:80,chromePadding:M0.symmetric(1,0),footer:"none",onDismiss:A.onDismiss,child:A.child})}function y78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,12),child:new eH({commandName:"Share with Support",title:"Share Thread with Support",placeholder:"What went wrong? (Need a reply? Email amp-devs@ampcode.com.)",isRequiredArg:!1,onSubmit:async($)=>{try{await A.shareThreadWithSupport(Q,$||void 0),B.pushResultPane(H9A({title:"Shared with Support",onDismiss:B.dismissFlow,child:new A10}))}catch(J){T.error("Failed to share thread with support",{error:J,threadID:Q}),B.pushResultPane(H9A({title:"Share with Support failed",onDismiss:B.dismissFlow,child:new t({text:new O(`Failed to share thread with support: ${J instanceof Error?J.message:String(J)}`)})}))}},onDismiss:B.dismissFlow})})})}function z9A(A,Q){return{noun:"thread",verb:"share with support",description:"Share with Amp support for debugging",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;B.push(y78(A,Y,{dismissFlow:J,pushResultPane:(Z)=>B.push(Z)}))}}}class Q10 extends y0{props;constructor(A){super();this.props=A}createState(){return new q9A}}class q9A extends v0{result=void 0;isLoading=!1;build(A){let Q=[];if(this.isLoading)Q.push(new fQ({message:"Updating visibility..."}));else if(this.result!==void 0)Q.push(new l7({message:this.result,onDismiss:()=>{this.widget.props.onDismiss()}}));else{let B=["private","workspace","unlisted","public"],$=this.widget.props.workspace?.groups&&this.widget.props.workspace.groups.length>0?["private","workspace","group","unlisted","public"]:B;Q.push(new k5({items:$,getLabel:(J)=>{switch(J){case"private":return"Private - Only you can see this thread";case"workspace":return"Workspace - Visible to workspace members";case"group":return"Group - Visible to group members";case"unlisted":return"Unlisted - Anyone with the link can view";case"public":return"Public - Searchable and on your public profile"}},title:"Select Thread Visibility",onAccept:async(J)=>{this.setState(()=>{this.isLoading=!0});let Y=await this.widget.props.execute(J);this.setState(()=>{this.isLoading=!1,this.result=Y})},onDismiss:this.widget.props.onDismiss}))}return new CA({children:Q,fit:"expand"})}}function x78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,16),child:new Q10({workspace:null,threadID:Q,execute:($)=>A.setVisibility(Q,$),onDismiss:B})})})}function N9A(A,Q){return{noun:"thread",verb:"set visibility",description:"Set thread visibility",keywords:["share","private","workspace","public","unlisted","team","group"],get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client?.getThreadId();if(!Y)return;B.push(x78(A,Y,J))}}}class oQ1 extends y0{initialAgentMode;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;history;updateDraftThreadSettings;onNewThread;shareThreadWithSupport;setThreadVisibility;archiveThread;addThreadLabel;removeThreadLabel;configService;connectionErrorMessage;hints;ideStatus;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.shareThreadWithSupport=A.shareThreadWithSupport,this.setThreadVisibility=A.setThreadVisibility,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.connectionErrorMessage=A.connectionErrorMessage,this.hints=A.hints,this.ideStatus=A.ideStatus}createState(){return new I9A}}class I9A extends v0{historyIndex=-1;historyDraft=null;promptHistoryPicker=new he(this);agentMode;expansion=new JQ1;previousThreadIDForReference=null;unregisterCommands=null;initState(){this.agentMode=this.widget.initialAgentMode,this.unregisterCommands=this.registerCommands()}didUpdateWidget(A){if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.historyIndex=-1,this.historyDraft=null,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null;else this.previousThreadIDForReference=null}dispose(){this.unregisterCommands?.(),this.unregisterCommands=null}registerCommands(){let A=OX.of(this.context),Q=c7.of(this.context),B=this,$=()=>{return B.widget.threadContext??null},J=()=>{let X=B.widget.threadContext?.client.getThreadId();if(!X)return null;return _Y(new URL(Q.ampURL),X).toString()},F=[...s$(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:X})=>({noun:"mode",verb:`use ${X}`,description:`Enable ${X} mode`,get status(){if(B.widget.threadContext)return{type:"disabled",reason:"Mode can only be changed on a new thread"};if(X===B.agentMode)return{type:"disabled",reason:`Already using ${X} mode`};return{type:"enabled"}},run:(D,G,V)=>{B.setAgentMode(X),V()}})),{noun:"speed",verb:"toggle speed",description:"Toggle speed (fast/standard) for this thread",keywords:["anthropic","openai","fast","standard","smart","deep"],get status(){let X=B.currentCommandAgentMode();return X==="smart"||N3(X)?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleSpeed(),G()}},{noun:"thread",verb:"toggle thinking blocks",description:"Expand or collapse all thinking blocks",keywords:["thinking","expand","collapse","reasoning"],shortcut:o1.alt("t"),status:{type:"enabled"},run:(X,D,G)=>{B.toggleGlobalThinking(),G()}},{noun:"mode",verb:"toggle deep effort",description:"Cycle deep reasoning effort (medium → high → xhigh)",keywords:["deep","thinking","reasoning","effort","depth"],shortcut:o1.alt("d"),get status(){return N3(B.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleDeepReasoningEffort(),G()}},{noun:"prompt",verb:"history",description:"Restore a previous prompt",keywords:["recent","reuse","search"],shortcut:o1.ctrl("r"),status:{type:"enabled"},run:(X,D,G)=>{X.pushWithDismiss((V)=>new hW0({entries:this.widget.history.getAll(),currentCwd:aQ1.cwd(),onAccept:(U)=>{this.restorePromptHistory(U),G()},onDismiss:V}))}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",keywords:["identifier","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;K6.maybeInvoke(D,new hG(V,"Thread ID copied to clipboard","Failed to copy thread ID")),G()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["link","share","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=J();if(!V)return;K6.maybeInvoke(D,new hG(V,"Thread URL copied to clipboard","Failed to copy thread URL")),G()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",keywords:["markdown","export","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;(async()=>{try{let U=await Q.getThreadMarkdown(V);if(!U){fK.error(D,"Failed to copy thread markdown");return}K6.maybeInvoke(D,new hG(U,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(U){T.error("Failed to render thread markdown from Neo command palette",{error:U,threadID:V}),fK.error(D,"Failed to copy thread markdown")}finally{G()}})()}},{noun:"thread",verb:"analyze context",description:"Analyze context token usage",keywords:["tokens","usage","window","size","cost"],get status(){let X=B.widget.threadContext;if(!X)return{type:"disabled",reason:"No active thread"};let D=t$(X.observer.agentMode);if(!w3A.includes(D))return{type:"disabled",reason:"Context analysis requires Claude Opus 4.7 (smart) or GPT-5.4 (deep)"};return{type:"enabled"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>{return new D3({header:"Context Usage Analysis",minWidth:60,maxWidth:60,chromePadding:M0.symmetric(1,0),footer:[{keys:["Esc"],label:"close"}],onDismiss:G,child:new d00({embedded:!0,contentWidth:58,thread:null,dtwAnalyze:(K)=>{return B.widget.analyzeContextForThread(D,K)},onDismiss:G})})})}},{noun:"skills",verb:"list",description:"List available skills for this thread",keywords:["agent","show"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>new nQ1({listSkills:(V)=>B.widget.listSkillsForThread(D,V),onDismiss:G,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start","reset","clear"],sortBoost:101,get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(X,D)=>{K6.maybeInvoke(D,new f00)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web","view","launch"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(X,D,G)=>{let V=J();if(!V)return;try{await V5(D,V)}finally{G()}}},z9A({shareThreadWithSupport:(X,D)=>{return this.widget.shareThreadWithSupport(X,D)}},$),N9A({setVisibility:(X,D)=>this.widget.setThreadVisibility(X,D)},$),x2A({archiveThread:(X)=>this.widget.archiveThread(X)},$),W9A($),B9A({configService:this.widget.configService,addLabel:(X,D)=>this.widget.addThreadLabel(X,D)},$),Y9A({configService:this.widget.configService,removeLabel:(X,D)=>this.widget.removeThreadLabel(X,D)},$)].map((X)=>A.register(X));return()=>{for(let X of F)X()}}currentCommandAgentMode(){return this.widget.threadContext?.observer.agentMode??this.agentMode}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let B=Q.observer.threadSettings().getValue()??{},$=A(B);return Q.client.sendClientUpdateThreadSettings($),this.widget.updateDraftThreadSettings(()=>$),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){let A=this.currentCommandAgentMode();if(A==="smart")return this.updateThreadSettings((Q)=>{let B={...Q};if(B["anthropic.speed"]==="fast")delete B["anthropic.speed"];else B["anthropic.speed"]="fast";return B});if(N3(A))return this.updateThreadSettings((Q)=>{let B={...Q};if(B["openai.speed"]==="fast")B["openai.speed"]="standard";else B["openai.speed"]="fast";return B});return"ignored"}toggleGlobalThinking(){return this.expansion.toggle(),"handled"}toggleDeepReasoningEffort(){if(!N3(this.currentCommandAgentMode()))return"ignored";return this.updateThreadSettings((A)=>{let Q=sE(A);return{...A,"agent.deepReasoningEffort":Q==="medium"?"high":Q==="high"?"xhigh":"medium"}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,aQ1.cwd()),this.resetHistory()};restorePromptHistory(A){this.resetHistory(),this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd()}handlePromptHistorySelection=(A)=>{this.promptHistoryPicker.disable(),this.restorePromptHistory(A)};navigateHistoryPrevious=()=>{let A=this.widget.history.previous();if(A!==null){if(this.historyIndex===-1)this.historyDraft=this.widget.editorController.text;this.historyIndex++,this.widget.editorController.text=A,this.widget.editorController.moveCursorToStart()}return"handled"};navigateHistoryNext=()=>{let A=this.widget.history.next();if(A!==null)this.historyIndex--,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.widget.editorController.text=this.historyDraft||"",this.widget.editorController.moveCursorToEnd(),this.historyDraft=null;return"handled"};resetHistory(){this.widget.history.reset(),this.historyIndex=-1,this.historyDraft=null}setAgentMode(A){if(this.widget.threadContext)return;this.setState(()=>{this.agentMode=A}),NX((Q)=>({...Q,agentMode:A}))}buildActions(){let A=new y4(()=>{return this.promptHistoryPicker.enable(),"handled"}),Q=new y4(()=>{return this.navigateHistoryPrevious()}),B=new y4(()=>{return this.navigateHistoryNext()}),$=new y4((Z)=>{return this.setAgentMode(Z.mode),"handled"}),J=new y4(()=>{return this.toggleDeepReasoningEffort()}),Y=new y4(()=>{return this.toggleGlobalThinking()});return new Map([[gH,A],[IW0,B],[NW0,Q],[g00,$],[CW0,J],[zW0,Y]])}build(A){let Q=this.widget.threadContext,$=[Q?new pQ1({editorController:this.widget.editorController,observingClient:{client:Q.client,observer:Q.observer},hints:this.widget.hints,ideStatus:this.widget.ideStatus,onPromptSubmitted:this.onPromptSubmitted}):new iQ1({agentMode:this.agentMode,threadSettings:this.widget.draftThreadSettings,editorController:this.widget.editorController,onNewThread:this.widget.onNewThread,previousThreadIDForReference:this.previousThreadIDForReference,connectionErrorMessage:this.widget.connectionErrorMessage,hints:this.widget.hints,ideStatus:this.widget.ideStatus})];if(this.promptHistoryPicker.isEnabled())$.push(new hW0({entries:this.widget.history.getAll(),currentCwd:aQ1.cwd(),onAccept:this.handlePromptHistorySelection,onDismiss:this.promptHistoryPicker.disable}));let J=new Map([[o1.ctrl("r"),new gH],[o1.alt("d"),new CW0],[o1.alt("t"),new zW0]]);if(this.promptHistoryPicker.isEnabled())J.set(o1.ctrl("o"),new gH);else J.set(o1.ctrl("n"),new IW0),J.set(o1.ctrl("p"),new NW0);return new K6({actions:this.buildActions(),child:new o3({debugLabel:"NeoThreadShortcuts",shortcuts:J,child:new jX({controller:this.expansion,child:new CA({children:$})})})})}}class rQ1 extends y0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;isFirstOpen;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.isFirstOpen=A.isFirstOpen??!1,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new C9A}}class C9A extends v0{editorController=new I2;commandPalette=new he(this);commandRegistry=new n71;toastController=new g31;exitHintTimer=new ue(this,1000);connectionErrorMessage=new r3(this,null);ideStatus=new r3(this,{});draftThreadSettings={};draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;ideErrorSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;firstOpenDialogVisible=!1;focusDebugVisible=!1;unregisterCommands=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.clearConnectionError(),this.connectToExistingThread(A)};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await m8A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return p8A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await $1A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await J1A({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 Y1A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(H$.getInstance().interceptConsole(),this.widget.isFirstOpen)this.firstOpenDialogVisible=!0;if(this.connectionErrorMessage.subscribe(this.widget.clientPool.connectionErrors$.pipe(aE(({threadID:Q,error:B})=>{T.error("Neo failed to connect to thread",{threadID:Q,error:B})}),N5(({threadID:Q})=>this.isConnectionErrorRelevant(Q)),aE(()=>this.clearActiveClientForConnectionError()),w1(({threadID:Q,error:B})=>{return Q?`Connection failed for ${Q}: ${B.message}`:`Connection failed: ${B.message}`}))),this.ideStatus.subscribe(this.widget.ideManager.status),this.ideErrorSubscription=this.widget.ideManager.errors$.subscribe((Q)=>{if(Q)this.setState(()=>{this.connectionErrorMessage.setValue(Q)})}),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID)this.connectToExistingThread(this.widget.initialThreadID,A);else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=i4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let Q=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(B,$,J)=>{B.pushWithDismiss((Y)=>bQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Y,onThreadSelected:J}))}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new $Q1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:$}))}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{mJ(this.widget.neoContext.settingsFilePath).catch((B)=>{T.error("Failed to open settings file in editor",{error:B})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(B,$,J)=>{B.pushWithDismiss((Y)=>new QQ1({onCancel:Y,onSelect:(Z)=>{this.handleIdeSelection(Z),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(B,$)=>{B.pushWithDismiss((J)=>new t71({commands:OX.of($).commands,onDismiss:J}))}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new D3({header:"Amp Version",maxWidth:72,onDismiss:$,child:new t({text:new O(y31({version:"0.0.1777147716-gff4795",buildTimestamp:"2026-04-25T20:12:25.387Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:o1.ctrl("c"),status:{type:"enabled"},run:(B,$)=>{K6.maybeInvoke($,new du)}},...g8A(this.widget.neoContext.logFilePath)].map((B)=>this.commandRegistry.register(B));return()=>{for(let B of Q)B()}}build(A){let Q=this.buildHints(),B=this.connectionErrorMessage.getValue(),$=this.ideStatus.getValue(),J=new oQ1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,connectionErrorMessage:B,hints:Q,ideStatus:$}),Y=F4.of(A),F=[new u0({constraints:W1.tight(Y.size.width,Y.size.height),child:J})];if(this.commandPalette.isEnabled())F.push(new a71({onDismiss:this.commandPalette.disable}));if(this.switchThreadPickerVisible)F.push(bQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.firstOpenDialogVisible)F.push(new e71({onDismiss:this.dismissFirstOpenDialog}));if(this.focusDebugVisible)F.push(new AQ1);return new c7({neoContext:this.widget.neoContext,child:new OX({commandRegistry:this.commandRegistry,child:new Aw({completionBuilder:this.widget.completionBuilder,child:new fK({controller:this.toastController,child:new K6({actions:this.buildActions(),child:new o3({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[o1.ctrl("c"),new WW0],[o1.ctrl("o"),new HW0],[o1.ctrl("t"),new qW0]]),child:new a4({debugLabel:"AppShellFocus",child:new m31({controller:this.toastController,child:new CA({children:F})})})})})})})})})}buildActions(){let A=new y4(()=>{return this.onExitPressed(),"handled"}),Q=new y4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new y4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new y4(()=>{return this.commandPalette.disable(),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null,this.connectionErrorMessage.setValue(null)}),"handled"}),J=new y4(()=>{return i4.instance.stop(),"handled"}),Y=new y4((F)=>{if(!F.text)return"ignored";return i4.instance.tuiInstance.clipboard.writeText(F.text).then(()=>{this.toastController.show(F.successMessage,"success",2000)}).catch((X)=>{T.error("Failed to copy Neo text to clipboard",{error:X}),this.toastController.show(F.failureMessage,"error",2000)}),"handled"}),Z=new y4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[WW0,A],[f00,$],[du,J],[hG,Y],[h00,B],[HW0,Q],[qW0,Z]])}ensureDraftThreadSettingsInitialized(){if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=await MK0(this.widget.configService);if(!this.mounted)return;this.setState(()=>{this.draftThreadSettings=A})}catch(A){T.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(gu);if(this.exitHintTimer.isActive())A.add(T00);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),i4.instance.stop();else this.exitHintTimer.activate()};dismissFirstOpenDialog=()=>{if(!this.firstOpenDialogVisible)return;this.setState(()=>{this.firstOpenDialogVisible=!1})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let B=A.find((J)=>J.type==="text");if(B&&B.type==="text")this.widget.history.add(B.text,gW0.cwd()),this.widget.history.reset();let $=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings);this.clearConnectionError(),this.sendUserMessage($,A,Q),this.setActiveClient($)};sendUserMessage(A,Q,B){A.observer.markMessageSent();let $=vX0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}async connectToExistingThread(A,Q){this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient(B),Q)this.sendUserMessage(B,[{type:"text",text:Q}])}catch(B){T.error("Failed to load thread",{error:B,threadID:A}),this.connectionErrorMessage.setValue(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`)}finally{this.setState(()=>{this.connectingToThreadID=null})}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.connectionErrorMessage.setValue(null),this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=gW0.cwd().replace(gW0.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";gW0.stdout.write(PC(B))}handleIdeSelection=async(A)=>{await this.widget.ideManager.connect(A)};dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.titleSubscription?.unsubscribe(),this.ideErrorSubscription?.unsubscribe(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}isConnectionErrorRelevant(A){if(!this.activeThreadContext)return!0;if(!A)return!0;return this.activeThreadContext.client.getThreadId()===A}clearConnectionError(){if(!this.connectionErrorMessage.getValue())return;this.setState(()=>{this.connectionErrorMessage.setValue(null)})}clearActiveClientForConnectionError(){if(!this.activeThreadContext)return;this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.widget.notificationService.detach(),this.writeTerminalTitle(void 0),this.activeThreadContext=null})}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.firstOpenDialogVisible}}e4();function w9A(A,Q,B,$){let J=mk(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 EZ(G,V),K=new gJ(42),E=new kC(G,V,G,V,G,V,0,A.agentMode??"smart","intensity",void 0,void 0,C0.default(),K);E.layout(W1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let j=0;j<V;j++)if(W[j].some((P)=>P.char!==" ")){H=j;break}let z=V-1;for(let j=V-1;j>=0;j--)if(W[j].some((P)=>P.char!==" ")){z=j;break}function q(j,P){if(!j)return"";if(j.type==="rgb"){let{r:R,g:b,b:g}=j.value;if(B.getColorDepth()>=24)return`\x1B[${P?38:48};2;${R};${b};${g}m`;let f=IP(R,b,g);return`\x1B[${P?38:48};5;${f}m`}return""}let N=[];if(z>=H)for(let j=H;j<=z;j++){let P="";for(let R=0;R<G;R++){let b=W[j][R],g=b.char,f=q(b.style.fg,!0);P+=f+g+"\x1B[0m"}N.push(P)}let I=N.length,C=Math.max(I,D.length),w=Math.floor((C-I)/2),M=Math.floor((C-D.length)/2);for(let j=0;j<C;j++){let P=" ".repeat(G);if(j>=w&&j<w+I)P=N[j-w];let R=" ",b="";if(j>=M&&j<M+D.length)b=D[j-M];B.write(P+R+b+`
5160
5160
  `)}if($)B.write(`
5161
5161
  \x1B[90m${$}\x1B[0m
5162
5162
  `)}l0();uK0();var f78=2000;function M9A(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<f78)return;if(J=U,_P())return;if(vU0())yU0();else pr(V)},Z=(V)=>{if(!Q||!B)return;if(_P()&&!Se()&&!BK0())return;process.stdout.write(SG(`\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&&NC(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){T.debug("Neo notification handling failed",{error:K})}finally{X=U}},error:(U)=>{T.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}l0();JW();z4();O1();function L9A(A,Q){if(!Q)return A;let B=Q.toLowerCase(),$=[];for(let J of A){let Y=b78(J,B);if(Y>0)$.push({...J,score:Y})}return $.sort((J,Y)=>{let Z=Y.score-J.score;if(Z!==0)return Z;return A.indexOf(J)-A.indexOf(Y)}),$}function b78(A,Q){let B=u78(A,Q),$=h78(A.message.toLowerCase(),Q);return Math.max(B,$)}function u78(A,Q){let B=A.hash.toLowerCase(),$=A.shortHash.toLowerCase();if($===Q)return 1000;if($.startsWith(Q))return 900;if(B.startsWith(Q))return 850;if(B.includes(Q)||$.includes(Q))return 400;return 0}function h78(A,Q){if(A===Q)return 800;if(A.startsWith(Q))return 700;let B=A.indexOf(Q);if(B!==-1)return 600-Math.min(B,500);let $=g78(A,Q);if($>0)return $;return 0}function g78(A,Q){let B=0,$=0,J=-1;while(B<A.length&&$<Q.length){if(A[B]===Q[$]){if(J===-1)J=B;$++}B++}if($===Q.length)return 250-Math.min(J,150);return 0}var O9A=":";function U_(A,Q){if(!UP())return;T.debug("[file mention completions]",{event:A,...Q})}function su(A){return A.length<=80?A:`${A.slice(0,77)}...`}class K_{fuzzyClient;cachedDirtyFiles=[];cachedCommits=[];refreshPromise;refreshCommitsPromise;constructor(A){this.fuzzyClient=A;this.refreshDirtyFilesInBackground(),this.refreshCommitsInBackground()}async buildOptions(A){if(A.trigger==="@"){let Q=A.query;if(Q.toLowerCase().startsWith(O9A)){let Z=Q.slice(O9A.length);return U_("commit_query_detected",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Z.length,queryPreview:su(Z)}),this.buildCommitOptions(Z)}let $=Q.length===0?18:20,J=await this.buildFileOptions(Q,$),Y=this.appendHintOptions(Q,J);return U_("build_options_completed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Q.length,queryPreview:su(Q),maxResults:$,fileOptionCount:J.filter((Z)=>Z.type==="file").length,hintOptionCount:Y.filter((Z)=>Z.type==="hint").length,finalOptionCount:Y.length,firstFilePaths:Y.filter((Z)=>Z.type==="file").slice(0,5).map((Z)=>Z.path)}),Y}return[]}async buildFileOptions(A,Q){try{let B=await this.getOpenFiles(),$=this.cachedDirtyFiles;this.refreshDirtyFilesInBackground();let J=await this.fuzzyClient.queryCompletions(A,Q,B,$),Y=J.map((Z)=>Y2A(Z));return U_("file_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:su(A),maxResults:Q,openFilesCount:B?.length??0,dirtyFilesCount:$.length,completionItemCount:J.length,fileOptionCount:Y.length,firstPaths:Y.slice(0,5).map((Z)=>Z.path)}),Y}catch(B){return U_("file_options_failed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:su(A),maxResults:Q,error:B instanceof Error?B.message:String(B)}),[]}}async getOpenFiles(){let A=await k1(i8.status);if(!A.connected)return;let Q=[];if(A.openFile)Q.push(Z1.parse(A.openFile).fsPath);if(A.visibleFiles)for(let B of A.visibleFiles){let $=Z1.parse(B).fsPath;if(!Q.includes($))Q.push($)}if(Q.length===0)return;return Q}refreshDirtyFilesInBackground(){if(this.refreshPromise!==void 0)return;this.refreshPromise=Ck4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedDirtyFiles=A}).catch(()=>{}).finally(()=>{this.refreshPromise=void 0})}async buildCommitOptions(A){this.refreshCommitsInBackground();let Q=this.cachedCommits;if(!Q.length)return U_("commit_options_empty_cache",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:su(A)}),[];let B=L9A(Q,A).slice(0,20);return U_("commit_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:su(A),commitCacheCount:Q.length,resultCount:B.length,firstCommitHashes:B.slice(0,5).map(($)=>$.shortHash)}),B.map(($)=>({type:"commit",hash:$.hash,shortHash:$.shortHash,message:$.message,relativeDate:$.relativeDate}))}refreshCommitsInBackground(){if(this.refreshCommitsPromise!==void 0)return;this.refreshCommitsPromise=wk4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedCommits=A}).catch(()=>{}).finally(()=>{this.refreshCommitsPromise=void 0})}appendHintOptions(A,Q){if(A.length>0)return Q;let B=[{type:"hint",kind:"commit",message:"mention a commit"},{type:"hint",kind:"thread",message:"mention a thread"}];return U_("hint_options_appended",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,fileOptionCount:Q.filter(($)=>$.type==="file").length,hintOptionCount:B.length,hintOnly:Q.length===0,firstFilePaths:Q.filter(($)=>$.type==="file").slice(0,5).map(($)=>$.path)}),[...Q,...B]}}var p78=[{long:"neo",description:"Use the Neo TUI",type:"boolean",default:!1},{long:"url",short:"u",description:"Amp server URL",type:"string",default:""},{long:"dangerously-allow-all",description:"Disable all command confirmation prompts (agent will execute all commands without asking)",type:"boolean",default:!1},{long:"observe",description:"Connect to an existing thread as observer only (no local executor). Accepts a thread ID or thread URL.",type:"string",default:""}],Xh2=k0A({name:"amp neo",description:"Start the Neo TUI",options:p78,positionals:[],action:async({options:A})=>{let Q=j9A(A);if(A.observe){let B=I3(A.observe)??EB(A.observe);await mW0(Q,{initialThreadID:B,observerOnly:!0});return}await mW0(Q)},subcommands:[{name:"threads",alias:"t",description:"List and manage threads",options:[],positionals:[],subcommands:[{name:"continue",alias:"c",description:"Continue an existing thread",options:[],positionals:[{name:"thread-id",description:"Thread ID to continue"}],action:async({globalOptions:A,positionals:Q})=>{let $=j9A(A);if(!Q["thread-id"]){await mW0($,{openThreadPickerOnStart:!0});return}let J=I3(Q["thread-id"]);if(!J)throw"invalid thread ID";await mW0($,{initialThreadID:J})}}]}]});function d78(A){if(A)return A;if(process.env.AMP_URL)return process.env.AMP_URL;return T9}function c78(A){if(process.env.RIVET_PUBLIC_ENDPOINT)return process.env.RIVET_PUBLIC_ENDPOINT;return xJ(A)}var R9A=Z1.file(m78.homedir()),l78=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(R9A,".config");async function i78(A){await NX((Q)=>_K0(Q,A,"interactive"))}function j9A(A){return{url:A.url,dangerouslyAllowAll:A["dangerously-allow-all"]}}async function mW0(A,Q={}){let{initialThreadID:B,openThreadPickerOnStart:$=!1,observerOnly:J=!1}=Q,Y=d78(A.url),Z={dataDir:void 0,getHook:(I,C)=>{if(I==="url")return Promise.resolve(Y);return C()}},F=await hU0(Z),X=PK0(await lt(Z,F)),D=c78(Y);if(A.dangerouslyAllowAll)FQ("dangerouslyAllowAll",!0);let G=await X.get("apiKey",Y);if(!G)throw new K4("API key required. Please run `amp login` first.",1);let V=bk({storage:F,secretStorage:X,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:Y,homeDir:R9A,userConfigDir:l78}),U=lO(V),K=WD0({configService:V}),E=n$0({configService:V,filesystem:k8}),W={registerToolsWithToolService:()=>({dispose:()=>{}}),getClient:()=>{return},servers:g0.of([]),getPrompt:async()=>null,searchResources:async()=>[],searchPrompts:()=>g0.of([]),getToolsForServer:async()=>{return}},H=process.cwd(),z=async({uri:I})=>{return IC({fileSystem:k8,workspaceRoot:H},I)},q=new ab(H,{},!0),N=new K_(q);await sQ1({ampURL:Y,apiKey:G,rivetEndpoint:D,configService:V,toolService:K.toolService,skillService:E,mcpService:W,readFileSystemDirectory:z,completionBuilder:N,workspaceRoot:H,listThreads:()=>U.listThreads(),getThreadFromServer:(I)=>U.getThread(I),isInternalUser:!1,settingsFilePath:F.getSettingsFilePath(),dispose:()=>{q.dispose(),K.dispose()}},{initialThreadID:B,openThreadPickerOnStart:$,observerOnly:J})}async function sQ1(A,Q={}){let{initialThreadID:B,initialUserInput:$,openThreadPickerOnStart:J=!1,observerOnly:Y=!1}=Q,Z=async(H)=>{let z=await A.getThreadFromServer(H);if(!z)return null;return zU0(z)},F=new V31(A.rivetEndpoint,A.apiKey,A.configService,{clientID:HC.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,invokeTool:async(H,z)=>{let q=typeof z.args==="object"&&z.args!==null?z.args:{},N=await PK({toolName:z.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:z.toolCallId,threadID:H});return A.toolService.invokeTool(z.toolName,{args:q},N)},persistLastThreadID:i78,readFileSystemDirectory:A.readFileSystemDirectory},Z),X=await Yu(),D={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(H)=>{let z=await A.getThreadFromServer(H);return z?UU(z):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:jt,mcpServers:A.mcpService.servers,observerOnly:Y,sessionAgentMode:X.agentMode,settingsFilePath:A.settingsFilePath,workspaceRoot:A.workspaceRoot},G=(H,z)=>{return Mb({ampURL:A.ampURL,configService:A.configService,threadID:H,signal:z})},V=(H,z)=>{return ue4({ampURL:A.ampURL,configService:A.configService,threadID:H,signal:z})},U=new v31,K=de4(X);NX(ce4);let E=M9A({configService:A.configService}),W=new Set;try{await ke(new rQ1({clientPool:F,analyzeContextForThread:G,listSkillsForThread:V,completionBuilder:A.completionBuilder,history:new ft,ideManager:U,configService:A.configService,initialThreadID:B,notificationService:E,initialUserInput:$,openThreadPickerOnStart:J,neoContext:D,isFirstOpen:K,onThreadArchived:(z)=>{W.add(z)}}));let H=F.lastActiveObservingClient;if(H){let{client:z,observer:q}=H,N=z.getThreadId();if(N){let I={id:N,title:q.title().getValue(),agentMode:q.agentMode,archived:W.has(N)},C=`${A.ampURL.replace(/\/$/,"")}/threads/${N}`;w9A(I,C,process.stdout)}}}finally{process.stdout.write(PC("")),E.unsubscribe(),F.dispose(),await A.dispose?.()}process.exit(0)}Ul();mL();async function n78(A,Q,B){let $=T70(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=fq($.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 P9A(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await n78(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
@@ -5941,7 +5941,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
5941
5941
  `),Y=[];for(let Z=0;Z<J.length;Z++){let D=J[Z].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let G of D)if(G.startsWith("\x00")&&G.endsWith("\x01"))Y.push(new O(G.slice(1,-1),new h({color:$.app.keybind,bold:!0})));else Y.push(new O(G,new h({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new O(`
5942
5942
  `))}return new u0({decoration:{color:B.colorScheme.background,border:Q4.all(new e1($.app.keybind,1,"rounded"))},child:new x0({padding:M0.symmetric(0,1),child:new t({text:new O(void 0,void 0,Y)})})})}}class U$1 extends n2{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=Vz0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new G$1({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(A){let Q=A;Q.chartData=this.chartData,Q.highlightIndex=this.highlightIndex,Q.showAxes=this.showAxes,Q.colors=this.colors,Q.markNeedsLayout()}}function B$A(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let F=B;return F>=0&&F<Y?F:null}case"bar":case"stacked-bar":{let F=Z?A2:0,X=$-F;if(X<=0)return null;let D=Q-F;if(D<0||D>=X)return null;let G=Math.max(1,Math.floor(X/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let F=Z?A2:0,X=$-F;if(X<=0)return null;let D=Math.max(0,Math.min(X-1,Q-F));if(Y===1)return 0;let G=X/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function eF8(A,Q,B,$,J,Y,Z,F){if(J<=0||Q<0||Q>=J)return null;let X=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?A2:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=Math.max(1,Math.floor(G/J)),K=D+Q*U+Math.floor(U/2),E=F>0?Z/F:0,W=Math.round((1-E)*(V-1));return{x:K,y:W}}case"line":case"sparkline":case"stacked-area":{let D=Y?A2:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=J>1?D+Math.round(Q/(J-1)*(G-1)):D+Math.floor(G/2),K=F>0?Z/F:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function AX8(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function QX8(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 BX8(A,Q,B,$,J,Y,Z){let F;try{let E=S1.of(A),W=S0.of(A);F={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:W.app.keybind}}catch{F={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let X=new h({color:F.foreground,bold:!0}),D=new h({color:F.foreground}),G=new h({color:F.foreground,dim:!0}),V=[],U=new h({color:F.foreground,underline:!0}),K=(E,W)=>new O(W,U,void 0,eU0(E),()=>{V5(A,E)});if($.length<=1){if(V.push(new O(`${Q.label}: `,X)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new O(Y(Q.value),D));if(Q.meta)V.push(new O(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new O(`${Q.label}
5943
5943
  `,X));let W=0;for(let H=0;H<$.length;H++){let z=$[H],q=z.points[B];if(!q)continue;W+=q.value;let N=z.color??J[H%J.length]??F.foreground;if(V.push(new O("● ",new h({color:N}))),V.push(new O(`${z.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new O(Y(q.value),D));if(H<$.length-1||E)V.push(new O(`
5944
- `))}if(E)V.push(new O(" ",G)),V.push(new O("Total: ",G)),V.push(new O(Y(W),D))}return new u0({decoration:{color:F.background,border:Q4.all(new e1(F.border,1,"rounded"))},child:new t({text:new O(void 0,void 0,V)})})}l0();c8();lL();k9();C8();E7();vo();UF();EQ();WQ();oB();GR();e4();Cy();zk();O1();l0();EQ();class K$1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1777144048-gff4795"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await j70(Q,this.configService)}catch(Q){T.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 ww extends y0{props;constructor(A){super();this.props=A}createState(){return new $$A}}class $$A extends v0{_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)}}oB();class J$A extends v0{controller=new I2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new E6({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>=TY)return!1;let Q=await RX(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=S0.of(A),{colors:B,app:$}=Q,Y=F4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new mG({controller:this.controller,triggers:[new iJ],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:i4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new a4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new u0({constraints:new W1({maxHeight:Z}),padding:M0.symmetric(1,0),child:X}),G=new u0({padding:M0.symmetric(1,0),child:new t({text:new O("",void 0,[new O("Command: ",new h({color:B.foreground})),new O(this.widget.props.commandName,new h({color:$.command,bold:!0}))])})}),V=new u0({padding:M0.symmetric(1,0),child:new t({text:this.isConfirmingClearInput?new O("",void 0,[new O("Esc",new h({color:$.keybind})),new O(" again to clear input",new h({color:B.foreground,dim:!0}))]):new O("",void 0,[new O("Press ",new h({color:B.foreground,dim:!0})),new O("Enter",new h({color:$.keybind})),new O(" to submit, ",new h({color:B.foreground,dim:!0})),new O("Esc",new h({color:$.keybind})),new O(" to clear",new h({color:B.foreground,dim:!0}))])})}),U=[G,new j0({height:1}),new y1({child:D}),new j0({height:1}),V];return new u0({decoration:{border:Q4.all(new e1(B.foreground,1,"solid")),color:B.background},padding:M0.all(1),child:new m0({children:U})})}}class E$1 extends y0{props;constructor(A){super();this.props=A}createState(){return new J$A}}function Y$A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class W$1 extends T1{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)=>Y$A(J.pubDate).length));return new k5({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=S0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new j0({width:H,child:F1.end([new t({text:new O(W,new h({color:K}))})])});return new u0({decoration:V?{color:V}:void 0,padding:M0.symmetric(2,0),child:new F1({children:[new y1({child:new t({text:new O(J.title,new h({color:U})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),E(Y$A(J.pubDate),B)]})})}})}}class SB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!SB._instance)SB._instance=new SB;return SB._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()}}c8();class Z$A extends y0{props;constructor(A){super();this.props=A}createState(){return new F$A}}class F$A extends v0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=s3.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=S0.of(A),{app:B}=Q;if(this.plugins.length===0)return new t({text:new O("No plugins found.",new h({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new O(`${Y}/${J} ${w4(J,"plugin")} active`,new h({bold:!0}))),Z>0||F>0)$.push(new O(` (${Z} ${w4(Z,"command")}, ${F} ${w4(F,"tool")})`,new h({dim:!0})));$.push(new O(`
5944
+ `))}if(E)V.push(new O(" ",G)),V.push(new O("Total: ",G)),V.push(new O(Y(W),D))}return new u0({decoration:{color:F.background,border:Q4.all(new e1(F.border,1,"rounded"))},child:new t({text:new O(void 0,void 0,V)})})}l0();c8();lL();k9();C8();E7();vo();UF();EQ();WQ();oB();GR();e4();Cy();zk();O1();l0();EQ();class K$1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1777147716-gff4795"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await j70(Q,this.configService)}catch(Q){T.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 ww extends y0{props;constructor(A){super();this.props=A}createState(){return new $$A}}class $$A extends v0{_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)}}oB();class J$A extends v0{controller=new I2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new E6({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>=TY)return!1;let Q=await RX(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=S0.of(A),{colors:B,app:$}=Q,Y=F4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new mG({controller:this.controller,triggers:[new iJ],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:i4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new a4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new u0({constraints:new W1({maxHeight:Z}),padding:M0.symmetric(1,0),child:X}),G=new u0({padding:M0.symmetric(1,0),child:new t({text:new O("",void 0,[new O("Command: ",new h({color:B.foreground})),new O(this.widget.props.commandName,new h({color:$.command,bold:!0}))])})}),V=new u0({padding:M0.symmetric(1,0),child:new t({text:this.isConfirmingClearInput?new O("",void 0,[new O("Esc",new h({color:$.keybind})),new O(" again to clear input",new h({color:B.foreground,dim:!0}))]):new O("",void 0,[new O("Press ",new h({color:B.foreground,dim:!0})),new O("Enter",new h({color:$.keybind})),new O(" to submit, ",new h({color:B.foreground,dim:!0})),new O("Esc",new h({color:$.keybind})),new O(" to clear",new h({color:B.foreground,dim:!0}))])})}),U=[G,new j0({height:1}),new y1({child:D}),new j0({height:1}),V];return new u0({decoration:{border:Q4.all(new e1(B.foreground,1,"solid")),color:B.background},padding:M0.all(1),child:new m0({children:U})})}}class E$1 extends y0{props;constructor(A){super();this.props=A}createState(){return new J$A}}function Y$A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class W$1 extends T1{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)=>Y$A(J.pubDate).length));return new k5({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=S0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new j0({width:H,child:F1.end([new t({text:new O(W,new h({color:K}))})])});return new u0({decoration:V?{color:V}:void 0,padding:M0.symmetric(2,0),child:new F1({children:[new y1({child:new t({text:new O(J.title,new h({color:U})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),E(Y$A(J.pubDate),B)]})})}})}}class SB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!SB._instance)SB._instance=new SB;return SB._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()}}c8();class Z$A extends y0{props;constructor(A){super();this.props=A}createState(){return new F$A}}class F$A extends v0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=s3.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=S0.of(A),{app:B}=Q;if(this.plugins.length===0)return new t({text:new O("No plugins found.",new h({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new O(`${Y}/${J} ${w4(J,"plugin")} active`,new h({bold:!0}))),Z>0||F>0)$.push(new O(` (${Z} ${w4(Z,"command")}, ${F} ${w4(F,"tool")})`,new h({dim:!0})));$.push(new O(`
5945
5945
 
5946
5946
  `));for(let X of this.plugins){let{icon:D,color:G}=this.statusIcon(X.status),V=this.getRelativePath(X.uri.toString());if($.push(new O(`${D} `,new h({color:G}))),$.push(new O(V,new h({bold:!0}))),$.push(new O(` ${X.status}`,new h({dim:!0}))),$.push(new O(`
5947
5947
  `)),X.status==="active"&&X.registeredEvents.length>0)$.push(new O(" Events: ",new h({dim:!0}))),$.push(new O(X.registeredEvents.join(", "),new h({color:B.link}))),$.push(new O(`
@@ -6123,7 +6123,7 @@ ${o.content||""}`:o.content||"",P0=[],b0=o.baseDir.startsWith("file://")?cz0(o.b
6123
6123
  `)}function YZA(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=Y54({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),X=await lA.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+`
6124
6124
  `),process.exit(1)}process.stdout.write(await SU8(X.result.displayText)+`
6125
6125
  `),process.exit(0)})}var tH8=D40.join(VF,"logs","headless.log"),MZ1=D40.join(rb,"device-id.json"),eH8=`cli-tui-${vDA(16).toString("hex")}`;async function Az8(){for(let A of aL)try{if((await A.listConfigs()).length>0)return A}catch(Q){T.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => H4(ah(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){_$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
6126
- `)}function Qz8(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 J7(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")FQ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")FQ("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)FQ("internal.model",Bz8(Q.model))}function jDA(A){let Q=A.indexOf(":");if(Q===-1)throw new K4(`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 K4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Bz8(A){if(!A.includes("="))return jDA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new K4(`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 K4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new K4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);jDA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new K4("No valid model overrides found in --model flag value.",1);return Q}function $z8(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 Jz8(A){try{return await yDA(A,"utf-8")}catch{return A}}async function RDA(A,Q,B){let $=$z8(A,Q);if(!$)return;let J=gA(B)?B.features:[],Y=gA(B)?B.user.email:void 0;if(!oh(J,J9.HARNESS_SYSTEM_PROMPT)&&!(Y&&U7(Y)))throw new K4("You are not allowed to do this.",1);FQ("systemPrompt",await Jz8($))}function oh(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function Yz8(A){return A!=="pending"}function sh(A){if(!gA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Zz8(A){let Q=sh(A);if(Q)return Q.id;if(UW(A))throw Error(A.error.message);throw Error("unreachable")}function Fz8(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 Xz8(A){let $=Fz8(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 K4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function OZ1(A,Q){let B=X51(Error(A.error.message));if(B.message===u7.networkOffline||B.message===u7.networkTimeout)return Xz8(Q);if(B.message!==u7.internalBug)return new K4(B.message,1,B.suggestion);return new K4(A.error.message.replace(/^Error: /,""),1)}var PDA=[{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??zX,description:`Custom settings file path (overrides the default location ${zX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(T).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${jt})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:w9(),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:cL.SMART.key,description:`Set the agent mode (${s$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:s$().map((A)=>A.mode).concat("large","deep","frontier")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neo",long:"neo",type:"switch",description:"Use the Neo TUI",hidden:!0},{name:"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}],_DA=(A)=>("deprecated"in A)&&A.deprecated===!0,Dz8=(A)=>("hidden"in A)&&A.hidden===!0,Gz8=(A)=>("default"in A),Vz8=(A)=>("default"in A)?A.default:void 0,xDA=[{name:"toggle-skills-count",entryPoint:tQ1}];function Uz8(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 K4(u7.unknownCommand(B),1,Z)}}async function xq0(A){return{...A,getThreadEnvironment:HH,osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new mO(A.fileSystem),generateThreadTitle:qK4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>YJ(A.configService),pluginService:A.pluginService}}function fDA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:HH,filesystem:A.fileSystem,threadService:A.threadService}}var bDA="code-tour";function LZ1(A){return A.filter((Q)=>Q.name!==bDA)}function Kz8(A){return{...A,skills:A.skills.pipe(w1(LZ1)),getSkills:async()=>LZ1(await A.getSkills()),getSkill:async(Q)=>Q===bDA?void 0:A.getSkill(Q),getSkillsList:async()=>{let Q=LZ1(await A.getSkills());return zy(Q)}}}var vq0=Z1.file(sH8.homedir()),jZ1=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(vq0,".config");function Ez8(A){return hy4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(vU0())yU0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())uy4();else pr(Q);let B=_P(),$=Se();if((!B||$||BK0())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(SG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(SG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(_P()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function e2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;m54("0.0.1777144048-gff4795");let Y=bk({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:vq0,userConfigDir:jZ1});o9A(Y);let Z=await Y.getLatest();T.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let m=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(m),T.info("API key lookup before login",{found:Boolean(m),ampURL:A.ampURL,deferAuth:$}),!m)if($)T.info("No API key found, continuing startup with deferred auth");else{E5.write(`No API key found. Starting login flow...
6126
+ `)}function Qz8(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 J7(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")FQ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")FQ("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)FQ("internal.model",Bz8(Q.model))}function jDA(A){let Q=A.indexOf(":");if(Q===-1)throw new K4(`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 K4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Bz8(A){if(!A.includes("="))return jDA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new K4(`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 K4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new K4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);jDA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new K4("No valid model overrides found in --model flag value.",1);return Q}function $z8(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 Jz8(A){try{return await yDA(A,"utf-8")}catch{return A}}async function RDA(A,Q,B){let $=$z8(A,Q);if(!$)return;let J=gA(B)?B.features:[],Y=gA(B)?B.user.email:void 0;if(!oh(J,J9.HARNESS_SYSTEM_PROMPT)&&!(Y&&U7(Y)))throw new K4("You are not allowed to do this.",1);FQ("systemPrompt",await Jz8($))}function oh(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function Yz8(A){return A!=="pending"}function sh(A){if(!gA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Zz8(A){let Q=sh(A);if(Q)return Q.id;if(UW(A))throw Error(A.error.message);throw Error("unreachable")}function Fz8(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 Xz8(A){let $=Fz8(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 K4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function OZ1(A,Q){let B=X51(Error(A.error.message));if(B.message===u7.networkOffline||B.message===u7.networkTimeout)return Xz8(Q);if(B.message!==u7.internalBug)return new K4(B.message,1,B.suggestion);return new K4(A.error.message.replace(/^Error: /,""),1)}var PDA=[{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??zX,description:`Custom settings file path (overrides the default location ${zX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(T).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${jt})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:w9(),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:cL.SMART.key,description:`Set the agent mode (${s$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:s$().map((A)=>A.mode).concat("large","deep","frontier")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neo",long:"neo",type:"switch",description:"Use the Neo TUI",hidden:!0},{name:"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}],_DA=(A)=>("deprecated"in A)&&A.deprecated===!0,Dz8=(A)=>("hidden"in A)&&A.hidden===!0,Gz8=(A)=>("default"in A),Vz8=(A)=>("default"in A)?A.default:void 0,xDA=[{name:"toggle-skills-count",entryPoint:tQ1}];function Uz8(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 K4(u7.unknownCommand(B),1,Z)}}async function xq0(A){return{...A,getThreadEnvironment:HH,osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new mO(A.fileSystem),generateThreadTitle:qK4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>YJ(A.configService),pluginService:A.pluginService}}function fDA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:HH,filesystem:A.fileSystem,threadService:A.threadService}}var bDA="code-tour";function LZ1(A){return A.filter((Q)=>Q.name!==bDA)}function Kz8(A){return{...A,skills:A.skills.pipe(w1(LZ1)),getSkills:async()=>LZ1(await A.getSkills()),getSkill:async(Q)=>Q===bDA?void 0:A.getSkill(Q),getSkillsList:async()=>{let Q=LZ1(await A.getSkills());return zy(Q)}}}var vq0=Z1.file(sH8.homedir()),jZ1=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(vq0,".config");function Ez8(A){return hy4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(vU0())yU0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())uy4();else pr(Q);let B=_P(),$=Se();if((!B||$||BK0())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(SG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(SG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(_P()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function e2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;m54("0.0.1777147716-gff4795");let Y=bk({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:vq0,userConfigDir:jZ1});o9A(Y);let Z=await Y.getLatest();T.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let m=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(m),T.info("API key lookup before login",{found:Boolean(m),ampURL:A.ampURL,deferAuth:$}),!m)if($)T.info("No API key found, continuing startup with deferred auth");else{E5.write(`No API key found. Starting login flow...
6127
6127
  `);let p=await Wz8(A),u=await A.secrets.get("apiKey",A.ampURL);if(T.info("Login flow completed",{success:p,storedKeyPresent:Boolean(u),ampURL:A.ampURL}),!p)await LK(),process.exit(1);F=!0}}{let m=await Y.getLatest(),p=m.settings.url,u=m.secrets.isSet?.[p];T.info("Config secrets state after login",{configURL:p,apiKeySet:u?.apiKey??!1})}let X=k1(YJ(Y).pipe(N5(Yz8))),D=$?"pending":await X;if(!$)T.info("Server status resolved",{status:"ready",isAuthenticated:gA(D),isError:UW(D),errorMessage:UW(D)?D.error.message:void 0});let G=X.then((m)=>Zz8(m));G.catch(()=>{return});let{toolService:V,dispose:U}=WD0({configService:Y}),K=new Map,E=()=>K.clear(),W=new Wm0(Y,A.settings.getWorkspaceRootPath()),H=n$0({configService:Y,filesystem:k8}),z=RF4({configService:Y,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(m,p,u)=>{let a=`${m}:${p}`,d=K.get(a);if(d)return T.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:p}),d;T.debug("Creating OAuth provider for server",{serverName:m,serverUrl:p});let s=(async()=>{let W0=new AO(A.secrets),n=await W0.getClientInfo(m,p),A0=u?.scopes??n?.scopes,D0=Nr4();T.info("OAuth headless mode check",{useHeadless:D0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:E5.isTTY});let z0;if(D0)z0=A.executeMode?qr4():zr4(m);let B0=new sf0({storage:W0,serverName:m,serverUrl:p,clientId:u?.clientId??n?.clientId,clientSecret:u?.clientSecret??n?.clientSecret,authUrl:u?.authUrl??n?.authUrl,tokenUrl:u?.tokenUrl??n?.tokenUrl,scopes:A0,headlessAuthHandler:z0});return T.debug("OAuth provider created",{serverName:m,serverUrl:p,hasManualClientId:!!(u?.clientId??n?.clientId),willUseDCR:!(u?.clientId??n?.clientId),scopes:A0,headlessMode:D0,executeMode:A.executeMode}),B0})();return K.set(a,s),s}}),q=Et0({configService:Y,filesystem:k8,spawn:uX0}),N;if(J)N=new Map;else if(A.executeMode){let m=await Qk4({toolService:V,providers:[z,q],initialTimeout:15000});N=m.registrations;for(let[p,u]of m.initErrors)T.warn(`${p} provider initialization slow or failed:`,u)}else N=Wt0({toolService:V,providers:[z,q]});if(Q.jetbrains)iL("JetBrains");else if(Q.ide&&Bs4())iL("VS Code");else if(Q.ide&&$s4())iL("Neovim");else if(Q.ide){let m=await Az8();if(m){let p=p90(m.ideName);if(p)iL(p)}}if(A.executeMode)p54(!0);let I,C=i8.status.pipe(w1((m)=>Boolean(m.connected&&m.authenticated&&m.ideName&&z84(m.ideName))),l4()).subscribe((m)=>{if(m){if(!I)I=V.registerTool(Ak4)}else I?.dispose(),I=void 0}),w;if(!A.executeMode){let m=await A.settings.get("fuzzy.alwaysIncludePaths")??[];w=new ab(process.cwd(),{alwaysIncludePaths:m},!0)}else w=new class extends ab{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=new Nd0(lO(Y),{maxThreads:200});T.info("Starting Amp background services");let j=new JB1,P=process.env.PLUGINS??"off",R=Q.headless?v9A():void 0,b=R??new pW0({configService:Y}),g=b instanceof pW0?b:void 0;if(g)g.pluginExecutorKind="local";let f=km0({configService:Y,fileSystem:k8,platform:b,internalPlugins:xDA,pluginFilter:P}),k=CX4({pluginService:f,toolService:V}),x={configService:Y,toolService:V,mcpService:z,skillService:H,toolboxService:q,trustStore:W,threadService:M,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:w,fileSystem:k8,terminal:j,pluginService:f,pluginPlatform:g,headlessPluginPlatform:R,serverStatus:D,serverStatusPromise:X,viewerUserIDPromise:G,hasAPIKeyAtStartup:F};return{...x,async asyncDispose(){if(x.mcpService.hasAuthenticatingClients())T.info("Waiting for OAuth authentication to complete before exit..."),await x.mcpService.waitForAuthentication();for(let m of N.values())m.dispose();await x.mcpService.dispose(),E(),await x.threadService.asyncDispose(),x.configService.unsubscribe(),U(),x.fuzzyServer.dispose(),x.settingsStorage[Symbol.dispose](),C.unsubscribe(),I?.dispose(),k.dispose(),await x.pluginService.dispose()}}}async function Wz8(A){if(!A.executeMode){if(!await wK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return E5.write(`Login cancelled. Run the command again to retry.
6128
6128
  `),!1}return await uDA(A)}async function uDA(A){let Q=vDA(32).toString("hex"),B=await Ju(A.ampURL,Q),$=new AbortController;try{await UD(B,$.signal)}catch(Y){T.error("Error opening browser",{error:Y})}let J=await Ju(A.ampURL,Q,!1);E5.write(`If your browser does not open automatically, visit:
6129
6129
 
@@ -6131,7 +6131,7 @@ ${n0.blue.bold(J)}
6131
6131
 
6132
6132
  `);try{return await He4(A.ampURL,Q,A.secrets,$),E5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return T.error("Login failed",{error:Y}),_$.write(`
6133
6133
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6134
- `),!1}}function Hz8(A){let Q=new uI().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)ZP(),process.exit(0);let W=E.originalError??E;sn4(W)}),y0A(Q,{version:"0.0.1777144048-gff4795",buildTimestamp:"2026-04-25T19:11:23.482Z",buildType:"'release'"}),Q.addHelpText("after",er4()),Q.configureHelp({formatHelp:As4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await Mz8(z)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await wz8(z,await lt(H,z.settings))}),Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await K8(z);await Dr4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await Gr4(z.ampURL,z.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(E)=>{await qt4({raw:E.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
6134
+ `),!1}}function Hz8(A){let Q=new uI().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)ZP(),process.exit(0);let W=E.originalError??E;sn4(W)}),y0A(Q,{version:"0.0.1777147716-gff4795",buildTimestamp:"2026-04-25T20:12:25.387Z",buildType:"'release'"}),Q.addHelpText("after",er4()),Q.configureHelp({formatHelp:As4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await Mz8(z)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await wz8(z,await lt(H,z.settings))}),Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await K8(z);await Dr4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await Gr4(z.ampURL,z.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(E)=>{await qt4({raw:E.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
6135
6135
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(E,W,H)=>{if(E&&W.apply)throw new K4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let z=W.apply??E;if(!z||z.trim().length===0)E5.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.
6136
6136
 
6137
6137
  `),H.outputHelp(),process.exit(0);let q=I3(z)??EB(z),N=H.optsWithGlobals(),I=await K8(N);J7(H,N);let C=await e2(I,N),w=!1;try{if(W.checkout&&W.skipCheckout)throw new K4("Choose either --checkout or --skip-checkout, not both.",1);if(UW(C.serverStatus))throw OZ1(C.serverStatus,I.ampURL);let M=gA(C.serverStatus)?C.serverStatus.features:void 0;if(!oh(M,J9.V2))throw new K4("live-sync is not enabled for your user",1);await Ye4({ampURL:I.ampURL,threadId:q,configService:C.configService,threadService:C.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof W.apply==="string",checkoutMode:W.checkout?"always":W.skipCheckout?"never":"prompt",promptForYesNo:wK0}),w=!0}finally{if(await C.asyncDispose(),w)process.exit(0)}});let B=async(E,W,H)=>{bk({storage:W.settings,secretStorage:W.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:W.ampURL,homeDir:vq0,userConfigDir:jZ1});let z={...W,executeMode:!1};await yq0(z,{...E,openThreadSwitcher:!0},H,A)},$=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await kDA(H,z,W)});$.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await yz8(H,z,W)}),$.command("continue [threadIDOrURL]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await K8(z);if(W.pick)_$.write(`${n0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -6165,8 +6165,8 @@ ${I}
6165
6165
 
6166
6166
  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 zz8(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await lW0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await lW0()).trimEnd(),stdinInput:null}}function qz8(A,Q,B){if(A.streamJson&&!Q)throw new K4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new K4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new K4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new K4("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 K4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new K4("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 K4("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 K4("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"
6167
6167
  Or pipe via stdin: echo "your message" | amp --execute`)}async function yq0(A,Q,B,$){let J=process.hrtime.bigint(),Y=(i,o)=>{let e=Number(process.hrtime.bigint()-o)/1e6,Y0=vd4();T.info("Startup phase",{phase:i,phaseMs:Math.round(e),sinceMainMs:Y0===null?void 0:Math.round(Y0)})},{userInput:Z,stdinInput:F}=await zz8(Q),X=!!Q.streamJson||!!Q.streamJsonThinking;qz8({...Q,streamJson:X},A.executeMode,Z),J7(B,Q);let D=process.hrtime.bigint(),G=Boolean(await A.secrets.get("apiKey",A.ampURL)),V=!A.executeMode&&!Q.headless&&G;T.info("Interactive auth startup mode",{deferInteractiveAuth:V,hasAPIKeyAtStartup:G,executeMode:A.executeMode,headless:Boolean(Q.headless)});let U=await e2(A,Q,{deferAuth:V});Y("runMainThread:createThreadDependencies",D);let{serverStatus:K}=U;if(!V&&UW(K))throw OZ1(K,A.ampURL);let E=gA(K)?K:null,W=E?.user.email,H=!!(W&&U7(W));if(!V)await RDA(B,Q,K);let z=sh(K),q=z?.features??[],N=z?.team??null,I=wW0(Q,z);if(I instanceof Error)o5(I.message);if(E&&!Hc(Q.mode,W))throw new K4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(Q.headless){if(process.env.AMP_EXECUTOR!=="1"&&(!W||!U7(W)))throw new K4("Headless executor mode is only available for Amp employees",1);let o=await U.secretStorage.get("apiKey",A.ampURL);if(!o)throw new K4("API key required for headless mode. Please run `amp login` first.",1);let e=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(e&&!e$(e))throw new K4(`Invalid thread ID: ${e}`,1);let Y0=e?void 0:await kz8({dependencies:U,apiKey:o,visibility:I??void 0}),$0=e??Y0?.threadId;if(!$0)throw new K4("Failed to resolve headless thread ID",1);let K0=await Mr4($0);if(K0.status==="already-running")await U.asyncDispose(),await LK(),process.exit(0);try{await Er4({ampURL:A.ampURL,apiKey:o,workspaceRoot:process.cwd(),threadId:$0,ownerUserId:Y0?.ownerUserId,threadVersion:Y0?.threadVersion,agentMode:Y0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform})}finally{await K0.release(),await U.asyncDispose()}await LK(),process.exit(0)}let C=Q.threadId&&e$(Q.threadId)?Q.threadId:void 0,w=Q.observe?I3(Q.observe)??EB(Q.observe):void 0,M=V?await U.serverStatusPromise:K,j=gA(M)&&oh(M.features,J9.NEO_TUI);if((j||Q.neo||!!w||!1)&&!A.executeMode&&!Q.takeMeBack){if((Q.neo||w)&&!j&&(!gA(M)||!U7(M.user.email)))throw new K4(Q.observe?"--observe is only available for Amp employees":"--neo is only available for Amp employees",1);let i=await U.secretStorage.get("apiKey",A.ampURL);if(!i)throw new K4("API key required. Please run `amp login` first.",1);let o=lO(U.configService),e=new K_(U.fuzzyServer),Y0=process.cwd();await sQ1({ampURL:A.ampURL,apiKey:i,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??xJ(A.ampURL),configService:U.configService,toolService:U.toolService,skillService:U.skillService,mcpService:U.mcpService,readFileSystemDirectory:({uri:$0})=>IC({fileSystem:U.fileSystem,workspaceRoot:Y0},$0),completionBuilder:e,workspaceRoot:Y0,listThreads:()=>o.listThreads(),getThreadFromServer:($0)=>o.getThread($0),isInternalUser:gA(M)&&U7(M.user.email),settingsFilePath:U.settingsStorage.getSettingsFilePath()},{initialThreadID:w??C,initialUserInput:Z||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!w});return}let R=gA(M)&&oh(M.features,J9.THREAD_ACTORS_TUI);if(A.executeMode&&!Q.takeMeBack&&R){let i=await U.secretStorage.get("apiKey",A.ampURL);if(!i)throw new K4("API key required. Please run `amp login` first.",1);Y31(U.mcpService,A.settings);try{let o=await ko4({apiKey:i,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:U,userInput:Z,stdinInput:F,stats:!!Q.stats,streamJson:X,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,labels:Q.label,initialThreadID:C});if(await rh(o,"execute"),Q.archive)await U.threadService.archive(o,!0)}finally{await U.asyncDispose()}await LK(),process.exit(0)}if(!A.executeMode&&!Q.headless)U.skillService=Kz8(U.skillService);D=process.hrtime.bigint();let g=await xq0(U);Y("runMainThread:createWorkerDeps",D);let f=A.executeMode?void 0:async(i)=>rh(i,"interactive"),k={threadService:U.threadService,workerDeps:g,createThread:async(i)=>{let o=V?await U.serverStatusPromise:K,e=await JU0(A.settings,process.cwd(),sh(o),I);if(e instanceof Error)o5(e.message);return rJ1(g,{threadMeta:e?gG(e):void 0,agentMode:i??Q.mode,onFirstAssistantMessage:f})},validateThreadOwnership:async(i,o)=>{if(o?.nonBlockingOwnershipCheck){TDA(i,U.configService,U.viewerUserIDPromise).catch((e)=>{if(e instanceof K4){if(o.onOwnershipError){o.onOwnershipError(e,i);return}kH(e,i);return}T.warn("Failed to validate thread ownership in CLI, allowing to open",{error:e})});return}try{await TDA(i,U.configService,U.viewerUserIDPromise)}catch(e){if(e instanceof K4)throw e;T.warn("Failed to validate thread ownership in CLI, allowing to open",{error:e})}},switchThreadVisibility:I,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:f,handleError:kH},x=async()=>{try{return QZA(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(i){if(i instanceof K4)throw i;throw await kH(i,Q.threadId),Error("handleError should have called process.exit()")}};if(Q.format==="jsonl")_$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6168
- `),await LK(),process.exit(1);let m=(async()=>{if(V){T.info("Skipping initial free tier status fetch until auth is complete");return}try{let i=await U.configService.getLatest(),o=Jc(i),e=await lA.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(o)});if(e.ok)return T.info("User free tier status:",e),e.result;return}catch(i){T.error("Failed to fetch free tier status:",i);return}})(),u=!A.executeMode?new EB1:null,a,d=null;if(u)a=u,d=(async()=>{let i=V?await U.serverStatusPromise:U.serverStatus;if(UW(i))throw OZ1(i,A.ampURL);await RDA(B,Q,i);let o=process.hrtime.bigint(),e=await x();if(Y("runMainThread:createThreadPool",o),u.attach(e),Z){let Y0=await k1(e.threadHandles$);if(!Y0)throw new K4("No active thread is available yet.",1);await Y0.sendMessage({content:[{type:"text",text:Z}]})}})(),d.catch(async(i)=>{let o=i instanceof Error?i:Error(String(i));u.setInitError(o),await kH(i,Q.threadId)});else D=process.hrtime.bigint(),a=await x(),Y("runMainThread:createThreadPool",D);let s=Q.notifications!==void 0?Q.notifications:!A.executeMode,W0=E!==null&&oh(E.features,J9.TUI_VOICE_NOTIF);if(V)U.serverStatusPromise.then((i)=>{W0=gA(i)&&oh(i.features,J9.TUI_VOICE_NOTIF)}).catch((i)=>{T.debug("Failed to resolve TUI voice notification feature flag",{error:i})});D=process.hrtime.bigint();let n=await U.configService.getLatest();if(Y("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),Ez8({configService:U.configService,threadService:U.threadService,config:n,useNotificationsForService:s,isTUIVoiceNotifEnabled:()=>W0,threadViewStates$:()=>a.threadHandles$.pipe(c4((i)=>{if(!i)return g0.of({});return u6(i.thread$,i.threadViewState$).pipe(w1(([o,e])=>({[o.id]:e})))}))}),Y("runMainThread:createCliNotificationService",D),A.executeMode){Y31(U.mcpService,A.settings);let i={userInput:Z,stdinInput:F,dependencies:U,streamJson:X,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,labels:Q.label},o=await qa4({threadPool:a,...i});if(await rh(o,"execute"),Q.archive)await U.threadService.archive(o,!0);await U.asyncDispose(),process.exit(0)}let A0=!1,D0=!1;if(Q.jetbrains||Q.ide){await d90();let i=await ID({jetbrainsOnly:Q.jetbrains});if(i.length===0){if(Q.jetbrains)A0=!await U.configService.get("jetbrains.skipInstall")}else if(i.length===1){let o=i[0];if(o)i8.selectConfig(o)}else D0=!0}D=process.hrtime.bigint();let z0=O81("0.0.1777144048-gff4795",U.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let B0=new Z31(U.mcpService,A.settings.getWorkspaceRootPath());if(Y("runMainThread:createMcpTrustHandler",D),Z&&A.executeMode){let i=await k1(a.threadHandles$);if(!i)throw new K4("No active thread is available yet.",1);await i.sendMessage({content:[{type:"text",text:Z}]})}D=process.hrtime.bigint();let Z0=await Yu();Y("runMainThread:loadSessionState",D),T.info("Loaded session state:",Z0);let c={...Z0,launchCount:Z0.launchCount+1};NX((i)=>({...i,launchCount:i.launchCount+1}));try{if(D=process.hrtime.bigint(),await t7A({history:new ft,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:lA,threadPool:a,createSystemPromptDeps:async()=>fDA(U),ideClient:i8,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:B0,updateService:z0,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:A0,showIdePickerHint:D0,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:eH8,logFile:{path:$},sessionState:c,freeTierStatusPromise:m,workspace:N??null,features:q,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,buildTimestamp:"2026-04-25T19:11:23.482Z"},(i)=>new CB1({...i,threadPool:i.threadPool},(o)=>new aJ1({...o,threadState:o.threadState}))),Y("runMainThread:mountApp-returned",D),d)await d}finally{await a.dispose().catch((i)=>{T.error("Failed to dispose thread pool during shutdown",i)})}await U.asyncDispose(),Y("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function K8(A){if(T.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)_$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6169
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;T.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await kF4({get:async(F)=>{if(F!==Fi)return;try{let X=await yDA(MZ1,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==Fi)return;await oH8(D40.dirname(MZ1),{recursive:!0}),await rH8(MZ1,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:TB0()});d54($);let J=await hU0({...A,workspaceTrust:{current:!0,changes:jx0},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 je4(A.mcpConfig);J=Re4(J,F)}let Y=D40.dirname(J.getSettingsFilePath());by4(rb,Y),J=w64(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=T9;if(T.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!xq(Z))T.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:PK0(await lt(A,J))}}function Nz8(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 Iz8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=D40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?tH8:jt));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function Cz8(){kd4();let A=Nz8(process.argv),Q=Iz8(process.argv,A),B=pn4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(Qz8(T),T.info("Starting Amp CLI.",{version:"0.0.1777144048-gff4795",buildTimestamp:"2026-04-25T19:11:23.482Z"}),process.platform==="win32"&&WP())Cs4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new K4(u7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Hz8(B).parseAsync(process.argv)}xy4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await Cz8().catch(kH)});async function wz8(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"),E5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6168
+ `),await LK(),process.exit(1);let m=(async()=>{if(V){T.info("Skipping initial free tier status fetch until auth is complete");return}try{let i=await U.configService.getLatest(),o=Jc(i),e=await lA.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(o)});if(e.ok)return T.info("User free tier status:",e),e.result;return}catch(i){T.error("Failed to fetch free tier status:",i);return}})(),u=!A.executeMode?new EB1:null,a,d=null;if(u)a=u,d=(async()=>{let i=V?await U.serverStatusPromise:U.serverStatus;if(UW(i))throw OZ1(i,A.ampURL);await RDA(B,Q,i);let o=process.hrtime.bigint(),e=await x();if(Y("runMainThread:createThreadPool",o),u.attach(e),Z){let Y0=await k1(e.threadHandles$);if(!Y0)throw new K4("No active thread is available yet.",1);await Y0.sendMessage({content:[{type:"text",text:Z}]})}})(),d.catch(async(i)=>{let o=i instanceof Error?i:Error(String(i));u.setInitError(o),await kH(i,Q.threadId)});else D=process.hrtime.bigint(),a=await x(),Y("runMainThread:createThreadPool",D);let s=Q.notifications!==void 0?Q.notifications:!A.executeMode,W0=E!==null&&oh(E.features,J9.TUI_VOICE_NOTIF);if(V)U.serverStatusPromise.then((i)=>{W0=gA(i)&&oh(i.features,J9.TUI_VOICE_NOTIF)}).catch((i)=>{T.debug("Failed to resolve TUI voice notification feature flag",{error:i})});D=process.hrtime.bigint();let n=await U.configService.getLatest();if(Y("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),Ez8({configService:U.configService,threadService:U.threadService,config:n,useNotificationsForService:s,isTUIVoiceNotifEnabled:()=>W0,threadViewStates$:()=>a.threadHandles$.pipe(c4((i)=>{if(!i)return g0.of({});return u6(i.thread$,i.threadViewState$).pipe(w1(([o,e])=>({[o.id]:e})))}))}),Y("runMainThread:createCliNotificationService",D),A.executeMode){Y31(U.mcpService,A.settings);let i={userInput:Z,stdinInput:F,dependencies:U,streamJson:X,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,labels:Q.label},o=await qa4({threadPool:a,...i});if(await rh(o,"execute"),Q.archive)await U.threadService.archive(o,!0);await U.asyncDispose(),process.exit(0)}let A0=!1,D0=!1;if(Q.jetbrains||Q.ide){await d90();let i=await ID({jetbrainsOnly:Q.jetbrains});if(i.length===0){if(Q.jetbrains)A0=!await U.configService.get("jetbrains.skipInstall")}else if(i.length===1){let o=i[0];if(o)i8.selectConfig(o)}else D0=!0}D=process.hrtime.bigint();let z0=O81("0.0.1777147716-gff4795",U.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let B0=new Z31(U.mcpService,A.settings.getWorkspaceRootPath());if(Y("runMainThread:createMcpTrustHandler",D),Z&&A.executeMode){let i=await k1(a.threadHandles$);if(!i)throw new K4("No active thread is available yet.",1);await i.sendMessage({content:[{type:"text",text:Z}]})}D=process.hrtime.bigint();let Z0=await Yu();Y("runMainThread:loadSessionState",D),T.info("Loaded session state:",Z0);let c={...Z0,launchCount:Z0.launchCount+1};NX((i)=>({...i,launchCount:i.launchCount+1}));try{if(D=process.hrtime.bigint(),await t7A({history:new ft,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:lA,threadPool:a,createSystemPromptDeps:async()=>fDA(U),ideClient:i8,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:B0,updateService:z0,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:A0,showIdePickerHint:D0,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:eH8,logFile:{path:$},sessionState:c,freeTierStatusPromise:m,workspace:N??null,features:q,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,buildTimestamp:"2026-04-25T20:12:25.387Z"},(i)=>new CB1({...i,threadPool:i.threadPool},(o)=>new aJ1({...o,threadState:o.threadState}))),Y("runMainThread:mountApp-returned",D),d)await d}finally{await a.dispose().catch((i)=>{T.error("Failed to dispose thread pool during shutdown",i)})}await U.asyncDispose(),Y("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function K8(A){if(T.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)_$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6169
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;T.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await kF4({get:async(F)=>{if(F!==Fi)return;try{let X=await yDA(MZ1,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==Fi)return;await oH8(D40.dirname(MZ1),{recursive:!0}),await rH8(MZ1,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:TB0()});d54($);let J=await hU0({...A,workspaceTrust:{current:!0,changes:jx0},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 je4(A.mcpConfig);J=Re4(J,F)}let Y=D40.dirname(J.getSettingsFilePath());by4(rb,Y),J=w64(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=T9;if(T.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!xq(Z))T.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:PK0(await lt(A,J))}}function Nz8(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 Iz8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=D40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?tH8:jt));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function Cz8(){kd4();let A=Nz8(process.argv),Q=Iz8(process.argv,A),B=pn4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(Qz8(T),T.info("Starting Amp CLI.",{version:"0.0.1777147716-gff4795",buildTimestamp:"2026-04-25T20:12:25.387Z"}),process.platform==="win32"&&WP())Cs4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new K4(u7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Hz8(B).parseAsync(process.argv)}xy4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await Cz8().catch(kH)});async function wz8(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"),E5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6170
6170
  `);else if(!xq(A.ampURL))E5.write(`Logging in to ${new URL(A.ampURL).hostname}
6171
6171
  `);let $=process.env.AMP_API_KEY;if($)E5.write(`API key found in environment variable, storing...
6172
6172
  `),await Q.set("apiKey",$,A.ampURL),E5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1777144048-gff4795",
3
+ "version": "0.0.1777147716-gff4795",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {