@sourcegraph/amp 0.0.1779959155-g362e01 → 0.0.1779973320-g362e01

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 +2 -2
package/dist/main.js CHANGED
@@ -4659,13 +4659,13 @@ ${z}`))}},error:(V)=>{if(!G)G=!0,Y(Error(`Failed to spawn brew: ${V.message}`))}
4659
4659
  ${z}`;if(F==="pnpm"&&z.includes("Unable to find the global bin directory"))K+=`
4660
4660
 
4661
4661
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4662
- npm install -g ${E}`;Y(Error(K))}},error:(V)=>{if(!I)I=!0,Y(Error(`Failed to spawn ${F}: ${V.message}`))},complete:()=>{if(!I)I=!0,U()}})})}b0();b0();Ig();var he6="@ampcode/cli";async function C50(A,Q,$=he6){let D=`${Q||"https://registry.npmjs.org"}/${$}/latest`,E=new AbortController,F=setTimeout(()=>E.abort(),5000);try{let J=await fetch(D,{signal:E.signal});if(!J.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let U=await J.json(),Y=U.version??U["dist-tags"]?.latest;if(!Y)return{hasUpdate:!1,currentVersion:A,source:"npm"};let Z=Jp(A,Y),X=Z<0,I,G;if(U.time){let V=U.time[A],z=U.time[Y],K=Date.now();if(V)I=Math.floor((K-new Date(V).getTime())/3600000);if(z)G=Math.floor((K-new Date(z).getTime())/3600000)}return _.info("NPM version comparison",{currentVersion:A,latestVersion:Y,compareResult:Z,hasUpdate:X,currentVersionAge:I,latestVersionAge:G}),{hasUpdate:X,latestVersion:Y,currentVersion:A,currentVersionAge:I,latestVersionAge:G,source:"npm"}}catch(J){return _.debug("Error checking npm version",{error:J}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(F)}}var ge6="https://static.ampcode.com/cli/cli-version.txt";async function W50(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${ge6}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=(await B.text()).trim();if(!D||!/^\d+\.\d+\.\d+/.test(D))return{hasUpdate:!1,currentVersion:A,source:"bin"};let E=Jp(A,D),F=E<0;return _.info("Bin version comparison",{currentVersion:A,latestVersion:D,compareResult:E,hasUpdate:F}),{hasUpdate:F,latestVersion:D,currentVersion:A,source:"bin"}}catch(B){return _.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}function Jp(A,Q){let $=(F)=>{let[J,U]=F.split("-");return{parts:J?.split(".").map(Number)||[],label:U}},B=$(A),D=$(Q),E=Math.max(B.parts.length,D.parts.length);for(let F=0;F<E;F++){let J=B.parts[F]||0,U=D.parts[F]||0;if(J<U)return-1;if(J>U)return 1}if(B.label===D.label)return 0;if(!B.label&&D.label)return 1;if(B.label&&!D.label)return-1;if(B.label&&D.label)return B.label<D.label?-1:1;return 0}function Up(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,E=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],F=B!==void 0?yV(B):void 0;return{sha:E,timestamp:B,age:F}}catch{return null}}LA();b0();import{readFile as me6,realpath as de6}from"node:fs/promises";import{dirname as MV4,join as ce6}from"node:path";async function LV4(A){switch(A){case"binary":case"brew":return pe6(Ep());case"npm":case"pnpm":case"yarn":case"bun":return le6()}}async function pe6(A){let Q=await gz(A,["--version"],5000);if(Q.reason!=="success")return _.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function le6(){try{let A=process.argv[1];if(!A)return null;let Q=await de6(A),$=MV4(MV4(Q));return await ie6(ce6($,"package.json"))}catch(A){return _.debug("failed to read installed version from package.json",{error:A}),null}}async function ie6(A){let Q=await me6(A,"utf8"),$=JSON.parse(Q);if(!$.name||!Hy0($.name))return _.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}b0();import{spawn as ne6}from"node:child_process";function jy0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return _.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var u50=null,Yp=null;function jV4(A){return new Promise((Q)=>{let $=ne6("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(D)=>{B+=D.toString()}),$.on("close",(D,E)=>{if(D!==0||E==="SIGTERM"){Q(null);return}let F=B.trim();Q(F&&F!=="undefined"?F:null)}),$.on("error",()=>{Q(null)})})}async function H50(){if(u50)return u50;if(Yp)return Yp;Yp=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return jy0(A);let Q=await jV4("@sourcegraph:registry");if(Q)return jy0(Q);let $=await jV4("registry");if($)return jy0($);return"https://registry.npmjs.org"})();try{return u50=await Yp,u50}finally{Yp=null}}var ae6=3600000,oe6=5000;function Ry0(A,Q,$={}){let B=new L4,D=B.pipe(BQ({shouldCountRefs:!1})),E=$.startDelayMs??0,F=$.checkIntervalMs??ae6,J=!1,U=()=>{J=!0};return setImmediate(async()=>{let Y=_.getChild("update");if(E>0){if(await hV(E),J)return}let Z=D.subscribe({next:(I)=>{Y.debug("emit new state",I)}}),X=A;try{while(!J){let I=await re6(X,Q,Y,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await hV(oe6),J)return;B.next("hidden")}if(F<=0)return;let G=1000,V=F;while(V>0&&!J){let z=Math.min(G,V);await hV(z),V-=z}}}finally{Z.unsubscribe(),B.complete()}}),{state:D,dispose:U}}async function re6(A,Q,$,B){let D={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),D.stop=!0,D;let E=await Q.get("updates.mode");if(E==="disabled")return $.debug("checking disabled"),D.stop=!0,D;let F=await JY(),J=F==="binary"||F==="brew",U=J?void 0:await mz();$.debug("checking",{currentVersion:A,mode:E,packageManager:F,isBinaryDistribution:J,npmPackageName:U});let Y;if(J)Y=await W50(A);else{let I=await H50();Y=await C50(A,I,U)}if(!(Y.latestVersion&&Y.hasUpdate))return $.debug("no update available"),D;let Z=(I)=>{B.next(I),D.emittedVisibleState=!0};if(F){let I=await LV4(F);if(I&&Jp(I,Y.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Y.latestVersion}),D.updatedTo=I,Jp(A,I)<0){let G=await xX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),Z("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),Z("updated-with-warning")}return D}}let X=()=>{if(Y.currentVersionAge!==void 0&&Y.latestVersionAge!==void 0){let I=Y.currentVersionAge-Y.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Y.currentVersionAge,latestVersionAge:Y.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!E)E=F==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:E});if(F==="brew"){if(!X())Z("update-available-brew");return D}if(F==="binary"&&process.execPath!==Ep()){if($.debug("non-standard binary path, showing warning"),!X())Z("update-available-unrecognized-path");return D}if(E==="warn"){if(!X())Z("update-available");return D}if(!F){if($.debug("auto-update not supported, falling back to warn mode"),!X())Z("update-available");return D}try{await Fp(Y.latestVersion,F),D.updatedTo=Y.latestVersion;let I=await xX(Y.latestVersion),G={from:Y.currentVersion,to:Y.latestVersion,...I};if(I.status==="same")$.info("success",G),Z("updated");else $.warn("success with warning",G),Z("updated-with-warning")}catch(I){Z("update-error")}return D}catch(E){return $.debug("check failed",{error:E}),D}}Ig();import{stderr as J2}from"node:process";function RV4(A){let Q=new kX().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(B)=>{await Wy0(B.force||!1,B.verbose||!1,"0.0.1779959155-g362e01"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new kX("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(B)=>{await ee6(B.targetVersion)});A.addCommand($)}function se6(A){let Q=Boolean(A.isTTY),$=0,B=!1;function D(){if(!Q||!B)return;A.write(`
4662
+ npm install -g ${E}`;Y(Error(K))}},error:(V)=>{if(!I)I=!0,Y(Error(`Failed to spawn ${F}: ${V.message}`))},complete:()=>{if(!I)I=!0,U()}})})}b0();b0();Ig();var he6="@ampcode/cli";async function C50(A,Q,$=he6){let D=`${Q||"https://registry.npmjs.org"}/${$}/latest`,E=new AbortController,F=setTimeout(()=>E.abort(),5000);try{let J=await fetch(D,{signal:E.signal});if(!J.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let U=await J.json(),Y=U.version??U["dist-tags"]?.latest;if(!Y)return{hasUpdate:!1,currentVersion:A,source:"npm"};let Z=Jp(A,Y),X=Z<0,I,G;if(U.time){let V=U.time[A],z=U.time[Y],K=Date.now();if(V)I=Math.floor((K-new Date(V).getTime())/3600000);if(z)G=Math.floor((K-new Date(z).getTime())/3600000)}return _.info("NPM version comparison",{currentVersion:A,latestVersion:Y,compareResult:Z,hasUpdate:X,currentVersionAge:I,latestVersionAge:G}),{hasUpdate:X,latestVersion:Y,currentVersion:A,currentVersionAge:I,latestVersionAge:G,source:"npm"}}catch(J){return _.debug("Error checking npm version",{error:J}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(F)}}var ge6="https://static.ampcode.com/cli/cli-version.txt";async function W50(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${ge6}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=(await B.text()).trim();if(!D||!/^\d+\.\d+\.\d+/.test(D))return{hasUpdate:!1,currentVersion:A,source:"bin"};let E=Jp(A,D),F=E<0;return _.info("Bin version comparison",{currentVersion:A,latestVersion:D,compareResult:E,hasUpdate:F}),{hasUpdate:F,latestVersion:D,currentVersion:A,source:"bin"}}catch(B){return _.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}function Jp(A,Q){let $=(F)=>{let[J,U]=F.split("-");return{parts:J?.split(".").map(Number)||[],label:U}},B=$(A),D=$(Q),E=Math.max(B.parts.length,D.parts.length);for(let F=0;F<E;F++){let J=B.parts[F]||0,U=D.parts[F]||0;if(J<U)return-1;if(J>U)return 1}if(B.label===D.label)return 0;if(!B.label&&D.label)return 1;if(B.label&&!D.label)return-1;if(B.label&&D.label)return B.label<D.label?-1:1;return 0}function Up(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,E=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],F=B!==void 0?yV(B):void 0;return{sha:E,timestamp:B,age:F}}catch{return null}}LA();b0();import{readFile as me6,realpath as de6}from"node:fs/promises";import{dirname as MV4,join as ce6}from"node:path";async function LV4(A){switch(A){case"binary":case"brew":return pe6(Ep());case"npm":case"pnpm":case"yarn":case"bun":return le6()}}async function pe6(A){let Q=await gz(A,["--version"],5000);if(Q.reason!=="success")return _.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function le6(){try{let A=process.argv[1];if(!A)return null;let Q=await de6(A),$=MV4(MV4(Q));return await ie6(ce6($,"package.json"))}catch(A){return _.debug("failed to read installed version from package.json",{error:A}),null}}async function ie6(A){let Q=await me6(A,"utf8"),$=JSON.parse(Q);if(!$.name||!Hy0($.name))return _.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}b0();import{spawn as ne6}from"node:child_process";function jy0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return _.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var u50=null,Yp=null;function jV4(A){return new Promise((Q)=>{let $=ne6("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(D)=>{B+=D.toString()}),$.on("close",(D,E)=>{if(D!==0||E==="SIGTERM"){Q(null);return}let F=B.trim();Q(F&&F!=="undefined"?F:null)}),$.on("error",()=>{Q(null)})})}async function H50(){if(u50)return u50;if(Yp)return Yp;Yp=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return jy0(A);let Q=await jV4("@sourcegraph:registry");if(Q)return jy0(Q);let $=await jV4("registry");if($)return jy0($);return"https://registry.npmjs.org"})();try{return u50=await Yp,u50}finally{Yp=null}}var ae6=3600000,oe6=5000;function Ry0(A,Q,$={}){let B=new L4,D=B.pipe(BQ({shouldCountRefs:!1})),E=$.startDelayMs??0,F=$.checkIntervalMs??ae6,J=!1,U=()=>{J=!0};return setImmediate(async()=>{let Y=_.getChild("update");if(E>0){if(await hV(E),J)return}let Z=D.subscribe({next:(I)=>{Y.debug("emit new state",I)}}),X=A;try{while(!J){let I=await re6(X,Q,Y,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await hV(oe6),J)return;B.next("hidden")}if(F<=0)return;let G=1000,V=F;while(V>0&&!J){let z=Math.min(G,V);await hV(z),V-=z}}}finally{Z.unsubscribe(),B.complete()}}),{state:D,dispose:U}}async function re6(A,Q,$,B){let D={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),D.stop=!0,D;let E=await Q.get("updates.mode");if(E==="disabled")return $.debug("checking disabled"),D.stop=!0,D;let F=await JY(),J=F==="binary"||F==="brew",U=J?void 0:await mz();$.debug("checking",{currentVersion:A,mode:E,packageManager:F,isBinaryDistribution:J,npmPackageName:U});let Y;if(J)Y=await W50(A);else{let I=await H50();Y=await C50(A,I,U)}if(!(Y.latestVersion&&Y.hasUpdate))return $.debug("no update available"),D;let Z=(I)=>{B.next(I),D.emittedVisibleState=!0};if(F){let I=await LV4(F);if(I&&Jp(I,Y.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Y.latestVersion}),D.updatedTo=I,Jp(A,I)<0){let G=await xX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),Z("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),Z("updated-with-warning")}return D}}let X=()=>{if(Y.currentVersionAge!==void 0&&Y.latestVersionAge!==void 0){let I=Y.currentVersionAge-Y.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Y.currentVersionAge,latestVersionAge:Y.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!E)E=F==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:E});if(F==="brew"){if(!X())Z("update-available-brew");return D}if(F==="binary"&&process.execPath!==Ep()){if($.debug("non-standard binary path, showing warning"),!X())Z("update-available-unrecognized-path");return D}if(E==="warn"){if(!X())Z("update-available");return D}if(!F){if($.debug("auto-update not supported, falling back to warn mode"),!X())Z("update-available");return D}try{await Fp(Y.latestVersion,F),D.updatedTo=Y.latestVersion;let I=await xX(Y.latestVersion),G={from:Y.currentVersion,to:Y.latestVersion,...I};if(I.status==="same")$.info("success",G),Z("updated");else $.warn("success with warning",G),Z("updated-with-warning")}catch(I){Z("update-error")}return D}catch(E){return $.debug("check failed",{error:E}),D}}Ig();import{stderr as J2}from"node:process";function RV4(A){let Q=new kX().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(B)=>{await Wy0(B.force||!1,B.verbose||!1,"0.0.1779973320-g362e01"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new kX("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(B)=>{await ee6(B.targetVersion)});A.addCommand($)}function se6(A){let Q=Boolean(A.isTTY),$=0,B=!1;function D(){if(!Q||!B)return;A.write(`
4663
4663
  `),B=!1,$=0}function E(F){if(!Q)return;let J=F.padEnd($," ");A.write(`\r${J}`),B=!0,$=J.length}return{flushProgressLine:D,renderProgress:E}}function te6(A){if(A.source==="npm"&&A.latestVersionAge!==void 0&&A.latestVersionAge>36)J2.write(f0.yellow(`The latest Amp CLI version reported by npm is older than expected. Be aware that you may be using an npm proxy with a corporate policy to delay package updates.
4664
4664
  `))}async function ee6(A){let $=process.platform==="win32"&&VN()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:B,renderProgress:D}=se6(J2);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")J2.write(f0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4665
4665
 
4666
4666
  `));try{if(!A){J2.write(f0.blue(`Checking for updates...
4667
- `));let J=!1,U;if(VN()){let Y=await W50("0.0.1779959155-g362e01");J=Y.hasUpdate,U=Y.latestVersion}else{let Y=await H50(),Z=await mz(),X=await C50("0.0.1779959155-g362e01",Y,Z);te6(X),J=X.hasUpdate,U=X.latestVersion}if(!J){let Y=Up("0.0.1779959155-g362e01"),Z=Y?.age?`released ${Y.age} ago`:`built ${yV(new Date("2026-05-28T09:10:57.457Z"))} ago`;J2.write(f0.green(`✓ Amp is already up to date on version ${"0.0.1779959155-g362e01"} (${Z})
4668
- `));let X=await xX("0.0.1779959155-g362e01",$);if(X.warning)J2.write(`
4667
+ `));let J=!1,U;if(VN()){let Y=await W50("0.0.1779973320-g362e01");J=Y.hasUpdate,U=Y.latestVersion}else{let Y=await H50(),Z=await mz(),X=await C50("0.0.1779973320-g362e01",Y,Z);te6(X),J=X.hasUpdate,U=X.latestVersion}if(!J){let Y=Up("0.0.1779973320-g362e01"),Z=Y?.age?`released ${Y.age} ago`:`built ${yV(new Date("2026-05-28T13:06:47.398Z"))} ago`;J2.write(f0.green(`✓ Amp is already up to date on version ${"0.0.1779973320-g362e01"} (${Z})
4668
+ `));let X=await xX("0.0.1779973320-g362e01",$);if(X.warning)J2.write(`
4669
4669
  `+f0.yellow(X.warning)+`
4670
4670
  `);process.exit(0)}if(!U)J2.write(f0.yellow("[WARN] could not find latest version")),process.exit(0);A=U}J2.write(f0.blue(`Updating to version ${A}...
4671
4671
  `)),await Fp(A,void 0,(J)=>{B(),J2.write(f0.dim(`Running: ${J}
@@ -4818,7 +4818,7 @@ ${B}`}async function S3Q(A,Q){if(!Q?.forceExternal&&Q?.onShowImagePreview&&su4(A
4818
4818
  `).length,D=new J0({text:new g(A,new $0({color:$}))});if(B<=mD0)return D;return new h0({width:1/0,height:mD0,child:new T3({autofocus:!1,controller:Q,child:D})})}function c8Q(){return new Map([[CA.key("PageUp"),new dD0],[CA.key("PageDown"),new Em0],[CA.ctrl("u"),new dD0],[CA.shift("Home"),new Fm0],[CA.shift("End"),new Jm0]])}function p8Q(A,Q,$){return Math.max(Q,Math.min(A,$))}var Um0=8,Hw4=1,Nw4=Um0-1;class Ym0 extends I4{}class Zm0 extends I4{}class cD0 extends I4{}class pD0 extends I4{}class Xm0 extends I4{}class Im0 extends I4{}class Gm0 extends a0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new qw4}}class qw4 extends n0{messageScroll=new Y$;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,$=l8Q(Q,this.messageScroll),B=i8Q(Q.options.message),D=B?new H4({actions:this.buildScrollActions(),child:new e6({debugLabel:"SelectDialogScrollShortcuts",shortcuts:a8Q(),child:$})}):$,E=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if(B)E.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return E.push({keys:["Esc"],label:"cancel"}),new r4({header:Q.options.title,minWidth:64,maxWidth:80,footer:E,autofocus:!1,onDismiss:Q.onCancel,child:D})}buildScrollActions(){let A=(Q)=>{let $=o8Q(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo($)};return new Map([[Ym0,new dA(()=>A(-Hw4))],[Zm0,new dA(()=>A(Hw4))],[cD0,new dA(()=>A(-Nw4))],[pD0,new dA(()=>A(Nw4))],[Xm0,new dA(()=>this.messageScroll.jumpTo(0))],[Im0,new dA(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function l8Q(A,Q){let $=A.options.options.map((D)=>({value:D,label:D})),B=Math.max(0,$.findIndex((D)=>D.value===A.options.initialValue));return new lX({options:$,selectedIndex:B,body:n8Q(A.options.message,Q),onSelect:(D)=>{if(D===null){A.onCancel();return}A.onSelect(D)},padding:e0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!0,wrapOptions:!0})}function i8Q(A){if(A===void 0)return!1;return A.split(`
4819
4819
  `).length>Um0}function n8Q(A,Q){if(A===void 0)return;let $=A.split(`
4820
4820
  `).length,B=Math.min($,Um0);return new h0({width:1/0,height:B,child:new T3({autofocus:!1,controller:Q,child:new J0({text:new g(A)})})})}function a8Q(){return new Map([[CA.key("PageUp"),new cD0],[CA.key("PageDown"),new pD0],[CA.ctrl("u"),new cD0],[CA.ctrl("d"),new pD0],[CA.ctrl("y"),new Ym0],[CA.ctrl("e"),new Zm0],[CA.shift("Home"),new Xm0],[CA.shift("End"),new Im0]])}function o8Q(A,Q,$){return Math.max(Q,Math.min(A,$))}var r8Q=3,s8Q=2097152,t8Q=new J3("PluginDialogOverlay");function lD0(A,Q,$){if($!==void 0)return{type:"response",id:A,error:$};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}function e8Q(A){let Q=new TextEncoder().encode(JSON.stringify(A)).byteLength;if(Q<=s8Q)return;throw Error(`thread.messages response is too large (${Q} bytes). Request fewer messages.`)}class Vm0{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];resolvingDialog=null;pendingOwnerUIRequests=new Map;pendingActorUIRequests=new Map;stateBackedRequestIDs=new Set;pluginUIRespondRequestCounter=0;statusItems=new Map;blockingConfirmDialog=!1;disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelOwnerUIRequests(),this.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}handlePluginMessage(A,Q){let $=A.message;if($.type==="response"){this.cancelOwnerUIRequest($.id),this.cancelActorUIRequest($.id);return}if($.type==="event"){if(this.handlePluginUIStateEvent($,Q))return;this.handlePluginEvent($);return}if(this.stateBackedRequestIDs.has($.id))return;if(!wB0($.method)){if($.method==="thread.messages")this.handleThreadMessagesRequest($,Q);return}this.handleOwnerUIRequest($,Q)}cancelOwnerUIRequests(){let A=[...this.pendingOwnerUIRequests.values(),...this.pendingActorUIRequests.values()];this.pendingOwnerUIRequests.clear(),this.pendingActorUIRequests.clear(),this.stateBackedRequestIDs.clear();for(let Q of A)Q.abort()}hasBlockingDialog(){return this.activeDialog!==null}hasBlockingConfirmDialog(){return this.activeDialog?.kind==="confirm"}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];return[new U$({key:t8Q,debugLabel:"PluginDialogOverlay",autofocus:!1,canRequestFocus:!0,child:this.buildActiveDialog(A)})]}buildActiveDialog(A){switch(A.kind){case"input":return new pl({key:new dz(A),header:A.options.title??"Input",helpText:A.options.helpText,initialValue:A.options.initialValue,isRequired:!1,onSubmit:(Q)=>this.resolveInputDialog(A,Q),onDismiss:()=>this.resolveInputDialog(A,void 0)});case"confirm":return new Dm0({key:new dz(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)});case"select":return new Gm0({key:new dz(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.context.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,this.options.readThreadMessages)A.readThreadMessagesHandler=this.readThreadMessages;A.runAgentHandler=this.options.context.observerOnly?async()=>{throw Error("agent.run is only available from an executor-owned plugin runtime")}:this.options.runAgent??(async()=>{throw Error("agent.run is not available in this context")}),A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}handlePluginEvent(A){if(A.event!=="ui.notify")return;let Q=A.data;if(typeof Q.message==="string")this.options.toastController.show(Q.message,"success")}async handleThreadMessagesRequest(A,Q){try{let{options:$,threadID:B}=this.parseThreadMessagesRequestParams(A.params),D=await this.readThreadMessages($,B);e8Q(D),Q(lD0(A.id,D))}catch($){Q(lD0(A.id,void 0,$ instanceof Error?$.message:String($)))}}parseThreadMessagesRequestParams(A){if(!A||typeof A!=="object")return{options:void 0,threadID:void 0};let Q=A;return{options:Q.options,threadID:typeof Q.threadID==="string"?Q.threadID:void 0}}async handleOwnerUIRequest(A,Q){let $=new AbortController;this.pendingOwnerUIRequests.set(A.id,$);try{let B=await this.dispatchOwnerUIRequest(A,$.signal);if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(lD0(A.id,B))}catch(B){if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(lD0(A.id,void 0,B instanceof Error?B.message:String(B)))}}dispatchOwnerUIRequest(A,Q){switch(A.method){case"ui.input":return this.showInputDialog(A.params.options,Q);case"ui.confirm":return this.showConfirmDialog(A.params.options,Q);case"ui.select":return this.showSelectDialog(A.params.options,Q);default:throw Error(`Unknown owner UI request method: ${A.method}`)}}cancelOwnerUIRequest(A){let Q=this.pendingOwnerUIRequests.get(A);if(!Q)return;this.pendingOwnerUIRequests.delete(A),Q.abort()}cancelActorUIRequest(A){let Q=this.pendingActorUIRequests.get(A);if(!Q)return;this.pendingActorUIRequests.delete(A),Q.abort()}buildPluginUIRespondRequest(A,Q,$){this.pluginUIRespondRequestCounter+=1;let B={requestId:A};if($!==void 0)B.error=$;else if(Q!==void 0)B.result=Q;return{type:"request",id:`plugin-ui-respond-${A}-${this.pluginUIRespondRequestCounter}`,method:"plugin.ui.respond",params:B}}async handleActorUIRequest(A,Q){let $=new AbortController;this.pendingActorUIRequests.set(A.requestId,$);let B={type:"request",id:A.requestId,method:A.method,params:A.params};try{let D=await this.dispatchOwnerUIRequest(B,$.signal);if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,D))}catch(D){if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,void 0,D instanceof Error?D.message:String(D)))}}upsertActorUIState(A,Q){if(this.stateBackedRequestIDs.add(A.requestId),A.status!=="pending"){this.cancelActorUIRequest(A.requestId);return}if(this.pendingActorUIRequests.has(A.requestId))return;this.handleActorUIRequest(A,Q)}handlePluginUISnapshot(A,Q){let $=new Set(A.requests.map((B)=>B.requestId));for(let B of this.pendingActorUIRequests.keys())if(!$.has(B))this.cancelActorUIRequest(B);for(let B of this.stateBackedRequestIDs)if(!$.has(B))this.stateBackedRequestIDs.delete(B);for(let B of A.requests)this.upsertActorUIState(B,Q)}handlePluginUIRequestAdded(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestSettled(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestRemoved(A){this.cancelActorUIRequest(A.requestId),this.stateBackedRequestIDs.delete(A.requestId)}handlePluginUIStateEvent(A,Q){if(A.event==="plugin.ui.snapshot"){let $=ZZ4.safeParse(A.data);if($.success)this.handlePluginUISnapshot($.data,Q);return!0}if(A.event==="plugin.ui.request_added"){let $=XZ4.safeParse(A.data);if($.success)this.handlePluginUIRequestAdded($.data,Q);return!0}if(A.event==="plugin.ui.request_settled"){let $=IZ4.safeParse(A.data);if($.success)this.handlePluginUIRequestSettled($.data,Q);return!0}if(A.event==="plugin.ui.request_removed"){let $=GZ4.safeParse(A.data);if($.success)this.handlePluginUIRequestRemoved($.data);return!0}return!1}clearPluginPlatformStatusHandlers(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.readThreadMessagesHandler===this.readThreadMessages)A.readThreadMessagesHandler=null;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null;if(A.runAgentHandler===this.options.runAgent)A.runAgentHandler=null}subscribePluginCommands(){let A=this.options.context.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let $=A.map((B)=>this.createPluginCommand(B)).map((B)=>this.options.commandRegistry.register(B));this.unregisterPluginCommands=()=>{for(let B of $)B()}}showNewPluginErrorToasts(A){let Q=new Set;for(let $ of A){if($.status!=="error")continue;if(Mh($.errorMessage))continue;let B=`${$.uri.toString()}
4821
- ${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,D]of this.statusItems){if(Q.has(D.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(D){_.error("Neo plugin command failed",{error:D,command:A}),this.options.toastController.show(D instanceof Error?D.message:String(D),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=FV(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=FV(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=FV(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),D={pluginURI:A,id:Q};if($!==void 0)D.value=$;this.statusItems.set(B,D)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,r8Q)}scheduleResolvingDialogAdvance(A,Q){W$.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}b0();import{spawnSync as A9Q}from"node:child_process";import q8 from"node:process";var ww4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function ll(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else I1.instance.stop()}function Ow4(A){return{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],shortcut:q8.env.NODE_ENV==="development"&&q8.platform==="darwin"?CA.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),ll(A)}}}function Q9Q(A,Q){let{command:$,args:B}=$9Q(A),D=q8.execve,E=q8.platform==="win32"||!D,F=E?"spawnSync":"execve";if(_.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:F}),E){let J=A9Q($,B,{cwd:Q,env:q8.env,stdio:"inherit"});if(J.error)return _.error("Failed to relaunch Amp",{error:J.error}),1;return J.status??1}try{if(q8.chdir(Q),$.includes("/"))return D($,[$,...B],q8.env);return D("/usr/bin/env",["env",$,...B],q8.env)}catch(J){return _.error("Failed to relaunch Amp",{error:J}),1}}class zm0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{_.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return Q9Q(this.requestedThreadIDs,A)}}function $9Q(A){let Q=A.length>0?["threads","continue",...A]:[],$=B9Q(q8.argv),B=E9Q();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let D=q8.argv[1],E=D&&D9Q(D)?[D]:[];return{command:q8.execPath,args:[...E,...$,...Q]}}function B9Q(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let D=$[B];if(!D?.startsWith("--"))continue;let[E,F]=D.split("=",2);if(!E)continue;let J=E.slice(2),U=J.startsWith("no-")?J.slice(3):J;if(ww4.booleans.has(U)){Q.push(D);continue}if(!ww4.options.has(J))continue;if(F!==void 0){Q.push(D);continue}let Y=$[B+1];if(Y===void 0||Y.startsWith("--"))continue;Q.push(D,Y),B+=1}return Q}function D9Q(A){return A!==q8.execPath&&!A.startsWith("/$bunfs/")}function E9Q(){if(q8.env.NODE_ENV!=="development")return null;let A=q8.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=F9Q(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function F9Q(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var J9Q=48;class Km0{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new ml({width:J9Q,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as U9Q}from"node:fs/promises";import Cm0 from"node:os";A3();function Y9Q(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function Mw4(A,Q){try{return{path:Q,contents:JT0(await U9Q(A,"utf8"))}}catch{return null}}async function iD0(A,Q){let $=[],B=Y9Q(),D=await x4.getThread({thread:Q},{config:A.configService}),E=D.ok?D.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(xU(E),null,2)});let F=await Mw4(gP(Q),`${B}/logs/${Q}.log`);if(F)$.push(F);let J=await Mw4(A.settingsFilePath,`${B}/settings/global.json`);if(J)$.push(J);let U=await JY()??"unknown",Y=await x4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1779959155-g362e01",clientOS:`${Cm0.platform()} ${Cm0.release()} ${Cm0.arch()}`,installMethod:U}},{config:A.configService});if(!Y.ok)throw Error(`Failed to submit report: ${Y.error.message}`);return Y.result.reportID}class Wm0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var Z9Q=18000000;class um0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??Z9Q)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>ll(this.options))}}class nD0 extends bQ{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new Hm0(this.offstage)}updateRenderObject(A){if(A instanceof Hm0)A.offstage=this.offstage}}class Hm0 extends xA{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;sA(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),Q.setOffset(0,0)}else{let $=A.smallest;this.setSize($.width,$.height)}super.performLayout()}paint(A,Q,$){if(this._offstage)return;super.paint(A,Q,$)}hitTest(A,Q,$,B){if(this._offstage)return!1;return super.hitTest(A,Q,$,B)}}class il{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class Nm0 extends a0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Lw4}}class Lw4 extends n0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new eP,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new eP,$=this.makeScopedDismiss(Q),B=A($);this.setState(()=>{this.entries.push({key:Q,widget:B,dismiss:$})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new nD0({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],D=$===this.entries.length-1,E=D?new U$({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(F)=>{if(F.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new nD0({key:B.key,offstage:!D,child:E}))}return new A6({fit:"expand",children:Q})}}class wm0 extends $4{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((D)=>D.status.type!=="hidden"),$=I9Q(Q),B="";return new r4({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:e0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new k5({items:Q,showBorder:!1,getLabel:(D)=>{let E=qm0(D);return D.keywords&&D.keywords.length>0?`${E} ${D.keywords.join(" ").toLowerCase()}`:E},onQueryChange:(D)=>{B=D},sortItems:(D,E,F)=>{B=F;let J=F.trim().toLowerCase();if(J===""){let V=D.item.status.type==="disabled"?1:0,z=E.item.status.type==="disabled"?1:0;if(V!==z)return V-z;let K=D.item.sortBoost??0,C=E.item.sortBoost??0;if(K!==C)return C-K;let W=D.item.noun?.toLowerCase()??"",u=E.item.noun?.toLowerCase()??"";if(W!==u)return W<u?-1:1;return 0}let U=jw4(D.item,J),Y=jw4(E.item,J);if(U!==Y)return U?-1:1;let Z=hN(D.item.verb.toLowerCase(),F),X=hN(E.item.verb.toLowerCase(),F);if(Z!==X)return X-Z;let I=hN(qm0(D.item),F),G=hN(qm0(E.item),F);if(I!==G)return G-I;return E.score-D.score},isItemDisabled:(D)=>D.status.type==="disabled",buildDisabledReasonWidget:(D,E)=>{if(D.status.type!=="disabled")return;let{colors:F}=FA.of(E);return new J0({text:new g(D.status.reason,new $0({color:F.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:(D,E,F,J)=>new Rw4({command:D,isSelected:E,isDisabled:F,categoryWidth:$,query:B,buildContext:J}),onAccept:(D)=>{this.props.onAccept(D)},onDismiss:this.props.onDismiss})})}}class Rw4 extends $4{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:D,query:E,buildContext:F}=this.props,J=FA.of(F),{colors:U,app:Y}=J,Z=$?Y.selectionBackground:void 0,X=$?Y.selectionForeground:U.foreground,I=$?X:U.mutedForeground,G=new J0({text:new g(Q.noun?.toLowerCase()??"",new $0({color:I,dim:B||!$})),textAlign:"right"}),V=[new g(Q.verb.toLowerCase(),new $0({color:X,bold:!0,dim:B}))];if(B)V.push(new g(" (unavailable)",new $0({color:X,dim:!0})));let z=X9Q(Q,E);if(z)V.push(new g(" (alias: ",new $0({color:X,dim:B}))),V.push(new g(z,new $0({color:X,dim:B}))),V.push(new g(")",new $0({color:X,dim:B})));let K=J0.spans(V),C=[{child:G,fixedWidth:D},{child:K,expanded:!0}];if(Q.shortcut)C.push({child:G9Q(Q.shortcut,J,B)});return new Pw4({columns:C,padding:e0.horizontal(1),backgroundColor:Z})}}function qm0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function jw4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function X9Q(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function I9Q(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,oA($.noun)):Q},0)}function G9Q(A,Q,$){let{app:B}=Q,D=new $0({color:B.keybind,bold:!0,dim:$}),E=[],F=hX(A.toString()).split("+");for(let J=0;J<F.length;J++){if(J>0)E.push(new g("+",D));E.push(new g(F[J],D))}return J0.spans(E)}class Pw4 extends $4{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:D}=this.props,E=[];for(let J=0;J<Q.length;J++){let U=Q[J];if(J>0&&$>0)E.push(new h0({width:$}));if(U.fixedWidth!==void 0)E.push(new h0({width:U.fixedWidth,child:U.child}));else if(U.expanded)E.push(new k4({child:U.child}));else E.push(U.child)}let F=new qA({crossAxisAlignment:"start",children:E});if(!B&&!D)return F;return new WA({decoration:D?{color:D}:void 0,padding:B,child:F})}}class Om0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let $=this.findByID(A);if(!$||$.status.type!=="enabled")return!1;return $.run(new il,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class AB extends EQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=AB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(AB)?.commandRegistry??null}}class Mm0 extends a0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Tw4}}class Tw4 extends n0{modalStack=new il;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=AB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=AB.of(A).commands,$=new wm0({commands:Q,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new Nm0({root:$,controller:this.modalStack})}}var vw4=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],_w4=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class aD0 extends $4{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=W4.of(A).size.width<50,B=[];for(let D of this.items){let[E,F]=this.renderRow(D),J;if($)J=new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[E,new cA({padding:e0.only({left:4}),child:F})]});else J=new qA({crossAxisAlignment:"start",children:[new k4({flex:1,child:E}),new h0({width:1}),new k4({flex:1,child:F})]});B.push(new cA({padding:e0.horizontal(6),child:J}))}return new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function V9Q(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return hX(Q.join("+"))}class Lm0 extends $4{commands;onDismiss;constructor(A){super();this.commands=A.commands,this.onDismiss=A.onDismiss}build(A){let Q=FA.of(A),{colors:$,app:B}=Q,D=W4.of(A),E=new $0({color:$.secondary,bold:!0}),F=new $0({color:B.keybind}),J=new $0({color:B.command}),U=new $0({color:$.foreground}),Y=Math.max(40,Math.min(80,D.size.width-4)),X=[...this.commands.filter((V)=>{let z=V.noun?.toLowerCase();return z!=="dev"&&z!=="debug"&&V.status.type!=="hidden"})].sort((V,z)=>{let K=(V.noun??"").toLowerCase(),C=(z.noun??"").toLowerCase(),W=K.localeCompare(C);if(W!==0)return W;return V.verb.toLowerCase().localeCompare(z.verb.toLowerCase())}),I=(V)=>{let z=V.methods.map((K)=>V9Q(K)).join(", ");return[new J0({text:new g(z,F)}),new J0({text:new g(V.description,U)})]},G=new T3({autofocus:!0,child:new WA({constraints:new Y4(Y,Y,0,Number.POSITIVE_INFINITY),child:new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new cA({padding:e0.horizontal(2),child:new J0({text:new g(`Editor Shortcuts
4821
+ ${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,D]of this.statusItems){if(Q.has(D.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(D){_.error("Neo plugin command failed",{error:D,command:A}),this.options.toastController.show(D instanceof Error?D.message:String(D),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=FV(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=FV(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=FV(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),D={pluginURI:A,id:Q};if($!==void 0)D.value=$;this.statusItems.set(B,D)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,r8Q)}scheduleResolvingDialogAdvance(A,Q){W$.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}b0();import{spawnSync as A9Q}from"node:child_process";import q8 from"node:process";var ww4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function ll(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else I1.instance.stop()}function Ow4(A){return{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],shortcut:q8.env.NODE_ENV==="development"&&q8.platform==="darwin"?CA.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),ll(A)}}}function Q9Q(A,Q){let{command:$,args:B}=$9Q(A),D=q8.execve,E=q8.platform==="win32"||!D,F=E?"spawnSync":"execve";if(_.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:F}),E){let J=A9Q($,B,{cwd:Q,env:q8.env,stdio:"inherit"});if(J.error)return _.error("Failed to relaunch Amp",{error:J.error}),1;return J.status??1}try{if(q8.chdir(Q),$.includes("/"))return D($,[$,...B],q8.env);return D("/usr/bin/env",["env",$,...B],q8.env)}catch(J){return _.error("Failed to relaunch Amp",{error:J}),1}}class zm0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{_.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return Q9Q(this.requestedThreadIDs,A)}}function $9Q(A){let Q=A.length>0?["threads","continue",...A]:[],$=B9Q(q8.argv),B=E9Q();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let D=q8.argv[1],E=D&&D9Q(D)?[D]:[];return{command:q8.execPath,args:[...E,...$,...Q]}}function B9Q(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let D=$[B];if(!D?.startsWith("--"))continue;let[E,F]=D.split("=",2);if(!E)continue;let J=E.slice(2),U=J.startsWith("no-")?J.slice(3):J;if(ww4.booleans.has(U)){Q.push(D);continue}if(!ww4.options.has(J))continue;if(F!==void 0){Q.push(D);continue}let Y=$[B+1];if(Y===void 0||Y.startsWith("--"))continue;Q.push(D,Y),B+=1}return Q}function D9Q(A){return A!==q8.execPath&&!A.startsWith("/$bunfs/")}function E9Q(){if(q8.env.NODE_ENV!=="development")return null;let A=q8.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=F9Q(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function F9Q(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var J9Q=48;class Km0{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new ml({width:J9Q,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as U9Q}from"node:fs/promises";import Cm0 from"node:os";A3();function Y9Q(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function Mw4(A,Q){try{return{path:Q,contents:JT0(await U9Q(A,"utf8"))}}catch{return null}}async function iD0(A,Q){let $=[],B=Y9Q(),D=await x4.getThread({thread:Q},{config:A.configService}),E=D.ok?D.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(xU(E),null,2)});let F=await Mw4(gP(Q),`${B}/logs/${Q}.log`);if(F)$.push(F);let J=await Mw4(A.settingsFilePath,`${B}/settings/global.json`);if(J)$.push(J);let U=await JY()??"unknown",Y=await x4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1779973320-g362e01",clientOS:`${Cm0.platform()} ${Cm0.release()} ${Cm0.arch()}`,installMethod:U}},{config:A.configService});if(!Y.ok)throw Error(`Failed to submit report: ${Y.error.message}`);return Y.result.reportID}class Wm0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var Z9Q=18000000;class um0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??Z9Q)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>ll(this.options))}}class nD0 extends bQ{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new Hm0(this.offstage)}updateRenderObject(A){if(A instanceof Hm0)A.offstage=this.offstage}}class Hm0 extends xA{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;sA(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),Q.setOffset(0,0)}else{let $=A.smallest;this.setSize($.width,$.height)}super.performLayout()}paint(A,Q,$){if(this._offstage)return;super.paint(A,Q,$)}hitTest(A,Q,$,B){if(this._offstage)return!1;return super.hitTest(A,Q,$,B)}}class il{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class Nm0 extends a0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Lw4}}class Lw4 extends n0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new eP,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new eP,$=this.makeScopedDismiss(Q),B=A($);this.setState(()=>{this.entries.push({key:Q,widget:B,dismiss:$})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new nD0({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],D=$===this.entries.length-1,E=D?new U$({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(F)=>{if(F.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new nD0({key:B.key,offstage:!D,child:E}))}return new A6({fit:"expand",children:Q})}}class wm0 extends $4{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((D)=>D.status.type!=="hidden"),$=I9Q(Q),B="";return new r4({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:e0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new k5({items:Q,showBorder:!1,getLabel:(D)=>{let E=qm0(D);return D.keywords&&D.keywords.length>0?`${E} ${D.keywords.join(" ").toLowerCase()}`:E},onQueryChange:(D)=>{B=D},sortItems:(D,E,F)=>{B=F;let J=F.trim().toLowerCase();if(J===""){let V=D.item.status.type==="disabled"?1:0,z=E.item.status.type==="disabled"?1:0;if(V!==z)return V-z;let K=D.item.sortBoost??0,C=E.item.sortBoost??0;if(K!==C)return C-K;let W=D.item.noun?.toLowerCase()??"",u=E.item.noun?.toLowerCase()??"";if(W!==u)return W<u?-1:1;return 0}let U=jw4(D.item,J),Y=jw4(E.item,J);if(U!==Y)return U?-1:1;let Z=hN(D.item.verb.toLowerCase(),F),X=hN(E.item.verb.toLowerCase(),F);if(Z!==X)return X-Z;let I=hN(qm0(D.item),F),G=hN(qm0(E.item),F);if(I!==G)return G-I;return E.score-D.score},isItemDisabled:(D)=>D.status.type==="disabled",buildDisabledReasonWidget:(D,E)=>{if(D.status.type!=="disabled")return;let{colors:F}=FA.of(E);return new J0({text:new g(D.status.reason,new $0({color:F.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:(D,E,F,J)=>new Rw4({command:D,isSelected:E,isDisabled:F,categoryWidth:$,query:B,buildContext:J}),onAccept:(D)=>{this.props.onAccept(D)},onDismiss:this.props.onDismiss})})}}class Rw4 extends $4{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:D,query:E,buildContext:F}=this.props,J=FA.of(F),{colors:U,app:Y}=J,Z=$?Y.selectionBackground:void 0,X=$?Y.selectionForeground:U.foreground,I=$?X:U.mutedForeground,G=new J0({text:new g(Q.noun?.toLowerCase()??"",new $0({color:I,dim:B||!$})),textAlign:"right"}),V=[new g(Q.verb.toLowerCase(),new $0({color:X,bold:!0,dim:B}))];if(B)V.push(new g(" (unavailable)",new $0({color:X,dim:!0})));let z=X9Q(Q,E);if(z)V.push(new g(" (alias: ",new $0({color:X,dim:B}))),V.push(new g(z,new $0({color:X,dim:B}))),V.push(new g(")",new $0({color:X,dim:B})));let K=J0.spans(V),C=[{child:G,fixedWidth:D},{child:K,expanded:!0}];if(Q.shortcut)C.push({child:G9Q(Q.shortcut,J,B)});return new Pw4({columns:C,padding:e0.horizontal(1),backgroundColor:Z})}}function qm0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function jw4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function X9Q(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function I9Q(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,oA($.noun)):Q},0)}function G9Q(A,Q,$){let{app:B}=Q,D=new $0({color:B.keybind,bold:!0,dim:$}),E=[],F=hX(A.toString()).split("+");for(let J=0;J<F.length;J++){if(J>0)E.push(new g("+",D));E.push(new g(F[J],D))}return J0.spans(E)}class Pw4 extends $4{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:D}=this.props,E=[];for(let J=0;J<Q.length;J++){let U=Q[J];if(J>0&&$>0)E.push(new h0({width:$}));if(U.fixedWidth!==void 0)E.push(new h0({width:U.fixedWidth,child:U.child}));else if(U.expanded)E.push(new k4({child:U.child}));else E.push(U.child)}let F=new qA({crossAxisAlignment:"start",children:E});if(!B&&!D)return F;return new WA({decoration:D?{color:D}:void 0,padding:B,child:F})}}class Om0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let $=this.findByID(A);if(!$||$.status.type!=="enabled")return!1;return $.run(new il,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class AB extends EQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=AB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(AB)?.commandRegistry??null}}class Mm0 extends a0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Tw4}}class Tw4 extends n0{modalStack=new il;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=AB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=AB.of(A).commands,$=new wm0({commands:Q,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new Nm0({root:$,controller:this.modalStack})}}var vw4=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],_w4=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class aD0 extends $4{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=W4.of(A).size.width<50,B=[];for(let D of this.items){let[E,F]=this.renderRow(D),J;if($)J=new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[E,new cA({padding:e0.only({left:4}),child:F})]});else J=new qA({crossAxisAlignment:"start",children:[new k4({flex:1,child:E}),new h0({width:1}),new k4({flex:1,child:F})]});B.push(new cA({padding:e0.horizontal(6),child:J}))}return new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function V9Q(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return hX(Q.join("+"))}class Lm0 extends $4{commands;onDismiss;constructor(A){super();this.commands=A.commands,this.onDismiss=A.onDismiss}build(A){let Q=FA.of(A),{colors:$,app:B}=Q,D=W4.of(A),E=new $0({color:$.secondary,bold:!0}),F=new $0({color:B.keybind}),J=new $0({color:B.command}),U=new $0({color:$.foreground}),Y=Math.max(40,Math.min(80,D.size.width-4)),X=[...this.commands.filter((V)=>{let z=V.noun?.toLowerCase();return z!=="dev"&&z!=="debug"&&V.status.type!=="hidden"})].sort((V,z)=>{let K=(V.noun??"").toLowerCase(),C=(z.noun??"").toLowerCase(),W=K.localeCompare(C);if(W!==0)return W;return V.verb.toLowerCase().localeCompare(z.verb.toLowerCase())}),I=(V)=>{let z=V.methods.map((K)=>V9Q(K)).join(", ");return[new J0({text:new g(z,F)}),new J0({text:new g(V.description,U)})]},G=new T3({autofocus:!0,child:new WA({constraints:new Y4(Y,Y,0,Number.POSITIVE_INFINITY),child:new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new cA({padding:e0.horizontal(2),child:new J0({text:new g(`Editor Shortcuts
4822
4822
  `,E)})}),new aD0({items:vw4.filter((V)=>V.submitOnEnterOnly===void 0||V.submitOnEnterOnly===!0),renderRow:I}),new h0({height:1}),new cA({padding:e0.horizontal(2),child:new J0({text:new g(`Scrolling & Navigation
4823
4823
  `,E)})}),new aD0({items:_w4,renderRow:I}),new h0({height:1}),new cA({padding:e0.horizontal(2),child:new J0({text:new g(`Command Palette Commands
4824
4824
  `,E)})}),new aD0({items:X,renderRow:(V)=>{let z=V.noun?`${V.noun}: ${V.verb}`:V.verb;return[new J0({text:new g(z,J)}),new J0({text:new g(V.description,U)})]}}),new h0({height:1})]})})});return new r4({header:"Amp CLI — Help & Keyboard Shortcuts",minWidth:Y,maxWidth:Y,maxHeight:D.size.height,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.onDismiss,child:G})}}class _T extends EQ{completionBuilder;constructor({completionBuilder:A,child:Q}){super({child:Q});this.completionBuilder=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(_T);if(!Q)throw Error("No CompletionBuilderProvider found in widget tree");return Q.completionBuilder}}var z9Q=250,K9Q=2000;class jm0 extends a0{configReloadEvents;toastController;child;constructor(A){super();this.configReloadEvents=A.configReloadEvents,this.toastController=A.toastController,this.child=A.child}createState(){return new Sw4}}class Sw4 extends n0{subscription=null;toastTimer=null;pendingToastType=null;lastToast=null;initState(){this.subscribeToConfigReloadEvents()}didUpdateWidget(A){if(A.configReloadEvents===this.widget.configReloadEvents)return;this.clearPendingToast(),this.subscribeToConfigReloadEvents()}dispose(){this.subscription?.unsubscribe(),this.subscription=null,this.clearPendingToast(),super.dispose()}build(A){return this.widget.child}subscribeToConfigReloadEvents(){this.subscription?.unsubscribe(),this.subscription=this.widget.configReloadEvents.subscribe((A)=>{this.scheduleToast(A)})}scheduleToast(A){if(this.pendingToastType=C9Q(this.pendingToastType,A),this.toastTimer)clearTimeout(this.toastTimer);this.toastTimer=setTimeout(()=>{if(!this.mounted)return;this.flushToast()},z9Q),this.toastTimer.unref()}flushToast(){let A=this.pendingToastType;if(this.clearPendingToast(),!A)return;let Q=Date.now();if(W9Q(this.lastToast,A,Q))return;this.lastToast={type:A,shownAt:Q},u9Q(this.widget.toastController,A)}clearPendingToast(){if(this.toastTimer)clearTimeout(this.toastTimer),this.toastTimer=null;this.pendingToastType=null}}function C9Q(A,Q){return A==="failed"||Q.type==="failed"?"failed":"succeeded"}function W9Q(A,Q,$){return A?.type===Q&&$-A.shownAt<K9Q}function u9Q(A,Q){switch(Q){case"succeeded":A.show("Config reloaded","success",1500);break;case"failed":A.show("Config reload failed","error",5000);break}}class h6 extends EQ{context;constructor({context:A,child:Q}){super({child:Q});this.context=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(h6);if(!Q)throw Error("No ContextProvider found in widget tree");return Q.context}}b0();c7();var rD0=80,H9Q=13,N9Q=1,kw4=-rD0,q9Q=16,w9Q=yb0(rD0,rD0);function fw4({ampURL:A,threadID:Q,logPath:$}){return[`Debug thread ${oG(new URL(A),Q).toString()} (cli log: ${$}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
@@ -4900,7 +4900,7 @@ Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)R=this.widget.centerContent
4900
4900
  `));if(J.tools.length===0)F.push(new g(` └─ No tools available
4901
4901
  `,D));else for(let Z of J.tools)lZQ(F,Z,$);F.push(new g(`
4902
4902
  `))}return F}function lZQ(A,Q,$){let{colors:B,app:D}=$,E=iZQ(Q.status,$);if(A.push(new g(` ${E.icon} `,new $0({color:E.color}))),A.push(new g(Q.name,new $0({color:Q.status==="pending"?B.warning:D.command}))),Q.status==="pending")A.push(new g(" discovering...",new $0({color:B.foreground,dim:!0})));else if(Q.description)A.push(new g(` ${LR4(Q.description,50)}`,new $0({color:B.foreground,dim:!0})));if(Q.error)A.push(new g(` ${LR4(Q.error,40)}`,new $0({color:D.toolError})));A.push(new g(`
4903
- `))}function iZQ(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function LR4(A,Q){let $=A.replace(/\s+/g," ").trim();if(oA($)<=Q)return $;let B="...",D=oA(B);if(Q<=D)return UD(B,Q);return`${UD($,Q-D,!0,"")}${B}`}var ac0="https://ampcode.com/news/neo",oc0=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:ac0,href:ac0}]}];function nZQ(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:ac0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function aZQ(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var aT=50,Jq=40,ic0=1000,oZQ=420,rZQ=760,sZQ=-250,tZQ=1100,i80=33,TR4=0.999,eZQ=2.1,AXQ=720,QXQ=420,bR4="Meet the new",hR4="Amp",gR4="CLI",rc0=F4(bR4).length,$XQ=F4(hR4).length,BXQ=F4(gR4).length,n80={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},vR4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},_R4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},SR4=[n80,vR4,_R4,n80,vR4,_R4,n80],DXQ=n80;class sc0 extends a0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??aZQ(),this.introStages=this.variant==="npm-migration"?nZQ(this.binaryInstallCommand):oc0,this.dismissible=this.variant!=="npm-migration"}createState(){return new mR4}}class mR4 extends n0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=ic0;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new x5(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=b9(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=TR4,this.firstStageHintVisible=this.animationProgress>=TR4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:ic0,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=b9(A/rZQ);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},i80)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=b9($/oZQ);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},i80)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let D=performance.now()-this.startedAt,E=b9(D/this.animationDurationMs),F=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*oT(E);if(this.setState(()=>{this.animationProgress=F}),E>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},i80)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,ic0+sZQ),Q=A+tZQ;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?b9((A-this.firstStageTitleRevealStartedAt)/AXQ):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?b9((A-this.firstStageHintRevealStartedAt)/QXQ):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},i80)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=kR4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:fR4(kR4(this.previousIntroStage),A,oT(this.stageTransitionProgress));return this.dismissProgress>0?fR4(Q,DXQ,oT(this.dismissProgress)):Q}build(A){let Q=S4.of(A).colorScheme,$=FA.of(A),B=this.currentOrbPalette(),D=N7(1,"frontier",B),E=W4.of(A).size,J=this.widget.animationProgress??this.animationProgress,U=Math.max(E.width/aT,E.height/Jq)*eZQ,Y=U+(1-U)*J,Z=oT(this.dismissProgress),X=Math.max(aT,Math.round(aT*Y)),I=Math.max(Jq,Math.round(Jq*Y)),G=Math.round((E.width-X)/2),V=Math.round((E.height-I)/2),z=Math.max(0,Math.floor((E.width-aT)/2)),K=-Math.floor(Jq/2),C=Math.round(G+(z-G)*J),W=Math.round(V+(K-V)*J),u=C+X/2,H=W+I/2,N=EXQ({dismissProgress:this.dismissProgress,easedDismissProgress:Z,introOrbScale:Y,normalOrbCenterX:u,normalOrbCenterY:H,size:E}),w=Math.max(aT,Math.round(aT*N.orbScale)),M=Math.max(Jq,Math.round(Jq*N.orbScale)),R=N.orbCenterX,S=N.orbCenterY,T=Math.round(R-w/2),f=Math.round(S-M/2),m=Math.max(3,Math.min(E.height-5,Math.floor(Jq/2)+2)),x=Math.max(m+3,E.height-3),v=N.textDissolveProgress,k=this.isFinalIntroStage()?N.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&v<1,d=c&&this.firstStageHintVisible,b=d&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,s=Math.max(24,Math.min(74,E.width-4)),X0=Math.min(12,Math.max(8,E.height-m-6)),E0=Math.max(0,Math.floor((E.width-s)/2)),G0=Math.max(0,Math.min(E.height-X0,Math.floor(E.height*0.55-X0/2))),N0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new EK({width:w,height:M,agentMode:"frontier",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new EK({width:w,height:M,agentMode:"frontier",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new U$({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(t)=>{if(t.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&t.key==="c"&&t.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&t.key==="q")return this.widget.onQuit?.(),"handled";if((t.key===" "||t.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(t.key==="Escape"||t.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(t.key==="ArrowRight")return this.nextIntroStage(),"handled";if(t.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new A6({fit:"expand",children:[new dR4({color:Q.background,dissolveProgress:k}),new A6({fit:"expand",children:[new pA({onClick:()=>{},child:h0.expand()}),new r1({left:T,top:f,width:w,height:M,child:N0}),...c?[new r1({left:E0,top:G0,width:s,height:X0,child:JXQ({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:s,height:X0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:D,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:v,context:A})})]:[],...d?[...b?[new r1({left:E0,top:Math.max(0,x-1),width:s,height:1,child:new J0({text:GXQ({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new r1({left:E0,top:x,width:s,height:1,child:zXQ({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:v,context:A})})]:[]]})]})})}}class dR4 extends U3{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new cR4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class cR4 extends xA{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;sA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),D=Math.floor($+this.offset.y),E=Math.floor(this.size.width),F=Math.floor(this.size.height),J={bg:this.color},U=b9(this.dissolveProgress);if(U<=0){A.fill(B,D,E,F," ",J);return}if(U>=1)return;for(let Y=0;Y<F;Y++)for(let Z=0;Z<E;Z++)if(!FXQ(Z,Y,E,F,U))A.fill(B+Z,D+Y,1,1," ",J)}}function b9(A){return Math.min(1,Math.max(0,A))}function oT(A){return 1-(1-A)**3}function kR4(A){return SR4[A]??SR4[0]}function fR4(A,Q,$){return{primary:gN(A.primary,Q.primary,$),secondary:gN(A.secondary,Q.secondary,$)}}function EXQ({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:D,size:E}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(E.width*0.54-B)*Q,orbCenterY:D-E.height*0.44*Q,textDissolveProgress:b9(A/0.52),backdropDissolveProgress:oT(b9((A-0.12)/0.88))}}function FXQ(A,Q,$,B,D){let E=B<=1?0:Q/(B-1),F=pR4(A+Q*Math.max(1,$));return(1-E)*0.72+F*0.28<D}function JXQ({introStages:A,stage:Q,previousStage:$,progress:B,direction:D,width:E,height:F,foreground:J,mutedForeground:U,accent:Y,link:Z,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return nc0({introStages:A,stage:Q,foreground:J,mutedForeground:U,accent:Y,link:Z,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let z=oT(B),K=D*Math.round((1-z)*E),C=-D*Math.round(z*E);return new LN(new A6({fit:"expand",children:[new r1({left:C,top:0,width:E,height:F,child:nc0({introStages:A,stage:$,foreground:J,mutedForeground:U,accent:Y,link:Z,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new r1({left:K,top:0,width:E,height:F,child:nc0({introStages:A,stage:Q,foreground:J,mutedForeground:U,accent:Y,link:Z,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function nc0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:D,link:E,keybind:F,titleRevealProgress:J,dissolveProgress:U,context:Y}){let Z=A[Q]??A[0]??oc0[0],X=new $0({color:D,bold:!0}),I=new $0({color:$}),G=A===oc0&&Q===0,V=[...Z.title===null?[]:[new J0({text:G?a80(ZXQ({progress:J,foreground:D,pulseColor:D}),U):new g(zD(Z.title,U),X),textAlign:"center"})],...Z.body.length>0?[UXQ()]:[],...Z.body.map((z)=>YXQ(z,I,B,E,F,U,Y))];return new AQ({child:new cA({padding:e0.horizontal(1),child:new IA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function UXQ(){return h0.height(1)}function YXQ(A,Q,$,B,D,E,F){if(typeof A==="string")return new J0({text:new g(zD(A,E),Q),textAlign:"center"});if("codeBlock"in A)return new ZD({onCopy:(J,U)=>{if(U)D6.success(F,"Copied to clipboard",2000)},child:new IA({mainAxisSize:"min",children:A.codeBlock.map((J)=>new J0({text:new g(zD(J,E),new $0({color:D})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let J=new J0({text:new g("",void 0,[new g(zD(A.text,E),new $0({color:$,dim:!0})),new g(zD(A.keybind,E,F4(A.text).length),new $0({color:D}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new AQ({child:new ZD({child:J})});return J}if("highlightText"in A){let J=N$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),U=AI.of(F),Y=new g("",void 0,[new g(A.text,Q),new g(A.highlightText,new $0({color:D})),new g(A.textAfterHighlight,Q),new g(J.text,J.style,J.children,J.hyperlink,()=>{u$(F,A.href,{forceExternal:!1,onShowImagePreview:U})}),new g(A.textAfter,Q)]);return new J0({text:a80(Y,E),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new IA({mainAxisSize:"min",children:[new J0({text:new g(zD(A.text,E),Q),textAlign:"center"}),new AQ({child:new qA({mainAxisSize:"min",children:[N$.createWidget(F,A.href,zD(A.linkText,E),new $0({color:B,underline:!0})),new J0({text:new g(zD(A.textAfter,E),Q)})]})})]});let J=N$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),U=AI.of(F),Y=new g("",void 0,[new g(A.text,Q),new g(J.text,J.style,J.children,J.hyperlink,()=>{u$(F,A.href,{forceExternal:!1,onShowImagePreview:U})}),new g(A.textAfter,Q)]);return new J0({text:a80(Y,E),textAlign:"center"})}if(E>0)return new J0({text:new g(zD(A.text,E),new $0({color:B,underline:!0})),textAlign:"center"});return new AQ({child:N$.createWidget(F,A.href,A.text,new $0({color:B,underline:!0}))})}function ZXQ({progress:A,foreground:Q,pulseColor:$}){let B=new $0({color:Q,bold:!0}),D=new $0({color:IXQ({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new g("",void 0,[new g(XXQ(A).padEnd(rc0," "),B),new g(" ",B),new g(xR4(hR4,$XQ,A,0.72),B),new g(" ",B),new g(xR4(gR4,BXQ,A,0.88),D)])}function XXQ(A){let Q=F4(bR4),$=Math.min(rc0,Math.ceil(b9(A/0.62)*rc0));return Q.slice(0,$).join("")}function xR4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function IXQ({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=b9((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function GXQ({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new g(zD(`${A}/${Q}`,B),new $0({color:$,dim:!0}))}function VXQ({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:E}){let F=new $0({color:B}),J=new $0({color:$,dim:!0}),U=Q?A?"Enter":"Space":"Esc",Y=Q?A?" to get started":" to continue":" to quit",Z="",X="",I=`${Y}`;if(!Q)return new g("",void 0,[new g(U,F),new g(Y,J),new g("",F),new g("",J)]);let G=yR4(U,D),V=yR4(I,b9((D*(F4(U).length+F4(I).length)-F4(U).length)/F4(I).length));return new g("",void 0,[new g(zD(G,E),F),new g(zD(V.slice(0,Y.length),E),J),new g(zD(V.slice(Y.length,Y.length+0),E),F),new g(zD(V.slice(Y.length+0),E),J)])}function zXQ({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:E,context:F}){if(Q)return new J0({text:VXQ({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:E}),textAlign:"center"});let J=new $0({color:B}),U=new $0({color:$,dim:!0});return new ZD({onCopy:(Y,Z)=>{if(Z)D6.success(F,"Copied to clipboard",2000)},child:new J0({text:new g("",void 0,[new g("q",J),new g(" to quit",U)]),textAlign:"center",selectable:!0})})}function yR4(A,Q){let $=F4(A),B=Math.min($.length,Math.ceil(b9(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function a80(A,Q,$=0){if(Q<=0)return A;let B=$+F4(A.text??"").length,D=A.children?.map((E)=>{let F=a80(E,Q,B);return B+=F4(E.toPlainText()).length,F});return new g(A.text?zD(A.text,Q,$):A.text,A.style,D,A.hyperlink,A.onClick)}function zD(A,Q,$=0){if(Q<=0)return A;return F4(A).map((D,E)=>{if(D.trim()==="")return D;return pR4($+E)<Q?" ":D}).join("")}function pR4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function KXQ(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function CXQ(A,Q={}){return new Promise(($,B)=>{let D=!1,E=setTimeout(()=>{F.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),F=A.observer.agentState().subscribe((J)=>{if(nB(J)){D=!0;return}if(!D)return;let U=KXQ(A);if(U===null)return;clearTimeout(E),F.unsubscribe(),$(U)})})}class tc0 extends a0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new iR4}}class iR4 extends n0{editorController=new KY;commandPalette=new bp(this);commandRegistry=new Om0;toastController=new fb0;relaunchNotificationController=new Km0;exitHintTimer=new yp(this,1000);ideStatus=new t3(this,{});threadNavigationHistory=new Wm0;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new Qi;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;loadThreads=async()=>{return this.widget.context.listThreads()};analyzeContextForThread=async(A,Q)=>{return nK4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};threadListSidebar=new pc0({state:this,isAvailable:()=>this.widget.context.isInternalUser,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),onSelectThread:this.onSwitchThread});sendFeedbackReport=async(A)=>iD0({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await P70({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await oH4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await rH4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(bX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.notices=new eg0(this.widget.configService,($)=>this.setState($)),W$.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(_.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(z00($.settings)))}),this.updateRelaunchIntegration=new um0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new Vm0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new rh0({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=I1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.context.pluginService?Kw4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[],B=[Ow4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100,run:(D,E,F)=>{D.pushWithDismiss((J)=>id0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:J,onThreadSelected:F}))}},...this.threadListSidebar.commands(),{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(D,E,F)=>{A.navigateBack(),F()}},CM4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(D,E,F)=>{A.navigateForward(),F()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"},run:(D,E,F)=>{D.push(new Ed0({mcpServers:this.widget.context.mcpServers,onDismiss:F}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"},run:(D)=>{D.pushWithDismiss((E)=>new lc0({toolboxes:this.widget.context.toolboxes,onDismiss:E}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"},run:async(D,E,F)=>{try{await u$(E,"https://ampcode.com/chronicle")}finally{F()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"},run:()=>{lz(this.widget.context.settingsFilePath).catch((D)=>{_.error("Failed to open settings file in editor",{error:D})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"},run:(D,E,F)=>{D.pushWithDismiss((J)=>new Dd0({onCancel:J,onSelect:(U)=>{this.handleIdeSelection(U),F()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["manual","?"],status:{type:"enabled"},run:(D,E,F)=>{D.push(new Lm0({commands:AB.of(E).commands,onDismiss:F}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"},run:(D,E,F)=>{F(),A.showWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"},run:(D,E,F)=>{F(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"},run:(D,E,F)=>{D.push(new r4({header:"Amp Version",maxWidth:72,onDismiss:F,child:new J0({text:new g($70({version:"0.0.1779959155-g362e01",buildTimestamp:"2026-05-28T09:10:57.457Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],shortcut:CA.ctrl("c"),status:{type:"enabled"},run:(D,E)=>{H4.maybeInvoke(E,new OT)}},...Q,...aH4(this.widget.context.logFilePath)].map((D)=>this.commandRegistry.register(D));return()=>{for(let D of B)D()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,D=new hc0({initialAgentMode:this.widget.context.sessionAgentMode,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(Z)=>this.notices.dismiss(Z)}),E=W4.of(A),F=E.capabilities.animationSupport!=="disabled",U=[new WA({constraints:Y4.tight(E.size.width,E.size.height),child:this.threadListSidebar.buildBody(D)})];if(this.commandPalette.isEnabled())U.push(new U$({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new Mm0({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)U.push(id0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)U.push(new U$({debugLabel:"WelcomeDialogOverlay",child:new sc0({onDismiss:this.dismissWelcome,onQuit:()=>I1.instance.stop(),animationsEnabled:F,variant:this.widget.welcomeVariant})}));let Y=this.executorAlreadyConnectedDialog;if(Y)U.push(new U$({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new $d0({existingExecutorPid:Y.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(U.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),U.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)U.push(new Rm0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:o80.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)U.push(new Bd0);if(this.endCreditsVisible)U.push(new rm0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));return new h6({context:this.widget.context,child:new AB({commandRegistry:this.commandRegistry,child:new _T({completionBuilder:this.widget.completionBuilder,child:new D6({controller:this.toastController,child:new H4({actions:this.buildActions(),child:new e6({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),child:new u6({debugLabel:"AppShellFocus",child:new xb0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new jm0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new A6({children:U})})})})})})})})})})}buildShortcuts(){let A=new Map([[CA.ctrl("c"),new n70],[CA.ctrl("o"),new o70],[CA.alt("i"),new s70],[CA.alt("p"),new Kp],[CA.ctrl("."),new AD0],[CA.ctrl("t"),new BD0],...this.threadListSidebar.shortcutEntries()]);if(o80.env.NODE_ENV==="development"&&o80.platform==="darwin")A.set(CA.meta("r"),new a70);return A}buildActions(){let A=new dA(()=>{if(nF.hasAnyCopyableSelection())return nF.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new dA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new dA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new dA(()=>{return this.startNewDraftThread(),"handled"}),D=new dA(()=>{return I1.instance.stop(),"handled"}),E=new dA(()=>{return ll({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),F=new dA((I)=>{if(!I.text)return"ignored";return I1.instance.tuiInstance.clipboard.writeText(I.text).then((G)=>{if(G.ok)this.toastController.show(I.successMessage,"success",2000);else this.toastController.show(`${I.failureMessage}: ${G.userFacingErrorMessage}`,"error",4000)}).catch((G)=>{_.error("Failed to copy Neo text to clipboard",{error:G}),this.toastController.show(I.failureMessage,"error",2000)}),"handled"}),J=new dA(()=>{return I1.instance.toggleFrameStatsOverlay(),"handled"}),U=new dA(()=>this.notices.dismissCurrent()?"handled":"ignored"),Y=new dA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),Z=xw4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new dA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[n70,A],[Vl,B],[OT,D],[a70,E],[Z3,F],[Wl,$],[o70,Q],[s70,Y],...this.threadListSidebar.actionEntries(),[AD0,U],...Z,[Kp,J],[BD0,X]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await oP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){_.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=UY(Q),D=q50(this.widget.context,Q);if(B!==void 0&&D!==void 0)$={...$,[B]:D};return N50($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=lR4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(FU(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=lR4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(ez);if(this.exitHintTimer.isActive())A.add(uT);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),I1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),YY((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{_.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")I1.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,D,E)=>{await this.ensureDraftThreadSettingsInitialized();let F=this.activeThreadContext?.client.getThreadId(),J=A.find(U00);if(J)this.widget.history.add(J.text,o80.cwd()),this.widget.history.reset();let U=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Y=$??U??null,Z=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Y??void 0,D,E);if(this.sendUserMessage(Z,A,D?void 0:Q,D?void 0:B),!D)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(F),this.setActiveClient(Z)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=UY(A),D=B?Q[B]:void 0;if(D!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:D};YY((E)=>{let F={...E,agentMode:A};if($!==void 0)F={...F,lastReasoningEffortByMode:{...F.lastReasoningEffortByMode??{},[A]:$}};if(D!==void 0)F={...F,lastSpeedByMode:{...F.lastSpeedByMode??{},[A]:D}};return F}).catch((E)=>{_.warn("Failed to persist Neo session defaults for new message",{error:E instanceof Error?E.message:String(E)})})}sendUserMessage(A,Q,$,B){let D=Q70(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{userState:D});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,userState:D})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("appendToThread is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.append is only available for the active executor thread");for(let D of A)this.sendUserMessage($,[{type:"text",text:D.content}])};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return xaA(yaA($.observer.protocolMessages()),A)};runPluginAgent=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1});this.sendUserMessage($,[{type:"text",text:Q.message}]);try{let B=await CXQ($,{timeoutMs:Q.timeoutMs}),D=$.client.getThreadId();return D?{threadID:D,text:B}:{text:B}}finally{this.widget.clientPool.disconnect($)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(D)=>this.promptExecutorAlreadyConnected(D)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(_.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){_.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(D)=>{A.sendPluginMessage(D)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(D)=>{A.sendPluginMessage(D)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){_.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function lR4(A,Q,$){let B={...A};for(let D of WXQ(Q,$)){if(!FU(A[D],Q[D]))continue;let E=$[D];if(E===void 0)delete B[D];else B[D]=E}return B}function WXQ(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}e$();function nR4(A,Q,$,B){let D=yyA(A),E="\x1B[0m",F="\x1B[34m",J="\x1B[90m",U="\x1B[2m",Y=[];if(A.archived)Y.push("\x1B[90m\x1B[2mArchived\x1B[0m");Y.push(`${D}`),Y.push(`\x1B[34m${Q}\x1B[0m`),Y.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let Z=14,X=7,I=new iF(Z,X),G=new x5(42),V=new kT(Z,X,Z,X,Z,X,0,A.agentMode??"smart","intensity","braille",void 0,void 0,d0.default(),G);V.layout(Y4.tight(Z,X)),V.paint(I,0,0);let z=I.getBuffer().getCells(),K=0;for(let R=0;R<X;R++)if(z[R].some((S)=>S.char!==" ")){K=R;break}let C=X-1;for(let R=X-1;R>=0;R--)if(z[R].some((S)=>S.char!==" ")){C=R;break}function W(R,S){if(!R)return"";if(R.type==="rgb"){let{r:T,g:f,b:m}=R.value;if($.getColorDepth()>=24)return`\x1B[${S?38:48};2;${T};${f};${m}m`;let x=jp(T,f,m);return`\x1B[${S?38:48};5;${x}m`}return""}let u=[];if(C>=K)for(let R=K;R<=C;R++){let S="";for(let T=0;T<Z;T++){let f=z[R][T],m=f.char,x=W(f.style.fg,!0);S+=x+m+"\x1B[0m"}u.push(S)}let H=u.length,N=Math.max(H,Y.length),w=Math.floor((N-H)/2),M=Math.floor((N-Y.length)/2);for(let R=0;R<N;R++){let S=" ".repeat(Z);if(R>=w&&R<w+H)S=u[R-w];let T=" ",f="";if(R>=M&&R<M+Y.length)f=Y[R-M];$.write(S+T+f+`
4903
+ `))}function iZQ(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function LR4(A,Q){let $=A.replace(/\s+/g," ").trim();if(oA($)<=Q)return $;let B="...",D=oA(B);if(Q<=D)return UD(B,Q);return`${UD($,Q-D,!0,"")}${B}`}var ac0="https://ampcode.com/news/neo",oc0=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:ac0,href:ac0}]}];function nZQ(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:ac0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function aZQ(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var aT=50,Jq=40,ic0=1000,oZQ=420,rZQ=760,sZQ=-250,tZQ=1100,i80=33,TR4=0.999,eZQ=2.1,AXQ=720,QXQ=420,bR4="Meet the new",hR4="Amp",gR4="CLI",rc0=F4(bR4).length,$XQ=F4(hR4).length,BXQ=F4(gR4).length,n80={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},vR4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},_R4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},SR4=[n80,vR4,_R4,n80,vR4,_R4,n80],DXQ=n80;class sc0 extends a0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??aZQ(),this.introStages=this.variant==="npm-migration"?nZQ(this.binaryInstallCommand):oc0,this.dismissible=this.variant!=="npm-migration"}createState(){return new mR4}}class mR4 extends n0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=ic0;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new x5(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=b9(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=TR4,this.firstStageHintVisible=this.animationProgress>=TR4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:ic0,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=b9(A/rZQ);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},i80)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=b9($/oZQ);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},i80)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let D=performance.now()-this.startedAt,E=b9(D/this.animationDurationMs),F=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*oT(E);if(this.setState(()=>{this.animationProgress=F}),E>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},i80)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,ic0+sZQ),Q=A+tZQ;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?b9((A-this.firstStageTitleRevealStartedAt)/AXQ):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?b9((A-this.firstStageHintRevealStartedAt)/QXQ):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},i80)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=kR4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:fR4(kR4(this.previousIntroStage),A,oT(this.stageTransitionProgress));return this.dismissProgress>0?fR4(Q,DXQ,oT(this.dismissProgress)):Q}build(A){let Q=S4.of(A).colorScheme,$=FA.of(A),B=this.currentOrbPalette(),D=N7(1,"frontier",B),E=W4.of(A).size,J=this.widget.animationProgress??this.animationProgress,U=Math.max(E.width/aT,E.height/Jq)*eZQ,Y=U+(1-U)*J,Z=oT(this.dismissProgress),X=Math.max(aT,Math.round(aT*Y)),I=Math.max(Jq,Math.round(Jq*Y)),G=Math.round((E.width-X)/2),V=Math.round((E.height-I)/2),z=Math.max(0,Math.floor((E.width-aT)/2)),K=-Math.floor(Jq/2),C=Math.round(G+(z-G)*J),W=Math.round(V+(K-V)*J),u=C+X/2,H=W+I/2,N=EXQ({dismissProgress:this.dismissProgress,easedDismissProgress:Z,introOrbScale:Y,normalOrbCenterX:u,normalOrbCenterY:H,size:E}),w=Math.max(aT,Math.round(aT*N.orbScale)),M=Math.max(Jq,Math.round(Jq*N.orbScale)),R=N.orbCenterX,S=N.orbCenterY,T=Math.round(R-w/2),f=Math.round(S-M/2),m=Math.max(3,Math.min(E.height-5,Math.floor(Jq/2)+2)),x=Math.max(m+3,E.height-3),v=N.textDissolveProgress,k=this.isFinalIntroStage()?N.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&v<1,d=c&&this.firstStageHintVisible,b=d&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,s=Math.max(24,Math.min(74,E.width-4)),X0=Math.min(12,Math.max(8,E.height-m-6)),E0=Math.max(0,Math.floor((E.width-s)/2)),G0=Math.max(0,Math.min(E.height-X0,Math.floor(E.height*0.55-X0/2))),N0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new EK({width:w,height:M,agentMode:"frontier",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new EK({width:w,height:M,agentMode:"frontier",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new U$({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(t)=>{if(t.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&t.key==="c"&&t.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&t.key==="q")return this.widget.onQuit?.(),"handled";if((t.key===" "||t.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(t.key==="Escape"||t.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(t.key==="ArrowRight")return this.nextIntroStage(),"handled";if(t.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new A6({fit:"expand",children:[new dR4({color:Q.background,dissolveProgress:k}),new A6({fit:"expand",children:[new pA({onClick:()=>{},child:h0.expand()}),new r1({left:T,top:f,width:w,height:M,child:N0}),...c?[new r1({left:E0,top:G0,width:s,height:X0,child:JXQ({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:s,height:X0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:D,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:v,context:A})})]:[],...d?[...b?[new r1({left:E0,top:Math.max(0,x-1),width:s,height:1,child:new J0({text:GXQ({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new r1({left:E0,top:x,width:s,height:1,child:zXQ({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:v,context:A})})]:[]]})]})})}}class dR4 extends U3{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new cR4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class cR4 extends xA{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;sA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),D=Math.floor($+this.offset.y),E=Math.floor(this.size.width),F=Math.floor(this.size.height),J={bg:this.color},U=b9(this.dissolveProgress);if(U<=0){A.fill(B,D,E,F," ",J);return}if(U>=1)return;for(let Y=0;Y<F;Y++)for(let Z=0;Z<E;Z++)if(!FXQ(Z,Y,E,F,U))A.fill(B+Z,D+Y,1,1," ",J)}}function b9(A){return Math.min(1,Math.max(0,A))}function oT(A){return 1-(1-A)**3}function kR4(A){return SR4[A]??SR4[0]}function fR4(A,Q,$){return{primary:gN(A.primary,Q.primary,$),secondary:gN(A.secondary,Q.secondary,$)}}function EXQ({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:D,size:E}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(E.width*0.54-B)*Q,orbCenterY:D-E.height*0.44*Q,textDissolveProgress:b9(A/0.52),backdropDissolveProgress:oT(b9((A-0.12)/0.88))}}function FXQ(A,Q,$,B,D){let E=B<=1?0:Q/(B-1),F=pR4(A+Q*Math.max(1,$));return(1-E)*0.72+F*0.28<D}function JXQ({introStages:A,stage:Q,previousStage:$,progress:B,direction:D,width:E,height:F,foreground:J,mutedForeground:U,accent:Y,link:Z,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return nc0({introStages:A,stage:Q,foreground:J,mutedForeground:U,accent:Y,link:Z,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let z=oT(B),K=D*Math.round((1-z)*E),C=-D*Math.round(z*E);return new LN(new A6({fit:"expand",children:[new r1({left:C,top:0,width:E,height:F,child:nc0({introStages:A,stage:$,foreground:J,mutedForeground:U,accent:Y,link:Z,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new r1({left:K,top:0,width:E,height:F,child:nc0({introStages:A,stage:Q,foreground:J,mutedForeground:U,accent:Y,link:Z,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function nc0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:D,link:E,keybind:F,titleRevealProgress:J,dissolveProgress:U,context:Y}){let Z=A[Q]??A[0]??oc0[0],X=new $0({color:D,bold:!0}),I=new $0({color:$}),G=A===oc0&&Q===0,V=[...Z.title===null?[]:[new J0({text:G?a80(ZXQ({progress:J,foreground:D,pulseColor:D}),U):new g(zD(Z.title,U),X),textAlign:"center"})],...Z.body.length>0?[UXQ()]:[],...Z.body.map((z)=>YXQ(z,I,B,E,F,U,Y))];return new AQ({child:new cA({padding:e0.horizontal(1),child:new IA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function UXQ(){return h0.height(1)}function YXQ(A,Q,$,B,D,E,F){if(typeof A==="string")return new J0({text:new g(zD(A,E),Q),textAlign:"center"});if("codeBlock"in A)return new ZD({onCopy:(J,U)=>{if(U)D6.success(F,"Copied to clipboard",2000)},child:new IA({mainAxisSize:"min",children:A.codeBlock.map((J)=>new J0({text:new g(zD(J,E),new $0({color:D})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let J=new J0({text:new g("",void 0,[new g(zD(A.text,E),new $0({color:$,dim:!0})),new g(zD(A.keybind,E,F4(A.text).length),new $0({color:D}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new AQ({child:new ZD({child:J})});return J}if("highlightText"in A){let J=N$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),U=AI.of(F),Y=new g("",void 0,[new g(A.text,Q),new g(A.highlightText,new $0({color:D})),new g(A.textAfterHighlight,Q),new g(J.text,J.style,J.children,J.hyperlink,()=>{u$(F,A.href,{forceExternal:!1,onShowImagePreview:U})}),new g(A.textAfter,Q)]);return new J0({text:a80(Y,E),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new IA({mainAxisSize:"min",children:[new J0({text:new g(zD(A.text,E),Q),textAlign:"center"}),new AQ({child:new qA({mainAxisSize:"min",children:[N$.createWidget(F,A.href,zD(A.linkText,E),new $0({color:B,underline:!0})),new J0({text:new g(zD(A.textAfter,E),Q)})]})})]});let J=N$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),U=AI.of(F),Y=new g("",void 0,[new g(A.text,Q),new g(J.text,J.style,J.children,J.hyperlink,()=>{u$(F,A.href,{forceExternal:!1,onShowImagePreview:U})}),new g(A.textAfter,Q)]);return new J0({text:a80(Y,E),textAlign:"center"})}if(E>0)return new J0({text:new g(zD(A.text,E),new $0({color:B,underline:!0})),textAlign:"center"});return new AQ({child:N$.createWidget(F,A.href,A.text,new $0({color:B,underline:!0}))})}function ZXQ({progress:A,foreground:Q,pulseColor:$}){let B=new $0({color:Q,bold:!0}),D=new $0({color:IXQ({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new g("",void 0,[new g(XXQ(A).padEnd(rc0," "),B),new g(" ",B),new g(xR4(hR4,$XQ,A,0.72),B),new g(" ",B),new g(xR4(gR4,BXQ,A,0.88),D)])}function XXQ(A){let Q=F4(bR4),$=Math.min(rc0,Math.ceil(b9(A/0.62)*rc0));return Q.slice(0,$).join("")}function xR4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function IXQ({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=b9((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function GXQ({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new g(zD(`${A}/${Q}`,B),new $0({color:$,dim:!0}))}function VXQ({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:E}){let F=new $0({color:B}),J=new $0({color:$,dim:!0}),U=Q?A?"Enter":"Space":"Esc",Y=Q?A?" to get started":" to continue":" to quit",Z="",X="",I=`${Y}`;if(!Q)return new g("",void 0,[new g(U,F),new g(Y,J),new g("",F),new g("",J)]);let G=yR4(U,D),V=yR4(I,b9((D*(F4(U).length+F4(I).length)-F4(U).length)/F4(I).length));return new g("",void 0,[new g(zD(G,E),F),new g(zD(V.slice(0,Y.length),E),J),new g(zD(V.slice(Y.length,Y.length+0),E),F),new g(zD(V.slice(Y.length+0),E),J)])}function zXQ({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:E,context:F}){if(Q)return new J0({text:VXQ({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:E}),textAlign:"center"});let J=new $0({color:B}),U=new $0({color:$,dim:!0});return new ZD({onCopy:(Y,Z)=>{if(Z)D6.success(F,"Copied to clipboard",2000)},child:new J0({text:new g("",void 0,[new g("q",J),new g(" to quit",U)]),textAlign:"center",selectable:!0})})}function yR4(A,Q){let $=F4(A),B=Math.min($.length,Math.ceil(b9(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function a80(A,Q,$=0){if(Q<=0)return A;let B=$+F4(A.text??"").length,D=A.children?.map((E)=>{let F=a80(E,Q,B);return B+=F4(E.toPlainText()).length,F});return new g(A.text?zD(A.text,Q,$):A.text,A.style,D,A.hyperlink,A.onClick)}function zD(A,Q,$=0){if(Q<=0)return A;return F4(A).map((D,E)=>{if(D.trim()==="")return D;return pR4($+E)<Q?" ":D}).join("")}function pR4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function KXQ(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function CXQ(A,Q={}){return new Promise(($,B)=>{let D=!1,E=setTimeout(()=>{F.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),F=A.observer.agentState().subscribe((J)=>{if(nB(J)){D=!0;return}if(!D)return;let U=KXQ(A);if(U===null)return;clearTimeout(E),F.unsubscribe(),$(U)})})}class tc0 extends a0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new iR4}}class iR4 extends n0{editorController=new KY;commandPalette=new bp(this);commandRegistry=new Om0;toastController=new fb0;relaunchNotificationController=new Km0;exitHintTimer=new yp(this,1000);ideStatus=new t3(this,{});threadNavigationHistory=new Wm0;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new Qi;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;loadThreads=async()=>{return this.widget.context.listThreads()};analyzeContextForThread=async(A,Q)=>{return nK4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};threadListSidebar=new pc0({state:this,isAvailable:()=>this.widget.context.isInternalUser,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),onSelectThread:this.onSwitchThread});sendFeedbackReport=async(A)=>iD0({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await P70({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await oH4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await rH4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(bX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.notices=new eg0(this.widget.configService,($)=>this.setState($)),W$.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(_.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(z00($.settings)))}),this.updateRelaunchIntegration=new um0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new Vm0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new rh0({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=I1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.context.pluginService?Kw4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[],B=[Ow4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100,run:(D,E,F)=>{D.pushWithDismiss((J)=>id0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:J,onThreadSelected:F}))}},...this.threadListSidebar.commands(),{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(D,E,F)=>{A.navigateBack(),F()}},CM4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(D,E,F)=>{A.navigateForward(),F()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"},run:(D,E,F)=>{D.push(new Ed0({mcpServers:this.widget.context.mcpServers,onDismiss:F}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"},run:(D)=>{D.pushWithDismiss((E)=>new lc0({toolboxes:this.widget.context.toolboxes,onDismiss:E}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"},run:async(D,E,F)=>{try{await u$(E,"https://ampcode.com/chronicle")}finally{F()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"},run:()=>{lz(this.widget.context.settingsFilePath).catch((D)=>{_.error("Failed to open settings file in editor",{error:D})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"},run:(D,E,F)=>{D.pushWithDismiss((J)=>new Dd0({onCancel:J,onSelect:(U)=>{this.handleIdeSelection(U),F()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["manual","?"],status:{type:"enabled"},run:(D,E,F)=>{D.push(new Lm0({commands:AB.of(E).commands,onDismiss:F}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"},run:(D,E,F)=>{F(),A.showWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"},run:(D,E,F)=>{F(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"},run:(D,E,F)=>{D.push(new r4({header:"Amp Version",maxWidth:72,onDismiss:F,child:new J0({text:new g($70({version:"0.0.1779973320-g362e01",buildTimestamp:"2026-05-28T13:06:47.398Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],shortcut:CA.ctrl("c"),status:{type:"enabled"},run:(D,E)=>{H4.maybeInvoke(E,new OT)}},...Q,...aH4(this.widget.context.logFilePath)].map((D)=>this.commandRegistry.register(D));return()=>{for(let D of B)D()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,D=new hc0({initialAgentMode:this.widget.context.sessionAgentMode,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(Z)=>this.notices.dismiss(Z)}),E=W4.of(A),F=E.capabilities.animationSupport!=="disabled",U=[new WA({constraints:Y4.tight(E.size.width,E.size.height),child:this.threadListSidebar.buildBody(D)})];if(this.commandPalette.isEnabled())U.push(new U$({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new Mm0({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)U.push(id0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)U.push(new U$({debugLabel:"WelcomeDialogOverlay",child:new sc0({onDismiss:this.dismissWelcome,onQuit:()=>I1.instance.stop(),animationsEnabled:F,variant:this.widget.welcomeVariant})}));let Y=this.executorAlreadyConnectedDialog;if(Y)U.push(new U$({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new $d0({existingExecutorPid:Y.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(U.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),U.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)U.push(new Rm0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:o80.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)U.push(new Bd0);if(this.endCreditsVisible)U.push(new rm0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));return new h6({context:this.widget.context,child:new AB({commandRegistry:this.commandRegistry,child:new _T({completionBuilder:this.widget.completionBuilder,child:new D6({controller:this.toastController,child:new H4({actions:this.buildActions(),child:new e6({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),child:new u6({debugLabel:"AppShellFocus",child:new xb0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new jm0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new A6({children:U})})})})})})})})})})}buildShortcuts(){let A=new Map([[CA.ctrl("c"),new n70],[CA.ctrl("o"),new o70],[CA.alt("i"),new s70],[CA.alt("p"),new Kp],[CA.ctrl("."),new AD0],[CA.ctrl("t"),new BD0],...this.threadListSidebar.shortcutEntries()]);if(o80.env.NODE_ENV==="development"&&o80.platform==="darwin")A.set(CA.meta("r"),new a70);return A}buildActions(){let A=new dA(()=>{if(nF.hasAnyCopyableSelection())return nF.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new dA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new dA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new dA(()=>{return this.startNewDraftThread(),"handled"}),D=new dA(()=>{return I1.instance.stop(),"handled"}),E=new dA(()=>{return ll({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),F=new dA((I)=>{if(!I.text)return"ignored";return I1.instance.tuiInstance.clipboard.writeText(I.text).then((G)=>{if(G.ok)this.toastController.show(I.successMessage,"success",2000);else this.toastController.show(`${I.failureMessage}: ${G.userFacingErrorMessage}`,"error",4000)}).catch((G)=>{_.error("Failed to copy Neo text to clipboard",{error:G}),this.toastController.show(I.failureMessage,"error",2000)}),"handled"}),J=new dA(()=>{return I1.instance.toggleFrameStatsOverlay(),"handled"}),U=new dA(()=>this.notices.dismissCurrent()?"handled":"ignored"),Y=new dA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),Z=xw4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new dA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[n70,A],[Vl,B],[OT,D],[a70,E],[Z3,F],[Wl,$],[o70,Q],[s70,Y],...this.threadListSidebar.actionEntries(),[AD0,U],...Z,[Kp,J],[BD0,X]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await oP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){_.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=UY(Q),D=q50(this.widget.context,Q);if(B!==void 0&&D!==void 0)$={...$,[B]:D};return N50($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=lR4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(FU(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=lR4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(ez);if(this.exitHintTimer.isActive())A.add(uT);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),I1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),YY((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{_.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")I1.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,D,E)=>{await this.ensureDraftThreadSettingsInitialized();let F=this.activeThreadContext?.client.getThreadId(),J=A.find(U00);if(J)this.widget.history.add(J.text,o80.cwd()),this.widget.history.reset();let U=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Y=$??U??null,Z=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Y??void 0,D,E);if(this.sendUserMessage(Z,A,D?void 0:Q,D?void 0:B),!D)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(F),this.setActiveClient(Z)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=UY(A),D=B?Q[B]:void 0;if(D!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:D};YY((E)=>{let F={...E,agentMode:A};if($!==void 0)F={...F,lastReasoningEffortByMode:{...F.lastReasoningEffortByMode??{},[A]:$}};if(D!==void 0)F={...F,lastSpeedByMode:{...F.lastSpeedByMode??{},[A]:D}};return F}).catch((E)=>{_.warn("Failed to persist Neo session defaults for new message",{error:E instanceof Error?E.message:String(E)})})}sendUserMessage(A,Q,$,B){let D=Q70(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{userState:D});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,userState:D})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("appendToThread is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.append is only available for the active executor thread");for(let D of A)this.sendUserMessage($,[{type:"text",text:D.content}])};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return xaA(yaA($.observer.protocolMessages()),A)};runPluginAgent=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1});this.sendUserMessage($,[{type:"text",text:Q.message}]);try{let B=await CXQ($,{timeoutMs:Q.timeoutMs}),D=$.client.getThreadId();return D?{threadID:D,text:B}:{text:B}}finally{this.widget.clientPool.disconnect($)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(D)=>this.promptExecutorAlreadyConnected(D)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(_.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){_.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(D)=>{A.sendPluginMessage(D)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(D)=>{A.sendPluginMessage(D)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){_.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function lR4(A,Q,$){let B={...A};for(let D of WXQ(Q,$)){if(!FU(A[D],Q[D]))continue;let E=$[D];if(E===void 0)delete B[D];else B[D]=E}return B}function WXQ(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}e$();function nR4(A,Q,$,B){let D=yyA(A),E="\x1B[0m",F="\x1B[34m",J="\x1B[90m",U="\x1B[2m",Y=[];if(A.archived)Y.push("\x1B[90m\x1B[2mArchived\x1B[0m");Y.push(`${D}`),Y.push(`\x1B[34m${Q}\x1B[0m`),Y.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let Z=14,X=7,I=new iF(Z,X),G=new x5(42),V=new kT(Z,X,Z,X,Z,X,0,A.agentMode??"smart","intensity","braille",void 0,void 0,d0.default(),G);V.layout(Y4.tight(Z,X)),V.paint(I,0,0);let z=I.getBuffer().getCells(),K=0;for(let R=0;R<X;R++)if(z[R].some((S)=>S.char!==" ")){K=R;break}let C=X-1;for(let R=X-1;R>=0;R--)if(z[R].some((S)=>S.char!==" ")){C=R;break}function W(R,S){if(!R)return"";if(R.type==="rgb"){let{r:T,g:f,b:m}=R.value;if($.getColorDepth()>=24)return`\x1B[${S?38:48};2;${T};${f};${m}m`;let x=jp(T,f,m);return`\x1B[${S?38:48};5;${x}m`}return""}let u=[];if(C>=K)for(let R=K;R<=C;R++){let S="";for(let T=0;T<Z;T++){let f=z[R][T],m=f.char,x=W(f.style.fg,!0);S+=x+m+"\x1B[0m"}u.push(S)}let H=u.length,N=Math.max(H,Y.length),w=Math.floor((N-H)/2),M=Math.floor((N-Y.length)/2);for(let R=0;R<N;R++){let S=" ".repeat(Z);if(R>=w&&R<w+H)S=u[R-w];let T=" ",f="";if(R>=M&&R<M+Y.length)f=Y[R-M];$.write(S+T+f+`
4904
4904
  `)}if(B)$.write(`
4905
4905
  \x1B[90m${B}\x1B[0m
4906
4906
  `)}b0();class ec0{status=yB.status;constructor(){this.autoConnect()}async connect(A){await yB.start(A,!0,"user-initiated"),yB.selectConfig(A)}autoConnect(){let A=yB.getSelectedConfig();if(A){yB.start(A,!0,"auto-startup").catch((Q)=>{_.error("Failed to auto-connect to IDE",{error:Q})});return}this.discoverAndConnect()}async discoverAndConnect(){try{await XhA();let A=await Eu({});if(A.length===1&&A[0])yB.selectConfig(A[0]),await yB.start(A[0],!0,"auto-startup")}catch(A){_.error("Failed to auto-discover IDE",{error:A})}}}b0();b0();import{exec as Uq}from"node:child_process";function aR4(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")Uq("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")Uq("powershell [console]::beep(800,200)");else if(process.platform==="linux")Uq("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="idle-review"){if(process.platform==="darwin")Uq("afplay /System/Library/Sounds/Glass.aiff")}else if(A==="requires-user-input"){if(process.platform==="darwin")Uq("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")Uq("powershell [console]::beep(1000,300)");else if(process.platform==="linux")Uq("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){_.error(`Failed to play notification sound (${A}):`,Q)}}r50();Mb0();var uXQ=2000,HXQ="Agent is ready",NXQ="Waiting for approval";function oR4(A){let Q=!0,$=!0,B=A.configService.config.subscribe((C)=>{Q=C.settings["notifications.enabled"]??!0,$=C.settings["notifications.system.enabled"]!==!1}),D=0,E=()=>{let C=G?.prepareTerminalTitleForNotification();if(C!==void 0)process.stdout.write(hz4(C))},F=(C)=>{if(!Q)return;let W=Date.now();if(W-D<uXQ)return;if(D=W,BT())return;if(wG4())E(),setTimeout(OG4,Yb0);else aR4(C)},J=()=>{F("idle"),V(HXQ)},U=()=>{F("requires-user-input"),V(NXQ)},Y=(C)=>C?.attempt===void 0||C.attempt===0,Z=null,X=null,I=null,G,V=(C)=>{if(!Q||!$)return;if(BT()&&!Ob0()&&!x50())return;E(),setTimeout(()=>{process.stdout.write(bz4(C))},Yb0)},z=()=>{Z?.unsubscribe(),X?.unsubscribe(),Z=null,X=null,I=null,G=void 0};return{attach:(C,W,u)=>{if(z(),G=u,W)X=W.subscribe({next:(H)=>{if(H===null)return;if(!Y(H))return;J()},error:(H)=>{_.debug("Neo notification active error stream errored",{error:H})}});Z=C.subscribe({next:(H)=>{try{let N=I!==null&&nB(I),w=I==="awaiting_approval",M=N||w;if(H==="awaiting_approval"&&!w)U();else if(H==="idle"&&M)J()}catch(N){_.debug("Neo notification handling failed",{error:N})}finally{I=H}},error:(H)=>{_.debug("Neo notification agent state stream errored",{error:H})}})},detach:z,unsubscribe(){z(),B.unsubscribe()}}}function qXQ({initialUserInput:A,showWelcome:Q,hideWelcome:$,welcomeVariant:B,welcomeDismissed:D}){if($)return{show:!1,markDismissedOnDismiss:!1};if(B==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let E=!A&&!D;return{show:E,markDismissedOnDismiss:E}}async function wXQ(A){await YY((Q)=>tP(Q,A,"interactive"))}async function rR4(A,Q={}){let{initialThreadIDs:$=[],initialUserInput:B,getDefaultNewThreadVisibility:D,openThreadPickerOnStart:E=!1,observerOnly:F=!1,initialAgentMode:J,initialReasoningEffort:U,onFirstFrame:Y,showWelcome:Z=!1,hideWelcome:X=!1,welcomeVariant:I="intro"}=Q,G=I==="npm-migration";if($.length>1)_.info("Resuming multiple initial threads",{threadIDs:$});let V=async(f)=>{let m=await A.getThreadFromServer(f);if(!m)return null;return tB0(m)},z=async(f)=>{let m=await A.getThreadFromServer(f);if(!m)throw Error(`Thread ${f} not found`);let x=await R3(f,A.configService,A.apiKey,{usesThreadActors:!0}),v=V8({endpoint:A.rivetEndpoint,poolName:x.poolName}),k={wsToken:x.wsToken,transport:"json-rpc"},d=await v.threadActor.get([x.threadId],{params:k}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:eB0(m)}),skipReadyWait:!0});if(!d.ok&&d.status!==409)throw Error(`Thread import failed (${d.status}): ${await d.text()}`);try{await J50(f,A.configService,A.apiKey,{executorType:"local-client"})}catch(b){_.warn("failed to mark thread as imported on server",{threadID:f,error:b instanceof Error?b.message:String(b)})}},K=new ey0(A.rivetEndpoint,A.apiKey,A.configService,{clientID:_z.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(f)=>A.pluginService.event.toolCall(f),requestPluginToolResult:(f)=>A.pluginService.event.toolResult(f),pluginService:A.pluginService,pluginPlatform:A.pluginPlatform,invokeTool:async(f,m)=>{let x=typeof m.args==="object"&&m.args!==null?m.args:{},v=await bz({toolName:m.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:m.toolCallId,threadId:f});return A.toolService.invokeTool(m.toolName,{args:x},v)},persistLastThreadID:wXQ,readFileSystemDirectory:A.readFileSystemDirectory},V,z),C=await zN(),W=qXQ({initialUserInput:B,showWelcome:Z,hideWelcome:X,welcomeVariant:I,welcomeDismissed:C.neoWelcomeDismissed}),u={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(f)=>{let m=await A.getThreadFromServer(f);return m?Z60(m):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:oc,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:G?!1:F,invadersHighScore:C.neoInvadersHighScore,sessionAgentMode:J??C.agentMode,explicitReasoningEffort:U,lastReasoningEffortByMode:C.lastReasoningEffortByMode,lastSpeedByMode:C.lastSpeedByMode,settingsFilePath:A.settingsFilePath,workspaceRoot:A.workspaceRoot},H=(f,m)=>{return Cz4({ampURL:A.ampURL,configService:A.configService,threadID:f,signal:m})},N=()=>uz4({apiKey:A.apiKey,configService:A.configService,rivetEndpoint:A.rivetEndpoint}),w=new ec0,M=oR4({configService:A.configService}),R=await A.configService.getLatest();I1.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:R.settings["terminal.animation"]===!1}});let S=new Set,T=new zm0;try{await Lb0(new tc0({clientPool:K,listSkillsForThread:H,completionBuilder:A.completionBuilder,history:new vy0,ideManager:w,configService:A.configService,updateService:A.updateService,initialThreadIDs:G?[]:$,notificationService:M,mcpTrustHandler:A.mcpTrustHandler,initialUserInput:G?void 0:B,getDefaultNewThreadVisibility:D,observeThreadSummaries:N,openThreadPickerOnStart:G?!1:E,workspaceSettingsFilePath:A.workspaceSettingsFilePath,context:u,showWelcome:W.show,welcomeVariant:I,onActiveThreadChange:A.setActiveThreadID,onRelaunchRequested:T.request,onWelcomeDismissed:W.markDismissedOnDismiss?()=>{YY(wz4).catch((m)=>{_.warn("Failed to mark Neo welcome as dismissed",{error:m})})}:void 0,onThreadArchived:(m)=>{S.add(m)},onFirstFrame:Y}));let f=K.lastActiveObservingClient;if(f&&T.shouldShowExitSummary){let{client:m,observer:x}=f,v=m.getThreadId();if(v){let k={id:v,title:x.title().getValue(),agentMode:x.agentMode,archived:S.has(v)},c=`${A.ampURL.replace(/\/$/,"")}/threads/${v}`;nR4(k,c,process.stdout)}}}finally{process.stdout.write(p50("")),M.unsubscribe(),K.dispose(),await A.dispose?.()}process.exit(T.relaunchIfRequested(A.workspaceRoot)??0)}import{execFile as OXQ}from"node:child_process";import{closeSync as sR4,openSync as MXQ,writeSync as LXQ}from"node:fs";import jXQ from"node:tty";var RXQ="\x1B[c",PXQ="\x1B[?1004h",TXQ="\x1B[?1004l",vXQ="\x1B[?u",tR4=200,_XQ="\x1B[>4;2m",SXQ="\x1B[?9001h",kXQ="\x1B[?9001l";function eR4(){let A=null;try{if(process.stdout.isTTY){let Q=process.stdout.getWindowSize();A=[Q[0],Q[1]]}}catch{}return{isTTY:process.stdout.isTTY,columns:process.stdout.columns??null,rows:process.stdout.rows??null,windowSize:A,hasRefreshSize:typeof process.stdout._refreshSize==="function"}}function fXQ(){if(process.stdout.isTTY)return{stream:process.stdout,target:"stdout",dispose:()=>{}};if(process.stderr.isTTY)return{stream:process.stderr,target:"stderr",dispose:()=>{}};if(process.platform!=="win32")try{let A=MXQ("/dev/tty","w");if(jXQ.isatty(A))return{stream:{write(Q){return LXQ(A,Q),!0}},target:"dev-tty",dispose:()=>{sR4(A)}};sR4(A)}catch{}return{stream:process.stdout,target:"stdout",dispose:()=>{}}}function q$(A,Q){if(!process.stdout.writable||process.stdout.destroyed){Q?.();return}let $=`${JSON.stringify(A)}
@@ -6800,7 +6800,7 @@ Start Amp from a smaller directory.`};function EI(A,Q){if(!IG4())return;_.debug(
6800
6800
  `)}function lT4(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async($,B)=>{let D=B.optsWithGlobals(),E=await Q(D),F=await E.settings.get("proxy"),J=TbA({settings:{url:E.ampURL,proxy:F},secrets:{getToken:(Y,Z)=>E.secrets.get(Y,Z)}}),U=await x4.userDisplayBalanceInfo({},{config:J});if(!U.ok){if(U.error.code==="auth-required")process.stderr.write(f0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(f0.red("Error: ")+U.error.message+`
6801
6801
  `),process.exit(1)}process.stdout.write(await mzQ(U.result.displayText)+`
6802
6802
  `),process.exit(0)})}var ZHQ=pi.join(DU,"logs","headless.log"),el0=pi.join(ty,"device-id.json");dX4();async function XHQ(){let A=await Promise.all(Du.map(async(Q)=>{try{return{query:Q,hasConfigs:(await Q.listConfigs()).length>0}}catch($){return _.debug("Failed to detect query-based IDE integration",{ideName:Q.ideName,error:$}),{query:Q,hasConfigs:!1}}}));for(let Q of A)if(Q.hasConfigs)return Q.query;return}function uk4(){XHQ().then((A)=>{if(A){let Q=R00(A.ideName);if(Q)tW(Q)}})}try{if(process.platform==="win32")await Promise.resolve().then(() => N4(uv(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){P7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
6803
- `)}function IHQ(A){process.emitWarning=(Q,$,B,D)=>{let E=typeof Q==="string"?Q:Q.message||String(Q),F=$||"Warning",J=!1;A.warn(E,{name:F,code:B})}}function wB(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")eG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli"&&qq(Q.mode))eG("experimental.agentMode",Q.mode)}function GHQ(A,Q){if(!Q$(Q))return;if(!h7(Q.user.email)){if(A.model)throw new MA("The --model flag is only available for Amp employees.",1);eG("internal.model",void 0);return}if(A.model)eG("internal.model",KHQ(A.model))}function Ik4(A){let Q=A.indexOf(":");if(Q===-1)throw new MA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new MA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function VHQ(A){if(A===void 0)return;let Q=A.trim();if(I00(Q))return Q;throw new MA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function zHQ(A,Q){if(fZ(A,Q))return;let $=Qu(A)?.levels,B=$?` Allowed for ${A}: ${$.join(", ")}.`:"";throw new MA(`Reasoning effort "${Q}" is not available for ${A} mode.${B}`,1)}function KHQ(A){if(!A.includes("="))return Ik4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let D=B.indexOf("=");if(D===-1)throw new MA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let E=B.slice(0,D).trim(),F=B.slice(D+1).trim();if(!E)throw new MA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!F)throw new MA(`Missing model value for mode "${E}". Expected "${E}=provider:model".`,1);Ik4(F),Q[E]=F}if(Object.keys(Q).length===0)throw new MA("No valid model overrides found in --model flag value.",1);return Q}function e90(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new bB0(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new bB0(`${Q} must be an integer <= ${$.max}`);return B}function CHQ(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 WHQ(A){try{return await Wk4(A,"utf-8")}catch{return A}}async function uHQ(A,Q,$){let B=CHQ(A,Q);if(!B)return;let D=Q$($)?$.features:[],E=Q$($)?$.user.email:void 0;if(!Hk4(D,NE.HARNESS_SYSTEM_PROMPT)&&!(E&&h7(E)))throw new MA("You are not allowed to do this.",1);eG("systemPrompt",await WHQ(B))}function Hk4(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}function HHQ(A){return A!=="pending"}function wq(A){if(!Q$(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function NHQ(A){let Q=wq(A);if(Q)return Q.id;if(eW(A))throw Error(A.error.message);throw Error("unreachable")}function qHQ(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 wHQ(A){let B=qHQ(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 MA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function $i0(A,Q){let $=mx0(Error(A.error.message));if($.message===WB.networkOffline||$.message===WB.networkTimeout)return wHQ(Q);if($.message!==WB.internalBug)return new MA($.message,1,$.suggestion);return new MA(A.error.message.replace(/^Error: /,""),1)}async function OHQ(){if(process.versions.bun)return!1;try{return await JY()==="npm"}catch(A){return _.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var Gk4=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??FF,description:`Custom settings file path (overrides the default location ${FF})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(_).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${oc})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:v9(),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:EF.SMART.key,description:`Set the agent mode (${tG({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"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}],Vk4=(A)=>("deprecated"in A)&&A.deprecated===!0,MHQ=(A)=>("hidden"in A)&&A.hidden===!0,LHQ=(A)=>("default"in A),jHQ=(A)=>("default"in A)?A.default:void 0;function zk4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=VHQ(Q.effort);if($!==void 0){if(qq(Q.mode))zHQ(Q.mode,$)}return $}var RHQ="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function qq(A){return Object.values(EF).some((Q)=>Q.key===A)}function PHQ(A,Q){if(qq(A))return A;throw new MA(`${Q} does not support plugin-defined agent modes`,1)}function THQ(A,Q){if(qq(Q))return{agentMode:Q};let $=A.agentModes.list().find((D)=>D.key===Q||D.label===Q);if(!$){let D=tG({}).map((J)=>J.mode).join(", "),E=A.agentModes.list().map((J)=>J.label).join(", "),F=E?` Plugin modes: ${E}.`:"";throw new MA(`Unknown agent mode '${Q}'. Built-in modes: ${D}.${F}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:EF.SMART.key,agent:$.agent,agentModeDisplay:B}}function vHQ(A,Q){let $=Q.args[0],B=Q.commands.map((E)=>E.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let E=B.filter((J)=>$.includes(J)||J.includes($)),F="Run amp --help for a list of available commands.";if(E.length>0)F=`Did you mean: ${E.join(", ")}? Or run amp --help for all commands.`;throw new MA(WB.unknownCommand($),1,F)}}var AE0=y0.file(YHQ.homedir()),Ai0=process.env.XDG_CONFIG_HOME?y0.file(process.env.XDG_CONFIG_HOME):l0.joinPath(AE0,".config");async function v3(A,Q,$){let B=$?.deferAuth??!1,D=$?.skipToolProviders??!1;ryA("0.0.1779959155-g362e01");let E=q00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:v0.of(y0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:AE0,userConfigDir:Ai0}),F=A.secrets.get("apiKey",A.ampURL),J=EL(E),U=null,Y=()=>{return},Z=new Promise((t)=>{Y=t}),X=F.then(async(t)=>{if(!t&&!B)await Z;return U??=J.subscribe(()=>{}),z4(J.pipe(I5(HHQ)))});X.catch(()=>{return}),LT4(E);let I=await E.getLatest();_.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let t=await F;if(G=Boolean(t),_.info("API key lookup before login",{found:Boolean(t),ampURL:A.ampURL,deferAuth:B}),!t)if(B)_.info("No API key found, continuing startup with deferred auth");else{T6.write(`No API key found. Starting login flow...
6803
+ `)}function IHQ(A){process.emitWarning=(Q,$,B,D)=>{let E=typeof Q==="string"?Q:Q.message||String(Q),F=$||"Warning",J=!1;A.warn(E,{name:F,code:B})}}function wB(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")eG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli"&&qq(Q.mode))eG("experimental.agentMode",Q.mode)}function GHQ(A,Q){if(!Q$(Q))return;if(!h7(Q.user.email)){if(A.model)throw new MA("The --model flag is only available for Amp employees.",1);eG("internal.model",void 0);return}if(A.model)eG("internal.model",KHQ(A.model))}function Ik4(A){let Q=A.indexOf(":");if(Q===-1)throw new MA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new MA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function VHQ(A){if(A===void 0)return;let Q=A.trim();if(I00(Q))return Q;throw new MA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function zHQ(A,Q){if(fZ(A,Q))return;let $=Qu(A)?.levels,B=$?` Allowed for ${A}: ${$.join(", ")}.`:"";throw new MA(`Reasoning effort "${Q}" is not available for ${A} mode.${B}`,1)}function KHQ(A){if(!A.includes("="))return Ik4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let D=B.indexOf("=");if(D===-1)throw new MA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let E=B.slice(0,D).trim(),F=B.slice(D+1).trim();if(!E)throw new MA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!F)throw new MA(`Missing model value for mode "${E}". Expected "${E}=provider:model".`,1);Ik4(F),Q[E]=F}if(Object.keys(Q).length===0)throw new MA("No valid model overrides found in --model flag value.",1);return Q}function e90(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new bB0(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new bB0(`${Q} must be an integer <= ${$.max}`);return B}function CHQ(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 WHQ(A){try{return await Wk4(A,"utf-8")}catch{return A}}async function uHQ(A,Q,$){let B=CHQ(A,Q);if(!B)return;let D=Q$($)?$.features:[],E=Q$($)?$.user.email:void 0;if(!Hk4(D,NE.HARNESS_SYSTEM_PROMPT)&&!(E&&h7(E)))throw new MA("You are not allowed to do this.",1);eG("systemPrompt",await WHQ(B))}function Hk4(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}function HHQ(A){return A!=="pending"}function wq(A){if(!Q$(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function NHQ(A){let Q=wq(A);if(Q)return Q.id;if(eW(A))throw Error(A.error.message);throw Error("unreachable")}function qHQ(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 wHQ(A){let B=qHQ(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 MA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function $i0(A,Q){let $=mx0(Error(A.error.message));if($.message===WB.networkOffline||$.message===WB.networkTimeout)return wHQ(Q);if($.message!==WB.internalBug)return new MA($.message,1,$.suggestion);return new MA(A.error.message.replace(/^Error: /,""),1)}async function OHQ(){if(process.versions.bun)return!1;try{return await JY()==="npm"}catch(A){return _.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var Gk4=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??FF,description:`Custom settings file path (overrides the default location ${FF})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(_).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${oc})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:v9(),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:EF.SMART.key,description:`Set the agent mode (${tG({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"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}],Vk4=(A)=>("deprecated"in A)&&A.deprecated===!0,MHQ=(A)=>("hidden"in A)&&A.hidden===!0,LHQ=(A)=>("default"in A),jHQ=(A)=>("default"in A)?A.default:void 0;function zk4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=VHQ(Q.effort);if($!==void 0){if(qq(Q.mode))zHQ(Q.mode,$)}return $}var RHQ="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function qq(A){return Object.values(EF).some((Q)=>Q.key===A)}function PHQ(A,Q){if(qq(A))return A;throw new MA(`${Q} does not support plugin-defined agent modes`,1)}function THQ(A,Q){if(qq(Q))return{agentMode:Q};let $=A.agentModes.list().find((D)=>D.key===Q||D.label===Q);if(!$){let D=tG({}).map((J)=>J.mode).join(", "),E=A.agentModes.list().map((J)=>J.label).join(", "),F=E?` Plugin modes: ${E}.`:"";throw new MA(`Unknown agent mode '${Q}'. Built-in modes: ${D}.${F}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:EF.SMART.key,agent:$.agent,agentModeDisplay:B}}function vHQ(A,Q){let $=Q.args[0],B=Q.commands.map((E)=>E.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let E=B.filter((J)=>$.includes(J)||J.includes($)),F="Run amp --help for a list of available commands.";if(E.length>0)F=`Did you mean: ${E.join(", ")}? Or run amp --help for all commands.`;throw new MA(WB.unknownCommand($),1,F)}}var AE0=y0.file(YHQ.homedir()),Ai0=process.env.XDG_CONFIG_HOME?y0.file(process.env.XDG_CONFIG_HOME):l0.joinPath(AE0,".config");async function v3(A,Q,$){let B=$?.deferAuth??!1,D=$?.skipToolProviders??!1;ryA("0.0.1779973320-g362e01");let E=q00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:v0.of(y0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:AE0,userConfigDir:Ai0}),F=A.secrets.get("apiKey",A.ampURL),J=EL(E),U=null,Y=()=>{return},Z=new Promise((t)=>{Y=t}),X=F.then(async(t)=>{if(!t&&!B)await Z;return U??=J.subscribe(()=>{}),z4(J.pipe(I5(HHQ)))});X.catch(()=>{return}),LT4(E);let I=await E.getLatest();_.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let t=await F;if(G=Boolean(t),_.info("API key lookup before login",{found:Boolean(t),ampURL:A.ampURL,deferAuth:B}),!t)if(B)_.info("No API key found, continuing startup with deferred auth");else{T6.write(`No API key found. Starting login flow...
6804
6804
  `);let C0=await _HQ(A),l=await A.secrets.get("apiKey",A.ampURL);if(_.info("Login flow completed",{success:C0,storedKeyPresent:Boolean(l),ampURL:A.ampURL}),!C0)await FY(),process.exit(1);G=!0,Y()}}{let t=await E.getLatest(),C0=t.settings.url,l=t.secrets.isSet?.[C0];_.info("Config secrets state after login",{configURL:C0,apiKeySet:l?.apiKey??!1})}let V=B?"pending":await X;if(!B)_.info("Server status resolved",{status:"ready",isAuthenticated:Q$(V),isError:eW(V),errorMessage:eW(V)?V.error.message:void 0});GHQ(Q,V);let z=X.then((t)=>NHQ(t));z.catch(()=>{return});let K=Q$(V),C=!1;if(process.env.AMP_DISABLE_PLUGINS==="1")_.warn("Ignoring AMP_DISABLE_PLUGINS outside development");let W=C?"off":"all",{toolService:u,dispose:H}=N24({configService:E}),N=new Map,w=()=>N.clear(),M=new fO0(E,A.settings.getWorkspaceRootPath()),R=qtA({configService:E}),S=EaA({configService:E,trustStore:M,skillMCPServers:R.skillMCPServers,uploadImageAttachments:K,createOAuthProvider:async(t,C0,l)=>{let i=`${t}:${C0}`,A0=N.get(i);if(A0)return _.debug("Reusing existing OAuth provider for server",{serverName:t,serverUrl:C0}),A0;_.debug("Creating OAuth provider for server",{serverName:t,serverUrl:C0});let r=(async()=>{let B0=new Xu(A.secrets),Q0=await B0.getClientInfo(t,C0),V0=l?.scopes??Q0?.scopes,z0=PG4();_.info("OAuth headless mode check",{useHeadless:z0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:T6.isTTY});let w0;if(z0)w0=A.executeMode?RG4():jG4(t);let I0=new ON0({storage:B0,serverName:t,serverUrl:C0,clientId:l?.clientId??Q0?.clientId,clientSecret:l?.clientSecret??Q0?.clientSecret,authUrl:l?.authUrl??Q0?.authUrl,tokenUrl:l?.tokenUrl??Q0?.tokenUrl,scopes:V0,headlessAuthHandler:w0});return _.debug("OAuth provider created",{serverName:t,serverUrl:C0,hasManualClientId:!!(l?.clientId??Q0?.clientId),willUseDCR:!(l?.clientId??Q0?.clientId),scopes:V0,headlessMode:z0,executeMode:A.executeMode}),I0})();return N.set(i,r),r}}),T=I_0({configService:E,spawn:c$0}),f=Q.headless?rP4():void 0,m=f??new J90({configService:E}),x=m instanceof J90?m:void 0;if(x)x.pluginExecutorKind="local";let v=new G4(null),k=null,c=K&&!C?[...eP4(I.settings)?[{name:"permissions",entryPoint:zp0}]:[],{name:"thread-visibility",entryPoint:$T4(E,()=>X.then(wq),()=>k,(t)=>{k=t}),alwaysLoad:!0}]:[],d=aO0({configService:E,platform:m,loadGlobalPlugins:$y0(E),pluginFilter:W,activeThread$:v,internalPlugins:c}),b=DoA(d),p=[S,T,b],n;if(D)n=new Map;else if(A.executeMode){let t=await J84({toolService:u,providers:p,initialTimeout:15000});n=t.registrations;for(let[C0,l]of t.initErrors)_.warn(`${C0} provider initialization slow or failed:`,l)}else n=G_0({toolService:u,providers:p});if(Q.jetbrains)tW("JetBrains");else if(Q.ide&&AV4())tW("VS Code");else if(Q.ide&&QV4())tW("Neovim");else if(Q.ide&&A.executeMode)uk4();if(A.executeMode)syA(!0);let s,X0=yB.status.pipe(TA((t)=>Boolean(t.connected&&t.authenticated&&t.ideName&&DhA(t.ideName))),f1()).subscribe((t)=>{if(t){if(!s)s=u.registerTool(F84)}else s?.dispose(),s=void 0}),E0;if(!A.executeMode){let t=await A.settings.get("fuzzy.alwaysIncludePaths")??[];E0=new Y50(process.cwd(),{alwaysIncludePaths:t},!0)}else E0=new class extends Y50{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let G0=new vL0(Yg(E,{usesThreadActors:!1}),{maxThreads:200});_.info("Starting Amp background services");let Z0=new qp0,N0={configService:E,toolService:u,mcpService:S,skillService:R,toolboxService:T,trustStore:M,threadService:G0,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:E0,terminal:Z0,pluginService:d,pluginPlatform:x,headlessPluginPlatform:f,activeThread$:v,serverStatus:V,serverStatusPromise:X,viewerUserIDPromise:z,hasAPIKeyAtStartup:G,consumeDraftNewThreadVisibility:()=>{let t=k;return k=null,t}};return{...N0,async asyncDispose(){if(N0.mcpService.hasAuthenticatingClients())_.info("Waiting for OAuth authentication to complete before exit..."),await N0.mcpService.waitForAuthentication();for(let t of n.values())t.dispose();await N0.mcpService.dispose(),w(),await N0.threadService.asyncDispose(),N0.configService.unsubscribe(),U?.unsubscribe(),H(),N0.fuzzyServer.dispose(),N0.settingsStorage[Symbol.dispose](),X0.unsubscribe(),s?.dispose(),await N0.pluginService.dispose()}}}async function _HQ(A){if(!A.executeMode){if(!await D90("Would you like to log in to Amp? [(y)es, (n)o]: "))return T6.write(`Login cancelled. Run the command again to retry.
6805
6805
  `),!1}return await Nk4(A)}async function Nk4(A){let Q=FHQ(32).toString("hex"),$=await Yp0(A.ampURL,Q),B=new AbortController;try{await fG($,B.signal)}catch(E){_.error("Error opening browser",{error:E})}let D=await Yp0(A.ampURL,Q,!1);T6.write(`If your browser does not open automatically, visit:
6806
6806
 
@@ -6808,7 +6808,7 @@ ${f0.blue.bold(D)}
6808
6808
 
6809
6809
  `);try{return await _P4(A.ampURL,Q,A.secrets,B),T6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(E){return _.error("Login failed",{error:E}),P7.write(`
6810
6810
  Login failed: ${E instanceof Error?E.message:String(E)}
6811
- `),!1}}async function SHQ(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new MA("No Amp API key found. Run `amp login` first.",1);let D=EHQ("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((E,F)=>{D.on("error",F),D.on("close",(J)=>E(J??1))})}function kHQ(A){let Q=new kX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)FN(),process.exit(0);let u=W.originalError??W;YI4(u)}),oK4(Q,{version:"0.0.1779959155-g362e01",buildTimestamp:"2026-05-28T09:10:57.457Z",buildType:"release"}),Q.addHelpText("after",sG4()),Q.configureHelp({formatHelp:tG4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,u)=>{let H=u.optsWithGlobals(),N=await JQ(H);await lHQ(N)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(W,u)=>{let H=u.optsWithGlobals(),N=await JQ(H);await pHQ(N,await Cp0(H,N.settings))}),FI4(Q,JQ);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...W)=>{let u=W.find((M)=>typeof M==="object"&&M!==null&&typeof M.optsWithGlobals==="function")??B,H=W.filter((M)=>M!==u).flatMap((M)=>Array.isArray(M)?M:typeof M==="string"?[M]:[]),N=u.optsWithGlobals(),w=await JQ(N);await SHQ(w.ampURL,w.secrets,H),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(W,u,H)=>{let N=H.optsWithGlobals(),w=await JQ(N);await zG4(W??"get",w.ampURL,w.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(W,u)=>{let H=u.optsWithGlobals(),N=await JQ(H);await KG4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(W)=>{await $P4({raw:W.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
6811
+ `),!1}}async function SHQ(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new MA("No Amp API key found. Run `amp login` first.",1);let D=EHQ("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((E,F)=>{D.on("error",F),D.on("close",(J)=>E(J??1))})}function kHQ(A){let Q=new kX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)FN(),process.exit(0);let u=W.originalError??W;YI4(u)}),oK4(Q,{version:"0.0.1779973320-g362e01",buildTimestamp:"2026-05-28T13:06:47.398Z",buildType:"release"}),Q.addHelpText("after",sG4()),Q.configureHelp({formatHelp:tG4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,u)=>{let H=u.optsWithGlobals(),N=await JQ(H);await lHQ(N)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(W,u)=>{let H=u.optsWithGlobals(),N=await JQ(H);await pHQ(N,await Cp0(H,N.settings))}),FI4(Q,JQ);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...W)=>{let u=W.find((M)=>typeof M==="object"&&M!==null&&typeof M.optsWithGlobals==="function")??B,H=W.filter((M)=>M!==u).flatMap((M)=>Array.isArray(M)?M:typeof M==="string"?[M]:[]),N=u.optsWithGlobals(),w=await JQ(N);await SHQ(w.ampURL,w.secrets,H),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(W,u,H)=>{let N=H.optsWithGlobals(),w=await JQ(N);await zG4(W??"get",w.ampURL,w.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(W,u)=>{let H=u.optsWithGlobals(),N=await JQ(H);await KG4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(W)=>{await $P4({raw:W.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
6812
6812
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(W,u,H)=>{if(W&&u.apply)throw new MA("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let N=u.apply??W;if(!N||N.trim().length===0)T6.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.
6813
6813
 
6814
6814
  `),H.outputHelp(),process.exit(0);let w=H3(N)??FD(N),M=H.optsWithGlobals(),R=await JQ(M);wB(H,M);let S=await v3(R,M),T=!1;try{if(u.checkout&&u.skipCheckout)throw new MA("Choose either --checkout or --skip-checkout, not both.",1);if(eW(S.serverStatus))throw $i0(S.serverStatus,R.ampURL);let f=Q$(S.serverStatus)?S.serverStatus.features:void 0;if(!Hk4(f,NE.V2))throw new MA("live-sync is not enabled for your user",1);await HP4({ampURL:R.ampURL,threadId:w,configService:S.configService,threadService:S.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof u.apply==="string",checkoutMode:u.checkout?"always":u.skipCheckout?"never":"prompt",promptForYesNo:D90}),T=!0}finally{if(await S.asyncDispose(),T)process.exit(0)}});let D=async(W,u,H)=>{q00({storage:u.settings,secretStorage:u.secrets,workspaceRoot:v0.of(y0.file(process.cwd())),defaultAmpURL:u.ampURL,homeDir:AE0,userConfigDir:Ai0});let N={...u,executeMode:!1};await Qi0(N,{...W,openThreadSwitcher:!0},H)},E=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").option("--limit <number>","Maximum number of threads to return",(W)=>e90(W,"--limit",{min:1,max:500})).option("--offset <number>","Number of threads to skip",(W)=>e90(W,"--offset",{min:0})).action(async(W,u)=>{let H=u.optsWithGlobals(),N=await JQ(H);await Ck4(H,N,u)});E.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,u)=>{let H=u.optsWithGlobals(),N=await JQ(H);await DNQ(H,N,u)}),E.command("continue [threadIDOrURLs...]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly. When multiple thread are given, all are resumed and the first is shown in the foreground.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(W,u,H)=>{let N=H.optsWithGlobals(),w=await JQ(N),M=Array.isArray(W)?W:[];if(u.pick)P7.write(`${f0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -6833,8 +6833,8 @@ ${R}
6833
6833
 
6834
6834
  `)},async input(){return},async confirm(){return!1},async select(){return},async ask(){return{result:"uncertain",probability:0.5,reason:"AI not available"}}},loadGlobalPlugins:$y0(N),pluginFilter:process.env.PLUGINS??"all"}),asyncDispose:async()=>{}}}),zT4(Q,async(W)=>{let u=W.optsWithGlobals(),H=await JQ(u);wB(W,u);let N=await v3(H,u),w=await N.secretStorage.get("apiKey",H.ampURL);if(!w)throw await N.asyncDispose(),new MA("API key required. Please run `amp login` first.",1);return{configService:N.configService,actorOptions:{apiKey:w,ampURL:H.ampURL,workspaceRoot:process.cwd(),dependencies:N},cleanupTerminal:FN,asyncDispose:N.asyncDispose.bind(N)}}),OT4(Q,async(W)=>{let u=W.optsWithGlobals(),H=await JQ(u);wB(W,u);let N=await v3(H,u);return{settings:H.settings,configService:N.configService,skillService:N.skillService,asyncDispose:N.asyncDispose.bind(N)}}),iP4(Q,async(W)=>{let u=W.optsWithGlobals();return await JQ(u)}),bP4(Q,async(W)=>{let u=await JQ(W);return{settings:u.settings,secretStorage:u.secrets,getThreadDeps:async(H)=>{wB(H,W);let N=await v3(u,W);return{mcpService:N.mcpService,settings:u.settings,asyncDispose:N.asyncDispose.bind(N)}}}}),AI4(Q,JQ),lT4(Q,JQ);function Y(W,u,H){let w=typeof W.description==="string"?W.description:H===void 0?W.description(!0):W.description(H),M=new cF(u,w),R=jHQ(W);if(R)M.default(R);if(M.hidden=MHQ(W)||Vk4(W),"choices"in W&&Array.isArray(W.choices))if("hiddenChoices"in W){let S=[...W.choices],T=Array.isArray(W.hiddenChoices)?W.hiddenChoices:[],f=new Set([...S,...T]);M.argParser((m)=>{if(!f.has(m))throw new bB0(`Allowed choices are ${S.join(", ")}.`);return m})}else M.choices([...W.choices]);return M}for(let W of Gk4){switch(W.type){case"flag":{Q.addOption(Y(W,`--${W.long}`)),Q.addOption(Y(W,`--no-${W.long}`,!1));break}case"switch":{Q.addOption(Y(W,`--${W.long}`,!0));break}case"optional-option":{Q.addOption(Y(W,`${"short"in W?`-${W.short}, `:""}--${W.long} [value]`));break}default:{Q.addOption(Y(W,`${"short"in W?`-${W.short}, `:""}--${W.long} <value>`));break}}if("aliases"in W&&Array.isArray(W.aliases))for(let u of W.aliases){let H=new cF(`--${u}`,W.description);H.hidden=!0,H.implies({[W.name]:!0}),Q.addOption(H)}}Q.hook("preAction",(W,u)=>{if(u.optsWithGlobals().takeMeBack)UQ(RHQ)});let Z=new cF("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);Q.addOption(Z);let X=new cF("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp(!0);Q.addOption(X);let I=new cF("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);Q.addOption(I);let G=new cF("--stream-json-thinking","Include thinking blocks in stream JSON output (non-Claude Code extension). Implies --stream-json.").default(!1);Q.addOption(G);let V=new cF("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);Q.addOption(V);let z=new cF("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);Q.addOption(z);let K=new cF("--archive","When used with --execute, archive the thread after the command finishes.").default(!1);Q.addOption(K);let C=new cF("-l, --label <label>","When used with --execute, add a label to the thread. Repeat the flag for multiple labels.").argParser((W,u)=>{if(u===void 0)return[W];return[...u,W]});return Q.addOption(C),Q.action(async(W,u)=>{let H=W,N=await JQ(H);if(Object.keys(H).forEach((w)=>{let M=Gk4.find((R)=>R.name===w);if(M&&Vk4(M)&&!LHQ(M))P7.write(f0.yellow(`Warning: '--${w}' flag is deprecated
6835
6835
  `))}),u.args.length>0)vHQ(N,u);await Qi0(N,H,u)}),RV4(Q),Q}async function qk4(A,Q){await YY(($)=>tP($,A,Q))}async function fHQ(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await Wp0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await Wp0()).trimEnd(),stdinInput:null}}function xHQ(A,Q,$){if(A.remote&&!Q)throw new MA("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(A.streamJson&&!Q)throw new MA("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new MA("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new MA("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new MA("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 MA("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new MA("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 MA("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&$===""&&!A.streamJsonInput&&!A.headless)throw new MA("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"
6836
- Or pipe via stdin: echo "your message" | amp --execute`)}function yHQ(){TmA([H00.parse({tool:"*",action:"allow"})]),$mA({bypass:!0})}function bHQ(A){if(A.threadId&&!d7(A.threadId))delete A.threadId}async function Qi0(A,Q,$){if(Q.headless)return hHQ(A,Q,$);let B=await v3(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new MA("Cannot use --show-welcome and --hide-welcome together",1);let D=!A.executeMode&&await OHQ();return yHQ(),bHQ(Q),gHQ(A,Q,$,B,{showNpmMigrationWelcome:D})}async function hHQ(A,Q,$){let B=(C,W)=>{let u=Number(process.hrtime.bigint()-W)/1e6,H=mX4();_.info("Startup phase",{phase:C,phaseMs:Math.round(u),sinceMainMs:H===null?void 0:Math.round(H)})};wB($,Q);let D=process.hrtime.bigint(),E=await v3(A,Q);B("runMainThread:createThreadDependencies",D);let{serverStatus:F}=E;if(eW(F))throw $i0(F,A.ampURL);let J=Q$(F)?F:null,U=J?.user.email;await uHQ($,Q,F);let Y=wq(F),Z=Wi(Q,Y);if(Z instanceof Error)UQ(Z.message);if(J&&qq(Q.mode)&&!G00(Q.mode,U))throw new MA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!U||!h7(U)))throw new MA("Headless executor mode is only available for Amp employees",1);bx0();let I=await E.secretStorage.get("apiKey",A.ampURL);if(!I)throw new MA("API key required for headless mode. Please run `amp login` first.",1);let G=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(G&&!d7(G))throw new MA(`Invalid thread ID: ${G}`,1);let V=G?void 0:await $NQ({dependencies:E,apiKey:I,visibility:Z??void 0}),z=G??V?.threadId;if(!z)throw new MA("Failed to resolve headless thread ID",1);let K=await SG4(z);if(K.status==="already-running")await E.asyncDispose(),await FY(),process.exit(0);try{await NG4({ampURL:A.ampURL,apiKey:I,workspaceRoot:process.cwd(),threadId:z,ownerUserId:V?.ownerUserId,threadVersion:V?.threadVersion,agentMode:V?.agentMode,initialToolDiscovery:Promise.all([E.mcpService.initialized,E.toolboxService.initialized,E.pluginService.initialized]).then(()=>{return}),configService:E.configService,mcpService:E.mcpService,toolService:E.toolService,skillService:E.skillService,pluginService:E.pluginService,pluginPlatform:E.headlessPluginPlatform})}finally{await K.release(),await E.asyncDispose()}await FY(),process.exit(0)}async function gHQ(A,Q,$,B,D){let{userInput:E,stdinInput:F}=await fHQ(Q),J=!!Q.streamJson||!!Q.streamJsonThinking;xHQ({...Q,streamJson:J},A.executeMode,E),wB($,Q),aX4(),bx0();let U=Q.threadId,Y=Q.resumeThreadIDs??(U?[U]:[]),Z=Q.observe?H3(Q.observe)??FD(Q.observe):void 0,X=await B.serverStatusPromise;if(eW(X))throw $i0(X,A.ampURL);let I=wq(X),G=Wi(Q,I);if(G instanceof Error)UQ(G.message);if(A.executeMode&&Q.remote){if(!qq(Q.mode))throw new MA("Remote execute mode does not support plugin-defined agent modes",1);if(!Q$(X)||!h7(X.user.email))throw new MA("Remote execute mode is only available for Amp employees",1);await UT4(E,F,B.configService,Q.mode),await B.asyncDispose(),await FY(),process.exit(0)}let V=null,z=async()=>{let W=B.consumeDraftNewThreadVisibility();if(W!==null)return W;return V??=(async()=>{let u=await aB0(A.settings,process.cwd(),I,G);if(u instanceof Error)UQ(u.message);return u})(),V},K=await B.secretStorage.get("apiKey",A.ampURL);if(!K)throw new MA("API key required. Please run `amp login` first.",1);let C=Q$(X)&&h7(X.user.email);if(A.executeMode){if(Y.length>1)throw new MA("Execute mode can only resume one thread.",1);dP4(B.mcpService,A.settings);try{await B.pluginService.initialized;let W=THQ(B.pluginService,Q.mode),u=zk4($,Q),H=await zN(),N=U?u:Sy0({agentMode:W.agentMode,explicitEffort:u,sessionState:H}),w=U?void 0:N50(await oP(B.configService),{agentMode:W.agentMode,explicitEffort:u,sessionState:H}),M=U?void 0:await z(),{threadID:R}=await U50({apiKey:K,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:E,stdinInput:F,stats:!!Q.stats,streamJson:J,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:W.agentMode,reasoningEffort:W.agent?void 0:N,agent:W.agent,labels:Q.label,initialThreadID:U,initialThreadMeta:M,initialSettings:w});if(await qk4(R,"execute"),Q.archive)await B.threadService.archive(R,!0)}finally{await B.asyncDispose()}await FY(),process.exit(0)}else{let W=zk4($,Q),u=D.showNpmMigrationWelcome?"npm-migration":"intro",H=Ry0("0.0.1779959155-g362e01",B.settingsStorage,{startDelayMs:3000}),N=new Zp0(B.mcpService,A.settings.getWorkspaceRootPath()),w=Yg(B.configService),M=new Lp0(B.fuzzyServer),R=process.cwd();await rR4({ampURL:A.ampURL,apiKey:K,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??z8(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:S})=>cP({workspaceRoot:R},S),completionBuilder:M,updateService:H,workspaceRoot:R,listThreads:()=>w.listThreads(),getThreadFromServer:(S)=>w.getThread(S),toolboxes:B.toolboxService.toolboxes,isInternalUser:C,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:N,setActiveThreadID:(S)=>B.activeThread$.next(S),dispose:()=>{return N.dispose(),H.dispose(),B.asyncDispose()}},{initialThreadIDs:Z?[Z]:Y,initialUserInput:E||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?uk4:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!Z,hideWelcome:!!Q.hideWelcome,showWelcome:Q.showWelcome,welcomeVariant:u,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"&&qq(Q.mode)?Q.mode:void 0,initialReasoningEffort:W}),process.exit(0)}}async function JQ(A){if(_.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)P7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6837
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;_.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await ZaA({get:async(J)=>{if(J!==Ch)return;try{let U=await Wk4(el0,"utf-8");return JSON.parse(U).installationID}catch{return}},set:async(J,U)=>{if(J!==Ch)return;await JHQ(pi.dirname(el0),{recursive:!0}),await UHQ(el0,JSON.stringify({installationID:U},null,2),{mode:384})}},{clientType:"cli",platform:x40()});tyA(B);let D=await qT4({...A,workspaceTrust:{current:!0,changes:Zy},getHook:process.env.AMP_URL?(J,U)=>{if(J==="url")return Promise.resolve(process.env.AMP_URL);return U()}:void 0});if(A.mcpConfig){let J=await gP4(A.mcpConfig);D=mP4(D,J)}let E=pi.dirname(D.getSettingsFilePath());M24(ty,E),D=$kA(D);let F=await D.get("url","admin")??await D.get("url","global");if(!F)F=lD;if(_.info("Resolved Amp URL",{ampURL:F,settingsFile:D.getSettingsFilePath(),workspaceRoot:D.getWorkspaceRootPath()}),!$L(F))_.info("Targeting custom Amp server",{ampURL:F});return{executeMode:Q,isTTY:$,ampURL:F,settings:D,secrets:KT4(await Cp0(A,D))}}function mHQ(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let E=B.slice(2).replace(/-([a-z])/g,(J,U)=>U.toUpperCase()),F=A[$+1];if(F&&!F.startsWith("--"))Q[E]=F,$++}}return Q}function dHQ(A,Q){let $=A.includes("--headless")||A.some((D)=>D.startsWith("--headless=")),B=pi.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?ZHQ:oc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function cHQ(){gX4();let A=mHQ(process.argv),Q=dHQ(process.argv,A),$=oX4(Q);o30("silent");let B=process.argv.includes("--no-color"),D=process.argv.includes("--color"),E=process.stdout.isTTY&&process.stderr.isTTY;if(B||!D&&!E)f0.level=0;if(IHQ(_),_.info("Starting Amp CLI.",{version:"0.0.1779959155-g362e01",buildTimestamp:"2026-05-28T09:10:57.457Z"}),process.platform==="win32"&&VN())wV4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new MA(WB.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await kHQ($).parseAsync(process.argv)}w24().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await cHQ().catch(oB0)});async function pHQ(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),T6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6836
+ Or pipe via stdin: echo "your message" | amp --execute`)}function yHQ(){TmA([H00.parse({tool:"*",action:"allow"})]),$mA({bypass:!0})}function bHQ(A){if(A.threadId&&!d7(A.threadId))delete A.threadId}async function Qi0(A,Q,$){if(Q.headless)return hHQ(A,Q,$);let B=await v3(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new MA("Cannot use --show-welcome and --hide-welcome together",1);let D=!A.executeMode&&await OHQ();return yHQ(),bHQ(Q),gHQ(A,Q,$,B,{showNpmMigrationWelcome:D})}async function hHQ(A,Q,$){let B=(C,W)=>{let u=Number(process.hrtime.bigint()-W)/1e6,H=mX4();_.info("Startup phase",{phase:C,phaseMs:Math.round(u),sinceMainMs:H===null?void 0:Math.round(H)})};wB($,Q);let D=process.hrtime.bigint(),E=await v3(A,Q);B("runMainThread:createThreadDependencies",D);let{serverStatus:F}=E;if(eW(F))throw $i0(F,A.ampURL);let J=Q$(F)?F:null,U=J?.user.email;await uHQ($,Q,F);let Y=wq(F),Z=Wi(Q,Y);if(Z instanceof Error)UQ(Z.message);if(J&&qq(Q.mode)&&!G00(Q.mode,U))throw new MA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!U||!h7(U)))throw new MA("Headless executor mode is only available for Amp employees",1);bx0();let I=await E.secretStorage.get("apiKey",A.ampURL);if(!I)throw new MA("API key required for headless mode. Please run `amp login` first.",1);let G=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(G&&!d7(G))throw new MA(`Invalid thread ID: ${G}`,1);let V=G?void 0:await $NQ({dependencies:E,apiKey:I,visibility:Z??void 0}),z=G??V?.threadId;if(!z)throw new MA("Failed to resolve headless thread ID",1);let K=await SG4(z);if(K.status==="already-running")await E.asyncDispose(),await FY(),process.exit(0);try{await NG4({ampURL:A.ampURL,apiKey:I,workspaceRoot:process.cwd(),threadId:z,ownerUserId:V?.ownerUserId,threadVersion:V?.threadVersion,agentMode:V?.agentMode,initialToolDiscovery:Promise.all([E.mcpService.initialized,E.toolboxService.initialized,E.pluginService.initialized]).then(()=>{return}),configService:E.configService,mcpService:E.mcpService,toolService:E.toolService,skillService:E.skillService,pluginService:E.pluginService,pluginPlatform:E.headlessPluginPlatform})}finally{await K.release(),await E.asyncDispose()}await FY(),process.exit(0)}async function gHQ(A,Q,$,B,D){let{userInput:E,stdinInput:F}=await fHQ(Q),J=!!Q.streamJson||!!Q.streamJsonThinking;xHQ({...Q,streamJson:J},A.executeMode,E),wB($,Q),aX4(),bx0();let U=Q.threadId,Y=Q.resumeThreadIDs??(U?[U]:[]),Z=Q.observe?H3(Q.observe)??FD(Q.observe):void 0,X=await B.serverStatusPromise;if(eW(X))throw $i0(X,A.ampURL);let I=wq(X),G=Wi(Q,I);if(G instanceof Error)UQ(G.message);if(A.executeMode&&Q.remote){if(!qq(Q.mode))throw new MA("Remote execute mode does not support plugin-defined agent modes",1);if(!Q$(X)||!h7(X.user.email))throw new MA("Remote execute mode is only available for Amp employees",1);await UT4(E,F,B.configService,Q.mode),await B.asyncDispose(),await FY(),process.exit(0)}let V=null,z=async()=>{let W=B.consumeDraftNewThreadVisibility();if(W!==null)return W;return V??=(async()=>{let u=await aB0(A.settings,process.cwd(),I,G);if(u instanceof Error)UQ(u.message);return u})(),V},K=await B.secretStorage.get("apiKey",A.ampURL);if(!K)throw new MA("API key required. Please run `amp login` first.",1);let C=Q$(X)&&h7(X.user.email);if(A.executeMode){if(Y.length>1)throw new MA("Execute mode can only resume one thread.",1);dP4(B.mcpService,A.settings);try{await B.pluginService.initialized;let W=THQ(B.pluginService,Q.mode),u=zk4($,Q),H=await zN(),N=U?u:Sy0({agentMode:W.agentMode,explicitEffort:u,sessionState:H}),w=U?void 0:N50(await oP(B.configService),{agentMode:W.agentMode,explicitEffort:u,sessionState:H}),M=U?void 0:await z(),{threadID:R}=await U50({apiKey:K,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:E,stdinInput:F,stats:!!Q.stats,streamJson:J,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:W.agentMode,reasoningEffort:W.agent?void 0:N,agent:W.agent,labels:Q.label,initialThreadID:U,initialThreadMeta:M,initialSettings:w});if(await qk4(R,"execute"),Q.archive)await B.threadService.archive(R,!0)}finally{await B.asyncDispose()}await FY(),process.exit(0)}else{let W=zk4($,Q),u=D.showNpmMigrationWelcome?"npm-migration":"intro",H=Ry0("0.0.1779973320-g362e01",B.settingsStorage,{startDelayMs:3000}),N=new Zp0(B.mcpService,A.settings.getWorkspaceRootPath()),w=Yg(B.configService),M=new Lp0(B.fuzzyServer),R=process.cwd();await rR4({ampURL:A.ampURL,apiKey:K,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??z8(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:S})=>cP({workspaceRoot:R},S),completionBuilder:M,updateService:H,workspaceRoot:R,listThreads:()=>w.listThreads(),getThreadFromServer:(S)=>w.getThread(S),toolboxes:B.toolboxService.toolboxes,isInternalUser:C,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:N,setActiveThreadID:(S)=>B.activeThread$.next(S),dispose:()=>{return N.dispose(),H.dispose(),B.asyncDispose()}},{initialThreadIDs:Z?[Z]:Y,initialUserInput:E||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?uk4:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!Z,hideWelcome:!!Q.hideWelcome,showWelcome:Q.showWelcome,welcomeVariant:u,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"&&qq(Q.mode)?Q.mode:void 0,initialReasoningEffort:W}),process.exit(0)}}async function JQ(A){if(_.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)P7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6837
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;_.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await ZaA({get:async(J)=>{if(J!==Ch)return;try{let U=await Wk4(el0,"utf-8");return JSON.parse(U).installationID}catch{return}},set:async(J,U)=>{if(J!==Ch)return;await JHQ(pi.dirname(el0),{recursive:!0}),await UHQ(el0,JSON.stringify({installationID:U},null,2),{mode:384})}},{clientType:"cli",platform:x40()});tyA(B);let D=await qT4({...A,workspaceTrust:{current:!0,changes:Zy},getHook:process.env.AMP_URL?(J,U)=>{if(J==="url")return Promise.resolve(process.env.AMP_URL);return U()}:void 0});if(A.mcpConfig){let J=await gP4(A.mcpConfig);D=mP4(D,J)}let E=pi.dirname(D.getSettingsFilePath());M24(ty,E),D=$kA(D);let F=await D.get("url","admin")??await D.get("url","global");if(!F)F=lD;if(_.info("Resolved Amp URL",{ampURL:F,settingsFile:D.getSettingsFilePath(),workspaceRoot:D.getWorkspaceRootPath()}),!$L(F))_.info("Targeting custom Amp server",{ampURL:F});return{executeMode:Q,isTTY:$,ampURL:F,settings:D,secrets:KT4(await Cp0(A,D))}}function mHQ(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let E=B.slice(2).replace(/-([a-z])/g,(J,U)=>U.toUpperCase()),F=A[$+1];if(F&&!F.startsWith("--"))Q[E]=F,$++}}return Q}function dHQ(A,Q){let $=A.includes("--headless")||A.some((D)=>D.startsWith("--headless=")),B=pi.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?ZHQ:oc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function cHQ(){gX4();let A=mHQ(process.argv),Q=dHQ(process.argv,A),$=oX4(Q);o30("silent");let B=process.argv.includes("--no-color"),D=process.argv.includes("--color"),E=process.stdout.isTTY&&process.stderr.isTTY;if(B||!D&&!E)f0.level=0;if(IHQ(_),_.info("Starting Amp CLI.",{version:"0.0.1779973320-g362e01",buildTimestamp:"2026-05-28T13:06:47.398Z"}),process.platform==="win32"&&VN())wV4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new MA(WB.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await kHQ($).parseAsync(process.argv)}w24().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await cHQ().catch(oB0)});async function pHQ(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),T6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6838
6838
  `);else if(!$L(A.ampURL))T6.write(`Logging in to ${new URL(A.ampURL).hostname}
6839
6839
  `);let B=process.env.AMP_API_KEY;if(B)T6.write(`API key found in environment variable, storing...
6840
6840
  `),await Q.set("apiKey",B,A.ampURL),T6.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1779959155-g362e01",
3
+ "version": "0.0.1779973320-g362e01",
4
4
  "description": "Renamed to @ampcode/cli - see https://ampcode.com/news/npm-package-changes",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
@@ -8,7 +8,7 @@
8
8
  "amp": "node_modules/@ampcode/cli/bin/amp.exe"
9
9
  },
10
10
  "dependencies": {
11
- "@ampcode/cli": "0.0.1779959155-g362e01"
11
+ "@ampcode/cli": "0.0.1779973320-g362e01"
12
12
  },
13
13
  "files": [
14
14
  "dist/main.js",