@sourcegraph/amp 0.0.1779040962-g094dfb → 0.0.1779063447-g094dfb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +10 -10
  2. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -5354,12 +5354,12 @@ ${z}`))}},error:(E)=>{if(!K)K=!0,D(Error(`Failed to spawn brew: ${E.message}`))}
5354
5354
  ${z}`;if(Z==="pnpm"&&z.includes("Unable to find the global bin directory"))W+=`
5355
5355
 
5356
5356
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
5357
- npm install -g ${Y}`;D(Error(W))}},error:(E)=>{if(!U)U=!0,D(Error(`Failed to spawn ${Z}: ${E.message}`))},complete:()=>{if(!U)U=!0,X()}})})}c0();c0();Az();var Rq5="@ampcode/cli";async function cF0(A,Q,B=Rq5){let J=`${Q||"https://registry.npmjs.org"}/${B}/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=zo(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],z=X.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(z)K=Math.floor((W-new Date(z).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(F){return j.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var Pq5="https://static.ampcode.com/cli/cli-version.txt";async function lF0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${Pq5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=zo(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var _q5=604800000;function Ix4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>_q5)return{ageMs:B};return null}function zo(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function Wo(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let B=parseInt(Q[1],10),$=B!==0?B*1000:void 0,Y=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],Z=$!==void 0?EF($):void 0;return{sha:Y,timestamp:$,age:Z}}catch{return null}}R1();c0();import{readFile as Tq5,realpath as kq5}from"node:fs/promises";import{dirname as wx4,join as Sq5}from"node:path";async function Cx4(A){switch(A){case"binary":case"brew":return vq5(Ko());case"npm":case"pnpm":case"yarn":case"bun":return yq5()}}async function vq5(A){let Q=await JI(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function yq5(){try{let A=process.argv[1];if(!A)return null;let Q=await kq5(A),B=wx4(wx4(Q));return await fq5(Sq5(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function fq5(A){let Q=await Tq5(A,"utf8"),B=JSON.parse(Q);if(!B.name||!wt0(B.name))return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}c0();import{spawn as xq5}from"node:child_process";function Pt0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return j.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var iF0=null,Ho=null;function Mx4(A){return new Promise((Q)=>{let B=xq5("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),$="";B.stdout.on("data",(J)=>{$+=J.toString()}),B.on("close",(J,Y)=>{if(J!==0||Y==="SIGTERM"){Q(null);return}let Z=$.trim();Q(Z&&Z!=="undefined"?Z:null)}),B.on("error",()=>{Q(null)})})}async function nF0(){if(iF0)return iF0;if(Ho)return Ho;Ho=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return Pt0(A);let Q=await Mx4("@sourcegraph:registry");if(Q)return Pt0(Q);let B=await Mx4("registry");if(B)return Pt0(B);return"https://registry.npmjs.org"})();try{return iF0=await Ho,iF0}finally{Ho=null}}var bq5=3600000,uq5=5000;function aF0(A,Q,B={}){let $=new m4,J=$.pipe(oA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??bq5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=j.getChild("update");if(Y>0){if(await nV(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await hq5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await nV(uq5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let z=Math.min(K,E);await nV(z),E-=z}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function hq5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await IU(),F=Z==="binary"||Z==="brew",X=F?void 0:await YI();B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F,npmPackageName:X});let D;if(F)D=await lF0(A);else{let U=await nF0();D=await cF0(A,U,X)}if(!(D.latestVersion&&D.hasUpdate))return B.debug("no update available"),J;let G=(U)=>{$.next(U),J.emittedVisibleState=!0};if(Z){let U=await Cx4(Z);if(U&&zo(U,D.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:U,latestVersion:D.latestVersion}),J.updatedTo=U,zo(A,U)<0){let K=await Rz(U),E={from:A,to:U,externallyUpdated:!0,...K};if(K.status==="same")B.info("on-disk already updated by another instance",E),G("updated");else B.warn("on-disk already updated by another instance, with PATH warning",E),G("updated-with-warning")}return J}}let V=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let U=D.currentVersionAge-D.latestVersionAge,K=0.5;if(Math.abs(U)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:U}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!V())G("update-available-brew");return J}if(Z==="binary"&&process.execPath!==Ko()){if(B.debug("non-standard binary path, showing warning"),!V())G("update-available-unrecognized-path");return J}if(Y==="warn"){if(!V())G("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!V())G("update-available");return J}try{await Eo(D.latestVersion,Z),J.updatedTo=D.latestVersion;let U=await Rz(D.latestVersion),K={from:D.currentVersion,to:D.latestVersion,...U};if(U.status==="same")B.info("success",K),G("updated");else B.warn("success with warning",K),G("updated-with-warning")}catch(U){G("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}Az();import{stderr as RD}from"node:process";function Lx4(A){let Q=new uN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async($)=>{await Nt0($.force||!1,$.verbose||!1,"0.0.1779040962-g094dfb"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new uN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async($)=>{await mq5($.targetVersion)});A.addCommand(B)}function gq5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
5357
+ npm install -g ${Y}`;D(Error(W))}},error:(E)=>{if(!U)U=!0,D(Error(`Failed to spawn ${Z}: ${E.message}`))},complete:()=>{if(!U)U=!0,X()}})})}c0();c0();Az();var Rq5="@ampcode/cli";async function cF0(A,Q,B=Rq5){let J=`${Q||"https://registry.npmjs.org"}/${B}/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=zo(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],z=X.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(z)K=Math.floor((W-new Date(z).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(F){return j.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var Pq5="https://static.ampcode.com/cli/cli-version.txt";async function lF0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${Pq5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=zo(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var _q5=604800000;function Ix4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>_q5)return{ageMs:B};return null}function zo(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function Wo(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let B=parseInt(Q[1],10),$=B!==0?B*1000:void 0,Y=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],Z=$!==void 0?EF($):void 0;return{sha:Y,timestamp:$,age:Z}}catch{return null}}R1();c0();import{readFile as Tq5,realpath as kq5}from"node:fs/promises";import{dirname as wx4,join as Sq5}from"node:path";async function Cx4(A){switch(A){case"binary":case"brew":return vq5(Ko());case"npm":case"pnpm":case"yarn":case"bun":return yq5()}}async function vq5(A){let Q=await JI(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function yq5(){try{let A=process.argv[1];if(!A)return null;let Q=await kq5(A),B=wx4(wx4(Q));return await fq5(Sq5(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function fq5(A){let Q=await Tq5(A,"utf8"),B=JSON.parse(Q);if(!B.name||!wt0(B.name))return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}c0();import{spawn as xq5}from"node:child_process";function Pt0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return j.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var iF0=null,Ho=null;function Mx4(A){return new Promise((Q)=>{let B=xq5("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),$="";B.stdout.on("data",(J)=>{$+=J.toString()}),B.on("close",(J,Y)=>{if(J!==0||Y==="SIGTERM"){Q(null);return}let Z=$.trim();Q(Z&&Z!=="undefined"?Z:null)}),B.on("error",()=>{Q(null)})})}async function nF0(){if(iF0)return iF0;if(Ho)return Ho;Ho=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return Pt0(A);let Q=await Mx4("@sourcegraph:registry");if(Q)return Pt0(Q);let B=await Mx4("registry");if(B)return Pt0(B);return"https://registry.npmjs.org"})();try{return iF0=await Ho,iF0}finally{Ho=null}}var bq5=3600000,uq5=5000;function aF0(A,Q,B={}){let $=new m4,J=$.pipe(oA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??bq5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=j.getChild("update");if(Y>0){if(await nV(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await hq5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await nV(uq5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let z=Math.min(K,E);await nV(z),E-=z}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function hq5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await IU(),F=Z==="binary"||Z==="brew",X=F?void 0:await YI();B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F,npmPackageName:X});let D;if(F)D=await lF0(A);else{let U=await nF0();D=await cF0(A,U,X)}if(!(D.latestVersion&&D.hasUpdate))return B.debug("no update available"),J;let G=(U)=>{$.next(U),J.emittedVisibleState=!0};if(Z){let U=await Cx4(Z);if(U&&zo(U,D.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:U,latestVersion:D.latestVersion}),J.updatedTo=U,zo(A,U)<0){let K=await Rz(U),E={from:A,to:U,externallyUpdated:!0,...K};if(K.status==="same")B.info("on-disk already updated by another instance",E),G("updated");else B.warn("on-disk already updated by another instance, with PATH warning",E),G("updated-with-warning")}return J}}let V=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let U=D.currentVersionAge-D.latestVersionAge,K=0.5;if(Math.abs(U)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:U}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!V())G("update-available-brew");return J}if(Z==="binary"&&process.execPath!==Ko()){if(B.debug("non-standard binary path, showing warning"),!V())G("update-available-unrecognized-path");return J}if(Y==="warn"){if(!V())G("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!V())G("update-available");return J}try{await Eo(D.latestVersion,Z),J.updatedTo=D.latestVersion;let U=await Rz(D.latestVersion),K={from:D.currentVersion,to:D.latestVersion,...U};if(U.status==="same")B.info("success",K),G("updated");else B.warn("success with warning",K),G("updated-with-warning")}catch(U){G("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}Az();import{stderr as RD}from"node:process";function Lx4(A){let Q=new uN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async($)=>{await Nt0($.force||!1,$.verbose||!1,"0.0.1779063447-g094dfb"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new uN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async($)=>{await mq5($.targetVersion)});A.addCommand(B)}function gq5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
5358
5358
  `),$=!1,B=0}function Y(Z){if(!Q)return;let F=Z.padEnd(B," ");A.write(`\r${F}`),$=!0,B=F.length}return{flushProgressLine:J,renderProgress:Y}}async function mq5(A){let B=process.platform==="win32"&&Hj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=gq5(RD);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")RD.write(s0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
5359
5359
 
5360
5360
  `));try{if(!A){RD.write(s0.blue(`Checking for updates...
5361
- `));let F=!1,X;if(Hj()){let D=await lF0("0.0.1779040962-g094dfb");F=D.hasUpdate,X=D.latestVersion}else{let D=await nF0(),G=await YI(),V=await cF0("0.0.1779040962-g094dfb",D,G);F=V.hasUpdate,X=V.latestVersion}if(!F){let D=Wo("0.0.1779040962-g094dfb"),G=D?.age?`released ${D.age} ago`:`built ${EF(new Date("2026-05-17T18:07:35.955Z"))} ago`;RD.write(s0.green(`✓ Amp is already up to date on version ${"0.0.1779040962-g094dfb"} (${G})
5362
- `));let V=await Rz("0.0.1779040962-g094dfb",B);if(V.warning)RD.write(`
5361
+ `));let F=!1,X;if(Hj()){let D=await lF0("0.0.1779063447-g094dfb");F=D.hasUpdate,X=D.latestVersion}else{let D=await nF0(),G=await YI(),V=await cF0("0.0.1779063447-g094dfb",D,G);F=V.hasUpdate,X=V.latestVersion}if(!F){let D=Wo("0.0.1779063447-g094dfb"),G=D?.age?`released ${D.age} ago`:`built ${EF(new Date("2026-05-18T00:22:34.106Z"))} ago`;RD.write(s0.green(`✓ Amp is already up to date on version ${"0.0.1779063447-g094dfb"} (${G})
5362
+ `));let V=await Rz("0.0.1779063447-g094dfb",B);if(V.warning)RD.write(`
5363
5363
  `+s0.yellow(V.warning)+`
5364
5364
  `);process.exit(0)}if(!X)RD.write(s0.yellow("[WARN] could not find latest version")),process.exit(0);A=X}RD.write(s0.blue(`Updating to version ${A}...
5365
5365
  `)),await Eo(A,void 0,(F)=>{$(),RD.write(s0.dim(`Running: ${F}
@@ -5785,7 +5785,7 @@ ${$}`).join(`
5785
5785
  `).length,J=new p({text:new C(A,new S({color:B}))});if($<=WG0)return J;return new U0({width:1/0,height:WG0,child:new u2({autofocus:!1,controller:Q,child:J})})}function ev5(){return new Map([[C1.key("PageUp"),new HG0],[C1.key("PageDown"),new I41],[C1.ctrl("u"),new HG0],[C1.shift("Home"),new w41],[C1.shift("End"),new C41]])}function Ay5(A,Q,B){return Math.max(Q,Math.min(A,B))}var M41=8,Ei4=1,zi4=M41-1;class L41 extends L4{}class O41 extends L4{}class qG0 extends L4{}class NG0 extends L4{}class j41 extends L4{}class R41 extends L4{}class P41 extends _0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new Wi4}}class Wi4 extends P0{messageScroll=new yA;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,B=Qy5(Q,this.messageScroll),$=By5(Q.options.message),J=$?new d4({actions:this.buildScrollActions(),child:new Z5({debugLabel:"NeoSelectDialogScrollShortcuts",shortcuts:Jy5(),child:B})}):B,Y=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if($)Y.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return Y.push({keys:["Esc"],label:"cancel"}),new wA({header:Q.options.title,minWidth:64,maxWidth:80,footer:Y,autofocus:!1,onDismiss:Q.onCancel,child:J})}buildScrollActions(){let A=(Q)=>{let B=Yy5(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo(B)};return new Map([[L41,new g1(()=>A(-Ei4))],[O41,new g1(()=>A(Ei4))],[qG0,new g1(()=>A(-zi4))],[NG0,new g1(()=>A(zi4))],[j41,new g1(()=>this.messageScroll.jumpTo(0))],[R41,new g1(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function Qy5(A,Q){let B=A.options.options.map((J)=>({value:J,label:J})),$=Math.max(0,B.findIndex((J)=>J.value===A.options.initialValue));return new G2({options:B,selectedIndex:$,body:$y5(A.options.message,Q),onSelect:(J)=>{if(J===null){A.onCancel();return}A.onSelect(J)},padding:K0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!1})}function By5(A){if(A===void 0)return!1;return A.split(`
5786
5786
  `).length>M41}function $y5(A,Q){if(A===void 0)return;let B=A.split(`
5787
5787
  `).length,$=Math.min(B,M41);return new U0({width:1/0,height:$,child:new u2({autofocus:!1,controller:Q,child:new p({text:new C(A)})})})}function Jy5(){return new Map([[C1.key("PageUp"),new qG0],[C1.key("PageDown"),new NG0],[C1.ctrl("u"),new qG0],[C1.ctrl("d"),new NG0],[C1.ctrl("y"),new L41],[C1.ctrl("e"),new O41],[C1.shift("Home"),new j41],[C1.shift("End"),new R41]])}function Yy5(A,Q,B){return Math.max(Q,Math.min(A,B))}class _41{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];statusItems=new Map;disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}hasBlockingDialog(){return this.activeDialog!==null}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];switch(A.kind){case"input":return[new Qs({key:new Tz(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 N41({key:new Tz(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)})];case"select":return[new P41({key:new Tz(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})]}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.neoContext.pluginPlatform;if(!A)return;A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.neoContext.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}clearPluginPlatformStatusHandlers(){let A=this.options.neoContext.pluginPlatform;if(!A)return;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null}subscribePluginCommands(){let A=this.options.neoContext.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let B=A.map(($)=>this.createPluginCommand($)).map(($)=>this.options.commandRegistry.register($));this.unregisterPluginCommands=()=>{for(let $ of B)$()}}showNewPluginErrorToasts(A){let Q=new Set;for(let B of A){if(B.status!=="error")continue;if(pd(B.errorMessage))continue;let $=`${B.uri.toString()}
5788
- ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter(($)=>$.status==="active").map(($)=>$.uri.toString())),B=[];for(let[$,J]of this.statusItems){if(Q.has(J.pluginURI))continue;B.push($)}if(B.length===0)return;this.updateStatusItemState(()=>{for(let $ of B)this.statusItems.delete($)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{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,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"input",options:A,resolve:Q})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(!1);return}this.enqueueDialog({kind:"confirm",options:A,resolve:Q})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"select",options:A,resolve:Q})})};createStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let $=this.statusItemKey(A,Q),J={pluginURI:A,id:Q};if(B!==void 0)J.value=B;this.statusItems.set($,J)})};updateStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:B})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[];for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}enqueueDialog(A){if(this.activeDialog){this.queuedDialogs.push(A);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveConfirmDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveSelectDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}var Zy5=48;class T41{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 sr({width:Zy5,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+o, relaunch, Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}c0();import{spawnSync as Fy5}from"node:child_process";import vI from"node:process";function Bs(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else H4.instance.stop()}function Hi4(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:vI.env.NODE_ENV==="development"&&vI.platform==="darwin"?C1.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,B,$)=>{$(),Bs(A)}}}function Xy5(A,Q){j.info("Relaunching Amp; threads will be resumed",{threadIDs:A});let{command:B,args:$}=Dy5(A),J=Fy5(B,$,{cwd:Q,env:vI.env,stdio:"inherit"});if(J.error)return j.error("Failed to relaunch Amp",{error:J.error}),1;return J.status??1}class k41{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{j.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 Xy5(this.requestedThreadIDs,A)}}function Dy5(A){let Q=A.length>0?["threads","continue",...A]:[],B=Vy5();if(B)return{command:B.command,args:[...B.args,...Q]};let $=vI.argv[1],J=$&&Gy5($)?[$]:[];return{command:vI.execPath,args:[...J,...Q]}}function Gy5(A){return A!==vI.execPath&&!A.startsWith("/$bunfs/")}function Vy5(){if(vI.env.NODE_ENV!=="development")return null;let A=vI.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=Uy5(A),B=Q[0];if(!B)return null;return{command:B,args:Q.slice(1)}}function Uy5(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every((B)=>typeof B==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var Ky5=18000000;class S41{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 B=(this.options.minimumOpenDurationMs??Ky5)-(Date.now()-this.openedAt);if(B>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},B),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>Bs(this.options))}}zl();s8();import{readFile as Ey5}from"node:fs/promises";import v41 from"node:os";function zy5(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function qi4(A,Q){try{return{path:Q,contents:vh0(await Ey5(A,"utf8"))}}catch{return null}}async function IG0(A,Q){let B=[],$=zy5(),J=await r4.getThread({thread:Q},{config:A.configService}),Y=J.ok?J.result.thread.data:null;B.push({path:`${$}/thread.json`,contents:JSON.stringify(BJ(Y),null,2)});let Z=await qi4(gy(Q),`${$}/logs/${Q}.log`);if(Z)B.push(Z);let F=await qi4(A.settingsFilePath,`${$}/settings/global.json`);if(F)B.push(F);let X=await IU()??"unknown",D=await r4.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1779040962-g094dfb",clientOS:`${v41.platform()} ${v41.release()} ${v41.arch()}`,installMethod:X}},{config:A.configService});if(!D.ok)throw Error(`Failed to submit report: ${D.error.message}`);return D.result.reportID}class y41{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}class wG0 extends w5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new f41(this.offstage)}updateRenderObject(A){if(A instanceof f41)A.offstage=this.offstage}}class f41 extends Y4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class $s{_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 x41 extends _0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Ni4}}class Ni4 extends P0{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 Mj,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new Mj,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new wG0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new c4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new wG0({key:$.key,offstage:!J,child:Y}))}return new BA({fit:"expand",children:Q})}}import Ii4 from"node:process";class u41 extends q1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=Wy5(Q);return new wA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:K0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new G5({items:Q,showBorder:!1,getLabel:($)=>{let J=b41($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",z=J.item.noun?.toLowerCase()??"";if(E!==z)return E<z?-1:1;return 0}let Z=dj($.item.verb.toLowerCase(),Y),F=dj(J.item.verb.toLowerCase(),Y);if(Z!==F)return F-Z;let X=dj(b41($.item),Y),D=dj(b41(J.item),Y);if(X!==D)return D-X;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=R0.of(J);return new p({text:new C($.status.reason,new S({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new wi4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class wi4 extends q1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=R0.of(Y),{colors:F,app:X}=Z,D=B?X.selectionBackground:void 0,G=B?X.selectionForeground:F.foreground,V=B?G:F.mutedForeground,U=new p({text:new C(Q.noun?.toLowerCase()??"",new S({color:V,dim:$||!B})),textAlign:"right"}),K=[new C(Q.verb.toLowerCase(),new S({color:G,bold:!0,dim:$}))];if($)K.push(new C(" (unavailable)",new S({color:G,dim:!0})));let E=p.spans(K),z=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)z.push({child:Hy5(Q.shortcut,Z,$)});return new Ci4({columns:z,padding:K0.horizontal(1),backgroundColor:D})}}function b41(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Wy5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,_4(B.noun)):Q},0)}function Hy5(A,Q,B){let{colors:$,app:J}=Q,Y=new S({color:$.mutedForeground,dim:B}),Z=[];for(let F of A.modifiers()){if(Z.length>0)Z.push(new C(" ",Y));Z.push(new C(qy5(F),new S({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new C(" ",Y));return Z.push(new C(Ny5(A),new S({color:J.keybind,bold:!0,dim:B}))),p.spans(Z)}function qy5(A){return A==="Meta"&&Ii4.platform==="darwin"?"Cmd":A}function Ny5(A){return A.meta&&Ii4.platform==="darwin"?A.key.toUpperCase():A.key}class Ci4 extends q1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let F=0;F<Q.length;F++){let X=Q[F];if(F>0&&B>0)Y.push(new U0({width:B}));if(X.fixedWidth!==void 0)Y.push(new U0({width:X.fixedWidth,child:X.child}));else if(X.expanded)Y.push(new T1({child:X.child}));else Y.push(X.child)}let Z=new t0({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new u0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class h41{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let B=this.findByID(A);if(!B||B.status.type!=="enabled")return!1;return B.run(new $s,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class z9 extends V6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=z9.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(z9)?.commandRegistry??null}}class g41 extends _0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Mi4}}class Mi4 extends P0{modalStack=new $s;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=z9.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=z9.of(A).commands,B=new u41({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new x41({root:B,controller:this.modalStack})}}var m41=[{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"]}]}],p41=[{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 CG0 extends q1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=s1.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[F,X]=this.renderRow(Z),D;if(J)D=new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[F,new f0({padding:K0.only({left:4}),child:X})]});else D=new t0({crossAxisAlignment:"start",children:[new T1({flex:1,child:F}),new U0({width:1}),new T1({flex:1,child:X})]});Y.push(new f0({padding:K0.horizontal(6),child:D}))}return new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class d41 extends _0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new Li4}}class Li4 extends P0{scrollController;initState(){this.scrollController=new yA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=L1.of(A).colorScheme,J=R0.of(A).app,Y=s1.of(A),Z=new S({color:B.primary,bold:!0}),F=new S({color:B.secondary,bold:!0}),X=new S({color:J.keybind}),D=new S({color:J.command}),G=new S({color:B.foreground}),V=new S({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,z=K-4,W=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((L)=>{let R=L.noun?.toLowerCase();return R!=="dev"&&R!=="debug"&&!L.id.startsWith("debug-")&&!H.has(L.id)})].sort((L,R)=>{let v=(L.noun??"").toLowerCase(),T=(R.noun??"").toLowerCase(),f=v.localeCompare(T);if(f!==0)return f;let g=L.verb.toLowerCase(),u=R.verb.toLowerCase(),k=g.localeCompare(u);if(k!==0)return k;return L.id.localeCompare(R.id)}),I=new fA({autofocus:!0,controller:this.scrollController,child:new u0({constraints:new M1(W,W,0,Number.POSITIVE_INFINITY),child:new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new Q4({child:new p({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5788
+ ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter(($)=>$.status==="active").map(($)=>$.uri.toString())),B=[];for(let[$,J]of this.statusItems){if(Q.has(J.pluginURI))continue;B.push($)}if(B.length===0)return;this.updateStatusItemState(()=>{for(let $ of B)this.statusItems.delete($)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{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,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"input",options:A,resolve:Q})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(!1);return}this.enqueueDialog({kind:"confirm",options:A,resolve:Q})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"select",options:A,resolve:Q})})};createStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let $=this.statusItemKey(A,Q),J={pluginURI:A,id:Q};if(B!==void 0)J.value=B;this.statusItems.set($,J)})};updateStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:B})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[];for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}enqueueDialog(A){if(this.activeDialog){this.queuedDialogs.push(A);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveConfirmDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveSelectDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}var Zy5=48;class T41{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 sr({width:Zy5,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+o, relaunch, Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}c0();import{spawnSync as Fy5}from"node:child_process";import vI from"node:process";function Bs(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else H4.instance.stop()}function Hi4(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:vI.env.NODE_ENV==="development"&&vI.platform==="darwin"?C1.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,B,$)=>{$(),Bs(A)}}}function Xy5(A,Q){j.info("Relaunching Amp; threads will be resumed",{threadIDs:A});let{command:B,args:$}=Dy5(A),J=Fy5(B,$,{cwd:Q,env:vI.env,stdio:"inherit"});if(J.error)return j.error("Failed to relaunch Amp",{error:J.error}),1;return J.status??1}class k41{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{j.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 Xy5(this.requestedThreadIDs,A)}}function Dy5(A){let Q=A.length>0?["threads","continue",...A]:[],B=Vy5();if(B)return{command:B.command,args:[...B.args,...Q]};let $=vI.argv[1],J=$&&Gy5($)?[$]:[];return{command:vI.execPath,args:[...J,...Q]}}function Gy5(A){return A!==vI.execPath&&!A.startsWith("/$bunfs/")}function Vy5(){if(vI.env.NODE_ENV!=="development")return null;let A=vI.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=Uy5(A),B=Q[0];if(!B)return null;return{command:B,args:Q.slice(1)}}function Uy5(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every((B)=>typeof B==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var Ky5=18000000;class S41{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 B=(this.options.minimumOpenDurationMs??Ky5)-(Date.now()-this.openedAt);if(B>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},B),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>Bs(this.options))}}zl();s8();import{readFile as Ey5}from"node:fs/promises";import v41 from"node:os";function zy5(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function qi4(A,Q){try{return{path:Q,contents:vh0(await Ey5(A,"utf8"))}}catch{return null}}async function IG0(A,Q){let B=[],$=zy5(),J=await r4.getThread({thread:Q},{config:A.configService}),Y=J.ok?J.result.thread.data:null;B.push({path:`${$}/thread.json`,contents:JSON.stringify(BJ(Y),null,2)});let Z=await qi4(gy(Q),`${$}/logs/${Q}.log`);if(Z)B.push(Z);let F=await qi4(A.settingsFilePath,`${$}/settings/global.json`);if(F)B.push(F);let X=await IU()??"unknown",D=await r4.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1779063447-g094dfb",clientOS:`${v41.platform()} ${v41.release()} ${v41.arch()}`,installMethod:X}},{config:A.configService});if(!D.ok)throw Error(`Failed to submit report: ${D.error.message}`);return D.result.reportID}class y41{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}class wG0 extends w5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new f41(this.offstage)}updateRenderObject(A){if(A instanceof f41)A.offstage=this.offstage}}class f41 extends Y4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class $s{_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 x41 extends _0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Ni4}}class Ni4 extends P0{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 Mj,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new Mj,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new wG0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new c4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new wG0({key:$.key,offstage:!J,child:Y}))}return new BA({fit:"expand",children:Q})}}import Ii4 from"node:process";class u41 extends q1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=Wy5(Q);return new wA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:K0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new G5({items:Q,showBorder:!1,getLabel:($)=>{let J=b41($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",z=J.item.noun?.toLowerCase()??"";if(E!==z)return E<z?-1:1;return 0}let Z=dj($.item.verb.toLowerCase(),Y),F=dj(J.item.verb.toLowerCase(),Y);if(Z!==F)return F-Z;let X=dj(b41($.item),Y),D=dj(b41(J.item),Y);if(X!==D)return D-X;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=R0.of(J);return new p({text:new C($.status.reason,new S({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new wi4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class wi4 extends q1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=R0.of(Y),{colors:F,app:X}=Z,D=B?X.selectionBackground:void 0,G=B?X.selectionForeground:F.foreground,V=B?G:F.mutedForeground,U=new p({text:new C(Q.noun?.toLowerCase()??"",new S({color:V,dim:$||!B})),textAlign:"right"}),K=[new C(Q.verb.toLowerCase(),new S({color:G,bold:!0,dim:$}))];if($)K.push(new C(" (unavailable)",new S({color:G,dim:!0})));let E=p.spans(K),z=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)z.push({child:Hy5(Q.shortcut,Z,$)});return new Ci4({columns:z,padding:K0.horizontal(1),backgroundColor:D})}}function b41(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Wy5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,_4(B.noun)):Q},0)}function Hy5(A,Q,B){let{colors:$,app:J}=Q,Y=new S({color:$.mutedForeground,dim:B}),Z=[];for(let F of A.modifiers()){if(Z.length>0)Z.push(new C(" ",Y));Z.push(new C(qy5(F),new S({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new C(" ",Y));return Z.push(new C(Ny5(A),new S({color:J.keybind,bold:!0,dim:B}))),p.spans(Z)}function qy5(A){return A==="Meta"&&Ii4.platform==="darwin"?"Cmd":A}function Ny5(A){return A.meta&&Ii4.platform==="darwin"?A.key.toUpperCase():A.key}class Ci4 extends q1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let F=0;F<Q.length;F++){let X=Q[F];if(F>0&&B>0)Y.push(new U0({width:B}));if(X.fixedWidth!==void 0)Y.push(new U0({width:X.fixedWidth,child:X.child}));else if(X.expanded)Y.push(new T1({child:X.child}));else Y.push(X.child)}let Z=new t0({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new u0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class h41{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let B=this.findByID(A);if(!B||B.status.type!=="enabled")return!1;return B.run(new $s,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class z9 extends V6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=z9.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(z9)?.commandRegistry??null}}class g41 extends _0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Mi4}}class Mi4 extends P0{modalStack=new $s;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=z9.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=z9.of(A).commands,B=new u41({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new x41({root:B,controller:this.modalStack})}}var m41=[{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"]}]}],p41=[{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 CG0 extends q1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=s1.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[F,X]=this.renderRow(Z),D;if(J)D=new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[F,new f0({padding:K0.only({left:4}),child:X})]});else D=new t0({crossAxisAlignment:"start",children:[new T1({flex:1,child:F}),new U0({width:1}),new T1({flex:1,child:X})]});Y.push(new f0({padding:K0.horizontal(6),child:D}))}return new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class d41 extends _0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new Li4}}class Li4 extends P0{scrollController;initState(){this.scrollController=new yA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=L1.of(A).colorScheme,J=R0.of(A).app,Y=s1.of(A),Z=new S({color:B.primary,bold:!0}),F=new S({color:B.secondary,bold:!0}),X=new S({color:J.keybind}),D=new S({color:J.command}),G=new S({color:B.foreground}),V=new S({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,z=K-4,W=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((L)=>{let R=L.noun?.toLowerCase();return R!=="dev"&&R!=="debug"&&!L.id.startsWith("debug-")&&!H.has(L.id)})].sort((L,R)=>{let v=(L.noun??"").toLowerCase(),T=(R.noun??"").toLowerCase(),f=v.localeCompare(T);if(f!==0)return f;let g=L.verb.toLowerCase(),u=R.verb.toLowerCase(),k=g.localeCompare(u);if(k!==0)return k;return L.id.localeCompare(R.id)}),I=new fA({autofocus:!0,controller:this.scrollController,child:new u0({constraints:new M1(W,W,0,Number.POSITIVE_INFINITY),child:new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new Q4({child:new p({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5789
5789
  `,Z)})}),new U0({height:1}),new f0({padding:K0.horizontal(2),child:new p({text:new C(`Editor Shortcuts
5790
5790
  `,F)})}),new CG0({items:m41.filter((L)=>L.submitOnEnterOnly===void 0||L.submitOnEnterOnly===this.widget.submitOnEnter),renderRow:(L)=>{let R=[];for(let T of L.methods){let f=this.buildCleanKeyCombination(T);R.push(f)}let v=R.join(", ");return[new p({text:new C(v,X)}),new p({text:new C(L.description,G)})]}}),new U0({height:1}),new f0({padding:K0.horizontal(2),child:new p({text:new C(`Scrolling & Navigation
5791
5791
  `,F)})}),new CG0({items:p41,renderRow:(L)=>{let R=[];for(let T of L.methods){let f=this.buildCleanKeyCombination(T);R.push(f)}let v=R.join(", ");return[new p({text:new C(v,X)}),new p({text:new C(L.description,G)})]}}),new U0({height:1}),new f0({padding:K0.horizontal(2),child:new p({text:new C(`Command Palette Commands
@@ -5875,7 +5875,7 @@ Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)g=this.widget.centerContent
5875
5875
  `))}return Z}function fh5(A,Q,B){let{colors:$,app:J}=B,Y=xh5(Q.status,B);if(A.push(new C(` ${Y.icon} `,new S({color:Y.color}))),A.push(new C(Q.name,new S({color:Q.status==="pending"?$.warning:J.command}))),Q.status==="pending")A.push(new C(" discovering...",new S({color:$.foreground,dim:!0})));else if(Q.description)A.push(new C(` ${Br4(Q.description,50)}`,new S({color:$.foreground,dim:!0})));if(Q.error)A.push(new C(` ${Br4(Q.error,40)}`,new S({color:J.toolError})));A.push(new C(`
5876
5876
  `))}function xh5(A,Q){let{colors:B,app:$}=Q;switch(A){case"pending":return{icon:"◌",color:B.warning};case"registered":return{icon:"•",color:B.mutedForeground};case"failed":return{icon:"✗",color:$.toolError};case"duplicate":return{icon:"◇",color:B.warning};default:return{icon:"?",color:B.foreground}}}function Br4(A,Q){let B=A.replace(/\s+/g," ").trim();if(_4(B)<=Q)return B;let $="...",J=_4($);if(Q<=J)return KJ($,Q);return`${KJ(B,Q-J,!0,"")}${$}`}var P61="https://ampcode.com/news/neo",_61=[{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:P61,href:P61},"","",{text:"Need old Amp for a bit? Use ",keybind:"amp --take-me-back"}]}];function bh5(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:P61,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function uh5(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var _x=50,ZR=40,j61=1000,hh5=420,gh5=760,mh5=-250,ph5=1100,tG0=33,Zr4=0.999,dh5=2.1,ch5=720,lh5=420,Er4="Meet the new",zr4="Amp",Wr4="CLI",T61=w4(Er4).length,ih5=w4(zr4).length,nh5=w4(Wr4).length,eG0={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},Fr4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},Xr4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},Dr4=[eG0,Fr4,Xr4,eG0,Fr4,Xr4,eG0],ah5=eG0;class k61 extends _0{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??uh5(),this.introStages=this.variant==="npm-migration"?bh5(this.binaryInstallCommand):_61,this.dismissible=this.variant!=="npm-migration"}createState(){return new Hr4}}class Hr4 extends P0{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=j61;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 u9(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=nY(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=Zr4,this.firstStageHintVisible=this.animationProgress>=Zr4,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:j61,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=nY(A/gh5);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},tG0)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let B=performance.now()-this.stageTransitionStartedAt,$=nY(B/hh5);if(this.setState(()=>{if(this.stageTransitionProgress=$,$>=1)this.previousIntroStage=null}),$>=1)this.stopStageTransitionTimer()},tG0)}startProgressAnimation({from:A,to:Q,durationMs:B,onComplete:$}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=B,this.onAnimationComplete=$,this.animationProgress=A,this.animationTimer=setInterval(()=>{let J=performance.now()-this.startedAt,Y=nY(J/this.animationDurationMs),Z=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*Tx(Y);if(this.setState(()=>{this.animationProgress=Z}),Y>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},tG0)}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,j61+mh5),Q=A+ph5;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?nY((A-this.firstStageTitleRevealStartedAt)/ch5):this.firstStageTitleRevealProgress,B=this.firstStageHintRevealStartedAt?nY((A-this.firstStageHintRevealStartedAt)/lh5):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=B}),Q>=1&&B>=1)this.stopFirstStageRevealTimer()},tG0)}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=Gr4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:Vr4(Gr4(this.previousIntroStage),A,Tx(this.stageTransitionProgress));return this.dismissProgress>0?Vr4(Q,ah5,Tx(this.dismissProgress)):Q}build(A){let Q=L1.of(A).colorScheme,B=R0.of(A),$=this.currentOrbPalette(),J=oQ(1,"frontier",$),Y=s1.of(A).size,F=this.widget.animationProgress??this.animationProgress,X=Math.max(Y.width/_x,Y.height/ZR)*dh5,D=X+(1-X)*F,G=Tx(this.dismissProgress),V=Math.max(_x,Math.round(_x*D)),U=Math.max(ZR,Math.round(ZR*D)),K=Math.round((Y.width-V)/2),E=Math.round((Y.height-U)/2),z=Math.max(0,Math.floor((Y.width-_x)/2)),W=-Math.floor(ZR/2),H=Math.round(K+(z-K)*F),q=Math.round(E+(W-E)*F),N=H+V/2,I=q+U/2,w=oh5({dismissProgress:this.dismissProgress,easedDismissProgress:G,introOrbScale:D,normalOrbCenterX:N,normalOrbCenterY:I,size:Y}),O=Math.max(_x,Math.round(_x*w.orbScale)),L=Math.max(ZR,Math.round(ZR*w.orbScale)),R=w.orbCenterX,v=w.orbCenterY,T=Math.round(R-O/2),f=Math.round(v-L/2),g=Math.max(3,Math.min(Y.height-5,Math.floor(ZR/2)+2)),u=Math.max(g+3,Y.height-3),k=w.textDissolveProgress,b=this.isFinalIntroStage()?w.backdropDissolveProgress:0,d=this.firstStageTitleVisible&&k<1,c=d&&this.firstStageHintVisible,h=c&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),i=this.introStage===0?this.firstStageTitleRevealProgress:1,r=this.introStage===0?this.firstStageHintRevealProgress:1,Q0=Math.max(24,Math.min(74,Y.width-4)),w0=Math.min(12,Math.max(8,Y.height-g-6)),X0=Math.max(0,Math.floor((Y.width-Q0)/2)),H0=Math.max(0,Math.min(Y.height-w0,Math.floor(Y.height*0.55-w0/2))),j0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new If({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new If({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new c4({autofocus:!0,canRequestFocus:!0,debugLabel:"NeoWelcomeTakeover",onKey:(B0)=>{if(B0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&B0.key==="c"&&B0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&B0.key==="q")return this.widget.onQuit?.(),"handled";if((B0.key===" "||B0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(B0.key==="Escape"||B0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(B0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(B0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new BA({fit:"expand",children:[new qr4({color:Q.background,dissolveProgress:b}),new BA({fit:"expand",children:[new _1({onClick:()=>{},child:U0.expand()}),new WA({left:T,top:f,width:O,height:L,child:j0}),...d?[new WA({left:X0,top:H0,width:Q0,height:w0,child:sh5({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:Q0,height:w0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:J,link:B.app.link,keybind:B.app.keybind,titleRevealProgress:i,dissolveProgress:k,context:A})})]:[],...c?[...h?[new WA({left:X0,top:Math.max(0,u-1),width:Q0,height:1,child:new p({text:$g5({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:k}),textAlign:"center"})})]:[],new WA({left:X0,top:u,width:Q0,height:1,child:Yg5({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:B.app.keybind,revealProgress:r,dissolveProgress:k,context:A})})]:[]]})]})})}}class qr4 extends V8{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new Nr4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class Nr4 extends Y4{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=Math.floor(this.size.width),Z=Math.floor(this.size.height),F={bg:this.color},X=nY(this.dissolveProgress);if(X<=0){A.fill($,J,Y,Z," ",F);return}if(X>=1)return;for(let D=0;D<Z;D++)for(let G=0;G<Y;G++)if(!rh5(G,D,Y,Z,X))A.fill($+G,J+D,1,1," ",F)}}function nY(A){return Math.min(1,Math.max(0,A))}function Tx(A){return 1-(1-A)**3}function Gr4(A){return Dr4[A]??Dr4[0]}function Vr4(A,Q,B){return{primary:Lj(A.primary,Q.primary,B),secondary:Lj(A.secondary,Q.secondary,B)}}function oh5({dismissProgress:A,easedDismissProgress:Q,introOrbScale:B,normalOrbCenterX:$,normalOrbCenterY:J,size:Y}){return{orbScale:B+(B*0.86-B)*Q,orbCenterX:$+(Y.width*0.54-$)*Q,orbCenterY:J-Y.height*0.44*Q,textDissolveProgress:nY(A/0.52),backdropDissolveProgress:Tx(nY((A-0.12)/0.88))}}function rh5(A,Q,B,$,J){let Y=$<=1?0:Q/($-1),Z=Ir4(A+Q*Math.max(1,B));return(1-Y)*0.72+Z*0.28<J}function sh5({introStages:A,stage:Q,previousStage:B,progress:$,direction:J,width:Y,height:Z,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E}){if(B===null||$>=1)return R61({introStages:A,stage:Q,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E});let z=Tx($),W=J*Math.round((1-z)*Y),H=-J*Math.round(z*Y);return new yz(new BA({fit:"expand",children:[new WA({left:H,top:0,width:Y,height:Z,child:R61({introStages:A,stage:B,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:B===0?1:U,dissolveProgress:K,context:E})}),new WA({left:W,top:0,width:Y,height:Z,child:R61({introStages:A,stage:Q,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E})})]}))}function R61({introStages:A,stage:Q,foreground:B,mutedForeground:$,accent:J,link:Y,keybind:Z,titleRevealProgress:F,dissolveProgress:X,context:D}){let G=A[Q]??A[0]??_61[0],V=new S({color:J,bold:!0}),U=new S({color:B}),K=A===_61&&Q===0,E=[...G.title===null?[]:[new p({text:K?AV0(Ag5({progress:F,foreground:J,pulseColor:J}),X):new C(F$(G.title,X),V),textAlign:"center"})],...G.body.length>0?[th5()]:[],...G.body.map((z)=>eh5(z,U,$,Y,Z,X,D))];return new Q4({child:new f0({padding:K0.horizontal(1),child:new y0({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:E})})})}function th5(){return U0.height(1)}function eh5(A,Q,B,$,J,Y,Z){if(typeof A==="string")return new p({text:new C(F$(A,Y),Q),textAlign:"center"});if("codeBlock"in A)return new X3({onCopy:(F,X)=>{if(X)u5.success(Z,"Copied to clipboard",2000)},child:new y0({mainAxisSize:"min",children:A.codeBlock.map((F)=>new p({text:new C(F$(F,Y),new S({color:J})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let F=new p({text:new C("",void 0,[new C(F$(A.text,Y),new S({color:B,dim:!0})),new C(F$(A.keybind,Y,w4(A.text).length),new S({color:J}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new Q4({child:new X3({child:F})});return F}if("highlightText"in A){let F=TA.createSpan(A.href,A.linkText,new S({color:$,underline:!0})),X=pD.of(Z),D=new C("",void 0,[new C(A.text,Q),new C(A.highlightText,new S({color:J})),new C(A.textAfterHighlight,Q),new C(F.text,F.style,F.children,F.hyperlink,()=>{lA(Z,A.href,{forceExternal:!1,onShowImagePreview:X})}),new C(A.textAfter,Q)]);return new p({text:AV0(D,Y),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new y0({mainAxisSize:"min",children:[new p({text:new C(F$(A.text,Y),Q),textAlign:"center"}),new Q4({child:new t0({mainAxisSize:"min",children:[TA.createWidget(Z,A.href,F$(A.linkText,Y),new S({color:$,underline:!0})),new p({text:new C(F$(A.textAfter,Y),Q)})]})})]});let F=TA.createSpan(A.href,A.linkText,new S({color:$,underline:!0})),X=pD.of(Z),D=new C("",void 0,[new C(A.text,Q),new C(F.text,F.style,F.children,F.hyperlink,()=>{lA(Z,A.href,{forceExternal:!1,onShowImagePreview:X})}),new C(A.textAfter,Q)]);return new p({text:AV0(D,Y),textAlign:"center"})}if(Y>0)return new p({text:new C(F$(A.text,Y),new S({color:$,underline:!0})),textAlign:"center"});return new Q4({child:TA.createWidget(Z,A.href,A.text,new S({color:$,underline:!0}))})}function Ag5({progress:A,foreground:Q,pulseColor:B}){let $=new S({color:Q,bold:!0}),J=new S({color:Bg5({progress:A,foreground:Q,pulseColor:B}),bold:!0});return new C("",void 0,[new C(Qg5(A).padEnd(T61," "),$),new C(" ",$),new C(Ur4(zr4,ih5,A,0.72),$),new C(" ",$),new C(Ur4(Wr4,nh5,A,0.88),J)])}function Qg5(A){let Q=w4(Er4),B=Math.min(T61,Math.ceil(nY(A/0.62)*T61));return Q.slice(0,B).join("")}function Ur4(A,Q,B,$){return B>=$?A:"".padEnd(Q," ")}function Bg5({progress:A,foreground:Q,pulseColor:B}){if(A<0.88||A>=1)return Q;let $=nY((A-0.88)/0.12);return Math.cos($*Math.PI*4)*(1-$)>0.12?B:Q}function $g5({stage:A,featureStageCount:Q,foreground:B,dissolveProgress:$}){return new C(F$(`${A}/${Q}`,$),new S({color:B,dim:!0}))}function Jg5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y}){let Z=new S({color:$}),F=new S({color:B,dim:!0}),X=Q?A?"Enter":"Space":"Esc",D=Q?A?" to get started":" to continue":" to quit, or use ",G=Q?"":"amp --take-me-back",V=Q?"":" to use the old version",U=`${D}${G}${V}`;if(!Q)return new C("",void 0,[new C(X,Z),new C(D,F),new C(G,Z),new C(V,F)]);let K=Kr4(X,J),E=Kr4(U,nY((J*(w4(X).length+w4(U).length)-w4(X).length)/w4(U).length));return new C("",void 0,[new C(F$(K,Y),Z),new C(F$(E.slice(0,D.length),Y),F),new C(F$(E.slice(D.length,D.length+G.length),Y),Z),new C(F$(E.slice(D.length+G.length),Y),F)])}function Yg5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y,context:Z}){if(Q)return new p({text:Jg5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y}),textAlign:"center"});let F=new S({color:$}),X=new S({color:B,dim:!0});return new X3({onCopy:(D,G)=>{if(G)u5.success(Z,"Copied to clipboard",2000)},child:new p({text:new C("",void 0,[new C("q",F),new C(" to quit, or use ",X),new C("amp --take-me-back",F),new C(" to use the old version",X)]),textAlign:"center",selectable:!0})})}function Kr4(A,Q){let B=w4(A),$=Math.min(B.length,Math.ceil(nY(Q)*B.length));return B.slice(0,$).join("").padEnd(B.length," ")}function AV0(A,Q,B=0){if(Q<=0)return A;let $=B+w4(A.text??"").length,J=A.children?.map((Y)=>{let Z=AV0(Y,Q,$);return $+=w4(Y.toPlainText()).length,Z});return new C(A.text?F$(A.text,Q,B):A.text,A.style,J,A.hyperlink,A.onClick)}function F$(A,Q,B=0){if(Q<=0)return A;return w4(A).map((J,Y)=>{if(J.trim()==="")return J;return Ir4(B+Y)<Q?" ":J}).join("")}function Ir4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}c0();s8();function dI(A,Q){let{colors:B,dim:$}=Q,J=[];if(A.totalCostUSD===null)return J;let Y=A.costBreakdown,Z=Y?.freeUSD??0,F=Y?.paidUSD??0;if(Z===0&&F===0)return J;let D={decimalPlaces:"more-if-tiny",intent:"cost"};if(F===0)J.push(new C(uU(Z,D),new S({color:B.foreground,dim:$}))),J.push(new C(" (free)",new S({color:B.foreground,dim:$})));else if(Z>0)J.push(new C(uU(Z,D),new S({color:B.foreground,dim:$}))),J.push(new C(" (free)",new S({color:B.foreground,dim:$}))),J.push(new C(" + ",new S({color:B.foreground,dim:$}))),J.push(new C(uU(F,D),new S({color:B.foreground,dim:$,bold:!$})));else J.push(new C(uU(F,D),new S({color:B.foreground,dim:$,bold:!$})));return J}class S61 extends L4{}class v61 extends L4{}function Zg5(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 Fg5(A,Q){let B=R0.of(Q),{colors:$}=B,J=dI(A,{colors:{foreground:$.foreground}}),Y=[];if(J.length>0)Y.push(new C("Total: ",new S({color:$.mutedForeground}))),Y.push(...J);else if(A.totalCostUSD===null)Y.push(new C("Usage information is currently unavailable."));else Y.push(new C("No usage recorded for this thread yet."));if(A.costBreakdownURL)Y.push(new C(`
5877
5877
 
5878
- `)),Y.push(new C("Details: ",new S({color:$.mutedForeground}))),Y.push(new C(A.costBreakdownURL,new S({color:B.app.link})));return new p({text:new C("",void 0,Y)})}function Xg5(A,Q,B){let $=Fg5(A,Q);if(!A.costBreakdownURL)return new wA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new g1(()=>{return d4.maybeInvoke(Q,new p9(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new g1(()=>{return lA(Q,J),"handled"});return new wA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new d4({actions:new Map([[S61,Y],[v61,Z]]),child:new Z5({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[C1.key("o"),new v61],[C1.key("y"),new S61]]),child:new g4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function wr4(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await r4.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(Zg5(J,Y.error),"error",5000),$();return}Q.push(Xg5(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}class y61 extends _0{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 Mr4}}class Mr4 extends P0{editorController=new P8;commandPalette=new oe0(this);commandRegistry=new h41;toastController=new A01;relaunchNotificationController=new T41;exitHintTimer=new eo(this,1000);ideStatus=new D2(this,{});threadNavigationHistory=new y41;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;loadThreads=async()=>{return this.widget.neoContext.listThreads()};analyzeContextForThread=async(A,Q)=>{return oh4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>IG0({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);archiveThread=async(A)=>{let Q=await Bd4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await $d4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await Jd4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(eB.getInstance().interceptConsole(),this.notices=new W41(this.widget.configService,(B)=>this.setState(B)),Q6.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:B,error:$})=>{if(j.error("Neo failed to connect to thread",{threadID:B,error:$}),!B)this.toastController.show(`Connection failed: ${$.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe((B)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(C30(B.settings)))}),this.updateRelaunchIntegration=new S41({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 B={};if(A)B.initialUserInput=A;this.connectToInitialThreads(Q,B)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new _41({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.mcpTrustIntegration=new z41({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=H4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?Gi4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],$=[Hi4({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:(J,Y,Z)=>{J.pushWithDismiss((F)=>jA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:F,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},wr4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new s41({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new O61({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await lA(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{sQ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((F)=>new o41({onCancel:F,onSelect:(X)=>{this.handleIdeSelection(X),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new c41({commands:z9.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new wA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new p({text:new C(mX0({version:"0.0.1779040962-g094dfb",buildTimestamp:"2026-05-17T18:07:35.955Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:C1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{d4.maybeInvoke(Y,new Ux)}},...Q,...il4(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=this.notices.current,J=new Map([[C1.ctrl("c"),new JG0],[C1.ctrl("o"),new ZG0],[C1.alt("i"),new XG0],[C1.alt("p"),new WI],[C1.ctrl("."),new GG0],[C1.ctrl("t"),new KG0]]);if(QV0.env.NODE_ENV==="development"&&QV0.platform==="darwin")J.set(C1.meta("r"),new YG0);let Y=new L61({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:B,statusItems:this.pluginIntegration?.getStatusItems()??[],notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.neoWelcomeVisible?null:$,onDismissNotice:(V)=>this.notices.dismiss(V)}),Z=s1.of(A),F=Z.capabilities.animationSupport!=="disabled",D=[new u0({constraints:M1.tight(Z.size.width,Z.size.height),child:Y})];if(this.commandPalette.isEnabled())D.push(new c4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new g41({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)D.push(jA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)D.push(new c4({debugLabel:"NeoWelcomeDialogOverlay",child:new k61({onDismiss:this.dismissNeoWelcome,onQuit:()=>H4.instance.stop(),animationsEnabled:F,variant:this.widget.neoWelcomeVariant})}));let G=this.executorAlreadyConnectedDialog;if(G)D.push(new c4({debugLabel:"NeoExecutorAlreadyConnectedDialogOverlay",child:new n41({existingExecutorPid:G.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(D.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),D.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)D.push(new i41({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:QV0.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)D.push(new a41);return new A8({neoContext:this.widget.neoContext,child:new z9({commandRegistry:this.commandRegistry,child:new zx({completionBuilder:this.widget.completionBuilder,child:new u5({controller:this.toastController,child:new d4({actions:this.buildActions(),child:new Z5({debugLabel:"NeoAppShortcuts",shortcuts:J,child:new g4({debugLabel:"AppShellFocus",child:new Q01({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...$&&this.activeThreadContext&&!this.neoWelcomeVisible?[this.notices]:[]],child:new l41({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new BA({children:D})})})})})})})})})})}buildActions(){let A=new g1(()=>{if(HJ.hasAnyCopyableSelection())return HJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new g1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new g1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new g1(()=>{return this.startNewDraftThread(),"handled"}),J=new g1(()=>{return H4.instance.stop(),"handled"}),Y=new g1(()=>{return Bs({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),Z=new g1((U)=>{if(!U.text)return"ignored";return H4.instance.tuiInstance.clipboard.writeText(U.text).then((K)=>{if(K.ok)this.toastController.show(U.successMessage,"success",2000);else this.toastController.show(`${U.failureMessage}: ${K.userFacingErrorMessage}`,"error",4000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),F=new g1(()=>{return H4.instance.toggleFrameStatsOverlay(),"handled"}),X=new g1(()=>this.notices.dismissCurrent()?"handled":"ignored"),D=new g1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),G=Pi4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,neoContext:this.widget.neoContext,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),V=new g1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[JG0,A],[nr,$],[Ux,J],[YG0,Y],[p9,Z],[rr,B],[ZG0,Q],[XG0,D],[GG0,X],...G,[WI,F],[KG0,V]])}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.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),A.prompt!==void 0)this.editorController.text=A.prompt}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 Rf(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=A$(Q),J=PX0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return RX0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Cr4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(SZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Cr4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(SI);if(this.exitHintTimer.isActive())A.add(Fx);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),H4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:(B)=>{Q(B==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")H4.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,B=null,$)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),Y=A.find(K30);if(Y)this.widget.history.add(Y.text,QV0.cwd()),this.widget.history.reset();let Z=B?void 0:await this.widget.getDefaultNewThreadVisibility?.(),F=B??Z??null,X=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,F??void 0);this.sendUserMessage(X,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(X)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=A$(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};rQ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=qY0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let B of this.widget.clientPool.activeThreadIDs)A.add(B);return[...A]};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly,onExecutorAlreadyConnected:(J)=>this.promptExecutorAlreadyConnected(J)});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let B=this.widget.initialThreadIDs.filter(($)=>$!==A);await Promise.all(B.map(($)=>this.resumeBackgroundThread($)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){j.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.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.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.pluginIntegration?.hasBlockingDialog()??!1)}}function Cr4(A,Q,B){let $={...A};for(let J of Dg5(Q,B)){if(!SZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Dg5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}n4();function Lr4(A,Q,B,$){let J=cT(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new gY(G,V),K=new u9(42),E=new VI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,E0.default(),K);E.layout(M1.tight(G,V)),E.paint(U,0,0);let z=U.getBuffer().getCells(),W=0;for(let R=0;R<V;R++)if(z[R].some((v)=>v.char!==" ")){W=R;break}let H=V-1;for(let R=V-1;R>=0;R--)if(z[R].some((v)=>v.char!==" ")){H=R;break}function q(R,v){if(!R)return"";if(R.type==="rgb"){let{r:T,g:f,b:g}=R.value;if(B.getColorDepth()>=24)return`\x1B[${v?38:48};2;${T};${f};${g}m`;let u=wj(T,f,g);return`\x1B[${v?38:48};5;${u}m`}return""}let N=[];if(H>=W)for(let R=W;R<=H;R++){let v="";for(let T=0;T<G;T++){let f=z[R][T],g=f.char,u=q(f.style.fg,!0);v+=u+g+"\x1B[0m"}N.push(v)}let I=N.length,w=Math.max(I,D.length),O=Math.floor((w-I)/2),L=Math.floor((w-D.length)/2);for(let R=0;R<w;R++){let v=" ".repeat(G);if(R>=O&&R<O+I)v=N[R-O];let T=" ",f="";if(R>=L&&R<L+D.length)f=D[R-L];B.write(v+T+f+`
5878
+ `)),Y.push(new C("Details: ",new S({color:$.mutedForeground}))),Y.push(new C(A.costBreakdownURL,new S({color:B.app.link})));return new p({text:new C("",void 0,Y)})}function Xg5(A,Q,B){let $=Fg5(A,Q);if(!A.costBreakdownURL)return new wA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new g1(()=>{return d4.maybeInvoke(Q,new p9(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new g1(()=>{return lA(Q,J),"handled"});return new wA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new d4({actions:new Map([[S61,Y],[v61,Z]]),child:new Z5({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[C1.key("o"),new v61],[C1.key("y"),new S61]]),child:new g4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function wr4(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await r4.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(Zg5(J,Y.error),"error",5000),$();return}Q.push(Xg5(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}class y61 extends _0{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 Mr4}}class Mr4 extends P0{editorController=new P8;commandPalette=new oe0(this);commandRegistry=new h41;toastController=new A01;relaunchNotificationController=new T41;exitHintTimer=new eo(this,1000);ideStatus=new D2(this,{});threadNavigationHistory=new y41;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;loadThreads=async()=>{return this.widget.neoContext.listThreads()};analyzeContextForThread=async(A,Q)=>{return oh4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>IG0({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);archiveThread=async(A)=>{let Q=await Bd4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await $d4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await Jd4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(eB.getInstance().interceptConsole(),this.notices=new W41(this.widget.configService,(B)=>this.setState(B)),Q6.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:B,error:$})=>{if(j.error("Neo failed to connect to thread",{threadID:B,error:$}),!B)this.toastController.show(`Connection failed: ${$.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe((B)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(C30(B.settings)))}),this.updateRelaunchIntegration=new S41({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 B={};if(A)B.initialUserInput=A;this.connectToInitialThreads(Q,B)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new _41({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.mcpTrustIntegration=new z41({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=H4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?Gi4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],$=[Hi4({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:(J,Y,Z)=>{J.pushWithDismiss((F)=>jA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:F,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},wr4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new s41({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new O61({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await lA(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{sQ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((F)=>new o41({onCancel:F,onSelect:(X)=>{this.handleIdeSelection(X),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new c41({commands:z9.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new wA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new p({text:new C(mX0({version:"0.0.1779063447-g094dfb",buildTimestamp:"2026-05-18T00:22:34.106Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:C1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{d4.maybeInvoke(Y,new Ux)}},...Q,...il4(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=this.notices.current,J=new Map([[C1.ctrl("c"),new JG0],[C1.ctrl("o"),new ZG0],[C1.alt("i"),new XG0],[C1.alt("p"),new WI],[C1.ctrl("."),new GG0],[C1.ctrl("t"),new KG0]]);if(QV0.env.NODE_ENV==="development"&&QV0.platform==="darwin")J.set(C1.meta("r"),new YG0);let Y=new L61({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:B,statusItems:this.pluginIntegration?.getStatusItems()??[],notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.neoWelcomeVisible?null:$,onDismissNotice:(V)=>this.notices.dismiss(V)}),Z=s1.of(A),F=Z.capabilities.animationSupport!=="disabled",D=[new u0({constraints:M1.tight(Z.size.width,Z.size.height),child:Y})];if(this.commandPalette.isEnabled())D.push(new c4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new g41({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)D.push(jA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)D.push(new c4({debugLabel:"NeoWelcomeDialogOverlay",child:new k61({onDismiss:this.dismissNeoWelcome,onQuit:()=>H4.instance.stop(),animationsEnabled:F,variant:this.widget.neoWelcomeVariant})}));let G=this.executorAlreadyConnectedDialog;if(G)D.push(new c4({debugLabel:"NeoExecutorAlreadyConnectedDialogOverlay",child:new n41({existingExecutorPid:G.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(D.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),D.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)D.push(new i41({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:QV0.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)D.push(new a41);return new A8({neoContext:this.widget.neoContext,child:new z9({commandRegistry:this.commandRegistry,child:new zx({completionBuilder:this.widget.completionBuilder,child:new u5({controller:this.toastController,child:new d4({actions:this.buildActions(),child:new Z5({debugLabel:"NeoAppShortcuts",shortcuts:J,child:new g4({debugLabel:"AppShellFocus",child:new Q01({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...$&&this.activeThreadContext&&!this.neoWelcomeVisible?[this.notices]:[]],child:new l41({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new BA({children:D})})})})})})})})})})}buildActions(){let A=new g1(()=>{if(HJ.hasAnyCopyableSelection())return HJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new g1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new g1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new g1(()=>{return this.startNewDraftThread(),"handled"}),J=new g1(()=>{return H4.instance.stop(),"handled"}),Y=new g1(()=>{return Bs({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),Z=new g1((U)=>{if(!U.text)return"ignored";return H4.instance.tuiInstance.clipboard.writeText(U.text).then((K)=>{if(K.ok)this.toastController.show(U.successMessage,"success",2000);else this.toastController.show(`${U.failureMessage}: ${K.userFacingErrorMessage}`,"error",4000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),F=new g1(()=>{return H4.instance.toggleFrameStatsOverlay(),"handled"}),X=new g1(()=>this.notices.dismissCurrent()?"handled":"ignored"),D=new g1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),G=Pi4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,neoContext:this.widget.neoContext,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),V=new g1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[JG0,A],[nr,$],[Ux,J],[YG0,Y],[p9,Z],[rr,B],[ZG0,Q],[XG0,D],[GG0,X],...G,[WI,F],[KG0,V]])}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.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),A.prompt!==void 0)this.editorController.text=A.prompt}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 Rf(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=A$(Q),J=PX0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return RX0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Cr4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(SZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Cr4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(SI);if(this.exitHintTimer.isActive())A.add(Fx);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),H4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:(B)=>{Q(B==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")H4.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,B=null,$)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),Y=A.find(K30);if(Y)this.widget.history.add(Y.text,QV0.cwd()),this.widget.history.reset();let Z=B?void 0:await this.widget.getDefaultNewThreadVisibility?.(),F=B??Z??null,X=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,F??void 0);this.sendUserMessage(X,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(X)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=A$(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};rQ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=qY0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let B of this.widget.clientPool.activeThreadIDs)A.add(B);return[...A]};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly,onExecutorAlreadyConnected:(J)=>this.promptExecutorAlreadyConnected(J)});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let B=this.widget.initialThreadIDs.filter(($)=>$!==A);await Promise.all(B.map(($)=>this.resumeBackgroundThread($)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){j.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.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.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.pluginIntegration?.hasBlockingDialog()??!1)}}function Cr4(A,Q,B){let $={...A};for(let J of Dg5(Q,B)){if(!SZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Dg5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}n4();function Lr4(A,Q,B,$){let J=cT(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new gY(G,V),K=new u9(42),E=new VI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,E0.default(),K);E.layout(M1.tight(G,V)),E.paint(U,0,0);let z=U.getBuffer().getCells(),W=0;for(let R=0;R<V;R++)if(z[R].some((v)=>v.char!==" ")){W=R;break}let H=V-1;for(let R=V-1;R>=0;R--)if(z[R].some((v)=>v.char!==" ")){H=R;break}function q(R,v){if(!R)return"";if(R.type==="rgb"){let{r:T,g:f,b:g}=R.value;if(B.getColorDepth()>=24)return`\x1B[${v?38:48};2;${T};${f};${g}m`;let u=wj(T,f,g);return`\x1B[${v?38:48};5;${u}m`}return""}let N=[];if(H>=W)for(let R=W;R<=H;R++){let v="";for(let T=0;T<G;T++){let f=z[R][T],g=f.char,u=q(f.style.fg,!0);v+=u+g+"\x1B[0m"}N.push(v)}let I=N.length,w=Math.max(I,D.length),O=Math.floor((w-I)/2),L=Math.floor((w-D.length)/2);for(let R=0;R<w;R++){let v=" ".repeat(G);if(R>=O&&R<O+I)v=N[R-O];let T=" ",f="";if(R>=L&&R<L+D.length)f=D[R-L];B.write(v+T+f+`
5879
5879
  `)}if($)B.write(`
5880
5880
  \x1B[90m${$}\x1B[0m
5881
5881
  `)}c0();uX0();var Gg5=2000,Vg5="Agent is ready",Ug5="Waiting for approval";function Or4(A){let Q=!0,B=!0,$=A.configService.config.subscribe((z)=>{Q=z.settings["notifications.enabled"]??!0,B=z.settings["notifications.system.enabled"]!==!1}),J=0,Y=(z)=>{if(!Q)return;let W=Date.now();if(W-J<Gg5)return;if(J=W,_j())return;if(bF0())uF0();else sY0(z)},Z=(z)=>{if(!Q||!B)return;if(_j()&&!lo()&&!Hf())return;process.stdout.write(_D(`\x1B]777;notify;Amp;${z}\x1B\\`))},F=()=>{Y("idle"),Z(Vg5)},X=()=>{Y("requires-user-input"),Z(Ug5)},D=(z)=>z?.attempt===void 0||z.attempt===0,G=null,V=null,U=null,K=()=>{G?.unsubscribe(),V?.unsubscribe(),G=null,V=null,U=null};return{attach:(z,W)=>{if(K(),W)V=W.subscribe({next:(H)=>{if(H===null)return;if(!D(H))return;F()},error:(H)=>{j.debug("Neo notification active error stream errored",{error:H})}});G=z.subscribe({next:(H)=>{try{let q=U!==null&&hQ(U),N=U==="awaiting_approval",I=q||N;if(H==="awaiting_approval"&&!N)X();else if(H==="idle"&&I)F()}catch(q){j.debug("Neo notification handling failed",{error:q})}finally{U=H}},error:(H)=>{j.debug("Neo notification agent state stream errored",{error:H})}})},detach:K,unsubscribe(){K(),$.unsubscribe()}}}function Kg5({initialUserInput:A,showNeoWelcome:Q,hideNeoWelcome:B,neoWelcomeVariant:$,neoWelcomeDismissed:J}){if(B)return{show:!1,markDismissedOnDismiss:!1};if($==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let Y=!A&&!J;return{show:Y,markDismissedOnDismiss:Y}}async function Eg5(A){await rQ((Q)=>_f(Q,A,"interactive"))}async function jr4(A,Q={}){let{initialThreadIDs:B=[],initialUserInput:$,getDefaultNewThreadVisibility:J,openThreadPickerOnStart:Y=!1,observerOnly:Z=!1,initialAgentMode:F,initialReasoningEffort:X,onFirstFrame:D,showNeoWelcome:G=!1,hideNeoWelcome:V=!1,neoWelcomeVariant:U="intro"}=Q,K=U==="npm-migration";if(B.length>1)j.info("Resuming multiple initial threads",{threadIDs:B});let E=async(T)=>{let f=await A.getThreadFromServer(T);if(!f)return null;return CF0(f)},z=async(T)=>{let f=await A.getThreadFromServer(T);if(!f)throw Error(`Thread ${T} not found`);let g=await f9(T,A.configService,A.apiKey,{usesThreadActors:!0}),b=await qU({endpoint:A.rivetEndpoint,poolName:g.poolName}).threadActor.getOrCreate([T],{params:{wsToken:g.wsToken},createWithInput:{threadId:g.threadId,threadVersion:g.threadVersion,ownerUserId:g.ownerUserId,...g.agentMode?{agentMode:g.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:Vy4(f)}),skipReadyWait:!0});if(!b.ok&&b.status!==409)throw Error(`Thread import failed (${b.status}): ${await b.text()}`);try{await hy4(T,A.configService,A.apiKey,{executorType:"local-client"})}catch(d){j.warn("failed to mark thread as imported on server",{threadID:T,error:d instanceof Error?d.message:String(d)})}},W=new je0(A.rivetEndpoint,A.apiKey,A.configService,{clientID:pN.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(T)=>A.pluginService.event.toolCall(T),requestPluginToolResult:(T)=>A.pluginService.event.toolResult(T),pluginService:A.pluginService,invokeTool:async(T,f)=>{let g=typeof f.args==="object"&&f.args!==null?f.args:{},u=await AI({toolName:f.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:f.toolCallId,threadId:T});return A.toolService.invokeTool(f.toolName,{args:g},u)},persistLastThreadID:Eg5,readFileSystemDirectory:A.readFileSystemDirectory},E,z),H=await vz(),q=Kg5({initialUserInput:$,showNeoWelcome:G,hideNeoWelcome:V,neoWelcomeVariant:U,neoWelcomeDismissed:H.neoWelcomeDismissed}),N={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(T)=>{let f=await A.getThreadFromServer(T);return f?PV(f):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:Wa,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:K?!1:Z,sessionAgentMode:F??H.agentMode,explicitReasoningEffort:X,lastReasoningEffortByMode:H.lastReasoningEffortByMode,lastSpeedByMode:H.lastSpeedByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},I=(T,f)=>{return Qh4({ampURL:A.ampURL,configService:A.configService,threadID:T,signal:f})},w=new ie0,O=Or4({configService:A.configService}),L=await A.configService.getLatest();H4.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:L.settings["terminal.animation"]===!1}});let R=new Set,v=new k41;try{await io(new y61({clientPool:W,listSkillsForThread:I,completionBuilder:A.completionBuilder,history:new Qo,ideManager:w,configService:A.configService,updateService:A.updateService,initialThreadIDs:K?[]:B,notificationService:O,mcpTrustHandler:A.mcpTrustHandler,initialUserInput:K?void 0:$,getDefaultNewThreadVisibility:J,openThreadPickerOnStart:K?!1:Y,workspaceSettingsFilePath:A.workspaceSettingsFilePath,neoContext:N,showNeoWelcome:q.show,neoWelcomeVariant:U,onActiveThreadChange:A.setActiveThreadID,onRelaunchRequested:v.request,onNeoWelcomeDismissed:q.markDismissedOnDismiss?()=>{rQ(Jh4).catch((f)=>{j.warn("Failed to mark Neo welcome as dismissed",{error:f})})}:void 0,onThreadArchived:(f)=>{R.add(f)},onFirstFrame:D}));let T=W.lastActiveObservingClient;if(T&&v.shouldShowExitSummary){let{client:f,observer:g}=T,u=f.getThreadId();if(u){let k={id:u,title:g.title().getValue(),agentMode:g.agentMode,archived:R.has(u)},b=`${A.ampURL.replace(/\/$/,"")}/threads/${u}`;Lr4(k,b,process.stdout)}}}finally{process.stdout.write(XI("")),O.unsubscribe(),W.dispose(),await A.dispose?.()}process.exit(v.relaunchIfRequested(A.workspaceRoot)??0)}Z3();function kx(A){let Q=[],B={meta:{visibility:"private",sharedGroupIDs:[]}};if(A.workspace?.disablePrivateThreads)B.disabledReason="Disabled by workspace policy";if(Q.push(B),A.workspace?.groups&&A.workspace.groups.length>0){let Z={meta:{visibility:"private",shareWithAllCreatorGroups:!0}};if(A.creatorIsViewer===!1)Z.disabledReason="Can only be set by thread creator";Q.push(Z)}if(A.workspace)Q.push({meta:{visibility:"thread_workspace_shared"}});let $=A.workspace?.disablePublicSharing?"Disabled by workspace policy":void 0,J={meta:{visibility:"public_unlisted"}},Y={meta:{visibility:"public_discoverable"}};if($)J.disabledReason=$,Y.disabledReason=$;return Q.push(J,Y),Q}function Rr4(A){if(A.visibility!=="private")return!0;if("shareWithAllCreatorGroups"in A&&A.shareWithAllCreatorGroups)return!0;return"sharedGroupIDs"in A&&A.sharedGroupIDs.length>0}function FR(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"private":{let B="shareWithAllCreatorGroups"in A&&A.shareWithAllCreatorGroups,J=(B?Q.workspace?.groups.map((Y)=>Y.id)??[]:("sharedGroupIDs"in A)?A.sharedGroupIDs:[]).reduce((Y,Z)=>{let F=Q.workspace?.groups.find((X)=>X.id===Z)?.name;if(F)Y.push(`'${F}'`);return Y},[]);if(J.length>0)return{text:"Group",description:`Shared with ${D4(J.length,"group")} ${J.join(", ")} and workspace admins`};if(B)return{text:"Group",description:"Shared with creator groups and workspace admins"};return{text:"Private",description:Q.workspace?"Only visible to you and workspace admins":"Only you can see this thread"}}}}function BV0(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 Sx(A,Q=null){let B=A!==null&&typeof A==="object"&&"visibility"in A?A.visibility:void 0;if(!B||typeof B!=="string")return;let J=kx({workspace:Q?.team??void 0}).filter((Y)=>!Y.disabledReason).map((Y)=>BV0(Y.meta));if(J.includes(B))return zg5(B);if(B==="group"&&!J.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.
@@ -7637,7 +7637,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
7637
7637
  `),Y=[];for(let Z=0;Z<J.length;Z++){let D=J[Z].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let G of D)if(G.startsWith("\x00")&&G.endsWith("\x01"))Y.push(new C(G.slice(1,-1),new S({color:$.app.keybind,bold:!0})));else Y.push(new C(G,new S({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new C(`
7638
7638
  `))}return new u0({decoration:{color:B.colorScheme.background,border:d1.all(new c1($.app.keybind,1,"rounded"))},child:new f0({padding:K0.symmetric(0,1),child:new p({text:new C(void 0,void 0,Y)})})})}}class c51 extends V8{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=qU0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new p51({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 Y0A(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let F=B;return F>=0&&F<Y?F:null}case"bar":case"stacked-bar":{let F=Z?c8:0,X=$-F;if(X<=0)return null;let D=Q-F;if(D<0||D>=X)return null;let G=Math.max(1,Math.floor(X/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let F=Z?c8:0,X=$-F;if(X<=0)return null;let D=Math.max(0,Math.min(X-1,Q-F));if(Y===1)return 0;let G=X/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function fi5(A,Q,B,$,J,Y,Z,F){if(J<=0||Q<0||Q>=J)return null;let X=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?c8:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=Math.max(1,Math.floor(G/J)),K=D+Q*U+Math.floor(U/2),E=F>0?Z/F:0,z=Math.round((1-E)*(V-1));return{x:K,y:z}}case"line":case"sparkline":case"stacked-area":{let D=Y?c8:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=J>1?D+Math.round(Q/(J-1)*(G-1)):D+Math.floor(G/2),K=F>0?Z/F:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function xi5(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function bi5(A,Q,B,$,J){if(B.length<=1){let F=$(A.value),X=A.meta?` (${A.meta})`:"";return A.label.length+2+F.length+X.length}let Y=A.label.length,Z=0;for(let F of B){let X=F.points[Q];if(!X)continue;Z+=X.value;let D=2+F.name.length+2+$(X.value).length;Y=Math.max(Y,D)}if(J){let F=9+$(Z).length;Y=Math.max(Y,F)}return Y}function ui5(A,Q,B,$,J,Y,Z){let F;try{let E=L1.of(A),z=R0.of(A);F={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:z.app.keybind}}catch{F={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let X=new S({color:F.foreground,bold:!0}),D=new S({color:F.foreground}),G=new S({color:F.foreground,dim:!0}),V=[],U=new S({color:F.foreground,underline:!0}),K=(E,z)=>new C(z,U,void 0,Pz(E),()=>{lA(A,E)});if($.length<=1){if(V.push(new C(`${Q.label}: `,X)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new C(Y(Q.value),D));if(Q.meta)V.push(new C(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new C(`${Q.label}
7639
7639
  `,X));let z=0;for(let W=0;W<$.length;W++){let H=$[W],q=H.points[B];if(!q)continue;z+=q.value;let N=H.color??J[W%J.length]??F.foreground;if(V.push(new C("● ",new S({color:N}))),V.push(new C(`${H.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new C(Y(q.value),D));if(W<$.length-1||E)V.push(new C(`
7640
- `))}if(E)V.push(new C(" ",G)),V.push(new C("Total: ",G)),V.push(new C(Y(z),D))}return new u0({decoration:{color:F.background,border:d1.all(new c1(F.border,1,"rounded"))},child:new p({text:new C(void 0,void 0,V)})})}c0();function Z0A(A){return A.length===0?A:A[0].toLowerCase()+A.slice(1)}Z3();c3();k3();_B();Q7();s8();OQ();bq();n4();bS();GT();R1();c0();Q7();class l51{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1779040962-g094dfb"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await H30(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Bw extends _0{props;constructor(A){super();this.props=A}createState(){return new F0A}}class F0A extends P0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class X0A extends P0{controller=new P8;focusNode=new A6({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=R0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=d1.all(new c1(B.foreground,1,"solid")),X=new B$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new t0({children:[new u0({decoration:{color:B.background},child:new p({text:new C(">",new S({color:B.foreground}))})}),new T1({child:X})]}),G=new u0({padding:K0.symmetric(1,0),child:new p({text:this.widget.props.title?new C(this.widget.props.title,new S({color:$.command,bold:!0})):new C("",void 0,[new C("Command: ",new S({color:B.foreground})),new C(this.widget.props.commandName,new S({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new C("Enter",new S({color:$.keybind}))),V.push(new C(" to submit, ",new S({color:B.foreground,dim:!0})));V.push(new C("Esc",new S({color:$.keybind}))),V.push(new C(" to cancel",new S({color:B.foreground,dim:!0})));let U=new u0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,V)})});return new u0({decoration:{border:F,color:B.background},padding:K0.all(1),child:new y0({children:[G,new U0({height:1}),D,new X5,U]})})}}class us extends _0{props;constructor(A){super();this.props=A}createState(){return new X0A}}OQ();class D0A extends P0{controller=new P8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new A6({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>=C9)return!1;let Q=await fU(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=R0.of(A),{colors:B,app:$}=Q,Y=s1.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new cz({controller:this.controller,triggers:[new lF],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:H4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new g4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new u0({constraints:new M1({maxHeight:Z}),padding:K0.symmetric(1,0),child:X}),G=new u0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,[new C("Command: ",new S({color:B.foreground})),new C(this.widget.props.commandName,new S({color:$.command,bold:!0}))])})}),V=new u0({padding:K0.symmetric(1,0),child:new p({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new S({color:$.keybind})),new C(" again to clear input",new S({color:B.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new S({color:B.foreground,dim:!0})),new C("Enter",new S({color:$.keybind})),new C(" to submit, ",new S({color:B.foreground,dim:!0})),new C("Esc",new S({color:$.keybind})),new C(" to clear",new S({color:B.foreground,dim:!0}))])})}),U=[G,new U0({height:1}),new T1({child:D}),new U0({height:1}),V];return new u0({decoration:{border:d1.all(new c1(B.foreground,1,"solid")),color:B.background},padding:K0.all(1),child:new y0({children:U})})}}class i51 extends _0{props;constructor(A){super();this.props=A}createState(){return new D0A}}function G0A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class n51 extends q1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>G0A(J.pubDate).length));return new G5({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,F)=>{let X=R0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(z,W)=>new U0({width:W,child:t0.end([new p({text:new C(z,new S({color:K}))})])});return new u0({decoration:V?{color:V}:void 0,padding:K0.symmetric(2,0),child:new t0({children:[new T1({child:new p({text:new C(J.title,new S({color:U})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),E(G0A(J.pubDate),B)]})})}})}}class FB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!FB._instance)FB._instance=new FB;return FB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}c0();class V0A extends P0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=R0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),X=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new G5({title:"Add Label",items:X,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new u0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C("",void 0,[new C("Create new label: ",new S({color:E})),new C(W,new S({color:E,bold:!0}))])})})}return new u0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C(D.name,new S({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class a51 extends _0{props;constructor(A){super();this.props=A}createState(){return new V0A}}class nD extends _0{props;constructor(A){super();this.props=A}createState(){return new U0A}}class U0A extends P0{_spinner=new q6;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=R0.of(A),{colors:B,app:$}=Q,J=d1.all(new c1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new p({textAlign:"center",text:new C("",void 0,[new C(Y,new S({color:$.processing})),new C(" ",void 0),new C(this.widget.props.message,new S({color:B.foreground}))])}),X=[new T1({child:new y0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new U0({height:2,child:new u0({padding:K0.symmetric(2,0),child:new p({text:new C("",new S({dim:!0}),[new C("Press ",new S({color:B.foreground})),new C("Esc",new S({color:B.info})),new C(" to cancel",new S({color:B.foreground}))])})})}));let D=new u0({decoration:new b4(B.background,J),child:new U0({width:60,height:7,child:new y0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new c4({debugLabel:"LoadingDialog",child:new g4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class mU extends _0{props;constructor(A){super();this.props=A}createState(){return new K0A}}class K0A extends P0{scrollController=new yA;scrollAreaKey=new F2("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 b2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=R0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=qD0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=d1.all(new c1(Q.colors.border,1,"solid")),Z=new u0({padding:K0.symmetric(1,0),child:new p({text:new C($.title,new S({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new p({text:new C($.description,new S({color:Q.colors.foreground})),selectable:!0}),X=new T1({child:new X3({child:new u0({padding:K0.symmetric(1,0),child:new t0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new fA({controller:this.scrollController,autofocus:!0,child:F})}),new U2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new u0({padding:K0.symmetric(1,0),child:new p({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new S({color:Q.colors.foreground,dim:!0})),new C("R",new S({color:Q.app.keybind})),new C(" to retry, ",new S({color:Q.colors.foreground,dim:!0})),new C("Esc",new S({color:Q.app.keybind})),new C(" to cancel",new S({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new S({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new S({color:Q.app.keybind}),U=new S({color:Q.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",V),new C(" to close • Use ",U),new C("↑↓",V),new C(" or ",U),new C("j/k",V),new C(" to scroll",U)])}return new C("Press any key to close",new S({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new c4({debugLabel:"MessageDialog",child:new BA({fit:"expand",children:[new _1({onClick:()=>{},child:new U0}),new g4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new u0({decoration:{border:Y,color:Q.colors.background},padding:K0.all(1),child:new y0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),X,D]})})})]})})}}Z3();r1();class E0A extends _0{props;constructor(A){super();this.props=A}createState(){return new z0A}}class z0A extends P0{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=d0.file(this.widget.props.cwd),B=$1.relativePath(Q,D6(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return p5(A)}statusIcon(A){let Q=p8.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=R0.of(A),{app:B}=Q;if(this.plugins.length===0)return new p({text:new C("No plugins found.",new S({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new C(`${Y}/${J} ${D4(J,"plugin")} active`,new S({bold:!0}))),Z>0||F>0)$.push(new C(` (${Z} ${D4(Z,"command")}, ${F} ${D4(F,"tool")})`,new S({dim:!0})));$.push(new C(`
7640
+ `))}if(E)V.push(new C(" ",G)),V.push(new C("Total: ",G)),V.push(new C(Y(z),D))}return new u0({decoration:{color:F.background,border:d1.all(new c1(F.border,1,"rounded"))},child:new p({text:new C(void 0,void 0,V)})})}c0();function Z0A(A){return A.length===0?A:A[0].toLowerCase()+A.slice(1)}Z3();c3();k3();_B();Q7();s8();OQ();bq();n4();bS();GT();R1();c0();Q7();class l51{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1779063447-g094dfb"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await H30(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Bw extends _0{props;constructor(A){super();this.props=A}createState(){return new F0A}}class F0A extends P0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class X0A extends P0{controller=new P8;focusNode=new A6({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=R0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=d1.all(new c1(B.foreground,1,"solid")),X=new B$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new t0({children:[new u0({decoration:{color:B.background},child:new p({text:new C(">",new S({color:B.foreground}))})}),new T1({child:X})]}),G=new u0({padding:K0.symmetric(1,0),child:new p({text:this.widget.props.title?new C(this.widget.props.title,new S({color:$.command,bold:!0})):new C("",void 0,[new C("Command: ",new S({color:B.foreground})),new C(this.widget.props.commandName,new S({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new C("Enter",new S({color:$.keybind}))),V.push(new C(" to submit, ",new S({color:B.foreground,dim:!0})));V.push(new C("Esc",new S({color:$.keybind}))),V.push(new C(" to cancel",new S({color:B.foreground,dim:!0})));let U=new u0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,V)})});return new u0({decoration:{border:F,color:B.background},padding:K0.all(1),child:new y0({children:[G,new U0({height:1}),D,new X5,U]})})}}class us extends _0{props;constructor(A){super();this.props=A}createState(){return new X0A}}OQ();class D0A extends P0{controller=new P8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new A6({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>=C9)return!1;let Q=await fU(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=R0.of(A),{colors:B,app:$}=Q,Y=s1.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new cz({controller:this.controller,triggers:[new lF],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:H4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new g4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new u0({constraints:new M1({maxHeight:Z}),padding:K0.symmetric(1,0),child:X}),G=new u0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,[new C("Command: ",new S({color:B.foreground})),new C(this.widget.props.commandName,new S({color:$.command,bold:!0}))])})}),V=new u0({padding:K0.symmetric(1,0),child:new p({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new S({color:$.keybind})),new C(" again to clear input",new S({color:B.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new S({color:B.foreground,dim:!0})),new C("Enter",new S({color:$.keybind})),new C(" to submit, ",new S({color:B.foreground,dim:!0})),new C("Esc",new S({color:$.keybind})),new C(" to clear",new S({color:B.foreground,dim:!0}))])})}),U=[G,new U0({height:1}),new T1({child:D}),new U0({height:1}),V];return new u0({decoration:{border:d1.all(new c1(B.foreground,1,"solid")),color:B.background},padding:K0.all(1),child:new y0({children:U})})}}class i51 extends _0{props;constructor(A){super();this.props=A}createState(){return new D0A}}function G0A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class n51 extends q1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>G0A(J.pubDate).length));return new G5({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,F)=>{let X=R0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(z,W)=>new U0({width:W,child:t0.end([new p({text:new C(z,new S({color:K}))})])});return new u0({decoration:V?{color:V}:void 0,padding:K0.symmetric(2,0),child:new t0({children:[new T1({child:new p({text:new C(J.title,new S({color:U})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),E(G0A(J.pubDate),B)]})})}})}}class FB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!FB._instance)FB._instance=new FB;return FB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}c0();class V0A extends P0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=R0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),X=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new G5({title:"Add Label",items:X,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new u0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C("",void 0,[new C("Create new label: ",new S({color:E})),new C(W,new S({color:E,bold:!0}))])})})}return new u0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C(D.name,new S({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class a51 extends _0{props;constructor(A){super();this.props=A}createState(){return new V0A}}class nD extends _0{props;constructor(A){super();this.props=A}createState(){return new U0A}}class U0A extends P0{_spinner=new q6;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=R0.of(A),{colors:B,app:$}=Q,J=d1.all(new c1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new p({textAlign:"center",text:new C("",void 0,[new C(Y,new S({color:$.processing})),new C(" ",void 0),new C(this.widget.props.message,new S({color:B.foreground}))])}),X=[new T1({child:new y0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new U0({height:2,child:new u0({padding:K0.symmetric(2,0),child:new p({text:new C("",new S({dim:!0}),[new C("Press ",new S({color:B.foreground})),new C("Esc",new S({color:B.info})),new C(" to cancel",new S({color:B.foreground}))])})})}));let D=new u0({decoration:new b4(B.background,J),child:new U0({width:60,height:7,child:new y0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new c4({debugLabel:"LoadingDialog",child:new g4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class mU extends _0{props;constructor(A){super();this.props=A}createState(){return new K0A}}class K0A extends P0{scrollController=new yA;scrollAreaKey=new F2("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 b2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=R0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=qD0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=d1.all(new c1(Q.colors.border,1,"solid")),Z=new u0({padding:K0.symmetric(1,0),child:new p({text:new C($.title,new S({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new p({text:new C($.description,new S({color:Q.colors.foreground})),selectable:!0}),X=new T1({child:new X3({child:new u0({padding:K0.symmetric(1,0),child:new t0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new fA({controller:this.scrollController,autofocus:!0,child:F})}),new U2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new u0({padding:K0.symmetric(1,0),child:new p({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new S({color:Q.colors.foreground,dim:!0})),new C("R",new S({color:Q.app.keybind})),new C(" to retry, ",new S({color:Q.colors.foreground,dim:!0})),new C("Esc",new S({color:Q.app.keybind})),new C(" to cancel",new S({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new S({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new S({color:Q.app.keybind}),U=new S({color:Q.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",V),new C(" to close • Use ",U),new C("↑↓",V),new C(" or ",U),new C("j/k",V),new C(" to scroll",U)])}return new C("Press any key to close",new S({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new c4({debugLabel:"MessageDialog",child:new BA({fit:"expand",children:[new _1({onClick:()=>{},child:new U0}),new g4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new u0({decoration:{border:Y,color:Q.colors.background},padding:K0.all(1),child:new y0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),X,D]})})})]})})}}Z3();r1();class E0A extends _0{props;constructor(A){super();this.props=A}createState(){return new z0A}}class z0A extends P0{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=d0.file(this.widget.props.cwd),B=$1.relativePath(Q,D6(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return p5(A)}statusIcon(A){let Q=p8.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=R0.of(A),{app:B}=Q;if(this.plugins.length===0)return new p({text:new C("No plugins found.",new S({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new C(`${Y}/${J} ${D4(J,"plugin")} active`,new S({bold:!0}))),Z>0||F>0)$.push(new C(` (${Z} ${D4(Z,"command")}, ${F} ${D4(F,"tool")})`,new S({dim:!0})));$.push(new C(`
7641
7641
 
7642
7642
  `));for(let X of this.plugins){let{icon:D,color:G}=this.statusIcon(X.status),V=this.getRelativePath(X.uri);if($.push(new C(`${D} `,new S({color:G}))),$.push(new C(V,new S({bold:!0}))),$.push(new C(` ${X.status}`,new S({dim:!0}))),$.push(new C(`
7643
7643
  `)),X.status==="active"&&X.registeredEvents.length>0)$.push(new C(" Events: ",new S({dim:!0}))),$.push(new C(X.registeredEvents.join(", "),new S({color:B.link}))),$.push(new C(`
@@ -7815,7 +7815,7 @@ ${t.content||""}`:t.content||"",g0=[],p0=t.baseDir.startsWith("file://")?iU0(t.b
7815
7815
  `)}function r4A(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async(B,$)=>{let J=$.optsWithGlobals(),Y=await Q(J),Z=await Y.settings.get("proxy"),F=G04({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),X=await r4.userDisplayBalanceInfo({},{config:F});if(!X.ok){if(X.error.code==="auth-required")process.stderr.write(s0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(s0.red("Error: ")+X.error.message+`
7816
7816
  `),process.exit(1)}process.stdout.write(await Yr5(X.result.displayText)+`
7817
7817
  `),process.exit(0)})}var R03=Ct.join(b$,"logs","headless.log"),s21=Ct.join(Up,"device-id.json"),P03=`cli-tui-${L3A(16).toString("hex")}`;async function _03(){let A=await Promise.all(fM.map(async(Q)=>{try{return{query:Q,hasConfigs:(await Q.listConfigs()).length>0}}catch(B){return j.debug("Failed to detect query-based IDE integration",{ideName:Q.ideName,error:B}),{query:Q,hasConfigs:!1}}}));for(let Q of A)if(Q.hasConfigs)return Q.query;return}function j3A(){_03().then((A)=>{if(A){let Q=u30(A.ideName);if(Q)RM(Q)}})}try{if(process.platform==="win32")await Promise.resolve().then(() => v4(wb(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){XB.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
7818
- `)}function T03(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function p2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")FY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")FY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)FY("internal.model",v03(Q.model))}function H3A(A){let Q=A.indexOf(":");if(Q===-1)throw new l1(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new l1(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function k03(A){if(A===void 0)return;let Q=A.trim();if(de1(Q))return Q;throw new l1(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function S03(A,Q){if(I8(A,Q))return;let B=d$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new l1(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function v03(A){if(!A.includes("="))return H3A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new l1(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new l1(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new l1(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);H3A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new l1("No valid model overrides found in --model flag value.",1);return Q}function y03(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 f03(A){try{return await O3A(A,"utf-8")}catch{return A}}async function t21(A,Q,B){let $=y03(A,Q);if(!$)return;let J=sA(B)?B.features:[],Y=sA(B)?B.user.email:void 0;if(!Ot(J,LB.HARNESS_SYSTEM_PROMPT)&&!(Y&&f7(Y)))throw new l1("You are not allowed to do this.",1);FY("systemPrompt",await f03($))}function Ot(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function x03(A){return A!=="pending"}function VW(A){if(!sA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function b03(A){let Q=VW(A);if(Q)return Q.id;if(TX(A))throw Error(A.error.message);throw Error("unreachable")}function u03(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 h03(A){let $=u03(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 l1(`Couldn't connect to the Amp server at ${A}.`,1,$)}function Mt(A,Q){let B=_o0(Error(A.error.message));if(B.message===K7.networkOffline||B.message===K7.networkTimeout)return h03(Q);if(B.message!==K7.internalBug)return new l1(B.message,1,B.suggestion);return new l1(A.error.message.replace(/^Error: /,""),1)}async function g03(){if(process.versions.bun)return!1;try{return await IU()==="npm"}catch(A){return j.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var q3A=[{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??SX,description:`Custom settings file path (overrides the default location ${SX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Wa})`},{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:K9(),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:SM.SMART.key,description:`Set the agent mode (${p$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(p$().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}],N3A=(A)=>("deprecated"in A)&&A.deprecated===!0,m03=(A)=>("hidden"in A)&&A.hidden===!0,p03=(A)=>("default"in A),d03=(A)=>("default"in A)?A.default:void 0;function fK0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=k03(Q.effort);if(B!==void 0)S03(Q.mode,B);return B}function c03(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new l1(K7.unknownCommand(B),1,Z)}}async function uK0(A){return{...A,getThreadEnvironment:Hz,getEnvironmentData:(Q,B)=>fE(Q,B),skillService:A.skillService,fileChangeTrackerStorage:new NL,generateThreadTitle:UF4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>bZ(A.configService),pluginService:A.pluginService}}function R3A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:Hz,getEnvironmentData:(Q,B)=>fE(Q,B)}}var xK0=d0.file(j03.homedir()),e21=process.env.XDG_CONFIG_HOME?d0.file(process.env.XDG_CONFIG_HOME):$1.joinPath(xK0,".config");function l03(A){return XR4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(bF0())uF0();else sY0(Q);let B=_j(),$=lo();if((!B||$||Hf())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(_D("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(_D("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(_j()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function l8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;ye1("0.0.1779040962-g094dfb");let Y=T30({storage:A.settings,secretStorage:A.secrets,workspaceRoot:b0.of(d0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:xK0,userConfigDir:e21}),Z=A.secrets.get("apiKey",A.ampURL),F=bZ(Y),X=null,D=()=>{return},G=new Promise((B0)=>{D=B0}),V=Z.then(async(B0)=>{if(!B0&&!$)await G;return X??=F.subscribe(()=>{}),S1(F.pipe(d5(x03)))});V.catch(()=>{return}),Xs4(Y);let U=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(U.settings)});let K=!1;{let B0=await Z;if(K=Boolean(B0),j.info("API key lookup before login",{found:Boolean(B0),ampURL:A.ampURL,deferAuth:$}),!B0)if($)j.info("No API key found, continuing startup with deferred auth");else{r6.write(`No API key found. Starting login flow...
7818
+ `)}function T03(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function p2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")FY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")FY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)FY("internal.model",v03(Q.model))}function H3A(A){let Q=A.indexOf(":");if(Q===-1)throw new l1(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new l1(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function k03(A){if(A===void 0)return;let Q=A.trim();if(de1(Q))return Q;throw new l1(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function S03(A,Q){if(I8(A,Q))return;let B=d$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new l1(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function v03(A){if(!A.includes("="))return H3A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new l1(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new l1(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new l1(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);H3A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new l1("No valid model overrides found in --model flag value.",1);return Q}function y03(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 f03(A){try{return await O3A(A,"utf-8")}catch{return A}}async function t21(A,Q,B){let $=y03(A,Q);if(!$)return;let J=sA(B)?B.features:[],Y=sA(B)?B.user.email:void 0;if(!Ot(J,LB.HARNESS_SYSTEM_PROMPT)&&!(Y&&f7(Y)))throw new l1("You are not allowed to do this.",1);FY("systemPrompt",await f03($))}function Ot(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function x03(A){return A!=="pending"}function VW(A){if(!sA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function b03(A){let Q=VW(A);if(Q)return Q.id;if(TX(A))throw Error(A.error.message);throw Error("unreachable")}function u03(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 h03(A){let $=u03(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 l1(`Couldn't connect to the Amp server at ${A}.`,1,$)}function Mt(A,Q){let B=_o0(Error(A.error.message));if(B.message===K7.networkOffline||B.message===K7.networkTimeout)return h03(Q);if(B.message!==K7.internalBug)return new l1(B.message,1,B.suggestion);return new l1(A.error.message.replace(/^Error: /,""),1)}async function g03(){if(process.versions.bun)return!1;try{return await IU()==="npm"}catch(A){return j.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var q3A=[{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??SX,description:`Custom settings file path (overrides the default location ${SX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Wa})`},{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:K9(),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:SM.SMART.key,description:`Set the agent mode (${p$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(p$().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}],N3A=(A)=>("deprecated"in A)&&A.deprecated===!0,m03=(A)=>("hidden"in A)&&A.hidden===!0,p03=(A)=>("default"in A),d03=(A)=>("default"in A)?A.default:void 0;function fK0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=k03(Q.effort);if(B!==void 0)S03(Q.mode,B);return B}function c03(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new l1(K7.unknownCommand(B),1,Z)}}async function uK0(A){return{...A,getThreadEnvironment:Hz,getEnvironmentData:(Q,B)=>fE(Q,B),skillService:A.skillService,fileChangeTrackerStorage:new NL,generateThreadTitle:UF4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>bZ(A.configService),pluginService:A.pluginService}}function R3A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:Hz,getEnvironmentData:(Q,B)=>fE(Q,B)}}var xK0=d0.file(j03.homedir()),e21=process.env.XDG_CONFIG_HOME?d0.file(process.env.XDG_CONFIG_HOME):$1.joinPath(xK0,".config");function l03(A){return XR4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(bF0())uF0();else sY0(Q);let B=_j(),$=lo();if((!B||$||Hf())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(_D("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(_D("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(_j()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function l8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;ye1("0.0.1779063447-g094dfb");let Y=T30({storage:A.settings,secretStorage:A.secrets,workspaceRoot:b0.of(d0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:xK0,userConfigDir:e21}),Z=A.secrets.get("apiKey",A.ampURL),F=bZ(Y),X=null,D=()=>{return},G=new Promise((B0)=>{D=B0}),V=Z.then(async(B0)=>{if(!B0&&!$)await G;return X??=F.subscribe(()=>{}),S1(F.pipe(d5(x03)))});V.catch(()=>{return}),Xs4(Y);let U=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(U.settings)});let K=!1;{let B0=await Z;if(K=Boolean(B0),j.info("API key lookup before login",{found:Boolean(B0),ampURL:A.ampURL,deferAuth:$}),!B0)if($)j.info("No API key found, continuing startup with deferred auth");else{r6.write(`No API key found. Starting login flow...
7819
7819
  `);let M0=await i03(A),n=await A.secrets.get("apiKey",A.ampURL);if(j.info("Login flow completed",{success:M0,storedKeyPresent:Boolean(n),ampURL:A.ampURL}),!M0)await Wz(),process.exit(1);K=!0,D()}}{let B0=await Y.getLatest(),M0=B0.settings.url,n=B0.secrets.isSet?.[M0];j.info("Config secrets state after login",{configURL:M0,apiKeySet:n?.apiKey??!1})}let E=$?"pending":await V;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:sA(E),isError:TX(E),errorMessage:TX(E)?E.error.message:void 0});let z=V.then((B0)=>b03(B0));z.catch(()=>{return});let W=!Q.takeMeBack&&sA(E)&&Ot(E.features,LB.THREAD_ACTORS_TUI),H=!1;if(process.env.AMP_DISABLE_PLUGINS==="1")j.warn("Ignoring AMP_DISABLE_PLUGINS outside development");let q=H?"off":W?"all":process.env.PLUGINS??"permissions",{toolService:N,dispose:I}=$R4({configService:Y}),w=new Map,O=()=>w.clear(),L=new vx0(Y,A.settings.getWorkspaceRootPath()),R=pJ4({configService:Y}),v=j74({configService:Y,trustStore:L,skillMCPServers:R.skillMCPServers,uploadImageAttachments:W,createOAuthProvider:async(B0,M0,n)=>{let a=`${B0}:${M0}`,t=w.get(a);if(t)return j.debug("Reusing existing OAuth provider for server",{serverName:B0,serverUrl:M0}),t;j.debug("Creating OAuth provider for server",{serverName:B0,serverUrl:M0});let e=(async()=>{let Z0=new mM(A.secrets),Y0=await Z0.getClientInfo(B0,M0),I0=n?.scopes??Y0?.scopes,C0=Lf4();j.info("OAuth headless mode check",{useHeadless:C0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:r6.isTTY});let T0;if(C0)T0=A.executeMode?Mf4():Cf4(B0);let G0=new dS0({storage:Z0,serverName:B0,serverUrl:M0,clientId:n?.clientId??Y0?.clientId,clientSecret:n?.clientSecret??Y0?.clientSecret,authUrl:n?.authUrl??Y0?.authUrl,tokenUrl:n?.tokenUrl??Y0?.tokenUrl,scopes:I0,headlessAuthHandler:T0});return j.debug("OAuth provider created",{serverName:B0,serverUrl:M0,hasManualClientId:!!(n?.clientId??Y0?.clientId),willUseDCR:!(n?.clientId??Y0?.clientId),scopes:I0,headlessMode:C0,executeMode:A.executeMode}),G0})();return w.set(a,e),e}}),T=fn0({configService:Y,spawn:MY0}),f=Q.headless?yr4():void 0,g=f??new $V0({configService:Y}),u=g instanceof $V0?g:void 0;if(u)u.pluginExecutorKind="local";let k=new n1(null),b=null,d=W&&!H?[...br4(U.settings)?[{name:"permissions",entryPoint:u61}]:[],{name:"thread-visibility",entryPoint:gr4(Y,()=>V.then(VW),()=>b,(B0)=>{b=B0}),alwaysLoad:!0}]:[],c=ax0({configService:Y,platform:g,loadGlobalPlugins:Qt0(Y),pluginFilter:q,activeThread$:k,internalPlugins:d}),h=NQ4(c),i=[v,T,h],r;if(J)r=new Map;else if(A.executeMode){let B0=await VO4({toolService:N,providers:i,initialTimeout:15000});r=B0.registrations;for(let[M0,n]of B0.initErrors)j.warn(`${M0} provider initialization slow or failed:`,n)}else r=xn0({toolService:N,providers:i});if(Q.jetbrains)RM("JetBrains");else if(Q.ide&&of4())RM("VS Code");else if(Q.ide&&rf4())RM("Neovim");else if(Q.ide&&(!W||A.executeMode||Q.takeMeBack))j3A();if(A.executeMode)fe1(!0);let Q0,w0=l3.status.pipe(I1((B0)=>Boolean(B0.connected&&B0.authenticated&&B0.ideName&&h04(B0.ideName))),T4()).subscribe((B0)=>{if(B0){if(!Q0)Q0=N.registerTool(GO4)}else Q0?.dispose(),Q0=void 0}),X0;if(!A.executeMode){let B0=await A.settings.get("fuzzy.alwaysIncludePaths")??[];X0=new yF0(process.cwd(),{alwaysIncludePaths:B0},!0)}else X0=new class extends yF0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let H0=new rh0(Ol(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let A0=new c61,j0={configService:Y,toolService:N,mcpService:v,skillService:R,toolboxService:T,trustStore:L,threadService:H0,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:X0,terminal:A0,pluginService:c,pluginPlatform:u,headlessPluginPlatform:f,activeThread$:k,serverStatus:E,serverStatusPromise:V,viewerUserIDPromise:z,hasAPIKeyAtStartup:K,consumeDraftNewThreadVisibility:()=>{let B0=b;return b=null,B0}};return{...j0,async asyncDispose(){if(j0.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await j0.mcpService.waitForAuthentication();for(let B0 of r.values())B0.dispose();await j0.mcpService.dispose(),O(),await j0.threadService.asyncDispose(),j0.configService.unsubscribe(),X?.unsubscribe(),I(),j0.fuzzyServer.dispose(),j0.settingsStorage[Symbol.dispose](),w0.unsubscribe(),Q0?.dispose(),await j0.pluginService.dispose()}}}async function i03(A){if(!A.executeMode){if(!await LX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return r6.write(`Login cancelled. Run the command again to retry.
7820
7820
  `),!1}return await P3A(A)}async function P3A(A){let Q=L3A(32).toString("hex"),B=await jf(A.ampURL,Q),$=new AbortController;try{await RX(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await jf(A.ampURL,Q,!1);r6.write(`If your browser does not open automatically, visit:
7821
7821
 
@@ -7823,7 +7823,7 @@ ${s0.blue.bold(J)}
7823
7823
 
7824
7824
  `);try{return await Du4(A.ampURL,Q,A.secrets,$),r6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return j.error("Login failed",{error:Y}),XB.write(`
7825
7825
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
7826
- `),!1}}async function n03(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new l1("No Amp API key found. Run `amp login` first.",1);let J=M03("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(F)=>Y(F??1))})}function a03(A){let Q=new uN().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)oO(),process.exit(0);let H=W.originalError??W;MT4(H)}),sh4(Q,{version:"0.0.1779040962-g094dfb",buildTimestamp:"2026-05-17T18:07:35.955Z",buildType:"release"}),Q.addHelpText("after",if4()),Q.configureHelp({formatHelp:nf4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await a5(q);await J13(N)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await a5(q);await $13(N,await g61(q,N.settings))}),IT4(Q,a5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...W)=>{let H=W.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=W.filter((w)=>w!==H).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=H.optsWithGlobals(),I=await a5(N);await n03(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(W,H,q)=>{let N=q.optsWithGlobals(),I=await a5(N);await Ef4(W??"get",I.ampURL,I.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(W,H)=>{let q=H.optsWithGlobals(),N=await a5(q);await zf4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(W)=>{await Xb4({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(`
7826
+ `),!1}}async function n03(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new l1("No Amp API key found. Run `amp login` first.",1);let J=M03("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(F)=>Y(F??1))})}function a03(A){let Q=new uN().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)oO(),process.exit(0);let H=W.originalError??W;MT4(H)}),sh4(Q,{version:"0.0.1779063447-g094dfb",buildTimestamp:"2026-05-18T00:22:34.106Z",buildType:"release"}),Q.addHelpText("after",if4()),Q.configureHelp({formatHelp:nf4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await a5(q);await J13(N)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await a5(q);await $13(N,await g61(q,N.settings))}),IT4(Q,a5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...W)=>{let H=W.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=W.filter((w)=>w!==H).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=H.optsWithGlobals(),I=await a5(N);await n03(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(W,H,q)=>{let N=q.optsWithGlobals(),I=await a5(N);await Ef4(W??"get",I.ampURL,I.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(W,H)=>{let q=H.optsWithGlobals(),N=await a5(q);await zf4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(W)=>{await Xb4({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(`
7827
7827
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(W,H,q)=>{if(W&&H.apply)throw new l1("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let N=H.apply??W;if(!N||N.trim().length===0)r6.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.
7828
7828
 
7829
7829
  `),q.outputHelp(),process.exit(0);let I=L2(N)??oB(N),w=q.optsWithGlobals(),O=await a5(w);p2(q,w);let L=await l8(O,w),R=!1;try{if(H.checkout&&H.skipCheckout)throw new l1("Choose either --checkout or --skip-checkout, not both.",1);if(TX(L.serverStatus))throw Mt(L.serverStatus,O.ampURL);let v=sA(L.serverStatus)?L.serverStatus.features:void 0;if(!Ot(v,LB.V2))throw new l1("live-sync is not enabled for your user",1);await tb4({ampURL:O.ampURL,threadId:I,configService:L.configService,threadService:L.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:LX0}),R=!0}finally{if(await L.asyncDispose(),R)process.exit(0)}});let J=async(W,H,q)=>{T30({storage:H.settings,secretStorage:H.secrets,workspaceRoot:b0.of(d0.file(process.cwd())),defaultAmpURL:H.ampURL,homeDir:xK0,userConfigDir:e21});let N={...H,executeMode:!1};await bK0(N,{...W,openThreadSwitcher:!0},q,A)},Y=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await a5(q);await M3A(q,N,H)});Y.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await a5(q);await H13(q,N,H)}),Y.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,H,q)=>{let N=q.optsWithGlobals(),I=await a5(N),w=Array.isArray(W)?W:[];if(H.pick)XB.write(`${s0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -7856,8 +7856,8 @@ ${O}
7856
7856
  `))}),H.args.length>0)c03(N,H);await bK0(N,q,H,A)}),Lx4(Q),Q}async function Lt(A,Q){await rQ((B)=>_f(B,A,Q))}async function I3A(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([r4.getThreadLinkInfo({thread:A},{config:Q}),B]);if(j.getChild("fetchAndStartThread").info(`Ownership check in ${Date.now()-$}ms`),J.ok){let Z=J.result.creatorUserID;if(Z&&Z!==Y&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new l1(`Cannot resume thread created by another user.
7857
7857
 
7858
7858
  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 _3A(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await XV0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await XV0()).trimEnd(),stdinInput:null}}function T3A(A,Q,B){if(A.streamJson&&!Q)throw new l1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new l1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new l1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new l1("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 l1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new l1("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 l1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&B===""&&!A.streamJsonInput&&!A.headless)throw new l1("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"
7859
- Or pipe via stdin: echo "your message" | amp --execute`)}function o03(){RA4([R30.parse({tool:"*",action:"allow"})]),YA4({bypass:!0})}function r03(A){if(A.threadId&&!I9(A.threadId))delete A.threadId}async function bK0(A,Q,B,$){if(Q.headless)return s03(A,Q,B);let J=await l8(A,Q),Y=await J.serverStatusPromise,Z=sA(Y)&&Ot(Y.features,LB.THREAD_ACTORS_TUI),F=Z&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await J.asyncDispose(),new l1("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!Z)throw await J.asyncDispose(),new l1("--show-welcome is only available with the new Amp CLI feature flag",1);if(F){let X=!A.executeMode&&await g03();return o03(),r03(Q),t03(A,Q,B,J,{showNpmMigrationWelcome:X})}else{if(Q.threadId&&I9(Q.threadId)){let X=await r4.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(X?.ok&&X.result.usesThreadActors)throw await J.asyncDispose(),new l1(`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 e03(A,Q,B,$,{dependencies:J})}}async function s03(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=No0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};p2(B,Q);let J=process.hrtime.bigint(),Y=await l8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(TX(Z))throw Mt(Z,A.ampURL);let F=sA(Z)?Z:null,X=F?.user.email;await t21(B,Q,Z);let D=VW(Z),G=Sx(Q,D);if(G instanceof Error)j5(G.message);if(F&&!kM(Q.mode,X))throw new l1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!X||!f7(X)))throw new l1("Headless executor mode is only available for Amp employees",1);SZ0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new l1("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!I9(K))throw new l1(`Invalid thread ID: ${K}`,1);let E=K?void 0:await z13({dependencies:Y,apiKey:U,visibility:G??void 0}),z=K??E?.threadId;if(!z)throw new l1("Failed to resolve headless thread ID",1);let W=await Pf4(z);if(W.status==="already-running")await Y.asyncDispose(),await Wz(),process.exit(0);try{await Nf4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:z,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await Wz(),process.exit(0)}async function t03(A,Q,B,$,J){let{userInput:Y,stdinInput:Z}=await _3A(Q),F=!!Q.streamJson||!!Q.streamJsonThinking;T3A({...Q,streamJson:F},A.executeMode,Y),p2(B,Q),XT4(),SZ0();let X=Q.threadId,D=Q.resumeThreadIDs??(X?[X]:[]),G=Q.observe?L2(Q.observe)??oB(Q.observe):void 0,V=await $.serverStatusPromise;if(TX(V))throw Mt(V,A.ampURL);let U=VW(V),K=Sx(Q,U);if(K instanceof Error)j5(K.message);let E=null,z=async()=>{let q=$.consumeDraftNewThreadVisibility();if(q!==null)return q;return E??=(async()=>{let N=await Ha(A.settings,process.cwd(),U,K);if(N instanceof Error)j5(N.message);return N})(),E},W=await $.secretStorage.get("apiKey",A.ampURL);if(!W)throw new l1("API key required. Please run `amp login` first.",1);let H=sA(V)&&f7(V.user.email);if(A.executeMode){if(D.length>1)throw new l1("Execute mode can only resume one thread.",1);Xe0($.mcpService,A.settings);try{let q=fK0(B,Q),N=await vz(),I=X?q:jX0({agentMode:Q.mode,explicitEffort:q,sessionState:N}),w=X?void 0:RX0(await Rf($.configService),{agentMode:Q.mode,explicitEffort:q,sessionState:N}),O=X?void 0:await z(),L=await iy4({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:Y,stdinInput:Z,stats:!!Q.stats,streamJson:F,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:I,labels:Q.label,initialThreadID:X,initialThreadMeta:O,initialSettings:w});if(await Lt(L,"execute"),Q.archive)await $.threadService.archive(L,!0)}finally{await $.asyncDispose()}await Wz(),process.exit(0)}else{let q=fK0(B,Q),N=J.showNpmMigrationWelcome?"npm-migration":"intro",I=aF0("0.0.1779040962-g094dfb",$.settingsStorage,{startDelayMs:3000}),w=new OX0($.mcpService,A.settings.getWorkspaceRootPath()),O=Ol($.configService),L=new hs($.fuzzyServer),R=process.cwd();await jr4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??vF(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:v})=>Ff({workspaceRoot:R},v),completionBuilder:L,updateService:I,workspaceRoot:R,listThreads:()=>O.listThreads(),getThreadFromServer:(v)=>O.getThread(v),toolboxes:$.toolboxService.toolboxes,isInternalUser:H,settingsFilePath:$.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:$.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:w,setActiveThreadID:(v)=>$.activeThread$.next(v),dispose:()=>{return w.dispose(),I.dispose(),$.asyncDispose()}},{initialThreadIDs:G?[G]:D,initialUserInput:Y||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?j3A:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!G,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:N,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:q}),process.exit(0)}}async function e03(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(A0,j0)=>{let B0=Number(process.hrtime.bigint()-j0)/1e6,M0=No0();j.info("Startup phase",{phase:A0,phaseMs:Math.round(B0),sinceMainMs:M0===null?void 0:Math.round(M0)})},{userInput:F,stdinInput:X}=await _3A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;T3A({...Q,streamJson:D},A.executeMode,F),p2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await l8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&TX(E))throw Mt(E,A.ampURL);let z=sA(E)?E:null,W=z?.user.email,H=!!(W&&f7(W));if(H)SZ0();if(!K)await t21(B,Q,E);let q=VW(E),N=q?.features??[],I=q?.team??null,w=Sx(Q,q);if(w instanceof Error)j5(w.message);if(z&&!kM(Q.mode,W))throw new l1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&I9(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let L=await uK0(V);Z("runMainThread:createWorkerDeps",G);let R=A.executeMode?void 0:async(A0)=>Lt(A0,"interactive"),v={threadService:V.threadService,workerDeps:L,createThread:async(A0)=>{let j0=K?await V.serverStatusPromise:E,B0=await Ha(A.settings,process.cwd(),VW(j0),w);if(B0 instanceof Error)j5(B0.message);return L81(L,{threadMeta:B0,agentMode:A0??Q.mode,onFirstAssistantMessage:R})},validateThreadOwnership:async(A0,j0)=>{if(j0?.nonBlockingOwnershipCheck){I3A(A0,V.configService,V.viewerUserIDPromise).catch((B0)=>{if(B0 instanceof l1){if(j0.onOwnershipError){j0.onOwnershipError(B0,A0);return}qz(B0,A0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})});return}try{await I3A(A0,V.configService,V.viewerUserIDPromise)}catch(B0){if(B0 instanceof l1)throw B0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:R,handleError:qz},T=async()=>{try{return i4A(v,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(A0){if(A0 instanceof l1)throw A0;throw await qz(A0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let A0=await V.configService.getLatest(),j0=Rm(A0),B0=await r4.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(j0)});if(B0.ok)return j.info("User free tier status:",B0),B0.result;return}catch(A0){j.error("Failed to fetch free tier status:",A0);return}})(),u=!A.executeMode?new o61:null,k,b=null;if(u)k=u,b=(async()=>{let A0=K?await V.serverStatusPromise:V.serverStatus;if(TX(A0))throw Mt(A0,A.ampURL);await t21(B,Q,A0);let j0=process.hrtime.bigint(),B0=await T();if(Z("runMainThread:createThreadPool",j0),u.attach(B0),F){let M0=await S1(B0.threadHandles$);if(!M0)throw new l1("No active thread is available yet.",1);await M0.sendMessage({content:[{type:"text",text:F}]})}})(),b.catch(async(A0)=>{let j0=A0 instanceof Error?A0:Error(String(A0));u.setInitError(j0),await qz(A0,Q.threadId)});else G=process.hrtime.bigint(),k=await T(),Z("runMainThread:createThreadPool",G);let d=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let c=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),l03({configService:V.configService,threadService:V.threadService,config:c,useNotificationsForService:d,threadViewStates$:()=>k.threadHandles$.pipe(y4((A0)=>{if(!A0)return b0.of({});return M6(A0.thread$,A0.threadViewState$).pipe(I1(([j0,B0])=>({[j0.id]:B0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){Xe0(V.mcpService,A.settings);let A0=fK0(B,Q),j0=await vz(),B0=O?A0:jX0({agentMode:Q.mode,explicitEffort:A0,sessionState:j0}),M0={userInput:F,stdinInput:X,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,reasoningEffort:B0,labels:Q.label},n=await cT4({threadPool:k,...M0});if(await Lt(n,"execute"),Q.archive)await V.threadService.archive(n,!0);await V.asyncDispose(),process.exit(0)}let h=!1,i=!1;if(Q.jetbrains||Q.ide){await g30();let A0=await yX({jetbrainsOnly:Q.jetbrains});if(A0.length===0){if(Q.jetbrains)h=!await V.configService.get("jetbrains.skipInstall")}else if(A0.length===1){let j0=A0[0];if(j0)l3.selectConfig(j0)}else i=!0}G=process.hrtime.bigint();let r=aF0("0.0.1779040962-g094dfb",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let Q0=new OX0(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),F&&A.executeMode){let A0=await S1(k.threadHandles$);if(!A0)throw new l1("No active thread is available yet.",1);await A0.sendMessage({content:[{type:"text",text:F}]})}G=process.hrtime.bigint();let w0=await vz();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let X0=fK0(B,Q),H0={...w0,launchCount:w0.launchCount+1,lastReasoningEffortByMode:X0?{...w0.lastReasoningEffortByMode,[Q.mode]:X0}:w0.lastReasoningEffortByMode};rQ((A0)=>({...A0,launchCount:A0.launchCount+1}));try{if(G=process.hrtime.bigint(),await Yt4({history:new Qo,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:r4,threadPool:k,createSystemPromptDeps:async()=>R3A(V),ideClient:l3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:Q0,updateService:r,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:h,showIdePickerHint:i,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:P03,logFile:{path:$},sessionState:H0,freeTierStatusPromise:f,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-17T18:07:35.955Z"},(A0)=>new B51({...A0,threadPool:A0.threadPool},(j0)=>new C81({...j0,threadState:j0.threadState}))),Z("runMainThread:mountApp-returned",G),b)await b}finally{await k.dispose().catch((A0)=>{j.error("Failed to dispose thread pool during shutdown",A0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function a5(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)XB.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7860
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await k74({get:async(F)=>{if(F!==yd)return;try{let X=await O3A(s21,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==yd)return;await L03(Ct.dirname(s21),{recursive:!0}),await O03(s21,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:F90()});xe1($);let J=await Js4({...A,workspaceTrust:{current:!0,changes:Pm},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await Nu4(A.mcpConfig);J=Iu4(J,F)}let Y=Ct.dirname(J.getSettingsFilePath());FR4(Up,Y),J=Gs1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=h7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!bH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:tr4(await g61(A,J))}}function A13(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function Q13(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=Ct.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?R03:Wa));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function B13(){BT4();let A=A13(process.argv),Q=Q13(process.argv,A),B=DT4(Q);LZ0("silent");let $=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)s0.level=0;if(T03(j),j.info("Starting Amp CLI.",{version:"0.0.1779040962-g094dfb",buildTimestamp:"2026-05-17T18:07:35.955Z"}),process.platform==="win32"&&Hj())qx4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new l1(K7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await a03(B).parseAsync(process.argv)}YR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await B13().catch(qz)});async function $13(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),r6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7859
+ Or pipe via stdin: echo "your message" | amp --execute`)}function o03(){RA4([R30.parse({tool:"*",action:"allow"})]),YA4({bypass:!0})}function r03(A){if(A.threadId&&!I9(A.threadId))delete A.threadId}async function bK0(A,Q,B,$){if(Q.headless)return s03(A,Q,B);let J=await l8(A,Q),Y=await J.serverStatusPromise,Z=sA(Y)&&Ot(Y.features,LB.THREAD_ACTORS_TUI),F=Z&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await J.asyncDispose(),new l1("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!Z)throw await J.asyncDispose(),new l1("--show-welcome is only available with the new Amp CLI feature flag",1);if(F){let X=!A.executeMode&&await g03();return o03(),r03(Q),t03(A,Q,B,J,{showNpmMigrationWelcome:X})}else{if(Q.threadId&&I9(Q.threadId)){let X=await r4.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(X?.ok&&X.result.usesThreadActors)throw await J.asyncDispose(),new l1(`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 e03(A,Q,B,$,{dependencies:J})}}async function s03(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=No0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};p2(B,Q);let J=process.hrtime.bigint(),Y=await l8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(TX(Z))throw Mt(Z,A.ampURL);let F=sA(Z)?Z:null,X=F?.user.email;await t21(B,Q,Z);let D=VW(Z),G=Sx(Q,D);if(G instanceof Error)j5(G.message);if(F&&!kM(Q.mode,X))throw new l1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!X||!f7(X)))throw new l1("Headless executor mode is only available for Amp employees",1);SZ0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new l1("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!I9(K))throw new l1(`Invalid thread ID: ${K}`,1);let E=K?void 0:await z13({dependencies:Y,apiKey:U,visibility:G??void 0}),z=K??E?.threadId;if(!z)throw new l1("Failed to resolve headless thread ID",1);let W=await Pf4(z);if(W.status==="already-running")await Y.asyncDispose(),await Wz(),process.exit(0);try{await Nf4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:z,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await Wz(),process.exit(0)}async function t03(A,Q,B,$,J){let{userInput:Y,stdinInput:Z}=await _3A(Q),F=!!Q.streamJson||!!Q.streamJsonThinking;T3A({...Q,streamJson:F},A.executeMode,Y),p2(B,Q),XT4(),SZ0();let X=Q.threadId,D=Q.resumeThreadIDs??(X?[X]:[]),G=Q.observe?L2(Q.observe)??oB(Q.observe):void 0,V=await $.serverStatusPromise;if(TX(V))throw Mt(V,A.ampURL);let U=VW(V),K=Sx(Q,U);if(K instanceof Error)j5(K.message);let E=null,z=async()=>{let q=$.consumeDraftNewThreadVisibility();if(q!==null)return q;return E??=(async()=>{let N=await Ha(A.settings,process.cwd(),U,K);if(N instanceof Error)j5(N.message);return N})(),E},W=await $.secretStorage.get("apiKey",A.ampURL);if(!W)throw new l1("API key required. Please run `amp login` first.",1);let H=sA(V)&&f7(V.user.email);if(A.executeMode){if(D.length>1)throw new l1("Execute mode can only resume one thread.",1);Xe0($.mcpService,A.settings);try{let q=fK0(B,Q),N=await vz(),I=X?q:jX0({agentMode:Q.mode,explicitEffort:q,sessionState:N}),w=X?void 0:RX0(await Rf($.configService),{agentMode:Q.mode,explicitEffort:q,sessionState:N}),O=X?void 0:await z(),L=await iy4({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:Y,stdinInput:Z,stats:!!Q.stats,streamJson:F,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:I,labels:Q.label,initialThreadID:X,initialThreadMeta:O,initialSettings:w});if(await Lt(L,"execute"),Q.archive)await $.threadService.archive(L,!0)}finally{await $.asyncDispose()}await Wz(),process.exit(0)}else{let q=fK0(B,Q),N=J.showNpmMigrationWelcome?"npm-migration":"intro",I=aF0("0.0.1779063447-g094dfb",$.settingsStorage,{startDelayMs:3000}),w=new OX0($.mcpService,A.settings.getWorkspaceRootPath()),O=Ol($.configService),L=new hs($.fuzzyServer),R=process.cwd();await jr4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??vF(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:v})=>Ff({workspaceRoot:R},v),completionBuilder:L,updateService:I,workspaceRoot:R,listThreads:()=>O.listThreads(),getThreadFromServer:(v)=>O.getThread(v),toolboxes:$.toolboxService.toolboxes,isInternalUser:H,settingsFilePath:$.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:$.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:w,setActiveThreadID:(v)=>$.activeThread$.next(v),dispose:()=>{return w.dispose(),I.dispose(),$.asyncDispose()}},{initialThreadIDs:G?[G]:D,initialUserInput:Y||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?j3A:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!G,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:N,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:q}),process.exit(0)}}async function e03(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(A0,j0)=>{let B0=Number(process.hrtime.bigint()-j0)/1e6,M0=No0();j.info("Startup phase",{phase:A0,phaseMs:Math.round(B0),sinceMainMs:M0===null?void 0:Math.round(M0)})},{userInput:F,stdinInput:X}=await _3A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;T3A({...Q,streamJson:D},A.executeMode,F),p2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await l8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&TX(E))throw Mt(E,A.ampURL);let z=sA(E)?E:null,W=z?.user.email,H=!!(W&&f7(W));if(H)SZ0();if(!K)await t21(B,Q,E);let q=VW(E),N=q?.features??[],I=q?.team??null,w=Sx(Q,q);if(w instanceof Error)j5(w.message);if(z&&!kM(Q.mode,W))throw new l1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&I9(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let L=await uK0(V);Z("runMainThread:createWorkerDeps",G);let R=A.executeMode?void 0:async(A0)=>Lt(A0,"interactive"),v={threadService:V.threadService,workerDeps:L,createThread:async(A0)=>{let j0=K?await V.serverStatusPromise:E,B0=await Ha(A.settings,process.cwd(),VW(j0),w);if(B0 instanceof Error)j5(B0.message);return L81(L,{threadMeta:B0,agentMode:A0??Q.mode,onFirstAssistantMessage:R})},validateThreadOwnership:async(A0,j0)=>{if(j0?.nonBlockingOwnershipCheck){I3A(A0,V.configService,V.viewerUserIDPromise).catch((B0)=>{if(B0 instanceof l1){if(j0.onOwnershipError){j0.onOwnershipError(B0,A0);return}qz(B0,A0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})});return}try{await I3A(A0,V.configService,V.viewerUserIDPromise)}catch(B0){if(B0 instanceof l1)throw B0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:R,handleError:qz},T=async()=>{try{return i4A(v,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(A0){if(A0 instanceof l1)throw A0;throw await qz(A0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let A0=await V.configService.getLatest(),j0=Rm(A0),B0=await r4.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(j0)});if(B0.ok)return j.info("User free tier status:",B0),B0.result;return}catch(A0){j.error("Failed to fetch free tier status:",A0);return}})(),u=!A.executeMode?new o61:null,k,b=null;if(u)k=u,b=(async()=>{let A0=K?await V.serverStatusPromise:V.serverStatus;if(TX(A0))throw Mt(A0,A.ampURL);await t21(B,Q,A0);let j0=process.hrtime.bigint(),B0=await T();if(Z("runMainThread:createThreadPool",j0),u.attach(B0),F){let M0=await S1(B0.threadHandles$);if(!M0)throw new l1("No active thread is available yet.",1);await M0.sendMessage({content:[{type:"text",text:F}]})}})(),b.catch(async(A0)=>{let j0=A0 instanceof Error?A0:Error(String(A0));u.setInitError(j0),await qz(A0,Q.threadId)});else G=process.hrtime.bigint(),k=await T(),Z("runMainThread:createThreadPool",G);let d=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let c=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),l03({configService:V.configService,threadService:V.threadService,config:c,useNotificationsForService:d,threadViewStates$:()=>k.threadHandles$.pipe(y4((A0)=>{if(!A0)return b0.of({});return M6(A0.thread$,A0.threadViewState$).pipe(I1(([j0,B0])=>({[j0.id]:B0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){Xe0(V.mcpService,A.settings);let A0=fK0(B,Q),j0=await vz(),B0=O?A0:jX0({agentMode:Q.mode,explicitEffort:A0,sessionState:j0}),M0={userInput:F,stdinInput:X,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,reasoningEffort:B0,labels:Q.label},n=await cT4({threadPool:k,...M0});if(await Lt(n,"execute"),Q.archive)await V.threadService.archive(n,!0);await V.asyncDispose(),process.exit(0)}let h=!1,i=!1;if(Q.jetbrains||Q.ide){await g30();let A0=await yX({jetbrainsOnly:Q.jetbrains});if(A0.length===0){if(Q.jetbrains)h=!await V.configService.get("jetbrains.skipInstall")}else if(A0.length===1){let j0=A0[0];if(j0)l3.selectConfig(j0)}else i=!0}G=process.hrtime.bigint();let r=aF0("0.0.1779063447-g094dfb",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let Q0=new OX0(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),F&&A.executeMode){let A0=await S1(k.threadHandles$);if(!A0)throw new l1("No active thread is available yet.",1);await A0.sendMessage({content:[{type:"text",text:F}]})}G=process.hrtime.bigint();let w0=await vz();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let X0=fK0(B,Q),H0={...w0,launchCount:w0.launchCount+1,lastReasoningEffortByMode:X0?{...w0.lastReasoningEffortByMode,[Q.mode]:X0}:w0.lastReasoningEffortByMode};rQ((A0)=>({...A0,launchCount:A0.launchCount+1}));try{if(G=process.hrtime.bigint(),await Yt4({history:new Qo,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:r4,threadPool:k,createSystemPromptDeps:async()=>R3A(V),ideClient:l3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:Q0,updateService:r,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:h,showIdePickerHint:i,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:P03,logFile:{path:$},sessionState:H0,freeTierStatusPromise:f,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-18T00:22:34.106Z"},(A0)=>new B51({...A0,threadPool:A0.threadPool},(j0)=>new C81({...j0,threadState:j0.threadState}))),Z("runMainThread:mountApp-returned",G),b)await b}finally{await k.dispose().catch((A0)=>{j.error("Failed to dispose thread pool during shutdown",A0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function a5(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)XB.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7860
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await k74({get:async(F)=>{if(F!==yd)return;try{let X=await O3A(s21,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==yd)return;await L03(Ct.dirname(s21),{recursive:!0}),await O03(s21,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:F90()});xe1($);let J=await Js4({...A,workspaceTrust:{current:!0,changes:Pm},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await Nu4(A.mcpConfig);J=Iu4(J,F)}let Y=Ct.dirname(J.getSettingsFilePath());FR4(Up,Y),J=Gs1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=h7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!bH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:tr4(await g61(A,J))}}function A13(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function Q13(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=Ct.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?R03:Wa));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function B13(){BT4();let A=A13(process.argv),Q=Q13(process.argv,A),B=DT4(Q);LZ0("silent");let $=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)s0.level=0;if(T03(j),j.info("Starting Amp CLI.",{version:"0.0.1779063447-g094dfb",buildTimestamp:"2026-05-18T00:22:34.106Z"}),process.platform==="win32"&&Hj())qx4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new l1(K7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await a03(B).parseAsync(process.argv)}YR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await B13().catch(qz)});async function $13(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),r6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7861
7861
  `);else if(!bH(A.ampURL))r6.write(`Logging in to ${new URL(A.ampURL).hostname}
7862
7862
  `);let $=process.env.AMP_API_KEY;if($)r6.write(`API key found in environment variable, storing...
7863
7863
  `),await Q.set("apiKey",$,A.ampURL),r6.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1779040962-g094dfb",
3
+ "version": "0.0.1779063447-g094dfb",
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.1779040962-g094dfb"
11
+ "@ampcode/cli": "0.0.1779063447-g094dfb"
12
12
  },
13
13
  "files": [
14
14
  "dist/main.js",