@sourcegraph/amp 0.0.1779409185-ge486da → 0.0.1779426990-g24af9a

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 +11 -12
  2. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -4796,13 +4796,13 @@ ${z}`))}},error:(K)=>{if(!V)V=!0,Z(Error(`Failed to spawn brew: ${K.message}`))}
4796
4796
  ${z}`;if(F==="pnpm"&&z.includes("Unable to find the global bin directory"))W+=`
4797
4797
 
4798
4798
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4799
- npm install -g ${J}`;Z(Error(W))}},error:(K)=>{if(!G)G=!0,Z(Error(`Failed to spawn ${F}: ${K.message}`))},complete:()=>{if(!G)G=!0,E()}})})}p0();p0();zz();var BM3="@ampcode/cli";async function pE0(A,Q,$=BM3){let D=`${Q||"https://registry.npmjs.org"}/${$}/latest`,J=new AbortController,F=setTimeout(()=>J.abort(),5000);try{let Y=await fetch(D,{signal:J.signal});if(!Y.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let E=await Y.json(),Z=E.version??E["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let U=eo(A,Z),X=U<0,G,V;if(E.time){let K=E.time[A],z=E.time[Z],W=Date.now();if(K)G=Math.floor((W-new Date(K).getTime())/3600000);if(z)V=Math.floor((W-new Date(z).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:U,hasUpdate:X,currentVersionAge:G,latestVersionAge:V}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:G,latestVersionAge:V,source:"npm"}}catch(Y){return P.debug("Error checking npm version",{error:Y}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(F)}}var DM3="https://static.ampcode.com/cli/cli-version.txt";async function cE0(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${DM3}?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 J=eo(A,D),F=J<0;return P.info("Bin version comparison",{currentVersion:A,latestVersion:D,compareResult:J,hasUpdate:F}),{hasUpdate:F,latestVersion:D,currentVersion:A,source:"bin"}}catch(B){return P.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}var JM3=604800000;function ab4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let $=Date.now()-Q;if($>JM3)return{ageMs:$};return null}function eo(A,Q){let $=(F)=>{let[Y,E]=F.split("-");return{parts:Y?.split(".").map(Number)||[],label:E}},B=$(A),D=$(Q),J=Math.max(B.parts.length,D.parts.length);for(let F=0;F<J;F++){let Y=B.parts[F]||0,E=D.parts[F]||0;if(Y<E)return-1;if(Y>E)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 Ar(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,J=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],F=B!==void 0?uY(B):void 0;return{sha:J,timestamp:B,age:F}}catch{return null}}P1();p0();import{readFile as FM3,realpath as YM3}from"node:fs/promises";import{dirname as ob4,join as EM3}from"node:path";async function rb4(A){switch(A){case"binary":case"brew":return ZM3(so());case"npm":case"pnpm":case"yarn":case"bun":return UM3()}}async function ZM3(A){let Q=await LN(A,["--version"],5000);if(Q.reason!=="success")return P.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function UM3(){try{let A=process.argv[1];if(!A)return null;let Q=await YM3(A),$=ob4(ob4(Q));return await XM3(EM3($,"package.json"))}catch(A){return P.debug("failed to read installed version from package.json",{error:A}),null}}async function XM3(A){let Q=await FM3(A,"utf8"),$=JSON.parse(Q);if(!$.name||!$01($.name))return P.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}p0();import{spawn as GM3}from"node:child_process";function Z01(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return P.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var lE0=null,Qr=null;function sb4(A){return new Promise((Q)=>{let $=GM3("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,J)=>{if(D!==0||J==="SIGTERM"){Q(null);return}let F=B.trim();Q(F&&F!=="undefined"?F:null)}),$.on("error",()=>{Q(null)})})}async function iE0(){if(lE0)return lE0;if(Qr)return Qr;Qr=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return Z01(A);let Q=await sb4("@sourcegraph:registry");if(Q)return Z01(Q);let $=await sb4("registry");if($)return Z01($);return"https://registry.npmjs.org"})();try{return lE0=await Qr,lE0}finally{Qr=null}}var VM3=3600000,KM3=5000;function nE0(A,Q,$={}){let B=new d4,D=B.pipe(t6({shouldCountRefs:!1})),J=$.startDelayMs??0,F=$.checkIntervalMs??VM3,Y=!1,E=()=>{Y=!0};return setImmediate(async()=>{let Z=P.getChild("update");if(J>0){if(await BG(J),Y)return}let U=D.subscribe({next:(G)=>{Z.debug("emit new state",G)}}),X=A;try{while(!Y){let G=await zM3(X,Q,Z,B);if(G.stop)return;if(G.updatedTo)X=G.updatedTo;if(G.emittedVisibleState){if(await BG(KM3),Y)return;B.next("hidden")}if(F<=0)return;let V=1000,K=F;while(K>0&&!Y){let z=Math.min(V,K);await BG(z),K-=z}}}finally{U.unsubscribe(),B.complete()}}),{state:D,dispose:E}}async function zM3(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 J=await Q.get("updates.mode");if(J==="disabled")return $.debug("checking disabled"),D.stop=!0,D;let F=await kG(),Y=F==="binary"||F==="brew",E=Y?void 0:await ON();$.debug("checking",{currentVersion:A,mode:J,packageManager:F,isBinaryDistribution:Y,npmPackageName:E});let Z;if(Y)Z=await cE0(A);else{let G=await iE0();Z=await pE0(A,G,E)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),D;let U=(G)=>{B.next(G),D.emittedVisibleState=!0};if(F){let G=await rb4(F);if(G&&eo(G,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:G,latestVersion:Z.latestVersion}),D.updatedTo=G,eo(A,G)<0){let V=await dz(G),K={from:A,to:G,externallyUpdated:!0,...V};if(V.status==="same")$.info("on-disk already updated by another instance",K),U("updated");else $.warn("on-disk already updated by another instance, with PATH warning",K),U("updated-with-warning")}return D}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let G=Z.currentVersionAge-Z.latestVersionAge,V=0.5;if(Math.abs(G)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:G}),!0}return!1};if(!J)J=F==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:J});if(F==="brew"){if(!X())U("update-available-brew");return D}if(F==="binary"&&process.execPath!==so()){if($.debug("non-standard binary path, showing warning"),!X())U("update-available-unrecognized-path");return D}if(J==="warn"){if(!X())U("update-available");return D}if(!F){if($.debug("auto-update not supported, falling back to warn mode"),!X())U("update-available");return D}try{await to(Z.latestVersion,F),D.updatedTo=Z.latestVersion;let G=await dz(Z.latestVersion),V={from:Z.currentVersion,to:Z.latestVersion,...G};if(G.status==="same")$.info("success",V),U("updated");else $.warn("success with warning",V),U("updated-with-warning")}catch(G){U("update-error")}return D}catch(J){return $.debug("check failed",{error:J}),D}}zz();import{stderr as aY}from"node:process";function tb4(A){let Q=new JN().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 A01(B.force||!1,B.verbose||!1,"0.0.1779409185-ge486da"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new JN("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 HM3(B.targetVersion)});A.addCommand($)}function WM3(A){let Q=Boolean(A.isTTY),$=0,B=!1;function D(){if(!Q||!B)return;A.write(`
4799
+ npm install -g ${J}`;Z(Error(W))}},error:(K)=>{if(!G)G=!0,Z(Error(`Failed to spawn ${F}: ${K.message}`))},complete:()=>{if(!G)G=!0,E()}})})}p0();p0();zz();var BM3="@ampcode/cli";async function pE0(A,Q,$=BM3){let D=`${Q||"https://registry.npmjs.org"}/${$}/latest`,J=new AbortController,F=setTimeout(()=>J.abort(),5000);try{let Y=await fetch(D,{signal:J.signal});if(!Y.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let E=await Y.json(),Z=E.version??E["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let U=eo(A,Z),X=U<0,G,V;if(E.time){let K=E.time[A],z=E.time[Z],W=Date.now();if(K)G=Math.floor((W-new Date(K).getTime())/3600000);if(z)V=Math.floor((W-new Date(z).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:U,hasUpdate:X,currentVersionAge:G,latestVersionAge:V}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:G,latestVersionAge:V,source:"npm"}}catch(Y){return P.debug("Error checking npm version",{error:Y}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(F)}}var DM3="https://static.ampcode.com/cli/cli-version.txt";async function cE0(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${DM3}?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 J=eo(A,D),F=J<0;return P.info("Bin version comparison",{currentVersion:A,latestVersion:D,compareResult:J,hasUpdate:F}),{hasUpdate:F,latestVersion:D,currentVersion:A,source:"bin"}}catch(B){return P.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}var JM3=604800000;function ab4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let $=Date.now()-Q;if($>JM3)return{ageMs:$};return null}function eo(A,Q){let $=(F)=>{let[Y,E]=F.split("-");return{parts:Y?.split(".").map(Number)||[],label:E}},B=$(A),D=$(Q),J=Math.max(B.parts.length,D.parts.length);for(let F=0;F<J;F++){let Y=B.parts[F]||0,E=D.parts[F]||0;if(Y<E)return-1;if(Y>E)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 Ar(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,J=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],F=B!==void 0?uY(B):void 0;return{sha:J,timestamp:B,age:F}}catch{return null}}P1();p0();import{readFile as FM3,realpath as YM3}from"node:fs/promises";import{dirname as ob4,join as EM3}from"node:path";async function rb4(A){switch(A){case"binary":case"brew":return ZM3(so());case"npm":case"pnpm":case"yarn":case"bun":return UM3()}}async function ZM3(A){let Q=await LN(A,["--version"],5000);if(Q.reason!=="success")return P.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function UM3(){try{let A=process.argv[1];if(!A)return null;let Q=await YM3(A),$=ob4(ob4(Q));return await XM3(EM3($,"package.json"))}catch(A){return P.debug("failed to read installed version from package.json",{error:A}),null}}async function XM3(A){let Q=await FM3(A,"utf8"),$=JSON.parse(Q);if(!$.name||!$01($.name))return P.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}p0();import{spawn as GM3}from"node:child_process";function Z01(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return P.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var lE0=null,Qr=null;function sb4(A){return new Promise((Q)=>{let $=GM3("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,J)=>{if(D!==0||J==="SIGTERM"){Q(null);return}let F=B.trim();Q(F&&F!=="undefined"?F:null)}),$.on("error",()=>{Q(null)})})}async function iE0(){if(lE0)return lE0;if(Qr)return Qr;Qr=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return Z01(A);let Q=await sb4("@sourcegraph:registry");if(Q)return Z01(Q);let $=await sb4("registry");if($)return Z01($);return"https://registry.npmjs.org"})();try{return lE0=await Qr,lE0}finally{Qr=null}}var VM3=3600000,KM3=5000;function nE0(A,Q,$={}){let B=new d4,D=B.pipe(t6({shouldCountRefs:!1})),J=$.startDelayMs??0,F=$.checkIntervalMs??VM3,Y=!1,E=()=>{Y=!0};return setImmediate(async()=>{let Z=P.getChild("update");if(J>0){if(await BG(J),Y)return}let U=D.subscribe({next:(G)=>{Z.debug("emit new state",G)}}),X=A;try{while(!Y){let G=await zM3(X,Q,Z,B);if(G.stop)return;if(G.updatedTo)X=G.updatedTo;if(G.emittedVisibleState){if(await BG(KM3),Y)return;B.next("hidden")}if(F<=0)return;let V=1000,K=F;while(K>0&&!Y){let z=Math.min(V,K);await BG(z),K-=z}}}finally{U.unsubscribe(),B.complete()}}),{state:D,dispose:E}}async function zM3(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 J=await Q.get("updates.mode");if(J==="disabled")return $.debug("checking disabled"),D.stop=!0,D;let F=await kG(),Y=F==="binary"||F==="brew",E=Y?void 0:await ON();$.debug("checking",{currentVersion:A,mode:J,packageManager:F,isBinaryDistribution:Y,npmPackageName:E});let Z;if(Y)Z=await cE0(A);else{let G=await iE0();Z=await pE0(A,G,E)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),D;let U=(G)=>{B.next(G),D.emittedVisibleState=!0};if(F){let G=await rb4(F);if(G&&eo(G,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:G,latestVersion:Z.latestVersion}),D.updatedTo=G,eo(A,G)<0){let V=await dz(G),K={from:A,to:G,externallyUpdated:!0,...V};if(V.status==="same")$.info("on-disk already updated by another instance",K),U("updated");else $.warn("on-disk already updated by another instance, with PATH warning",K),U("updated-with-warning")}return D}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let G=Z.currentVersionAge-Z.latestVersionAge,V=0.5;if(Math.abs(G)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:G}),!0}return!1};if(!J)J=F==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:J});if(F==="brew"){if(!X())U("update-available-brew");return D}if(F==="binary"&&process.execPath!==so()){if($.debug("non-standard binary path, showing warning"),!X())U("update-available-unrecognized-path");return D}if(J==="warn"){if(!X())U("update-available");return D}if(!F){if($.debug("auto-update not supported, falling back to warn mode"),!X())U("update-available");return D}try{await to(Z.latestVersion,F),D.updatedTo=Z.latestVersion;let G=await dz(Z.latestVersion),V={from:Z.currentVersion,to:Z.latestVersion,...G};if(G.status==="same")$.info("success",V),U("updated");else $.warn("success with warning",V),U("updated-with-warning")}catch(G){U("update-error")}return D}catch(J){return $.debug("check failed",{error:J}),D}}zz();import{stderr as aY}from"node:process";function tb4(A){let Q=new JN().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 A01(B.force||!1,B.verbose||!1,"0.0.1779426990-g24af9a"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new JN("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 HM3(B.targetVersion)});A.addCommand($)}function WM3(A){let Q=Boolean(A.isTTY),$=0,B=!1;function D(){if(!Q||!B)return;A.write(`
4800
4800
  `),B=!1,$=0}function J(F){if(!Q)return;let Y=F.padEnd($," ");A.write(`\r${Y}`),B=!0,$=Y.length}return{flushProgressLine:D,renderProgress:J}}function IM3(A){if(A.source==="npm"&&A.latestVersionAge!==void 0&&A.latestVersionAge>36)aY.write(t0.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.
4801
4801
  `))}async function HM3(A){let $=process.platform==="win32"&&yj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:B,renderProgress:D}=WM3(aY);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")aY.write(t0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4802
4802
 
4803
4803
  `));try{if(!A){aY.write(t0.blue(`Checking for updates...
4804
- `));let Y=!1,E;if(yj()){let Z=await cE0("0.0.1779409185-ge486da");Y=Z.hasUpdate,E=Z.latestVersion}else{let Z=await iE0(),U=await ON(),X=await pE0("0.0.1779409185-ge486da",Z,U);IM3(X),Y=X.hasUpdate,E=X.latestVersion}if(!Y){let Z=Ar("0.0.1779409185-ge486da"),U=Z?.age?`released ${Z.age} ago`:`built ${uY(new Date("2026-05-22T00:24:20.009Z"))} ago`;aY.write(t0.green(`✓ Amp is already up to date on version ${"0.0.1779409185-ge486da"} (${U})
4805
- `));let X=await dz("0.0.1779409185-ge486da",$);if(X.warning)aY.write(`
4804
+ `));let Y=!1,E;if(yj()){let Z=await cE0("0.0.1779426990-g24af9a");Y=Z.hasUpdate,E=Z.latestVersion}else{let Z=await iE0(),U=await ON(),X=await pE0("0.0.1779426990-g24af9a",Z,U);IM3(X),Y=X.hasUpdate,E=X.latestVersion}if(!Y){let Z=Ar("0.0.1779426990-g24af9a"),U=Z?.age?`released ${Z.age} ago`:`built ${uY(new Date("2026-05-22T05:21:19.350Z"))} ago`;aY.write(t0.green(`✓ Amp is already up to date on version ${"0.0.1779426990-g24af9a"} (${U})
4805
+ `));let X=await dz("0.0.1779426990-g24af9a",$);if(X.warning)aY.write(`
4806
4806
  `+t0.yellow(X.warning)+`
4807
4807
  `);process.exit(0)}if(!E)aY.write(t0.yellow("[WARN] could not find latest version")),process.exit(0);A=E}aY.write(t0.blue(`Updating to version ${A}...
4808
4808
  `)),await to(A,void 0,(Y)=>{B(),aY.write(t0.dim(`Running: ${Y}
@@ -5230,7 +5230,7 @@ ${B}`).join(`
5230
5230
  `).length,D=new d({text:new C(A,new T({color:$}))});if(B<=qX0)return D;return new X0({width:1/0,height:qX0,child:new n8({autofocus:!1,controller:Q,child:D})})}function Tb3(){return new Map([[G1.key("PageUp"),new NX0],[G1.key("PageDown"),new t61],[G1.ctrl("u"),new NX0],[G1.shift("Home"),new e61],[G1.shift("End"),new AA1]])}function vb3(A,Q,$){return Math.max(Q,Math.min(A,$))}var QA1=8,na4=1,aa4=QA1-1;class $A1 extends V4{}class BA1 extends V4{}class wX0 extends V4{}class CX0 extends V4{}class DA1 extends V4{}class JA1 extends V4{}class FA1 extends R0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new oa4}}class oa4 extends j0{messageScroll=new v6;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,$=kb3(Q,this.messageScroll),B=Sb3(Q.options.message),D=B?new x4({actions:this.buildScrollActions(),child:new kA({debugLabel:"NeoSelectDialogScrollShortcuts",shortcuts:yb3(),child:$})}):$,J=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if(B)J.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return J.push({keys:["Esc"],label:"cancel"}),new w6({header:Q.options.title,minWidth:64,maxWidth:80,footer:J,autofocus:!1,onDismiss:Q.onCancel,child:D})}buildScrollActions(){let A=(Q)=>{let $=xb3(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo($)};return new Map([[$A1,new T1(()=>A(-na4))],[BA1,new T1(()=>A(na4))],[wX0,new T1(()=>A(-aa4))],[CX0,new T1(()=>A(aa4))],[DA1,new T1(()=>this.messageScroll.jumpTo(0))],[JA1,new T1(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function kb3(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 K8({options:$,selectedIndex:B,body:fb3(A.options.message,Q),onSelect:(D)=>{if(D===null){A.onCancel();return}A.onSelect(D)},padding:V0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!0,wrapOptions:!0})}function Sb3(A){if(A===void 0)return!1;return A.split(`
5231
5231
  `).length>QA1}function fb3(A,Q){if(A===void 0)return;let $=A.split(`
5232
5232
  `).length,B=Math.min($,QA1);return new X0({width:1/0,height:B,child:new n8({autofocus:!1,controller:Q,child:new d({text:new C(A)})})})}function yb3(){return new Map([[G1.key("PageUp"),new wX0],[G1.key("PageDown"),new CX0],[G1.ctrl("u"),new wX0],[G1.ctrl("d"),new CX0],[G1.ctrl("y"),new $A1],[G1.ctrl("e"),new BA1],[G1.shift("Home"),new DA1],[G1.shift("End"),new JA1]])}function xb3(A,Q,$){return Math.max(Q,Math.min(A,$))}var bb3=3,hb3=new f6("NeoPluginDialogOverlay");function ra4(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}}class YA1{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(!lY0($.method))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 k4({key:hb3,debugLabel:"PluginDialogOverlay",autofocus:!1,canRequestFocus:!0,child:this.buildActiveDialog(A)})]}buildActiveDialog(A){switch(A.kind){case"input":return new ps({key:new iz(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 s61({key:new iz(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)});case"select":return new FA1({key:new iz(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.neoContext.pluginPlatform;if(!A)return;A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.neoContext.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}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 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(ra4(A.id,B))}catch(B){if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(ra4(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 $=vk4.safeParse(A.data);if($.success)this.handlePluginUISnapshot($.data,Q);return!0}if(A.event==="plugin.ui.request_added"){let $=kk4.safeParse(A.data);if($.success)this.handlePluginUIRequestAdded($.data,Q);return!0}if(A.event==="plugin.ui.request_settled"){let $=Sk4.safeParse(A.data);if($.success)this.handlePluginUIRequestSettled($.data,Q);return!0}if(A.event==="plugin.ui.request_removed"){let $=fk4.safeParse(A.data);if($.success)this.handlePluginUIRequestRemoved($.data);return!0}return!1}clearPluginPlatformStatusHandlers(){let A=this.options.neoContext.pluginPlatform;if(!A)return;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null}subscribePluginCommands(){let A=this.options.neoContext.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let $=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(Cc($.errorMessage))continue;let B=`${$.uri.toString()}
5233
- ${$.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.neoContext.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(D){P.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=QY(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=QY(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=QY(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))})};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,bb3)}scheduleResolvingDialogAdvance(A,Q){i6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"NeoPluginIntegration.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)}}var gb3=48;class EA1{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 hs({width:gb3,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()}}p0();import{spawnSync as mb3}from"node:child_process";import FW from"node:process";var sa4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function cs(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else W4.instance.stop()}function ta4(A){return{noun:"amp",verb:"Relaunch (Quit, then Reopen & Resume Thread)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update","resume","reopen"],shortcut:FW.env.NODE_ENV==="development"&&FW.platform==="darwin"?G1.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),cs(A)}}}function db3(A,Q){P.info("Relaunching Amp; threads will be resumed",{threadIDs:A});let{command:$,args:B}=pb3(A),D=mb3($,B,{cwd:Q,env:FW.env,stdio:"inherit"});if(D.error)return P.error("Failed to relaunch Amp",{error:D.error}),1;return D.status??1}class ZA1{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{P.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 db3(this.requestedThreadIDs,A)}}function pb3(A){let Q=A.length>0?["threads","continue",...A]:[],$=cb3(FW.argv),B=ib3();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let D=FW.argv[1],J=D&&lb3(D)?[D]:[];return{command:FW.execPath,args:[...J,...$,...Q]}}function cb3(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let D=$[B];if(!D?.startsWith("--"))continue;let[J,F]=D.split("=",2);if(!J)continue;let Y=J.slice(2),E=Y.startsWith("no-")?Y.slice(3):Y;if(sa4.booleans.has(E)){Q.push(D);continue}if(!sa4.options.has(Y))continue;if(F!==void 0){Q.push(D);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(D,Z),B+=1}return Q}function lb3(A){return A!==FW.execPath&&!A.startsWith("/$bunfs/")}function ib3(){if(FW.env.NODE_ENV!=="development")return null;let A=FW.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=nb3(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function nb3(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 ab3=18000000;class UA1{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??ab3)-(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(()=>cs(this.options))}}ol();A8();import{readFile as ob3}from"node:fs/promises";import XA1 from"node:os";function rb3(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function ea4(A,Q){try{return{path:Q,contents:Fm0(await ob3(A,"utf8"))}}catch{return null}}async function MX0(A,Q){let $=[],B=rb3(),D=await e4.getThread({thread:Q},{config:A.configService}),J=D.ok?D.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(GD(J),null,2)});let F=await ea4(Wf(Q),`${B}/logs/${Q}.log`);if(F)$.push(F);let Y=await ea4(A.settingsFilePath,`${B}/settings/global.json`);if(Y)$.push(Y);let E=await kG()??"unknown",Z=await e4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1779409185-ge486da",clientOS:`${XA1.platform()} ${XA1.release()} ${XA1.arch()}`,installMethod:E}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class GA1{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)}}}}class LX0 extends M3{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new VA1(this.offstage)}updateRenderObject(A){if(A instanceof VA1)A.offstage=this.offstage}}class VA1 extends b1{_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;z4(!!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 ls{_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 KA1 extends R0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Ao4}}class Ao4 extends j0{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 dj,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new dj,$=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 LX0({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],D=$===this.entries.length-1,J=D?new k4({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(F)=>{if(F.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new LX0({key:B.key,offstage:!D,child:J}))}return new i4({fit:"expand",children:Q})}}import Qo4 from"node:process";class WA1 extends H1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((B)=>B.status.type!=="hidden"),$=sb3(Q);return new w6({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:V0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new cA({items:Q,showBorder:!1,getLabel:(B)=>{let D=zA1(B);return B.keywords&&B.keywords.length>0?`${D} ${B.keywords.join(" ").toLowerCase()}`:D},sortItems:(B,D,J)=>{if(J===""){let U=B.item.status.type==="disabled"?1:0,X=D.item.status.type==="disabled"?1:0;if(U!==X)return U-X;let G=B.item.sortBoost??0,V=D.item.sortBoost??0;if(G!==V)return V-G;let K=B.item.noun?.toLowerCase()??"",z=D.item.noun?.toLowerCase()??"";if(K!==z)return K<z?-1:1;return 0}let F=ER(B.item.verb.toLowerCase(),J),Y=ER(D.item.verb.toLowerCase(),J);if(F!==Y)return Y-F;let E=ER(zA1(B.item),J),Z=ER(zA1(D.item),J);if(E!==Z)return Z-E;return D.score-B.score},isItemDisabled:(B)=>B.status.type==="disabled",buildDisabledReasonWidget:(B,D)=>{if(B.status.type!=="disabled")return;let{colors:J}=O0.of(D);return new d({text:new C(B.status.reason,new T({color:J.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:(B,D,J,F)=>new $o4({command:B,isSelected:D,isDisabled:J,categoryWidth:$,buildContext:F}),onAccept:(B)=>{this.props.onAccept(B)},onDismiss:this.props.onDismiss})})}}class $o4 extends H1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:D,buildContext:J}=this.props,F=O0.of(J),{colors:Y,app:E}=F,Z=$?E.selectionBackground:void 0,U=$?E.selectionForeground:Y.foreground,X=$?U:Y.mutedForeground,G=new d({text:new C(Q.noun?.toLowerCase()??"",new T({color:X,dim:B||!$})),textAlign:"right"}),V=[new C(Q.verb.toLowerCase(),new T({color:U,bold:!0,dim:B}))];if(B)V.push(new C(" (unavailable)",new T({color:U,dim:!0})));let K=d.spans(V),z=[{child:G,fixedWidth:D},{child:K,expanded:!0}];if(Q.shortcut)z.push({child:tb3(Q.shortcut,F,B)});return new Bo4({columns:z,padding:V0.horizontal(1),backgroundColor:Z})}}function zA1(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function sb3(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,J4($.noun)):Q},0)}function tb3(A,Q,$){let{colors:B,app:D}=Q,J=new T({color:B.mutedForeground,dim:$}),F=[];for(let Y of A.modifiers()){if(F.length>0)F.push(new C(" ",J));F.push(new C(eb3(Y),new T({color:D.keybind,bold:!0,dim:$})))}if(F.length>0)F.push(new C(" ",J));return F.push(new C(Ah3(A),new T({color:D.keybind,bold:!0,dim:$}))),d.spans(F)}function eb3(A){return A==="Meta"&&Qo4.platform==="darwin"?"Cmd":A}function Ah3(A){return A.meta&&Qo4.platform==="darwin"?A.key.toUpperCase():A.key}class Bo4 extends H1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:D}=this.props,J=[];for(let Y=0;Y<Q.length;Y++){let E=Q[Y];if(Y>0&&$>0)J.push(new X0({width:$}));if(E.fixedWidth!==void 0)J.push(new X0({width:E.fixedWidth,child:E.child}));else if(E.expanded)J.push(new R1({child:E.child}));else J.push(E.child)}let F=new r0({crossAxisAlignment:"start",children:J});if(!B&&!D)return F;return new x0({decoration:D?{color:D}:void 0,padding:B,child:F})}}class IA1{#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 ls,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class M9 extends VA{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=M9.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(M9)?.commandRegistry??null}}class HA1 extends R0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Do4}}class Do4 extends j0{modalStack=new ls;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=M9.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=M9.of(A).commands,$=new WA1({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 KA1({root:$,controller:this.modalStack})}}var qA1=[{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"]}]}],NA1=[{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 OX0 extends H1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=h1.of(A).size.width,B=50,D=$<50,J=[];for(let F of this.items){let[Y,E]=this.renderRow(F),Z;if(D)Z=new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[Y,new f0({padding:V0.only({left:4}),child:E})]});else Z=new r0({crossAxisAlignment:"start",children:[new R1({flex:1,child:Y}),new X0({width:1}),new R1({flex:1,child:E})]});J.push(new f0({padding:V0.horizontal(6),child:Z}))}return new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:J})}}class wA1 extends R0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:$}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=$??!0}createState(){return new Jo4}}class Jo4 extends j0{scrollController;initState(){this.scrollController=new v6,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let $=L1.of(A).colorScheme,D=O0.of(A).app,J=h1.of(A),F=new T({color:$.primary,bold:!0}),Y=new T({color:$.secondary,bold:!0}),E=new T({color:D.keybind}),Z=new T({color:D.command}),U=new T({color:$.foreground}),X=new T({color:$.foreground}),G=J.size.width,V=J.size.height,K=G-4,z=V-4,W=Math.max(40,Math.min(80,K)),I=new Set(["permissions-disable"]),q=[...this.widget.commands.filter((L)=>{let j=L.noun?.toLowerCase();return j!=="dev"&&j!=="debug"&&!L.id.startsWith("debug-")&&!I.has(L.id)})].sort((L,j)=>{let k=(L.noun??"").toLowerCase(),_=(j.noun??"").toLowerCase(),f=k.localeCompare(_);if(f!==0)return f;let h=L.verb.toLowerCase(),b=j.verb.toLowerCase(),v=h.localeCompare(b);if(v!==0)return v;return L.id.localeCompare(j.id)}),N=new k6({autofocus:!0,controller:this.scrollController,child:new x0({constraints:new C1(W,W,0,Number.POSITIVE_INFINITY),child:new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new $4({child:new d({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5233
+ ${$.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.neoContext.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(D){P.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=QY(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=QY(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=QY(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))})};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,bb3)}scheduleResolvingDialogAdvance(A,Q){i6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"NeoPluginIntegration.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)}}var gb3=48;class EA1{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 hs({width:gb3,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()}}p0();import{spawnSync as mb3}from"node:child_process";import FW from"node:process";var sa4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function cs(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else W4.instance.stop()}function ta4(A){return{noun:"amp",verb:"Relaunch (Quit, then Reopen & Resume Thread)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update","resume","reopen"],shortcut:FW.env.NODE_ENV==="development"&&FW.platform==="darwin"?G1.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),cs(A)}}}function db3(A,Q){P.info("Relaunching Amp; threads will be resumed",{threadIDs:A});let{command:$,args:B}=pb3(A),D=mb3($,B,{cwd:Q,env:FW.env,stdio:"inherit"});if(D.error)return P.error("Failed to relaunch Amp",{error:D.error}),1;return D.status??1}class ZA1{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{P.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 db3(this.requestedThreadIDs,A)}}function pb3(A){let Q=A.length>0?["threads","continue",...A]:[],$=cb3(FW.argv),B=ib3();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let D=FW.argv[1],J=D&&lb3(D)?[D]:[];return{command:FW.execPath,args:[...J,...$,...Q]}}function cb3(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let D=$[B];if(!D?.startsWith("--"))continue;let[J,F]=D.split("=",2);if(!J)continue;let Y=J.slice(2),E=Y.startsWith("no-")?Y.slice(3):Y;if(sa4.booleans.has(E)){Q.push(D);continue}if(!sa4.options.has(Y))continue;if(F!==void 0){Q.push(D);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(D,Z),B+=1}return Q}function lb3(A){return A!==FW.execPath&&!A.startsWith("/$bunfs/")}function ib3(){if(FW.env.NODE_ENV!=="development")return null;let A=FW.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=nb3(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function nb3(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 ab3=18000000;class UA1{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??ab3)-(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(()=>cs(this.options))}}ol();A8();import{readFile as ob3}from"node:fs/promises";import XA1 from"node:os";function rb3(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function ea4(A,Q){try{return{path:Q,contents:Fm0(await ob3(A,"utf8"))}}catch{return null}}async function MX0(A,Q){let $=[],B=rb3(),D=await e4.getThread({thread:Q},{config:A.configService}),J=D.ok?D.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(GD(J),null,2)});let F=await ea4(Wf(Q),`${B}/logs/${Q}.log`);if(F)$.push(F);let Y=await ea4(A.settingsFilePath,`${B}/settings/global.json`);if(Y)$.push(Y);let E=await kG()??"unknown",Z=await e4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1779426990-g24af9a",clientOS:`${XA1.platform()} ${XA1.release()} ${XA1.arch()}`,installMethod:E}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class GA1{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)}}}}class LX0 extends M3{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new VA1(this.offstage)}updateRenderObject(A){if(A instanceof VA1)A.offstage=this.offstage}}class VA1 extends b1{_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;z4(!!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 ls{_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 KA1 extends R0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Ao4}}class Ao4 extends j0{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 dj,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new dj,$=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 LX0({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],D=$===this.entries.length-1,J=D?new k4({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(F)=>{if(F.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new LX0({key:B.key,offstage:!D,child:J}))}return new i4({fit:"expand",children:Q})}}import Qo4 from"node:process";class WA1 extends H1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((B)=>B.status.type!=="hidden"),$=sb3(Q);return new w6({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:V0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new cA({items:Q,showBorder:!1,getLabel:(B)=>{let D=zA1(B);return B.keywords&&B.keywords.length>0?`${D} ${B.keywords.join(" ").toLowerCase()}`:D},sortItems:(B,D,J)=>{if(J===""){let U=B.item.status.type==="disabled"?1:0,X=D.item.status.type==="disabled"?1:0;if(U!==X)return U-X;let G=B.item.sortBoost??0,V=D.item.sortBoost??0;if(G!==V)return V-G;let K=B.item.noun?.toLowerCase()??"",z=D.item.noun?.toLowerCase()??"";if(K!==z)return K<z?-1:1;return 0}let F=ER(B.item.verb.toLowerCase(),J),Y=ER(D.item.verb.toLowerCase(),J);if(F!==Y)return Y-F;let E=ER(zA1(B.item),J),Z=ER(zA1(D.item),J);if(E!==Z)return Z-E;return D.score-B.score},isItemDisabled:(B)=>B.status.type==="disabled",buildDisabledReasonWidget:(B,D)=>{if(B.status.type!=="disabled")return;let{colors:J}=O0.of(D);return new d({text:new C(B.status.reason,new T({color:J.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:(B,D,J,F)=>new $o4({command:B,isSelected:D,isDisabled:J,categoryWidth:$,buildContext:F}),onAccept:(B)=>{this.props.onAccept(B)},onDismiss:this.props.onDismiss})})}}class $o4 extends H1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:D,buildContext:J}=this.props,F=O0.of(J),{colors:Y,app:E}=F,Z=$?E.selectionBackground:void 0,U=$?E.selectionForeground:Y.foreground,X=$?U:Y.mutedForeground,G=new d({text:new C(Q.noun?.toLowerCase()??"",new T({color:X,dim:B||!$})),textAlign:"right"}),V=[new C(Q.verb.toLowerCase(),new T({color:U,bold:!0,dim:B}))];if(B)V.push(new C(" (unavailable)",new T({color:U,dim:!0})));let K=d.spans(V),z=[{child:G,fixedWidth:D},{child:K,expanded:!0}];if(Q.shortcut)z.push({child:tb3(Q.shortcut,F,B)});return new Bo4({columns:z,padding:V0.horizontal(1),backgroundColor:Z})}}function zA1(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function sb3(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,J4($.noun)):Q},0)}function tb3(A,Q,$){let{colors:B,app:D}=Q,J=new T({color:B.mutedForeground,dim:$}),F=[];for(let Y of A.modifiers()){if(F.length>0)F.push(new C(" ",J));F.push(new C(eb3(Y),new T({color:D.keybind,bold:!0,dim:$})))}if(F.length>0)F.push(new C(" ",J));return F.push(new C(Ah3(A),new T({color:D.keybind,bold:!0,dim:$}))),d.spans(F)}function eb3(A){return A==="Meta"&&Qo4.platform==="darwin"?"Cmd":A}function Ah3(A){return A.meta&&Qo4.platform==="darwin"?A.key.toUpperCase():A.key}class Bo4 extends H1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:D}=this.props,J=[];for(let Y=0;Y<Q.length;Y++){let E=Q[Y];if(Y>0&&$>0)J.push(new X0({width:$}));if(E.fixedWidth!==void 0)J.push(new X0({width:E.fixedWidth,child:E.child}));else if(E.expanded)J.push(new R1({child:E.child}));else J.push(E.child)}let F=new r0({crossAxisAlignment:"start",children:J});if(!B&&!D)return F;return new x0({decoration:D?{color:D}:void 0,padding:B,child:F})}}class IA1{#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 ls,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class M9 extends VA{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=M9.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(M9)?.commandRegistry??null}}class HA1 extends R0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Do4}}class Do4 extends j0{modalStack=new ls;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=M9.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=M9.of(A).commands,$=new WA1({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 KA1({root:$,controller:this.modalStack})}}var qA1=[{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"]}]}],NA1=[{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 OX0 extends H1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=h1.of(A).size.width,B=50,D=$<50,J=[];for(let F of this.items){let[Y,E]=this.renderRow(F),Z;if(D)Z=new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[Y,new f0({padding:V0.only({left:4}),child:E})]});else Z=new r0({crossAxisAlignment:"start",children:[new R1({flex:1,child:Y}),new X0({width:1}),new R1({flex:1,child:E})]});J.push(new f0({padding:V0.horizontal(6),child:Z}))}return new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:J})}}class wA1 extends R0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:$}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=$??!0}createState(){return new Jo4}}class Jo4 extends j0{scrollController;initState(){this.scrollController=new v6,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let $=L1.of(A).colorScheme,D=O0.of(A).app,J=h1.of(A),F=new T({color:$.primary,bold:!0}),Y=new T({color:$.secondary,bold:!0}),E=new T({color:D.keybind}),Z=new T({color:D.command}),U=new T({color:$.foreground}),X=new T({color:$.foreground}),G=J.size.width,V=J.size.height,K=G-4,z=V-4,W=Math.max(40,Math.min(80,K)),I=new Set(["permissions-disable"]),q=[...this.widget.commands.filter((L)=>{let j=L.noun?.toLowerCase();return j!=="dev"&&j!=="debug"&&!L.id.startsWith("debug-")&&!I.has(L.id)})].sort((L,j)=>{let k=(L.noun??"").toLowerCase(),_=(j.noun??"").toLowerCase(),f=k.localeCompare(_);if(f!==0)return f;let h=L.verb.toLowerCase(),b=j.verb.toLowerCase(),v=h.localeCompare(b);if(v!==0)return v;return L.id.localeCompare(j.id)}),N=new k6({autofocus:!0,controller:this.scrollController,child:new x0({constraints:new C1(W,W,0,Number.POSITIVE_INFINITY),child:new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new $4({child:new d({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5234
5234
  `,F)})}),new X0({height:1}),new f0({padding:V0.horizontal(2),child:new d({text:new C(`Editor Shortcuts
5235
5235
  `,Y)})}),new OX0({items:qA1.filter((L)=>L.submitOnEnterOnly===void 0||L.submitOnEnterOnly===this.widget.submitOnEnter),renderRow:(L)=>{let j=[];for(let _ of L.methods){let f=this.buildCleanKeyCombination(_);j.push(f)}let k=j.join(", ");return[new d({text:new C(k,E)}),new d({text:new C(L.description,U)})]}}),new X0({height:1}),new f0({padding:V0.horizontal(2),child:new d({text:new C(`Scrolling & Navigation
5236
5236
  `,Y)})}),new OX0({items:NA1,renderRow:(L)=>{let j=[];for(let _ of L.methods){let f=this.buildCleanKeyCombination(_);j.push(f)}let k=j.join(", ");return[new d({text:new C(k,E)}),new d({text:new C(L.description,U)})]}}),new X0({height:1}),new f0({padding:V0.horizontal(2),child:new d({text:new C(`Command Palette Commands
@@ -5297,8 +5297,7 @@ Used: `,$)),J.push(new C(`${WG0(Q.totalTokens)} tokens`,B)),J.push(new C(` (${Z}
5297
5297
  `,D)),J.push(new C("Free: ",$)),J.push(new C(`${WG0(Q.freeSpace)} tokens`,B)),J}formatSectionRow(A,Q,$,B){let D=GQ(A,B.nameWidth),J=QZ0(D,B.nameWidth+2),F=QZ0(WG0(Q),8,void 0,"right"),Y=QZ0(`(${$.toFixed(1)}%)`,8,void 0,"right");return[new C(J,B.nameStyle),new C(F,B.valueStyle),new C(` ${Y}
5298
5298
  `,B.percentStyle)]}}o5();function Gl3(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}class Vt extends H1{message;onDestruct;constructor({key:A,message:Q,onDestruct:$}){super(A?{key:A}:{});this.message=Q,this.onDestruct=$}build(A){let $=O0.of(A).colors,B=h1.of(A),D=new T({color:$.foreground,dim:!0}),J=new T({color:$.foreground}),F=Math.max(50,Math.min(80,B.size.width-4)),Y=[{keys:["Esc"],label:"destroy message"}];return new w6({header:this.message.title,footer:Y,visualStyle:{borderShape:"classic",borderAnimation:"mysterious-message",titleAnimation:"scramble"},chromePadding:V0.symmetric(2,2),minWidth:F,maxWidth:F,maxHeight:B.size.height,autofocus:!1,onDismiss:this.onDestruct,child:new X5({child:new n8({autofocus:!0,child:new S0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new $4({child:new d({text:new C(Gl3(this.message.visibleFrom),D)})}),new X0({height:1}),new d({text:new C(this.message.body,J),selectable:!0})]})})})})}}var K51=" .:-=+*#%@",z51=[" ",".","·","·",":",":","•","•","●","●"],Jx=0.5,Xw=64,Vl3=30,Kt=0.9,ot4=1.4,W51=Kt+ot4,I51=6,at4=0.5,Kl3=1.6,zl3=28;class H51 extends R0{originX;originY;agentMode;visualStyle;primaryColor;secondaryColor;elapsed;fps;onComplete;constructor({originX:A,originY:Q,agentMode:$,visualStyle:B="classic",primaryColor:D,secondaryColor:J,elapsed:F,fps:Y=Vl3,onComplete:E,key:Z}){super(Z?{key:Z}:{});this.originX=A,this.originY=Q,this.agentMode=$,this.visualStyle=B,this.primaryColor=D,this.secondaryColor=J,this.elapsed=F,this.fps=Y,this.onComplete=E}createState(){return new rt4}}class rt4 extends j0{elapsed=0;timer=null;startMs=0;completed=!1;glow=new a9;initState(){if(super.initState(),this.widget.elapsed!==void 0){this.elapsed=this.widget.elapsed;return}if(this.startMs=performance.now(),this.widget.fps<=0){this.elapsed=W51,this.complete();return}let A=Math.max(16,Math.floor(1000/this.widget.fps));this.timer=setInterval(()=>{if(!this.mounted)return;if(this.elapsed=(performance.now()-this.startMs)/1000,this.elapsed>=W51){this.elapsed=W51,this.setState(()=>{}),this.complete();return}this.setState(()=>{})},A)}didUpdateWidget(A){if(super.didUpdateWidget(A),this.widget.elapsed!==void 0&&this.widget.elapsed!==A.elapsed)this.elapsed=this.widget.elapsed,this.setState(()=>{})}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null;super.dispose()}complete(){if(this.completed)return;if(this.completed=!0,this.timer)clearInterval(this.timer),this.timer=null;this.widget.onComplete?.()}build(A){let Q=L1.of(A);return new st4({originX:this.widget.originX,originY:this.widget.originY,elapsed:this.elapsed,agentMode:this.widget.agentMode,visualStyle:this.widget.visualStyle,primaryColor:this.widget.primaryColor,secondaryColor:this.widget.secondaryColor,backgroundColor:Q.colorScheme.background,glow:this.glow})}}class st4 extends R5{props;constructor(A,Q){super(Q?{key:Q}:{});this.props=A}createElement(){return new D$(this)}createRenderObject(){return new tt4(this.props)}updateRenderObject(A){A.update(this.props)}}function Wl3(A){let Q=A>>>0;return()=>{Q=Q+1831565813>>>0;let $=Q;return $=Math.imul($^$>>>15,$|1),$^=$+Math.imul($^$>>>7,$|61),(($^$>>>14)>>>0)/4294967296}}class tt4 extends b1{_props;_palette=[];_paletteSignature="";_fragments=null;_fragmentRadius=0;_fragmentVisualStyle="classic";constructor(A){super();this._props=A,this.rebuildPalette()}update(A){let Q=A.agentMode!==this._props.agentMode||A.visualStyle!==this._props.visualStyle||A.primaryColor!==this._props.primaryColor||A.secondaryColor!==this._props.secondaryColor;if(this._props=A,Q)this.rebuildPalette();this.markNeedsPaint()}rebuildPalette(){let A=this._props.primaryColor&&this._props.secondaryColor?{primary:this._props.primaryColor,secondary:this._props.secondaryColor}:void 0;this._palette=Array.from({length:Xw},(Q,$)=>{let B=$/(Xw-1);return J$(B,this._props.agentMode,A)}),this._paletteSignature=`${this._props.agentMode??"smart"}|${this._props.primaryColor?`${this._props.primaryColor.r},${this._props.primaryColor.g},${this._props.primaryColor.b}`:""}|${this._props.secondaryColor?`${this._props.secondaryColor.r},${this._props.secondaryColor.g},${this._props.secondaryColor.b}`:""}`}performLayout(){let A=this._lastConstraints,Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}getMaxRadius(A,Q){let $=A*at4,B=Q*at4*(1/Jx);return Math.max(I51+1,Math.min($,B))}buildFragments(A,Q){let $=Wl3(2654435761),B=[],D=Q==="neo"?z51:K51,J=Math.min(600,Math.max(120,Math.floor(A*A*0.45)));for(let F=0;F<J;F++){let Y=Math.sqrt($()),E=$()*Math.PI*2,Z=Math.cos(E)*Y*A,U=Math.sin(E)*Y*A*Jx,X=(0.5+Y*0.9)*Kl3*A,G=0.7+$()*0.6,V=Math.cos(E)*X*G,K=Math.sin(E)*X*G*Jx-$()*A*0.6,z=0.4+$()*0.6,W=Math.min(D.length-1,Math.floor(z*D.length));B.push({x:Z,y:U,vx:V,vy:K,glyph:D[W]||"*",intensity:z})}return B}paint(A,Q=0,$=0){let{elapsed:B,originX:D,originY:J,backgroundColor:F,glow:Y}=this._props,E=Q+this.offset.x,Z=$+this.offset.y,U=Math.floor(this.size.width),X=Math.floor(this.size.height),G=A.getSize(),V=G.width,K=G.height,z=this._palette;this._paletteSignature;let W=this.getMaxRadius(U,X),I=D-E,H=J-Z;if(B<Kt){let L=1-(1-B/Kt)**3,j=I51+(W-I51)*L;this.paintOrb(A,E,Z,I,H,j,1,B,Y,z,F,V,K);return}if(!this._fragments||this._fragmentRadius!==W||this._fragmentVisualStyle!==this._props.visualStyle)this._fragments=this.buildFragments(W,this._props.visualStyle),this._fragmentRadius=W,this._fragmentVisualStyle=this._props.visualStyle;let q=Math.min(1,(B-Kt)/ot4);if(q<0.2){let O=1-q/0.2;this.paintOrb(A,E,Z,I,H,W,O,B,Y,z,F,V,K)}let N=B-Kt,w=1-q;for(let O of this._fragments){let L=O.x+O.vx*N,j=O.y+O.vy*N+0.5*zl3*N*N,k=Math.round(E+I+L),_=Math.round(Z+H+j);if(k<0||k>=V||_<0||_>=K)continue;let f=Math.max(0.05,O.intensity*w),h=this._props.visualStyle==="neo"?z51:K51,b=Math.min(h.length-1,Math.floor(f*h.length)),v=q>0.7?".":h[b]||O.glyph,y=Math.min(Xw-1,Math.floor(f*Xw)),c=z[y]||z[Xw-1];if(!c)continue;A.setCell(k,_,{char:v,width:1,style:{fg:c,bg:F,dim:q>0.55,bold:q<0.15}})}}paintOrb(A,Q,$,B,D,J,F,Y,E,Z,U,X,G){let V=Math.max(1,J),K=V*V,z=1/K,W=1/Jx,I=this._props.visualStyle,H=Math.max(0,Math.floor(D-V*Jx)),q=Math.min(G-$-1,Math.ceil(D+V*Jx));for(let N=H;N<=q;N++){let w=$+N;if(w<0||w>=G)continue;let O=(N-D)*W,L=O*O;if(L>=K)continue;let j=Math.sqrt(K-L),k=Math.max(0,Math.floor(B-j)),_=Math.min(X-Q-1,Math.ceil(B+j));for(let f=k;f<=_;f++){let h=f-B,b=h*h+L;if(b>=K)continue;let v=1-b*z,y=E.sample(f,N,Y,1),c=y*v*F,p=K51;if(I==="neo"){let E0=Math.sqrt(b*z),I0=h/V,$0=O/V,P0=Math.sqrt(Math.max(0,1-E0*E0)),Q0=Math.max(0,I0*-0.45+$0*-0.35+P0*0.88),M0=Math.max(0,1-P0)**1.8,n=Math.exp(-((I0+0.28)*(I0+0.28)*54+($0+0.32)*($0+0.32)*115));if(c=(0.12+v*0.16+Q0*0.6+M0*0.34+n*0.75+y*0.16)*F,p=z51,c<0.08)continue}if(c<=0)continue;let g=Math.max(I==="neo"?1:0,Math.min(p.length-1,Math.floor(c*p.length))),i=p[g]||" ",o=Math.min(Xw-1,Math.floor(c*Xw*(I==="neo"?1.2:1))),A0=Z[o]||Z[Xw-1];if(!A0)continue;let W0=Q+f;if(W0<0||W0>=X)continue;A.setCell(W0,w,{char:i,width:1,style:{fg:A0,bg:U,bold:I==="neo"&&c>0.65}})}}}}var q51=5,et4=3.8,Ae4=280;var Il3=["*","+",".",":","'"];function Qe4(A,Q,$=Date.now()){return Math.floor(A)*73856093^Math.floor(Q)*19349663^$}function $e4(A,Q,$={}){let{burstParticleCount:B=72,burstSpeedMin:D=10,burstSpeedRange:J=16,rainSpeedMin:F=4,rainSpeedRange:Y=9,burstDelayMax:E=0.18,rainDelayMax:Z=1,burstLifetimeMin:U=1.4,burstLifetimeRange:X=1.2,rainLifetimeMin:G=2.8,rainLifetimeRange:V=1.8,burstDriftMin:K=0.3,burstDriftRange:z=0.9,rainDriftMin:W=0.8,rainDriftRange:I=1.8,rainAngleCenter:H=Math.PI/2,rainAngleSpread:q=1.4,colorIndexCount:N=6,sparkleGlyphs:w=Il3}=$,O=Hl3(A),L=[];for(let j=0;j<Q;j++){let k=j<B,_=k?O()*Math.PI*2:H+(O()-0.5)*q,f=k?D+O()*J:F+O()*Y,h=k?O()*E:O()*Z,b=k?U+O()*X:G+O()*V,v=k?K+O()*z:W+O()*I,y=O()*Math.PI*2,c=w[Math.floor(O()*w.length)]??"*";L.push({kind:k?"burst":"rain",angle:_,speed:f,delay:h,lifetime:b,drift:v,phase:y,glyph:c,colorIndex:Math.floor(O()*N)})}return L}function Be4(A,Q){let{elapsedSeconds:$,originX:B,originY:D,unitScale:J=1}=Q,F=$-A.delay;if(F<0||F>A.lifetime)return null;let Y=A.kind==="burst"?9:12,E=A.speed*J,Z=Math.cos(A.angle)*E,U=Math.sin(A.angle)*E,X=Math.sin((F+A.phase)*8)*A.drift*J;return{x:B+Z*F+X,y:D+U*F+Y*J*F*F,progress:F/A.lifetime}}function Hl3(A){let Q=A>>>0;if(Q===0)Q=2654435769;return()=>{return Q=Q*1664525+1013904223>>>0,Q/4294967296}}class IG0 extends R5{text;baseColor;backgroundColor;glow;time;agentMode;orbWidth;orbHeight;glowIntensity;shockwaves;constructor({key:A,text:Q,baseColor:$,backgroundColor:B,glow:D,time:J,agentMode:F,orbWidth:Y=40,orbHeight:E=40,glowIntensity:Z=0.4,shockwaves:U=[]}){super(A?{key:A}:{});this.text=Q,this.baseColor=$,this.backgroundColor=B,this.glow=D,this.time=J,this.agentMode=F,this.orbWidth=Y,this.orbHeight=E,this.glowIntensity=Z,this.shockwaves=U}createElement(){return new D$(this)}createRenderObject(){return new De4(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}updateRenderObject(A){A.update(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}}var ql3=0.5;class De4 extends b1{_text;_baseColor;_backgroundColor;_glow;_time;_agentMode;_orbWidth;_orbHeight;_glowIntensity;_shockwaves;constructor(A,Q,$,B,D,J,F,Y,E,Z){super();this._text=A;this._baseColor=Q;this._backgroundColor=$;this._glow=B;this._time=D;this._agentMode=J;this._orbWidth=F;this._orbHeight=Y;this._glowIntensity=E;this._shockwaves=Z}update(A,Q,$,B,D,J,F,Y,E,Z){let U=A!==this._text;if(this._text=A,this._baseColor=Q,this._backgroundColor=$,this._glow=B,this._time=D,this._agentMode=J,this._orbWidth=F,this._orbHeight=Y,this._glowIntensity=E,this._shockwaves=Z,U)this.markNeedsLayout();this.markNeedsPaint()}getMinIntrinsicWidth(A){return J4(this._text,!1)}getMaxIntrinsicWidth(A){return J4(this._text,!1)}getMinIntrinsicHeight(A){return 1}getMaxIntrinsicHeight(A){return 1}performLayout(){let A=this._lastConstraints;z4(!!A,"performLayout called without constraints");let Q=J4(this._text,!1),$=A.constrain(Q,1);this.setSize($.width,$.height),super.performLayout()}paint(A,Q=0,$=0){let B=Q+this.offset.x,D=$+this.offset.y,J=Y4(this._text),F=this._agentMode==="rush"?2.5:1,{primary:Y,secondary:E}=_01(this._agentMode),Z=B;for(let U=0;U<J.length;U++){let X=J[U],G=YA(X,!1),K=(1-U/Math.max(J.length-1,1)*0.7)**1.2,z=this._glow.sample(this._orbWidth-2+U*0.5,this._orbHeight/2,this._time,F),W=0;for(let N of this._shockwaves){let w=this._time-N.startTime;if(w<0||w>QF)continue;let O=this._orbWidth*0.7+U,L=this._orbHeight/2,j=O-N.x,k=(L-N.y)/ql3,_=Math.sqrt(j*j+k*k),f=w*IZ0,h=Math.abs(_-f);if(h<az){let b=1-w/QF,v=(1-h/az)*b;W=Math.max(W,v*0.6)}}let I=z**0.7,H=Math.min(1,I*K+W),q=this.blendWithGlow(this._baseColor,H,Y,E);A.setCell(Z,D,{char:X,width:G,style:{fg:q,bg:this._backgroundColor}}),Z+=G}}blendWithGlow(A,Q,$,B){let D=cj($,B,Q),J=Q*this._glowIntensity;if(A.type==="rgb"){let F=A.value,Y=Math.round(F.r*(1-J)+D.r*J),E=Math.round(F.g*(1-J)+D.g*J),Z=Math.round(F.b*(1-J)+D.b*J);return{type:"rgb",value:{r:Y,g:E,b:Z}}}if(J>0.15)return{type:"rgb",value:{r:D.r,g:D.g,b:D.b}};return A}}var Je4=["ctrl+x","y","z"],Fe4=1.5,Nl3=2000,HG0="!@#$%^&*()_+-=[]{}|;:,.<>?/~`0123456789",L51="Welcome to ",zt=2,M51=1,Ye4=zt+M51,Ee4=3.2,wl3=0.18,Cl3=1.5,Ze4=1.4,Ue4=30,N51=0.16,He4=[{suffix:"the Orb",palettePosition:0.62},{suffix:"the Future",palettePosition:0.72},{suffix:"the Frontier",palettePosition:0.82},{suffix:"the Jungle",palettePosition:0.54},{suffix:"your Agent",palettePosition:0.68}],O51={suffix:"Amp",palettePosition:0.98,final:!0},Ml3=[...He4,O51],Ll3=Math.max(...Ml3.map((A)=>J4(A.suffix,!1))),Ol3=Y4(L51).length,jl3=Y4(`${L51}${O51.suffix}`).length;function Rl3(){let A=[...He4];for(let Q=A.length-1;Q>0;Q--){let $=Math.floor(Math.random()*(Q+1)),B=A[Q];A[Q]=A[$],A[$]=B}return A.push(O51),A}function Pl3(A,Q){let $=Q.length-1;if(A>=zt)return Q[$];let B=zt/$,D=Math.min($,Math.floor(A/B));return Q[D]}function Xe4(A,Q){let $={color:A};if(Q)$.bold=!0;return new T($)}function ul3(A,Q){let B=Math.max(0,A-zt)%Ee4/Ee4*1.6-0.3,D=Q/Math.max(1,jl3-1),J=Math.abs(D-B);return Math.max(0,1-J/wl3)**2}function Ge4(A,Q,$,B,D,J){if(!J.bold)return new C(A,Xe4(J$(Q,B,D),!1));return new C("",void 0,Y4(A).map((F,Y)=>{let E=ul3($,J.characterOffset+Y),Z=J$(Math.min(1,Q+E*0.14),B,D);return new C(F,Xe4(Z,!0))}))}function _l3(A,Q,$,B){let D=Pl3(A,Q),J="final"in D,F=Math.max(0,A-zt),Y=J&&F<M51?Math.sin(F/M51*Math.PI):0,E=J?0.74+Y*0.22:Math.max(0.34,D.palettePosition-0.24),Z=J?0.88+Y*0.12:D.palettePosition,U=Ge4(L51,E,A,$,B,{bold:J,characterOffset:0}),X=Ge4(D.suffix,Z,A,$,B,{bold:J,characterOffset:Ol3});return new r0({mainAxisSize:"min",children:[new d({text:U}),new X0({width:Ll3,child:new tz({contentKey:D.suffix,durationMs:280,child:new d({text:X})})})]})}function Tl3(A,Q,$){let B=Math.max(A.length,Q.length),D=[];for(let J=0;J<B;J++){let F=A[J]??" ",Y=Q[J]??" ",E=F===" "||F===`
5299
5299
  `||F==="\t",Z=Y===" "||Y===`
5300
- `||Y==="\t";if(E&&Z){D.push($<0.5?F:Y);continue}let U=J/B*0.4,X=Math.max(0,Math.min(1,($-U)/(1-U)));if(X===0)D.push(F);else if(X>=1)D.push(Y);else if(E)D.push(X<0.7?" ":Y);else if(Z)D.push(X<0.3?F:" ");else if(X<0.5){let G=X*2;if(Math.random()<G)D.push(HG0[Math.floor(Math.random()*HG0.length)]);else D.push(F)}else{let G=(X-0.5)*2;if(Math.random()<G)D.push(Y);else D.push(HG0[Math.floor(Math.random()*HG0.length)])}}return D.join("").trimEnd()}var vl3="https://ampcode.com/news/neo",kl3={type:"quote",text:`"Wait, a completely rebuilt Amp? Called Neo?
5301
- I have to see this."`,url:vl3,linkText:"Neo"},Ve4=[{type:"command",text:'amp -x "What package manager do we use here?"'},{type:"command",text:'amp -x "Run the linter and fix the errors"'},{type:"hint",text:"Use Ctrl+G to edit the prompt in your $EDITOR"},{type:"hint",text:"Use the `prompt: queue` command to enqueue messages without interrupting the agent"},{type:"hint",text:"Use the `thread: browser` command to open your thread in the browser"},{type:"hint",text:"Use the `thread: new` command to start a fresh thread"},{type:"hint",text:"Use the `thread: handoff` command to draft a new thread with relevant context"},{type:"hint",text:"Use the `thread: visibility` command to change thread visibility settings"},{type:"hint",text:"Use the `settings: open in editor` command to configure Amp"},{type:"hint",text:"Use the `agents-md: generate` command to create an AGENTS.md"},{type:"hint",text:"Use Tab/Shift+Tab to navigate to previous messages to edit or restore to a previous state"},{type:"prompt",text:'"Use the oracle to review the code we just wrote."'},{type:"prompt",text:'"Use subagents to update these components to use the new attribute we added."'},{type:"prompt",text:'"Do not write any code yet. Plan first."'},{type:"prompt",text:'"Think hard before you start implementing."'},{type:"prompt",text:`"Use 'psql' to change all blog_posts to have comments"`},{type:"prompt",text:'"Run <build command> and fix all the errors"'},{type:"quote",text:`"We are at the 'introduction of photography' period of programming. Painting by hand just doesn't have the same appeal anymore" - Orta Therox`},{type:"quote",text:'"Programming in the normal way feels like walking. You type out each expression, stepping incrementally toward your goal. When programming with AI, each move is bigger than a step. You lift off the ground." - Mary Rose Cook'},{type:"quote",text:'"Tomorrow all this may change, but right now after daily experience writing code with LLMs I strongly believe the maximum quality of work is reached using the human+LLM equation." - antirez'},{type:"quote",text:`"The magic that's coming now is the most powerful yet. And that means that we're beginning a profound period of exploration and creativity, trying to understand how to make that magic work and to derive new advantages from its power." - Tim O'Reilly`},{type:"quote",text:`"They're applying years of hard-won engineering wisdom to shape and constrain the AI's output. The AI is accelerating their implementation, but their expertise is what keeps the code maintainable." - Addy Osmani`},{type:"quote",text:'"I love computers just for the—sheer machine of it. This is the most exciting new thing that computers have been doing, probably in my lifetime." - DHH'},{type:"quote",text:`"We wouldn't even need to bother looking at the AI-generated code any more, just like we don't bother looking at the machine code generated by a compiler." - Martin Kleppmann`},{type:"quote",text:'"Real progress is messy, iterative, and deeply intertwined with the tools we build. Large language models are the latest, most dramatic example of that truth." - Daniel Lemire'},{type:"quote",text:`"'Human in the loop' is evolving from 'human who fixes AI mistakes' to 'human who directs AI work.'" - Ethan Mollick`},{type:"quote",text:`"I'm trying to code like a surgeon. A surgeon isn't a manager, they do the actual work! But their skills and time are highly leveraged." - Geoffrey Litt`},{type:"quote",text:`"It's important to do things fast. You learn more per unit time because you make contact with reality more frequently." - Nat Friedman`},{type:"quote",text:'"Once coding speed jumps, everything around it becomes the constraint. Your throughput gets capped by whatever is slowest." - Paul Dix'},{type:"quote",text:'"Bubble or no bubble, no one knows anything." - Benedict Evans'},{type:"quote",text:`"I actually don't think documentation is too important: LLMs can read the code a lot faster than you to figure out how to use it." - Simon Willison`},{type:"quote",text:`"The vast majority of AI tokens in the future will be used on things we don't even do today as workers." - Aaron Levie`},{type:"quote",text:`"Once you're airborne, you're suddenly immune to the length of the runway. You have days, not months. Time to break some things." - Kent Beck`},{type:"quote",text:'"Absolutely every fundamental assumption about how I work has to be questioned. There are days when it feels like I would be better off if I did not know anything about programming and started from scratch." - David Crawshaw'},{type:"quote",text:'"Code was the easiest part." - Andrej Karpathy'},{type:"quote",text:`"It's amazing for learning a codebase you're not familiar with, so it's great for discovery. Getting us out of writing boilerplate, getting us out of memorizing APIs, getting us out of looking up that thing from Stack Overflow." - Jeremy Howard`},{type:"quote",text:`"Don't anthropomorphize them!" - Steven Sinofsky`}],w51=40,C51=40,Ke4=44,ze4=36,Sl3=8,fl3=8,qe4=50,Ne4=2,yl3=4,xl3=4,bl3={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},hl3={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},gl3={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}};function ml3(A){return A==="rush"?3.4:A==="deep"?0.9:1.45}function We4(A,Q,$){let B=(A-Q)/$;return Math.exp(-(B*B))}function dl3(A){return 1-(1-Math.max(0,Math.min(1,A)))**3}function pl3(A,Q){let $=ml3(Q),B=0.35,D=4.5,J=72,F=A+1.4,Y=Number.NEGATIVE_INFINITY;for(let E=0;E<72;E++){let Z=E/Math.max(1,71),U=A+0.35+4.15*Z,X=U*$,G=X*1.35,K=(Math.sin(G)+1)*0.5,z=1-Math.abs(Math.cos(G)),W=Math.cos(X*1.55)*0.38-0.18,I=Math.sin(X*1.15)*0.25-0.26,H=We4(W,-0.14,0.2)*0.45+We4(I,-0.29,0.12)*0.55,q=(1-Math.abs(Math.sin(X*1.55)))*0.5+(1-Math.abs(Math.cos(X*1.15)))*0.5,N=X*0.45,w=(1-Math.abs(Math.cos(N)))*0.6+(1-Math.abs(Math.sin(N*0.7)))*0.4,O=1-Z,L=K*0.34+z*0.24+H*0.22+q*0.12+w*0.04+O*0.04;if(L>Y)Y=L,F=U}return F}function Ie4(A,Q){if(A==="frontier")return{colorMode:"vertical",colors:bl3};if(Q&&A==="smart")return{colorMode:"vertical",colors:hl3};if(Q&&A==="deep")return{colorMode:"vertical",colors:gl3};return{colorMode:"intensity"}}function cl3(A,Q,$,B){if(A.type==="hint")return A.text.split(/(`[^`]+`)/g).map((J)=>{if(J.startsWith("`")&&J.endsWith("`"))return new C(J.slice(1,-1),$);return new C(J,Q)});if(A.url&&A.linkText){let D=A.text.indexOf(A.linkText);if(D>=0){let J=A.url,F=A.text.slice(0,D),Y=A.text.slice(D+A.linkText.length);return[new C(F,Q),new C(A.linkText,Q.copyWith({underline:!0}),void 0,cz(J),()=>B(J)),new C(Y,Q)]}}return[new C(A.text,Q)]}function ll3(A){let Q=Math.max(Sl3,A.width-qe4-Ne4-yl3),$=Math.max(fl3,A.height-xl3),B=Math.min(Ke4,Q),D=Math.ceil(B/Ke4*ze4),J=Math.min(ze4,$,D);return{width:B,height:J}}function il3(A,Q){return J$(A==="frontier"?0.78:0.9,A,Q)}class Fx extends R0{agentMode;orbVisualStyle;mysteriousMessage;mysterySequenceProgress;onOrbExplode;settleAnimation;interactive;useNeoColors;centerContent;constructor(A={}){super(A.key?{key:A.key}:{});this.agentMode=A.agentMode,this.orbVisualStyle=A.orbVisualStyle??"classic",this.mysteriousMessage=A.mysteriousMessage,this.mysterySequenceProgress=A.mysterySequenceProgress,this.onOrbExplode=A.onOrbExplode,this.settleAnimation=A.settleAnimation??!1,this.interactive=A.interactive??!0,this.useNeoColors=A.useNeoColors??!1,this.centerContent=A.centerContent}createState(){return new we4}}class we4 extends j0{_glow;_neoWelcomeVariants;_t=0;_effectTime=0;_neoWelcomeTime=0;_timer=null;_fps=0;_animateNeoWelcome=!1;_lastTickTimeMs=null;_settleStartTimeMs=null;_settleStartAnimationTime=null;_settleTargetAnimationTime=null;_shockwaves=[];_neoOrbClickComboCount=0;_neoOrbLastClickTime=null;_neoOrbChargeStartTime=null;_neoOrbRegrowStartTime=null;_suggestion;_morphStartTime=null;_previousHasMystery=!1;initState(){if(super.initState(),this._glow=new a9,this._neoWelcomeVariants=Rl3(),this.widget.orbVisualStyle==="neo")this._suggestion=kl3;else{let A=process.env.NO_SPLASH_QUOTE==="1"?Ve4.filter((Q)=>Q.type!=="quote"):Ve4;this._suggestion=A[Math.floor(Math.random()*A.length)]}if(this._previousHasMystery=!!this.widget.mysteriousMessage,this.widget.settleAnimation)this.startSettlingAnimation()}didUpdateWidget(A){if(super.didUpdateWidget(A),!A.settleAnimation&&this.widget.settleAnimation)this.startSettlingAnimation()}getMorphProgress(A){if(this._morphStartTime===null)return null;let Q=A-this._morphStartTime;if(Q>=Fe4)return null;return Q/Fe4}handleShockwave=(A)=>{if(this._shockwaves.push(A),this._timer===null&&this._fps>0)this.startAnimation(this._fps,this._animateNeoWelcome);this.setState(()=>{})};handleOrbClick=(A)=>{if(this.widget.orbVisualStyle!=="neo")return;if(this.getNeoOrbRegrowthScale(A.time)<1){this._neoOrbClickComboCount=0,this._neoOrbLastClickTime=null,this._neoOrbChargeStartTime=null;return}let Q=this._neoOrbLastClickTime===null?Number.POSITIVE_INFINITY:A.time-this._neoOrbLastClickTime,$=Q>=0&&Q<=Cl3;if(this._neoOrbClickComboCount=$?this._neoOrbClickComboCount+1:1,this._neoOrbLastClickTime=A.time,this._neoOrbChargeStartTime=A.time,this._timer===null&&this._fps>0)this.startAnimation(this._fps,this._animateNeoWelcome);if(this._neoOrbClickComboCount>=q51){this._neoOrbClickComboCount=0,this._neoOrbLastClickTime=null,this._neoOrbChargeStartTime=null,this._neoOrbRegrowStartTime=A.time;let B=Ie4(this.widget.agentMode,this.widget.useNeoColors).colors,D={x:A.x,y:A.y};if(B)D.primaryColor=B.primary,D.secondaryColor=B.secondary;this.widget.onOrbExplode?.(D)}this.setState(()=>{})};dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;this._lastTickTimeMs=null,super.dispose()}startSettlingAnimation(){if(this._settleStartTimeMs!==null)return;this._settleStartTimeMs=Date.now(),this._settleStartAnimationTime=this._t,this._settleTargetAnimationTime=this.widget.orbVisualStyle==="neo"?pl3(this._t,this.widget.agentMode):this._t}getSettleProgress(A){if(this._settleStartTimeMs===null)return null;return Math.min(1,Math.max(0,(A-this._settleStartTimeMs)/Nl3))}getCurrentEffectTime(){if(this._timer===null&&this._lastTickTimeMs!==null)return this._effectTime+(Date.now()-this._lastTickTimeMs)/1000;return this._effectTime}getNeoOrbClickCharge(A=this.getCurrentEffectTime()){if(this.widget.orbVisualStyle!=="neo"||this._neoOrbChargeStartTime===null)return 0;let Q=A-this._neoOrbChargeStartTime;if(Q<0||Q>Ze4)return 0;let $=Math.min(1,this._neoOrbClickComboCount/Math.max(1,q51-1)),B=1-Q/Ze4,D=Math.exp(-Q*4)*0.12;return Math.max(0,Math.min(1,$*(0.3+B*0.7)+D))}getNeoOrbRegrowthScale(A=this.getCurrentEffectTime()){if(this.widget.orbVisualStyle!=="neo"||this._neoOrbRegrowStartTime===null)return 1;let Q=A-this._neoOrbRegrowStartTime;if(Q<=0)return N51;if(Q>=Ue4)return 1;let $=Q/Ue4;return N51+(1-N51)*$}getAnimationSpeed(A){let Q=this.getSettleProgress(A);if(Q===null)return 1;return(1-Q)*(1-Q)}getSettledOrbTime(A){let Q=this.getSettleProgress(A);if(Q===null||this._settleStartAnimationTime===null||this._settleTargetAnimationTime===null)return null;return this._settleStartAnimationTime+(this._settleTargetAnimationTime-this._settleStartAnimationTime)*dl3(Q)}isNeoWelcomeAnimationPending(){return this._animateNeoWelcome&&this._neoWelcomeTime<Ye4}isClickEffectPending(){let A=this.getCurrentEffectTime();return this._shockwaves.some((Q)=>A-Q.startTime<QF)||this.getNeoOrbClickCharge(A)>0||this.getNeoOrbRegrowthScale(A)<1}stopAnimationTimer(){if(this._timer)clearInterval(this._timer),this._timer=null;this._lastTickTimeMs=null}startAnimation(A,Q){if(this.stopAnimationTimer(),this._fps=A,this._animateNeoWelcome=Q,A>0&&(this.getAnimationSpeed(Date.now())>0||this.isNeoWelcomeAnimationPending()||this.isClickEffectPending()))this._lastTickTimeMs=Date.now(),this._timer=setInterval(()=>{let $=Date.now(),B=this.getAnimationSpeed($);if(B<=0&&!this.isNeoWelcomeAnimationPending()&&!this.isClickEffectPending()){let J=this.getSettledOrbTime($);if(J!==null)this._t=J;this.stopAnimationTimer(),this.setState(()=>{});return}let D=this._lastTickTimeMs===null?1/A:($-this._lastTickTimeMs)/1000;if(this._lastTickTimeMs=$,this._effectTime+=D,this._animateNeoWelcome)this._neoWelcomeTime+=D;if(B>0){let J=this.getSettledOrbTime($);this._t=J??this._t+D*B}this._shockwaves=this._shockwaves.filter((J)=>this._effectTime-J.startTime<QF),this.setState(()=>{})},1000/A)}build(A){let $=L1.of(A).colorScheme,D=O0.of(A).app,J=h1.of(A),F=J.capabilities.animationSupport,Y=F==="fast"?30:F==="slow"?15:0,E=this.widget.orbVisualStyle==="neo"&&F==="fast";if(Y!==this._fps||E!==this._animateNeoWelcome)this.startAnimation(Y,E);let Z=!!this.widget.mysteriousMessage,U=this._suggestion,X=F==="disabled"?3:this._t,G=F==="disabled"?Ye4:this._neoWelcomeTime;if(Z&&!this._previousHasMystery&&F!=="disabled")this._morphStartTime=X;this._previousHasMystery=Z;let V=this.getMorphProgress(X),K=V!==null,z=Ie4(this.widget.agentMode,this.widget.useNeoColors),W=z.colors,I=this.widget.orbVisualStyle==="neo",H=il3(this.widget.agentMode,W),q=I?new T({color:$.foreground,dim:!0}):U.type==="quote"||U.type==="news"?new T({color:$.foreground,dim:!0}):U.type==="hint"?new T({color:$.secondary}):new T({color:U.type==="prompt"||U.type==="note"?$.primary:$.warning}),N=I?new T({color:$.foreground,bold:!0}):new T({color:D.keybind}),w=I?new T({color:H}):new T({color:D.command}),O=new T({color:$.foreground,dim:!0}),L=cl3(U,q,w,(W0)=>{n6(A,W0)}),j=F==="fast",k=j&&this.widget.orbVisualStyle==="classic",_;if(k)_=new IG0({text:"Welcome to Amp",baseColor:$.foreground,backgroundColor:$.background,glow:this._glow,time:X,agentMode:this.widget.agentMode,orbWidth:w51,orbHeight:C51,glowIntensity:1,shockwaves:this._shockwaves});else if(E)_=_l3(G,this._neoWelcomeVariants,this.widget.agentMode,W);else _=new d({text:new C("Welcome to Amp",new T({color:$.foreground}))});let f=null;if(Z){let E0=0.3+(Math.sin(X*0.5)*0.5+0.5)*0.4,I0=new T({color:$.primary,italic:!0,dim:E0<0.5}),P0=this.widget.mysterySequenceProgress?.matched.length??0,Q0=P0>0?"Keep going...":"A message awaits...",M0=[];for(let n=0;n<Je4.length;n++){let a=Je4[n],t=a==="ctrl+x"?"Ctrl-X":a.toUpperCase(),F0=n<P0?new T({color:$.primary,bold:!0}):N;if(n>0)M0.push(new C(", ",O));M0.push(new C(t,F0))}f=new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[j?new IG0({text:Q0,baseColor:$.primary,glow:this._glow,time:X,agentMode:this.widget.agentMode,orbWidth:w51,orbHeight:C51,glowIntensity:0.6,shockwaves:this._shockwaves}):new d({text:new C(Q0,I0)}),new d({text:new C("",void 0,[...M0,new C(" to unlock",O)])})]})}let h,b=`A message awaits...
5300
+ `||Y==="\t";if(E&&Z){D.push($<0.5?F:Y);continue}let U=J/B*0.4,X=Math.max(0,Math.min(1,($-U)/(1-U)));if(X===0)D.push(F);else if(X>=1)D.push(Y);else if(E)D.push(X<0.7?" ":Y);else if(Z)D.push(X<0.3?F:" ");else if(X<0.5){let G=X*2;if(Math.random()<G)D.push(HG0[Math.floor(Math.random()*HG0.length)]);else D.push(F)}else{let G=(X-0.5)*2;if(Math.random()<G)D.push(Y);else D.push(HG0[Math.floor(Math.random()*HG0.length)])}}return D.join("").trimEnd()}var vl3="https://ampcode.com/news/neo",kl3={type:"quote",text:'"Wait, a completely rebuilt Amp? Called Neo?"',url:vl3,linkText:"Neo"},Ve4=[{type:"command",text:'amp -x "What package manager do we use here?"'},{type:"command",text:'amp -x "Run the linter and fix the errors"'},{type:"hint",text:"Use Ctrl+G to edit the prompt in your $EDITOR"},{type:"hint",text:"Use the `prompt: queue` command to enqueue messages without interrupting the agent"},{type:"hint",text:"Use the `thread: browser` command to open your thread in the browser"},{type:"hint",text:"Use the `thread: new` command to start a fresh thread"},{type:"hint",text:"Use the `thread: handoff` command to draft a new thread with relevant context"},{type:"hint",text:"Use the `thread: visibility` command to change thread visibility settings"},{type:"hint",text:"Use the `settings: open in editor` command to configure Amp"},{type:"hint",text:"Use the `agents-md: generate` command to create an AGENTS.md"},{type:"hint",text:"Use Tab/Shift+Tab to navigate to previous messages to edit or restore to a previous state"},{type:"prompt",text:'"Use the oracle to review the code we just wrote."'},{type:"prompt",text:'"Use subagents to update these components to use the new attribute we added."'},{type:"prompt",text:'"Do not write any code yet. Plan first."'},{type:"prompt",text:'"Think hard before you start implementing."'},{type:"prompt",text:`"Use 'psql' to change all blog_posts to have comments"`},{type:"prompt",text:'"Run <build command> and fix all the errors"'},{type:"quote",text:`"We are at the 'introduction of photography' period of programming. Painting by hand just doesn't have the same appeal anymore" - Orta Therox`},{type:"quote",text:'"Programming in the normal way feels like walking. You type out each expression, stepping incrementally toward your goal. When programming with AI, each move is bigger than a step. You lift off the ground." - Mary Rose Cook'},{type:"quote",text:'"Tomorrow all this may change, but right now after daily experience writing code with LLMs I strongly believe the maximum quality of work is reached using the human+LLM equation." - antirez'},{type:"quote",text:`"The magic that's coming now is the most powerful yet. And that means that we're beginning a profound period of exploration and creativity, trying to understand how to make that magic work and to derive new advantages from its power." - Tim O'Reilly`},{type:"quote",text:`"They're applying years of hard-won engineering wisdom to shape and constrain the AI's output. The AI is accelerating their implementation, but their expertise is what keeps the code maintainable." - Addy Osmani`},{type:"quote",text:'"I love computers just for the—sheer machine of it. This is the most exciting new thing that computers have been doing, probably in my lifetime." - DHH'},{type:"quote",text:`"We wouldn't even need to bother looking at the AI-generated code any more, just like we don't bother looking at the machine code generated by a compiler." - Martin Kleppmann`},{type:"quote",text:'"Real progress is messy, iterative, and deeply intertwined with the tools we build. Large language models are the latest, most dramatic example of that truth." - Daniel Lemire'},{type:"quote",text:`"'Human in the loop' is evolving from 'human who fixes AI mistakes' to 'human who directs AI work.'" - Ethan Mollick`},{type:"quote",text:`"I'm trying to code like a surgeon. A surgeon isn't a manager, they do the actual work! But their skills and time are highly leveraged." - Geoffrey Litt`},{type:"quote",text:`"It's important to do things fast. You learn more per unit time because you make contact with reality more frequently." - Nat Friedman`},{type:"quote",text:'"Once coding speed jumps, everything around it becomes the constraint. Your throughput gets capped by whatever is slowest." - Paul Dix'},{type:"quote",text:'"Bubble or no bubble, no one knows anything." - Benedict Evans'},{type:"quote",text:`"I actually don't think documentation is too important: LLMs can read the code a lot faster than you to figure out how to use it." - Simon Willison`},{type:"quote",text:`"The vast majority of AI tokens in the future will be used on things we don't even do today as workers." - Aaron Levie`},{type:"quote",text:`"Once you're airborne, you're suddenly immune to the length of the runway. You have days, not months. Time to break some things." - Kent Beck`},{type:"quote",text:'"Absolutely every fundamental assumption about how I work has to be questioned. There are days when it feels like I would be better off if I did not know anything about programming and started from scratch." - David Crawshaw'},{type:"quote",text:'"Code was the easiest part." - Andrej Karpathy'},{type:"quote",text:`"It's amazing for learning a codebase you're not familiar with, so it's great for discovery. Getting us out of writing boilerplate, getting us out of memorizing APIs, getting us out of looking up that thing from Stack Overflow." - Jeremy Howard`},{type:"quote",text:`"Don't anthropomorphize them!" - Steven Sinofsky`}],w51=40,C51=40,Ke4=44,ze4=36,Sl3=8,fl3=8,qe4=50,Ne4=2,yl3=4,xl3=4,bl3={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},hl3={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},gl3={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}};function ml3(A){return A==="rush"?3.4:A==="deep"?0.9:1.45}function We4(A,Q,$){let B=(A-Q)/$;return Math.exp(-(B*B))}function dl3(A){return 1-(1-Math.max(0,Math.min(1,A)))**3}function pl3(A,Q){let $=ml3(Q),B=0.35,D=4.5,J=72,F=A+1.4,Y=Number.NEGATIVE_INFINITY;for(let E=0;E<72;E++){let Z=E/Math.max(1,71),U=A+0.35+4.15*Z,X=U*$,G=X*1.35,K=(Math.sin(G)+1)*0.5,z=1-Math.abs(Math.cos(G)),W=Math.cos(X*1.55)*0.38-0.18,I=Math.sin(X*1.15)*0.25-0.26,H=We4(W,-0.14,0.2)*0.45+We4(I,-0.29,0.12)*0.55,q=(1-Math.abs(Math.sin(X*1.55)))*0.5+(1-Math.abs(Math.cos(X*1.15)))*0.5,N=X*0.45,w=(1-Math.abs(Math.cos(N)))*0.6+(1-Math.abs(Math.sin(N*0.7)))*0.4,O=1-Z,L=K*0.34+z*0.24+H*0.22+q*0.12+w*0.04+O*0.04;if(L>Y)Y=L,F=U}return F}function Ie4(A,Q){if(A==="frontier")return{colorMode:"vertical",colors:bl3};if(Q&&A==="smart")return{colorMode:"vertical",colors:hl3};if(Q&&A==="deep")return{colorMode:"vertical",colors:gl3};return{colorMode:"intensity"}}function cl3(A,Q,$,B){if(A.type==="hint")return A.text.split(/(`[^`]+`)/g).map((J)=>{if(J.startsWith("`")&&J.endsWith("`"))return new C(J.slice(1,-1),$);return new C(J,Q)});if(A.url&&A.linkText){let D=A.text.indexOf(A.linkText);if(D>=0){let J=A.url,F=A.text.slice(0,D),Y=A.text.slice(D+A.linkText.length);return[new C(F,Q),new C(A.linkText,Q.copyWith({underline:!0}),void 0,cz(J),()=>B(J)),new C(Y,Q)]}}return[new C(A.text,Q)]}function ll3(A){let Q=Math.max(Sl3,A.width-qe4-Ne4-yl3),$=Math.max(fl3,A.height-xl3),B=Math.min(Ke4,Q),D=Math.ceil(B/Ke4*ze4),J=Math.min(ze4,$,D);return{width:B,height:J}}function il3(A,Q){return J$(A==="frontier"?0.78:0.9,A,Q)}class Fx extends R0{agentMode;orbVisualStyle;mysteriousMessage;mysterySequenceProgress;onOrbExplode;settleAnimation;interactive;useNeoColors;centerContent;constructor(A={}){super(A.key?{key:A.key}:{});this.agentMode=A.agentMode,this.orbVisualStyle=A.orbVisualStyle??"classic",this.mysteriousMessage=A.mysteriousMessage,this.mysterySequenceProgress=A.mysterySequenceProgress,this.onOrbExplode=A.onOrbExplode,this.settleAnimation=A.settleAnimation??!1,this.interactive=A.interactive??!0,this.useNeoColors=A.useNeoColors??!1,this.centerContent=A.centerContent}createState(){return new we4}}class we4 extends j0{_glow;_neoWelcomeVariants;_t=0;_effectTime=0;_neoWelcomeTime=0;_timer=null;_fps=0;_animateNeoWelcome=!1;_lastTickTimeMs=null;_settleStartTimeMs=null;_settleStartAnimationTime=null;_settleTargetAnimationTime=null;_shockwaves=[];_neoOrbClickComboCount=0;_neoOrbLastClickTime=null;_neoOrbChargeStartTime=null;_neoOrbRegrowStartTime=null;_suggestion;_morphStartTime=null;_previousHasMystery=!1;initState(){if(super.initState(),this._glow=new a9,this._neoWelcomeVariants=Rl3(),this.widget.orbVisualStyle==="neo")this._suggestion=kl3;else{let A=process.env.NO_SPLASH_QUOTE==="1"?Ve4.filter((Q)=>Q.type!=="quote"):Ve4;this._suggestion=A[Math.floor(Math.random()*A.length)]}if(this._previousHasMystery=!!this.widget.mysteriousMessage,this.widget.settleAnimation)this.startSettlingAnimation()}didUpdateWidget(A){if(super.didUpdateWidget(A),!A.settleAnimation&&this.widget.settleAnimation)this.startSettlingAnimation()}getMorphProgress(A){if(this._morphStartTime===null)return null;let Q=A-this._morphStartTime;if(Q>=Fe4)return null;return Q/Fe4}handleShockwave=(A)=>{if(this._shockwaves.push(A),this._timer===null&&this._fps>0)this.startAnimation(this._fps,this._animateNeoWelcome);this.setState(()=>{})};handleOrbClick=(A)=>{if(this.widget.orbVisualStyle!=="neo")return;if(this.getNeoOrbRegrowthScale(A.time)<1){this._neoOrbClickComboCount=0,this._neoOrbLastClickTime=null,this._neoOrbChargeStartTime=null;return}let Q=this._neoOrbLastClickTime===null?Number.POSITIVE_INFINITY:A.time-this._neoOrbLastClickTime,$=Q>=0&&Q<=Cl3;if(this._neoOrbClickComboCount=$?this._neoOrbClickComboCount+1:1,this._neoOrbLastClickTime=A.time,this._neoOrbChargeStartTime=A.time,this._timer===null&&this._fps>0)this.startAnimation(this._fps,this._animateNeoWelcome);if(this._neoOrbClickComboCount>=q51){this._neoOrbClickComboCount=0,this._neoOrbLastClickTime=null,this._neoOrbChargeStartTime=null,this._neoOrbRegrowStartTime=A.time;let B=Ie4(this.widget.agentMode,this.widget.useNeoColors).colors,D={x:A.x,y:A.y};if(B)D.primaryColor=B.primary,D.secondaryColor=B.secondary;this.widget.onOrbExplode?.(D)}this.setState(()=>{})};dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;this._lastTickTimeMs=null,super.dispose()}startSettlingAnimation(){if(this._settleStartTimeMs!==null)return;this._settleStartTimeMs=Date.now(),this._settleStartAnimationTime=this._t,this._settleTargetAnimationTime=this.widget.orbVisualStyle==="neo"?pl3(this._t,this.widget.agentMode):this._t}getSettleProgress(A){if(this._settleStartTimeMs===null)return null;return Math.min(1,Math.max(0,(A-this._settleStartTimeMs)/Nl3))}getCurrentEffectTime(){if(this._timer===null&&this._lastTickTimeMs!==null)return this._effectTime+(Date.now()-this._lastTickTimeMs)/1000;return this._effectTime}getNeoOrbClickCharge(A=this.getCurrentEffectTime()){if(this.widget.orbVisualStyle!=="neo"||this._neoOrbChargeStartTime===null)return 0;let Q=A-this._neoOrbChargeStartTime;if(Q<0||Q>Ze4)return 0;let $=Math.min(1,this._neoOrbClickComboCount/Math.max(1,q51-1)),B=1-Q/Ze4,D=Math.exp(-Q*4)*0.12;return Math.max(0,Math.min(1,$*(0.3+B*0.7)+D))}getNeoOrbRegrowthScale(A=this.getCurrentEffectTime()){if(this.widget.orbVisualStyle!=="neo"||this._neoOrbRegrowStartTime===null)return 1;let Q=A-this._neoOrbRegrowStartTime;if(Q<=0)return N51;if(Q>=Ue4)return 1;let $=Q/Ue4;return N51+(1-N51)*$}getAnimationSpeed(A){let Q=this.getSettleProgress(A);if(Q===null)return 1;return(1-Q)*(1-Q)}getSettledOrbTime(A){let Q=this.getSettleProgress(A);if(Q===null||this._settleStartAnimationTime===null||this._settleTargetAnimationTime===null)return null;return this._settleStartAnimationTime+(this._settleTargetAnimationTime-this._settleStartAnimationTime)*dl3(Q)}isNeoWelcomeAnimationPending(){return this._animateNeoWelcome&&this._neoWelcomeTime<Ye4}isClickEffectPending(){let A=this.getCurrentEffectTime();return this._shockwaves.some((Q)=>A-Q.startTime<QF)||this.getNeoOrbClickCharge(A)>0||this.getNeoOrbRegrowthScale(A)<1}stopAnimationTimer(){if(this._timer)clearInterval(this._timer),this._timer=null;this._lastTickTimeMs=null}startAnimation(A,Q){if(this.stopAnimationTimer(),this._fps=A,this._animateNeoWelcome=Q,A>0&&(this.getAnimationSpeed(Date.now())>0||this.isNeoWelcomeAnimationPending()||this.isClickEffectPending()))this._lastTickTimeMs=Date.now(),this._timer=setInterval(()=>{let $=Date.now(),B=this.getAnimationSpeed($);if(B<=0&&!this.isNeoWelcomeAnimationPending()&&!this.isClickEffectPending()){let J=this.getSettledOrbTime($);if(J!==null)this._t=J;this.stopAnimationTimer(),this.setState(()=>{});return}let D=this._lastTickTimeMs===null?1/A:($-this._lastTickTimeMs)/1000;if(this._lastTickTimeMs=$,this._effectTime+=D,this._animateNeoWelcome)this._neoWelcomeTime+=D;if(B>0){let J=this.getSettledOrbTime($);this._t=J??this._t+D*B}this._shockwaves=this._shockwaves.filter((J)=>this._effectTime-J.startTime<QF),this.setState(()=>{})},1000/A)}build(A){let $=L1.of(A).colorScheme,D=O0.of(A).app,J=h1.of(A),F=J.capabilities.animationSupport,Y=F==="fast"?30:F==="slow"?15:0,E=this.widget.orbVisualStyle==="neo"&&F==="fast";if(Y!==this._fps||E!==this._animateNeoWelcome)this.startAnimation(Y,E);let Z=!!this.widget.mysteriousMessage,U=this._suggestion,X=F==="disabled"?3:this._t,G=F==="disabled"?Ye4:this._neoWelcomeTime;if(Z&&!this._previousHasMystery&&F!=="disabled")this._morphStartTime=X;this._previousHasMystery=Z;let V=this.getMorphProgress(X),K=V!==null,z=Ie4(this.widget.agentMode,this.widget.useNeoColors),W=z.colors,I=this.widget.orbVisualStyle==="neo",H=il3(this.widget.agentMode,W),q=I?new T({color:$.foreground,dim:!0}):U.type==="quote"||U.type==="news"?new T({color:$.foreground,dim:!0}):U.type==="hint"?new T({color:$.secondary}):new T({color:U.type==="prompt"||U.type==="note"?$.primary:$.warning}),N=I?new T({color:$.foreground,bold:!0}):new T({color:D.keybind}),w=I?new T({color:H}):new T({color:D.command}),O=new T({color:$.foreground,dim:!0}),L=cl3(U,q,w,(W0)=>{n6(A,W0)}),j=F==="fast",k=j&&this.widget.orbVisualStyle==="classic",_;if(k)_=new IG0({text:"Welcome to Amp",baseColor:$.foreground,backgroundColor:$.background,glow:this._glow,time:X,agentMode:this.widget.agentMode,orbWidth:w51,orbHeight:C51,glowIntensity:1,shockwaves:this._shockwaves});else if(E)_=_l3(G,this._neoWelcomeVariants,this.widget.agentMode,W);else _=new d({text:new C("Welcome to Amp",new T({color:$.foreground}))});let f=null;if(Z){let E0=0.3+(Math.sin(X*0.5)*0.5+0.5)*0.4,I0=new T({color:$.primary,italic:!0,dim:E0<0.5}),P0=this.widget.mysterySequenceProgress?.matched.length??0,Q0=P0>0?"Keep going...":"A message awaits...",M0=[];for(let n=0;n<Je4.length;n++){let a=Je4[n],t=a==="ctrl+x"?"Ctrl-X":a.toUpperCase(),F0=n<P0?new T({color:$.primary,bold:!0}):N;if(n>0)M0.push(new C(", ",O));M0.push(new C(t,F0))}f=new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[j?new IG0({text:Q0,baseColor:$.primary,glow:this._glow,time:X,agentMode:this.widget.agentMode,orbWidth:w51,orbHeight:C51,glowIntensity:0.6,shockwaves:this._shockwaves}):new d({text:new C(Q0,I0)}),new d({text:new C("",void 0,[...M0,new C(" to unlock",O)])})]})}let h,b=`A message awaits...
5302
5301
  Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)h=this.widget.centerContent;else if(K){let E0=U.text.replace(/`([^`]+)`/g,"$1")+`
5303
5302
  `,I0=Tl3(E0,b,V),$0=new T({color:$.primary,dim:!0}),P0=I0.split(`
5304
5303
  `);h=new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new d({text:new C(P0[0]??"",$0)}),new d({text:new C(P0[1]??" ",$0)})]})}else if(Z)h=new X0({width:0,height:0});else h=new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new d({text:new C("",void 0,L)}),new d({text:new C(" ")})]});let v=[_,new d({text:new C("",void 0,[new C(`
@@ -5322,7 +5321,7 @@ Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)h=this.widget.centerContent
5322
5321
  `))}return F}function Ri3(A,Q,$){let{colors:B,app:D}=$,J=Pi3(Q.status,$);if(A.push(new C(` ${J.icon} `,new T({color:J.color}))),A.push(new C(Q.name,new T({color:Q.status==="pending"?B.warning:D.command}))),Q.status==="pending")A.push(new C(" discovering...",new T({color:B.foreground,dim:!0})));else if(Q.description)A.push(new C(` ${me4(Q.description,50)}`,new T({color:B.foreground,dim:!0})));if(Q.error)A.push(new C(` ${me4(Q.error,40)}`,new T({color:D.toolError})));A.push(new C(`
5323
5322
  `))}function Pi3(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 me4(A,Q){let $=A.replace(/\s+/g," ").trim();if(J4($)<=Q)return $;let B="...",D=J4(B);if(Q<=D)return GQ(B,Q);return`${GQ($,Q-D,!0,"")}${B}`}var f51="https://ampcode.com/news/neo",y51=[{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:f51,href:f51},"","",{text:"Need old Amp for a bit? Use ",keybind:"amp --take-me-back"}]}];function ui3(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:f51,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function _i3(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var Yx=50,TR=40,k51=1000,Ti3=420,vi3=760,ki3=-250,Si3=1100,NG0=33,le4=0.999,fi3=2.1,yi3=720,xi3=420,ee4="Meet the new",A06="Amp",Q06="CLI",x51=Y4(ee4).length,bi3=Y4(A06).length,hi3=Y4(Q06).length,wG0={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},ie4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},ne4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},ae4=[wG0,ie4,ne4,wG0,ie4,ne4,wG0],gi3=wG0;class b51 extends R0{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??_i3(),this.introStages=this.variant==="npm-migration"?ui3(this.binaryInstallCommand):y51,this.dismissible=this.variant!=="npm-migration"}createState(){return new $06}}class $06 extends j0{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=k51;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 a9(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=YF(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=le4,this.firstStageHintVisible=this.animationProgress>=le4,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:k51,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=YF(A/vi3);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},NG0)}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=YF($/Ti3);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},NG0)}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,J=YF(D/this.animationDurationMs),F=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*Ex(J);if(this.setState(()=>{this.animationProgress=F}),J>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},NG0)}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,k51+ki3),Q=A+Si3;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?YF((A-this.firstStageTitleRevealStartedAt)/yi3):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?YF((A-this.firstStageHintRevealStartedAt)/xi3):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},NG0)}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=oe4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:re4(oe4(this.previousIntroStage),A,Ex(this.stageTransitionProgress));return this.dismissProgress>0?re4(Q,gi3,Ex(this.dismissProgress)):Q}build(A){let Q=L1.of(A).colorScheme,$=O0.of(A),B=this.currentOrbPalette(),D=J$(1,"frontier",B),J=h1.of(A).size,Y=this.widget.animationProgress??this.animationProgress,E=Math.max(J.width/Yx,J.height/TR)*fi3,Z=E+(1-E)*Y,U=Ex(this.dismissProgress),X=Math.max(Yx,Math.round(Yx*Z)),G=Math.max(TR,Math.round(TR*Z)),V=Math.round((J.width-X)/2),K=Math.round((J.height-G)/2),z=Math.max(0,Math.floor((J.width-Yx)/2)),W=-Math.floor(TR/2),I=Math.round(V+(z-V)*Y),H=Math.round(K+(W-K)*Y),q=I+X/2,N=H+G/2,w=mi3({dismissProgress:this.dismissProgress,easedDismissProgress:U,introOrbScale:Z,normalOrbCenterX:q,normalOrbCenterY:N,size:J}),O=Math.max(Yx,Math.round(Yx*w.orbScale)),L=Math.max(TR,Math.round(TR*w.orbScale)),j=w.orbCenterX,k=w.orbCenterY,_=Math.round(j-O/2),f=Math.round(k-L/2),h=Math.max(3,Math.min(J.height-5,Math.floor(TR/2)+2)),b=Math.max(h+3,J.height-3),v=w.textDissolveProgress,y=this.isFinalIntroStage()?w.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&v<1,p=c&&this.firstStageHintVisible,g=p&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),i=this.introStage===0?this.firstStageTitleRevealProgress:1,o=this.introStage===0?this.firstStageHintRevealProgress:1,A0=Math.max(24,Math.min(74,J.width-4)),W0=Math.min(12,Math.max(8,J.height-h-6)),E0=Math.max(0,Math.floor((J.width-A0)/2)),I0=Math.max(0,Math.min(J.height-W0,Math.floor(J.height*0.55-W0/2))),P0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new _N({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new _N({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new k4({autofocus:!0,canRequestFocus:!0,debugLabel:"NeoWelcomeTakeover",onKey:(Q0)=>{if(Q0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&Q0.key==="c"&&Q0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&Q0.key==="q")return this.widget.onQuit?.(),"handled";if((Q0.key===" "||Q0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(Q0.key==="Escape"||Q0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(Q0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(Q0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new i4({fit:"expand",children:[new B06({color:Q.background,dissolveProgress:y}),new i4({fit:"expand",children:[new O1({onClick:()=>{},child:X0.expand()}),new o4({left:_,top:f,width:O,height:L,child:P0}),...c?[new o4({left:E0,top:I0,width:A0,height:W0,child:pi3({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:A0,height:W0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:D,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:i,dissolveProgress:v,context:A})})]:[],...p?[...g?[new o4({left:E0,top:Math.max(0,b-1),width:A0,height:1,child:new d({text:oi3({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new o4({left:E0,top:b,width:A0,height:1,child:si3({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:o,dissolveProgress:v,context:A})})]:[]]})]})})}}class B06 extends R5{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new D06(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class D06 extends b1{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;z4(!!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),J=Math.floor(this.size.width),F=Math.floor(this.size.height),Y={bg:this.color},E=YF(this.dissolveProgress);if(E<=0){A.fill(B,D,J,F," ",Y);return}if(E>=1)return;for(let Z=0;Z<F;Z++)for(let U=0;U<J;U++)if(!di3(U,Z,J,F,E))A.fill(B+U,D+Z,1,1," ",Y)}}function YF(A){return Math.min(1,Math.max(0,A))}function Ex(A){return 1-(1-A)**3}function oe4(A){return ae4[A]??ae4[0]}function re4(A,Q,$){return{primary:cj(A.primary,Q.primary,$),secondary:cj(A.secondary,Q.secondary,$)}}function mi3({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:D,size:J}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(J.width*0.54-B)*Q,orbCenterY:D-J.height*0.44*Q,textDissolveProgress:YF(A/0.52),backdropDissolveProgress:Ex(YF((A-0.12)/0.88))}}function di3(A,Q,$,B,D){let J=B<=1?0:Q/(B-1),F=J06(A+Q*Math.max(1,$));return(1-J)*0.72+F*0.28<D}function pi3({introStages:A,stage:Q,previousStage:$,progress:B,direction:D,width:J,height:F,foreground:Y,mutedForeground:E,accent:Z,link:U,keybind:X,titleRevealProgress:G,dissolveProgress:V,context:K}){if($===null||B>=1)return S51({introStages:A,stage:Q,foreground:Y,mutedForeground:E,accent:Z,link:U,keybind:X,titleRevealProgress:G,dissolveProgress:V,context:K});let z=Ex(B),W=D*Math.round((1-z)*J),I=-D*Math.round(z*J);return new rz(new i4({fit:"expand",children:[new o4({left:I,top:0,width:J,height:F,child:S51({introStages:A,stage:$,foreground:Y,mutedForeground:E,accent:Z,link:U,keybind:X,titleRevealProgress:$===0?1:G,dissolveProgress:V,context:K})}),new o4({left:W,top:0,width:J,height:F,child:S51({introStages:A,stage:Q,foreground:Y,mutedForeground:E,accent:Z,link:U,keybind:X,titleRevealProgress:G,dissolveProgress:V,context:K})})]}))}function S51({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:D,link:J,keybind:F,titleRevealProgress:Y,dissolveProgress:E,context:Z}){let U=A[Q]??A[0]??y51[0],X=new T({color:D,bold:!0}),G=new T({color:$}),V=A===y51&&Q===0,K=[...U.title===null?[]:[new d({text:V?CG0(ii3({progress:Y,foreground:D,pulseColor:D}),E):new C(WB(U.title,E),X),textAlign:"center"})],...U.body.length>0?[ci3()]:[],...U.body.map((z)=>li3(z,G,B,J,F,E,Z))];return new $4({child:new f0({padding:V0.horizontal(1),child:new S0({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:K})})})}function ci3(){return X0.height(1)}function li3(A,Q,$,B,D,J,F){if(typeof A==="string")return new d({text:new C(WB(A,J),Q),textAlign:"center"});if("codeBlock"in A)return new X5({onCopy:(Y,E)=>{if(E)L3.success(F,"Copied to clipboard",2000)},child:new S0({mainAxisSize:"min",children:A.codeBlock.map((Y)=>new d({text:new C(WB(Y,J),new T({color:D})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let Y=new d({text:new C("",void 0,[new C(WB(A.text,J),new T({color:$,dim:!0})),new C(WB(A.keybind,J,Y4(A.text).length),new T({color:D}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new $4({child:new X5({child:Y})});return Y}if("highlightText"in A){let Y=u6.createSpan(A.href,A.linkText,new T({color:B,underline:!0})),E=eZ.of(F),Z=new C("",void 0,[new C(A.text,Q),new C(A.highlightText,new T({color:D})),new C(A.textAfterHighlight,Q),new C(Y.text,Y.style,Y.children,Y.hyperlink,()=>{n6(F,A.href,{forceExternal:!1,onShowImagePreview:E})}),new C(A.textAfter,Q)]);return new d({text:CG0(Z,J),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new S0({mainAxisSize:"min",children:[new d({text:new C(WB(A.text,J),Q),textAlign:"center"}),new $4({child:new r0({mainAxisSize:"min",children:[u6.createWidget(F,A.href,WB(A.linkText,J),new T({color:B,underline:!0})),new d({text:new C(WB(A.textAfter,J),Q)})]})})]});let Y=u6.createSpan(A.href,A.linkText,new T({color:B,underline:!0})),E=eZ.of(F),Z=new C("",void 0,[new C(A.text,Q),new C(Y.text,Y.style,Y.children,Y.hyperlink,()=>{n6(F,A.href,{forceExternal:!1,onShowImagePreview:E})}),new C(A.textAfter,Q)]);return new d({text:CG0(Z,J),textAlign:"center"})}if(J>0)return new d({text:new C(WB(A.text,J),new T({color:B,underline:!0})),textAlign:"center"});return new $4({child:u6.createWidget(F,A.href,A.text,new T({color:B,underline:!0}))})}function ii3({progress:A,foreground:Q,pulseColor:$}){let B=new T({color:Q,bold:!0}),D=new T({color:ai3({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new C("",void 0,[new C(ni3(A).padEnd(x51," "),B),new C(" ",B),new C(se4(A06,bi3,A,0.72),B),new C(" ",B),new C(se4(Q06,hi3,A,0.88),D)])}function ni3(A){let Q=Y4(ee4),$=Math.min(x51,Math.ceil(YF(A/0.62)*x51));return Q.slice(0,$).join("")}function se4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function ai3({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=YF((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function oi3({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new C(WB(`${A}/${Q}`,B),new T({color:$,dim:!0}))}function ri3({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:J}){let F=new T({color:B}),Y=new T({color:$,dim:!0}),E=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit, or use ",U=Q?"":"amp --take-me-back",X=Q?"":" to use the old version",G=`${Z}${U}${X}`;if(!Q)return new C("",void 0,[new C(E,F),new C(Z,Y),new C(U,F),new C(X,Y)]);let V=te4(E,D),K=te4(G,YF((D*(Y4(E).length+Y4(G).length)-Y4(E).length)/Y4(G).length));return new C("",void 0,[new C(WB(V,J),F),new C(WB(K.slice(0,Z.length),J),Y),new C(WB(K.slice(Z.length,Z.length+U.length),J),F),new C(WB(K.slice(Z.length+U.length),J),Y)])}function si3({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:J,context:F}){if(Q)return new d({text:ri3({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:J}),textAlign:"center"});let Y=new T({color:B}),E=new T({color:$,dim:!0});return new X5({onCopy:(Z,U)=>{if(U)L3.success(F,"Copied to clipboard",2000)},child:new d({text:new C("",void 0,[new C("q",Y),new C(" to quit, or use ",E),new C("amp --take-me-back",Y),new C(" to use the old version",E)]),textAlign:"center",selectable:!0})})}function te4(A,Q){let $=Y4(A),B=Math.min($.length,Math.ceil(YF(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function CG0(A,Q,$=0){if(Q<=0)return A;let B=$+Y4(A.text??"").length,D=A.children?.map((J)=>{let F=CG0(J,Q,B);return B+=Y4(J.toPlainText()).length,F});return new C(A.text?WB(A.text,Q,$):A.text,A.style,D,A.hyperlink,A.onClick)}function WB(A,Q,$=0){if(Q<=0)return A;return Y4(A).map((D,J)=>{if(D.trim()==="")return D;return J06($+J)<Q?" ":D}).join("")}function J06(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}p0();A8();function Gw(A,Q){let{colors:$,dim:B}=Q,D=[];if(A.totalCostUSD===null)return D;let J=A.costBreakdown,F=J?.freeUSD??0,Y=J?.paidUSD??0;if(F===0&&Y===0)return D;let Z={decimalPlaces:"more-if-tiny",intent:"cost"};if(Y===0)D.push(new C(eG(F,Z),new T({color:$.foreground,dim:B}))),D.push(new C(" (free)",new T({color:$.foreground,dim:B})));else if(F>0)D.push(new C(eG(F,Z),new T({color:$.foreground,dim:B}))),D.push(new C(" (free)",new T({color:$.foreground,dim:B}))),D.push(new C(" + ",new T({color:$.foreground,dim:B}))),D.push(new C(eG(Y,Z),new T({color:$.foreground,dim:B,bold:!B})));else D.push(new C(eG(Y,Z),new T({color:$.foreground,dim:B,bold:!B})));return D}class h51 extends V4{}class g51 extends V4{}function ti3(A,Q){if(Q.code==="auth-required")return"You must be logged in to view thread usage. Run `amp login` first.";if(Q.code==="thread-not-found")return`Thread ${A} not found.`;return`Failed to load thread usage: ${Q.message??Q.code}`}function ei3(A,Q){let $=O0.of(Q),{colors:B}=$,D=Gw(A,{colors:{foreground:B.foreground}}),J=[];if(D.length>0)J.push(new C("Total: ",new T({color:B.mutedForeground}))),J.push(...D);else if(A.totalCostUSD===null)J.push(new C("Usage information is currently unavailable."));else J.push(new C("No usage recorded for this thread yet."));if(A.costBreakdownURL)J.push(new C(`
5324
5323
 
5325
- `)),J.push(new C("Details: ",new T({color:B.mutedForeground}))),J.push(new C(A.costBreakdownURL,new T({color:$.app.link})));return new d({text:new C("",void 0,J)})}function An3(A,Q,$){let B=ei3(A,Q);if(!A.costBreakdownURL)return new w6({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:$,child:B});let D=A.costBreakdownURL,J=new T1(()=>{return x4.maybeInvoke(Q,new W8(D,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),F=new T1(()=>{return n6(Q,D),"handled"});return new w6({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:$,child:new x4({actions:new Map([[h51,J],[g51,F]]),child:new kA({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[G1.key("o"),new g51],[G1.key("y"),new h51]]),child:new v4({autofocus:!0,debugLabel:"ThreadCostBody",child:B})})})})}function F06(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,$,B)=>{let D=A.getActiveThreadID();if(!D)return;try{let J=await e4.threadDisplayCostInfo({threadID:D},{config:A.configService});if(!J.ok){A.toastController.show(ti3(D,J.error),"error",5000),B();return}Q.push(An3(J.result,$,B))}catch(J){P.error("Failed to load Neo thread cost",{error:J,threadID:D}),A.toastController.show(`Failed to show thread cost: ${J instanceof Error?J.message:String(J)}`,"error",5000),B()}}}}p0();u9();Q4();class UW extends V4{direction;constructor(A){super();this.direction=A}}class MG0 extends V4{}class Wt extends V4{}class LG0 extends V4{index;constructor(A){super();this.index=A}}function m51(A){return A.length+2}class d51 extends R0{props;constructor(A){super();this.props=A}createState(){return new Y06}}class Y06 extends j0{selectedIndex=0;initState(){super.initState(),this.selectedIndex=this.findSelectableIndex(this.widget.props.initialSelectedIndex??0)}didUpdateWidget(A){this.selectedIndex=this.findSelectableIndex(this.selectedIndex)}isSelectable(A){let Q=this.widget.props.entries[A];return Q?.type==="item"&&(Q.enabled??!0)}findSelectableIndex(A){let{entries:Q}=this.widget.props;if(Q.length===0)return 0;let $=Math.max(0,Math.min(A,Q.length-1));if(this.isSelectable($))return $;for(let B=1;B<Q.length;B++){let D=$+B;if(D<Q.length&&this.isSelectable(D))return D;let J=$-B;if(J>=0&&this.isSelectable(J))return J}return 0}moveSelection(A){let Q=this.findNextSelectableIndex(A);if(Q===this.selectedIndex)return;this.setState(()=>{this.selectedIndex=Q})}findNextSelectableIndex(A){let{entries:Q}=this.widget.props;for(let $=this.selectedIndex+A;$>=0&&$<Q.length;$+=A)if(this.isSelectable($))return $;return this.selectedIndex}acceptIndex(A){let Q=this.widget.props.entries[A];if(Q?.type!=="item"||!(Q.enabled??!0))return;this.setState(()=>{this.selectedIndex=A}),this.widget.props.onAccept(Q.value)}invoke=(A)=>{if(A instanceof UW)return this.moveSelection(A.direction),"handled";if(A instanceof MG0)return this.acceptIndex(this.selectedIndex),"handled";if(A instanceof Wt)return this.widget.props.onDismiss(),"handled";if(A instanceof LG0)return this.acceptIndex(A.index),"handled";return"ignored"};buildShortcuts(){let A=new Map([[G1.key("ArrowDown"),new UW(1)],[G1.key("j"),new UW(1)],[G1.ctrl("n"),new UW(1)],[G1.key("ArrowUp"),new UW(-1)],[G1.key("k"),new UW(-1)],[G1.ctrl("p"),new UW(-1)],[G1.key("Enter"),new MG0],[G1.key("Escape"),new Wt],[G1.ctrl("."),new Wt]]);return this.widget.props.entries.forEach((Q,$)=>{if(Q.type==="item"&&Q.shortcut)A.set(Q.shortcut,new LG0($))}),A}buildActions(){return new Map([[UW,new T1(this.invoke)],[MG0,new T1(this.invoke)],[Wt,new T1(this.invoke)],[LG0,new T1(this.invoke)]])}build(A){let Q=O0.of(A),$=Qn3(this.widget.props.entries,h1.of(A).supportsEmojiWidth);return new x0({width:this.widget.props.width,height:m51(this.widget.props.entries),decoration:new R4(Q.colors.background,p1.all(new c1(Q.colors.border,1,"solid"))),child:new x4({actions:this.buildActions(),child:new kA({debugLabel:"NeoContextPickerShortcuts",shortcuts:this.buildShortcuts(),child:new v4({autofocus:!0,debugLabel:"NeoContextPicker",child:new S0({mainAxisSize:"min",crossAxisAlignment:"stretch",children:this.widget.props.entries.map((B,D)=>this.buildEntry(B,D,$,Q))})})})})})}buildEntry(A,Q,$,B){if(A.type==="separator")return new x0({height:1,decoration:{border:new p1(new c1(B.colors.border,1,"solid"))}});let D=Q===this.selectedIndex,J=A.enabled??!0,F=new T({color:D?B.app.selectionForeground:B.colors.foreground,dim:!J}),Y=new T({color:D?B.app.selectionForeground:B.app.keybind,bold:!0,dim:!J});return new O1({onClick:()=>this.acceptIndex(Q),child:new x0({padding:V0.symmetric(1,0),decoration:D?new R4(B.app.selectionBackground):void 0,child:new r0({crossAxisAlignment:"start",children:[new R1({child:new d({text:new C(A.label,F),maxLines:1,overflow:"ellipsis"})}),new X0({width:1}),new X0({width:$,child:new d({text:new C(E06(A),Y),textAlign:"right",maxLines:1,overflow:"ellipsis"})})]})})})}}function Qn3(A,Q){return A.reduce(($,B)=>{return B.type==="item"?Math.max($,J4(E06(B),Q)):$},0)}function E06(A){return A.shortcutLabel??A.shortcut?.toString().toLowerCase()??""}var $n3=36,Bn3=24,Dn3=72;class Z06 extends R0{child;onContext;constructor(A,Q){super();this.child=A;this.onContext=Q}createState(){return new U06}}class U06 extends j0{build(A){return this.widget.onContext(A),this.widget.child}}function X06(A){return A.replace(/ ago$/,"")}function OG0(A){return A.reduce((Q,$)=>Math.max(Q,J4(X06($.description.timeAgo))),0)}function G06(A){return Math.max(Bn3,Math.min(A,Dn3))}class p51 extends V4{}class c51 extends V4{}class l51{options;visibility;width=$n3;constructor(A){this.options=A;this.visibility=new xr(A.state)}isVisible(){return this.visibility.isEnabled()}buildBody(A){return new r0({crossAxisAlignment:"stretch",children:[this.buildSlot(),new R1({child:A})]})}buildSlot(){if(!this.options.isAvailable()||this.visibility.isDisabled())return new X0({width:0});return new X0({width:this.width,child:new k4({debugLabel:"ThreadListSidebar",child:new V06({activeThreadID:this.options.getActiveThreadID(),currentWorkspaceURI:t1(i0.file(this.options.getWorkspaceRoot())),width:this.width,loadThreads:this.options.loadThreads,onSelectThread:this.options.onSelectThread,onDismiss:this.close,onResizeWidth:this.resize})})})}commands(){if(!this.options.isAvailable())return[];return[{noun:"thread",verb:"toggle sidebar",description:"Show or hide the thread sidebar",keywords:["sidebar","recent","history","threads"],shortcut:G1.alt("s"),status:{type:"enabled"},run:(A,Q,$)=>{$(),this.toggle()}}]}shortcutEntries(){return this.options.isAvailable()?[[G1.alt("s"),new XX0]]:[]}actionEntries(){if(!this.options.isAvailable())return[];return[[XX0,new T1(()=>this.toggle())]]}toggle=()=>{if(!this.options.isAvailable())return"ignored";if(this.visibility.isDisabled()&&this.options.isBlocked())return"ignored";return this.visibility.toggle(),"handled"};close=()=>{this.visibility.disable()};resize=(A)=>{let Q=G06(A);if(Q===this.width)return;this.options.state.setState(()=>{this.width=Q})}}class V06 extends R0{props;constructor(A){super();this.props=A}createState(){return new K06}}class K06 extends j0{threads=[];isLoading=!0;isSwitchingThread=!1;hasError=!1;filterByWorkspace=!0;timeColWidth=0;contextMenu=null;pendingThreadMutations=new Map;resizeSession=null;isResizeHandleHovered=!1;pickerController=new Qs;threadItemContexts=new Map;shortcuts=new Map([[G1.alt("w"),new p51],[G1.ctrl("."),new c51]]);actions=new Map([[p51,new T1(()=>{return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.contextMenu=null}),"handled"})],[c51,new T1(()=>this.openContextMenu())]]);get isBusy(){return this.isLoading||this.isSwitchingThread}get isResizeActive(){return this.resizeSession!==null||this.isResizeHandleHovered}didUpdateWidget(A){if(this.contextMenu&&(A.props.width!==this.widget.props.width||A.props.currentWorkspaceURI!==this.widget.props.currentWorkspaceURI))this.contextMenu=null}initState(){super.initState(),this.loadThreadSummaries()}async loadThreadSummaries(){try{let A=await this.widget.props.loadThreads(),Q=k31(A);if(!this.mounted)return;this.setState(()=>{this.pickerController.selectedItem=Q.find(($)=>$.id===this.widget.props.activeThreadID)??null,this.threads=Q,this.timeColWidth=OG0(Q),this.isLoading=!1,this.hasError=!1})}catch(A){if(P.error("Failed to load threads for Neo sidebar",{error:A}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}handleSelectThread=async(A)=>{if(this.isSwitchingThread)return;this.setState(()=>{this.isSwitchingThread=!0});try{await this.widget.props.onSelectThread(A),this.widget.props.onDismiss()}catch(Q){P.error("Failed to switch thread from Neo sidebar",{error:Q,threadID:A})}finally{if(this.mounted)this.setState(()=>{this.isSwitchingThread=!1})}};getOptimisticThreads(){return this.threads.flatMap((A)=>{if(this.pendingThreadMutations.get(A.id)?.kind==="archive")return[];return[A]})}getThreadsForDisplay(){let A=this.getOptimisticThreads();return this.filterByWorkspace?A.filter((Q)=>!Q.workspaceURI||Q.workspaceURI===this.widget.props.currentWorkspaceURI):A}buildContextMenuEntries(){return[{type:"item",value:"archive",label:"Archive Thread",shortcut:G1.key("a"),shortcutLabel:"a"},{type:"separator"},{type:"item",value:"copy-id",label:"Copy ID",shortcut:G1.ctrl("c"),shortcutLabel:"ctrl+c"},{type:"item",value:"copy-url",label:"Copy URL",shortcut:new G1("c",{shift:!0,ctrl:!0}),shortcutLabel:"shift+ctrl+c"}]}openContextMenu(){let A=this.pickerController.selectedItem;if(!A||this.isBusy||this.hasError)return"ignored";let Q=this.buildContextMenuEntries(),$=m51(Q),B=this.getContextMenuWidth(),D=this.getContextMenuPosition(A.id,$,B);return this.setState(()=>{this.contextMenu={threadID:A.id,left:D.left,top:D.top,width:B,height:$}}),"handled"}getContextMenuWidth(){let A=Math.max(24,this.widget.props.width-3);return Math.max(1,Math.min(A,this.widget.props.width-2))}getContextMenuPosition(A,Q,$){let B=Math.max(0,Math.min(2,this.widget.props.width-$)),D=1,J=this.threadItemContexts.get(A)?.findRenderObject(),F=this.context.findRenderObject();if(!(J instanceof b1)||!(F instanceof b1))return{left:B,top:1};let Y=J.localToGlobal({x:0,y:0}),E=F.localToGlobal({x:0,y:0}),Z=Y.y-E.y,U=Z+J.size.height,X=h1.sizeOf(this.context).height,G=Math.max(1,Math.min(F.size.height,X-E.y)),z=G-U>=Q||Z<G/2?U:Z-Q,W=Math.max(0,G-Q);return{left:B,top:Math.max(0,Math.min(z,W))}}closeContextMenu=()=>{if(!this.contextMenu)return;this.setState(()=>{this.contextMenu=null})};handleContextMenuAccept=(A)=>{let Q=this.contextMenu?.threadID;if(!Q)return;if(this.closeContextMenu(),A==="archive"){this.archiveContextMenuThread(Q);return}if(A==="copy-id"){x4.maybeInvoke(this.context,new W8(Q,"Thread ID copied to clipboard","Failed to copy thread ID"));return}x4.maybeInvoke(this.context,new W8(this.getThreadURL(Q),"Thread URL copied to clipboard","Failed to copy thread URL"))};beginOptimisticArchive(A){if(this.pendingThreadMutations.has(A))return!1;if(!this.threads.some(($)=>$.id===A))return!1;let Q={kind:"archive",fallbackSelectedThreadID:null};return this.setState(()=>{this.pendingThreadMutations.set(A,Q),this.timeColWidth=OG0(this.getOptimisticThreads())}),i6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;let $=this.pendingThreadMutations.get(A);if($?.kind!=="archive")return;$.fallbackSelectedThreadID=this.pickerController.selectedItem?.id??null}),!0}commitOptimisticArchive(A){if(this.pendingThreadMutations.get(A)?.kind!=="archive")return;this.pendingThreadMutations.delete(A),this.threads=this.threads.filter(($)=>$.id!==A),this.timeColWidth=OG0(this.getOptimisticThreads())}rollbackOptimisticArchive(A){let Q=this.pendingThreadMutations.get(A);if(Q?.kind!=="archive")return;let $=this.threads.find((B)=>B.id===A);if(!$){this.pendingThreadMutations.delete(A);return}this.setState(()=>{this.pendingThreadMutations.delete(A),this.timeColWidth=OG0(this.getOptimisticThreads());let B=this.pickerController.selectedItem?.id??null;if(B===null||B===Q.fallbackSelectedThreadID)this.pickerController.selectedItem=$})}async archiveContextMenuThread(A){let Q=L3.maybeOf(this.context),{configService:$}=V5.of(this.context);if(!this.beginOptimisticArchive(A))return;try{let B=await zU0({configService:$},A);if(!this.mounted)return;if(B){this.rollbackOptimisticArchive(A),Q?.show(B.message,"error");return}this.commitOptimisticArchive(A)}catch(B){if(P.error("Failed to archive thread from Neo sidebar context menu",{error:B,threadID:A}),!this.mounted)return;this.rollbackOptimisticArchive(A),Q?.show("Failed to archive thread","error")}}getThreadURL(A){return x$(new URL(V5.of(this.context).ampURL),A).toString()}buildContextMenuOverlay(){let A=this.contextMenu;if(!A||!this.getThreadsForDisplay().some((Q)=>Q.id===A.threadID))return null;return new o4({left:A.left,top:A.top,width:A.width,height:A.height,child:new k4({debugLabel:"ThreadListSidebarContextMenu",onFocusChange:(Q)=>{if(!Q)this.closeContextMenu()},child:new d51({entries:this.buildContextMenuEntries(),width:A.width,onAccept:this.handleContextMenuAccept,onDismiss:this.closeContextMenu})})})}buildContextMenuBackdrop(){return new o4({left:0,top:0,right:0,bottom:0,child:new O1({onClick:()=>this.closeContextMenu(),child:X0.expand()})})}buildThreadItem(A,Q,$,B){let D=O0.of(B),{app:J,colors:F}=D,Y=!Q,E=Q?J.selectionForeground:F.foreground,Z=Q?J.selectionForeground:F.mutedForeground,X=A.id===this.widget.props.activeThreadID?new d({text:new C("*",new T({color:Q?J.selectionForeground:F.success,dim:Y}))}):void 0,G=X06(A.description.timeAgo);return new Z06(new x0({padding:V0.symmetric(1,0),child:new r0({children:[new X0({width:2,child:X}),new R1({child:new d({text:new C(A.title,new T({color:E,dim:Y})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new X0({width:$,child:r0.end([new d({text:new C(G,new T({color:Z,dim:Y}))})])})]})}),(V)=>{this.threadItemContexts.set(A.id,V)})}handleResizeHandlePress=(A)=>{if(A.button!=="left")return;this.setState(()=>{this.resizeSession={baseWidthColumns:this.widget.props.width,startColumn:Math.floor(A.position.x)}})};handleResizeHandleDrag=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;let Q=Math.floor(A.position.x)-this.resizeSession.startColumn,$=G06(this.resizeSession.baseWidthColumns+Q);if($!==this.widget.props.width)this.widget.props.onResizeWidth($)};handleResizeHandleRelease=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;this.setState(()=>{this.resizeSession=null})};handleResizeHandleEnter=()=>{if(this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!0})};handleResizeHandleExit=()=>{if(!this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!1})};buildResizeHandle(){return new o4({top:0,right:0,bottom:0,width:1,child:new O1({cursor:EA.EW_RESIZE,onClick:this.handleResizeHandlePress,onDrag:this.handleResizeHandleDrag,onRelease:this.handleResizeHandleRelease,onEnter:this.handleResizeHandleEnter,onExit:this.handleResizeHandleExit,child:new X0({width:1})})})}build(A){let Q=O0.of(A),$=this.getThreadsForDisplay(),B=this.hasError?[]:$;this.threadItemContexts.clear();let D=this.isSwitchingThread?"Switching thread...":"Loading threads...",J=this.hasError?"Failed to load threads":"No threads match your filter",F=this.isResizeActive?2:1,Y=new p1(void 0,new c1(Q.colors.border,F),void 0,void 0),E=this.buildContextMenuOverlay(),Z=[new x0({decoration:new R4(Q.colors.background,Y),child:new x4({actions:this.actions,child:new kA({shortcuts:this.shortcuts,debugLabel:"ThreadListSidebarFilter",child:new cA({items:B,getLabel:(U)=>`${U.title} ${U.id}`,controller:this.pickerController,onAccept:(U)=>void this.handleSelectThread(U.id),onDismiss:this.widget.props.onDismiss,renderItem:(U,X,G,V)=>this.buildThreadItem(U,X,this.timeColWidth,V),enabled:!this.isBusy,isLoading:this.isBusy,hidePromptWhenLoading:!0,loadingText:D,emptyStateText:J,maxRenderItems:200,showBorder:!1})})})}),this.buildResizeHandle()];if(E)Z.push(this.buildContextMenuBackdrop()),Z.push(E);return new x0({width:this.widget.props.width,child:new i4({fit:"expand",children:Z})})}}class i51 extends R0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;openThreadPickerOnStart;workspaceSettingsFilePath;neoContext;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.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,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.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.neoContext=A.neoContext}createState(){return new W06}}class W06 extends j0{editorController=new _2;commandPalette=new xr(this);commandRegistry=new IA1;toastController=new k11;relaunchNotificationController=new EA1;exitHintTimer=new yr(this,1000);ideStatus=new V8(this,{});threadNavigationHistory=new GA1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;endCreditsVisible=!1;neoInvadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new ss;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;loadThreads=async()=>{return this.widget.neoContext.listThreads()};analyzeContextForThread=async(A,Q)=>{return Pd4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};threadListSidebar=new l51({state:this,isAvailable:()=>this.widget.neoContext.isInternalUser,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.neoContext.workspaceRoot,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread});sendFeedbackReport=async(A)=>MX0({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);archiveThread=async(A)=>{let Q=await zU0({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await yl4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await xl4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(EB.getInstance().interceptConsole(),this.neoInvadersHighScore=this.widget.neoContext.neoInvadersHighScore??0,this.notices=new a61(this.widget.configService,($)=>this.setState($)),i6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(P.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(q20($.settings)))}),this.updateRelaunchIntegration=new UA1({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.neoContext.sessionAgentMode);this.pluginIntegration=new YA1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new n61({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=W4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?pa4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],B=[ta4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(D,J,F)=>{D.pushWithDismiss((Y)=>S31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Y,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,J,F)=>{A.navigateBack(),F()}},F06({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,J,F)=>{A.navigateForward(),F()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new A31({mcpServers:this.widget.neoContext.mcpServers,onDismiss:F}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(D)=>{D.pushWithDismiss((J)=>new v51({toolboxes:this.widget.neoContext.toolboxes,onDismiss:J}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(D,J,F)=>{try{await n6(J,"https://ampcode.com/chronicle")}finally{F()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{F$(this.widget.neoContext.settingsFilePath).catch((D)=>{P.error("Failed to open settings file in editor",{error:D})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(D,J,F)=>{D.pushWithDismiss((Y)=>new tA1({onCancel:Y,onSelect:(E)=>{this.handleIdeSelection(E),F()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new CA1({commands:M9.of(J).commands,onDismiss:F}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showNeoWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",keywords:["team","contributors","movie","credits","easter egg"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new w6({header:"Amp Version",maxWidth:72,onDismiss:F,child:new d({text:new C(dZ0({version:"0.0.1779409185-ge486da",buildTimestamp:"2026-05-22T00:24:20.009Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:G1.ctrl("c"),status:{type:"enabled"},run:(D,J)=>{x4.maybeInvoke(J,new gy)}},...Q,...Oa4(this.widget.neoContext.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 T51({initialAgentMode:this.widget.neoContext.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.neoWelcomeVisible?null:B,onDismissNotice:(U)=>this.notices.dismiss(U)}),J=h1.of(A),F=J.capabilities.animationSupport!=="disabled",E=[new x0({constraints:C1.tight(J.size.width,J.size.height),child:this.threadListSidebar.buildBody(D)})];if(this.commandPalette.isEnabled())E.push(new k4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new HA1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)E.push(S31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)E.push(new k4({debugLabel:"NeoWelcomeDialogOverlay",child:new b51({onDismiss:this.dismissNeoWelcome,onQuit:()=>W4.instance.stop(),animationsEnabled:F,variant:this.widget.neoWelcomeVariant})}));let Z=this.executorAlreadyConnectedDialog;if(Z)E.push(new k4({debugLabel:"NeoExecutorAlreadyConnectedDialogOverlay",child:new rA1({existingExecutorPid:Z.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(E.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),E.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)E.push(new LA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:jG0.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)E.push(new sA1);if(this.endCreditsVisible)E.push(new cA1({onComplete:this.completeEndCredits,highScore:this.neoInvadersHighScore,onHighScoreChange:this.updateNeoInvadersHighScore}));return new V5({neoContext:this.widget.neoContext,child:new M9({commandRegistry:this.commandRegistry,child:new py({completionBuilder:this.widget.completionBuilder,child:new L3({controller:this.toastController,child:new x4({actions:this.buildActions(),child:new kA({debugLabel:"NeoAppShortcuts",shortcuts:this.buildShortcuts(),child:new v4({debugLabel:"AppShellFocus",child:new S11({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.neoWelcomeVisible?[this.notices]:[]],child:new MA1({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new i4({children:E})})})})})})})})})})}buildShortcuts(){let A=new Map([[G1.ctrl("c"),new FX0],[G1.ctrl("o"),new EX0],[G1.alt("i"),new UX0],[G1.alt("p"),new yN],[G1.ctrl("."),new VX0],[G1.ctrl("t"),new WX0],...this.threadListSidebar.shortcutEntries()]);if(jG0.env.NODE_ENV==="development"&&jG0.platform==="darwin")A.set(G1.meta("r"),new YX0);return A}buildActions(){let A=new T1(()=>{if(RD.hasAnyCopyableSelection())return RD.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new T1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new T1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new T1(()=>{return this.startNewDraftThread(),"handled"}),D=new T1(()=>{return W4.instance.stop(),"handled"}),J=new T1(()=>{return cs({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),F=new T1((G)=>{if(!G.text)return"ignored";return W4.instance.tuiInstance.clipboard.writeText(G.text).then((V)=>{if(V.ok)this.toastController.show(G.successMessage,"success",2000);else this.toastController.show(`${G.failureMessage}: ${V.userFacingErrorMessage}`,"error",4000)}).catch((V)=>{P.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Y=new T1(()=>{return W4.instance.toggleFrameStatsOverlay(),"handled"}),E=new T1(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new T1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),U=Zo4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,neoContext:this.widget.neoContext,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new T1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[FX0,A],[Ss,B],[gy,D],[YX0,J],[W8,F],[bs,$],[EX0,Q],[UX0,Z],...this.threadListSidebar.actionEntries(),[VX0,E],...U,[yN,Y],[WX0,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 By(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){P.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,$=A,B=ZB(Q),D=PZ0(this.widget.neoContext,Q);if(B!==void 0&&D!==void 0)$={...$,[B]:D};return RZ0($,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=z06(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(iF(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=z06(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(Aw);if(this.exitHintTimer.isActive())A.add(fy);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),W4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};updateNeoInvadersHighScore=(A)=>{if(A<=this.neoInvadersHighScore)return;this.setState(()=>{this.neoInvadersHighScore=A}),KQ((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{P.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!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")W4.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)=>{await this.ensureDraftThreadSettingsInitialized();let D=this.activeThreadContext?.client.getThreadId(),J=A.find(Z20);if(J)this.widget.history.add(J.text,jG0.cwd()),this.widget.history.reset();let F=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Y=$??F??null,E=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Y??void 0);this.sendUserMessage(E,A,Q,B),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(D),this.setActiveClient(E)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:$};let B=ZB(A),D=B?Q[B]:void 0;if(D!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:D};KQ((J)=>{let F={...J,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((J)=>{P.warn("Failed to persist Neo session defaults for new message",{error:J instanceof Error?J.message:String(J)})})}sendUserMessage(A,Q,$,B){let D=KF0(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}])};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.neoContext.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(P.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.neoContext.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){P.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}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe(($)=>{this.widget.onActiveThreadChange?.($)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage($,(B)=>{A.sendPluginMessage(B)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...$]}}},(B)=>{A.sendPluginMessage(B)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){P.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.neoWelcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function z06(A,Q,$){let B={...A};for(let D of Jn3(Q,$)){if(!iF(A[D],Q[D]))continue;let J=$[D];if(J===void 0)delete B[D];else B[D]=J}return B}function Jn3(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}a4();function I06(A,Q,$,B){let D=IT(A),J="\x1B[0m",F="\x1B[34m",Y="\x1B[90m",E="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${D}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let U=14,X=7,G=new tJ(U,X),V=new a9(42),K=new TN(U,X,U,X,U,X,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,K0.default(),V);K.layout(C1.tight(U,X)),K.paint(G,0,0);let z=G.getBuffer().getCells(),W=0;for(let j=0;j<X;j++)if(z[j].some((k)=>k.char!==" ")){W=j;break}let I=X-1;for(let j=X-1;j>=0;j--)if(z[j].some((k)=>k.char!==" ")){I=j;break}function H(j,k){if(!j)return"";if(j.type==="rgb"){let{r:_,g:f,b:h}=j.value;if($.getColorDepth()>=24)return`\x1B[${k?38:48};2;${_};${f};${h}m`;let b=gj(_,f,h);return`\x1B[${k?38:48};5;${b}m`}return""}let q=[];if(I>=W)for(let j=W;j<=I;j++){let k="";for(let _=0;_<U;_++){let f=z[j][_],h=f.char,b=H(f.style.fg,!0);k+=b+h+"\x1B[0m"}q.push(k)}let N=q.length,w=Math.max(N,Z.length),O=Math.floor((w-N)/2),L=Math.floor((w-Z.length)/2);for(let j=0;j<w;j++){let k=" ".repeat(U);if(j>=O&&j<O+N)k=q[j-O];let _=" ",f="";if(j>=L&&j<L+Z.length)f=Z[j-L];$.write(k+_+f+`
5324
+ `)),J.push(new C("Details: ",new T({color:B.mutedForeground}))),J.push(new C(A.costBreakdownURL,new T({color:$.app.link})));return new d({text:new C("",void 0,J)})}function An3(A,Q,$){let B=ei3(A,Q);if(!A.costBreakdownURL)return new w6({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:$,child:B});let D=A.costBreakdownURL,J=new T1(()=>{return x4.maybeInvoke(Q,new W8(D,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),F=new T1(()=>{return n6(Q,D),"handled"});return new w6({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:$,child:new x4({actions:new Map([[h51,J],[g51,F]]),child:new kA({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[G1.key("o"),new g51],[G1.key("y"),new h51]]),child:new v4({autofocus:!0,debugLabel:"ThreadCostBody",child:B})})})})}function F06(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,$,B)=>{let D=A.getActiveThreadID();if(!D)return;try{let J=await e4.threadDisplayCostInfo({threadID:D},{config:A.configService});if(!J.ok){A.toastController.show(ti3(D,J.error),"error",5000),B();return}Q.push(An3(J.result,$,B))}catch(J){P.error("Failed to load Neo thread cost",{error:J,threadID:D}),A.toastController.show(`Failed to show thread cost: ${J instanceof Error?J.message:String(J)}`,"error",5000),B()}}}}p0();u9();Q4();class UW extends V4{direction;constructor(A){super();this.direction=A}}class MG0 extends V4{}class Wt extends V4{}class LG0 extends V4{index;constructor(A){super();this.index=A}}function m51(A){return A.length+2}class d51 extends R0{props;constructor(A){super();this.props=A}createState(){return new Y06}}class Y06 extends j0{selectedIndex=0;initState(){super.initState(),this.selectedIndex=this.findSelectableIndex(this.widget.props.initialSelectedIndex??0)}didUpdateWidget(A){this.selectedIndex=this.findSelectableIndex(this.selectedIndex)}isSelectable(A){let Q=this.widget.props.entries[A];return Q?.type==="item"&&(Q.enabled??!0)}findSelectableIndex(A){let{entries:Q}=this.widget.props;if(Q.length===0)return 0;let $=Math.max(0,Math.min(A,Q.length-1));if(this.isSelectable($))return $;for(let B=1;B<Q.length;B++){let D=$+B;if(D<Q.length&&this.isSelectable(D))return D;let J=$-B;if(J>=0&&this.isSelectable(J))return J}return 0}moveSelection(A){let Q=this.findNextSelectableIndex(A);if(Q===this.selectedIndex)return;this.setState(()=>{this.selectedIndex=Q})}findNextSelectableIndex(A){let{entries:Q}=this.widget.props;for(let $=this.selectedIndex+A;$>=0&&$<Q.length;$+=A)if(this.isSelectable($))return $;return this.selectedIndex}acceptIndex(A){let Q=this.widget.props.entries[A];if(Q?.type!=="item"||!(Q.enabled??!0))return;this.setState(()=>{this.selectedIndex=A}),this.widget.props.onAccept(Q.value)}invoke=(A)=>{if(A instanceof UW)return this.moveSelection(A.direction),"handled";if(A instanceof MG0)return this.acceptIndex(this.selectedIndex),"handled";if(A instanceof Wt)return this.widget.props.onDismiss(),"handled";if(A instanceof LG0)return this.acceptIndex(A.index),"handled";return"ignored"};buildShortcuts(){let A=new Map([[G1.key("ArrowDown"),new UW(1)],[G1.key("j"),new UW(1)],[G1.ctrl("n"),new UW(1)],[G1.key("ArrowUp"),new UW(-1)],[G1.key("k"),new UW(-1)],[G1.ctrl("p"),new UW(-1)],[G1.key("Enter"),new MG0],[G1.key("Escape"),new Wt],[G1.ctrl("."),new Wt]]);return this.widget.props.entries.forEach((Q,$)=>{if(Q.type==="item"&&Q.shortcut)A.set(Q.shortcut,new LG0($))}),A}buildActions(){return new Map([[UW,new T1(this.invoke)],[MG0,new T1(this.invoke)],[Wt,new T1(this.invoke)],[LG0,new T1(this.invoke)]])}build(A){let Q=O0.of(A),$=Qn3(this.widget.props.entries,h1.of(A).supportsEmojiWidth);return new x0({width:this.widget.props.width,height:m51(this.widget.props.entries),decoration:new R4(Q.colors.background,p1.all(new c1(Q.colors.border,1,"solid"))),child:new x4({actions:this.buildActions(),child:new kA({debugLabel:"NeoContextPickerShortcuts",shortcuts:this.buildShortcuts(),child:new v4({autofocus:!0,debugLabel:"NeoContextPicker",child:new S0({mainAxisSize:"min",crossAxisAlignment:"stretch",children:this.widget.props.entries.map((B,D)=>this.buildEntry(B,D,$,Q))})})})})})}buildEntry(A,Q,$,B){if(A.type==="separator")return new x0({height:1,decoration:{border:new p1(new c1(B.colors.border,1,"solid"))}});let D=Q===this.selectedIndex,J=A.enabled??!0,F=new T({color:D?B.app.selectionForeground:B.colors.foreground,dim:!J}),Y=new T({color:D?B.app.selectionForeground:B.app.keybind,bold:!0,dim:!J});return new O1({onClick:()=>this.acceptIndex(Q),child:new x0({padding:V0.symmetric(1,0),decoration:D?new R4(B.app.selectionBackground):void 0,child:new r0({crossAxisAlignment:"start",children:[new R1({child:new d({text:new C(A.label,F),maxLines:1,overflow:"ellipsis"})}),new X0({width:1}),new X0({width:$,child:new d({text:new C(E06(A),Y),textAlign:"right",maxLines:1,overflow:"ellipsis"})})]})})})}}function Qn3(A,Q){return A.reduce(($,B)=>{return B.type==="item"?Math.max($,J4(E06(B),Q)):$},0)}function E06(A){return A.shortcutLabel??A.shortcut?.toString().toLowerCase()??""}var $n3=36,Bn3=24,Dn3=72;class Z06 extends R0{child;onContext;constructor(A,Q){super();this.child=A;this.onContext=Q}createState(){return new U06}}class U06 extends j0{build(A){return this.widget.onContext(A),this.widget.child}}function X06(A){return A.replace(/ ago$/,"")}function OG0(A){return A.reduce((Q,$)=>Math.max(Q,J4(X06($.description.timeAgo))),0)}function G06(A){return Math.max(Bn3,Math.min(A,Dn3))}class p51 extends V4{}class c51 extends V4{}class l51{options;visibility;width=$n3;constructor(A){this.options=A;this.visibility=new xr(A.state)}isVisible(){return this.visibility.isEnabled()}buildBody(A){return new r0({crossAxisAlignment:"stretch",children:[this.buildSlot(),new R1({child:A})]})}buildSlot(){if(!this.options.isAvailable()||this.visibility.isDisabled())return new X0({width:0});return new X0({width:this.width,child:new k4({debugLabel:"ThreadListSidebar",child:new V06({activeThreadID:this.options.getActiveThreadID(),currentWorkspaceURI:t1(i0.file(this.options.getWorkspaceRoot())),width:this.width,loadThreads:this.options.loadThreads,onSelectThread:this.options.onSelectThread,onDismiss:this.close,onResizeWidth:this.resize})})})}commands(){if(!this.options.isAvailable())return[];return[{noun:"thread",verb:"toggle sidebar",description:"Show or hide the thread sidebar",keywords:["sidebar","recent","history","threads"],shortcut:G1.alt("s"),status:{type:"enabled"},run:(A,Q,$)=>{$(),this.toggle()}}]}shortcutEntries(){return this.options.isAvailable()?[[G1.alt("s"),new XX0]]:[]}actionEntries(){if(!this.options.isAvailable())return[];return[[XX0,new T1(()=>this.toggle())]]}toggle=()=>{if(!this.options.isAvailable())return"ignored";if(this.visibility.isDisabled()&&this.options.isBlocked())return"ignored";return this.visibility.toggle(),"handled"};close=()=>{this.visibility.disable()};resize=(A)=>{let Q=G06(A);if(Q===this.width)return;this.options.state.setState(()=>{this.width=Q})}}class V06 extends R0{props;constructor(A){super();this.props=A}createState(){return new K06}}class K06 extends j0{threads=[];isLoading=!0;isSwitchingThread=!1;hasError=!1;filterByWorkspace=!0;timeColWidth=0;contextMenu=null;pendingThreadMutations=new Map;resizeSession=null;isResizeHandleHovered=!1;pickerController=new Qs;threadItemContexts=new Map;shortcuts=new Map([[G1.alt("w"),new p51],[G1.ctrl("."),new c51]]);actions=new Map([[p51,new T1(()=>{return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.contextMenu=null}),"handled"})],[c51,new T1(()=>this.openContextMenu())]]);get isBusy(){return this.isLoading||this.isSwitchingThread}get isResizeActive(){return this.resizeSession!==null||this.isResizeHandleHovered}didUpdateWidget(A){if(this.contextMenu&&(A.props.width!==this.widget.props.width||A.props.currentWorkspaceURI!==this.widget.props.currentWorkspaceURI))this.contextMenu=null}initState(){super.initState(),this.loadThreadSummaries()}async loadThreadSummaries(){try{let A=await this.widget.props.loadThreads(),Q=k31(A);if(!this.mounted)return;this.setState(()=>{this.pickerController.selectedItem=Q.find(($)=>$.id===this.widget.props.activeThreadID)??null,this.threads=Q,this.timeColWidth=OG0(Q),this.isLoading=!1,this.hasError=!1})}catch(A){if(P.error("Failed to load threads for Neo sidebar",{error:A}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}handleSelectThread=async(A)=>{if(this.isSwitchingThread)return;this.setState(()=>{this.isSwitchingThread=!0});try{await this.widget.props.onSelectThread(A),this.widget.props.onDismiss()}catch(Q){P.error("Failed to switch thread from Neo sidebar",{error:Q,threadID:A})}finally{if(this.mounted)this.setState(()=>{this.isSwitchingThread=!1})}};getOptimisticThreads(){return this.threads.flatMap((A)=>{if(this.pendingThreadMutations.get(A.id)?.kind==="archive")return[];return[A]})}getThreadsForDisplay(){let A=this.getOptimisticThreads();return this.filterByWorkspace?A.filter((Q)=>!Q.workspaceURI||Q.workspaceURI===this.widget.props.currentWorkspaceURI):A}buildContextMenuEntries(){return[{type:"item",value:"archive",label:"Archive Thread",shortcut:G1.key("a"),shortcutLabel:"a"},{type:"separator"},{type:"item",value:"copy-id",label:"Copy ID",shortcut:G1.ctrl("c"),shortcutLabel:"ctrl+c"},{type:"item",value:"copy-url",label:"Copy URL",shortcut:new G1("c",{shift:!0,ctrl:!0}),shortcutLabel:"shift+ctrl+c"}]}openContextMenu(){let A=this.pickerController.selectedItem;if(!A||this.isBusy||this.hasError)return"ignored";let Q=this.buildContextMenuEntries(),$=m51(Q),B=this.getContextMenuWidth(),D=this.getContextMenuPosition(A.id,$,B);return this.setState(()=>{this.contextMenu={threadID:A.id,left:D.left,top:D.top,width:B,height:$}}),"handled"}getContextMenuWidth(){let A=Math.max(24,this.widget.props.width-3);return Math.max(1,Math.min(A,this.widget.props.width-2))}getContextMenuPosition(A,Q,$){let B=Math.max(0,Math.min(2,this.widget.props.width-$)),D=1,J=this.threadItemContexts.get(A)?.findRenderObject(),F=this.context.findRenderObject();if(!(J instanceof b1)||!(F instanceof b1))return{left:B,top:1};let Y=J.localToGlobal({x:0,y:0}),E=F.localToGlobal({x:0,y:0}),Z=Y.y-E.y,U=Z+J.size.height,X=h1.sizeOf(this.context).height,G=Math.max(1,Math.min(F.size.height,X-E.y)),z=G-U>=Q||Z<G/2?U:Z-Q,W=Math.max(0,G-Q);return{left:B,top:Math.max(0,Math.min(z,W))}}closeContextMenu=()=>{if(!this.contextMenu)return;this.setState(()=>{this.contextMenu=null})};handleContextMenuAccept=(A)=>{let Q=this.contextMenu?.threadID;if(!Q)return;if(this.closeContextMenu(),A==="archive"){this.archiveContextMenuThread(Q);return}if(A==="copy-id"){x4.maybeInvoke(this.context,new W8(Q,"Thread ID copied to clipboard","Failed to copy thread ID"));return}x4.maybeInvoke(this.context,new W8(this.getThreadURL(Q),"Thread URL copied to clipboard","Failed to copy thread URL"))};beginOptimisticArchive(A){if(this.pendingThreadMutations.has(A))return!1;if(!this.threads.some(($)=>$.id===A))return!1;let Q={kind:"archive",fallbackSelectedThreadID:null};return this.setState(()=>{this.pendingThreadMutations.set(A,Q),this.timeColWidth=OG0(this.getOptimisticThreads())}),i6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;let $=this.pendingThreadMutations.get(A);if($?.kind!=="archive")return;$.fallbackSelectedThreadID=this.pickerController.selectedItem?.id??null}),!0}commitOptimisticArchive(A){if(this.pendingThreadMutations.get(A)?.kind!=="archive")return;this.pendingThreadMutations.delete(A),this.threads=this.threads.filter(($)=>$.id!==A),this.timeColWidth=OG0(this.getOptimisticThreads())}rollbackOptimisticArchive(A){let Q=this.pendingThreadMutations.get(A);if(Q?.kind!=="archive")return;let $=this.threads.find((B)=>B.id===A);if(!$){this.pendingThreadMutations.delete(A);return}this.setState(()=>{this.pendingThreadMutations.delete(A),this.timeColWidth=OG0(this.getOptimisticThreads());let B=this.pickerController.selectedItem?.id??null;if(B===null||B===Q.fallbackSelectedThreadID)this.pickerController.selectedItem=$})}async archiveContextMenuThread(A){let Q=L3.maybeOf(this.context),{configService:$}=V5.of(this.context);if(!this.beginOptimisticArchive(A))return;try{let B=await zU0({configService:$},A);if(!this.mounted)return;if(B){this.rollbackOptimisticArchive(A),Q?.show(B.message,"error");return}this.commitOptimisticArchive(A)}catch(B){if(P.error("Failed to archive thread from Neo sidebar context menu",{error:B,threadID:A}),!this.mounted)return;this.rollbackOptimisticArchive(A),Q?.show("Failed to archive thread","error")}}getThreadURL(A){return x$(new URL(V5.of(this.context).ampURL),A).toString()}buildContextMenuOverlay(){let A=this.contextMenu;if(!A||!this.getThreadsForDisplay().some((Q)=>Q.id===A.threadID))return null;return new o4({left:A.left,top:A.top,width:A.width,height:A.height,child:new k4({debugLabel:"ThreadListSidebarContextMenu",onFocusChange:(Q)=>{if(!Q)this.closeContextMenu()},child:new d51({entries:this.buildContextMenuEntries(),width:A.width,onAccept:this.handleContextMenuAccept,onDismiss:this.closeContextMenu})})})}buildContextMenuBackdrop(){return new o4({left:0,top:0,right:0,bottom:0,child:new O1({onClick:()=>this.closeContextMenu(),child:X0.expand()})})}buildThreadItem(A,Q,$,B){let D=O0.of(B),{app:J,colors:F}=D,Y=!Q,E=Q?J.selectionForeground:F.foreground,Z=Q?J.selectionForeground:F.mutedForeground,X=A.id===this.widget.props.activeThreadID?new d({text:new C("*",new T({color:Q?J.selectionForeground:F.success,dim:Y}))}):void 0,G=X06(A.description.timeAgo);return new Z06(new x0({padding:V0.symmetric(1,0),child:new r0({children:[new X0({width:2,child:X}),new R1({child:new d({text:new C(A.title,new T({color:E,dim:Y})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new X0({width:$,child:r0.end([new d({text:new C(G,new T({color:Z,dim:Y}))})])})]})}),(V)=>{this.threadItemContexts.set(A.id,V)})}handleResizeHandlePress=(A)=>{if(A.button!=="left")return;this.setState(()=>{this.resizeSession={baseWidthColumns:this.widget.props.width,startColumn:Math.floor(A.position.x)}})};handleResizeHandleDrag=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;let Q=Math.floor(A.position.x)-this.resizeSession.startColumn,$=G06(this.resizeSession.baseWidthColumns+Q);if($!==this.widget.props.width)this.widget.props.onResizeWidth($)};handleResizeHandleRelease=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;this.setState(()=>{this.resizeSession=null})};handleResizeHandleEnter=()=>{if(this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!0})};handleResizeHandleExit=()=>{if(!this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!1})};buildResizeHandle(){return new o4({top:0,right:0,bottom:0,width:1,child:new O1({cursor:EA.EW_RESIZE,onClick:this.handleResizeHandlePress,onDrag:this.handleResizeHandleDrag,onRelease:this.handleResizeHandleRelease,onEnter:this.handleResizeHandleEnter,onExit:this.handleResizeHandleExit,child:new X0({width:1})})})}build(A){let Q=O0.of(A),$=this.getThreadsForDisplay(),B=this.hasError?[]:$;this.threadItemContexts.clear();let D=this.isSwitchingThread?"Switching thread...":"Loading threads...",J=this.hasError?"Failed to load threads":"No threads match your filter",F=this.isResizeActive?2:1,Y=new p1(void 0,new c1(Q.colors.border,F),void 0,void 0),E=this.buildContextMenuOverlay(),Z=[new x0({decoration:new R4(Q.colors.background,Y),child:new x4({actions:this.actions,child:new kA({shortcuts:this.shortcuts,debugLabel:"ThreadListSidebarFilter",child:new cA({items:B,getLabel:(U)=>`${U.title} ${U.id}`,controller:this.pickerController,onAccept:(U)=>void this.handleSelectThread(U.id),onDismiss:this.widget.props.onDismiss,renderItem:(U,X,G,V)=>this.buildThreadItem(U,X,this.timeColWidth,V),enabled:!this.isBusy,isLoading:this.isBusy,hidePromptWhenLoading:!0,loadingText:D,emptyStateText:J,maxRenderItems:200,showBorder:!1})})})}),this.buildResizeHandle()];if(E)Z.push(this.buildContextMenuBackdrop()),Z.push(E);return new x0({width:this.widget.props.width,child:new i4({fit:"expand",children:Z})})}}class i51 extends R0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;openThreadPickerOnStart;workspaceSettingsFilePath;neoContext;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.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,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.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.neoContext=A.neoContext}createState(){return new W06}}class W06 extends j0{editorController=new _2;commandPalette=new xr(this);commandRegistry=new IA1;toastController=new k11;relaunchNotificationController=new EA1;exitHintTimer=new yr(this,1000);ideStatus=new V8(this,{});threadNavigationHistory=new GA1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;endCreditsVisible=!1;neoInvadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new ss;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;loadThreads=async()=>{return this.widget.neoContext.listThreads()};analyzeContextForThread=async(A,Q)=>{return Pd4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};threadListSidebar=new l51({state:this,isAvailable:()=>this.widget.neoContext.isInternalUser,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.neoContext.workspaceRoot,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread});sendFeedbackReport=async(A)=>MX0({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);archiveThread=async(A)=>{let Q=await zU0({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await yl4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await xl4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(EB.getInstance().interceptConsole(),this.neoInvadersHighScore=this.widget.neoContext.neoInvadersHighScore??0,this.notices=new a61(this.widget.configService,($)=>this.setState($)),i6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(P.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(q20($.settings)))}),this.updateRelaunchIntegration=new UA1({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.neoContext.sessionAgentMode);this.pluginIntegration=new YA1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new n61({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=W4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?pa4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],B=[ta4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(D,J,F)=>{D.pushWithDismiss((Y)=>S31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Y,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,J,F)=>{A.navigateBack(),F()}},F06({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,J,F)=>{A.navigateForward(),F()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new A31({mcpServers:this.widget.neoContext.mcpServers,onDismiss:F}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(D)=>{D.pushWithDismiss((J)=>new v51({toolboxes:this.widget.neoContext.toolboxes,onDismiss:J}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(D,J,F)=>{try{await n6(J,"https://ampcode.com/chronicle")}finally{F()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{F$(this.widget.neoContext.settingsFilePath).catch((D)=>{P.error("Failed to open settings file in editor",{error:D})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(D,J,F)=>{D.pushWithDismiss((Y)=>new tA1({onCancel:Y,onSelect:(E)=>{this.handleIdeSelection(E),F()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new CA1({commands:M9.of(J).commands,onDismiss:F}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showNeoWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",keywords:["team","contributors","movie","credits","easter egg"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new w6({header:"Amp Version",maxWidth:72,onDismiss:F,child:new d({text:new C(dZ0({version:"0.0.1779426990-g24af9a",buildTimestamp:"2026-05-22T05:21:19.350Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:G1.ctrl("c"),status:{type:"enabled"},run:(D,J)=>{x4.maybeInvoke(J,new gy)}},...Q,...Oa4(this.widget.neoContext.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 T51({initialAgentMode:this.widget.neoContext.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.neoWelcomeVisible?null:B,onDismissNotice:(U)=>this.notices.dismiss(U)}),J=h1.of(A),F=J.capabilities.animationSupport!=="disabled",E=[new x0({constraints:C1.tight(J.size.width,J.size.height),child:this.threadListSidebar.buildBody(D)})];if(this.commandPalette.isEnabled())E.push(new k4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new HA1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)E.push(S31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)E.push(new k4({debugLabel:"NeoWelcomeDialogOverlay",child:new b51({onDismiss:this.dismissNeoWelcome,onQuit:()=>W4.instance.stop(),animationsEnabled:F,variant:this.widget.neoWelcomeVariant})}));let Z=this.executorAlreadyConnectedDialog;if(Z)E.push(new k4({debugLabel:"NeoExecutorAlreadyConnectedDialogOverlay",child:new rA1({existingExecutorPid:Z.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(E.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),E.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)E.push(new LA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:jG0.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)E.push(new sA1);if(this.endCreditsVisible)E.push(new cA1({onComplete:this.completeEndCredits,highScore:this.neoInvadersHighScore,onHighScoreChange:this.updateNeoInvadersHighScore}));return new V5({neoContext:this.widget.neoContext,child:new M9({commandRegistry:this.commandRegistry,child:new py({completionBuilder:this.widget.completionBuilder,child:new L3({controller:this.toastController,child:new x4({actions:this.buildActions(),child:new kA({debugLabel:"NeoAppShortcuts",shortcuts:this.buildShortcuts(),child:new v4({debugLabel:"AppShellFocus",child:new S11({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.neoWelcomeVisible?[this.notices]:[]],child:new MA1({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new i4({children:E})})})})})})})})})})}buildShortcuts(){let A=new Map([[G1.ctrl("c"),new FX0],[G1.ctrl("o"),new EX0],[G1.alt("i"),new UX0],[G1.alt("p"),new yN],[G1.ctrl("."),new VX0],[G1.ctrl("t"),new WX0],...this.threadListSidebar.shortcutEntries()]);if(jG0.env.NODE_ENV==="development"&&jG0.platform==="darwin")A.set(G1.meta("r"),new YX0);return A}buildActions(){let A=new T1(()=>{if(RD.hasAnyCopyableSelection())return RD.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new T1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new T1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new T1(()=>{return this.startNewDraftThread(),"handled"}),D=new T1(()=>{return W4.instance.stop(),"handled"}),J=new T1(()=>{return cs({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),F=new T1((G)=>{if(!G.text)return"ignored";return W4.instance.tuiInstance.clipboard.writeText(G.text).then((V)=>{if(V.ok)this.toastController.show(G.successMessage,"success",2000);else this.toastController.show(`${G.failureMessage}: ${V.userFacingErrorMessage}`,"error",4000)}).catch((V)=>{P.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Y=new T1(()=>{return W4.instance.toggleFrameStatsOverlay(),"handled"}),E=new T1(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new T1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),U=Zo4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,neoContext:this.widget.neoContext,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new T1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[FX0,A],[Ss,B],[gy,D],[YX0,J],[W8,F],[bs,$],[EX0,Q],[UX0,Z],...this.threadListSidebar.actionEntries(),[VX0,E],...U,[yN,Y],[WX0,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 By(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){P.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,$=A,B=ZB(Q),D=PZ0(this.widget.neoContext,Q);if(B!==void 0&&D!==void 0)$={...$,[B]:D};return RZ0($,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=z06(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(iF(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=z06(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(Aw);if(this.exitHintTimer.isActive())A.add(fy);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),W4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};updateNeoInvadersHighScore=(A)=>{if(A<=this.neoInvadersHighScore)return;this.setState(()=>{this.neoInvadersHighScore=A}),KQ((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{P.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!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")W4.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)=>{await this.ensureDraftThreadSettingsInitialized();let D=this.activeThreadContext?.client.getThreadId(),J=A.find(Z20);if(J)this.widget.history.add(J.text,jG0.cwd()),this.widget.history.reset();let F=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Y=$??F??null,E=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Y??void 0);this.sendUserMessage(E,A,Q,B),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(D),this.setActiveClient(E)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:$};let B=ZB(A),D=B?Q[B]:void 0;if(D!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:D};KQ((J)=>{let F={...J,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((J)=>{P.warn("Failed to persist Neo session defaults for new message",{error:J instanceof Error?J.message:String(J)})})}sendUserMessage(A,Q,$,B){let D=KF0(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}])};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.neoContext.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(P.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.neoContext.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){P.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}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe(($)=>{this.widget.onActiveThreadChange?.($)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage($,(B)=>{A.sendPluginMessage(B)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...$]}}},(B)=>{A.sendPluginMessage(B)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){P.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.neoWelcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function z06(A,Q,$){let B={...A};for(let D of Jn3(Q,$)){if(!iF(A[D],Q[D]))continue;let J=$[D];if(J===void 0)delete B[D];else B[D]=J}return B}function Jn3(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}a4();function I06(A,Q,$,B){let D=IT(A),J="\x1B[0m",F="\x1B[34m",Y="\x1B[90m",E="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${D}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let U=14,X=7,G=new tJ(U,X),V=new a9(42),K=new TN(U,X,U,X,U,X,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,K0.default(),V);K.layout(C1.tight(U,X)),K.paint(G,0,0);let z=G.getBuffer().getCells(),W=0;for(let j=0;j<X;j++)if(z[j].some((k)=>k.char!==" ")){W=j;break}let I=X-1;for(let j=X-1;j>=0;j--)if(z[j].some((k)=>k.char!==" ")){I=j;break}function H(j,k){if(!j)return"";if(j.type==="rgb"){let{r:_,g:f,b:h}=j.value;if($.getColorDepth()>=24)return`\x1B[${k?38:48};2;${_};${f};${h}m`;let b=gj(_,f,h);return`\x1B[${k?38:48};5;${b}m`}return""}let q=[];if(I>=W)for(let j=W;j<=I;j++){let k="";for(let _=0;_<U;_++){let f=z[j][_],h=f.char,b=H(f.style.fg,!0);k+=b+h+"\x1B[0m"}q.push(k)}let N=q.length,w=Math.max(N,Z.length),O=Math.floor((w-N)/2),L=Math.floor((w-Z.length)/2);for(let j=0;j<w;j++){let k=" ".repeat(U);if(j>=O&&j<O+N)k=q[j-O];let _=" ",f="";if(j>=L&&j<L+Z.length)f=Z[j-L];$.write(k+_+f+`
5326
5325
  `)}if(B)$.write(`
5327
5326
  \x1B[90m${B}\x1B[0m
5328
5327
  `)}p0();p0();import{exec as vR}from"node:child_process";function RG0(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")vR("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")vR("powershell [console]::beep(800,200)");else if(process.platform==="linux")vR("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="idle-review"){if(process.platform==="darwin")vR("afplay /System/Library/Sounds/Glass.aiff")}else if(A==="requires-user-input"){if(process.platform==="darwin")vR("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")vR("powershell [console]::beep(1000,300)");else if(process.platform==="linux")vR("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){P.error(`Failed to play notification sound (${A}):`,Q)}}bZ0();var Fn3=2000,Yn3="Agent is ready",En3="Waiting for approval";function H06(A){let Q=!0,$=!0,B=A.configService.config.subscribe((I)=>{Q=I.settings["notifications.enabled"]??!0,$=I.settings["notifications.system.enabled"]!==!1}),D=0,J=()=>{let I=V?.prepareTerminalTitleForNotification();if(I!==void 0)process.stdout.write(BZ0(I))},F=(I)=>{if(!Q)return;let H=Date.now();if(H-D<Fn3)return;if(D=H,aj())return;if(yE0())J(),setTimeout(xE0,Ur);else RG0(I)},Y=()=>{F("idle"),K(Yn3)},E=()=>{F("requires-user-input"),K(En3)},Z=(I)=>I?.attempt===void 0||I.attempt===0,U=null,X=null,G=null,V,K=(I)=>{if(!Q||!$)return;if(aj()&&!ur()&&!af())return;J(),setTimeout(()=>{process.stdout.write(Xr(I))},Ur)},z=()=>{U?.unsubscribe(),X?.unsubscribe(),U=null,X=null,G=null,V=void 0};return{attach:(I,H,q)=>{if(z(),V=q,H)X=H.subscribe({next:(N)=>{if(N===null)return;if(!Z(N))return;Y()},error:(N)=>{P.debug("Neo notification active error stream errored",{error:N})}});U=I.subscribe({next:(N)=>{try{let w=G!==null&&tQ(G),O=G==="awaiting_approval",L=w||O;if(N==="awaiting_approval"&&!O)E();else if(N==="idle"&&L)Y()}catch(w){P.debug("Neo notification handling failed",{error:w})}finally{G=N}},error:(N)=>{P.debug("Neo notification agent state stream errored",{error:N})}})},detach:z,unsubscribe(){z(),B.unsubscribe()}}}function Zn3({initialUserInput:A,showNeoWelcome:Q,hideNeoWelcome:$,neoWelcomeVariant:B,neoWelcomeDismissed:D}){if($)return{show:!1,markDismissedOnDismiss:!1};if(B==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let J=!A&&!D;return{show:J,markDismissedOnDismiss:J}}async function Un3(A){await KQ((Q)=>Fy(Q,A,"interactive"))}async function q06(A,Q={}){let{initialThreadIDs:$=[],initialUserInput:B,getDefaultNewThreadVisibility:D,openThreadPickerOnStart:J=!1,observerOnly:F=!1,initialAgentMode:Y,initialReasoningEffort:E,onFirstFrame:Z,showNeoWelcome:U=!1,hideNeoWelcome:X=!1,neoWelcomeVariant:G="intro"}=Q,V=G==="npm-migration";if($.length>1)P.info("Resuming multiple initial threads",{threadIDs:$});let K=async(_)=>{let f=await A.getThreadFromServer(_);if(!f)return null;return LE0(f)},z=async(_)=>{let f=await A.getThreadFromServer(_);if(!f)throw Error(`Thread ${_} not found`);let h=await l9(_,A.configService,A.apiKey,{usesThreadActors:!0}),b=TG({endpoint:A.rivetEndpoint,poolName:h.poolName}),v={wsToken:h.wsToken,transport:"amp-rpc"},c=await b.threadActor.getOrCreate([_],{params:v,createWithInput:{threadId:h.threadId,threadVersion:h.threadVersion,ownerUserId:h.ownerUserId,...h.agentMode?{agentMode:h.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:ny4(f)}),skipReadyWait:!0});if(!c.ok&&c.status!==409)throw Error(`Thread import failed (${c.status}): ${await c.text()}`);try{await Cx4(_,A.configService,A.apiKey,{executorType:"local-client"})}catch(p){P.warn("failed to mark thread as imported on server",{threadID:_,error:p instanceof Error?p.message:String(p)})}},W=new J11(A.rivetEndpoint,A.apiKey,A.configService,{clientID:UN.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(_)=>A.pluginService.event.toolCall(_),requestPluginToolResult:(_)=>A.pluginService.event.toolResult(_),pluginService:A.pluginService,pluginPlatform:A.pluginPlatform,invokeTool:async(_,f)=>{let h=typeof f.args==="object"&&f.args!==null?f.args:{},b=await CN({toolName:f.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:f.toolCallId,threadId:_});return A.toolService.invokeTool(f.toolName,{args:h},b)},persistLastThreadID:Un3,readFileSystemDirectory:A.readFileSystemDirectory},K,z),I=await oz(),H=Zn3({initialUserInput:B,showNeoWelcome:U,hideNeoWelcome:X,neoWelcomeVariant:G,neoWelcomeDismissed:I.neoWelcomeDismissed}),q={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(_)=>{let f=await A.getThreadFromServer(_);return f?bX(f):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:Ao,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:V?!1:F,neoInvadersHighScore:I.neoInvadersHighScore,sessionAgentMode:Y??I.agentMode,explicitReasoningEffort:E,lastReasoningEffortByMode:I.lastReasoningEffortByMode,lastSpeedByMode:I.lastSpeedByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},N=(_,f)=>{return fm4({ampURL:A.ampURL,configService:A.configService,threadID:_,signal:f})},w=new R11,O=H06({configService:A.configService}),L=await A.configService.getLatest();W4.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:L.settings["terminal.animation"]===!1}});let j=new Set,k=new ZA1;try{await _r(new i51({clientPool:W,listSkillsForThread:N,completionBuilder:A.completionBuilder,history:new mo,ideManager:w,configService:A.configService,updateService:A.updateService,initialThreadIDs:V?[]:$,notificationService:O,mcpTrustHandler:A.mcpTrustHandler,initialUserInput:V?void 0:B,getDefaultNewThreadVisibility:D,openThreadPickerOnStart:V?!1:J,workspaceSettingsFilePath:A.workspaceSettingsFilePath,neoContext:q,showNeoWelcome:H.show,neoWelcomeVariant:G,onActiveThreadChange:A.setActiveThreadID,onRelaunchRequested:k.request,onNeoWelcomeDismissed:H.markDismissedOnDismiss?()=>{KQ(bm4).catch((f)=>{P.warn("Failed to mark Neo welcome as dismissed",{error:f})})}:void 0,onThreadArchived:(f)=>{j.add(f)},onFirstFrame:Z}));let _=W.lastActiveObservingClient;if(_&&k.shouldShowExitSummary){let{client:f,observer:h}=_,b=f.getThreadId();if(b){let v={id:b,title:h.title().getValue(),agentMode:h.agentMode,archived:j.has(b)},y=`${A.ampURL.replace(/\/$/,"")}/threads/${b}`;I06(v,y,process.stdout)}}}finally{process.stdout.write(RN("")),O.unsubscribe(),W.dispose(),await A.dispose?.()}process.exit(k.relaunchIfRequested(A.workspaceRoot)??0)}Z5();function Zx(A){let Q=[],$={meta:{visibility:"private",sharedGroupIDs:[]}};if(A.workspace?.disablePrivateThreads)$.disabledReason="Disabled by workspace policy";if(Q.push($),A.workspace?.groups&&A.workspace.groups.length>0){let F={meta:{visibility:"private",shareWithAllCreatorGroups:!0}};if(A.creatorIsViewer===!1)F.disabledReason="Can only be set by thread creator";Q.push(F)}if(A.workspace)Q.push({meta:{visibility:"thread_workspace_shared"}});let B=A.workspace?.disablePublicSharing?"Disabled by workspace policy":void 0,D={meta:{visibility:"public_unlisted"}},J={meta:{visibility:"public_discoverable"}};if(B)D.disabledReason=B,J.disabledReason=B;return Q.push(D,J),Q}function N06(A){if(A.visibility==="thread_group_shared")return"sharedGroupIDs"in A&&A.sharedGroupIDs.length>0;if(A.visibility!=="private")return!0;if("shareWithAllCreatorGroups"in A&&A.shareWithAllCreatorGroups)return!0;return"sharedGroupIDs"in A&&A.sharedGroupIDs.length>0}function kR(A,Q={}){switch(A.visibility){case"thread_workspace_shared":return{text:"Workspace",description:"Visible to all members of the workspace"};case"public_discoverable":return{text:"Public",description:"Visible on public profile & publicly searchable"};case"public_unlisted":return{text:"Unlisted",description:"Visible to anyone on the Internet who has the link"};case"thread_group_shared":case"private":{let $=A.visibility==="private"&&"shareWithAllCreatorGroups"in A&&A.shareWithAllCreatorGroups,B=$?Q.workspace?.groups.map((J)=>J.id)??[]:("sharedGroupIDs"in A)?A.sharedGroupIDs:[],D=B.reduce((J,F)=>{let Y=Q.workspace?.groups.find((E)=>E.id===F)?.name;if(Y)J.push(`'${Y}'`);return J},[]);if(D.length>0)return{text:"Group",description:`Shared with ${X4(D.length,"group")} ${D.join(", ")} and workspace admins`};if($)return{text:"Group",description:"Shared with creator groups and workspace admins"};if(B.length>0)return{text:"Group",description:`Shared with ${X4(B.length,"group")} and workspace admins`};return{text:"Private",description:Q.workspace?"Only visible to you and workspace admins":"Only you can see this thread"}}}}function PG0(A){if(A.visibility==="private")return"shareWithAllCreatorGroups"in A?"group":"private";if(A.visibility==="thread_workspace_shared")return"workspace";if(A.visibility==="public_unlisted")return"unlisted";return"public"}function Ux(A,Q=null){let $=A!==null&&typeof A==="object"&&"visibility"in A?A.visibility:void 0;if(!$||typeof $!=="string")return;let D=Zx({workspace:Q?.team??void 0}).filter((J)=>!J.disabledReason).map((J)=>PG0(J.meta));if(D.includes($))return Xn3($);if($==="group"&&!D.includes("group")){if(Q?.team?.groups!==void 0)return Error(`Group visibility is not available. You are not a member of any group in this workspace.
@@ -7084,7 +7083,7 @@ ${D}`,Q);this.line=$,this.column=B,this.codeblock=D}}/*!
7084
7083
  `),J=[];for(let F=0;F<D.length;F++){let Z=D[F].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let U of Z)if(U.startsWith("\x00")&&U.endsWith("\x01"))J.push(new C(U.slice(1,-1),new T({color:B.app.keybind,bold:!0})));else J.push(new C(U,new T({color:$.colorScheme.foreground})));if(F<D.length-1)J.push(new C(`
7085
7084
  `))}return new x0({decoration:{color:$.colorScheme.background,border:p1.all(new c1(B.app.keybind,1,"rounded"))},child:new f0({padding:V0.symmetric(0,1),child:new d({text:new C(void 0,void 0,J)})})})}}class $81 extends R5{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:$=null,showAxes:B=!0,colors:D=cV0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=$,this.showAxes=B,this.colors=D}createRenderObject(){return new A81({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(A){let Q=A;Q.chartData=this.chartData,Q.highlightIndex=this.highlightIndex,Q.showAxes=this.showAxes,Q.colors=this.colors,Q.markNeedsLayout()}}function AA6(A,Q,$,B,D,J,F){if(J<=0)return null;switch(A){case"horizontal-bar":{let Y=$;return Y>=0&&Y<J?Y:null}case"bar":case"stacked-bar":{let Y=F?i2:0,E=B-Y;if(E<=0)return null;let Z=Q-Y;if(Z<0||Z>=E)return null;let U=Math.max(1,Math.floor(E/J)),X=Math.floor(Z/U);return X>=0&&X<J?X:null}case"line":case"sparkline":case"stacked-area":{let Y=F?i2:0,E=B-Y;if(E<=0)return null;let Z=Math.max(0,Math.min(E-1,Q-Y));if(J===1)return 0;let U=E/(J-1),X=Math.round(Z/U);return Math.max(0,Math.min(J-1,X))}default:return null}}function ye3(A,Q,$,B,D,J,F,Y){if(D<=0||Q<0||Q>=D)return null;let E=2;switch(A){case"horizontal-bar":return{x:Math.floor($/2),y:Q};case"bar":case"stacked-bar":{let Z=J?i2:0,U=$-Z,X=B-(J?E:0);if(U<=0||X<=0)return null;let G=Math.max(1,Math.floor(U/D)),V=Z+Q*G+Math.floor(G/2),K=Y>0?F/Y:0,z=Math.round((1-K)*(X-1));return{x:V,y:z}}case"line":case"sparkline":case"stacked-area":{let Z=J?i2:0,U=$-Z,X=B-(J?E:0);if(U<=0||X<=0)return null;let G=D>1?Z+Math.round(Q/(D-1)*(U-1)):Z+Math.floor(U/2),V=Y>0?F/Y:0,K=Math.round((1-V)*(X-1));return{x:G,y:K}}default:return null}}function xe3(A){let Q=0;for(let $ of A)for(let B of $.points)if(B.value>Q)Q=B.value;return Q||1}function be3(A,Q,$,B,D){if($.length<=1){let Y=B(A.value),E=A.meta?` (${A.meta})`:"";return A.label.length+2+Y.length+E.length}let J=A.label.length,F=0;for(let Y of $){let E=Y.points[Q];if(!E)continue;F+=E.value;let Z=2+Y.name.length+2+B(E.value).length;J=Math.max(J,Z)}if(D){let Y=9+B(F).length;J=Math.max(J,Y)}return J}function he3(A,Q,$,B,D,J,F){let Y;try{let K=L1.of(A),z=O0.of(A);Y={foreground:K.colorScheme.foreground,background:K.colorScheme.background,border:z.app.keybind}}catch{Y={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let E=new T({color:Y.foreground,bold:!0}),Z=new T({color:Y.foreground}),U=new T({color:Y.foreground,dim:!0}),X=[],G=new T({color:Y.foreground,underline:!0}),V=(K,z)=>new C(z,G,void 0,cz(K),()=>{n6(A,K)});if(B.length<=1){if(X.push(new C(`${Q.label}: `,E)),Q.link)X.push(V(Q.link,J(Q.value)));else X.push(new C(J(Q.value),Z));if(Q.meta)X.push(new C(` (${Q.meta})`,U))}else{let K=F==="stacked-bar"||F==="stacked-area";X.push(new C(`${Q.label}
7086
7085
  `,E));let z=0;for(let W=0;W<B.length;W++){let I=B[W],H=I.points[$];if(!H)continue;z+=H.value;let q=I.color??D[W%D.length]??Y.foreground;if(X.push(new C("● ",new T({color:q}))),X.push(new C(`${I.name}: `,U)),H.link)X.push(V(H.link,J(H.value)));else X.push(new C(J(H.value),Z));if(W<B.length-1||K)X.push(new C(`
7087
- `))}if(K)X.push(new C(" ",U)),X.push(new C("Total: ",U)),X.push(new C(J(z),Z))}return new x0({decoration:{color:Y.background,border:p1.all(new c1(Y.border,1,"rounded"))},child:new d({text:new C(void 0,void 0,X)})})}p0();function QA6(A){return A.length===0?A:A[0].toLowerCase()+A.slice(1)}Z5();o5();x5();g$();u9();A8();xQ();Bq();a4();Uk();y_();P1();p0();u9();class B81{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,$])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1779409185-ge486da"},parameters:{metadata:{count:$}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await V20(Q,this.configService)}catch(Q){P.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Ow extends R0{props;constructor(A){super();this.props=A}createState(){return new $A6}}class $A6 extends j0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=($)=>{this.setState(()=>{this._state=$(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class BA6 extends j0{controller=new _2;focusNode=new r6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=this.widget.props.isRequiredArg??!0,J=this.controller.text.trim().length>0,F=!D||J,Y=p1.all(new c1($.foreground,1,"solid")),E=new XB({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(V)=>{let K=V.trim();if(D&&K.length===0)return;this.widget.props.onSubmit(K)},autofocus:!0,style:{textColor:$.foreground,border:null},maxLines:1}),Z=new r0({children:[new x0({decoration:{color:$.background},child:new d({text:new C(">",new T({color:$.foreground}))})}),new R1({child:E})]}),U=new x0({padding:V0.symmetric(1,0),child:new d({text:this.widget.props.title?new C(this.widget.props.title,new T({color:B.command,bold:!0})):new C("",void 0,[new C("Command: ",new T({color:$.foreground})),new C(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=[];if(F)X.push(new C("Enter",new T({color:B.keybind}))),X.push(new C(" to submit, ",new T({color:$.foreground,dim:!0})));X.push(new C("Esc",new T({color:B.keybind}))),X.push(new C(" to cancel",new T({color:$.foreground,dim:!0})));let G=new x0({padding:V0.symmetric(1,0),child:new d({text:new C("",void 0,X)})});return new x0({decoration:{border:Y,color:$.background},padding:V0.all(1),child:new S0({children:[U,new X0({height:1}),Z,new U3,G]})})}}class ft extends R0{props;constructor(A){super();this.props=A}createState(){return new BA6}}xQ();class DA6 extends j0{controller=new _2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new r6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=T9)return!1;let Q=await rG(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,J=h1.of(A).size.height,F=Math.max(Math.floor(J*0.5),10),Y=new EW({controller:this.controller,triggers:[new YE],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(V)=>{this.widget.props.onSubmit(V.trim(),this.imageAttachments)},theme:$,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:W4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),E=new v4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:Y}),Z=new x0({constraints:new C1({maxHeight:F}),padding:V0.symmetric(1,0),child:E}),U=new x0({padding:V0.symmetric(1,0),child:new d({text:new C("",void 0,[new C("Command: ",new T({color:$.foreground})),new C(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=new x0({padding:V0.symmetric(1,0),child:new d({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new T({color:B.keybind})),new C(" again to clear input",new T({color:$.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new T({color:$.foreground,dim:!0})),new C("Enter",new T({color:B.keybind})),new C(" to submit, ",new T({color:$.foreground,dim:!0})),new C("Esc",new T({color:B.keybind})),new C(" to clear",new T({color:$.foreground,dim:!0}))])})}),G=[U,new X0({height:1}),new R1({child:Z}),new X0({height:1}),X];return new x0({decoration:{border:p1.all(new c1($.foreground,1,"solid")),color:$.background},padding:V0.all(1),child:new S0({children:G})})}}class D81 extends R0{props;constructor(A){super();this.props=A}createState(){return new DA6}}function JA6(A){let $=new Date().getTime()-A.getTime(),B=Math.floor($/60000),D=Math.floor($/3600000),J=Math.floor($/86400000);if(B<1)return"just now";if(B<60)return`${B}m ago`;if(D<24)return`${D}h ago`;if(J<7)return`${J}d ago`;return A.toLocaleDateString()}class J81 extends H1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((D,J)=>J.pubDate.getTime()-D.pubDate.getTime()),$=Math.max(0,...Q.map((D)=>JA6(D.pubDate).length));return new cA({items:Q,getLabel:(D)=>D.title,onAccept:(D)=>this.props.onSelect?.(D),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(D,J,F,Y)=>{let E=O0.of(Y),{colors:Z}=E,U=E.app,X=J?U.selectionBackground:void 0,G=J?U.selectionForeground:Z.foreground,V=Z.mutedForeground,K=(z,W)=>new X0({width:W,child:r0.end([new d({text:new C(z,new T({color:V}))})])});return new x0({decoration:X?{color:X}:void 0,padding:V0.symmetric(2,0),child:new r0({children:[new R1({child:new d({text:new C(D.title,new T({color:G})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),K(JA6(D.pubDate),$)]})})}})}}class I${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!I$._instance)I$._instance=new I$;return I$._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}p0();class FA6 extends j0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){P.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){P.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let $=this.widget.props.currentLabels||[],B=this.labels.some((J)=>J.name===Q),D=$.includes(Q);return!B&&!D}build(A){let Q=O0.of(A),{app:$,colors:B}=Q,D=this.currentQuery.trim().toLowerCase(),J=D.length>0?this.getValidationError(D):null,F=this.getAvailableLabels(),E=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...F];return new cA({title:"Add Label",items:E,getLabel:(Z)=>{if("__isCreateMarker"in Z)return this.currentQuery.trim().toLowerCase();return Z.name},onAccept:(Z)=>{if("__isCreateMarker"in Z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(Z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:J||"Type to create a new label",renderItem:(Z,U,X,G)=>{let V=U?$.selectionBackground:void 0,K=U?$.selectionForeground:B.foreground;if("__isCreateMarker"in Z&&Z.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new x0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new C("",void 0,[new C("Create new label: ",new T({color:K})),new C(W,new T({color:K,bold:!0}))])})})}return new x0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new C(Z.name,new T({color:K}))})})},filterItem:(Z,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in Z&&Z.__isCreateMarker)return this.shouldShowCreateMarker(U);let G=U.trim().toLowerCase();return G.length===0||Z.name.includes(G)},sortItems:(Z,U,X)=>{let G="__isCreateMarker"in Z.item&&Z.item.__isCreateMarker,V="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(G&&!V)return-1;if(!G&&V)return 1;return U.score-Z.score}})}}class F81 extends R0{props;constructor(A){super();this.props=A}createState(){return new FA6}}class DU extends R0{props;constructor(A){super();this.props=A}createState(){return new YA6}}class YA6 extends j0{_spinner=new NA;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=p1.all(new c1($.foreground,1,"solid")),J=this._spinner.toBraille(),F=new d({textAlign:"center",text:new C("",void 0,[new C(J,new T({color:B.processing})),new C(" ",void 0),new C(this.widget.props.message,new T({color:$.foreground}))])}),E=[new R1({child:new S0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[F]})})];if(this.widget.props.onAbort)E.push(new X0({height:2,child:new x0({padding:V0.symmetric(2,0),child:new d({text:new C("",new T({dim:!0}),[new C("Press ",new T({color:$.foreground})),new C("Esc",new T({color:$.info})),new C(" to cancel",new T({color:$.foreground}))])})})}));let Z=new x0({decoration:new R4($.background,D),child:new X0({width:60,height:7,child:new S0({mainAxisAlignment:"start",children:E})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",child:new v4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:Z})});return Z}}class $V extends R0{props;constructor(A){super();this.props=A}createState(){return new EA6}}class EA6 extends j0{scrollController=new v6;scrollAreaKey=new U8("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof i8}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let $=Q.size;if(typeof $.height==="number"&&$.height>0)return this.viewportHeight=$.height,$.height}return this.viewportHeight}build(A){let Q=O0.of(A),$=this.widget.props.message,B=(()=>{if(this.isWidgetMessage($))return{title:$.title,type:$.type};if($ instanceof Error&&$.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:$.message};if($ instanceof Error&&$.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:$.message};let U=NU0($);return{title:U.title,type:U.type,description:U.description}})(),D=B.type==="error"?Q.app.toolError:Q.app.command,J=p1.all(new c1(Q.colors.border,1,"solid")),F=new x0({padding:V0.symmetric(1,0),child:new d({text:new C(B.title,new T({color:D,bold:!0}))})}),Y=this.isWidgetMessage($)?$.widget:new d({text:new C(B.description,new T({color:Q.colors.foreground})),selectable:!0}),E=new R1({child:new X5({child:new x0({padding:V0.symmetric(1,0),child:new r0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new R1({child:new k6({controller:this.scrollController,autofocus:!0,child:Y})}),new I8({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,X=this.scrollController.offset,G=this.getViewportHeight(),V=U+G;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(G,1),scrollOffset:Math.max(X,0)}}})]})})})}),Z=new x0({padding:V0.symmetric(1,0),child:new d({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new T({color:Q.colors.foreground,dim:!0})),new C("R",new T({color:Q.app.keybind})),new C(" to retry, ",new T({color:Q.colors.foreground,dim:!0})),new C("Esc",new T({color:Q.app.keybind})),new C(" to cancel",new T({color:Q.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new T({color:Q.colors.foreground,dim:!0}));if(U==="help"){let X=new T({color:Q.app.keybind}),G=new T({color:Q.colors.foreground,dim:!0});return new C("",G,[new C("Press ",G),new C("Escape",X),new C(" to close • Use ",G),new C("↑↓",X),new C(" or ",G),new C("j/k",X),new C(" to scroll",G)])}return new C("Press any key to close",new T({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({debugLabel:"MessageDialog",child:new i4({fit:"expand",children:[new O1({onClick:()=>{},child:new X0}),new v4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new x0({decoration:{border:J,color:Q.colors.background},padding:V0.all(1),child:new S0({mainAxisAlignment:"center",children:[F,new X0({height:1}),E,Z]})})})]})})}}Z5();Q4();class ZA6 extends R0{props;constructor(A){super();this.props=A}createState(){return new UA6}}class UA6 extends j0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=i0.file(this.widget.props.cwd),$=B1.relativePath(Q,XA(A));if($!==null&&$!==""&&$!==".."&&!$.startsWith("../"))return $;return l3(A)}statusIcon(A){let Q=p2.default(),{colors:$,app:B}=Q;switch(A){case"loading":return{icon:"◌",color:$.warning};case"active":return{icon:"✓",color:B.toolSuccess};case"error":return{icon:"✗",color:B.toolError}}}build(A){let Q=O0.of(A),{app:$}=Q;if(this.plugins.length===0)return new d({text:new C("No plugins found.",new T({dim:!0}))});let B=[],D=this.plugins.length,J=this.plugins.filter((E)=>E.status==="active").length,F=this.plugins.reduce((E,Z)=>E+Z.registeredCommands.length,0),Y=this.plugins.reduce((E,Z)=>E+Z.registeredTools.length,0);if(B.push(new C(`${J}/${D} ${X4(D,"plugin")} active`,new T({bold:!0}))),F>0||Y>0)B.push(new C(` (${F} ${X4(F,"command")}, ${Y} ${X4(Y,"tool")})`,new T({dim:!0})));B.push(new C(`
7086
+ `))}if(K)X.push(new C(" ",U)),X.push(new C("Total: ",U)),X.push(new C(J(z),Z))}return new x0({decoration:{color:Y.background,border:p1.all(new c1(Y.border,1,"rounded"))},child:new d({text:new C(void 0,void 0,X)})})}p0();function QA6(A){return A.length===0?A:A[0].toLowerCase()+A.slice(1)}Z5();o5();x5();g$();u9();A8();xQ();Bq();a4();Uk();y_();P1();p0();u9();class B81{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,$])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1779426990-g24af9a"},parameters:{metadata:{count:$}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await V20(Q,this.configService)}catch(Q){P.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Ow extends R0{props;constructor(A){super();this.props=A}createState(){return new $A6}}class $A6 extends j0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=($)=>{this.setState(()=>{this._state=$(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class BA6 extends j0{controller=new _2;focusNode=new r6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=this.widget.props.isRequiredArg??!0,J=this.controller.text.trim().length>0,F=!D||J,Y=p1.all(new c1($.foreground,1,"solid")),E=new XB({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(V)=>{let K=V.trim();if(D&&K.length===0)return;this.widget.props.onSubmit(K)},autofocus:!0,style:{textColor:$.foreground,border:null},maxLines:1}),Z=new r0({children:[new x0({decoration:{color:$.background},child:new d({text:new C(">",new T({color:$.foreground}))})}),new R1({child:E})]}),U=new x0({padding:V0.symmetric(1,0),child:new d({text:this.widget.props.title?new C(this.widget.props.title,new T({color:B.command,bold:!0})):new C("",void 0,[new C("Command: ",new T({color:$.foreground})),new C(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=[];if(F)X.push(new C("Enter",new T({color:B.keybind}))),X.push(new C(" to submit, ",new T({color:$.foreground,dim:!0})));X.push(new C("Esc",new T({color:B.keybind}))),X.push(new C(" to cancel",new T({color:$.foreground,dim:!0})));let G=new x0({padding:V0.symmetric(1,0),child:new d({text:new C("",void 0,X)})});return new x0({decoration:{border:Y,color:$.background},padding:V0.all(1),child:new S0({children:[U,new X0({height:1}),Z,new U3,G]})})}}class ft extends R0{props;constructor(A){super();this.props=A}createState(){return new BA6}}xQ();class DA6 extends j0{controller=new _2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new r6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=T9)return!1;let Q=await rG(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,J=h1.of(A).size.height,F=Math.max(Math.floor(J*0.5),10),Y=new EW({controller:this.controller,triggers:[new YE],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(V)=>{this.widget.props.onSubmit(V.trim(),this.imageAttachments)},theme:$,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:W4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),E=new v4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:Y}),Z=new x0({constraints:new C1({maxHeight:F}),padding:V0.symmetric(1,0),child:E}),U=new x0({padding:V0.symmetric(1,0),child:new d({text:new C("",void 0,[new C("Command: ",new T({color:$.foreground})),new C(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=new x0({padding:V0.symmetric(1,0),child:new d({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new T({color:B.keybind})),new C(" again to clear input",new T({color:$.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new T({color:$.foreground,dim:!0})),new C("Enter",new T({color:B.keybind})),new C(" to submit, ",new T({color:$.foreground,dim:!0})),new C("Esc",new T({color:B.keybind})),new C(" to clear",new T({color:$.foreground,dim:!0}))])})}),G=[U,new X0({height:1}),new R1({child:Z}),new X0({height:1}),X];return new x0({decoration:{border:p1.all(new c1($.foreground,1,"solid")),color:$.background},padding:V0.all(1),child:new S0({children:G})})}}class D81 extends R0{props;constructor(A){super();this.props=A}createState(){return new DA6}}function JA6(A){let $=new Date().getTime()-A.getTime(),B=Math.floor($/60000),D=Math.floor($/3600000),J=Math.floor($/86400000);if(B<1)return"just now";if(B<60)return`${B}m ago`;if(D<24)return`${D}h ago`;if(J<7)return`${J}d ago`;return A.toLocaleDateString()}class J81 extends H1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((D,J)=>J.pubDate.getTime()-D.pubDate.getTime()),$=Math.max(0,...Q.map((D)=>JA6(D.pubDate).length));return new cA({items:Q,getLabel:(D)=>D.title,onAccept:(D)=>this.props.onSelect?.(D),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(D,J,F,Y)=>{let E=O0.of(Y),{colors:Z}=E,U=E.app,X=J?U.selectionBackground:void 0,G=J?U.selectionForeground:Z.foreground,V=Z.mutedForeground,K=(z,W)=>new X0({width:W,child:r0.end([new d({text:new C(z,new T({color:V}))})])});return new x0({decoration:X?{color:X}:void 0,padding:V0.symmetric(2,0),child:new r0({children:[new R1({child:new d({text:new C(D.title,new T({color:G})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),K(JA6(D.pubDate),$)]})})}})}}class I${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!I$._instance)I$._instance=new I$;return I$._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}p0();class FA6 extends j0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){P.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){P.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let $=this.widget.props.currentLabels||[],B=this.labels.some((J)=>J.name===Q),D=$.includes(Q);return!B&&!D}build(A){let Q=O0.of(A),{app:$,colors:B}=Q,D=this.currentQuery.trim().toLowerCase(),J=D.length>0?this.getValidationError(D):null,F=this.getAvailableLabels(),E=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...F];return new cA({title:"Add Label",items:E,getLabel:(Z)=>{if("__isCreateMarker"in Z)return this.currentQuery.trim().toLowerCase();return Z.name},onAccept:(Z)=>{if("__isCreateMarker"in Z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(Z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:J||"Type to create a new label",renderItem:(Z,U,X,G)=>{let V=U?$.selectionBackground:void 0,K=U?$.selectionForeground:B.foreground;if("__isCreateMarker"in Z&&Z.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new x0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new C("",void 0,[new C("Create new label: ",new T({color:K})),new C(W,new T({color:K,bold:!0}))])})})}return new x0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new C(Z.name,new T({color:K}))})})},filterItem:(Z,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in Z&&Z.__isCreateMarker)return this.shouldShowCreateMarker(U);let G=U.trim().toLowerCase();return G.length===0||Z.name.includes(G)},sortItems:(Z,U,X)=>{let G="__isCreateMarker"in Z.item&&Z.item.__isCreateMarker,V="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(G&&!V)return-1;if(!G&&V)return 1;return U.score-Z.score}})}}class F81 extends R0{props;constructor(A){super();this.props=A}createState(){return new FA6}}class DU extends R0{props;constructor(A){super();this.props=A}createState(){return new YA6}}class YA6 extends j0{_spinner=new NA;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=p1.all(new c1($.foreground,1,"solid")),J=this._spinner.toBraille(),F=new d({textAlign:"center",text:new C("",void 0,[new C(J,new T({color:B.processing})),new C(" ",void 0),new C(this.widget.props.message,new T({color:$.foreground}))])}),E=[new R1({child:new S0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[F]})})];if(this.widget.props.onAbort)E.push(new X0({height:2,child:new x0({padding:V0.symmetric(2,0),child:new d({text:new C("",new T({dim:!0}),[new C("Press ",new T({color:$.foreground})),new C("Esc",new T({color:$.info})),new C(" to cancel",new T({color:$.foreground}))])})})}));let Z=new x0({decoration:new R4($.background,D),child:new X0({width:60,height:7,child:new S0({mainAxisAlignment:"start",children:E})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",child:new v4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:Z})});return Z}}class $V extends R0{props;constructor(A){super();this.props=A}createState(){return new EA6}}class EA6 extends j0{scrollController=new v6;scrollAreaKey=new U8("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof i8}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let $=Q.size;if(typeof $.height==="number"&&$.height>0)return this.viewportHeight=$.height,$.height}return this.viewportHeight}build(A){let Q=O0.of(A),$=this.widget.props.message,B=(()=>{if(this.isWidgetMessage($))return{title:$.title,type:$.type};if($ instanceof Error&&$.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:$.message};if($ instanceof Error&&$.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:$.message};let U=NU0($);return{title:U.title,type:U.type,description:U.description}})(),D=B.type==="error"?Q.app.toolError:Q.app.command,J=p1.all(new c1(Q.colors.border,1,"solid")),F=new x0({padding:V0.symmetric(1,0),child:new d({text:new C(B.title,new T({color:D,bold:!0}))})}),Y=this.isWidgetMessage($)?$.widget:new d({text:new C(B.description,new T({color:Q.colors.foreground})),selectable:!0}),E=new R1({child:new X5({child:new x0({padding:V0.symmetric(1,0),child:new r0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new R1({child:new k6({controller:this.scrollController,autofocus:!0,child:Y})}),new I8({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,X=this.scrollController.offset,G=this.getViewportHeight(),V=U+G;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(G,1),scrollOffset:Math.max(X,0)}}})]})})})}),Z=new x0({padding:V0.symmetric(1,0),child:new d({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new T({color:Q.colors.foreground,dim:!0})),new C("R",new T({color:Q.app.keybind})),new C(" to retry, ",new T({color:Q.colors.foreground,dim:!0})),new C("Esc",new T({color:Q.app.keybind})),new C(" to cancel",new T({color:Q.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new T({color:Q.colors.foreground,dim:!0}));if(U==="help"){let X=new T({color:Q.app.keybind}),G=new T({color:Q.colors.foreground,dim:!0});return new C("",G,[new C("Press ",G),new C("Escape",X),new C(" to close • Use ",G),new C("↑↓",X),new C(" or ",G),new C("j/k",X),new C(" to scroll",G)])}return new C("Press any key to close",new T({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({debugLabel:"MessageDialog",child:new i4({fit:"expand",children:[new O1({onClick:()=>{},child:new X0}),new v4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new x0({decoration:{border:J,color:Q.colors.background},padding:V0.all(1),child:new S0({mainAxisAlignment:"center",children:[F,new X0({height:1}),E,Z]})})})]})})}}Z5();Q4();class ZA6 extends R0{props;constructor(A){super();this.props=A}createState(){return new UA6}}class UA6 extends j0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=i0.file(this.widget.props.cwd),$=B1.relativePath(Q,XA(A));if($!==null&&$!==""&&$!==".."&&!$.startsWith("../"))return $;return l3(A)}statusIcon(A){let Q=p2.default(),{colors:$,app:B}=Q;switch(A){case"loading":return{icon:"◌",color:$.warning};case"active":return{icon:"✓",color:B.toolSuccess};case"error":return{icon:"✗",color:B.toolError}}}build(A){let Q=O0.of(A),{app:$}=Q;if(this.plugins.length===0)return new d({text:new C("No plugins found.",new T({dim:!0}))});let B=[],D=this.plugins.length,J=this.plugins.filter((E)=>E.status==="active").length,F=this.plugins.reduce((E,Z)=>E+Z.registeredCommands.length,0),Y=this.plugins.reduce((E,Z)=>E+Z.registeredTools.length,0);if(B.push(new C(`${J}/${D} ${X4(D,"plugin")} active`,new T({bold:!0}))),F>0||Y>0)B.push(new C(` (${F} ${X4(F,"command")}, ${Y} ${X4(Y,"tool")})`,new T({dim:!0})));B.push(new C(`
7088
7087
 
7089
7088
  `));for(let E of this.plugins){let{icon:Z,color:U}=this.statusIcon(E.status),X=this.getRelativePath(E.uri);if(B.push(new C(`${Z} `,new T({color:U}))),B.push(new C(X,new T({bold:!0}))),B.push(new C(` ${E.status}`,new T({dim:!0}))),B.push(new C(`
7090
7089
  `)),E.status==="active"&&E.registeredEvents.length>0)B.push(new C(" Events: ",new T({dim:!0}))),B.push(new C(E.registeredEvents.join(", "),new T({color:$.link}))),B.push(new C(`
@@ -7263,7 +7262,7 @@ ${t.content||""}`:t.content||"",d0=[],b0=t.baseDir.startsWith("file://")?HK0(t.b
7263
7262
  `)}function l56(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async($,B)=>{let D=B.optsWithGlobals(),J=await Q(D),F=await J.settings.get("proxy"),Y=w44({settings:{url:J.ampURL,proxy:F},secrets:{getToken:(Z,U)=>J.secrets.get(Z,U)}}),E=await e4.userDisplayBalanceInfo({},{config:Y});if(!E.ok){if(E.error.code==="auth-required")process.stderr.write(t0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(t0.red("Error: ")+E.error.message+`
7264
7263
  `),process.exit(1)}process.stdout.write(await F65(E.result.displayText)+`
7265
7264
  `),process.exit(0)})}var P25=qe.join(iB,"logs","headless.log"),ZQ1=qe.join(id,"device-id.json"),u25=`cli-tui-${q76(16).toString("hex")}`;async function _25(){let A=await Promise.all($L.map(async(Q)=>{try{return{query:Q,hasConfigs:(await Q.listConfigs()).length>0}}catch($){return P.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 w76(){_25().then((A)=>{if(A){let Q=f20(A.ideName);if(Q)oM(Q)}})}try{if(process.platform==="win32")await Promise.resolve().then(() => b4(Ab(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){H$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
7266
- `)}function T25(A){process.emitWarning=(Q,$,B,D)=>{let J=typeof Q==="string"?Q:Q.message||String(Q),F=$||"Warning",Y=!1;A.warn(J,{name:F,code:B})}}function s8(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")IJ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")IJ("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)IJ("internal.model",S25(Q.model))}function G76(A){let Q=A.indexOf(":");if(Q===-1)throw new n1(`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 n1(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function v25(A){if(A===void 0)return;let Q=A.trim();if(z20(Q))return Q;throw new n1(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function k25(A,Q){if(a5(A,Q))return;let $=eB(A)?.levels,B=$?` Allowed for ${A}: ${$.join(", ")}.`:"";throw new n1(`Reasoning effort "${Q}" is not available for ${A} mode.${B}`,1)}function S25(A){if(!A.includes("="))return G76(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let D=B.indexOf("=");if(D===-1)throw new n1(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let J=B.slice(0,D).trim(),F=B.slice(D+1).trim();if(!J)throw new n1(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!F)throw new n1(`Missing model value for mode "${J}". Expected "${J}=provider:model".`,1);G76(F),Q[J]=F}if(Object.keys(Q).length===0)throw new n1("No valid model overrides found in --model flag value.",1);return Q}function Yz0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new AY0(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new AY0(`${Q} must be an integer <= ${$.max}`);return B}function f25(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 y25(A){try{return await N76(A,"utf-8")}catch{return A}}async function UQ1(A,Q,$){let B=f25(A,Q);if(!B)return;let D=e6($)?$.features:[],J=e6($)?$.user.email:void 0;if(!Ce(D,S$.HARNESS_SYSTEM_PROMPT)&&!(J&&p7(J)))throw new n1("You are not allowed to do this.",1);IJ("systemPrompt",await y25(B))}function Ce(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}function x25(A){return A!=="pending"}function TW(A){if(!e6(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function b25(A){let Q=TW(A);if(Q)return Q.id;if(lE(A))throw Error(A.error.message);throw Error("unreachable")}function h25(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 g25(A){let B=h25(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 n1(`Couldn't connect to the Amp server at ${A}.`,1,B)}function Ne(A,Q){let $=Is0(Error(A.error.message));if($.message===d9.networkOffline||$.message===d9.networkTimeout)return g25(Q);if($.message!==d9.internalBug)return new n1($.message,1,$.suggestion);return new n1(A.error.message.replace(/^Error: /,""),1)}async function m25(){if(process.versions.bun)return!1;try{return await kG()==="npm"}catch(A){return P.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var V76=[{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??nE,description:`Custom settings file path (overrides the default location ${nE})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ao})`},{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:w9(),description:(A)=>A?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(A)=>A?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:eM.SMART.key,description:`Set the agent mode (${tB({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(tB().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],K76=(A)=>("deprecated"in A)&&A.deprecated===!0,d25=(A)=>("hidden"in A)&&A.hidden===!0,p25=(A)=>("default"in A),c25=(A)=>("default"in A)?A.default:void 0;function Ez0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=v25(Q.effort);if($!==void 0)k25(Q.mode,$);return $}function l25(A,Q){let $=Q.args[0],B=Q.commands.map((J)=>J.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let J=B.filter((Y)=>$.includes(Y)||Y.includes($)),F="Run amp --help for a list of available commands.";if(J.length>0)F=`Did you mean: ${J.join(", ")}? Or run amp --help for all commands.`;throw new n1(d9.unknownCommand($),1,F)}}async function Xz0(A){return{...A,getThreadEnvironment:vz,getEnvironmentData:(Q,$)=>rK(Q,$),skillService:A.skillService,fileChangeTrackerStorage:new mL,generateThreadTitle:jZ4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>sF(A.configService),pluginService:A.pluginService}}function C76(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:vz,getEnvironmentData:(Q,$)=>rK(Q,$)}}var Zz0=i0.file(R25.homedir()),XQ1=process.env.XDG_CONFIG_HOME?i0.file(process.env.XDG_CONFIG_HOME):B1.joinPath(Zz0,".config");async function n2(A,Q,$){let B=$?.deferAuth??!1,D=$?.skipToolProviders??!1;i14("0.0.1779409185-ge486da");let J=R20({storage:A.settings,secretStorage:A.secrets,workspaceRoot:h0.of(i0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:Zz0,userConfigDir:XQ1}),F=A.secrets.get("apiKey",A.ampURL),Y=sF(J),E=null,Z=()=>{return},U=new Promise((Q0)=>{Z=Q0}),X=F.then(async(Q0)=>{if(!Q0&&!B)await U;return E??=Y.subscribe(()=>{}),k1(Y.pipe(i3(x25)))});X.catch(()=>{return}),Q16(J);let G=await J.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let V=!1;{let Q0=await F;if(V=Boolean(Q0),P.info("API key lookup before login",{found:Boolean(Q0),ampURL:A.ampURL,deferAuth:B}),!Q0)if(B)P.info("No API key found, continuing startup with deferred auth");else{Q3.write(`No API key found. Starting login flow...
7265
+ `)}function T25(A){process.emitWarning=(Q,$,B,D)=>{let J=typeof Q==="string"?Q:Q.message||String(Q),F=$||"Warning",Y=!1;A.warn(J,{name:F,code:B})}}function s8(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")IJ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")IJ("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)IJ("internal.model",S25(Q.model))}function G76(A){let Q=A.indexOf(":");if(Q===-1)throw new n1(`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 n1(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function v25(A){if(A===void 0)return;let Q=A.trim();if(z20(Q))return Q;throw new n1(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function k25(A,Q){if(a5(A,Q))return;let $=eB(A)?.levels,B=$?` Allowed for ${A}: ${$.join(", ")}.`:"";throw new n1(`Reasoning effort "${Q}" is not available for ${A} mode.${B}`,1)}function S25(A){if(!A.includes("="))return G76(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let D=B.indexOf("=");if(D===-1)throw new n1(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let J=B.slice(0,D).trim(),F=B.slice(D+1).trim();if(!J)throw new n1(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!F)throw new n1(`Missing model value for mode "${J}". Expected "${J}=provider:model".`,1);G76(F),Q[J]=F}if(Object.keys(Q).length===0)throw new n1("No valid model overrides found in --model flag value.",1);return Q}function Yz0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new AY0(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new AY0(`${Q} must be an integer <= ${$.max}`);return B}function f25(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 y25(A){try{return await N76(A,"utf-8")}catch{return A}}async function UQ1(A,Q,$){let B=f25(A,Q);if(!B)return;let D=e6($)?$.features:[],J=e6($)?$.user.email:void 0;if(!Ce(D,S$.HARNESS_SYSTEM_PROMPT)&&!(J&&p7(J)))throw new n1("You are not allowed to do this.",1);IJ("systemPrompt",await y25(B))}function Ce(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}function x25(A){return A!=="pending"}function TW(A){if(!e6(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function b25(A){let Q=TW(A);if(Q)return Q.id;if(lE(A))throw Error(A.error.message);throw Error("unreachable")}function h25(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 g25(A){let B=h25(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 n1(`Couldn't connect to the Amp server at ${A}.`,1,B)}function Ne(A,Q){let $=Is0(Error(A.error.message));if($.message===d9.networkOffline||$.message===d9.networkTimeout)return g25(Q);if($.message!==d9.internalBug)return new n1($.message,1,$.suggestion);return new n1(A.error.message.replace(/^Error: /,""),1)}async function m25(){if(process.versions.bun)return!1;try{return await kG()==="npm"}catch(A){return P.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var V76=[{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??nE,description:`Custom settings file path (overrides the default location ${nE})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ao})`},{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:w9(),description:(A)=>A?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(A)=>A?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:eM.SMART.key,description:`Set the agent mode (${tB({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(tB().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],K76=(A)=>("deprecated"in A)&&A.deprecated===!0,d25=(A)=>("hidden"in A)&&A.hidden===!0,p25=(A)=>("default"in A),c25=(A)=>("default"in A)?A.default:void 0;function Ez0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=v25(Q.effort);if($!==void 0)k25(Q.mode,$);return $}function l25(A,Q){let $=Q.args[0],B=Q.commands.map((J)=>J.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let J=B.filter((Y)=>$.includes(Y)||Y.includes($)),F="Run amp --help for a list of available commands.";if(J.length>0)F=`Did you mean: ${J.join(", ")}? Or run amp --help for all commands.`;throw new n1(d9.unknownCommand($),1,F)}}async function Xz0(A){return{...A,getThreadEnvironment:vz,getEnvironmentData:(Q,$)=>rK(Q,$),skillService:A.skillService,fileChangeTrackerStorage:new mL,generateThreadTitle:jZ4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>sF(A.configService),pluginService:A.pluginService}}function C76(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:vz,getEnvironmentData:(Q,$)=>rK(Q,$)}}var Zz0=i0.file(R25.homedir()),XQ1=process.env.XDG_CONFIG_HOME?i0.file(process.env.XDG_CONFIG_HOME):B1.joinPath(Zz0,".config");async function n2(A,Q,$){let B=$?.deferAuth??!1,D=$?.skipToolProviders??!1;i14("0.0.1779426990-g24af9a");let J=R20({storage:A.settings,secretStorage:A.secrets,workspaceRoot:h0.of(i0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:Zz0,userConfigDir:XQ1}),F=A.secrets.get("apiKey",A.ampURL),Y=sF(J),E=null,Z=()=>{return},U=new Promise((Q0)=>{Z=Q0}),X=F.then(async(Q0)=>{if(!Q0&&!B)await U;return E??=Y.subscribe(()=>{}),k1(Y.pipe(i3(x25)))});X.catch(()=>{return}),Q16(J);let G=await J.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let V=!1;{let Q0=await F;if(V=Boolean(Q0),P.info("API key lookup before login",{found:Boolean(Q0),ampURL:A.ampURL,deferAuth:B}),!Q0)if(B)P.info("No API key found, continuing startup with deferred auth");else{Q3.write(`No API key found. Starting login flow...
7267
7266
  `);let M0=await i25(A),n=await A.secrets.get("apiKey",A.ampURL);if(P.info("Login flow completed",{success:M0,storedKeyPresent:Boolean(n),ampURL:A.ampURL}),!M0)await Tz(),process.exit(1);V=!0,Z()}}{let Q0=await J.getLatest(),M0=Q0.settings.url,n=Q0.secrets.isSet?.[M0];P.info("Config secrets state after login",{configURL:M0,apiKeySet:n?.apiKey??!1})}let K=B?"pending":await X;if(!B)P.info("Server status resolved",{status:"ready",isAuthenticated:e6(K),isError:lE(K),errorMessage:lE(K)?K.error.message:void 0});let z=X.then((Q0)=>b25(Q0));z.catch(()=>{return});let W=!Q.takeMeBack&&e6(K)&&Ce(K.features,S$.THREAD_ACTORS_TUI),I=!1;if(process.env.AMP_DISABLE_PLUGINS==="1")P.warn("Ignoring AMP_DISABLE_PLUGINS outside development");let H=I?"off":W?"all":process.env.PLUGINS??"permissions",{toolService:q,dispose:N}=yu4({configService:J}),w=new Map,O=()=>w.clear(),L=new Fb0(J,A.settings.getWorkspaceRootPath()),j=QY4({configService:J}),k=b$4({configService:J,trustStore:L,skillMCPServers:j.skillMCPServers,uploadImageAttachments:W,createOAuthProvider:async(Q0,M0,n)=>{let a=`${Q0}:${M0}`,t=w.get(a);if(t)return P.debug("Reusing existing OAuth provider for server",{serverName:Q0,serverUrl:M0}),t;P.debug("Creating OAuth provider for server",{serverName:Q0,serverUrl:M0});let e=(async()=>{let F0=new EL(A.secrets),J0=await F0.getClientInfo(Q0,M0),w0=n?.scopes??J0?.scopes,C0=tx4();P.info("OAuth headless mode check",{useHeadless:C0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:Q3.isTTY});let _0;if(C0)_0=A.executeMode?sx4():rx4(Q0);let U0=new WS0({storage:F0,serverName:Q0,serverUrl:M0,clientId:n?.clientId??J0?.clientId,clientSecret:n?.clientSecret??J0?.clientSecret,authUrl:n?.authUrl??J0?.authUrl,tokenUrl:n?.tokenUrl??J0?.tokenUrl,scopes:w0,headlessAuthHandler:_0});return P.debug("OAuth provider created",{serverName:Q0,serverUrl:M0,hasManualClientId:!!(n?.clientId??J0?.clientId),willUseDCR:!(n?.clientId??J0?.clientId),scopes:w0,headlessMode:C0,executeMode:A.executeMode}),U0})();return w.set(a,e),e}}),_=Eo0({configService:J,spawn:qF0}),f=Q.headless?R06():void 0,h=f??new uG0({configService:J}),b=h instanceof uG0?h:void 0;if(b)b.pluginExecutorKind="local";let v=new a1(null),y=null,c=W&&!I?[..._06(G.settings)?[{name:"permissions",entryPoint:r51}]:[],{name:"thread-visibility",entryPoint:k06(J,()=>X.then(TW),()=>y,(Q0)=>{y=Q0}),alwaysLoad:!0}]:[],p=wb0({configService:J,platform:h,loadGlobalPlugins:ye0(J),pluginFilter:H,activeThread$:v,internalPlugins:c}),g=TB4(p),i=[k,_,g],o;if(D)o=new Map;else if(A.executeMode){let Q0=await OR4({toolService:q,providers:i,initialTimeout:15000});o=Q0.registrations;for(let[M0,n]of Q0.initErrors)P.warn(`${M0} provider initialization slow or failed:`,n)}else o=Zo0({toolService:q,providers:i});if(Q.jetbrains)oM("JetBrains");else if(Q.ide&&Mb4())oM("VS Code");else if(Q.ide&&Lb4())oM("Neovim");else if(Q.ide&&(!W||A.executeMode||Q.takeMeBack))w76();if(A.executeMode)n14(!0);let A0,W0=r5.status.pipe(N1((Q0)=>Boolean(Q0.connected&&Q0.authenticated&&Q0.ideName&&r44(Q0.ideName))),T4()).subscribe((Q0)=>{if(Q0){if(!A0)A0=q.registerTool(LR4)}else A0?.dispose(),A0=void 0}),E0;if(!A.executeMode){let Q0=await A.settings.get("fuzzy.alwaysIncludePaths")??[];E0=new kE0(process.cwd(),{alwaysIncludePaths:Q0},!0)}else E0=new class extends kE0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let I0=new Mm0(Ji(J,{usesThreadActors:!1}),{maxThreads:200});P.info("Starting Amp background services");let $0=new $21,P0={configService:J,toolService:q,mcpService:k,skillService:j,toolboxService:_,trustStore:L,threadService:I0,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:E0,terminal:$0,pluginService:p,pluginPlatform:b,headlessPluginPlatform:f,activeThread$:v,serverStatus:K,serverStatusPromise:X,viewerUserIDPromise:z,hasAPIKeyAtStartup:V,consumeDraftNewThreadVisibility:()=>{let Q0=y;return y=null,Q0}};return{...P0,async asyncDispose(){if(P0.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await P0.mcpService.waitForAuthentication();for(let Q0 of o.values())Q0.dispose();await P0.mcpService.dispose(),O(),await P0.threadService.asyncDispose(),P0.configService.unsubscribe(),E?.unsubscribe(),N(),P0.fuzzyServer.dispose(),P0.settingsStorage[Symbol.dispose](),W0.unsubscribe(),A0?.dispose(),await P0.pluginService.dispose()}}}async function i25(A){if(!A.executeMode){if(!await LZ0("Would you like to log in to Amp? [(y)es, (n)o]: "))return Q3.write(`Login cancelled. Run the command again to retry.
7268
7267
  `),!1}return await M76(A)}async function M76(A){let Q=q76(32).toString("hex"),$=await $y(A.ampURL,Q),B=new AbortController;try{await pE($,B.signal)}catch(J){P.error("Error opening browser",{error:J})}let D=await $y(A.ampURL,Q,!1);Q3.write(`If your browser does not open automatically, visit:
7269
7268
 
@@ -7271,7 +7270,7 @@ ${t0.blue.bold(D)}
7271
7270
 
7272
7271
  `);try{return await hg4(A.ampURL,Q,A.secrets,B),Q3.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(J){return P.error("Login failed",{error:J}),H$.write(`
7273
7272
  Login failed: ${J instanceof Error?J.message:String(J)}
7274
- `),!1}}async function n25(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new n1("No Amp API key found. Run `amp login` first.",1);let D=L25("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((J,F)=>{D.on("error",F),D.on("close",(Y)=>J(Y??1))})}function a25(A){let Q=new JN().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)zj(),process.exit(0);let I=W.originalError??W;Qk4(I)}),_d4(Q,{version:"0.0.1779409185-ge486da",buildTimestamp:"2026-05-22T00:24:20.009Z",buildType:"release"}),Q.addHelpText("after",Nb4()),Q.configureHelp({formatHelp:wb4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,I)=>{let H=I.optsWithGlobals(),q=await d3(H);await D85(q)}),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,I)=>{let H=I.optsWithGlobals(),q=await d3(H);await B85(q,await t51(H,q.settings))}),tv4(Q,d3);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 I=W.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??B,H=W.filter((w)=>w!==I).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),q=I.optsWithGlobals(),N=await d3(q);await n25(N.ampURL,N.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,I,H)=>{let q=H.optsWithGlobals(),N=await d3(q);await dx4(W??"get",N.ampURL,N.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,I)=>{let H=I.optsWithGlobals(),q=await d3(H);await px4(q.ampURL,q.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 bh4({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(`
7273
+ `),!1}}async function n25(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new n1("No Amp API key found. Run `amp login` first.",1);let D=L25("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((J,F)=>{D.on("error",F),D.on("close",(Y)=>J(Y??1))})}function a25(A){let Q=new JN().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)zj(),process.exit(0);let I=W.originalError??W;Qk4(I)}),_d4(Q,{version:"0.0.1779426990-g24af9a",buildTimestamp:"2026-05-22T05:21:19.350Z",buildType:"release"}),Q.addHelpText("after",Nb4()),Q.configureHelp({formatHelp:wb4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,I)=>{let H=I.optsWithGlobals(),q=await d3(H);await D85(q)}),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,I)=>{let H=I.optsWithGlobals(),q=await d3(H);await B85(q,await t51(H,q.settings))}),tv4(Q,d3);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 I=W.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??B,H=W.filter((w)=>w!==I).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),q=I.optsWithGlobals(),N=await d3(q);await n25(N.ampURL,N.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,I,H)=>{let q=H.optsWithGlobals(),N=await d3(q);await dx4(W??"get",N.ampURL,N.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,I)=>{let H=I.optsWithGlobals(),q=await d3(H);await px4(q.ampURL,q.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 bh4({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(`
7275
7274
  `)).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,I,H)=>{if(W&&I.apply)throw new n1("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let q=I.apply??W;if(!q||q.trim().length===0)Q3.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.
7276
7275
 
7277
7276
  `),H.outputHelp(),process.exit(0);let N=S8(q)??JB(q),w=H.optsWithGlobals(),O=await d3(w);s8(H,w);let L=await n2(O,w),j=!1;try{if(I.checkout&&I.skipCheckout)throw new n1("Choose either --checkout or --skip-checkout, not both.",1);if(lE(L.serverStatus))throw Ne(L.serverStatus,O.ampURL);let k=e6(L.serverStatus)?L.serverStatus.features:void 0;if(!Ce(k,S$.V2))throw new n1("live-sync is not enabled for your user",1);await Pg4({ampURL:O.ampURL,threadId:N,configService:L.configService,threadService:L.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof I.apply==="string",checkoutMode:I.checkout?"always":I.skipCheckout?"never":"prompt",promptForYesNo:LZ0}),j=!0}finally{if(await L.asyncDispose(),j)process.exit(0)}});let D=async(W,I,H)=>{R20({storage:I.settings,secretStorage:I.secrets,workspaceRoot:h0.of(i0.file(process.cwd())),defaultAmpURL:I.ampURL,homeDir:Zz0,userConfigDir:XQ1});let q={...I,executeMode:!1};await Uz0(q,{...W,openThreadSwitcher:!0},H,A)},J=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)=>Yz0(W,"--limit",{min:1,max:500})).option("--offset <number>","Number of threads to skip",(W)=>Yz0(W,"--offset",{min:0})).action(async(W,I)=>{let H=I.optsWithGlobals(),q=await d3(H);await H76(H,q,I)});J.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,I)=>{let H=I.optsWithGlobals(),q=await d3(H);await I85(H,q,I)}),J.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,I,H)=>{let q=H.optsWithGlobals(),N=await d3(q),w=Array.isArray(W)?W:[];if(I.pick)H$.write(`${t0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -7304,8 +7303,8 @@ ${O}
7304
7303
  `))}),I.args.length>0)l25(q,I);await Uz0(q,H,I,A)}),tb4(Q),Q}async function we(A,Q){await KQ(($)=>Fy($,A,Q))}async function z76(A,Q,$){let B=Date.now(),[D,J]=await Promise.all([e4.getThreadLinkInfo({thread:A},{config:Q}),$]);if(P.getChild("fetchAndStartThread").info(`Ownership check in ${Date.now()-B}ms`),D.ok){let F=D.result.creatorUserID;if(F&&F!==J&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new n1(`Cannot resume thread created by another user.
7305
7304
 
7306
7305
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function L76(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await SG0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await SG0()).trimEnd(),stdinInput:null}}function O76(A,Q,$){if(A.streamJson&&!Q)throw new n1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new n1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new n1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new n1("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 n1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new n1("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 n1("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 n1("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"
7307
- Or pipe via stdin: echo "your message" | amp --execute`)}function o25(){c34([L20.parse({tool:"*",action:"allow"})]),W34({bypass:!0})}function r25(A){if(A.threadId&&!P9(A.threadId))delete A.threadId}async function Uz0(A,Q,$,B){if(Q.headless)return s25(A,Q,$);let D=await n2(A,Q),J=await D.serverStatusPromise,F=e6(J)&&Ce(J.features,S$.THREAD_ACTORS_TUI),Y=F&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await D.asyncDispose(),new n1("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!F)throw await D.asyncDispose(),new n1("--show-welcome is only available with the new Amp CLI feature flag",1);if(Y){let E=!A.executeMode&&await m25();return o25(),r25(Q),t25(A,Q,$,D,{showNpmMigrationWelcome:E})}else{if(Q.threadId&&P9(Q.threadId)){let E=await e4.getThreadLinkInfo({thread:Q.threadId},{config:D.configService}).catch(()=>null);if(E?.ok&&E.result.usesThreadActors)throw await D.asyncDispose(),new n1(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return e25(A,Q,$,B,{dependencies:D})}}async function s25(A,Q,$){let B=(I,H)=>{let q=Number(process.hrtime.bigint()-H)/1e6,N=Ys0();P.info("Startup phase",{phase:I,phaseMs:Math.round(q),sinceMainMs:N===null?void 0:Math.round(N)})};s8($,Q);let D=process.hrtime.bigint(),J=await n2(A,Q);B("runMainThread:createThreadDependencies",D);let{serverStatus:F}=J;if(lE(F))throw Ne(F,A.ampURL);let Y=e6(F)?F:null,E=Y?.user.email;await UQ1($,Q,F);let Z=TW(F),U=Ux(Q,Z);if(U instanceof Error)P3(U.message);if(Y&&!tM(Q.mode,E))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!E||!p7(E)))throw new n1("Headless executor mode is only available for Amp employees",1);vY0();let G=await J.secretStorage.get("apiKey",A.ampURL);if(!G)throw new n1("API key required for headless mode. Please run `amp login` first.",1);let V=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(V&&!P9(V))throw new n1(`Invalid thread ID: ${V}`,1);let K=V?void 0:await z85({dependencies:J,apiKey:G,visibility:U??void 0}),z=V??K?.threadId;if(!z)throw new n1("Failed to resolve headless thread ID",1);let W=await $b4(z);if(W.status==="already-running")await J.asyncDispose(),await Tz(),process.exit(0);try{await nx4({ampURL:A.ampURL,apiKey:G,workspaceRoot:process.cwd(),threadId:z,ownerUserId:K?.ownerUserId,threadVersion:K?.threadVersion,agentMode:K?.agentMode,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized,J.pluginService.initialized]).then(()=>{return}),configService:J.configService,mcpService:J.mcpService,toolService:J.toolService,skillService:J.skillService,pluginService:J.pluginService,pluginPlatform:J.headlessPluginPlatform})}finally{await W.release(),await J.asyncDispose()}await Tz(),process.exit(0)}async function t25(A,Q,$,B,D){let{userInput:J,stdinInput:F}=await L76(Q),Y=!!Q.streamJson||!!Q.streamJsonThinking;O76({...Q,streamJson:Y},A.executeMode,J),s8($,Q),hv4(),vY0();let E=Q.threadId,Z=Q.resumeThreadIDs??(E?[E]:[]),U=Q.observe?S8(Q.observe)??JB(Q.observe):void 0,X=await B.serverStatusPromise;if(lE(X))throw Ne(X,A.ampURL);let G=TW(X),V=Ux(Q,G);if(V instanceof Error)P3(V.message);let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let q=await Qo(A.settings,process.cwd(),G,V);if(q instanceof Error)P3(q.message);return q})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new n1("API key required. Please run `amp login` first.",1);let I=e6(X)&&p7(X.user.email);if(A.executeMode){if(Z.length>1)throw new n1("Execute mode can only resume one thread.",1);p01(B.mcpService,A.settings);try{let H=Ez0($,Q),q=await oz(),N=E?H:jZ0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),w=E?void 0:RZ0(await By(B.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),O=E?void 0:await z(),L=await ux4({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:J,stdinInput:F,stats:!!Q.stats,streamJson:Y,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:E,initialThreadMeta:O,initialSettings:w});if(await we(L,"execute"),Q.archive)await B.threadService.archive(L,!0)}finally{await B.asyncDispose()}await Tz(),process.exit(0)}else{let H=Ez0($,Q),q=D.showNpmMigrationWelcome?"npm-migration":"intro",N=nE0("0.0.1779409185-ge486da",B.settingsStorage,{startDelayMs:3000}),w=new OZ0(B.mcpService,A.settings.getWorkspaceRootPath()),O=Ji(B.configService),L=new yt(B.fuzzyServer),j=process.cwd();await q06({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??rJ(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:k})=>bf({workspaceRoot:j},k),completionBuilder:L,updateService:N,workspaceRoot:j,listThreads:()=>O.listThreads(),getThreadFromServer:(k)=>O.getThread(k),toolboxes:B.toolboxService.toolboxes,isInternalUser:I,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:w,setActiveThreadID:(k)=>B.activeThread$.next(k),dispose:()=>{return w.dispose(),N.dispose(),B.asyncDispose()}},{initialThreadIDs:U?[U]:Z,initialUserInput:J||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?w76:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!U,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function e25(A,Q,$,B,D){let J=process.hrtime.bigint(),F=($0,P0)=>{let Q0=Number(process.hrtime.bigint()-P0)/1e6,M0=Ys0();P.info("Startup phase",{phase:$0,phaseMs:Math.round(Q0),sinceMainMs:M0===null?void 0:Math.round(M0)})},{userInput:Y,stdinInput:E}=await L76(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;O76({...Q,streamJson:Z},A.executeMode,Y),s8($,Q);let U=process.hrtime.bigint(),X=D?.dependencies??await n2(A,Q),G=X.hasAPIKeyAtStartup,V=X.serverStatus==="pending";if(P.info("Interactive auth startup mode",{deferInteractiveAuth:V,hasAPIKeyAtStartup:G,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!D)F("runMainThread:createThreadDependencies",U);let{serverStatus:K}=X;if(!V&&lE(K))throw Ne(K,A.ampURL);let z=e6(K)?K:null,W=z?.user.email,I=!!(W&&p7(W));if(I)vY0();if(!V)await UQ1($,Q,K);let H=TW(K),q=H?.features??[],N=H?.team??null,w=Ux(Q,H);if(w instanceof Error)P3(w.message);if(z&&!tM(Q.mode,W))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&P9(Q.threadId)?Q.threadId:void 0;U=process.hrtime.bigint();let L=await Xz0(X);F("runMainThread:createWorkerDeps",U);let j=A.executeMode?void 0:async($0)=>we($0,"interactive"),k={threadService:X.threadService,workerDeps:L,createThread:async($0)=>{let P0=V?await X.serverStatusPromise:K,Q0=await Qo(A.settings,process.cwd(),TW(P0),w);if(Q0 instanceof Error)P3(Q0.message);return y91(L,{threadMeta:Q0,agentMode:$0??Q.mode,onFirstAssistantMessage:j})},validateThreadOwnership:async($0,P0)=>{if(P0?.nonBlockingOwnershipCheck){z76($0,X.configService,X.viewerUserIDPromise).catch((Q0)=>{if(Q0 instanceof n1){if(P0.onOwnershipError){P0.onOwnershipError(Q0,$0);return}kz(Q0,$0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await z76($0,X.configService,X.viewerUserIDPromise)}catch(Q0){if(Q0 instanceof n1)throw Q0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:j,handleError:kz},_=async()=>{try{return m56(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof n1)throw $0;throw await kz($0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(V){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let $0=await X.configService.getLatest(),P0=Yd($0),Q0=await e4.getUserFreeTierStatus({},{config:X.configService,signal:AbortSignal.timeout(P0)});if(Q0.ok)return P.info("User free tier status:",Q0),Q0.result;return}catch($0){P.error("Failed to fetch free tier status:",$0);return}})(),b=!A.executeMode?new Y21:null,v,y=null;if(b)v=b,y=(async()=>{let $0=V?await X.serverStatusPromise:X.serverStatus;if(lE($0))throw Ne($0,A.ampURL);await UQ1($,Q,$0);let P0=process.hrtime.bigint(),Q0=await _();if(F("runMainThread:createThreadPool",P0),b.attach(Q0),Y){let M0=await k1(Q0.threadHandles$);if(!M0)throw new n1("No active thread is available yet.",1);await M0.sendMessage({content:[{type:"text",text:Y}]})}})(),y.catch(async($0)=>{let P0=$0 instanceof Error?$0:Error(String($0));b.setInitError(P0),await kz($0,Q.threadId)});else U=process.hrtime.bigint(),v=await _(),F("runMainThread:createThreadPool",U);let c=Q.notifications!==void 0?Q.notifications:!A.executeMode;U=process.hrtime.bigint();let p=await X.configService.getLatest();if(F("runMainThread:configService.getLatest",U),U=process.hrtime.bigint(),R16({configService:X.configService,threadService:X.threadService,threadPool:v,config:p,useNotifications:c}),F("runMainThread:createLegacyTuiNotificationService",U),A.executeMode){p01(X.mcpService,A.settings);let $0=Ez0($,Q),P0=await oz(),Q0=O?$0:jZ0({agentMode:Q.mode,explicitEffort:$0,sessionState:P0}),M0={userInput:Y,stdinInput:E,dependencies:X,streamJson:Z,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:I,agentMode:Q.mode,reasoningEffort:Q0,labels:Q.label},n=await Ck4({threadPool:v,...M0});if(await we(n,"execute"),Q.archive)await X.threadService.archive(n,!0);await X.asyncDispose(),process.exit(0)}let g=!1,i=!1;if(Q.jetbrains||Q.ide){await x20();let $0=await oE({jetbrainsOnly:Q.jetbrains});if($0.length===0){if(Q.jetbrains)g=!await X.configService.get("jetbrains.skipInstall")}else if($0.length===1){let P0=$0[0];if(P0)r5.selectConfig(P0)}else i=!0}U=process.hrtime.bigint();let o=nE0("0.0.1779409185-ge486da",X.settingsStorage,{startDelayMs:3000});F("runMainThread:createUpdateService",U),U=process.hrtime.bigint();let A0=new OZ0(X.mcpService,A.settings.getWorkspaceRootPath());if(F("runMainThread:createMcpTrustHandler",U),Y&&A.executeMode){let $0=await k1(v.threadHandles$);if(!$0)throw new n1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:Y}]})}U=process.hrtime.bigint();let W0=await oz();F("runMainThread:loadSessionState",U),P.info("Loaded session state:",W0);let E0=Ez0($,Q),I0={...W0,launchCount:W0.launchCount+1,lastReasoningEffortByMode:E0?{...W0.lastReasoningEffortByMode,[Q.mode]:E0}:W0.lastReasoningEffortByMode};KQ(($0)=>({...$0,launchCount:$0.launchCount+1}));try{if(U=process.hrtime.bigint(),await A46({history:new mo,fuzzyServer:X.fuzzyServer,settingsStorage:X.settingsStorage,threadService:X.threadService,skillService:X.skillService,configService:X.configService,secretStorage:X.secretStorage,internalAPIClient:e4,threadPool:v,createSystemPromptDeps:async()=>C76(X),ideClient:r5,mcpService:X.mcpService,toolboxService:X.toolboxService,mcpTrustHandler:A0,updateService:o,pluginPlatform:X.pluginPlatform,pluginService:X.pluginService},{initialServerStatus:X.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:X.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:g,showIdePickerHint:i,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:u25,logFile:{path:B},sessionState:I0,freeTierStatusPromise:f,workspace:N??null,features:q,isInternalUser:I,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-22T00:24:20.009Z"},($0)=>new K21({...$0,threadPool:$0.threadPool},(P0)=>new S91({...P0,threadState:P0.threadState}))),F("runMainThread:mountApp-returned",U),y)await y}finally{await v.dispose().catch(($0)=>{P.error("Failed to dispose thread pool during shutdown",$0)})}await X.asyncDispose(),F("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function d3(A){if(P.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)H$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7308
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await p$4({get:async(Y)=>{if(Y!==Kc)return;try{let E=await N76(ZQ1,"utf-8");return JSON.parse(E).installationID}catch{return}},set:async(Y,E)=>{if(Y!==Kc)return;await O25(qe.dirname(ZQ1),{recursive:!0}),await j25(ZQ1,JSON.stringify({installationID:E},null,2),{mode:384})}},{clientType:"cli",platform:Q70()});a14(B);let D=await s06({...A,workspaceTrust:{current:!0,changes:Ed},getHook:process.env.AMP_URL?(Y,E)=>{if(Y==="url")return Promise.resolve(process.env.AMP_URL);return E()}:void 0});if(A.mcpConfig){let Y=await og4(A.mcpConfig);D=rg4(D,Y)}let J=qe.dirname(D.getSettingsFilePath());gu4(id,J),D=Ce1(D);let F=await D.get("url","admin")??await D.get("url","global");if(!F)F=n7;if(P.info("Resolved Amp URL",{ampURL:F,settingsFile:D.getSettingsFilePath(),workspaceRoot:D.getWorkspaceRootPath()}),!BH(F))P.info("Targeting custom Amp server",{ampURL:F});return{executeMode:Q,isTTY:$,ampURL:F,settings:D,secrets:l06(await t51(A,D))}}function A85(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let J=B.slice(2).replace(/-([a-z])/g,(Y,E)=>E.toUpperCase()),F=A[$+1];if(F&&!F.startsWith("--"))Q[J]=F,$++}}return Q}function Q85(A,Q){let $=A.includes("--headless")||A.some((D)=>D.startsWith("--headless=")),B=qe.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?P25:Ao));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function $85(){kv4();let A=A85(process.argv),Q=Q85(process.argv,A),$=gv4(Q);LY0("silent");let B=process.argv.includes("--no-color"),D=process.argv.includes("--color"),J=process.stdout.isTTY&&process.stderr.isTTY;if(B||!D&&!J)t0.level=0;if(T25(P),P.info("Starting Amp CLI.",{version:"0.0.1779409185-ge486da",buildTimestamp:"2026-05-22T00:24:20.009Z"}),process.platform==="win32"&&yj())ib4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new n1(d9.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await a25($).parseAsync(process.argv)}bu4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await $85().catch(kz)});async function B85(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"),Q3.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7306
+ Or pipe via stdin: echo "your message" | amp --execute`)}function o25(){c34([L20.parse({tool:"*",action:"allow"})]),W34({bypass:!0})}function r25(A){if(A.threadId&&!P9(A.threadId))delete A.threadId}async function Uz0(A,Q,$,B){if(Q.headless)return s25(A,Q,$);let D=await n2(A,Q),J=await D.serverStatusPromise,F=e6(J)&&Ce(J.features,S$.THREAD_ACTORS_TUI),Y=F&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await D.asyncDispose(),new n1("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!F)throw await D.asyncDispose(),new n1("--show-welcome is only available with the new Amp CLI feature flag",1);if(Y){let E=!A.executeMode&&await m25();return o25(),r25(Q),t25(A,Q,$,D,{showNpmMigrationWelcome:E})}else{if(Q.threadId&&P9(Q.threadId)){let E=await e4.getThreadLinkInfo({thread:Q.threadId},{config:D.configService}).catch(()=>null);if(E?.ok&&E.result.usesThreadActors)throw await D.asyncDispose(),new n1(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return e25(A,Q,$,B,{dependencies:D})}}async function s25(A,Q,$){let B=(I,H)=>{let q=Number(process.hrtime.bigint()-H)/1e6,N=Ys0();P.info("Startup phase",{phase:I,phaseMs:Math.round(q),sinceMainMs:N===null?void 0:Math.round(N)})};s8($,Q);let D=process.hrtime.bigint(),J=await n2(A,Q);B("runMainThread:createThreadDependencies",D);let{serverStatus:F}=J;if(lE(F))throw Ne(F,A.ampURL);let Y=e6(F)?F:null,E=Y?.user.email;await UQ1($,Q,F);let Z=TW(F),U=Ux(Q,Z);if(U instanceof Error)P3(U.message);if(Y&&!tM(Q.mode,E))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!E||!p7(E)))throw new n1("Headless executor mode is only available for Amp employees",1);vY0();let G=await J.secretStorage.get("apiKey",A.ampURL);if(!G)throw new n1("API key required for headless mode. Please run `amp login` first.",1);let V=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(V&&!P9(V))throw new n1(`Invalid thread ID: ${V}`,1);let K=V?void 0:await z85({dependencies:J,apiKey:G,visibility:U??void 0}),z=V??K?.threadId;if(!z)throw new n1("Failed to resolve headless thread ID",1);let W=await $b4(z);if(W.status==="already-running")await J.asyncDispose(),await Tz(),process.exit(0);try{await nx4({ampURL:A.ampURL,apiKey:G,workspaceRoot:process.cwd(),threadId:z,ownerUserId:K?.ownerUserId,threadVersion:K?.threadVersion,agentMode:K?.agentMode,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized,J.pluginService.initialized]).then(()=>{return}),configService:J.configService,mcpService:J.mcpService,toolService:J.toolService,skillService:J.skillService,pluginService:J.pluginService,pluginPlatform:J.headlessPluginPlatform})}finally{await W.release(),await J.asyncDispose()}await Tz(),process.exit(0)}async function t25(A,Q,$,B,D){let{userInput:J,stdinInput:F}=await L76(Q),Y=!!Q.streamJson||!!Q.streamJsonThinking;O76({...Q,streamJson:Y},A.executeMode,J),s8($,Q),hv4(),vY0();let E=Q.threadId,Z=Q.resumeThreadIDs??(E?[E]:[]),U=Q.observe?S8(Q.observe)??JB(Q.observe):void 0,X=await B.serverStatusPromise;if(lE(X))throw Ne(X,A.ampURL);let G=TW(X),V=Ux(Q,G);if(V instanceof Error)P3(V.message);let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let q=await Qo(A.settings,process.cwd(),G,V);if(q instanceof Error)P3(q.message);return q})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new n1("API key required. Please run `amp login` first.",1);let I=e6(X)&&p7(X.user.email);if(A.executeMode){if(Z.length>1)throw new n1("Execute mode can only resume one thread.",1);p01(B.mcpService,A.settings);try{let H=Ez0($,Q),q=await oz(),N=E?H:jZ0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),w=E?void 0:RZ0(await By(B.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),O=E?void 0:await z(),L=await ux4({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:J,stdinInput:F,stats:!!Q.stats,streamJson:Y,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:E,initialThreadMeta:O,initialSettings:w});if(await we(L,"execute"),Q.archive)await B.threadService.archive(L,!0)}finally{await B.asyncDispose()}await Tz(),process.exit(0)}else{let H=Ez0($,Q),q=D.showNpmMigrationWelcome?"npm-migration":"intro",N=nE0("0.0.1779426990-g24af9a",B.settingsStorage,{startDelayMs:3000}),w=new OZ0(B.mcpService,A.settings.getWorkspaceRootPath()),O=Ji(B.configService),L=new yt(B.fuzzyServer),j=process.cwd();await q06({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??rJ(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:k})=>bf({workspaceRoot:j},k),completionBuilder:L,updateService:N,workspaceRoot:j,listThreads:()=>O.listThreads(),getThreadFromServer:(k)=>O.getThread(k),toolboxes:B.toolboxService.toolboxes,isInternalUser:I,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:w,setActiveThreadID:(k)=>B.activeThread$.next(k),dispose:()=>{return w.dispose(),N.dispose(),B.asyncDispose()}},{initialThreadIDs:U?[U]:Z,initialUserInput:J||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?w76:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!U,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function e25(A,Q,$,B,D){let J=process.hrtime.bigint(),F=($0,P0)=>{let Q0=Number(process.hrtime.bigint()-P0)/1e6,M0=Ys0();P.info("Startup phase",{phase:$0,phaseMs:Math.round(Q0),sinceMainMs:M0===null?void 0:Math.round(M0)})},{userInput:Y,stdinInput:E}=await L76(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;O76({...Q,streamJson:Z},A.executeMode,Y),s8($,Q);let U=process.hrtime.bigint(),X=D?.dependencies??await n2(A,Q),G=X.hasAPIKeyAtStartup,V=X.serverStatus==="pending";if(P.info("Interactive auth startup mode",{deferInteractiveAuth:V,hasAPIKeyAtStartup:G,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!D)F("runMainThread:createThreadDependencies",U);let{serverStatus:K}=X;if(!V&&lE(K))throw Ne(K,A.ampURL);let z=e6(K)?K:null,W=z?.user.email,I=!!(W&&p7(W));if(I)vY0();if(!V)await UQ1($,Q,K);let H=TW(K),q=H?.features??[],N=H?.team??null,w=Ux(Q,H);if(w instanceof Error)P3(w.message);if(z&&!tM(Q.mode,W))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&P9(Q.threadId)?Q.threadId:void 0;U=process.hrtime.bigint();let L=await Xz0(X);F("runMainThread:createWorkerDeps",U);let j=A.executeMode?void 0:async($0)=>we($0,"interactive"),k={threadService:X.threadService,workerDeps:L,createThread:async($0)=>{let P0=V?await X.serverStatusPromise:K,Q0=await Qo(A.settings,process.cwd(),TW(P0),w);if(Q0 instanceof Error)P3(Q0.message);return y91(L,{threadMeta:Q0,agentMode:$0??Q.mode,onFirstAssistantMessage:j})},validateThreadOwnership:async($0,P0)=>{if(P0?.nonBlockingOwnershipCheck){z76($0,X.configService,X.viewerUserIDPromise).catch((Q0)=>{if(Q0 instanceof n1){if(P0.onOwnershipError){P0.onOwnershipError(Q0,$0);return}kz(Q0,$0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await z76($0,X.configService,X.viewerUserIDPromise)}catch(Q0){if(Q0 instanceof n1)throw Q0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:j,handleError:kz},_=async()=>{try{return m56(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof n1)throw $0;throw await kz($0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(V){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let $0=await X.configService.getLatest(),P0=Yd($0),Q0=await e4.getUserFreeTierStatus({},{config:X.configService,signal:AbortSignal.timeout(P0)});if(Q0.ok)return P.info("User free tier status:",Q0),Q0.result;return}catch($0){P.error("Failed to fetch free tier status:",$0);return}})(),b=!A.executeMode?new Y21:null,v,y=null;if(b)v=b,y=(async()=>{let $0=V?await X.serverStatusPromise:X.serverStatus;if(lE($0))throw Ne($0,A.ampURL);await UQ1($,Q,$0);let P0=process.hrtime.bigint(),Q0=await _();if(F("runMainThread:createThreadPool",P0),b.attach(Q0),Y){let M0=await k1(Q0.threadHandles$);if(!M0)throw new n1("No active thread is available yet.",1);await M0.sendMessage({content:[{type:"text",text:Y}]})}})(),y.catch(async($0)=>{let P0=$0 instanceof Error?$0:Error(String($0));b.setInitError(P0),await kz($0,Q.threadId)});else U=process.hrtime.bigint(),v=await _(),F("runMainThread:createThreadPool",U);let c=Q.notifications!==void 0?Q.notifications:!A.executeMode;U=process.hrtime.bigint();let p=await X.configService.getLatest();if(F("runMainThread:configService.getLatest",U),U=process.hrtime.bigint(),R16({configService:X.configService,threadService:X.threadService,threadPool:v,config:p,useNotifications:c}),F("runMainThread:createLegacyTuiNotificationService",U),A.executeMode){p01(X.mcpService,A.settings);let $0=Ez0($,Q),P0=await oz(),Q0=O?$0:jZ0({agentMode:Q.mode,explicitEffort:$0,sessionState:P0}),M0={userInput:Y,stdinInput:E,dependencies:X,streamJson:Z,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:I,agentMode:Q.mode,reasoningEffort:Q0,labels:Q.label},n=await Ck4({threadPool:v,...M0});if(await we(n,"execute"),Q.archive)await X.threadService.archive(n,!0);await X.asyncDispose(),process.exit(0)}let g=!1,i=!1;if(Q.jetbrains||Q.ide){await x20();let $0=await oE({jetbrainsOnly:Q.jetbrains});if($0.length===0){if(Q.jetbrains)g=!await X.configService.get("jetbrains.skipInstall")}else if($0.length===1){let P0=$0[0];if(P0)r5.selectConfig(P0)}else i=!0}U=process.hrtime.bigint();let o=nE0("0.0.1779426990-g24af9a",X.settingsStorage,{startDelayMs:3000});F("runMainThread:createUpdateService",U),U=process.hrtime.bigint();let A0=new OZ0(X.mcpService,A.settings.getWorkspaceRootPath());if(F("runMainThread:createMcpTrustHandler",U),Y&&A.executeMode){let $0=await k1(v.threadHandles$);if(!$0)throw new n1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:Y}]})}U=process.hrtime.bigint();let W0=await oz();F("runMainThread:loadSessionState",U),P.info("Loaded session state:",W0);let E0=Ez0($,Q),I0={...W0,launchCount:W0.launchCount+1,lastReasoningEffortByMode:E0?{...W0.lastReasoningEffortByMode,[Q.mode]:E0}:W0.lastReasoningEffortByMode};KQ(($0)=>({...$0,launchCount:$0.launchCount+1}));try{if(U=process.hrtime.bigint(),await A46({history:new mo,fuzzyServer:X.fuzzyServer,settingsStorage:X.settingsStorage,threadService:X.threadService,skillService:X.skillService,configService:X.configService,secretStorage:X.secretStorage,internalAPIClient:e4,threadPool:v,createSystemPromptDeps:async()=>C76(X),ideClient:r5,mcpService:X.mcpService,toolboxService:X.toolboxService,mcpTrustHandler:A0,updateService:o,pluginPlatform:X.pluginPlatform,pluginService:X.pluginService},{initialServerStatus:X.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:X.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:g,showIdePickerHint:i,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:u25,logFile:{path:B},sessionState:I0,freeTierStatusPromise:f,workspace:N??null,features:q,isInternalUser:I,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-22T05:21:19.350Z"},($0)=>new K21({...$0,threadPool:$0.threadPool},(P0)=>new S91({...P0,threadState:P0.threadState}))),F("runMainThread:mountApp-returned",U),y)await y}finally{await v.dispose().catch(($0)=>{P.error("Failed to dispose thread pool during shutdown",$0)})}await X.asyncDispose(),F("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function d3(A){if(P.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)H$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7307
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await p$4({get:async(Y)=>{if(Y!==Kc)return;try{let E=await N76(ZQ1,"utf-8");return JSON.parse(E).installationID}catch{return}},set:async(Y,E)=>{if(Y!==Kc)return;await O25(qe.dirname(ZQ1),{recursive:!0}),await j25(ZQ1,JSON.stringify({installationID:E},null,2),{mode:384})}},{clientType:"cli",platform:Q70()});a14(B);let D=await s06({...A,workspaceTrust:{current:!0,changes:Ed},getHook:process.env.AMP_URL?(Y,E)=>{if(Y==="url")return Promise.resolve(process.env.AMP_URL);return E()}:void 0});if(A.mcpConfig){let Y=await og4(A.mcpConfig);D=rg4(D,Y)}let J=qe.dirname(D.getSettingsFilePath());gu4(id,J),D=Ce1(D);let F=await D.get("url","admin")??await D.get("url","global");if(!F)F=n7;if(P.info("Resolved Amp URL",{ampURL:F,settingsFile:D.getSettingsFilePath(),workspaceRoot:D.getWorkspaceRootPath()}),!BH(F))P.info("Targeting custom Amp server",{ampURL:F});return{executeMode:Q,isTTY:$,ampURL:F,settings:D,secrets:l06(await t51(A,D))}}function A85(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let J=B.slice(2).replace(/-([a-z])/g,(Y,E)=>E.toUpperCase()),F=A[$+1];if(F&&!F.startsWith("--"))Q[J]=F,$++}}return Q}function Q85(A,Q){let $=A.includes("--headless")||A.some((D)=>D.startsWith("--headless=")),B=qe.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?P25:Ao));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function $85(){kv4();let A=A85(process.argv),Q=Q85(process.argv,A),$=gv4(Q);LY0("silent");let B=process.argv.includes("--no-color"),D=process.argv.includes("--color"),J=process.stdout.isTTY&&process.stderr.isTTY;if(B||!D&&!J)t0.level=0;if(T25(P),P.info("Starting Amp CLI.",{version:"0.0.1779426990-g24af9a",buildTimestamp:"2026-05-22T05:21:19.350Z"}),process.platform==="win32"&&yj())ib4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new n1(d9.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await a25($).parseAsync(process.argv)}bu4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await $85().catch(kz)});async function B85(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"),Q3.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7309
7308
  `);else if(!BH(A.ampURL))Q3.write(`Logging in to ${new URL(A.ampURL).hostname}
7310
7309
  `);let B=process.env.AMP_API_KEY;if(B)Q3.write(`API key found in environment variable, storing...
7311
7310
  `),await Q.set("apiKey",B,A.ampURL),Q3.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1779409185-ge486da",
3
+ "version": "0.0.1779426990-g24af9a",
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.1779409185-ge486da"
11
+ "@ampcode/cli": "0.0.1779426990-g24af9a"
12
12
  },
13
13
  "files": [
14
14
  "dist/main.js",